我想为一系列序列生成one-hot编码。
def encode_output(sequences, vocab_size):
y = np.zeros([sequences.shape[0], sequences.shape[1], vocab_size], dtype='int16')
for i in range(sequences.shape[0]):
y[i] = keras.utils.to_categorical(sequences[i], num_classes=vocab_size, dtype='int16')
return y序列是一个二维numpy数组
array([[ 23, 4, 563, ..., 0, 0, 0],
[3480, 3, 86, ..., 0, 0, 0],
[ 9, 930, 6, ..., 0, 0, 0],
...,
[ 507, 1408, 0, ..., 0, 0, 0],
[4447, 13, 642, ..., 0, 0, 0],
[ 1, 195, 2618, ..., 0, 0, 0]], dtype=int32)我的代码运行得很好,但也许有一种方法可以让它不使用for循环?
发布于 2020-03-09 16:19:52
您可以简单地使用array-assignment -
def encode_vectorized(a, n, dtype=int):
out = np.zeros(a.shape + (n,), dtype=dtype)
np.put_along_axis(out, a[...,None], 1, axis=-1)
return out发布于 2020-03-09 09:25:11
对于OHE练习,我总是使用:pd.get_dummies
下面是一个简单的例子:
import pandas as pd
s = pd.Series(list('abca'))
pd.get_dummies(s)
a b c
0 1 0 0
1 0 1 0
2 0 0 1
3 1 0 0资源:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html
https://stackoverflow.com/questions/60593037
复制相似问题