【发布时间】: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