【问题标题】:ValueError: bad input shape (2835, 18)ValueError: 错误的输入形状 (2835, 18)
【发布时间】:2020-04-14 16:04:32
【问题描述】:

我是数据科学的新手,我想从分类数据中进行分类。 我希望在使用 K-means 算法之前这样做,但是当我使用 fit_transform() 并且我不知道如何修复它时,我得到了这个 'error ValueError: bad input shape (2835, 18)'。我希望有人可以帮助我。

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder

#load my data
myData = pd.read_excel('panelForOneHot.xlsx')
myData = myData.dropna()
myData.reset_index(drop = True, inplace = True)
myData

values = np.array(myData)
print(values)

#integer encode
label_encoder = LabelEncoder()
integer_encoded = label_encoder.fit_transform(values)

【问题讨论】:

    标签: python scikit-learn data-science


    【解决方案1】:

    LabelEncoder() 需要一维数据。传递一个特定的字段进行编码,如下所示。

    # Import label encoder 
    from sklearn import preprocessing 
    
    # label_encoder object knows how to understand word labels. 
    label_encoder = preprocessing.LabelEncoder() 
    
    # Encode labels in column 'species'. 
    df['species']= label_encoder.fit_transform(df['species']) 
    
    df['species'].unique() 
    

    如果您打算对所有列进行编码,

    df.apply(LabelEncoder().fit_transform)
    

    如果您打算对多列而不是全部进行编码,

    from sklearn.compose import make_column_transformer
    from sklearn.preprocessing import RobustScaler
    from sklearn.preprocessing import OneHotEncoder
    
    categorical_columns = ['country', 'gender']
    numerical_columns = ['age']
    column_trans = make_column_transformer(
        (categorical_columns, OneHotEncoder(handle_unknown='ignore'),
        (numerical_columns, RobustScaler())
    column_trans.fit_transform(df)
    

    【讨论】:

    • 小心LabelEncoder。它永远不应该用于您的数据,只能用于目标(即标签)。仅在处理数据矩阵时使用OneHot Encoder
    • 我同意,您可以查看datascience.stackexchange.com/a/9447 了解何时可能需要使用标签编码器。
    猜你喜欢
    • 2018-01-27
    • 1970-01-01
    • 2020-03-16
    • 2017-08-14
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    相关资源
    最近更新 更多