【问题标题】:NotFittedError: This LinearRegression instance is not fitted yet. Call 'fit' with appropriate arguments before using this method [closed]NotFittedError:此 LinearRegression 实例尚未拟合。在使用此方法之前使用适当的参数调用“fit”[关闭]
【发布时间】:2020-05-19 03:01:17
【问题描述】:

我正在尝试使用线性回归来拟合曲线。到目前为止,这是我的代码:

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'”我不确定为什么会发生这种情况,因此非常感谢您的解释。谢谢!

【问题讨论】:

    标签: python pandas numpy matplotlib linear-regression


    【解决方案1】:

    请改用regr.fit()。将您的数据提供给它。

    【讨论】:

      猜你喜欢
      • 2020-04-14
      • 2019-12-13
      • 2022-11-07
      • 2019-10-05
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      • 2020-07-03
      相关资源
      最近更新 更多