Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何创建一个批生成器,用于训练具有不同长度的批大小序列的Keras模型>;1._Python_Keras_Nlp_Lstm - Fatal编程技术网

Python 如何创建一个批生成器,用于训练具有不同长度的批大小序列的Keras模型>;1.

Python 如何创建一个批生成器,用于训练具有不同长度的批大小序列的Keras模型>;1.,python,keras,nlp,lstm,Python,Keras,Nlp,Lstm,在我的训练数据中,长度为1,2,3的文本序列分布相当均匀。 我的目标数据是一个表示单词的热编码向量 示例数据 X = [[1,4,3], [1,4], [1],...] y = [0 0 0 0 1 0 0, 0 0 1 0 0 0 0, .............] 根据本文中的答案,我可以看到有两种方法可以在不使用填充的情况下使用不同长度的序列训练模型 一个是使用批量大小1训练模型,类似于上面文章中的解决方案,我也将在这里发布

在我的训练数据中,长度为1,2,3的文本序列分布相当均匀。 我的目标数据是一个表示单词的热编码向量

示例数据

 X = [[1,4,3],
      [1,4],
      [1],...]

 y = [0 0 0 0 1 0 0,
      0 0 1 0 0 0 0,
      .............]
根据本文中的答案,我可以看到有两种方法可以在不使用填充的情况下使用不同长度的序列训练模型

一个是使用批量大小1训练模型,类似于上面文章中的解决方案,我也将在这里发布

    class MyBatchGenerator(Sequence):
        'Generates data for Keras'
        def __init__(self, X, y, batch_size=1, shuffle=True):
            'Initialization'
            self.X = X
            self.y = y
            self.batch_size = batch_size
            self.shuffle = shuffle
            self.on_epoch_end()

        def __len__(self):
            'Denotes the number of batches per epoch'
            return int(np.floor(len(self.y)/self.batch_size))

        def __getitem__(self, index):
            return self.__data_generation(index)

        def on_epoch_end(self):
            'Shuffles indexes after each epoch'
            self.indexes = np.arange(len(self.y))
            if self.shuffle == True:
                np.random.shuffle(self.indexes)

        def __data_generation(self, index):
            Xb = np.empty((self.batch_size, *X[index].shape))
            yb = np.empty((self.batch_size, *y[index].shape))
            # naively use the same sample over and over again
            for s in range(0, self.batch_size):
                Xb[s] = X[index]
                yb[s] = y[index]
            return Xb, yb

model = Sequential()
model.add(Embedding(vocabulary_size, 64 , input_length=None))
model.add(LSTM(50,return_sequences=True))
model.add(LSTM(50))
model.add(Dense(50,activation='relu'))
model.add(Dense(vocabulary_size, activation='softmax'))
# compiling the network
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit_generator(MyBatchGenerator(X_train, y_train, batch_size=1), epochs=100)
如何修改
MyBatchGenerator
,使其返回与
batch\u size>1
相同长度的
batch\u size
序列