【问题标题】:use of numpy.newaxis in machine learning在机器学习中使用 numpy.newaxis
【发布时间】:2019-04-03 16:53:06
【问题描述】:

我正在尝试增加初始数组的维度:

import matplotlib.pyplot as plt
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
x = 10*rng.rand(50)
y = np.sin(x) + 0.1*rng.rand(50)

poly = PolynomialFeatures(7, include_bias=False)
poly.fit_transform(x[:,np.newaxis])

首先,我知道 np.newaxis 正在创建附加列。为什么需要这样做?

现在我将使用线性回归训练更新后的 x 数据(多边形)

test_x = np.linspace(0,10,1000)
from sklearn.linear_model import LinearRegression

model = LinearRegression()
# train with increased dimension(x=poly) with its target
model.fit(poly,y)
# testing
test_y = model.predict(x_test)

当我运行它时,它给了我:ValueError: Expected 2D array, got scalar array instead: on model.fit(poly,y) line。我已经为多边形添加了一个维度,发生了什么?

x[:,np.newaxis] 与 x[:,np.newaxis] 之间还有什么区别。 x[:,无]?

【问题讨论】:

    标签: python numpy machine-learning


    【解决方案1】:
    In [55]: x=10*np.random.rand(5)                                                 
    In [56]: x                                                                      
    Out[56]: array([6.47634068, 6.25520837, 7.58822106, 4.65466951, 2.35783624])
    In [57]: x.shape                                                                
    Out[57]: (5,)
    

    newaxis 不加列,只加维度:

    In [58]: x1 = x[:,np.newaxis]                                                   
    In [59]: x1                                                                     
    Out[59]: 
    array([[6.47634068],
           [6.25520837],
           [7.58822106],
           [4.65466951],
           [2.35783624]])
    In [60]: x1.shape                                                               
    Out[60]: (5, 1)
    

    np.newaxis 的值为None,因此两者的工作方式相同。

    In[61]: x[:,None].shape                                                        
    Out[61]: (5, 1)
    

    一个对人类读者来说更清晰一些,另一个更容易打字。 https://www.numpy.org/devdocs/reference/constants.html

    xx1 是否有效取决于学习代码的期望。一些学习代码需要(samples, features) 形状的输入。它可以假设一个 (50,) 形状数组是 50 个样本,1 个特征,或 1 个案例,50 个特征。但最好能准确说出你的意思。


    查看文档:

    https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.html#sklearn.preprocessing.PolynomialFeatures.fit_transform

    poly.fit_transform
    X : numpy array of shape [n_samples, n_features]
    

    当然看起来fit_transform 需要二维输入。

    https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression.fit

    Xy 都应该是二维的。

    【讨论】:

    • 添加列就像添加维度不是吗?例如,如果您有 [x,y] 并且想要添加额外的 z 列,它将成为 [x,y,z] 3-D 空间。
    • xy 是单点,还是多个点的值?您可以用 (n,2) 数组来描述一组 n 点,用于 2-d 空间,或 (n,3) 用于 3-d 空间。但两者都是二维数组。另一方面,您可以使用 (n,m) 数组或 3d 空间中的 (n,m,o) 定义笛卡尔空间中的 2d 网格。 dimension 的定义取决于上下文。
    猜你喜欢
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 2015-10-23
    • 2017-03-03
    • 2019-05-14
    • 2019-07-10
    • 2015-04-09
    相关资源
    最近更新 更多