在独热编码后的预测

我尝试使用一个示例数据框:

data = [['Alex','USA',0],['Bob','India',1],['Clarke','SriLanka',0]]df = pd.DataFrame(data,columns=['Name','Country','Traget'])

从这里开始,我使用get_dummies将字符串列转换为整数:

column_names=['Name','Country']  one_hot = pd.get_dummies(df[column_names])  

转换后的列为:Age,Name_Alex,Name_Bob,Name_Clarke,Country_India,Country_SriLanka,Country_USA

数据切片。

x=df[["Name_Alex","Name_Bob","Name_Clarke","Country_India","Country_SriLanka","Country_USA"]].values  y=df['Age'].values

将数据集分成训练集和测试集

from sklearn.cross_validation import train_test_splitx_train,x_test,y_train,y_test=train_test_split(x,y,train_size=float(0.5),random_state=0)

逻辑回归

from sklearn.linear_model import LogisticRegressionlogreg = LogisticRegression()logreg.fit(x_train, y_train)

现在,模型已经训练完成。

假设我想通过提供“Name”和“Country”来预测“target”,例如:[“Alex”,”USA”]。

预测。

如果我使用这个:

logreg.predict([["Alex","USA"]])    

显然这是行不通的。

问题1)在训练过程中应用独热编码后,如何测试预测?

问题2)如何对仅包含“Name”和“Country”的样本CSV文件进行预测?


回答:

我建议你使用sklearn的标签编码器和独热编码器包,而不是pd.get_dummies。

一旦你为每个特征初始化了标签编码器和独热编码器,就将其保存到某个地方,这样当你想要对数据进行预测时,你可以轻松地导入保存的标签编码器和独热编码器,并再次对你的特征进行编码。

这样,你的特征编码方式与你在制作训练集时相同。

以下是我用于保存编码器的代码:

labelencoder_dict = {}onehotencoder_dict = {}X_train = Nonefor i in range(0, X.shape[1]):    label_encoder = LabelEncoder()    labelencoder_dict[i] = label_encoder    feature = label_encoder.fit_transform(X[:,i])    feature = feature.reshape(X.shape[0], 1)    onehot_encoder = OneHotEncoder(sparse=False)    feature = onehot_encoder.fit_transform(feature)    onehotencoder_dict[i] = onehot_encoder    if X_train is None:      X_train = feature    else:      X_train = np.concatenate((X_train, feature), axis=1)

现在我保存这个onehotencoder_dict和labelencoder_dict,并在以后用于编码。

def getEncoded(test_data,labelencoder_dict,onehotencoder_dict):    test_encoded_x = None    for i in range(0,test_data.shape[1]):        label_encoder =  labelencoder_dict[i]        feature = label_encoder.transform(test_data[:,i])        feature = feature.reshape(test_data.shape[0], 1)        onehot_encoder = onehotencoder_dict[i]        feature = onehot_encoder.transform(feature)        if test_encoded_x is None:          test_encoded_x = feature        else:          test_encoded_x = np.concatenate((test_encoded_x, feature), axis=1)  return test_encoded_x

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注