I’ve been working on matrr.com project for the last year. Different labs across the country offer monkeys an alcoholic beverages (4% EtOH mixed with sugar in water) and investigate the consequesnces. We collect the data for the reuse by others, while also aggregating and doing various analysis. In particular, while making the weight change plots, I figured that drinking make you fat!

Well, there is no surprise - I’ve noticed that drinkers often fat (if they are not poor) a long time ago among humans. But let’s see that effect precisly on Rhesus Macaques:

Animal Weight Change

Notice how weight increases steadily over the alcohol exposure periods (Induction and Open Access). Then something interesting happens: after withdrawal (they take them away from alcohol), animal loses 20% of its body weight during one month! Then, alcohol restored, it gains weight again; cycle repeats with the new withdrawals.

Lesson to be learned? Don’t drink heavily, but if you do, don’t eat too much, at least :)

On the separate note, check out how easy it is to work with python\django\matplotlib\pandas - you type and it does it. Here is how to create this plot:

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
def monkey_weight_plot(monkey):
    """
    Create mky weight plot
    """
    def weight_plot_makeup(ax):
        """
         Adjusting plot appearance
        """
        # set font size
        matplotlib.rcParams.update({'font.size': 14})

        # get legend: handles (lines) and labels (captions)
        handles, labels = ax.get_legend_handles_labels()

        # add animal's info
        if monkey.mky_drinking_category is None:
            labels = [str(monkey.mky_id) + ' Control']
        else:
            labels = [str(monkey.mky_id) + ' ' + monkey.mky_drinking_category]

        # plug labels back
        ax.legend(handles, labels, loc='upper left')  # reverse to keep order consistent

        # set labels and titles
        ax.set_ylabel('Monkey Weight')
        ax.set_title('Animal Weight Change')

        # make tight layout to avoid space waste
        pyplot.tight_layout()

    def make_event_annotations(ax):
        """
        Annotate the axis with cohort's events
        """
        # retrieve events for cohort from DB
        cevs = CohortEvent.objects.filter(cohort=monkey.cohort)

        # put into data frame
        evts = pd.DataFrame(list(cevs.values_list('event__evt_name', 'cev_date')),
                            columns=['event', 'date'])      # get values
        # filter by regex and negate
        evts_begin = evts[~evts.event.str.contains('.*(Before|Necropsy|Pre|Endocrine|(H2O)|(Ethanol.*End.*))')]

        # plot ablines
        [ax.axvline(x, color='r', linestyle='--') for x in evts_begin.date]

        # get ylim of axis
        ymin, ymax = ax.get_ylim()

        # plot event at date while iteration tuples
        [ax.text(x[1].date, ymin + 0.05, x[1].event,
                 verticalalignment='bottom', horizontalalignment='right',
                 rotation='vertical') for x in evts_begin.iterrows()]

        # adjust left xlim to fit text annotaiton
        xmin, xmax = ax.get_xlim()
        ax.set_xlim(xmin - 20, xmax)

    # retrieve data from DB into ORM's (Django) class objects
    mtds = MonkeyToDrinkingExperiment.objects.filter(monkey=monkey)\
        .filter(mtd_weight__isnull=False).order_by('drinking_experiment__dex_date')

    # if have data (no need to write count() > 0)
    if mtds.count():
        # create pandas dataframe
        df = pd.DataFrame(list(mtds.values_list('drinking_experiment__dex_date', 'mtd_weight')),
                          columns=['Date', 'weight'])

        # get new figure with desired size and DPI
        fig = pyplot.figure(figsize=DEFAULT_FIG_SIZE_ALEX, dpi=DEFAULT_DPI)

        # add subplot to a figure
        ax = fig.add_subplot(111)

        # line plot the weight change via pandas df's method
        df.plot(x='Date', y='weight', ax=ax, color=DRINKING_CATEGORIES_COLORS[monkey.mky_drinking_category])

        # adjust appearance
        weight_plot_makeup(ax)

        # make event annotations
        make_event_annotations(ax)

        return fig, True
    else:
        return False, False
(Read More...)

During the Spring 2015 I’ve taken the Machine Learning class which was a blast: by applying rather simple math apparatus in a fancy fashion we can learn on the data we have.

What is Machine Learning anyways?

There is a slim edge between stats, data mining and ML - they all interconnected, sure, but the key difference is the following:

  • Stats: we try to describe the data and estimate significance based on the samples we have; most of the times we want sample to be drawn out of “normal” population (meaning, in stats, all the possible data points).

  • Data Mining: we try to mine some associations and connections between the items in the dataset; no assumptions on the data.

  • Machine Learning: given the dataset (sample mapping) of X->Y, we want to *learn to mimic” the algorithm that converts the X into Y, so we can use it later on new X’. In general, there are no assumptions on the distribution (although some methods do assume things), and what’s cool, that we don’t really care what the algorithm looks like, as long as we can successfully mimic it (what a bummer for all the stats people who are like “wat? I want to know the true process!” right now..)

Anyways, during the class we had several home assignments to investigate different aspects of various methods which I present below, along with the short summary of what is learned.

Investigations (pdf papers)

Linear and Logistic regression: Gradient Descent and Newton’s method

W3Schools The most basic ML’s tool is the Linear Regression: we try to fit the line into the data points (i.e. price of the apartment based on size and distance to public transport; then we can predict how much would the new apt cost with given size and distance).

Then we can do a “sliding window” for achieving locally-weighted linear regression - we can make the line flexible. Playing with the weights we trade off bias and variance.

Instead of “float” regression, we can do “logistic” (dichotomy) regression, i.e. answering “yes” or “no” for a given data.

To solve this we use the one of the following:

Linear Regression & Logistic Regression:

  • Gradient Descent - fast and efficient, has closed form solution; could get stuck in local optima; could be randomized.
  • Newthon’s method - even faster - finishes in just a few iteration; could have issues on some data since needs Hessian matrix (second partial derivative).

K-Means Clustering

W3Schools K-means is a work horse in data analysis - it is so simple, fast and efficient, that most of the times we end up using it either directly, or within more complex procedure.

The paper investigates how to choose optimal k (try several, check the error, take the k with min error) and the importance of the initialization - with bad luck K-means can get stuck in local optima; but we are computer scientists, we don’t like to be dependent on luck - run K-means many many times and take the best results - the chances of getting stuck in local optima decrease polynomially.

K-means is a particular case of Expectation-Minimization algorithms family. We could use median or whatever else to achieve the result - paper shows the generalized approach.

GDA, Naive Bayes and Ridge Regression

W3Schools In Gradient Descent we have some problems with the collinearity. Ridge regression technique allows to penalize high theta (hypothesis of algorithm that we are trying to learn) coefficients, that appeared due to the collinearity in the data, while with moderate values of parameter λ it would not significantly decrease predictive power (in other words would not increase cost function). By doing that we avoid blown-up theta values that potentially lead to calculus errors.

Paper also compares the Naive Bayes vs SVM performance on spam filter example, how to do La-Place smoothing to avoid missing data errors, and also shows how the two-class Gaussian Discriminant Analysis, with common covariance Σ, is exactly a logistic sigmoid function.

Mistake Bounds and Uniform Convergence

W3Schools The cool thing is - we can put a bound on how big our mistakes could be. This paper goes rather deep in how by making more hypothesis we reduce the chance of the mistakes. Also discuses the usage of L-2 soft margins for SVM.

(Read More...)

Being a Mustashian, as I’ve learned only recently (many Russians are anyway), I like to see precisely how my money flow in and out. It’s been a year since I started to play the Credit Game, and now when my score was high enough to get some classic credit cards I’m ready to do some evaluation.

Firstly, primary reasons for credit cards are:

  • Protection against fraud
  • Risk diversification - use credit cards in seedy places
  • Cash Back Rewards
  • Some other perks like free rental insurance

I decided to start with BoF Cash Rewards which promised a $100 sing-up bonus after I spent $500 in first three months. Since I can pay my electricity and at&t bills with the credit cards without any fees, along with the groceries of course, I decided $500 would not take longer then a couple of months anyway.

Here is what I’ve got:
bof-cach-back-rewards

Surprisingly, I’ve gotten rewards on almost all the purchases (I did not plan individual purchases) since card makes 3% (instead of base 1%) on gas and groceries. Additionally, as promised, I received a $100 signing bonus.

(Important caveat: I know that for many people it’s very hard to control what they buy when the see buzz words “free”, “reward” etc; I tend to believe I’m almost free of such impulses and all the purchases I would have made regardless of the whether or not I get a cash back bonus)

Now the coolest part is that nobody forces me to spent this cash right away (although they try to advertise various stores and deals). I simply chosen to redeem as a direct deposit to my checking account. I was surprised that for doing so I actually receive additional %10 loyalty bonus: bof-cach-back-rewards

Additionally, I actually used Chase Freedom credit card. I have had to flight for onsite interviews and had to spend reimbursable money - I figured free cash back would be nice. There were “spend $300 in three months” deal too so I’ve gotten additional $100 bonus.

To compare cards: Chase’s freedom gives much better CL, but their online banking is garbage. They use points instead of actual currency which hinders analysis and that I don’t like.

PS this post inspired by Brandon’s blog which is a nice story to read. Reading, writing and thinking about things allows be to better understand nature, and that, in turn, makes me a happier primate.

PSS ugly $100 for at&t is due to the new user on my account which covers two month of the usage. Normally I pay only $30, which still a whole lot for the little of simple service I need.

(Read More...)

I’m often fascinated by the randomness and its patterns around us. It’s gorgeous. Just look at this picture, generated by percolation simulation: percolation

Simulation starts with all the cells closed, then iteratively opens one cell at the time at random. If cell connected to the top - it percolates with water. Simulation stops whenever water reaches the bottom. On average, it takes ~0.59% of cells to be open for the system to percolate. As it percolates, some cells still stay closed.

This picture reminds of the galaxies - why some happened to be suitable for water and atmosphere and some to be so barren? The answer is, probably, - due to the chance.

Another picture, taken from wiki storage, shows one of the few possible chess board traversal by the knight without visiting the same cell twice.
knights tour

Interestingly, you can easily see the patterns, yet you can’t easily comprehend the complex structure of the puzzle.

(Read More...)

So much more often than not users are being solicited with the “Install our new super awesome mobile app”, which does not fulfil the goals for which they tried to access the web resource in the first place. Annoying pop up often prevents from getting further, but even if you manage to close the pop up - you’ll most likely get a mobile version of the web site.

While apps and mobile versions of the sites are great and have some significant advantages, they often just don’t provide with the full functionality of the original resource, and rightly so. Well, the thing is, sometimes you just absolutely need to access the full version to get what you want. Alternatively, you don’t want to spend your space on the device (especially in today’s world of ridiculous >50 MB apps for something really unimportant), or you want to spare the internet connection - the list goes on and on.

So the rule of thumbs for developers is: allow easy, obvious access to the full version of the web site on the mobile devices.

Another anti-pattern is to unilaterally turn on the sound on the mobile device. That’s just horrible, really. Never, never play sound on the mobile unless user asks for it. Facebook and Instagram recently realized that (obvious) idea which is great. Other devs should follow too.

Pop Up Sound

P.S. As usual, screenshot doesn’t capture video frames. In reality, video is playing without me starting it.

(Read More...)