python - 如何实现单热编码的生成器函数

标签 python deep-learning generator one-hot-encoding

我实现了一个生成器函数来生成一个热编码向量,但生成器实际上抛出了错误

我使用生成器函数来生成一个热编码向量,因为后者将用作深度学习 lstm 模型的输入。我这样做是为了避免在尝试对非常大的数据集创建一种热编码时出现过多的负载和内存故障。但是,我在生成器函数中没有遇到错误。我需要帮助来找出我哪里出了问题。

之前的代码:

X = np.zeros((len(sequences), seq_length, vocab_size), dtype=np.bool)
y = np.zeros((len(sequences), vocab_size), dtype=np.bool)
for i, sentence in enumerate(sequences):
    for t, word in enumerate(sentence):
        X[i, t, vocab[word]] = 1
    y[i, vocab[next_words[i]]] = 1

这里,

sequences = sentences generated from data set
seq_length = length of each sentence(this is constant)
vocab_size = number of unique words in dictionary

My program when run on the large data set produces,

sequences = 44073315
seq_length = 30
vocab_size = 124958

因此,当上面的代码直接用于后面的输入时,会出现 beloe 错误。

Traceback (most recent call last):
  File "1.py", line 206, in <module>
    X = np.zeros((len(sequences), seq_length, vocab_size), dtype=np.bool)
MemoryError
(my_env) [rjagannath1@login ~]$

所以,我尝试创建一个生成器函数(用于测试),如下 -

def gen(batch_size, no_of_sequences, seq_length, vocab_size):
    bs = batch_size
    ns = no_of_sequences
    X = np.zeros((batch_size, seq_length, vocab_size), dtype=np.bool)
    y = np.zeros((batch_size, vocab_size), dtype=np.bool)
    while(ns > bs):
        for i, sentence in enumerate(sequences):
            for t, word in enumerate(sentence):
                X[i, t, vocab[word]] = 1
            y[i, vocab[next_words[i]]] = 1
        print(X.shape())
        print(y.shape())
        yield(X, y)
        ns = ns - bs 

for item in gen(1000, 44073315, 30, 124958):
    print(item) 

但我收到以下错误 -

File "path_of_file", line 247, in gen
    X[i, t, vocab[word]] = 1

IndexError: index 1000 is out of bounds for axis 0 with size 1000

我在生成器函数中犯了什么错误?

最佳答案

在生成器中进行如下修改:

batch_i = 0
while(ns > bs):
    s = batch_i*batch_size
    e = (batch_i+1)*batch_size
    for i, sentence in enumerate(sequences[s:e]):

基本上,您希望在 batch_size 大小的窗口上运行,因此您可以通过 sequences 制作一个运行切片,这似乎是您的整个数据集。

您还必须增加batch_i,将其放在yield之后,因此添加 batch_i+=1

关于python - 如何实现单热编码的生成器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55528001/

相关文章:

python - 为什么 cross_validate 返回 NaN 分数?

tensorflow - 多任务网络中ValueError : Shape must be rank 0 but is rank 1

python - 如何修改填充向量的 seq2seq 成本函数?

Python 生成器 : understanding the order of execution

python - 无限 python 生成器

python - 如何使 macports python 使用自己的软件包而不是其他安装的软件包?

python - 如何在Python中高效清空DBM文件?

python - 执行生成器表达式的最pythonic方式是什么?

python - python中定时器的一些误解

python - 在tensorflow/keras中,为什么使用predict_on_batch训练后重新计算时train_on_batch输出损失不同?