簡體   English   中英

一鍵編碼后的預測

[英]Prediction After One-hot encoding

我正在嘗試使用示例dataFrame:

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])  

轉換后,這些列是:年齡,姓名亞歷克斯,姓名鮑勃,姓名克拉克,印度國家/地區,斯里蘭卡國家/地區,美國

切片數據。

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_split

x_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 LogisticRegression

logreg = LogisticRegression()

logreg.fit(x_train, y_train)

現在,模型已訓練完畢。

對於預測,假設我要通過提供“名稱”和“國家/地區”來預測“目標”。
像:[“ Alex”,“ USA”]。

預測。

如果我用這個:

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

顯然,它將無法正常工作。

問題1)在訓練過程中應用一鍵編碼后如何測試預測?

Question2)如何在僅包含“名稱”和“國家/地區”的示例csv文件中進行預測?

我建議您使用sklearn標簽編碼器和一個熱編碼器包,而不要使用pd.get_dummies。

初始化標簽編碼器和每個功能部件一個熱編碼器后,將其保存在某處,以便在要對數據進行預測時,可以輕松地導入已保存的標簽編碼器和一個熱編碼器並再次對功能部件進行編碼。

這樣,您將以與訓練集相同的方式再次對功能進行編碼。

以下是我用於保存編碼器的代碼:

labelencoder_dict = {}
onehotencoder_dict = {}
X_train = None
for 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和標簽encoder_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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM