简体   繁体   中英

How to create for loop to compare train and test score of linear regression models

I want to create loop to compare scores of machine learning model, but generate error "too many values to unpack (expected 2)". How to fix the problem?

from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
from sklearn.linear_model import ElasticNet
from sklearn.ensemble import GradientBoostingRegressor

names=[]
train_scores =[]
test_score =[]

models={'OLS': LinearRegression(),
       'Ridge': Ridge(),
       'Lasso': Lasso(),
       'ElasticN': ElasticNet(),
       'GBReg': GradientBoostingRegressor()}

for name, model in models:
    name_model = model
    name_fit = name_model.fit(X_train, y_train)
    name_pred = name_model.predict(X_test)
    name_train_score = name_model.score(X_train, y_train).round(4)
    name_test_score = name_model.score(X_test, y_test).round(4)
    names.append(name)
    train_scores.append(name_train_score)
    test_scores.append(name_test_score)

score_df = pd.DataFrame(names, train_scores, test_scores)
score_df

Hi this is because you are looping over a dict. A dictionary stores a key, value pair. If you would like to access both you can do so by adding .items() behind the dict.

for name, model in models.items():

For further reading, take a look at this !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM