如何有效地将布尔值 table 转换为一个热向量?
How can I convert a boolean table to one hot vectors efficiently?
假设我有一个 table 看起来像这样的东西 -
Movie Action Scifi Drama Romance
Abc True False False False
Def False False True False
Ghi False False False True
我想将它转换成一个热向量,这样
Abc - [1 0 0 0]'
Def - [0 0 1 0]'
Ghi - [0 0 0 1]'
已知只有一列可以为True。
在python中有没有有效的方法来做到这一点?
您可以使用 numpy
来做到这一点。
import numpy as np
Abc = np.array([True,False,False,False])
Def = np.array([False,False,True,False])
Ghi = np.array([False,False,False,True])
movies = np.array([Abc, Def, Ghi])
print("Input:")
print(movies)
#casting from boolean to integer
result = np.array(movies, dtype=np.int)
print("Output:")
print(result)
好的,所以我找到了一种方法来为更大的数据集执行此操作。
df['genre'] = pd.Series(np.random.randn(size), index=df.index)
for i in range(len(df)):
if df.iloc[i]['action'] == True:
df.at[i, 'genre'] = 0
elif df.iloc[i]['scifi'] == True:
df.at[i, 'genre'] = 1
elif df.iloc[i]['drama'] == True:
df.at[i, 'genre'] = 2
elif df.iloc[i]['romance'] == True:
df.at[i, 'genre'] = 3
因此,通过这样做,我们将在名为 'genre' 的数据框中创建一个新列并为其赋予适当的值。之后,
y = df['genre']
import tensorflow as tf
y_categorical = tf.keras.utils.to_categorical(y)
这将完成将其转换为一个热向量的工作。
假设我有一个 table 看起来像这样的东西 -
Movie Action Scifi Drama Romance
Abc True False False False
Def False False True False
Ghi False False False True
我想将它转换成一个热向量,这样
Abc - [1 0 0 0]'
Def - [0 0 1 0]'
Ghi - [0 0 0 1]'
已知只有一列可以为True。
在python中有没有有效的方法来做到这一点?
您可以使用 numpy
来做到这一点。
import numpy as np
Abc = np.array([True,False,False,False])
Def = np.array([False,False,True,False])
Ghi = np.array([False,False,False,True])
movies = np.array([Abc, Def, Ghi])
print("Input:")
print(movies)
#casting from boolean to integer
result = np.array(movies, dtype=np.int)
print("Output:")
print(result)
好的,所以我找到了一种方法来为更大的数据集执行此操作。
df['genre'] = pd.Series(np.random.randn(size), index=df.index)
for i in range(len(df)):
if df.iloc[i]['action'] == True:
df.at[i, 'genre'] = 0
elif df.iloc[i]['scifi'] == True:
df.at[i, 'genre'] = 1
elif df.iloc[i]['drama'] == True:
df.at[i, 'genre'] = 2
elif df.iloc[i]['romance'] == True:
df.at[i, 'genre'] = 3
因此,通过这样做,我们将在名为 'genre' 的数据框中创建一个新列并为其赋予适当的值。之后,
y = df['genre']
import tensorflow as tf
y_categorical = tf.keras.utils.to_categorical(y)
这将完成将其转换为一个热向量的工作。