【问题标题】:Linear Regression of Filtered Data Set过滤数据集的线性回归
【发布时间】:2020-05-19 01:29:38
【问题描述】:

在最终计算出我的数据集并能够绘制它之后,我一直在尝试使用线性回归来拟合曲线。我尝试了一些方法,但都没有给我任何结果,我认为这是由于我的数据是如何被过滤的。这是我的代码:

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, 0)

US = df.loc[df['location'] == 'United States']


plt.plot_date(US['date'],US['new_deaths'], 'blue', label = 'US', linewidth = 5)
#plt.plot_date(US['date'],US['total_deaths'], 'red', label = 'US', linewidth = 5)

#linear_regressor = LinearRegression()  # create object for the class
#linear_regressor.fit(US['date'], US['new_deaths'])  # perform linear regression
#Y_pred = linear_regressor.predict(X)  # make predictions

#m , b = np.polyfit(x = US['date'], y = US['new_deaths'], deg = 1)






plt.title('New Deaths per Day In US')
plt.xlabel('Time')
plt.ylabel('New Deaths')
plt.legend()
plt.grid()
plt.show()


我知道这个问题已经问了数千次了,所以如果那里有我没有遇到的帖子,请给我链接。谢谢你们! :D

【问题讨论】:

  • 当你说none have given me any results时,你是什么意思?我认为最好分享您的经验和结果。目前,还不清楚您的问题是什么。
  • 我尝试了几种方法在这里找到:1)scipy-lectures.org/packages/scikit-learn/auto_examples/…,2)stackoverflow.com/questions/6148207/…,3)towardsdatascience.com/…,但是当我尝试将我的数据集传递给线性回归函数时,我总是得到“TypeError: can only concatenate str (not "float") to str”。
  • 基本上,我如何才能获得适合我过滤数据集的方式的线性回归曲线? @alift
  • 您应该就您遇到的错误提出问题;这显然是关于在拟合 LR 之前将 str 特征转换为浮动。只需谷歌您的错误,第一个结果是 stackoverflow.com/questions/52796600/… ;这有帮助吗?
  • 是的,我尝试从 str 转换为 float,但由于我如何过滤数据,我不确定格式会是什么样子。不过同意,我的问题应该是关于如何格式化从 str 到 float 的转换。

标签: python pandas numpy matplotlib linear-regression


【解决方案1】:

使用 sklearn 的 LinearRegression,您可以这样做来拟合回归:

regr = LinearRegression()
regr.fit(US['date'].values.reshape(-1, 1), US['new_deaths'])

绘制它:

# plot the original points
plt.plt(US['date'], US['new_deaths'])

# plot the fitted line. To do so, first generate an input set containing
# only the max and min limits of the x range
trendline_x = np.array([US['date'].min(), US['date'].max()]).reshape(-1, 1)
# predict the y values of these two points
trendline_y = regr.predict(trendline_x)
# plot the trendline
plt.plot(trendline_x, trendline_y)

如果您只追求视觉效果,Seaborn 的 lmplot 是一个方便且美观的替代品。

【讨论】:

  • 我收到来自regr.fit(US['date'], US['new_deaths']) 的错误消息“无法将字符串转换为浮点数:'2019-12-31'”@xcmkz
  • 好的,您需要将日期从字符串转换为日期的实际连续表示,例如datetime。为此:使用pd.to_datetime(US['date']) 而不是US['date']
  • 我还更新了答案中的regr.fit 行——我忘记了 X 矩阵必须是形状 (N, k),其中 k 是特征数。换句话说,输入的形状应该是 (N, 1) 而不是 (N,)。对不起
  • 知道了,谢谢!我收到错误消息:“ValueError:无法将字符串转换为浮点数:'2019-12-31'”仍然会做更多的研究。一旦我的值被转换为浮点数,看起来你的代码应该可以工作了。
猜你喜欢
  • 2013-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-04
  • 2013-11-06
  • 1970-01-01
  • 2016-05-18
  • 2014-05-05
相关资源
最近更新 更多