我正在尝试使用线性回归来拟合曲线。到目前为止,这是我的代码:
from matplotlib import pyplot as plt
import numpy as np
from pandas import DataFrame
from sklearn.linear_model import LinearRegression
from matplotlib.pyplot import figure
figure(num=None, figsize=(100, 100), dpi=100, facecolor='w', edgecolor='k')
plt.rc('font', size=100) # controls default text sizes
plt.rc('axes', titlesize=100) # fontsize of the axes title
plt.rc('axes', labelsize=100) # fontsize of the x and y labels
plt.rc('xtick', labelsize=30) # fontsize of the tick labels
plt.rc('ytick', labelsize=60) # fontsize of the tick labels
plt.rc('legend', fontsize=100) # legend fontsize
plt.rc('figure', titlesize=100)
plt.xticks(rotation=90)
ds = pd.read_csv("https://covid.ourworldindata.org/data/owid-covid-data.csv")
df = DataFrame(ds, columns = ['date', 'location', 'new_deaths', 'total_deaths'])
df = df.replace(np.nan, )
US = df.loc[df['location'] == 'United States']
plt.plot_date(US['date'],US['new_deaths'], 'blue', label = 'US', linewidth = 5)
pd.to_datetime(US['date'])
regr = LinearRegression()
trendline_x = np.array([US['date'].min(), US['date'].max()]).reshape(-1, 1)
plt.plot(US['date'], US['new_deaths'])
trendline_x = np.array([US['date'].min(), US['date'].max()]).reshape(-1, 1)
trendline_y = regr.predict(trendline_x)
plt.plot(trendline_x, trendline_y)
plt.title('New Deaths per Day In US')
plt.xlabel('Time')
plt.ylabel('New Deaths')
plt.legend()
plt.grid()
plt.show()
我曾尝试使用trendline_x.fit= np.array([US['date'].min(), US['date'].max()]).reshape(-1, 1)
,但收到错误“ AttributeError:'numpy.ndarray'对象没有属性'fit'”。我不确定为什么会这样,所以不胜枚举。谢谢!
改为使用regr.fit()
。向其中输入数据。
您应该使数据适合LinearRegression对象。
regr.fit(X_data,y_data)