【问题标题】:Linear Regression's coefficient and intercept kept changing线性回归的系数和截距不断变化
【发布时间】:2022-08-06 23:23:29
【问题描述】:
bach_sal = bach[\'Salary\']
masters_sal = masters[\'Salary\']
phd_sal = phd[\'Salary\']
deg_category_sal = [assoc_sal, bach_sal, masters_sal, phd_sal]

x = np.array(assoc[\'Person\'])
y = np.array(assoc_sal)
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.7)
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
lr.fit(x_train.reshape(-1,1),y_train)
print (lr.coef_)
print (lr.intercept_)

我收到了系数和 y 截距,但每次运行代码时,它们都会更改为不同的数字。请帮忙。谢谢你。

  • 也许您可以尝试为您的代码/在哪里执行 train_test_split 设置一个随机种子。该方法随机选择您的数据的 %,因此它会在运行之间发生变化\\

标签: python machine-learning scikit-learn statistics data-science


【解决方案1】:

这是因为您没有在 train_test 拆分函数中设置 random_state。这会在每次运行时对测试数据的切割进行洗牌,因此,系数会略有变化。 将 random_state 设置为整数以在多次运行中获得相同的答案。

https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html

【讨论】:

    【解决方案2】:

    这将不断变化,直到您为您的火车测试行号指定一个固定的 random_state 值。

    x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.3, random_state=42)
    

    进行此更改后,您可能会得到完全相同的值。通常,您的训练和测试数据将不断变化,直到您指定用于训练和测试的集合行。

    【讨论】:

      猜你喜欢
      • 2020-08-18
      • 1970-01-01
      • 2022-01-09
      • 2018-02-21
      • 1970-01-01
      • 2019-05-27
      • 2016-08-31
      • 2018-06-11
      • 2020-10-28
      相关资源
      最近更新 更多