/
modeler.py
1442 lines (1182 loc) · 54.8 KB
/
modeler.py
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Class for dealing with training built-in or SKLL models,
as well as making predictions for new data.
:author: Jeremy Biggs (jbiggs@ets.org)
:author: Anastassia Loukina (aloukina@ets.org)
:author: Nitin Madnani (nmadnani@ets.org)
:organization: ETS
"""
import logging
import pickle
import warnings
from math import log10, sqrt
from os.path import join
import numpy as np
import pandas as pd
from numpy.random import RandomState
from scipy.optimize import nnls
from sklearn.linear_model import LassoCV
from skll import FeatureSet, Learner
from rsmtool.analyzer import Analyzer
from rsmtool.utils import compute_expected_scores_from_model, is_skll_model
from rsmtool.preprocessor import FeaturePreprocessor
from rsmtool.configuration_parser import Configuration
from rsmtool.container import DataContainer
from rsmtool.writer import DataWriter
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=FutureWarning)
import statsmodels.api as sm
class Modeler:
"""
A class for training and predicting with either
built-in or SKLL models. Also provides helper functions
for predicting train and test datasets.
"""
def __init__(self):
self.learner = None
@classmethod
def load_from_file(cls, model_path):
"""
Load a Model object from file.
Parameters
----------
model_path : str
The path to a model
Returns
-------
model : Modeler
A Modeler instance
Raises
------
ValuError
If the `model_path` does not end with '.model'
"""
if not model_path.lower().endswith('.model'):
raise ValueError('The file `{}` does not end with the '
'proper extension. Please make sure that '
'it is a `.model` file.'.format(model_path))
# Create SKLL learner from file
learner = Learner.from_file(model_path)
return cls.load_from_learner(learner)
@classmethod
def load_from_learner(cls, learner):
"""
Load a Modeler object from file.
Parameters
----------
learner : SKLL.Learner
A SKLL Learner object
Returns
-------
modeler : Modeler
A Modeler instance
Raises
------
TypeError
If `learner` is not SKLL.Learner instance.
"""
if not isinstance(learner, Learner):
raise TypeError('The `learner` argument must be a '
'` SKLL.Learner` instance, not `{}`.'
''.format(type(learner)))
# Create Modeler instance
modeler = Modeler()
modeler.learner = learner
return modeler
@staticmethod
def model_fit_to_dataframe(fit):
"""
Take an object containing a statsmodels OLS model fit and extact
the main model fit metrics into a data frame.
Parameters
----------
fit : a statsmodels fit object
Model fit object obtained from a linear model trained using
`statsmodels.OLS`.
Returns
-------
df_fit : pandas DataFrame
Data frame with the main model fit metrics.
"""
df_fit = pd.DataFrame({"N responses": [int(fit.nobs)]})
df_fit['N features'] = int(fit.df_model)
df_fit['R2'] = fit.rsquared
df_fit['R2_adjusted'] = fit.rsquared_adj
return df_fit
@staticmethod
def ols_coefficients_to_dataframe(coefs):
"""
Take a series containing OLS coefficients and convert it
to a data frame.
Parameters
----------
coefs : pandas Series
Series with feature names in the index and the coefficient
values as the data, obtained from a linear model trained
using `statsmodels.OLS`.
Returns
-------
df_coef : pandas DataFrame
Data frame with two columns, the first being the feature name
and the second being the coefficient value.
Note
----
The first row in the output data frame is always for the intercept
and the rest are sorted by feature name.
"""
# first create a sorted data frame for all the non-intercept features
non_intercept_columns = [c for c in coefs.index if c != 'const']
df_non_intercept = pd.DataFrame(coefs.filter(non_intercept_columns),
columns=['coefficient'])
df_non_intercept.index.name = 'feature'
df_non_intercept = df_non_intercept.sort_index()
df_non_intercept.reset_index(inplace=True)
# now create a data frame that just has the intercept
df_intercept = pd.DataFrame([{'feature': 'Intercept',
'coefficient': coefs['const']}])
# append the non-intercept frame to the intercept one
df_coef = df_intercept.append(df_non_intercept, sort=True, ignore_index=True)
# we always want to have the feature column first
df_coef = df_coef[['feature', 'coefficient']]
return df_coef
@staticmethod
def skll_learner_params_to_dataframe(learner):
"""
Take the given SKLL learner object and return a data
frame containing its parameters.
Parameters
----------
learner : SKLL.Learner
A SKLL learner object
Returns
-------
df_coef : pandas DataFrame
a data frame containing the model parameters
from the given SKLL learner object.
Note
----
1. We use underlying `sklearn` model object to get at the
coefficients and the intercept because the `model_params` attribute
of the SKLL model ignores zero coefficients, which we do not want.
2. The first row in the output data frame is always for the intercept
and the rest are sorted by feature name.
"""
# get the intercept, coefficients, and feature names
intercept = learner.model.intercept_
coefficients = learner.model.coef_
feature_names = learner.feat_vectorizer.get_feature_names()
# first create a sorted data frame for all the non-intercept features
df_non_intercept = pd.DataFrame({'feature': feature_names,
'coefficient': coefficients})
df_non_intercept = df_non_intercept.sort_values(by=['feature'])
# now create a data frame that just has the intercept
df_intercept = pd.DataFrame([{'feature': 'Intercept',
'coefficient': intercept}])
# append the non-intercept frame to the intercept one
df_coef = df_intercept.append(df_non_intercept, sort=True, ignore_index=True)
# we always want to have the feature column first
df_coef = df_coef[['feature', 'coefficient']]
return df_coef
@staticmethod
def create_fake_skll_learner(df_coefficients):
"""
Create fake SKLL linear regression learner object
using the coefficients in the given data frame.
Parameters
----------
df_coefficients : pandas DataFrame
Data frame containing the linear coefficients
we want to create the fake SKLL model with.
Returns
-------
learner: skll Learner object
SKLL LinearRegression Learner object containing
with the specified coefficients.
"""
# initialize a random number generator
randgen = RandomState(1234567890)
# iterate over the coefficients
coefdict = {}
for feature, coefficient in df_coefficients.itertuples(index=False):
if feature == 'Intercept':
intercept = coefficient
else:
# exclude NA coefficients
if coefficient == np.nan:
logging.warning("No coefficient was estimated for "
"{}. This is likely due to exact "
"collinearity in the model. This "
"feature will not be used for model "
"building".format(feature))
else:
coefdict[feature] = coefficient
learner = Learner('LinearRegression')
num_features = len(coefdict) # excluding the intercept
fake_feature_values = randgen.rand(num_features)
fake_features = [dict(zip(coefdict, fake_feature_values))]
fake_fs = FeatureSet('fake', ids=['1'], labels=[1.0], features=fake_features)
learner.train(fake_fs, grid_search=False)
# now create its parameters from the coefficients from the built-in model
learner.model.coef_ = learner.feat_vectorizer.transform(coefdict).toarray()[0]
learner.model.intercept_ = intercept
return learner
def train_linear_regression(self, df_train, feature_columns):
"""
Train `LinearRegression` (formerly empWt) -
A simple linear regression model.
Parameters
----------
df_train : pd.DataFrame
Data frame containing the features on which
to train the model.
feature_columns : list
A list of feature columns to use in training the model.
Returns
-------
learner : skll.Learner
The SKLL learner object
fit : statsmodels.RegressionResults
A statsmodels regression results object.
df_coef : pd.DataFrame
The model coefficients in a data_frame
used_features : list
A list of features used in the final model.
"""
# get the feature columns
X = df_train[feature_columns]
# add the intercept
X = sm.add_constant(X)
# fit the model
fit = sm.OLS(df_train['sc1'], X).fit()
df_coef = self.ols_coefficients_to_dataframe(fit.params)
learner = self.create_fake_skll_learner(df_coef)
# we used all the features
used_features = feature_columns
return learner, fit, df_coef, used_features
def train_equal_weights_lr(self, df_train, feature_columns):
"""
Train `EqualWeightsLR` (formerly eqWt) -
All features get equal weight.
Parameters
----------
df_train : pd.DataFrame
Data frame containing the features on which
to train the model.
feature_columns : list
A list of feature columns to use in training the model.
Returns
-------
learner : skll.Learner
The SKLL learner object
fit : statsmodels.RegressionResults
A statsmodels regression results object.
df_coef : pd.DataFrame
The model coefficients in a data_frame
used_features : list
A list of features used in the final model.
"""
# we first compute a single feature that is simply the sum of all features
df_train_eqwt = df_train.copy()
df_train_eqwt['sumfeature'] = df_train_eqwt[feature_columns].apply(np.sum,
axis=1)
# train a plain Linear Regression model
X = df_train_eqwt['sumfeature']
X = sm.add_constant(X)
fit = sm.OLS(df_train_eqwt['sc1'], X).fit()
# get the coefficient for the summed feature and the intercept
coef = fit.params['sumfeature']
const = fit.params['const']
# now we need to assign this coefficient to all of the original
# features and create a fake SKLL learner with these weights
original_features = [c for c in df_train_eqwt.columns if c not in ['sc1',
'sumfeature',
'spkitemid']]
coefs = pd.Series(dict([(origf, coef)
for origf in original_features] + [('const', const)]))
df_coef = self.ols_coefficients_to_dataframe(coefs)
# create fake SKLL learner with these coefficients
learner = self.create_fake_skll_learner(df_coef)
# we used all the features
used_features = feature_columns
return learner, fit, df_coef, used_features
def train_rebalanced_lr(self, df_train, feature_columns):
"""
Train `RebalancedLR` (formerly empWtBalanced) -
Balanced empirical weights by changing betas
[adapted from: https://stats.stackexchange.com/q/30876]
Parameters
----------
df_train : pd.DataFrame
Data frame containing the features on which
to train the model.
feature_columns : list
A list of feature columns to use in training the model.
Returns
-------
learner : skll.Learner
The SKLL learner object
fit : statsmodels.RegressionResults
A statsmodels regression results object.
df_coef : pd.DataFrame
The model coefficients in a data_frame
used_features : list
A list of features used in the final model.
"""
# train a plain Linear Regression model
X = df_train[feature_columns]
X = sm.add_constant(X)
fit = sm.OLS(df_train['sc1'], X).fit()
# convert the model parameters into a data frame
df_params = self.ols_coefficients_to_dataframe(fit.params)
df_params = df_params.set_index('feature')
# compute the betas for the non-intercept coefficients
df_weights = df_params.loc[feature_columns]
df_betas = df_weights.copy()
df_train_std = df_train[feature_columns].std()
df_betas['coefficient'] = (df_weights['coefficient'].multiply(df_train_std,
axis='index') /
df_train['sc1'].std())
# replace each negative beta with delta and adjust
# all the positive betas to account for this
RT = 0.05
df_positive_betas = df_betas[df_betas['coefficient'] > 0]
df_negative_betas = df_betas[df_betas['coefficient'] < 0]
delta = np.sum(df_positive_betas['coefficient']) * RT / len(df_negative_betas)
df_betas['coefficient'] = df_betas.apply(lambda row: row['coefficient'] * (1 - RT)
if row['coefficient'] > 0 else delta, axis=1)
# rescale the adjusted betas to get the new coefficients
df_coef = df_betas['coefficient'] * df_train['sc1'].std()
df_coef = df_coef.divide(df_train[feature_columns].std(), axis='index')
# add the intercept back to the new coefficients
df_coef['Intercept'] = df_params.loc['Intercept'].coefficient
df_coef = df_coef.sort_index().reset_index()
df_coef.columns = ['feature', 'coefficient']
# create fake SKLL learner with these coefficients
learner = self.create_fake_skll_learner(df_coef)
# we used all the features
used_features = feature_columns
return learner, fit, df_coef, used_features
def train_lasso_fixed_lambda_then_lr(self, df_train, feature_columns):
"""
Train `LassoFixedLambdaThenLR` (formerly empWtLasso) -
First do feature selection using lasso regression with
a fixed lambda and then use only those features to train
a second linear regression
Parameters
----------
df_train : pd.DataFrame
Data frame containing the features on which
to train the model.
feature_columns : list
A list of feature columns to use in training the model.
Returns
-------
learner : skll.Learner
The SKLL learner object
fit : statsmodels.RegressionResults
A statsmodels regression results object.
df_coef : pd.DataFrame
The model coefficients in a data_frame
used_features : list
A list of features used in the final model.
"""
# train a Lasso Regression model with this featureset with a preset lambda
p_lambda = sqrt(len(df_train) * log10(len(feature_columns)))
# create a SKLL FeatureSet instance from the given data frame
fs_train = FeatureSet.from_data_frame(df_train[feature_columns + ['sc1']],
'train',
labels_column='sc1')
# note that 'alpha' in sklearn is different from this lambda
# so we need to normalize looking at the sklearn objective equation
p_alpha = p_lambda / len(df_train)
l_lasso = Learner('Lasso', model_kwargs={'alpha': p_alpha, 'positive': True})
l_lasso.train(fs_train, grid_search=False)
# get the feature names that have the non-zero coefficients
non_zero_features = list(l_lasso.model_params[0].keys())
# now train a new vanilla linear regression with just the non-zero features
X = df_train[non_zero_features]
X = sm.add_constant(X)
fit = sm.OLS(df_train['sc1'], X).fit()
# get the coefficients data frame
df_coef = self.ols_coefficients_to_dataframe(fit.params)
# create fake SKLL learner with these coefficients
learner = self.create_fake_skll_learner(df_coef)
# we used only the non-zero features
used_features = non_zero_features
return learner, fit, df_coef, used_features
def train_positive_lasso_cv_then_lr(self, df_train, feature_columns):
"""
Train `PositiveLassoCVThenLR` (formerly empWtLassoBest) -
First do feature selection using lasso regression optimized
for log likelihood using cross validation and then use only
those features to train a second linear regression
Parameters
----------
df_train : pd.DataFrame
Data frame containing the features on which
to train the model.
feature_columns : list
A list of feature columns to use in training the model.
Returns
-------
learner : skll.Learner
The SKLL learner object
fit : statsmodels.RegressionResults
A statsmodels regression results object.
df_coef : pd.DataFrame
The model coefficients in a data_frame
used_features : list
A list of features used in the final model.
"""
# train a LassoCV outside of SKLL since it's not exposed there
X = df_train[feature_columns].values
y = df_train['sc1'].values
clf = LassoCV(cv=10, positive=True, random_state=1234567890)
model = clf.fit(X, y)
# get the non-zero features from this model
non_zero_features = []
for feature, coefficient in zip(feature_columns, model.coef_):
if coefficient != 0:
non_zero_features.append(feature)
# now train a new linear regression with just these non-zero features
X = df_train[non_zero_features]
X = sm.add_constant(X)
fit = sm.OLS(df_train['sc1'], X).fit()
# convert the model parameters into a data frame
df_coef = self.ols_coefficients_to_dataframe(fit.params)
# create fake SKLL learner with these coefficients
learner = self.create_fake_skll_learner(df_coef)
# we used only the non-zero features
used_features = non_zero_features
return learner, fit, df_coef, used_features
def train_non_negative_lr(self, df_train, feature_columns):
"""
Train `NNLR` (formerly empWtNNLS) -
First do feature selection using non-negative least squares (NNLS)
and then use only its non-zero features to train a regular linear regression.
We do the regular LR at the end since we want an LR object so that we have access
to R^2 and other useful statistics. There should be no difference
between the non-zero coefficients from NNLS and the coefficients
that end up coming out of the subsequent LR.
Parameters
----------
df_train : pd.DataFrame
Data frame containing the features on which
to train the model.
feature_columns : list
A list of feature columns to use in training the model.
Returns
-------
learner : skll.Learner
The SKLL learner object
fit : statsmodels.RegressionResults
A statsmodels regression results object.
df_coef : pd.DataFrame
The model coefficients in a data_frame
used_features : list
A list of features used in the final model.
"""
# add an intercept to the features manually
X = df_train[feature_columns].values
intercepts = np.ones((len(df_train), 1))
X_plus_intercept = np.concatenate([intercepts, X], axis=1)
y = df_train['sc1'].values
# fit an NNLS model on this data
coefs, rnorm = nnls(X_plus_intercept, y)
# check whether the intercept is set to 0 and if so then we need
# to flip the sign and refit the model to ensure that it is always
# kept in the model
if coefs[0] == 0:
intercepts = -1 * np.ones((len(df_train), 1))
X_plus_intercept = np.concatenate([intercepts, X], axis=1)
coefs, rnorm = nnls(X_plus_intercept, y)
# separate the intercept and feature coefficients
# intercept = coefs[0]
coefficients = coefs[1:].tolist()
# get the non-zero features from this model
non_zero_features = []
for feature, coefficient in zip(feature_columns, coefficients):
if coefficient != 0:
non_zero_features.append(feature)
# now train a new linear regression with just these non-zero features
X = df_train[non_zero_features]
X = sm.add_constant(X)
fit = sm.OLS(df_train['sc1'], X).fit()
# convert this model's parameters to a data frame
df_coef = self.ols_coefficients_to_dataframe(fit.params)
# create fake SKLL learner with these coefficients
learner = self.create_fake_skll_learner(df_coef)
# we used only the non-zero features
used_features = non_zero_features
return learner, fit, df_coef, used_features
def train_non_negative_lr_iterative(self, df_train, feature_columns):
"""
Train `NNLR_iterative` -
For applications where there is a concern that standard NNLS may not
converge, an alternate method of training NNLR by iteratively fitting OLS
models, checking the coefficients, and dropping negative coefficients.
First, fit an OLS model. Then, identify any variables whose coefficients
are negative. Drop these variables from the model. Finally, refit the
model. If any coefficients are still negative, set these to zero.
Parameters
----------
df_train : pd.DataFrame
Data frame containing the features on which
to train the model.
feature_columns : list
A list of feature columns to use in training the model.
Returns
-------
learner : skll.Learner
The SKLL learner object.
fit : statsmodels.RegressionResults
A statsmodels regression results object.
df_coef : pd.DataFrame
The model coefficients in a data frame
used_features : list
A list of features used in the final model.
"""
X = df_train[feature_columns]
X = sm.add_constant(X)
y = df_train['sc1']
fit = sm.OLS(y, X).fit()
positive_features = []
for name, value in fit.params.items():
if value >= 0 and name != 'const':
positive_features.append(name)
X = df_train[positive_features]
X = sm.add_constant(X)
fit = sm.OLS(y, X).fit()
# if any parameters are still negative, set them to zero
params = fit.params.copy()
params = params.drop('const')
if not (params >= 0).all():
fit.params[(fit.params < 0) & (fit.params.index != 'const')] = 0
# convert this model's parameters to a data frame
df_coef = self.ols_coefficients_to_dataframe(fit.params)
# create fake SKLL learner with these coefficients
learner = self.create_fake_skll_learner(df_coef)
# we used only the non-zero features
used_features = positive_features
return learner, fit, df_coef, used_features
def train_lasso_fixed_lambda_then_non_negative_lr(self, df_train, feature_columns):
"""
Train `LassoFixedLambdaThenNNLR` (formerly empWtDropNegLasso) -
First do feature selection using lasso regression and positive only weights.
Then fit an NNLR (see above) on those features.
Parameters
----------
df_train : pd.DataFrame
Data frame containing the features on which
to train the model.
feature_columns : list
A list of feature columns to use in training the model.
Returns
-------
learner : skll.Learner
The SKLL learner object
fit : statsmodels.RegressionResults
A statsmodels regression results object.
df_coef : pd.DataFrame
The model coefficients in a data_frame
used_features : list
A list of features used in the final model.
"""
# train a Lasso Regression model with a preset lambda
p_lambda = sqrt(len(df_train) * log10(len(feature_columns)))
# create a SKLL FeatureSet instance from the given data frame
fs_train = FeatureSet.from_data_frame(df_train[feature_columns + ['sc1']],
'train',
labels_column='sc1')
# note that 'alpha' in sklearn is different from this lambda
# so we need to normalize looking at the sklearn objective equation
p_alpha = p_lambda / len(df_train)
l_lasso = Learner('Lasso', model_kwargs={'alpha': p_alpha, 'positive': True})
l_lasso.train(fs_train, grid_search=False)
# get the feature names that have the non-zero coefficients
non_zero_features = list(l_lasso.model_params[0].keys())
# now train an NNLS regression using these non-zero features
# first add an intercept to the features manually
X = df_train[feature_columns].values
intercepts = np.ones((len(df_train), 1))
X_plus_intercept = np.concatenate([intercepts, X], axis=1)
y = df_train['sc1'].values
# fit an NNLS model on this data
coefs, rnorm = nnls(X_plus_intercept, y)
# check whether the intercept is set to 0 and if so then we need
# to flip the sign and refit the model to ensure that it is always
# kept in the model
if coefs[0] == 0:
intercepts = -1 * np.ones((len(df_train), 1))
X_plus_intercept = np.concatenate([intercepts, X], axis=1)
coefs, rnorm = nnls(X_plus_intercept, y)
# separate the intercept and feature coefficients
# even though we do not use intercept in the code
# we define it here for readability
# intercept = coefs[0]
coefficients = coefs[1:].tolist()
# get the non-zero features from this model
non_zero_features = []
for feature, coefficient in zip(feature_columns, coefficients):
if coefficient != 0:
non_zero_features.append(feature)
# now train a new linear regression with just these non-zero features
X = df_train[non_zero_features]
X = sm.add_constant(X)
fit = sm.OLS(df_train['sc1'], X).fit()
# convert this model's parameters into a data frame
df_coef = self.ols_coefficients_to_dataframe(fit.params)
# create fake SKLL learner with these coefficients
learner = self.create_fake_skll_learner(df_coef)
# we used only the positive features
used_features = non_zero_features
return learner, fit, df_coef, used_features
def train_lasso_fixed_lambda(self, df_train, feature_columns):
"""
Train `LassoFixedLambda` (formerly lassoWtLasso) -
A Lasso model with a fixed lambda
Parameters
----------
df_train : pd.DataFrame
Data frame containing the features on which
to train the model.
feature_columns : list
A list of feature columns to use in training the model.
Returns
-------
learner : skll.Learner
The SKLL learner object
fit : statsmodels.RegressionResults
A statsmodels regression results object or None.
df_coef : pd.DataFrame
The model coefficients in a data_frame
used_features : list
A list of features used in the final model.
"""
# train a Lasso Regression model with a preset lambda
p_lambda = sqrt(len(df_train) * log10(len(feature_columns)))
# create a SKLL FeatureSet instance from the given data frame
fs_train = FeatureSet.from_data_frame(df_train[feature_columns + ['sc1']],
'train',
labels_column='sc1')
# note that 'alpha' in sklearn is different from this lambda
# so we need to normalize looking at the sklearn objective equation
alpha = p_lambda / len(df_train)
learner = Learner('Lasso', model_kwargs={'alpha': alpha, 'positive': True})
learner.train(fs_train, grid_search=False)
# convert this model's parameters to a data frame
df_coef = self.skll_learner_params_to_dataframe(learner)
# there's no OLS fit object in this case
fit = None
# we used all the features
used_features = feature_columns
return learner, fit, df_coef, used_features
def train_positive_lasso_cv(self, df_train, feature_columns):
"""
Train `PositiveLassoCV` (formerly lassoWtLassoBest) -
Feature selection using lasso regression optimized for log likelihood
using cross validation.
Parameters
----------
df_train : pd.DataFrame
Data frame containing the features on which
to train the model.
feature_columns : list
A list of feature columns to use in training the model.
Returns
-------
learner : skll.Learner
The SKLL learner object
fit : statsmodels.RegressionResults
A statsmodels regression results object or None.
df_coef : pd.DataFrame
The model coefficients in a data_frame
used_features : list
A list of features used in the final model.
"""
# train a LassoCV outside of SKLL since it's not exposed there
X = df_train[feature_columns].values
y = df_train['sc1'].values
clf = LassoCV(cv=10, positive=True, random_state=1234567890)
model = clf.fit(X, y)
# save the non-zero model coefficients and intercept to a data frame
non_zero_features, non_zero_feature_values = [], []
for feature, coefficient in zip(feature_columns, model.coef_):
if coefficient != 0:
non_zero_features.append(feature)
non_zero_feature_values.append(coefficient)
# initialize the coefficient data frame with just the intercept
df_coef = pd.DataFrame([('Intercept', model.intercept_)])
df_coef = df_coef.append(list(zip(non_zero_features,
non_zero_feature_values)), ignore_index=True)
df_coef.columns = ['feature', 'coefficient']
# create a fake SKLL learner with these non-zero weights
learner = self.create_fake_skll_learner(df_coef)
# there's no OLS fit object in this case
fit = None
# we used only the non-zero features
used_features = non_zero_features
return learner, fit, df_coef, used_features
def train_score_weighted_lr(self, df_train, feature_columns):
"""
Train `ScoreWeightedLR` -
Linear regression model weighted by score.
Parameters
----------
df_train : pd.DataFrame
Data frame containing the features on which
to train the model.
feature_columns : list
A list of feature columns to use in training the model.
Returns
-------
learner : skll.Learner
The SKLL learner object
fit : statsmodels.RegressionResults
A statsmodels regression results object or None.
df_coef : pd.DataFrame
The model coefficients in a data_frame
used_features : list
A list of features used in the final model.
"""
# train weighted least squares regression
# get the feature columns
X = df_train[feature_columns]
# add the intercept
X = sm.add_constant(X)
# define the weights as inverse proportion of total
# number of data points for each score
score_level_dict = df_train['sc1'].value_counts()
expected_proportion = 1 / len(score_level_dict)
score_weights_dict = {sc1: expected_proportion / count
for sc1, count in score_level_dict.items()}
weights = [score_weights_dict[sc1] for sc1 in df_train['sc1']]
# fit the model
fit = sm.WLS(df_train['sc1'], X, weights=weights).fit()
df_coef = self.ols_coefficients_to_dataframe(fit.params)
learner = self.create_fake_skll_learner(df_coef)
# we used all the features
used_features = feature_columns
return learner, fit, df_coef, used_features
def train_builtin_model(self,
model_name,
df_train,
experiment_id,
filedir,
figdir,
file_format='csv'):
"""
Train one of the :ref:`built-in linear regression models <builtin_models>`.
Parameters
----------
model_name : str
Name of the built-in model to train.
df_train : pandas DataFrame
Data frame containing the features on which
to train the model. The data frame must contain the ID column named
`spkitemid` and the numeric label column named `sc1`.
experiment_id : str
The experiment ID.
filedir : str
Path to the `output` experiment output directory.
figdir : str
Path to the `figure` experiment output directory.
file_format : {'csv', 'tsv', 'xlsx'}, optional
The format in which to save files.
Defaults to 'csv'.
Returns
-------
learner : `Learner` object
SKLL `LinearRegression` `Learner <https://skll.readthedocs.io/en/latest/api/learner.html#skll.learner.Learner`_ object containing
the coefficients learned by training the built-in model.
"""
# get the columns that actually contain the feature values
feature_columns = [c for c in df_train.columns if c not in ['spkitemid', 'sc1']]
# LinearRegression
if model_name == 'LinearRegression':
result = self.train_linear_regression(df_train, feature_columns)
# EqualWeightsLR
elif model_name == 'EqualWeightsLR':
result = self.train_equal_weights_lr(df_train, feature_columns)
# RebalancedLR
elif model_name == 'RebalancedLR':
result = self.train_rebalanced_lr(df_train, feature_columns)
# LassoFixedLambdaThenLR
elif model_name == 'LassoFixedLambdaThenLR':
result = self.train_lasso_fixed_lambda_then_lr(df_train, feature_columns)
# PositiveLassoCVThenLR
elif model_name == 'PositiveLassoCVThenLR':
result = self.train_positive_lasso_cv_then_lr(df_train, feature_columns)
# NNLR
elif model_name == 'NNLR':
result = self.train_non_negative_lr(df_train, feature_columns)
# NNLRIterative
elif model_name == 'NNLRIterative':
result = self.train_non_negative_lr_iterative(df_train, feature_columns)
# LassoFixedLambdaThenNNLR
elif model_name == 'LassoFixedLambdaThenNNLR':
result = self.train_lasso_fixed_lambda_then_non_negative_lr(df_train, feature_columns)
# LassoFixedLambda
elif model_name == 'LassoFixedLambda':