sklearn.preprocessing.StandardScaler ValueError: Expected 2D array, got 1D array instead

Viewed 6156

I'm trying to work through a tutorial at http://www.semspirit.com/artificial-intelligence/machine-learning/regression/support-vector-regression/support-vector-regression-in-python/ but there's no csv file included, so I'm using my own data. Here's the code so far:

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)

The last line throws an error:

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.

and yes, I've reshaped my target array t with t.reshape(-1,1) as shown here, here, here and here, but to no avail. Am I reshaping correctly?

Here's all my variables: enter image description here

1 Answers

I am guessing you have a dataframe, so you need to reassign the variable 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)

To check it works:

np.mean(t2)
2.4646951146678477e-16
Related