为什么我不能使用 preprocessing.normalize 规范化我的数据?

数据挖掘 机器学习
2022-02-12 19:50:21

代码:

df['Miles'] = preprocessing.normalize(df['Miles'])

错误信息:

ValueError: Expected 2D array, got 1D array instead:
array=[33.3304678  33.3304678  33.3304678  ...  3.00959404  3.00959404
  3.00959404].
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.
2个回答

Sklearn.preprocessing.normalize 是向量范数归一化。默认情况下,它使用 L2 范数,即例如,如果有一个向量,那么,那么如果你对向量进行归一化,它将是xnorm=Σxi2(1,2,3)xnorm=12+22+32=3.7416(13.7416,23.7416,33.7416)

如果这是您想要的,请尝试

# convert to numpy array with shape(rows,1)
df_array = df['Miles'].values.reshape(-1,1)
df['Miles'] = preprocessing.normalize(df_array,axis=0)

请注意设置axis = 0,否则它将按列完成,您将获得所有1个向量。

我认为您可能想要缩放向量而不是标准化,尝试 mean-std scale by sklearn.preprocessing.scale, max-min scale by sklearn.preprocessing.minmax_scale确保首先重塑阵列。

首先,这可能不是您正在寻找的规范化 sklearn.preprocessing.normalize 是一种确保特征向量长度为​​ 1 的工具。

根据 sklearn.preprocessing.normalize

将输入向量单独缩放到单位范数(向量长度)。

如果你仍然坚持,修复很简单。简单地做

df['Miles'] = preprocessing.normalize(df['Miles'].values.reshape(-1,1))

但我可以猜测你的结果将是一个全为 1 的特征向量。