首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Keras中没有for循环的One-hot编码

Keras中没有for循环的One-hot编码
EN

Stack Overflow用户
提问于 2020-03-09 07:26:56
回答 2查看 50关注 0票数 2

我想为一系列序列生成one-hot编码。

代码语言:javascript
复制
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数组

代码语言:javascript
复制
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循环?

EN

回答 2

Stack Overflow用户

发布于 2020-03-09 16:19:52

您可以简单地使用array-assignment -

代码语言:javascript
复制
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
票数 2
EN

Stack Overflow用户

发布于 2020-03-09 09:25:11

对于OHE练习,我总是使用:pd.get_dummies

下面是一个简单的例子:

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60593037

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档