绘制一个简单的线性回归模型出错

Plotting a simple linear regression model goes wrong

我想创建一个线性回归模型,显示 BMI 和疾病风险(基线后一年疾病的定量测量)之间的正相关关系。

该数据集与sklearn数据集中的数据集相同-- import sklearn.datasets.load_diabetes

这是 URL (https://www4.stat.ncsu.edu/~boos/var.select/diabetes.tab.txt)

我使用 read_csv(args) 导入了整个 table 并将其命名为 'data'

df = DataFrame({'BMI': data['BMI'], 'Target': data['Y']}).sort_values('BMI')

df.plot.scatter('BMI', 'Target')

model = LinearRegression(fit_intercept=True)
model.fit(data[['BMI']], data['Y'])

x_test = np.linspace(data['BMI'].min(), data['BMI'].max())
y_pred = model.predict(x_test[:, np.newaxis])

df.plot(x_test, y_pred, linestyle=":", color="red")

当我尝试这个时,它给了我一个我不明白的大错误信息,为什么会这样?

我想你想要的是:

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

[...]

df = pd.DataFrame({'BMI': data['BMI'], 'Target': data['Y']}).sort_values('BMI')

model = LinearRegression(fit_intercept=True)
model.fit(data[['BMI']], data['Y'])

x_test = np.linspace(data['BMI'].min(), data['BMI'].max())
y_pred = model.predict(x_test[:, np.newaxis])

plt.scatter(df['BMI'].values, df['Target'].values)
plt.plot(x_test, y_pred, linestyle="-", color="red")
plt.show()

这给了我们:

您使用 df.plot(x, y) 的解决方案给您错误,因为这个 plot function of the pandas dataframe only works on the dataframe it is called on. It's no general plot function like the pyplot.plot(x, y) plot 函数。