【问题标题】:What is the best method to append to numpy array in for loop in Python? [closed]在 Python 的 for 循环中追加到 numpy 数组的最佳方法是什么? [关闭]
【发布时间】:2023-03-29 10:42:01
【问题描述】:

我为形状 (4,100) 创建了一个空白的 numpy 数组,我试图在 for 循环中为其分配/添加值,但我一直在获取原始数组。我尝试过使用连接和附加,但这似乎也不起作用。我希望输出一个形状为 (4,100) 的数组,其中包含所有预测值。

下面是我正在尝试做的代码

import pandas as pd
import numpy as np

from sklearn.model_selection import train_test_split



desired_width = 3000
pd.set_option('display.width',desired_width)
pd.set_option('display.max_columns',300)

from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

np.random.seed(0)
n = 15
x = np.linspace(0, 10, n) + np.random.randn(n) / 5
y = np.sin(x) + x / 6 + np.random.randn(n) / 10

degrees = [1, 3, 6, 9]
test_x = np.linspace(0,10,100).reshape(-1,1)

X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)
res = np.zeros((4,100), int)
for pos, degree in enumerate(degrees):
    poly = PolynomialFeatures(degree=degree)
    X_trans = poly.fit_transform(X_train.reshape(-1,1))
    lm = LinearRegression().fit(X_trans, y_train)
    print('goodness of fit is {}'.format(lm.score(poly.fit_transform(X_test.reshape(-1,1)),y_test)))
    test_x_poly = poly.fit_transform(test_x)
    y_predict = lm.predict(test_x_poly)
    print(y_predict.shape)
    print(y_predict.reshape(1,100).shape)
    res[pos,:] = y_predict.reshape(1,100)

【问题讨论】:

  • 嗨 Rajat,欢迎来到 Stack Overflow!请尝试create a minimal reproducible example,以便我们更轻松地为您提供帮助
  • 当然@techPirate99 - 感谢您的建议和描述性链接。

标签: python arrays numpy machine-learning linear-regression


【解决方案1】:

我在代码中发现了错误。我不得不用浮点数而不是整数来初始化数组。

【讨论】:

  • 你可能想删除这个问题。
猜你喜欢
  • 2017-07-13
  • 2014-10-28
  • 2021-11-19
  • 2022-01-25
  • 2018-06-15
  • 1970-01-01
  • 1970-01-01
  • 2015-04-06
  • 2021-08-10
相关资源
最近更新 更多