【问题标题】:How to tell a SciKit LinearRegression model that a predicted value cannot be less than Zero?如何告诉 SciKit 线性回归模型预测值不能小于零?
【发布时间】:2020-09-13 23:31:49
【问题描述】:

我有以下代码,它试图根据非价格特征评估股票。

price = df.loc[:,'regularMarketPrice']
features = df.loc[:,feature_list]

# 
X_train, X_test, y_train, y_test = train_test_split(features, price, test_size = 0.15, random_state = 1)

if len(X_train.shape) < 2:
    X_train = np.array(X_train).reshape(-1,1)
    X_test = np.array(X_test).reshape(-1,1)

# 
model = LinearRegression()
model.fit(X_train,y_train)

# 
print('Train Score:', model.score(X_train,y_train))
print('Test Score:', model.score(X_test,y_test))


# 
y_predicted = model.predict(X_test)

在我的df(非常大)中,从来没有'regularMarketPrice'小于0的实例。但是,对于y_predicted中的某些点,我偶尔会收到小于0的值。

Scikit 中有没有办法说任何小于 0 的东西都是无效的预测?我希望这能让我的模型更准确。

如果需要进一步解释,请发表评论。

【问题讨论】:

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


    【解决方案1】:

    考虑使用非高斯响应变量。用直方图绘制 y 值。如果数据正确偏斜,请考虑使用 glm、伽马分布和日志链接进行建模。

    或者,您可以将 y_predicted 设置为 model.score 值的最大值和 0。

    【讨论】:

      【解决方案2】:

      要使更多预测大于 0,您不应使用线性回归。您应该考虑广义线性回归 (glm),例如泊松回归。

      from sklearn.linear_model import PoissonRegressor
      
      price = df.loc[:,'regularMarketPrice']
      features = df.loc[:,feature_list]
      
      # 
      X_train, X_test, y_train, y_test = train_test_split(features, price, test_size = 0.15, random_state = 1)
      
      if len(X_train.shape) < 2:
          X_train = np.array(X_train).reshape(-1,1)
          X_test = np.array(X_test).reshape(-1,1)
      
      # 
      model = PoissonRegressor()
      model.fit(X_train,y_train)
      
      # 
      print('Train Score:', model.score(X_train,y_train))
      print('Test Score:', model.score(X_test,y_test))
      
      
      # 
      y_predicted = model.predict(X_test)
      

      所有预测都大于等于0

      【讨论】:

      • 这解决了我的问题。但是,对于阅读本文的任何人,PossionRegressor 在低于 0.23(2020 年 5 月 12 日)的任何 scikit 版本中均不可用。所以请确保你的 Scikit 是最新的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 2020-04-05
      • 2017-11-30
      • 2021-01-15
      • 2021-02-25
      相关资源
      最近更新 更多