如何从随机生成的值中获得多项式的四阶并将数组从(100)整形为(100,4)?

问题描述 投票:0回答:1

我正在尝试实现多项式的四阶,并通过以下指令实现以下​​逻辑:

  1. 首先,从scikit-learn导入PolynomialFeatures函数
  2. 并使用它来生成一个新的X_4d数组,该数组具有所有功能直至4阶功能
  3. 变换后的形状应为(100,4),以添加高阶多项式特征,并且前5个>]
  4. 样本应如下所示
  5. 代码:

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

def forth_order(m, a=-3.15, b=1.18, c=3.52, d=3.92, mu=0.0, sigma=0.33):
    new_x = np.random.uniform(low=-1.0, high=1.0, size=(m,)).reshape(100,4)
    new_y =  a*x**3 + b*x**2 + c*x + d + np.random.randn(m)*sigma
    return(new_x, new_y)

print(new_x)
print(new_x.shape)

print(new_y)    
print(new_y.shape)

# to find the 4th order for random generated values
np.random.seed(42)
# call your function to generate the artificial cubic data set
new_x,new_y = make_cubic_dataset(100)

transformer = PolynomialFeatures(degree=4, include_bias=False)
transformer.fit(new_x).reshape(100,4)
x_ = transformer.transform(new_x)
X_4d = np.polyfit(x, y, 3) # fit a degree 4 (cubic) polynomial to the data

print(X_4d)
print(X_4d.shape)

一个错误:

ValueError: cannot reshape array of size 100 into shape (100,4)

预期结果:

变换后的形状应为(100,4)以添加高阶多项式特征,并且前5个和样本应如下所示

print(X_4d.shape)
>>> (100, 4)

print(X_4d[:5,:])
>>> [[-0.25091976  0.06296073 -0.01579809  0.00396405]
    [ 0.90142861  0.81257354  0.73247704  0.66027576]
    [ 0.46398788  0.21528476  0.09988952  0.04634753]
    [ 0.19731697  0.03893399  0.00768234  0.00151586]
    [-0.68796272  0.4732927  -0.32560773  0.22400598]]

我在解决此问题时遇到了麻烦。

我正在尝试实现多项式的四阶并通过以下指令实现以下​​逻辑:首先,从scikit-learn中导入PolynomialFeatures函数,并...

python python-3.x scikit-learn linear-regression sklearn-pandas
1个回答
0
投票
这是代码中的一个很小的变化,这是不言而喻的:
© www.soinside.com 2019 - 2024. All rights reserved.