JavaScript Loaders

Sunday, April 1, 2018

Surviving Shelter: Analysis of Time Spent and Outcome in Dallas Animal Shelters

In previous post we discovered Dallas Animal Services data sources (available on Dallas Open Data) and analyzed how animals get admitted to and discharged from the city shelters. We loaded actual shelter records and looked at the types of admittance, different outcomes and their relationships. In this post we continue this analysis by focusing on the time animals spend and factors that favor or hinder survival of dogs in the shelters. For consistency and representation only types of admission ConfiscatedOwner Surrender, and Stray and outcomes AdoptionDied, EuthanizedReturned to Owner, and Transfer were included. Dead on Arrival was excluded from survival analysis because it preempties outcome before stay in shelter begins.

Time Spent in Shelters

Compare the distributions of time spent in shelter for cats and dogs to note both similarities and differences:



Distributions are bimodal with relatively fat tails but they differ in how major modes compare to minor ones. As Wikipedia rightly notices "a bimodal distribution most commonly arises as a mixture of two different unimodal distributions" and dissecting data by admission and outcome types opens the door to further discovery:



If the former histogram used facets for separate plots for cats and dogs, the latter plot switched to dodged bars to pack more information into less space. Some interesting observations:

  • Confiscated admissions have distinctively different profile and peaks presumingly attributed to legal obligations to owners;
  • Confiscated has distinct bimodal distributions when outcomes are either Returned to Owner or Transfer;
  • Adoption times are similar for both cats and dogs;
  • Most distributions have clear unimodal profiles specific to the types of admission and outcome that vary between dogs and cats in density;
  • Adoption and to less degree Owner Surrender distributions are almost indistinguishable between cats and dogs.
Rendering the same data using density curve estimates lets us validate the differences and similarities observed:


The densities demonstrate striking similarity in Adoption and most differences in Euthanized outcome times. 

Sankeys With Average Times

We already used Sankey diagrams to project flow from admission to discharge by total number of occurrences in each transition. This time we decided on novel approach to Sankeys when thickness reflects average time spent in shelter. First diagram is for cats:




And then for dogs:





The thinner the line the shorter average stay between admission and outcome it connects. And the larger vertical panel (admission or outcome) the longer it indicates an animal spends in shelter after admission or before discharge (on average and unweighted).  

Expected Chance of Not Surviving in Shelter

For the purpose of this analysis any outcome other than Died or Euthanized means animal survived to leave shelter alive (most with outcomes Adoption, Foster, Returned to Owner or Transfer). Remember that we also excluded dogs with intake type Dead on Arrival (see introduction).

We begin with rather simple calculations - an estimates of chance of dying in shelter given animal satisfies certain condition. Plot below contains conditional probabilities for dogs (unless cats specified) not surviving in shelter given certain factor at the time of admission (intake categories):

Two health conditions stand out with the highest rates: untreatable and unmanageable, while another health condition contagious is present in 3 out of top 4 factors.

There is one more factor breed which has over 200 values just for dogs. Below we display chances of dying for the dog breeds with at least 100 recorded admissions:

Note that probability scale is different between last two plots. Surprisingly, breed Chow Chow took the top spot with Pit Bull Terrier breeds Staffordshire, Pit Bull, Am Pit Bull Terrier, and American Staffordshire close next. 

Survival Analysis

While applying classic survival analysis to animal shelter data presents certain challenges we apply the approach by ignoring few details. But any suggestions or comments how to improve are welcome. The survival function S(t) gives the probability that the subject (pet admitted to shelter) survives longer than time t

In this case pets survived when discharged with any outcome other than Died or Euthanized. The time t is always in days since the day of admission and all animal records included in this analysis are for animals that were discharged (effectively eliminating both left and right censoring cases). Survival analysis accounts for censored data - those subjects with last known status alive and no later information available. In our case all animal records contain outcome and thus all discharged alive are censored at discharge date.

Kaplan-Meier Estimator

Kaplan-Meier (KM) estimate is a non-parametric maximum likelihood estimate of the survival function, S(t). It measures the fraction of animals living for a certain number of days t after admission and produces a declining step function with drops (KM curve) that approximates the real survival function from data. Given single categorical factor we can observe and compare KM curves (univariate analysis) among multiple factor values. KM curves estimate and visualize survival chances in time just as survival functions: given time t what is probability that subject survives at least to that time or longer.

Cats vs. Dogs KM Curves

First we compare survival curves between cats and dogs:



The survival curve plot (top) is augmented with the bar chart of totals by categories and survival outcome (bottom) to give better understanding of underlying data. Survival chances for cats are never better than those and overall cats fare much worse than dogs - see bar chart above. Zooming in into the most critical first days after admission reveals more differences:



Day of admission is the worst for both but cats fare twice as bad with 25% lost right away. Days 4 and 5 are critical for dogs as their survival plummets on these days. After that survival rates stabilize and trend in similar pattern.


KM Curves by Dog Intake Types

To make further analysis more plausible we include only dog records from this point on. We also exclude pets admitted as Dead on Arrival or Euthanasia Requested since their outcomes are obvious and immediate.



Confiscated dogs survival chances are the best in first 10 days or so but then they quickly deteriorate crossing and diving below 2 other types after 2 weeks. The worst chances as expected belong to dogs surrendered by owner. And after 2 weeks all 3 curves cross to become less distinguishable.
 

KM Curves by Dog Origins

Dallas Animal Services also maintain origin field assigning it at admission with 3 most prevalent values being Field, Over the Counter, and Sweep. These are how survival curves differ depending on dog origin:


Again, significant shifts in survival chances happen after 5 days and then after 2-3 weeks when the fortunes of different origins turn around: after 5 days Over the Counter from the worst becomes 2d worst (or best) and then after 3 weeks the best. Both Field and Sweep drop after 5 days. In absolute numbers (shown in the bar plots) Field dogs survive  the worst.

Health Conditions at Admission

Unhealthy animals have little chance to survive shelters as evident from the following:


No surprise that unhealthy animals survival is significntly below healthy ones. Also, dominant majority of dogs accepted are in unhealthy condition, which is both not surprising and unfortunate. 

There is more information about unhealthy dogs available from shelter records: treatable vs. untreatable and contagious vs. non-contagious. Unfortunately, these values reside inside single field so the survival curves include combinations of the health factors:



It clearly shows how each health factor reduces survival chances: from Healthy to Treatable Rehabilitable to Treatable Manageable to Unhealthy Untreatable to finally Unhealthy Untreatable Contagious

If we extract and analyze each health factor (ignoring the rest) then these relationships become more apparent:





Survival of Dogs with Chips

As of June 17, 2017, all dogs and cats four months and older in the city of Dallas must be microchipped. This relatively new regulation will likely change both the share of chipped dogs in Dallas and survival curves as observed below from 2015 through October 2017:



Still having a dog microchipped will almost certainly keep survival chances higher.
 

Dog Breeds

Dallas shelters admitted dogs of over 200 different breeds from 2015 through 2017. Among them 56 breeds appeared 100 times or more (over 95% of all admissions): 


Top 4 breeds - Pit Bull, Labrador Retriever, Chihuahua, and German Shepherd - account for almost 60% of all admissions with next breed - Cairn Terrier - dropping to just under 3%. The survival curves for these 5 breeds contain almost 2/3 of all dogs admitted to Dallas shelters:

Pit Bull's suffer the worst survival rate of the 5 most admitted breeds. It drops to below 50% survival rate after just over a week at shelter. Labrador and German Shepherd get 50% some time  into 3 week period. Smaller breeds last much better as evident from Chihuahua and Cairn Terrier curves.

It turns out there are more breeds closely related to Pit Bull: American Staff, Am Pit Bull Ter, and Staffordshire:



Similar pattern for three of four breeds from the group sharply differ from the 4th - American Staffordshire for reason(s) beyond this analysis.
 

Next

In the next and final post on Dallas animal shelters we will apply Cox proportional hazard semi-parameterical statistical analysis to assess simultaneously the effect of several factors on survival time and outcome.

Resources

The R notebook (source code) with data pipeline and visualizations can be found here with knitted version on RPubs.

Monday, September 4, 2017

How Pets Get Admitted and Later Leave Dallas Animal Shelters

Thanks to Dallas OpenData anyone has access to the city animal shelter records.  If you lost or found a pet it could be that he or she spent some time in a shelter - I personally took lost dogs there. It's unfortunate but every year tens of thousands of animals find their way to shelters with significant fraction never finding way out. 


What and How Many Animals are Admitted?


City of Dallas animal shelter dataset contains 5 different animal types with solid lead belonging to dogs and cats (hardly any surprise to anyone):



For consistency and plausibility of analysis we will focus on cats and dogs only


How Animals get Admitted


Each shelter record has animal's intake type (reason animal was admitted) and outcome (cause for animal disharge). Top 2 reasons why cats and dogs turn up at shelters are Stray (lost or abandoned) and Owner Surrender (willingly brought in by owner) while Confiscated (abused, no owner, etc.) is #3 for dogs but not cats



How Animals Leave Shelter


Animals leave shelters (either alive or dead) for 4 main reasons (outcomes):  Adoption (good),  Euthanized (bad), Returned to Owner (good), and Transfer (neutral):



Unfortunately, for both cats and dogs the top reason to leave shelter is being euthanized. But that's where similarity between them ends: 


  • cats don't get returned to owner anywhere near as often as dogs;
  • dogs' adoption and euthanized rates are almost the same while cats get adopted far less. 

From Admissions to Outcomes with Sankey


So what is the relationship between intake types and outcomes? Which and to what extent intake types drive outcomes? The good news there is some causality effect because each stay begins with intake type and ends with outcome. 

We begin analyzing this relationship with higher level (in that case) but visually appealing visualization called sankey diagram (or just sankey). It is a specific type of flow diagram, in which the width of the arrows is shown proportionally to the flow quantity. In our case each dog shelter stay contributes to the pipe size flowing from left (an intake type) to right (an outcome). With this we basically visualize conditional probabilities of dog leaving shelter with certain outcome given its admission intake type (first image illustrates transitions for cats and second does the same for dogs):







While Owner Surrender intake type flows similarly for both, Stray animals don't: cat outcomes are dominated by Euthanized but dogs are dominated by Adoption with Transfer and Returned to Owner outcomes together matching Euthanized.


Correlations Between Admissions and Outcomes


Next, we go beyond overall totals used in the sankey and compute correlations. To correlate intake types and outcomes we construct time series by computing monthly totals for each intake type and outcome obtaining monthly trends. Then we correlate between monthly trends (separate for cats and dogs) animals brought in and removed from Dallas animal shelters for each pair of top intake types (Confiscated, Owner Surrender, and Stray) and outcomes (Adoption, Euthanized, Returned to Owner, and Transfer) - 12 coefficients in total:




In this case strong correlation implies (at least to some extent) causation effect due to presence of temporal relationship, consistency, and plausibility criteria (see here and here). Few observations to note:
  • The highest correlation for cats (0.91) and second highest for dogs (0.77) are observed between intake Surrendered by Owner and outcomeEuthanized which is almost as obvious as unfortunate.
  • Correlation between Stray and Returned to Owner for dogs is the highest at 0.86. This is great news because it means the more dogs get lost the more of them are found. The higher this correlation the healthier the city for 2 reasons: a) lost animals return home and b) larger share of stray dogs are lost ones and not abandoned (given that the city keeps collecting them).
  • Unfortunately trend in Stray cats correlates highly with Euthanized. So while Stray dog trend drives adoptions and returns, Stray cat trend affects euthanizations the most (we've seen that in sankey as well).
  • No trends are affected by variations in Confiscated dogs, but this is likely due to smaller share of such admissions.
  • Variation in Stray dogs admitted affect every outcome (but Euthanized). Indeed Stray intake type is the largest and is almost twice as big as the 2d largest dog type Owner Surrender
  • Low correlation for dogs between Stray and Euthanized needs additional analysis because it's counter-intuitive.

Monthly Trends


But can we do better than correlations of these trends which technically are sophisticated but still aggregates? Next visual places time series instead of correlation coefficients inside the same matrix grid allowing to see and compare actual monthly trends:



Note that each plot is a 3 x 4 matrix - the same dimension as correlations matrices before. But instead of correlation coefficient each cell contains a pair of monthly trends (in fact, each correlation was computed for these exact pairs of trends, hence, a reference to its aggregation origin). Each row corresponds to an intake type (the same blue line in each) and each column to an outcome (the same red line in each). Being able to see trends over time let's record a few observations (following the matrix order top down):
  • Confiscated intake trends flat for both cats and dogs with only significant spike for dogs in January 2016. This spike is so unusual, relatively big, and contained within single month or two that it begs additional investigation into probable external event or procedural change that may have caused it.
  • Number of Confiscated animals is relatively low to noticeably affect outcomes. Still, if we can reduce effect of other intake types some relationships are possible.
  • Owner Surrender trend correlation with Euthanized outcome is so obvious that this type of visualization is sufficient to find it. Yes, it is unfortunate but people bring their old or unhealthy pets for a reason. 
  • The same applies to Stray and Owner Surrender for cats only. 
  • Owner Surrender has significant seasonal component spiking in summer possibly due to hot weather or holiday season or both. For cats only seasonal component is also strong in Stray trend.
  • Euthanized trends together with Owner Surrender which causes it to a large degree.
  • Stray dogs trend slowly upwards in Dallas and it's alarming.
  • Adoption also trends upwards but not steep enough to compensate for inflow of dogs into shelters.  Targeted campaign to encourage more adoptions of pets in the city is due.
  • Transfer outcome trending upward also compensates  for the growth in stray dogs. It's not clear if it's positive or negative though as there is no means to track what happens to dogs after transfer (or is it?).
  • Stray trend for dogs dipped in January 2016 exactly when confiscated trend spiked - it could be a coincidence or related - for sure something to consider when investigating further.
  • For dogs Euthanized trend correlates strongly with Stray intake until the summer of 2016 when they start to diverge in opposite directions - again some policy or procedural change apparently caused it. Indeed, if we observe other outcomes we notice that Returned to Owner trend began its uptick at around the same time (indeed, after I observed this I found out about this and this - significant changes in Dallas Animal Services leadership and policies around summer and fall of 2016).
I will be back with more analysis (survival analysis). R code for data processing, analysis, and visualizations from this post can be found here.

Wednesday, July 5, 2017

The Role of Small Data and Vacation Recap Example

Wikipedia defines small data 'small' enough for human comprehension but then it goes further by qualifying data in a volume and format that makes it accessible, informative and actionable. I am not certain the latter is always true: smaller footprint doesn't automatically qualify data as informative and actionable without more work. In my book small data usually scales to kilobytes and has just a handful of dimensions. But its main feature remains human comprehension which really means there is simple story behind it. 

In the grand scheme of big data things small data story is the last mile of data science analysis. It still requires interpretation (or representation) in the form of visualization or application.


Case in point could be Google spreadsheet I kept while on vacation in Italy with daily recordings of miles and steps walked. Later I added main attractions for each day. The result was my personal small data covering about 2 weeks of touring Italy with bases in Rome and later in Sicily (this sentence was the story):

Google sheet of activities while on vacation in Italy

As-is this spreadsheet is destined to Google archives contributing to ever growing collection of docs I created and happily forgot about. So I created this visualization that represents both most of data and the story:


Small data visualization

Before explaining how this visualization was created with R I ought to acknowledge that Google spreadsheets offer adding a chart or graph to a document. But its functionality appears rather limited without resorting to JavaScript API.

Using R googlesheets package to source Google docs makes them integral part of data sources available from within R code:
For details on how code above authenticates with Google servers and processes documents see very detailed vignettes

Now we can get back to small data and its simple story. Which means single visualization may include most if not all of it. In case of small data the goal is designing such chart without sacrificing clarity.

Core attributes days (Date) and miles walked (Distance; I chose miles over Steps for simplicity) suggest a line chart with timeline along x-axis and distance for y-axis. But there are 2 more factors to incorporate: Place indicating where the base city was each day and Label for major attractions.


Base city receives color identification with deep red for Rome and olive green for Syracuse. Major attractions text was attached to each point with smart justifications to fit inside the chart:


Had I kept more detailed log I would have ended up with more dimensions to use. For example, miles driven by car or train, time spent at leisure versus touring, number of cities and places visited, historical marker attributes and so on. But that moves us further away from small data domain as footprint and dimensions grow and story becomes less comprehensible. One of indicators of this is that it becomes harder to collect data manually. Instead, there are apps that would do it for me, for example, Life Cycle or Apple Health.

Ultimately any big data problem is reduced to one or more small data ones by aggregating, regressions, clustering or some other data science method. The path to big data insights is a journey from big to small data in search of simple story. So learning how to deal with small data is where it all both ends and begins.

Friday, June 23, 2017

Logarithmic Scale Explained with U.S. Trade Balance

Skewed data prevail in real life. Unless you observe trivial or near constant processes data is skewed one way or another due to outliers, long tails, errors or something else. Such effects create problems in visualizations when a few data elements are much larger than the rest.
Consider U.S. 2016 merchandise trade partner balances data set where each point is a country with 2 features: U.S. imports and exports against it:

Suppose we decided to visualize top 30 U.S trading partners using bubble chart, which simply is a 2D scatter plot with the third dimension expressed through point size. Then U.S. trade partners become disks with imports and exports for xy coordinates and trade balance (abs(export - import)) for size:
 
China, Canada, and Mexico run far larger balances compared to the other 27 countries which causes most data points to collapse into crowded lower left corner. One way to "solve" this problem is to eliminate 3 mentioned outliers from the picture:

  
 While this plot does look better it no longer serves its original purpose of displaying all top trading partners. And undesirable effect of outliers though reduced still presents itself with new ones: Japan, Germany, and U.K. So let us bring all countries back into the mix by trying logarithmic scale.
Quick refresher from algebra. Log function (in this example log base 10 but the same applies to natural log or log base 2) is commonly used to transform positive real numbers. All because of its property of mapping multiplicative relationships into additive ones. Indeed, given numbers A, B, and C such that

`A*B=C and A,B,C > 0`

applying log  results in additive relationship:

`log(A) + log(B) = log(C)`

For example, let A=100, B=1000, and C=100000 then
 
`100 * 1000 = 100000`

so that after transformation it becomes

`log(100) + log(1000) = log(100000)`  or   `2 + 3 = 5`

Observe this on 1D plane:



Logarithmic scale is simply a log transformation applied to all feature's values before plotting them. In our example we used it on both trading partners' features - imports and exports which gives bubble chart new look:
 
 
The same data displayed on logarithmic scale appear almost uniform but not to forget the farther away points from 0 the more orders of magnitude they are apart on actual scale (observe this by scrolling back to the original plot). The main advantage of using log scale in this plot is ability of observing relationships between all top 30 countries without loosing the whole picture and avoiding collapsing smaller points together.
 
For more detailed discussion of logarithmic scale refer to When Should I Use Logarithmic Scales in My Charts and Graphs? Oh, and how about that trade deficit with China?
 
This is a re-post from the original blog on LinkedIn.