Python 中的简单线性回归问题

Simple Linear Regression issue in Python

我有这个数据:

我正在尝试对其进行简单的线性回归模型。

这是我的代码:

from sklearn.linear_model import LinearRegression

X = df[['Date']] 
y = df['ACP Cleaning'] 

model = LinearRegression()
model.fit(X, y)

X_predict = [['2021-1-1']]
y_predict = model.predict(X_predict)

这是我的错误:

ValueError: Unable to convert array of bytes/strings into decimal numbers with dtype='numeric'

线性回归适用于数字,而非字符串。

您必须预处理数据以匹配模型的输入。

一种方法是解析字符串并将其转换为时间戳:

import datetime

def process_date(date_str):
  d = datetime.datetime.strptime(date_str, '%Y-%m-%d')
  return d.timestamp()

X = df[['Date']].apply(process_date)

必须对您要预测的数据执行相同的操作。

更新: 如果您的数据集的数据类型正确,则问题出在您尝试用于预测的数据上(您无法预测字符串)。

以下是一个完整的工作示例。请密切注意对 X_predict 变量所做的处理。

import datetime
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression

rng = pd.date_range('2015-02-24', periods=5, freq='3A')
df = pd.DataFrame({ 'Date': rng, 'Val' : np.random.randn(len(rng))})
print(df.head())

X = np.array(df['Date']).reshape(-1,1)
y = df['Val']

model = LinearRegression()
model.fit(X, y)

def process_date(date_str):
  d = datetime.datetime.strptime(date_str, '%Y-%m-%d')
  # return array
  return [d.timestamp()]


X_predict = ['2021-1-1']
X_predict = list(map(process_date, X_predict))
y_predict = model.predict(X_predict)
y_predict

Returns:

        Date       Val
0 2015-12-31 -0.110503
1 2018-12-31 -0.621394
2 2021-12-31 -1.030068
3 2024-12-31  1.221146
4 2027-12-31 -0.327685

array([-2.6149628])

更新:我用你的数据创建了一个csv文件:

Date,Val
1-1-2020, 90404.71
2-1-2020, 69904.71
...

然后我加载了 pandas。我觉得一切都很好:

def process_date(date_str):
  # the date format is month-day-year
  d = datetime.datetime.strptime(date_str, '%m-%d-%Y')
  return d.timestamp()

df = pd.read_csv("test.csv")
df['Date'] = df['Date'].apply(process_date)
df.head()

输出:

Date    Val
0   1.577848e+09    90404.710
1   1.580526e+09    69904.710
2   1.583032e+09    98934.112
3   1.585710e+09    77084.430
4   1.588302e+09    35877.420

提取特征:

# must reshape 'cause we have only one feature
X = df['Date'].to_numpy().reshape(-1,1)
y = df['Val'].to_numpy()
model = LinearRegression()
model.fit(X, y)

预测:

X_predict = ['1-1-2021', '2-1-2021']
X_predict = np.array(list(map(process_date, X_predict)))
X_predict = X_predict.reshape(-1, 1)
y_predict = model.predict(X_predict)
y_predict

输出:

array([55492.2660361 , 53516.12292932])

这是一个很好的预测。您可以使用 matplotlib 绘制数据并说服自己:

import matplotlib.pyplot as plt
%matplotlib inline

plt.plot(df['Date'], df['Val'])
plt.show()

线性回归需要您的数组为数字类型,因为您的日期在 X 数组中存储为字符串,线性回归将无法按预期工作。

您可以通过计算从开始日期算起的天数,将X数组转换为数值类型。你可以在你的 DataFrame 中尝试这样的事情:

df.Date = (df.Date -  df.Date[0]).days

然后你就可以继续之前的操作了。

我假设你的 Date 列中的日期是 datetime 格式,否则你需要先转换它。