|
| 1 | +## Exercise Solutions |
| 2 | + |
| 3 | +General polynomial function: |
| 4 | + |
| 5 | + def calc_poly(params, data): |
| 6 | + x = np.c_[[data**i for i in range(len(params))]] |
| 7 | + return np.dot(params, x) |
| 8 | + |
| 9 | +Microbiome exercise: |
| 10 | + |
| 11 | + metadata = pd.read_excel('data/microbiome/metadata.xls', sheetname='Sheet1') |
| 12 | + |
| 13 | + chunks = [] |
| 14 | + for i in range(9): |
| 15 | + this_file = pd.read_excel('data/microbiome/MID{0}.xls'.format(i+1), 'Sheet 1', index_col=0, header=None, names=['Taxon', 'Count']) |
| 16 | + this_file.columns = ['Count'] |
| 17 | + this_file.index.name = 'Taxon' |
| 18 | + for m in metadata.columns: |
| 19 | + this_file[m] = metadata.ix[i][m] |
| 20 | + chunks.append(this_file) |
| 21 | + |
| 22 | + pd.concat(chunks) |
| 23 | + |
| 24 | +Titanic proportions: |
| 25 | + |
| 26 | + titanic = pd.read_excel("data/titanic.xls", "titanic") |
| 27 | + |
| 28 | + titanic.groupby('sex')['survived'].mean() |
| 29 | + |
| 30 | + titanic.groupby(['pclass','sex'])['survived'].mean() |
| 31 | + |
| 32 | + titanic['agecat'] = pd.cut(titanic.age, [0, 13, 20, 64, 100], labels=['child', 'adolescent', 'adult', 'senior']) |
| 33 | + titanic.groupby(['agecat', 'pclass','sex'])['survived'].mean() |
| 34 | + |
| 35 | +Survivor KDE plots: |
| 36 | + |
| 37 | + surv = dict(list(titanic.groupby('survived'))) |
| 38 | + for s in surv: |
| 39 | + surv[s]['age'].dropna().plot(kind='kde', label=bool(s)*'survived' or 'died', grid=False) |
| 40 | + legend() |
| 41 | + xlim(0,100) |
| 42 | + |
| 43 | +OBP: |
| 44 | + |
| 45 | + baseball[['h','bb', 'hbp']].sum(axis=1).div( |
| 46 | + baseball[['bb', 'hbp','ab', 'sf']].sum(axis=1) |
| 47 | + ).order(ascending=False) |
| 48 | + |
| 49 | +Cervical dystonia estimation: |
| 50 | + |
| 51 | + norm_like = lambda theta, x: -np.log(norm.pdf(x, theta[0], theta[1])).sum() |
| 52 | + |
| 53 | + fmin(norm_like, np.array([1,2]), args=(cdystonia.twstrs[(cdystonia.obs==6) & (cdystonia.treat=='Placebo')],)) |
| 54 | + fmin(norm_like, np.array([1,2]), args=(cdystonia.twstrs[(cdystonia.obs==6) & (cdystonia.treat=='5000U')],)) |
| 55 | + |
| 56 | +Cervical dystonia bootstrapping: |
| 57 | + |
| 58 | + x = cdystonia.twstrs[(cdystonia.obs==6) & (cdystonia.treat=='Placebo') & (cdystonia.twstrs.notnull())].values |
| 59 | + n = len(x) |
| 60 | + s = [x[np.random.randint(0,n,n)].mean() for i in range(R)] |
| 61 | + placebo_mean = np.sum(s)/R |
| 62 | + |
| 63 | + s_sorted = np.sort(s) |
| 64 | + alpha = 0.05 |
| 65 | + s_sorted[[(R+1)*alpha/2, (R+1)*(1-alpha/2)]] |
0 commit comments