Skip to content

Commit 9d8a411

Browse files
authored
Merge pull request #7 from mckenziephagen/pr_model
Pr model
2 parents 00cf616 + eec1d40 commit 9d8a411

File tree

3 files changed

+39
-21
lines changed

3 files changed

+39
-21
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
*ipynb*
2+
*cache*
3+
*egg*

src/model_fc/models.py

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,20 @@
1414
def run_model(train_ts, test_ts, n_rois, model, **kwargs):
1515
"""Calculate a model based functional connectivity matrix.
1616
17-
1817
train_ts: training timeseries
1918
test_ts: testing timeseries
2019
n_rois: number of rois in parcellation
2120
model: model object
2221
23-
2422
"""
2523
assert train_ts.shape[1] == n_rois == test_ts.shape[1]
26-
fc_mat = np.zeros((n_rois, n_rois))
24+
fc_mat = np.empty((n_rois, n_rois))
2725

28-
inner_rsq_dict = {"train": [], "test": []}
26+
results_dict = {}
2927

3028
for target_idx in range(train_ts.shape[1]):
29+
results_dict[f"node_{target_idx}"] = {}
30+
print(f"*****ECHO {target_idx}***********")
3131
y_train = np.array(train_ts[:, target_idx])
3232
X_train = np.delete(train_ts, target_idx, axis=1)
3333

@@ -36,13 +36,15 @@ def run_model(train_ts, test_ts, n_rois, model, **kwargs):
3636

3737
model.fit(X=X_train, y=y_train)
3838

39-
fc_mat[target_idx, :] = np.insert(model.coef_, target_idx, 0)
39+
fc_mat[target_idx, :] = np.insert(model.coef_, target_idx, 1)
4040
test_rsq, train_rsq = eval_metrics(X_train, y_train, X_test, y_test, model)
4141

42-
inner_rsq_dict["test"].append(test_rsq)
43-
inner_rsq_dict["train"].append(train_rsq)
42+
results_dict[f"node_{target_idx}"]["train_r2"] = train_rsq
43+
results_dict[f"node_{target_idx}"]["test_r2"] = test_rsq
44+
45+
results_dict["fc_matrix"] = fc_mat
4446

45-
return (fc_mat, inner_rsq_dict, model)
47+
return results_dict
4648

4749

4850
def eval_metrics(X_train, y_train, X_test, y_test, model):
@@ -58,25 +60,19 @@ def init_model(
5860
model_str, max_iter, random_state, stability_selection=16, selection_frac=0.7
5961
):
6062
"""Initialize model object for FC calculations."""
61-
if model_str == "uoi-lasso":
63+
if model_str == "uoiLasso":
6264
uoi_lasso = UoI_Lasso(estimation_score="BIC")
63-
comm = MPI.COMM_WORLD
64-
6565
uoi_lasso.selection_frac = selection_frac
6666
uoi_lasso.stability_selection = stability_selection
6767
uoi_lasso.copy_X = True
6868
uoi_lasso.estimation_target = None
6969
uoi_lasso.logger = None
70-
uoi_lasso.warm_start = False
71-
uoi_lasso.comm = comm
72-
uoi_lasso.random_state = 1
70+
uoi_lasso.warm_start = True
7371
uoi_lasso.n_lambdas = 100
7472
uoi_lasso.max_iter = max_iter
75-
uoi_lasso.random_state = random_state
76-
7773
model = uoi_lasso
7874

79-
elif model_str == "lasso-cv":
75+
elif model_str == "lassoCV":
8076
lasso = LassoCV(
8177
fit_intercept=True,
8278
cv=5,
@@ -86,8 +82,12 @@ def init_model(
8682
)
8783

8884
model = lasso
85+
elif model_str == "ridgeCV":
86+
ridge = RidgeCV(fit_intercept=True)
87+
88+
model = ridge
8989

90-
elif model_str == "lasso-bic":
90+
elif model_str == "lassoBIC":
9191
lasso = LassoLarsIC(criterion="bic", fit_intercept=True, max_iter=max_iter)
9292

9393
model = lasso
@@ -119,10 +119,10 @@ def fit(self, X, y):
119119

120120
# Calculate the Pearson coefficient between y and every column of x
121121
corrmatrix = np.corrcoef(np.concatenate([X, y[:, None]], -1).T)
122-
self.coeff_ = corrmatrix[-1, :-1]
122+
self.coef_ = corrmatrix[-1, :-1]
123123
# Calculate the linear combination of columns of X with these
124124
# coefficients
125-
naive_pred_y = X @ self.coeff_
125+
naive_pred_y = X @ self.coef_
126126
# Calculate the scale parameter to match the variance of y
127127
self.scale_ = np.mean(y / naive_pred_y)
128128
self.is_fitted_ = True
@@ -132,4 +132,4 @@ def fit(self, X, y):
132132
def predict(self, X):
133133
check_is_fitted(self)
134134
X = validate_data(self, X, reset=False)
135-
return (X @ self.coeff_) / self.scale_
135+
return X @ self.coef_ * self.scale_

test/test_models.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import math
2+
13
import numpy as np
24
from model_fc.models import PearsonRegressor
35
from sklearn.utils.estimator_checks import parametrize_with_checks
@@ -16,3 +18,16 @@ def test_PearsonRegressor():
1618
pr.fit(X, y)
1719
pred = pr.predict(X)
1820
assert pred.shape == y.shape
21+
22+
23+
def test_PearsonRegressorScale():
24+
y = np.random.randn(100)
25+
X = np.zeros((100, 10))
26+
for col in range(X.shape[1]):
27+
# no noise so that our scaling == 1 exactly
28+
X[:, col] = y
29+
30+
pr = PearsonRegressor()
31+
pr.fit(X, y)
32+
# assert scale is 1/ncols
33+
assert math.isclose(pr.scale_, 0.1)

0 commit comments

Comments
 (0)