如何根据数据集的所有特征绘制预测值
How to plot the predicted value against all features of a dataset
我想可视化波士顿数据集的数据点,并绘制线性回归平面。但是,我收到一个值错误。我正在使用合作社。下面是我的代码运行.
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
data1 = load_boston()
df1 = pd.DataFrame(data1.data)
df1.columns = data1.feature_names
df1['price']=data1.target
X = df1.iloc[:,0:13]
Y = df1.iloc[:,13]
xtrain,xtest,ytrain,ytest = train_test_split(X,Y,test_size = 0.2,random_state =0)
lin_reg = LinearRegression()
lin_reg.fit(xtrain,ytrain)
ypredict = lin_reg.predict(xtest)
plt.scatter(xtrain, ytrain, color = 'red')
plt.plot(xtrain, lin_reg.predict(xtrain), color = 'blue')
最后两行出现错误。
ValueError Traceback (most recent call last)
<ipython-input-54-4f89e0554222> in <module>()
----> 1 plt.scatter(xtrain, ytrain, color = 'red')
2 plt.plot(xtrain, lin_reg.predict(xtrain), color = 'blue')
3 frames
/usr/local/lib/python3.7/dist-packages/matplotlib/axes/_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, **kwargs)
4389 y = np.ma.ravel(y)
4390 if x.size != y.size:
-> 4391 raise ValueError("x and y must be the same size")
4392
4393 if s is None:
ValueError: x and y must be the same size
我知道 X 有 13 列,而 Y 有 1 列。这就是错误显示的原因。但是不知道怎么改。
有人可以帮忙吗?
- 必须单独绘制每个特征。
- 请记住,
'price'
是目标,因变量,lin_reg.predict(xtrain)
是训练数据的预测价格。
# predicted price from xtrain
ypred_train = lin_reg.predict(xtrain)
# create the figure
fig, axes = plt.subplots(ncols=4, nrows=4, figsize=(20, 20))
# flatten the axes to make it easier to index
axes = axes.flatten()
# iterate through the column values, and use i to index the axes
for i, v in enumerate(xtrain.columns):
# seclect the column to be plotted
data = xtrain[v]
# plot the actual price against the features
axes[i].scatter(x=data, y=ytrain, s=35, ec='white', label='actual')
# plot predicted prices against the features
axes[i].scatter(x=data, y=ypred_train, c='pink', s=20, ec='white', alpha=0.5, label='predicted')
# set the title and ylabel
axes[i].set(title=f'Feature: {v}', ylabel='price')
# set a single legend
axes[12].legend(title='Price', bbox_to_anchor=(1.05, 1), loc='upper left')
# delete the last 3 unused axes
for v in range(13, 16):
fig.delaxes(axes[v])
- 如果你把所有的东西都画成一个图,它会很拥挤而且毫无用处
- 您还可以通过将
df1
从宽格式融化为长格式,用 seaborn.relplot
绘制所有数据。
- 但是,将预测值添加到图形级图的顶部更加困难。
import seaborn as sns
dfm = df1.melt(id_vars='price', value_vars=df1.columns[:-1], var_name='Feature')
p = sns.relplot(kind='scatter', data=dfm, x='value', y='price', height=3,
col='Feature', col_wrap=4, facet_kws={'sharex': False})
我想可视化波士顿数据集的数据点,并绘制线性回归平面。但是,我收到一个值错误。我正在使用合作社。下面是我的代码运行.
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
data1 = load_boston()
df1 = pd.DataFrame(data1.data)
df1.columns = data1.feature_names
df1['price']=data1.target
X = df1.iloc[:,0:13]
Y = df1.iloc[:,13]
xtrain,xtest,ytrain,ytest = train_test_split(X,Y,test_size = 0.2,random_state =0)
lin_reg = LinearRegression()
lin_reg.fit(xtrain,ytrain)
ypredict = lin_reg.predict(xtest)
plt.scatter(xtrain, ytrain, color = 'red')
plt.plot(xtrain, lin_reg.predict(xtrain), color = 'blue')
最后两行出现错误。
ValueError Traceback (most recent call last)
<ipython-input-54-4f89e0554222> in <module>()
----> 1 plt.scatter(xtrain, ytrain, color = 'red')
2 plt.plot(xtrain, lin_reg.predict(xtrain), color = 'blue')
3 frames
/usr/local/lib/python3.7/dist-packages/matplotlib/axes/_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, **kwargs)
4389 y = np.ma.ravel(y)
4390 if x.size != y.size:
-> 4391 raise ValueError("x and y must be the same size")
4392
4393 if s is None:
ValueError: x and y must be the same size
我知道 X 有 13 列,而 Y 有 1 列。这就是错误显示的原因。但是不知道怎么改。
有人可以帮忙吗?
- 必须单独绘制每个特征。
- 请记住,
'price'
是目标,因变量,lin_reg.predict(xtrain)
是训练数据的预测价格。
# predicted price from xtrain
ypred_train = lin_reg.predict(xtrain)
# create the figure
fig, axes = plt.subplots(ncols=4, nrows=4, figsize=(20, 20))
# flatten the axes to make it easier to index
axes = axes.flatten()
# iterate through the column values, and use i to index the axes
for i, v in enumerate(xtrain.columns):
# seclect the column to be plotted
data = xtrain[v]
# plot the actual price against the features
axes[i].scatter(x=data, y=ytrain, s=35, ec='white', label='actual')
# plot predicted prices against the features
axes[i].scatter(x=data, y=ypred_train, c='pink', s=20, ec='white', alpha=0.5, label='predicted')
# set the title and ylabel
axes[i].set(title=f'Feature: {v}', ylabel='price')
# set a single legend
axes[12].legend(title='Price', bbox_to_anchor=(1.05, 1), loc='upper left')
# delete the last 3 unused axes
for v in range(13, 16):
fig.delaxes(axes[v])
- 如果你把所有的东西都画成一个图,它会很拥挤而且毫无用处
- 您还可以通过将
df1
从宽格式融化为长格式,用seaborn.relplot
绘制所有数据。- 但是,将预测值添加到图形级图的顶部更加困难。
import seaborn as sns
dfm = df1.melt(id_vars='price', value_vars=df1.columns[:-1], var_name='Feature')
p = sns.relplot(kind='scatter', data=dfm, x='value', y='price', height=3,
col='Feature', col_wrap=4, facet_kws={'sharex': False})