【问题标题】:how to run the same linear model n times?如何运行相同的线性模型 n 次?
【发布时间】:2021-03-19 03:05:11
【问题描述】:

我使用基于 Cement and Concrete Composites 数据集的 sklearn 构建了一个线性模型。

最初,我使用train_test_split(X, Y, test_size=0.3, Shuffle=False),发现训练和测试错误。

现在我尝试使用Shuffle=True 运行同一模型 10 次,并计算错误的均值和标准差。应该将新结果与第一个结果进行比较。

我怎样才能循环同一个模型 n 次并将错误保存在一个列表中?

【问题讨论】:

    标签: python scikit-learn linear-regression


    【解决方案1】:

    您需要的是交叉验证:在相同数据的不同拆分上重复评估模型。在这种情况下,train_test_split 是 ShuffleSplit 交叉验证的包装器。

    在您的情况下,它可能如下所示:

    from sklearn.model_selection import ShuffleSplit, cross_val_score
    import numpy as np
    from sklearn.linear_model import LinearRegression
    
    X, y = ... # read dataset
    
    model = LinearRegression()
    
    # n_splits=10 is for 10 random shuffled train-test splits
    cv = ShuffleSplit(n_splits=10, test_size=.3, random_state=0)
    
    scores = cross_val_score(model, X, y, cv=cv, scoring='neg_mean_squared_error')
    np.mean(scores), np.std(scores) 
    

    如果您想自己计算错误或对模型/结果做任何其他事情,您可以这样做:

    for train_ids, test_ids in cv.split(X):
        model.fit(X[train_ids], y[train_ids])
        model.score(X[test_ids], y[test_ids])
        ...
    

    更多信息: https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.ShuffleSplit.html

    【讨论】:

      【解决方案2】:

      试试这样的:

      from sklearn.metrics import accuracy_score
      from sklearn.linear_model import LinearRegression 
      
      errors = []
      for i in range(10):
          X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, Shuffle=True)
          model = LinearRegression() # the model you want to use here
          model.fit(X_train, y_train)
          y_pred = model.predict(X_test)
          error = accuracy_score(y_test, y_pred) # the error metric you want to use here
          errors.append(error)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-21
        • 2018-07-12
        • 1970-01-01
        • 2014-04-21
        • 1970-01-01
        • 1970-01-01
        • 2020-09-03
        • 1970-01-01
        相关资源
        最近更新 更多