gpt4 book ai didi

python - 如何从元素列表开始进行回归

转载 作者:行者123 更新时间:2023-12-01 08:42:00 25 4
gpt4 key购买 nike

我正在尝试在 python 中运行回归。我有一个列表列表(更大列表的一部分),看起来像这样:

[[1307622004, 0.0, 339.093, 130.132], 
[10562004, 0.0, 206.818, 62.111],
[127882004, 0.0, 994.624, 360.497],
[63702004, 0.0, 89.653, 19.103],
[655902004, 0.0, 199.613, 83.296],
[76482004, 0.0, 1891.0, 508.0],
[16332004, 0.0, 160.344, 25.446],
[294352004, 0.0, 67.115, 22.646],
[615922004, 0.0, 134.501, 41.01],
[1212572004, 0.0, 232.616, 5.086],
[658992004, 0.0, 189.155, 7.906],
[61962004, 0.0, 806.7, 164.1],
[121712004, 0.0, 1147.532, 271.014],
[1250142004, 0.0, 29.556, -5.721],
[148082004, 0.0, 22.05, -17.655]]

它看起来像这样,因为每一行都是我从中导入数据的 CSV 文件中的一行。从现在开始,请将列表中的元素视为变量列,以更好地理解我正在尝试进行回归的内容。例如,列表中的前 4 个列表看起来类似于转换为列(我不需要将变量转换为列,我这样做是为了说明目的):

1307622004     0.0    339.093    130.132
10562004 0.0 206.818 62.111
127882004 0.0 994.624 360.497

为了继续我的示例,我希望第一列是我的因变量,所有其他列都是自变量。我尝试使用 numpy 将列表转换为数组,然后应用 sklearn 回归。下面是代码片段:

重要注意事项: list_of_lists 包含许多与我在问题开头提供的列表类似的元素。

from sklearn import datasets ## imports datasets from scikit-learn
from sklearn.linear_model import LinearRegression
import numpy as np

for item in list_of_lists:
test_array = np.asarray(item)
# print(test_array)
X, Y = test_array[:, 0], test_array[:, 1]
mdl = LinearRegression().fit(X, Y)
scores = LinearRegression.score(X, Y)
print('--------------------------')

问题是我得到以下输出:

Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

我对 python 以及 python 中数组、矩阵的使用很陌生,所以我不太明白发生了什么。

最佳答案

我不太确定您为什么要迭代列表列表。更好的方法是将回归拟合到数组中。此外,如果您希望第一列作为响应(因)变量,其余所有作为预测(独立)变量,则需要更改 XY,因为正如您所拥有的,您将第一列作为预测变量,将第二列作为响应:

test_array = np.asarray(list_of_lists)
# Set independent variables to be all columns after first, dependent to first col
X, Y = test_array[:, 1:], test_array[:, 0]

# Create a regressor
reg = LinearRegression()
# Fit it to your data
mdl = reg.fit(X, Y)
# Exctract the R^2
scores = reg.score(X,Y)

关于python - 如何从元素列表开始进行回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53460099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com