[171cba]: / 4x / physical.py

Download this file

392 lines (203 with data), 8.6 kB

  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
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import numpy as np
import matplotlib.pyplot as plt
import seaborn
import pandas as pd
import itertools
from sklearn import linear_model, ensemble, decomposition, cross_validation, preprocessing
from statsmodels.regression.mixed_linear_model import MixedLM
def normalise(df, skip = []) :
for i in df.columns :
if i not in skip :
df[i] -= df[i].mean()
df[i] /= df[i].std()
return df
# Remove a layer from a list
def delayer(m) :
out = []
for i in m :
if isinstance(i, list) :
for j in i :
out.append(j)
else :
out.append(i)
return out
# Remove all layers from a list
def flatten(m) :
out = m[:]
while out != delayer(out) :
out = delayer(out)
return out
# Generate all combinations of objects in a list
def combinatorial(l) :
out = []
for numel in range(len(l)) :
for i in itertools.combinations(l, numel+1) :
out.append(list(i))
return out
def pcaplot(df) :
# PCA
pca = decomposition.PCA(whiten = True)
pca.fit(df)
p1 = pca.components_[0] / np.abs(pca.components_[0]).max() * np.sqrt(2)/2
p2 = pca.components_[1] / np.abs(pca.components_[1]).max() * np.sqrt(2)/2
# Normalise
norms = np.max([np.sqrt((np.array(zip(p1, p2)[i])**2).sum()) for i in range(len(p1))])
c = plt.Circle( (0, 0), radius = 1, alpha = 0.2)
plt.axes(aspect = 1)
plt.gca().add_artist(c)
plt.scatter(p1 / norms, p2 / norms)
plt.xlim([-1, 1])
plt.ylim([-1, 1])
for i, text in enumerate(df.columns) :
plt.annotate(text, xy = [p1[i], p2[i]])
plt.tight_layout()
def test_all_linear(df, y, x, return_significant = True, group = None) :
# All possible combinations of independent variables
independent = combinatorial(x)
fits = {}
pval = {}
linmodels = {}
qsum = {}
# For all dependent variables, one at a time
for dependent in y :
print "Fitting for %s." % dependent
# For all combinations of independent variables
for covariate in independent :
# Standard mixed model
if group is None :
# Fit a linear model
ols = pd.stats.api.ols(y = df[dependent], x = df[covariate])
# Save the results
if (return_significant and ols.f_stat["p-value"] < 0.05) or (not return_significant) :
linmodels.setdefault(dependent, []).append(ols)
fits.setdefault(dependent, []).append(ols.r2)
pval.setdefault(dependent, []).append(ols.f_stat["p-value"])
# Mixed effects model
else :
subset = delayer([covariate, dependent, group])
df2 = df[delayer(subset)].dropna()
# Fit a mixed effects model
ols = MixedLM(endog = df2[dependent], exog = df2[covariate], groups = df2[group]).fit()
# Calculate AIC
linmodels.setdefault(dependent, []).append(ols)
fits.setdefault(dependent, []).append(2 * (ols.k_fe + 1) - 2 * ols.llf)
pval.setdefault(dependent, []).append(ols.pvalues)
if group is not None :
for i in y :
f = np.array(fits[i])
models = np.array(linmodels[i])
idx = np.where(f - f.min() <= 2)[0]
bestmodelDoF = [j.k_fe for j in np.array(linmodels[i])[idx]]
bestmodels = [idx[j] for j in np.where(bestmodelDoF == np.min(bestmodelDoF))[0]]
qsum[i] = models[idx[np.where(f[bestmodels] == np.min(f[bestmodels]))]]
return linmodels, fits, pval, qsum
return linmodels, fits, pval
def summary(models) :
# Generate list of everything
r2 = np.array([m.r2 for dependent in models.keys() for m in models[dependent]])
p = np.array([m.f_stat["p-value"] for dependent in models.keys() for m in models[dependent]])
mod = np.array([m for dependent in models.keys() for m in models[dependent]])
dependent = np.array([dependent for dependent in models.keys() for m in models[dependent]])
# Sort by R2
idx = np.argsort(r2)[::-1]
# Output string
s = "%d significant regressions.\n\n" % len(r2)
s += "Ten most correlated :\n\n"
# Print a summary of the top ten correlations
for i in idx[:10] :
s += ("%s ~ %s\n" % (dependent[i], " + ".join(mod[i].x.columns[:-1])))
s += ("R^2 = %f\tp = %f\n\n" % (r2[i], p[i]))
print s
#return s
# Read physical data
physical = pd.read_csv("../physical.csv").drop(["CurrTag", "DeathDate", "Category"], 1)
# Read improc data
ent = pd.read_csv("results/entropy.csv").drop(["Unnamed: 0"], 1)
foci = pd.read_csv("results/foci.csv").drop(["Unnamed: 0"], 1)
lac = pd.read_csv("results/normalised_lacunarity.csv").drop(["Unnamed: 0"], 1)
gabor = pd.read_csv("results/gabor_filters.csv").drop(["Unnamed: 0"], 1)
ts = pd.read_csv("results/tissue_sinusoid_ratio.csv").drop(["Unnamed: 0"], 1)
# Merge dataframes
sheep = np.unique(ent.Sheep)
Ent = [np.mean(ent.loc[ent.Sheep == i]).Entropy for i in sheep]
EntVar = [np.var(ent.loc[ent.Sheep == i]).Entropy for i in sheep]
Focicount = [np.mean(foci.loc[foci.Sheep == i]).Count for i in sheep]
FocicountVar = [np.var(foci.loc[foci.Sheep == i]).Count for i in sheep]
Focisize = [np.mean(foci.loc[foci.Sheep == i]).meanSize for i in sheep]
FocisizeVar = [np.var(foci.loc[foci.Sheep == i]).meanSize for i in sheep]
Lac = [np.mean(lac.loc[lac.Sheep == i]).Lacunarity for i in sheep]
LacVar = [np.var(lac.loc[lac.Sheep == i]).Lacunarity for i in sheep]
Scale = [np.mean(gabor.loc[gabor.Sheep == i]).Scale for i in sheep]
ScaleVar = [np.var(gabor.loc[gabor.Sheep == i]).Scale for i in sheep]
Dir = [np.mean(gabor.loc[gabor.Sheep == i]).Directionality for i in sheep]
DirVar = [np.var(gabor.loc[gabor.Sheep == i]).Directionality for i in sheep]
TS = [np.mean(ts.loc[ts.Sheep == i]).TSRatio for i in sheep]
TSVar = [np.var(ts.loc[ts.Sheep == i]).TSRatio for i in sheep]
improc = pd.DataFrame({ "Sheep" : sheep,
"Entropy" : Ent,
"EntropyVar" : EntVar,
"FociCount" : Focicount,
"FociCountVar" : FocicountVar,
"FociSize" : Focisize,
"FociSizeVar" : FocisizeVar,
"Lacunarity" : Lac,
"LacunarityVar" : LacVar,
"Scale" : Scale,
"ScaleVar" : ScaleVar,
"Directionality" : Dir,
"DirectionalityVar" : DirVar,
"TissueToSinusoid" : TS,
"TissueToSinusoidVar" : TSVar
})
physcols = ["Weight", "Sex", "AgeAtDeath", "Foreleg", "Hindleg"]
imagecols = ["Entropy", "Lacunarity", "Scale", "Directionality", "FociCount", "FociSize", "TissueToSinusoid"]
# Merges :
# Sheep-centred dataframe
rawsheepdata = pd.merge(physical, improc, on="Sheep", how="outer")
sheepdata = normalise(rawsheepdata, skip = "Sheep")
# Image-centred dataframe
rawimagedata = pd.merge(lac, ent,
on=["Sheep", "Image"]).merge(foci.drop("stdSize", 1),
on=["Sheep", "Image"]).merge(gabor,
on=["Sheep", "Image"]).merge(ts,
on=["Sheep", "Image"]).merge(normalise(physical, skip = "Sheep"),
on="Sheep")
rawimagedata.rename(columns = { "meanSize" : "FociSize",
"TSRatio" : "TissueToSinusoid",
"Count" : "FociCount" }, inplace=True)
imagedata = normalise(rawimagedata, skip = physcols + ["Sheep"])
# COLUMN ON NUMBER OF IMAGES
"""
# CV
m = [ [[linear_model.ElasticNet(max_iter=1000000, alpha = i, l1_ratio = j)
for i in np.linspace(0.1, 1.0, 100)]
for j in np.linspace(0., 1.0, 100)],
[[[[linear_model.BayesianRidge(n_iter = 10000, alpha_1 = a1, alpha_2 = a2, lambda_1 = l1, lambda_2 = l2)
for a1 in np.logspace(1e-8, 1e-4, 20)]
for a2 in np.logspace(1e-8, 1e-4, 20)]
for l1 in np.logspace(1e-8, 1e-4, 20)]
for l2 in np.logspace(1e-8, 1e-4, 20)],
[ensemble.RandomForestRegressor(n_estimators = i) for i in np.unique(np.logspace(1, 4, 100).astype(int))],
[[[[ensemble.GradientBoostingRegressor(n_estimators = e, loss=l, learning_rate = r, max_depth = m)
for l in ["ls", "lad", "huber"]]
for e in np.unique(np.logspace(1, 4, 100).astype(int))]
for r in np.logspace(-4, 0, 200)]
for m in np.arange(1, 20)],
#ensemble.AdaBoostRegressor(n_estimators = 100),
#ensemble.AdaBoostRegressor(base_estimator = ensemble.GradientBoostingRegressor(n_estimators = 100), n_estimators = 100),
#ensemble.AdaBoostRegressor(base_estimator = ensemble.RandomForestRegressor(n_estimators = 50), n_estimators = 100),
[ensemble.BaggingRegressor(n_estimators = e) for e in np.unique(np.logspace(1, 4, 100).astype(int))]
]
methods = flatten(m)
# For each physical measurement, perform fits using all above methods
scores = {}
for col in physcols :
for q, method in enumerate(methods[10000:10100]) :
if not scores.has_key(col) :
scores[col] = []
scores[col].append(
cross_validation.cross_val_score(
method, d[imagecols], d[col], cv=cross_validation.ShuffleSplit(len(d), 100, test_size=0.1),
n_jobs = -1, scoring = "r2").mean())
print "Done %d" % q
"""