使用sklearn Boston房屋数据集:尝试为系数创建数据帧

2024-04-23 07:12:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我运行了以下几行代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

from sklearn.datasets import load_boston
boston = load_boston()
print(boston.data.shape) 

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

x = pd.DataFrame(boston.data)
x.columns = boston.feature_names
y=pd.DataFrame(boston.target)
y.columns=['TARGET']

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3,  random_state=101)

model = LinearRegression()

model.fit(x_train,y_train)


print('Coefficients: \n', model.coef_)
len(model.coef_)

Coefficients: 
 [[-8.74917163e-02  5.02793747e-02  2.06785359e-02  3.75457604e+00
  -1.77933846e+01  3.24118660e+00  1.20902568e-02 -1.40965453e+00
   2.63476633e-01 -1.03376395e-02 -9.52633123e-01  6.20783942e-03
  -5.97955998e-01]]
1


coeffecients = pd.DataFrame(data=model.coef_,index=x.columns,columns=['Coefficient'])

错误消息: 传递值的形状是(13,1),索引表示(1,13)

我认为问题在于系数数组的长度是1。不过还不确定。在


Tags: columnsfromtestimportdataframedatamodelmatplotlib
1条回答
网友
1楼 · 发布于 2024-04-23 07:12:37

在我看来,这是因为你的y_train是一个具有形状的2d数据帧(n个示例,1)。在

coef_ : array, shape (n_features, ) or (n_targets, n_features)

Estimated coefficients for the linear regression problem. If multiple targets are passed during the fit (y 2D), this is a 2D array of shape (n_targets, n_features), while if only one target is passed, this is a 1D array of length n_features.

传递np.ravel(y_train)或者仅仅使用y = pd.Series(boston.target)可以解决这个问题。在

相关问题 更多 >