[英]How can I one hot encode in Python?
我有一个包含 80% 分类变量的机器学习分类问题。 如果我想使用某个分类器进行分类,我必须使用一种热编码吗? 我可以在没有编码的情况下将数据传递给分类器吗?
我正在尝试执行以下功能选择:
我读了火车文件:
num_rows_to_read = 10000 train_small = pd.read_csv("../../dataset/train.csv", nrows=num_rows_to_read)
我将分类特征的类型更改为“类别”:
non_categorial_features = ['orig_destination_distance', 'srch_adults_cnt', 'srch_children_cnt', 'srch_rm_cnt', 'cnt'] for categorical_feature in list(train_small.columns): if categorical_feature not in non_categorial_features: train_small[categorical_feature] = train_small[categorical_feature].astype('category')
我使用一种热编码:
train_small_with_dummies = pd.get_dummies(train_small, sparse=True)
问题是第三部分经常卡住,尽管我使用的是一台强大的机器。
因此,如果没有一种热编码,我就无法进行任何特征选择,以确定特征的重要性。
你有什么建议吗?
方法 1:您可以使用 pandas 的pd.get_dummies
。
示例 1:
import pandas as pd
s = pd.Series(list('abca'))
pd.get_dummies(s)
Out[]:
a b c
0 1.0 0.0 0.0
1 0.0 1.0 0.0
2 0.0 0.0 1.0
3 1.0 0.0 0.0
示例 2:
以下将把给定的列转换为一个热列。 使用前缀有多个假人。
import pandas as pd
df = pd.DataFrame({
'A':['a','b','a'],
'B':['b','a','c']
})
df
Out[]:
A B
0 a b
1 b a
2 a c
# Get one hot encoding of columns B
one_hot = pd.get_dummies(df['B'])
# Drop column B as it is now encoded
df = df.drop('B',axis = 1)
# Join the encoded df
df = df.join(one_hot)
df
Out[]:
A a b c
0 a 0 1 0
1 b 1 0 0
2 a 0 0 1
方法 2:使用 Scikit-learn
使用OneHotEncoder
的优点是能够fit
一些训练数据,然后使用相同的实例对其他一些数据进行transform
。 我们还有handle_unknown
来进一步控制编码器对看不见的数据的处理。
给定一个具有三个特征和四个样本的数据集,我们让编码器找到每个特征的最大值并将数据转换为二进制 one-hot 编码。
>>> 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=<class '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], dtype=int32)
>>> enc.transform([[0, 1, 1]]).toarray()
array([[ 1., 0., 0., 1., 0., 0., 1., 0., 0.]])
这是此示例的链接:http: //scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html
使用 Pandas 进行基本的 one-hot 编码要容易得多。 如果您正在寻找更多选项,您可以使用scikit-learn
。
对于Pandas的基本 one-hot 编码,您将数据帧传递给get_dummies函数。
例如,如果我有一个名为imdb_movies的数据框:
...我想对 Rated 列进行一次热编码,我这样做:
pd.get_dummies(imdb_movies.Rated)
这将返回一个新的dataframe
,其中包含针对存在的每个“级别”评级的列,以及 1 或 0 指定给定观察的评级是否存在。
通常,我们希望它成为原始dataframe
的一部分。 在这种情况下,我们使用“列绑定”将新的虚拟编码帧附加到原始帧上。
我们可以使用 Pandas 的concat函数进行列绑定:
rated_dummies = pd.get_dummies(imdb_movies.Rated)
pd.concat([imdb_movies, rated_dummies], axis=1)
我们现在可以对我们的完整dataframe
进行分析。
简单实用功能
我建议让自己成为一个实用函数来快速执行此操作:
def encode_and_bind(original_dataframe, feature_to_encode):
dummies = pd.get_dummies(original_dataframe[[feature_to_encode]])
res = pd.concat([original_dataframe, dummies], axis=1)
return(res)
用法:
encode_and_bind(imdb_movies, 'Rated')
结果:
此外,根据@pmalbu 评论,如果您希望删除原始 feature_to_encode的功能,请使用此版本:
def encode_and_bind(original_dataframe, feature_to_encode):
dummies = pd.get_dummies(original_dataframe[[feature_to_encode]])
res = pd.concat([original_dataframe, dummies], axis=1)
res = res.drop([feature_to_encode], axis=1)
return(res)
您可以同时对多个特征进行编码,如下所示:
features_to_encode = ['feature_1', 'feature_2', 'feature_3',
'feature_4']
for feature in features_to_encode:
res = encode_and_bind(train_set, feature)
您可以使用numpy.eye
和 a 使用数组元素选择机制来做到这一点:
import numpy as np
nb_classes = 6
data = [[2, 3, 4, 0]]
def indices_to_one_hot(data, nb_classes):
"""Convert an iterable of indices to one-hot encoded labels."""
targets = np.array(data).reshape(-1)
return np.eye(nb_classes)[targets]
indices_to_one_hot(nb_classes, data)
的返回值现在是
array([[[ 0., 0., 1., 0., 0., 0.],
[ 0., 0., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 1., 0.],
[ 1., 0., 0., 0., 0., 0.]]])
.reshape(-1)
用于确保您具有正确的标签格式(您可能还具有[[2], [3], [4], [0]]
)。
首先,最简单的热编码方法:使用 Sklearn。
http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html
其次,我不认为使用 pandas 进行一个热编码是那么简单(虽然未经证实)
最后,你有必要进行一次热编码吗? 一种热编码会以指数方式增加特征的数量,从而大大增加任何分类器或您将要运行的任何其他东西的运行时间。 尤其是当每个分类特征都有很多层次时。 相反,您可以进行虚拟编码。
使用虚拟编码通常效果很好,运行时间和复杂性要少得多。 一位睿智的教授曾经告诉我,“少即是多”。
如果需要,这是我的自定义编码功能的代码。
from sklearn.preprocessing import LabelEncoder
#Auto encodes any dataframe column of type category or object.
def dummyEncode(df):
columnsToEncode = list(df.select_dtypes(include=['category','object']))
le = LabelEncoder()
for feature in columnsToEncode:
try:
df[feature] = le.fit_transform(df[feature])
except:
print('Error encoding '+feature)
return df
编辑:比较更清楚:
One-hot 编码:将 n 级转换为 n-1 列。
Index Animal Index cat mouse
1 dog 1 0 0
2 cat --> 2 1 0
3 mouse 3 0 1
如果您的分类特征中有许多不同的类型(或级别),您可以看到这将如何激发您的记忆力。 请记住,这只是一列。
虚拟编码:
Index Animal Index Animal
1 dog 1 0
2 cat --> 2 1
3 mouse 3 2
改为转换为数字表示。 极大地节省了特征空间,但牺牲了一点准确性。
使用 pandas 的一种热编码非常简单:
def one_hot(df, cols):
"""
@param df pandas DataFrame
@param cols a list of columns to encode
@return a DataFrame with one-hot encoding
"""
for each in cols:
dummies = pd.get_dummies(df[each], prefix=each, drop_first=False)
df = pd.concat([df, dummies], axis=1)
return df
编辑:
使用 sklearn 的LabelBinarizer
的 one_hot 的另一种方法:
from sklearn.preprocessing import LabelBinarizer
label_binarizer = LabelBinarizer()
label_binarizer.fit(all_your_labels_list) # need to be global or remembered to use it later
def one_hot_encode(x):
"""
One hot encode a list of sample labels. Return a one-hot encoded vector for each label.
: x: List of sample Labels
: return: Numpy array of one-hot encoded labels
"""
return label_binarizer.transform(x)
您可以使用 numpy.eye 功能。
import numpy as np
def one_hot_encode(x, n_classes):
"""
One hot encode a list of sample labels. Return a one-hot encoded vector for each label.
: x: List of sample Labels
: return: Numpy array of one-hot encoded labels
"""
return np.eye(n_classes)[x]
def main():
list = [0,1,2,3,4,3,2,1,0]
n_classes = 5
one_hot_list = one_hot_encode(list, n_classes)
print(one_hot_list)
if __name__ == "__main__":
main()
结果
D:\Desktop>python test.py
[[ 1. 0. 0. 0. 0.]
[ 0. 1. 0. 0. 0.]
[ 0. 0. 1. 0. 0.]
[ 0. 0. 0. 1. 0.]
[ 0. 0. 0. 0. 1.]
[ 0. 0. 0. 1. 0.]
[ 0. 0. 1. 0. 0.]
[ 0. 1. 0. 0. 0.]
[ 1. 0. 0. 0. 0.]]
pandas 具有内置函数“get_dummies”来获取该特定列的一个热编码。
一热编码的一行代码:
df=pd.concat([df,pd.get_dummies(df['column name'],prefix='column name')],axis=1).drop(['column name'],axis=1)
这是使用DictVectorizer
和 Pandas DataFrame.to_dict('records')
方法的解决方案。
>>> import pandas as pd
>>> X = pd.DataFrame({'income': [100000,110000,90000,30000,14000,50000],
'country':['US', 'CAN', 'US', 'CAN', 'MEX', 'US'],
'race':['White', 'Black', 'Latino', 'White', 'White', 'Black']
})
>>> from sklearn.feature_extraction import DictVectorizer
>>> v = DictVectorizer()
>>> qualitative_features = ['country','race']
>>> X_qual = v.fit_transform(X[qualitative_features].to_dict('records'))
>>> v.vocabulary_
{'country=CAN': 0,
'country=MEX': 1,
'country=US': 2,
'race=Black': 3,
'race=Latino': 4,
'race=White': 5}
>>> X_qual.toarray()
array([[ 0., 0., 1., 0., 0., 1.],
[ 1., 0., 0., 1., 0., 0.],
[ 0., 0., 1., 0., 1., 0.],
[ 1., 0., 0., 0., 0., 1.],
[ 0., 1., 0., 0., 0., 1.],
[ 0., 0., 1., 1., 0., 0.]])
One-hot 编码需要的不仅仅是将值转换为指示变量。 通常,ML 过程需要您多次将此编码应用于验证或测试数据集,并将您构建的模型应用于实时观察数据。 您应该存储用于构建模型的映射(转换)。 一个好的解决方案是使用DictVectorizer
或LabelEncoder
(后跟get_dummies
。这是您可以使用的函数:
def oneHotEncode2(df, le_dict = {}):
if not le_dict:
columnsToEncode = list(df.select_dtypes(include=['category','object']))
train = True;
else:
columnsToEncode = le_dict.keys()
train = False;
for feature in columnsToEncode:
if train:
le_dict[feature] = LabelEncoder()
try:
if train:
df[feature] = le_dict[feature].fit_transform(df[feature])
else:
df[feature] = le_dict[feature].transform(df[feature])
df = pd.concat([df,
pd.get_dummies(df[feature]).rename(columns=lambda x: feature + '_' + str(x))], axis=1)
df = df.drop(feature, axis=1)
except:
print('Error encoding '+feature)
#df[feature] = df[feature].convert_objects(convert_numeric='force')
df[feature] = df[feature].apply(pd.to_numeric, errors='coerce')
return (df, le_dict)
这适用于 pandas 数据框,并且对于它创建的数据框的每一列并返回一个映射。 所以你会这样称呼它:
train_data, le_dict = oneHotEncode2(train_data)
然后在测试数据上,通过传递从训练返回的字典进行调用:
test_data, _ = oneHotEncode2(test_data, le_dict)
一种等效的方法是使用DictVectorizer
。 我的博客上有一篇相关的文章。 我在这里提到它,因为它提供了这种方法背后的一些推理,而不是简单地使用 get_dummies 帖子(披露:这是我自己的博客)。
您可以将数据传递给 catboost 分类器而无需编码。 Catboost 通过执行 one-hot 和目标扩展均值编码来处理分类变量本身。
您也可以执行以下操作。 请注意以下内容,您不必使用pd.concat
。
import pandas as pd
# intialise data of lists.
data = {'Color':['Red', 'Yellow', 'Red', 'Yellow'], 'Length':[20.1, 21.1, 19.1, 18.1],
'Group':[1,2,1,2]}
# Create DataFrame
df = pd.DataFrame(data)
for _c in df.select_dtypes(include=['object']).columns:
print(_c)
df[_c] = pd.Categorical(df[_c])
df_transformed = pd.get_dummies(df)
df_transformed
您还可以将显式列更改为分类列。 例如,我在这里更改Color
和Group
import pandas as pd
# intialise data of lists.
data = {'Color':['Red', 'Yellow', 'Red', 'Yellow'], 'Length':[20.1, 21.1, 19.1, 18.1],
'Group':[1,2,1,2]}
# Create DataFrame
df = pd.DataFrame(data)
columns_to_change = list(df.select_dtypes(include=['object']).columns)
columns_to_change.append('Group')
for _c in columns_to_change:
print(_c)
df[_c] = pd.Categorical(df[_c])
df_transformed = pd.get_dummies(df)
df_transformed
我知道我参加这个聚会迟到了,但是以自动方式对数据帧进行热编码的最简单方法是使用此功能:
def hot_encode(df):
obj_df = df.select_dtypes(include=['object'])
return pd.get_dummies(df, columns=obj_df.columns).values
我在我的声学模型中使用了这个:可能这对你的模型有帮助。
def one_hot_encoding(x, n_out):
x = x.astype(int)
shape = x.shape
x = x.flatten()
N = len(x)
x_categ = np.zeros((N,n_out))
x_categ[np.arange(N), x] = 1
return x_categ.reshape((shape)+(n_out,))
这对我有用:
pandas.factorize( ['B', 'C', 'D', 'B'] )[0]
输出:
[0, 1, 2, 0]
这是一个在不使用 numpy、pandas 或其他包的情况下进行 one-hot-encoding 的函数。 它需要一个整数、布尔值或字符串(可能还有其他类型)的列表。
import typing
def one_hot_encode(items: list) -> typing.List[list]:
results = []
# find the unique items (we want to unique items b/c duplicate items will have the same encoding)
unique_items = list(set(items))
# sort the unique items
sorted_items = sorted(unique_items)
# find how long the list of each item should be
max_index = len(unique_items)
for item in items:
# create a list of zeros the appropriate length
one_hot_encoded_result = [0 for i in range(0, max_index)]
# find the index of the item
one_hot_index = sorted_items.index(item)
# change the zero at the index from the previous line to a one
one_hot_encoded_result[one_hot_index] = 1
# add the result
results.append(one_hot_encoded_result)
return results
例子:
one_hot_encode([2, 1, 1, 2, 5, 3])
# [[0, 1, 0, 0],
# [1, 0, 0, 0],
# [1, 0, 0, 0],
# [0, 1, 0, 0],
# [0, 0, 0, 1],
# [0, 0, 1, 0]]
one_hot_encode([True, False, True])
# [[0, 1], [1, 0], [0, 1]]
one_hot_encode(['a', 'b', 'c', 'a', 'e'])
# [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1]]
我知道这个问题已经有很多答案了,但我注意到了两件事。 首先,大多数答案都使用像 numpy 和/或 pandas 这样的包。 这是一件好事。 如果您正在编写生产代码,您可能应该使用像 numpy/pandas 包中提供的健壮、快速的算法。 但是,为了教育起见,我认为有人应该提供一个具有透明算法的答案,而不仅仅是别人算法的实现。 其次,我注意到许多答案没有提供单热编码的稳健实现,因为它们不满足以下要求之一。 以下是有用、准确和健壮的 one-hot 编码功能的一些要求(如我所见):
one-hot 编码函数必须:
我测试了这个问题的许多答案,其中大多数都未能满足上述要求之一。
尝试这个:
!pip install category_encoders
import category_encoders as ce
categorical_columns = [...the list of names of the columns you want to one-hot-encode ...]
encoder = ce.OneHotEncoder(cols=categorical_columns, use_cat_names=True)
df_train_encoded = encoder.fit_transform(df_train_small)
df_encoded.head()
生成的数据帧df_train_encoded
与原始数据帧相同,但分类特征现在已替换为其单热编码版本。
有关category_encoders
的更多信息,请点击此处。
为了补充其他问题,让我提供一下我是如何使用 Numpy 使用 Python 2.0 函数完成的:
def one_hot(y_):
# Function to encode output labels from number indexes
# e.g.: [[5], [0], [3]] --> [[0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]]
y_ = y_.reshape(len(y_))
n_values = np.max(y_) + 1
return np.eye(n_values)[np.array(y_, dtype=np.int32)] # Returns FLOATS
n_values = np.max(y_) + 1
行可以硬编码,以供您使用大量神经元,以防您使用小批量。
使用此功能的演示项目/教程: https ://github.com/guillaume-chevalier/LSTM-Human-Activity-Recognition
它可以而且应该很简单:
class OneHotEncoder:
def __init__(self,optionKeys):
length=len(optionKeys)
self.__dict__={optionKeys[j]:[0 if i!=j else 1 for i in range(length)] for j in range(length)}
用法 :
ohe=OneHotEncoder(["A","B","C","D"])
print(ohe.A)
print(ohe.D)
扩展@Martin Thoma 的答案
def one_hot_encode(y):
"""Convert an iterable of indices to one-hot encoded labels."""
y = y.flatten() # Sometimes not flattened vector is passed e.g (118,1) in these cases
# the function ends up creating a tensor e.g. (118, 2, 1). flatten removes this issue
nb_classes = len(np.unique(y)) # get the number of unique classes
standardised_labels = dict(zip(np.unique(y), np.arange(nb_classes))) # get the class labels as a dictionary
# which then is standardised. E.g imagine class labels are (4,7,9) if a vector of y containing 4,7 and 9 is
# directly passed then np.eye(nb_classes)[4] or 7,9 throws an out of index error.
# standardised labels fixes this issue by returning a dictionary;
# standardised_labels = {4:0, 7:1, 9:2}. The values of the dictionary are mapped to keys in y array.
# standardised_labels also removes the error that is raised if the labels are floats. E.g. 1.0; element
# cannot be called by an integer index e.g y[1.0] - throws an index error.
targets = np.vectorize(standardised_labels.get)(y) # map the dictionary values to array.
return np.eye(nb_classes)[targets]
让我们假设在 10 个变量中,您的数据框中有 3 个分类变量,分别命名为 cname1、cname2 和 cname3。 然后以下代码将自动在新数据帧中创建一个热编码变量。
import category_encoders as ce
encoder_var=ce.OneHotEncoder(cols=['cname1','cname2','cname3'],handle_unknown='return_nan',return_df=True,use_cat_names=True)
new_df = encoder_var.fit_transform(old_df)
在 numpy 中使用矢量化的简单示例并在 pandas 中应用示例:
import numpy as np
a = np.array(['male','female','female','male'])
#define function
onehot_function = lambda x: 1.0 if (x=='male') else 0.0
onehot_a = np.vectorize(onehot_function)(a)
print(onehot_a)
# [1., 0., 0., 1.]
# -----------------------------------------
import pandas as pd
s = pd.Series(['male','female','female','male'])
onehot_s = s.apply(onehot_function)
print(onehot_s)
# 0 1.0
# 1 0.0
# 2 0.0
# 3 1.0
# dtype: float64
在这里,我尝试了这种方法:
import numpy as np
#converting to one_hot
def one_hot_encoder(value, datal):
datal[value] = 1
return datal
def _one_hot_values(labels_data):
encoded = [0] * len(labels_data)
for j, i in enumerate(labels_data):
max_value = [0] * (np.max(labels_data) + 1)
encoded[j] = one_hot_encoder(i, max_value)
return np.array(encoded)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.