【发布时间】:2019-10-29 11:35:44
【问题描述】:
我有一个包含所有分类列的数据框,我使用来自sklearn.preprocessing 的oneHotEncoder 对其进行编码。我的代码如下:
from sklearn.preprocessing import OneHotEncoder
from sklearn.pipeline import Pipeline
steps = [('OneHotEncoder', OneHotEncoder(handle_unknown ='ignore')) ,('LReg', LinearRegression())]
pipeline = Pipeline(steps)
正如在OneHotEncoder 中看到的,handle_unknown 参数采用error 或ignore。我想知道是否有办法选择性地忽略某些列的未知类别而对其他列给出错误?
import pandas as pd
df = pd.DataFrame({'Country':['USA','USA','IND','UK','UK','UK'],
'Fruits':['Apple','Strawberry','Mango','Berries','Banana','Grape'],
'Flower': ['Rose','Lily','Orchid','Petunia','Lotus','Dandelion'],
'Result':[1,2,3,4,5,6,]})
from sklearn.preprocessing import OneHotEncoder
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
steps = [('OneHotEncoder', OneHotEncoder(handle_unknown ='ignore')) ,('LReg', LinearRegression())]
pipeline = Pipeline(steps)
from sklearn.model_selection import train_test_split
X = df[["Country","Flower","Fruits"]]
Y = df["Result"]
X_train, X_test, y_train, y_test = train_test_split(X,Y,test_size=0.3, random_state=30, shuffle =True)
print("X_train.shape:", X_train.shape)
print("y_train.shape:", y_train.shape)
print("X_test.shape:", X_test.shape)
print("y_test.shape:", y_test.shape)
pipeline.fit(X_train,y_train)
y_pred = pipeline.predict(X_test)
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
#Mean Squared Error:
MSE = mean_squared_error(y_test,y_pred)
print("MSE", MSE)
#Root Mean Squared Error:
from math import sqrt
RMSE = sqrt(MSE)
print("RMSE", RMSE)
#R-squared score:
R2_score = r2_score(y_test,y_pred)
print("R2_score", R2_score)
在这种情况下,对于 Country、Fruits 和 Flowers 的所有列,如果有新值出现,模型仍然能够预测输出。
我想知道是否有办法忽略 Fruits 和 Flowers 的未知类别,但在 Country 列中引发未知值错误?
【问题讨论】:
标签: python pandas scikit-learn one-hot-encoding