【问题标题】:Simple Linear Regression using Sklearn. Fit() is not working使用 Sklearn 的简单线性回归。适合()不工作
【发布时间】:2020-07-27 14:45:12
【问题描述】:

我正在使用这个数据集: https://filebin.net/wr2jy0ass7rsl0vt 共有三列:“日期”、“温度”、“异常”。我使用“日期”来预测“温度”。代码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

data_df = pd.read_csv("ave_yearly_temp_nyc_1895-2017.csv")


data_df.columns=  ["Date","Temperature","Anomaly"]

data_df["Date"] = data_df["Date"]//100

regressor = LinearRegression()

X_train,X_test, y_train,y_test = train_test_split(data_df.iloc[:,0],data_df.iloc[:,1],test_size=0.2, random_state=0)


regressor.fit(X_train,y_train) #training the algorithm

data_df:

错误:

如何解决?

【问题讨论】:

    标签: python python-3.x machine-learning scikit-learn linear-regression


    【解决方案1】:

    它需要一个二维数组,使用iloc[:,0] 你得到一个一维数组。 相反,您可以使用整个数据框列作为参数。 尝试使用:

    X_train,X_test, y_train,y_test = train_test_split(data_df['Date'],data_df['Temperature'],test_size=0.2, random_state=0)
    

    【讨论】:

    • 我尝试在 regressor.fit(X_train,y_train) 内部重塑。可能吗?怎么办?
    • 您可以使用 np.array(X_train).reshape(-1,1) 进行整形,但是您需要对使用 train_test_split 创建的 4 个数组中的每一个进行整形。在我看来,使用 DataFrame 列作为参数可以让你的代码更简洁。
    【解决方案2】:

    尝试按照错误消息告诉您的操作。似乎实现期望 X 包含不止一个特性。因此,您需要像这样对其进行转换:

    X_train, X_test, y_train, y_test = train_test_split(np.array(data_df.iloc[:,0]).reshape(-1, 1),data_df.iloc[:,1],test_size=0.2, random_state=0)
    

    【讨论】:

    • 我尝试在 regressor.fit(X_train,y_train) 内部重塑。可能吗?怎么办?
    猜你喜欢
    • 2016-12-03
    • 2019-01-19
    • 1970-01-01
    • 2020-04-09
    • 2018-05-16
    • 2021-02-04
    • 2019-03-26
    • 2018-12-13
    相关资源
    最近更新 更多