python - One-hot encodings in Keras without for loops
问题描述
I want to generate one-hot encodings for a list of sequences.
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
Sequences is a 2-D numpy array
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)
My code works fine, but maybe there is a way to make it without for loop?
解决方案
你可以简单地使用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
推荐阅读
- webpack - 由于基础,无法指向正确的捆绑包
- angular - 是否可以在不使用第三方链接的情况下使用 typescript 获取公共 IP 地址
- javascript - Angular:错误 TS2322:类型 'Observable<{}>' 不可分配 ... 使用 share() 运算符
- python - ValueError:无法为具有形状“(?,1)”的张量“Placeholder_37:0”提供形状(891,)的值
- python-2.7 - 使用 Selenium Python 复制文本字段值时,HTML 表单不返回剪贴板?
- ios - 为 iPhone 应用程序获取 .IPA 文件
- c++ - 从 .ini 加载数据使我的游戏崩溃!我能做些什么?C++
- spring-mvc - 设置了 DB 毫秒值的 Spring 调度程序
- c# - 将字符串分隔到不在集合字典中的列表中
- java - 具有 2 个过滤条件的 java 流