我正在尝试对一些数据进行线性回归。这就是数据的外观。
X = df['vectors']
看起来像这样:
0 [-1.86135, 1.3202, 0.023501, -2.9511, 1.62135,...1 [0.5487195, 0.27389452, 0.49712706, 0.6853927,...2 [-1.3525691, -0.8444542, 2.8269022, -1.4456564...3 [1.0730275, -0.14970247, -1.1424525, -1.953272...4 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ...
当我在其上运行线性回归模型时:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=101)lm = LinearRegression()lm.fit(X_train, y_train)
我得到了这个错误:
TypeError Traceback (most recent call last)TypeError: only size-1 arrays can be converted to Python scalarsThe above exception was the direct cause of the following exception:
我如何将X中的值转换为标量?我在考虑获取向量的平均值,但不确定具体该怎么做。
回答:
从外观上看,X
是一个 pandas.Series
对象。
由于X
中每一行的列表长度都相同,你可以将X
重塑为一个ndarray,其行数与X
相同,每个列表中的元素数量作为列数。
# 导入numpyimport numpy as np# 重塑X = np.array(X.explode()).reshape(len(X), -1)# 像之前一样进行X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=101)lm = LinearRegression()lm.fit(X_train, y_train)