通過sklearn 實現babel 編碼,之後進行xgboost預測。
LabelEncoder()
更多編碼操作可以參考:鏈接直通車
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
import xgboost as xgb
import pandas as pd
def GitdataCate():
df=pd.read_csv("Training.csv")
one_hot_feature=["prognosis"]
lbc = LabelEncoder()
for feature in one_hot_feature:
try:
df[feature] = lbc.fit_transform(df[feature].apply(int))
except:
df[feature] = lbc.fit_transform(df[feature])
# X=df.as_matrix(),此方法後面回去刪除,可以使用df.values
X=df.values
print(X)
#返回映射後的classes_的編碼
terminal_type1 = {index: label for index, label in enumerate( lbc.classes_)}
print(terminal_type1)
注意:上面的代碼只能返回最後的一列的特徵編碼字典,通過過下下方式可以打印出每一個特徵的特徵編碼。
for feature in one_hot_feature:
try:
df[feature] = lbc.fit_transform(df[feature].apply(int))
except:
df[feature] = lbc.fit_transform(df[feature])
# X=df.as_matrix(),此方法後面回去刪除,可以使用df.values
terminal_type1 = {index: label for index, label in enumerate( lbc.classes_)}
print(terminal_type1)
兩個特徵的特徵編碼:
更多操作:
from sklearn.preprocessing import LabelEncoder
包初始化
gle = LabelEncoder()
建立映射
terminal_type= gle.fit_transform(data1[‘terminal_type’])
映射後的對應值
terminal_type1 = {index: label for index, label in enumerate(gle.classes_)}
添加映射後的列
data1[‘terminal_type1’] = terminal_type
刪除映射前對的列
data1 = data1.drop([‘terminal_type’],axis=1)
data1.head()
klearn.preprocessing.LabelEncoder():標準化標籤,將標籤值統一轉換成range(標籤值個數-1)範圍內
以數字標籤爲例:
In [1]: from sklearn import preprocessing
...: le = preprocessing.LabelEncoder()
...: le.fit([1,2,2,6,3])
...:
Out[1]: LabelEncoder()
獲取標籤值
In [2]: le.classes_
Out[2]: array([1, 2, 3, 6])
將標籤值標準化
In [3]: le.transform([1,1,3,6,2])
Out[3]: array([0, 0, 2, 3, 1], dtype=int64)
將標準化的標籤值反轉
In [4]: le.inverse_transform([0, 0, 2, 3, 1])
Out[4]: array([1, 1, 3, 6, 2])
非數字型標籤值標準化:
In [5]: from sklearn import preprocessing
...: le =preprocessing.LabelEncoder()
...: le.fit(["paris", "paris", "tokyo", "amsterdam"])
...: print('標籤個數:%s'% le.classes_)
...: print('標籤值標準化:%s' % le.transform(["tokyo", "tokyo", "paris"]))
...: print('標準化標籤值反轉:%s' % le.inverse_transform([2, 2, 1]))
...:
標籤個數:[‘amsterdam’ ‘paris’ ‘tokyo’]
標籤值標準化:[2 2 1]
標準化標籤值反轉:[‘tokyo’ ‘tokyo’ ‘paris’]