Python’s Matplotlib offers great flexibility of plotting. Pandas adds convenience of working with data and plotting it. There is also a Seaborn that makes the output plots look pretty. Let’s see an example.

Basic Pandas Boxplot

I have a Pandas dataframe containing rows of data points describing monkey’s drinking. Each row has a few quantitative attributes of interest and experiment-specific attributes (factors), such as ‘Sex’ (Gender) and ‘Period’ (arbitrary stage of the experiment). Our goal is to see, whether the quantitative attributes are dependent on those factors.

In particular, it is of interest, for each quantitative attribute, to see the boxplot for each combination (Sex, Period). To do just that is very simple with pandas:

df.boxplot(column=attribute, by=['Sex', 'Period'])

And if, instead, we want to see M and F close together, by Period, then the change is tiny:

df.boxplot(column=attribute, by=['Period', 'Sex'])

Dealing With Two Factors

OK, well - that’s quite ugly: though works, it’s very hard to read the plot - viewer have to pay a close attention to the labels. How can we do better? First thing - is split factors somehow. Luckily, Pandas offers an easy way to do just that - we first groupby by one factor, and the boxplot with ‘by’ by another factor:

df.groupby('Sex').boxplot(column=attribute, by='Period')

That’s something - definitely looks better. The problem arises for the other grouping, however:

df.groupby('Period').boxplot(column=attribute, by='Sex')

Factorplot in Seaborn

Luckily, we can both make the plots look better and cope with bad subplots arrangement by using the Seaborn library. It doesn’t allow for multiple groupby in it’s boxplot implementation, however it offers a special factorplot which does exactly what we want:

import seaborn as sns
sns.factorplot(kind='box',        # Boxplot
               y=attribute,       # Y-axis - values for boxplot
               x='Period',        # X-axis - first factor
               hue='Sex',         # Second factor denoted by color
               data=df_dc,        # Dataframe 
               size=8,            # Figure size (x100px)      
               aspect=1.5,        # Width = size * aspect 
               legend_out=False)  # Make legend inside the plot

And surely that works for the alternative arrangement of the factors:

sns.factorplot(kind='box', y=attribute, x='Sex', hue='Period',
               data=df_dc, size=8, aspect=1.5, legend_out=False) 

With that, I hope all people, who produce plots, would care about their viewers and make a nice readable plots and will never ever ever create a piechart…

(Read More...)

I’ve taken Time Series analysis class to figure out if analyzing financial data and predicting stock markets (my first association with time series) were something I would be interested in doing. Additionally, there are many practical scientific and business applications - starting with electrocardiology analysis and ending with airline tickets sales.

What I’ve learned, shortly:

  • Don’t play on the stock markets - the best guess is (almost) always the current value (in other words, the chance of being any good in prediction is basically zero).
  • Use TS to gain insights about your business data.
  • Scientific use is very complicated most of the times nonetheless interesting.

What is Time Series Analysis anyways?

In regular stats we have a population (set of all data points), from which we have a random (i.e. representative - hopefully) sample (of size N) of available observations. We calculate sample statistics and infer it to be true about the general population as well. The bigger the sample size N the more we are statistically sure.

Now, Time Series Analysis aims to perform similar trick (analyzing sample and inferring about general) but for the process rather than for the population. Usually, then, we have only one observation/realization (Apple stock price history) of the process , but this process could have generated a different realization - in fact infinitely many of them! That is the key difference of the TS: we trying to describe the process that generated different realizations using available observations (usually one) and then predict what would happen to our realization in the future. I hope by now you get the idea of how sketchy and speculative all that sound - in case of the stock markets, especially, it’s pretty much a gamble.

To describe the observation (time series) people came up with a model ARIMA, which stands for auto regressive integrated moving average. Sounds scary, but in reality it’s extremely simple:

  • AR part is just a linear combination (summation with coefficients) of previous TS values equal white noise.
  • MA part is again just a linear combination, this time of random noise values equals to the current TS value.
  • Integrated simply means that de-trend the time series by linearly subtracting previous value from the current.

Given the realization, we try to fit the coefficients for those linear combinations and then predict the future values.

That is, shortly, what is Time Series about. Again, importantly, the length of the TS doesn’t give us the statistical power, as in regular statistics - we only gain power if we have more realizations, when, for instance, we track the heart beat process for the 24 hours straights, which yields a lot of observations of that cyclic process.

Investigations (pdf papers)

Estimating ARMA Coefficients and Predicting Future

In this take home final exam for TS class we created a definitive ARMA process (by specifying the true coefficients) to generate 500 realizations. Then using them (all or partially) tried to fit the coefficients using the standard tool set, while judging which metrics work better for our case. Finally, there is example of predicting TS - even for the simple case it works remarkably bad, in my opinion.

(Non) Consistent Estimators and the Effect of Differencing

Consistent estimator is an estimator which only gets closer to the true parameter given more realizations. In this paper we learn that while sample autocorrelation is consistent estimator, periodogram is not.

(First order) differencing is just: for each x_(i) in TS do: x_(i) = x_(i) - x_(i-1). By doing so we can remove linear trend. Paper discusses how to do that in R and how it affects sample correlogram and spectrum.

Harmonic Process and How to Convert ARMA into MA

Harmonic process is simply sum of sinusoids, we show it to be second-order stationary. Also it doesn’t have a good spectrum function because it’s not absolutely continuous; the cumulative spectrum is alright though.

Then paper shows how to convert ARMA into MA(inf) representation by long division - which only works if the AR roots are outside of unit circle.

Paper also shows the effect of taking the 12th differencing on spectrum and shows how to check whether or not the AR coefficients are valid (possible).

Time Series Models Summary

A dry summary on TS models: White Noise, Random Walk, Harmonic, AR, MA, ARMA and their properties: ACF, partial ACF and spectrum.

(Read More...)

I’ve grown to be quite a fan of Python tools for plotting - namely, Matplolib library, and other packages that uses it, i.e. Pandas. Community is also great, all the questions has long been answered on StackOverflow.

In this post I just want to share and preserve those useful methods and approaches that I came up with while working on my bio data analysis. Below is the result plot, which contains a lot of raw and aggregated information:

Regression (BD)

And here goes the code that makes it done, along with explanatory comments:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def plot_panels(df_all, df_group_1, df_group_2,
                label1, label2, font_sz=12):
    # Create figure and axes
    fig, axs = plt.subplots(nrows=4, ncols=3, figsize=(20, 10),
                            facecolor='w', edgecolor='k')
    # Makes axes a flat list
    axs = axs.ravel()

    # We would need a secondary Y-axis
    axs_hist = [ax.twiny() for ax in axs]

    # Const some plot props
    xlim = (0, 8)
    ylim = (-10, 400)
    alpha = 0.3

    # Iterate through drinking categories (DC) - rows in the plot
    # Enumerate allows to have index i
    for i, dc in enumerate(['LD', 'BD', 'HD', 'VHD']):
        # Filter data frames by DC
        df_dc_1 = df_group_1[df_group_1.dc == dc]
        df_dc_2 = df_group_2[df_group_2.dc == dc]
        df_dc_all = df_all[df_all.dc == dc]

        # Plot each group
        for x, ax_offset in zip(
                ['etoh_previos_day', 'etoh_at_bec_sample_time',
                 'etoh_next_day'],
                [0, 1, 2]):
            # Condition A
            df_dc_1.plot(kind='scatter', x=x, y='bec', c='g',
                         xlim=xlim, ylim=ylim, ax=axs[i*3 + ax_offset])

            # Condition B
            df_dc_2.plot(kind='scatter', x=x, y='bec', c='orange',
                         xlim=xlim, ylim=ylim, ax=axs[i*3 + ax_offset])

            # Add histogram for all data points
            df_dc_all.bec.hist(color='b', orientation='horizontal',
                               ax=axs_hist[i*3 + ax_offset],
                               alpha=alpha,   # transparency
                               bins=20,       # number of bins to distribute
                               normed=True)   # normalize to be comparable across 
                                              # different sample sizes

            # Add regressions
            _regression_and_corr(df=df_dc_1, x=x, ax=axs[i*3 + ax_offset])
            _regression_and_corr(df=df_dc_2, x=x, ax=axs[i*3 + ax_offset])

            # Calculate ANCOVA p-value (H0: slopes are equal)
            _plot_ancova_regression_pvalue(df=df, ax=axs[i*3 + ax_offset])

    # Fine tune plot look'n'feel
    plt.tight_layout()

    # Hide spaces between subplots
    fig.subplots_adjust(hspace=0)
    fig.subplots_adjust(wspace=0)

    # Hide all ticks
    plt.setp([a.get_xticklabels() for a in fig.axes], visible=False)
    plt.setp([a.get_yticklabels() for a in fig.axes], visible=False)

    # Show first columns and last row ticks since they are shared
    plt.setp([axs[i].get_xticklabels() for i in [9, 10, 11]], visible=True)
    plt.setp([axs[i].get_yticklabels() for i in [0, 3, 6, 9]], visible=True)

    # Label rows Y-label
    [ax.set_ylabel('') for ax in axs]
    axs[0].set_ylabel('LD', fontsize=font_sz)
    axs[3].set_ylabel('BD', fontsize=font_sz)
    axs[6].set_ylabel('HD', fontsize=font_sz)
    axs[9].set_ylabel('VHD', fontsize=font_sz)

    # Dummy scatter for legend
    dot_1 = plt.scatter([1], [1], color='g', marker='o', label=label1, s=80)
    dot_2 = plt.scatter([1], [1], color='orange', marker='o', label=label2, s=80)
    axs[0].legend(handles=[dot_1, dot_2],
                  bbox_to_anchor=[0, 1],
                  loc='lower left',
                  scatterpoints=1)

    # Set figure's title
    title = 'BEC correlation: EtOH the day before, day of and day after'
    fig.text(0.5, 0.94, title, ha='center', fontsize=font_sz + 4)
    fig.text(0.005, 0.5, 'BEC', va='center', rotation='vertical')
    fig.subplots_adjust(top=0.90)

    # Label groups
    fig.text(0.19, 0.01, 'EtOH Day Before', ha='center', fontsize=font_sz)
    fig.text(0.5, 0.01, 'EtOH Day of BEC Sample', ha='center', fontsize=font_sz)
    fig.text(0.83, 0.01, 'EtOH Day After', ha='center', fontsize=font_sz)
    fig.subplots_adjust(bottom=0.05)

    return fig

Where regression lines are made with Numpy’s polyfit:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def _regression_and_corr(df, x, ax):
    # Get x and y
    x = df[x]
    y = df['bec']
    
    # Fit straight line (polynomial of the first degree)
    fit = np.polyfit(x, y, deg=1)
    ax.plot(x, fit[0] * x + fit[1], color=linecol)

    # Annotate
    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
    text = group_label + ' Corr: %s' % np.round(x.corr(y), 4)
    ax.text(0.05, 0.95 + text_y_adj, text,
            transform=ax.transAxes, fontsize=14,
            verticalalignment='top', bbox=props)

The reason why histogram appeared on the plot is because we spotted some unexpected behavior - histogram clarified that it was just a perception problem - too many data points. As an alternative, we can do hexbin plot with a slight twitch of code:

1
2
3
4
5
# Using 24 subplots instead
# And Pandas's hexbin method:
axs[i*6 + offset].hexbin(x=df_dc_1.etoh_previos_day, y=df_dc_group_1.bec, 
			   cmap=plt.cm.Greens,  # Color scheme
			   gridsize=10)         # Fairly important parameter

Regression (BD)

Hexbin plot allows us to see another dimension for the case of too many data points by histograming those points into hexagonal bins.

(Read More...)

How to compare two regressions in Python? I didn’t find a good simple answer - hence this post. Seems like we need to compare regressions by slope, but how to test the significance? ANCOVA is the answer!

Imagine you have a dataset, in which you want to investigate the dependence of one variable of another, in our case - how BEC (Blood Ethanol Concentration) depends on EtOH. Additionally, we have the categorical variable - condition, in our case condition is either ‘Within’ or ‘Over’.

First step in the analysis is to scatterplot the data and calculate the correlation, for each condition:

Regression (BD)

Regression (HD)

We can clearly see, that while for ‘BD’ two regression lines differ in slopes a lot, for ‘HD’ they look almost parallel. Now the question is how to make a statistically sound statement?

Well, there is an ANCOVA (Analysis of Covariance) model. Why and how you can read intro here.

Now, how to do that in Python? Apperantly, you can use a standard OLS model from statsmodel with just a tweak of a formula (that is there is no big difference in the tool set between ANOVA and ANCOVA). Assume the following Pandas Data Frame:

DC  EtOH  BEC   Condition  
-------------------------
BD  2.60  59.0  True   
HD  2.20  77.0  True   
HD  2.22  60.0  False 
... ...   ...   ...

Then by doing:

1
2
3
4
5
6
from statsmodels.formula.api import ols
# formula = 'BEC ~ EtOH'               # Simple regression
formula = 'BEC ~ EtOH * C(Condition)'  # ANCOVA formula
lm = ols(formula, dataframe[dataframe.DC == 'HD'])
fit = lm.fit()
print fit().summary()

We get the p-value of how significant the effect of the Condition is on our regression slopes:

                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    bec   R-squared:                       0.172
Model:                            OLS   Adj. R-squared:                  0.170
Method:                 Least Squares   F-statistic:                     62.67
Date:                Thu, 14 Jan 2016   Prob (F-statistic):           8.32e-37
Time:                        16:31:31   Log-Likelihood:                -4877.4
No. Observations:                 906   AIC:                             9763.
Df Residuals:                     902   BIC:                             9782.
Df Model:                           3                                         
Covariance Type:            nonrobust                                         
==============================================================================
                                    coef    std err          t      P>|t|     
------------------------------------------------------------------------------
Intercept                        16.8906      6.233      2.710      0.007     
C(Condition)[T.True]             37.2833     26.816      1.390      0.165     
EtOH                             26.4234      2.160     12.233      0.000     
EtOH:C(Condition)[T.True]         2.2716      8.933      0.254      0.799     
==============================================================================
Omnibus:                       18.672   Durbin-Watson:                   1.143
Prob(Omnibus):                  0.000   Jarque-Bera (JB):               21.270
Skew:                           0.284   Prob(JB):                     2.41e-05
Kurtosis:                       3.490   Cond. No.                         49.0
==============================================================================  

We are interested in the line:

                                    coef    std err          t      P>|t|     
------------------------------------------------------------------------------   
EtOH:C(Condition)[T.True]         2.2716      8.933      0.254      0.799 

Meaning p-value = 0.799, which suggests us not to reject the H0 (initial hypothesis) that two slopes are equal. That means that slopes in case of ‘HD’ are statistically same.

No surprise - test for ‘BD’:

                                    coef    std err          t      P>|t|
-------------------------------------------------------------------------   
EtOH:C(Condition)[T.True]        42.6065     13.232      3.220      0.001

P-value of 0.001 and we happily reject the equal slopes hypothesis.

(Read More...)

Recently I figured a neat way to print the content of the model for your own testing of for data shipment. Most of the times you want to use Pandas DataFrame, but you need to pass along the fields that you want to select from the DB. More often than not though the fields that you want to display stay same for the model. That’s why I started to add one extra field to the model - columns for display. For example, in MonkeyEphys:

1
2
3
4
5
6
7
8
9
10
11
12
class MonkeyEphys(models.Model):   
  # bunch of fields: some useful, some technical
  ...
  monkey = models.ForeignKey(Monkey, related_name='mep_records')
  mep_frequency = models.FloatField("Frequency (hz)")
  mep_tissue_type = models.ForeignKey(TissueType, related_name='ephys_records')
  ...  

  # Tuple: (list of db attributes, list of column names to display)
  columns = (['monkey__mky_id', 'mep_tissue_type__tst_tissue_name',
              'mep_ephys_type', 'mep_frequency'],
             ['mky_id', 'tissue_name', 'ephys_type', 'frequency'])

Now you can use this tuple in Pandas:

1
2
3
4
5
 
  df = pd.DataFrame(list(MonkeyEphys.objects.all().\
         values_list(*MonkeyEphys.columns[0])),  # *kwargs - fields to be selected
         columns=MonkeyEphys.columns[1])         # displayable column names
  print df

Now, it gets better than this. Have you ever dreamed of static methods for the model? Well, your dreams are true - you can delegate repeatable some code specifically to the model, yey! Let’s continue with the Ephys example, say we don’t want to type the selection code every time - well, just append a static method for it:

1
2
3
4
5
6
7
 
@staticmethod
def content_print():
  print pd.DataFrame(list(MonkeyEphys.objects.all() ...)

# Now this does the job:
MonkeyEphys.content_print()

Pretty neat, hah? Too bad I was completely ignorant of that before.

(Read More...)