【问题标题】:How to use prediction model after onehot encoding?一次热编码后如何使用预测模型?
【发布时间】:2021-01-06 22:56:16
【问题描述】:

我已经为这个数据集创建了一个预测模型

>>df.head()

    Service    Tasks Difficulty     Hours
0   ABC         24     1           0.833333
1   CDE         77     1           1.750000
2   SDE         90     3           3.166667
3   QWE         47     1           1.083333
4   ASD         26     3           1.000000

>>df.shape
(998,4)

>>X = df.iloc[:,:-1]
>>y = df.iloc[:,-1].values
>>from sklearn.compose import ColumnTransformer 
>>ct = ColumnTransformer([("cat", OneHotEncoder(),[0])], remainder="passthrough")
>>X = ct.fit_transform(X)  
>>x = X.toarray()
>>x = x[:,1:]

>>x.shape
(998,339)

>>from sklearn.ensemble import RandomForestRegressor
>>rf_model = RandomForestRegressor(random_state = 1)
>>rf_model.fit(x,y)

我如何使用这个模型来预测Hours 以供用户输入这种格式[["SDE", 90, 3]]

我试过了

>>test_input = [["SDE", 90, 3]]
>>test_input = ct.fit_transform(test_input)  
>>test_input = test_input[[:,1:]

>>test_input[0]
array([24, 1], dtype=object)


>>predict_hours = rf_model.predict(test_input)
ValueError

由于我的数据集有很多categorical值,因此无法输入"SDE"的编码值作为输入,我需要在收到输入[["SDE", 90, 3]]后将"SDE"转换为onehot encoded格式

我不知道怎么做,谁能帮忙?

【问题讨论】:

  • 请从intro tour 重复on topichow to ask。 Stack Overflow 并不打算取代现有的文档和教程。由于有许多网站都在说明使用 one-hot 编码,因此我们希望您在发帖之前先使用它们。
  • 不要在训练和预测样本上都使用fit_transform()fit() 你的转换器到你的训练数据,然后transform() 你的训练和测试数据和拟合的转换器

标签: python prediction categorical-data one-hot-encoding


【解决方案1】:

您可以使用Pipeline 轻松处理预处理和分类阶段

import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split

# I have created a dummy dataset
df = pd.read_csv('test.csv')

X = df.iloc[:,:-1]
y = df.iloc[:,-1].values

# preprocessor
preprocessor = ColumnTransformer([("cat", OneHotEncoder(handle_unknown='ignore'),[0])], remainder="passthrough")

# create a pipeline with preprocessor and classifier
pipeline = Pipeline([('preprocessor', preprocessor),
                      ('classifier', RandomForestRegressor(random_state = 1))
                      ])
# split dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5,
                                                    random_state=0)

# train the pipelime
pipeline.fit(X_train, y_train)

# predict
print(pipeline.predict(X_test))

【讨论】:

    猜你喜欢
    • 2020-04-14
    • 2019-10-08
    • 2018-10-31
    • 2021-02-23
    • 2020-08-05
    • 2020-08-28
    • 2020-05-13
    • 2018-10-29
    • 2017-12-18
    相关资源
    最近更新 更多