【问题标题】:sklearn.preprocessing.StandardScaler ValueError: Expected 2D array, got 1D array instead [closed]sklearn.preprocessing.StandardScaler ValueError:预期的二维数组,得到一维数组[关闭]
【发布时间】:2021-03-01 02:13:31
【问题描述】:

我正在尝试完成http://www.semspirit.com/artificial-intelligence/machine-learning/regression/support-vector-regression/support-vector-regression-in-python/ 的教程 但没有包含 csv 文件,所以我使用自己的数据。到目前为止的代码如下:

import numpy as np
import pandas as pd
from matplotlib import cm
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy import stats

# Here's where I import my data; there's no csv file included in the tutorial
import quasar_functions as qf
dataset, datasetname, mags = qf.loaddata('sdss12')

S = np.asarray(dataset[mags])
t = np.asarray(dataset['z'])
t.reshape(-1,1)

# Feature scaling
from sklearn.preprocessing import StandardScaler as scale
sc_S = scale()
sc_t = scale()
S2 = sc_S.fit_transform(S)
t2 = sc_t.fit_transform(t)

最后一行抛出错误:

ValueError: Expected 2D array, got 1D array instead:
array=[4.17974 2.06468 5.46959 ... 0.41398 0.3672  1.9235 ].
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.

是的,我已经用t.reshape(-1,1) 重塑了我的目标数组t,如图所示herehereherehere,但无济于事。我的整形正确吗?

这是我的所有变量:

【问题讨论】:

    标签: python scikit-learn


    【解决方案1】:

    我猜你有一个dataframe,所以你需要重新分配变量t = t.reshape(-1,1)

    import pandas as pd
    
    dataset = pd.DataFrame(np.random.normal(2,1,(100,4)),columns=['z','x1','x2','x3'])
    mags = ['x1','x2','x3']
    
    S = np.asarray(dataset[mags])
    t = np.asarray(dataset['z'])
    t = t.reshape(-1,1)
    
    from sklearn.preprocessing import StandardScaler as scale
    sc_S = scale()
    sc_t = scale()
    S2 = sc_S.fit_transform(S)
    t2 = sc_t.fit_transform(t)
    
    要检查它是否有效:
    np.mean(t2)
    2.4646951146678477e-16
    

    【讨论】:

      猜你喜欢
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      • 2018-06-06
      • 2021-09-19
      • 2019-10-07
      • 2019-03-28
      • 2021-04-16
      • 2011-04-13
      相关资源
      最近更新 更多