python中时间序列的线性回归

Pro*_*man 5 python pandas scikit-learn

如何在线性回归图表上显示日期?

我的 csv 文件中的数据:

"date","bat"
"2020-05-13 00:00:00",84
"2020-05-14 00:00:00",83
"2020-05-15 00:00:00",81
"2020-05-16 00:00:00",81
Run Code Online (Sandbox Code Playgroud)

我能够使用线性规则生成图表。但不知道如何使 x 轴显示日期。

我的代码:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model

df = pd.read_csv('battery.csv', parse_dates=['date'])

x=np.array(pd.to_datetime(df['bat'].index.values, format='%Y-%m-%d'), dtype=float)
x=x.reshape(-1, 1)
y=np.array(df['bat'].values, dtype=float)

lm = linear_model.LinearRegression()
model = lm.fit(x,y)

predictions = lm.predict(x)

f, ax = plt.subplots(1, 1)
ax.plot(x, predictions,label='Linear fit', lw=3)
ax.scatter(x, y,label='value', marker='o', color='r')
plt.ylabel('bat')
ax.legend();

plt.show()
Run Code Online (Sandbox Code Playgroud)

Mik*_*zak 4

尝试这个:

df = pd.read_csv('battery.csv', parse_dates=['date'])

x=pd.to_datetime(df['date'], format='%Y-%m-%d')
y=df['bat'].values.reshape(-1, 1)

lm = linear_model.LinearRegression()
model = lm.fit(x.values.reshape(-1, 1),y)

predictions = lm.predict(x.values.astype(float).reshape(-1, 1))

f, ax = plt.subplots(1, 1)
ax.plot(x, predictions,label='Linear fit', lw=3)
ax.scatter(x, y,label='value', marker='o', color='r')
plt.ylabel('bat')
ax.legend();

plt.show()
Run Code Online (Sandbox Code Playgroud)