【问题标题】:Is it normal when you get different coefficients everytime your run your LR model code?每次运行 LR 模型代码时获得不同的系数是否正常?
【发布时间】:2022-07-22 21:47:21
【问题描述】:
#REGRESSION ANALYSIS
#splitting the dataset into x and y variables
firm1=pd.DataFrame(firm, columns=[\'Sales\', \'Advert\', \'Empl\', \'Prod\'])
print(firm1)
x = firm1.drop([\'Sales\'], axis=1)
y = firm1[\'Sales\']
print(x)
print(y)
x_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.2)
print(x_train.shape, y_train.shape)
print(x_test.shape, y_test.shape)

#the LR model
M=linear_model.LinearRegression(fit_intercept=True)
M.fit(x_train, y_train)
y_pred=M.predict(x_test)
print(y_pred)
print(\'Coeff: \', M.coef_)
for i in M.coef_:
    print(\'{:.4f}\'.format(i))

print(\'Intercept: \',\'{:.4f}\'.format(M.intercept_))
print(\'MSE: \',\'{:.4f}\'.format(mean_squared_error(y_test, y_pred)))
print(\'Coeffieicnt of determination (r2): \',\'{:.4f}\'.format(r2_score(y_test, y_pred)))
print(firm1.sample())

这是我的线性回归模型。每次我运行代码时,我都会为 x 变量和截距发送不同的系数。我不能有一个常数方程。这正常吗?

科夫:[454.83981664 63.77031531 59.31844506] 454.8398 63.7703 59.3184 拦截:-1073.5124 MSE: 434529.9361

这些是值(系数、截距和均方误差)。但是,当我再次运行它时,我得到如下所示的不同输出

科夫:[462.0304152 61.17909189 269.41075305] 462.0304 61.1791 269.4108 拦截:-1462.2449 MSE:4014768.0049

  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。
  • 我已编辑。请检查一下您现在是否可以理解。谢谢

标签: python machine-learning scikit-learn linear-regression


【解决方案1】:

在线性回归的每次训练中获得不同的系数是正常的。实际上,最初是随机设置系数,然后使用the least squares method 逐步更新。如果您希望每次训练具有相同的系数,您可以使用以下方式设置种子:

numpy.random.seed(42)

【讨论】:

    猜你喜欢
    • 2017-10-20
    • 2016-07-31
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多