如何使用onehotcoding

how to use onehotcoding

所以我正在尝试做一个项目,要求对某个部分进行一次热编码。但我不知道如何使用它。我一直在使用 google 来尝试理解,但我就是无法理解。我的问题在下面。

现在,我们也想使用分类特征!因此,我们必须执行 OneHotEncoding 用于分类特征。为此,每个分类特征都应该 替换为特征 table 中的虚拟列(每个可能值对应一列 分类特征),然后以二进制方式对其进行编码,使得至多只有 其中一个虚拟列一次可以取“1”(其余为零)。例如, “性别”可以取两个值“m”和“f”。因此,我们需要替换此功能(在 feature table) 由标题为“m”和“f”的两列组成。无论在哪里,我们有一个男性主体,我们 可以在“m”和“f”列中放入“1”和“0”。无论在哪里,我们有一个女性主题,我们 可以在“m”和“f”列中放置“0”和“1”。 (提示:你需要 4 列来编码 “ChestPain”和 3 列编码“Thal”)。

到目前为止我的代码是这样的,

# a- Read the dataset from the following URL:
# and assign it to a Pandas DataFrame 

heart_d = pd.read_csv("C:/Users/Michael/Desktop/HW2/Heart_s.csv")


feature_cols = ['Age','RestBP','Chol','RestECG','MaxHR','Oldpeak']
X = heart_d[feature_cols]

y = heart_d['AHD']

# Randomly splitting the original dataset into training set and testing set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=3)

目前为止这是有效的,但现在我必须对分类内容使用那种热编码,但我完全不知道它是如何工作的。 数据集中的 3 个分类特征是(性别、胸痛、 塔尔)。我试过这样做

df_cp = pd.get_dummies(heart_d['ChestPain'])
df_g = pd.get_dummies(heart_d['Gender'])
df_t = pd.get_dummies(heart_d['Thal'])

df_new = pd.concat([df, df_cp,df_g,df_t ], axis=1)

但我不确定那是否有效,当我 运行 我的分类时,我对所有内容都得到相同的答案

我想你可以使用 scikit-learn for data train, here is one-hot encoder example in it:

from sklearn.preprocessing import OneHotEncoder
>>> enc = OneHotEncoder()
>>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])  
OneHotEncoder(categorical_features='all', dtype=<... 'numpy.float64'>,
   handle_unknown='error', n_values='auto', sparse=True)
>>> enc.n_values_
array([2, 3, 4])
>>> enc.feature_indices_
array([0, 2, 5, 9])
>>> enc.transform([[0, 1, 1]]).toarray()
array([[ 1.,  0.,  0.,  1.,  0.,  0.,  1.,  0.,  0.]])

====更新====

我写了一个关于如何对字符串属性使用单热编码器的详细示例,DictVectorizer

import pandas as pd
from sklearn.feature_extraction import DictVectorizer as DV        

d = [
    {'country':'A', 'Gender':'M'},
    {'country':'B', 'Gender':'F'},                                 
    {'country':'C', 'Gender':'F'}
]               
df = pd.DataFrame(d)                                               
print df        
test_d = [
    {'country':'A', 'Gender':'F'},                                 
    {'country':'B', 'Gender':'F'}

]                                                                  
test_df = pd.DataFrame(test_d)
print test_df                                                      

train_x = df.T.to_dict().values()                                  
vx = DV(sparse=False)

transform_x = vx.fit_transform(train_x)
print 'transform_train_df'
print transform_x

test_x = test_df.T.to_dict().values()
transform_test_x = vx.transform(test_x)
print 'transform_test_df'
print transform_test_x                                             

输出:

  Gender country
0      M       A
1      F       B
2      F       C
  Gender country
0      F       A
1      F       B
transform_train_df
[[ 0.  1.  1.  0.  0.]
 [ 1.  0.  0.  1.  0.]
 [ 1.  0.  0.  0.  1.]]
transform_test_df
[[ 1.  0.  1.  0.  0.]
 [ 1.  0.  0.  1.  0.]]