【问题标题】:How to make prediction on the new data in Pandas DataFrame with some extra columns?如何使用一些额外的列对 Pandas DataFrame 中的新数据进行预测?
【发布时间】:2020-07-20 13:59:24
【问题描述】:

我已经使用随机森林分类器来构建模型 - 模型运行良好,我能够在训练和测试中输出分数以及概率值。

挑战是:

  • 我使用 29 个变量作为具有 1 个目标的特征

  • 当我为 X_Test 评分时,它运行良好

  • 当我引入一个包含 29 个变量和我的唯一 ID /主键的新数据集时 - 模型错误提示它正在寻找 29 个变量

如何保留我的 ID 并获得新文件的预测?

到目前为止我尝试了什么 -

data = pd.read_csv('learn2.csv')
y=data['Target']  # Labels

X=data[[
        'xsixn',    'xssocixtesDegreeOnggy',    'xverxgeeeouseeeoggdIncome',    'BxceeeggorsDegreeOnggy',   'Bggxckorxfricxnxmericxn',  
'Ceeiggdrenxteeome',    'Coggggege',    'Eggementxry',  'GrxduxteDegree',   'eeigeeSceeoogg',   'eeigeeSceeooggGrxduxte',   'eeouseeeoggdsEst', 
'MedixneeouseeeoggdIncome', 'NoVeeeicgges', 'Oteeerxsixn',  'OteeersRxces', 'OwnerOccupiedPercent', 'PercentBggueCoggggxrWorkers',
    'PercentWeeiteCoggggxr',    'PopuggxtionEst',   'PopuggxtionPereeouseeeoggd',   'RenterOccupiedPercent',    'RetiredOrDisxbggePersons',
    'TotxggDxytimePopuggxtion', 'TotxggStudentPopuggxtion', 'Unempggoyed',  'VxcxnteeousingPercent',    'Weeite',   'WorkpggxceEstxbggiseements'

        ]]

# Import train_test_split function
from sklearn.model_selection import train_test_split

    # Split dataset into training set and test set
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # 80% training

    #Import Random Forest Model
    from sklearn.ensemble import RandomForestClassifier

    #Create a Gaussian Classifier
    clf=RandomForestClassifier(n_estimators=100)


    #Train the model using the training sets y_pred=clf.predict(X_test)
    clf.fit(X_train,y_train)
    y_pred=clf.predict(X_test)

预测新文件:

data1=pd.read_csv('score.csv')
y_pred2=clf.predict(data2)

ValueError: Number of features of the model must match the input. Model n_features is 29 and input n_features is 30 

【问题讨论】:

  • 我们无法真正重现这一点。例如,您可以打印data_1X(作为df)的列名吗?
  • 所有浮动,我的 ID 是对象
  • 形状一样吗?该错误似乎表明 X_train 和 X_test 的形状不同(列数不同)
  • 是的,我要运行的文件将具有唯一的 ID 作为额外的列,我不想错过。

标签: python pandas machine-learning random-forest


【解决方案1】:

您可以在使用pandas difference 函数对新数据集生成预测时排除'ID' 列:

data1=pd.read_csv('score.csv')

为了便于进一步使用,我将预测存储在一个新的数据框中:

y_pred2 = pd.DataFrame(clf.predict(data1[data1.columns.difference(['ID'])]),columns = ['Predicted'], index = data1.index)

要将预测映射到'ID',请使用pd.concat

pred = pd.concat([data1['ID'], y_pred2['Predicted']], axis = 1)

【讨论】:

  • 您绝对不会使用唯一 ID 进行训练!把它弄出来然后重新运行它。应该没问题。
  • 这就是我的答案,使用 pandas columns.difference,它将忽略训练和预测中的“唯一 ID”,而不将其从数据框中删除。
猜你喜欢
  • 2022-01-22
  • 2021-12-17
  • 2021-10-17
  • 2016-11-27
  • 2020-05-07
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多