【问题标题】:Building a Language Model Using Recurrent Neural Networks使用递归神经网络构建语言模型
【发布时间】:2016-08-27 22:42:08
【问题描述】:

我在运行代码时收到此错误。

例外:输入数组应具有与目标数组相同数量的样本。找到 12196 个输入样本和 1 个目标样本。

下面是我训练的模型。

from keras.models import Sequential
from keras.layers.core import Dense
from keras.utils import np_utils
from keras.layers.embeddings import Embedding
from keras.layers.recurrent import LSTM
from keras.regularizers import l2
from keras.layers.wrappers import TimeDistributed

n_in = x_train.shape[1]
n_hidden = 100
n_out = word_vecs.shape[0]
number_of_epochs = 10
batch_size = 35

model = Sequential()

model.add(Embedding(output_dim=word_vecs.shape[1],                 input_dim=word_vecs.shape[0],input_length=n_in,  weights=[word_vecs],  mask_zero=True))  

model.add(LSTM(n_hidden, W_regularizer=l2(0.0001), U_regularizer=l2(0.0001), return_sequences=True))

model.add(TimeDistributed(Dense(n_out, activation='softmax', W_regularizer=l2(0.0001))))


model.compile(loss='categorical_crossentropy', optimizer='rmsprop')

我还对我的火车数据的一个热向量进行了编码。

下面是代码

new_instance = []

for instance in train_y :
    new_vector = np.zeros(shape=(instance.shape[0],  word_vecs.shape[0]))

    print(instance.shape[0],  word_vecs.shape[0])

    new_vector[np.arange(new_vector.shape[0]), instance ] =1

new_instance.append(new_vector)
new_instance = np.array(new_instance)

这是我对一个热向量的输出

(260, 4075)
(260, 4075)
(260, 4075)
(260, 4075)
(260, 4075)
(260, 4075)
(260, 4075)
(260, 4075)
(260, 4075)
(260, 4075)
(260, 4075)
(260, 4075)
(260, 4075)
(260, 4075)
(260, 4075)

[[[ 1.  0.  0. ...,  0.  0.  0.]
  [ 1.  0.  0. ...,  0.  0.  0.]
  [ 1.  0.  0. ...,  0.  0.  0.]
  ..., 
  [ 0.  0.  0. ...,  0.  0.  0.]
  [ 0.  0.  0. ...,  0.  0.  0.]
  [ 0.  0.  1. ...,  0.  0.  0.]]]

最后

for epoch in range(number_of_epochs):    
        start_time = time.time()

        #Train for 1 epoch
        model.fit(train_x, new_instance, nb_epoch=1,  batch_size=batch_size, verbose=False, shuffle=True)   

        print("%.2f sec for training" % (time.time() - start_time))
        sys.stdout.flush()

我是新手,请原谅我。谢谢

【问题讨论】:

    标签: python-2.7 recurrent-neural-network


    【解决方案1】:

    一段时间后,我发现问题出在一个热向量编码代码中的错误缩进。我还减小了数据集 Size 的大小以使其更快地符合要求。

    以下是修正后的代码

    new_instance = []
    
    for instance in train_y :
        new_vector = np.zeros(shape=(instance.shape[0],  word_vecs.shape[0]))
    
        print(instance.shape[0],  word_vecs.shape[0])
    
        new_vector[np.arange(new_vector.shape[0]), instance ] =1
    
        new_instance.append(new_vector)
    new_instance = np.array(new_instance)
    

    【讨论】:

      猜你喜欢
      • 2021-02-05
      • 2020-05-03
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      • 2017-10-21
      • 1970-01-01
      • 2017-02-26
      相关资源
      最近更新 更多