【问题标题】:First timer problems, multidimensional Output第一个计时器问题,多维输出
【发布时间】:2018-01-18 23:07:15
【问题描述】:

我是 Keras 和 LSTM 的新手,但对其他 NN 并不陌生。 目标是将句子的各个部分分为 4 个相互排斥的类别。我想使用 LTSM 将句子的单词打分到使用单词周围的上下文分配给它的标签上。例如:

[胡萝卜豌豆牛肉鸡胆小鸡]

到:

[食物食物食物人人]

我的输入向量是我通过嵌入运行的单词数组。然后我想给 LSTM 提供单词,并在输出分类上对其进行训练,这样它就可以了解在什么上下文中哪些单词属于哪些类别。

    x_in = [[2,6,3,74,45,...], [...], ...]
    y_in = [[0,0,0,1], [0,1,0,0], [...], ...]
    x_in_padded =  pad_sequences(x_in, maxlen=max_len, padding='post')
    model = Sequential()
    model.add(Embedding(len(words), 128))  # examples use 128 or 256...
    model.add(LSTM(4,  return_sequences=True))   #try a 4-word context
    model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

    print model.summary()
    model.fit(x_in_padded, y_in, batch_size=16, epochs=10)
    loss, accuracy = model.evaluate(x_in_padded, y_in, batch_size=16)

但是我得到了:

ValueError: Error when checking target: 
expected dense_1 to have 3 dimensions, but got array with shape (968, 1)

968 是 x_in_padded 中的句子数和 y_in 中的向量。我做错了什么?

** 更新 **

我一直在对其进行迭代,但仍然存在嵌入和 LSTM 层维度的问题。这是代码,我已经将其作为一个独立的示例。当前错误为:ValueError: setting an array element with a sequence. 启动 Epoch 后。

from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Embedding
from keras.layers import LSTM
from keras.utils import to_categorical
from keras.preprocessing.sequence import pad_sequences
from keras.utils.layer_utils import print_summary
import numpy as np

sentences = [
    ['the', 'imdb', 'review', 'data', 'does', 'have', 'a', 'one', 'dimensional', 'spatial', 'structure', 'in', 'the', 'sequence'],
    ['of', 'words', 'in', 'reviews', 'and', 'the', 'cnn', 'may', 'be', 'able', 'to', 'pick', 'out'],
    ['invariant', 'features', 'for', 'good', 'and', 'bad', 'sentiment', 'this', 'learned', 'spatial'],
    ['features', 'may', 'then', 'be', 'learned', 'as', 'sequences', 'by', 'an', 'lstm', 'layer']
]
    outputs = [
    ['class1', 'class1', 'class1', 'class1', 'class1', 'class1', 'class1', 'class1', 'class1', 'class1', 'class1', 'class2', 'class2', 'class2'],
    ['class2', 'class2', 'class2', 'class2', 'class1', 'class1', 'class1', 'class1', 'class1', 'class1', 'class2', 'class2', 'class2'],
    ['class1', 'class1', 'class2', 'class2', 'class2', 'class2', 'class2', 'class1', 'class1', 'class1'],
    ['class1', 'class1', 'class1', 'class1', 'class1', 'class1', 'class1', 'class2', 'class2', 'class2', 'class2']
]

words = sorted(list(words))
x_in = [ [words.index(word) for word in sentence] for sentence in sentences ]

out_classes = {'class1': [1,0], 'class2': [0,1]}
y_in = [ [ out_classes[sentence[i]] for i in range(len(sentence))] for sentence in outputs]

max_len = max([len(sentence) for sentence in sentences])

x_in_padded =  pad_sequences(x_in, maxlen=max_len, padding='post')
x_in_padded = np.reshape(x_in_padded, (x_in_padded.shape[0], x_in_padded.shape[1], 1)) #x_in_padded.shape +(1,))
print "x_in:"
print x_in_padded[2]
print x_in_padded.shape

print "y_in:"
y_in = np.array(y_in)

model = Sequential()
model.add(LSTM(4, return_sequences=False, input_shape=(None, 1)))
model.add(Dense(len(out_classes),  activation="softmax"))
model.compile(loss='sparse_categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

print_summary(model)
model.fit(x_in_padded, y_in, epochs=10)
loss, accuracy = model.evaluate(x_in_padded, y_in)

我目前的错误是: ValueError: 使用序列设置数组元素。

【问题讨论】:

    标签: machine-learning keras deep-learning lstm recurrent-neural-network


    【解决方案1】:

    这里有两件事:

    model.add(LSTM(4, return_sequences=True))   #try a 4-word context
    

    此行输出通过默认tanh 激活传递的数字。这对你的任务是不合理的。在网络顶部添加来自Dense 层的softmax 输出:

    model.add(LSTM(10, return_sequences=True))   #10 is arbitrary - try other values.
    model.add(Dense(4, activation='softmax')) # Output layer.
    

    另一件事是你的损失。对于多类分类任务,您应该使用categorical_crossentropy 的一些变体。如果你的目标是ints 的序列,你应该使用sparse_categorical_crossentropy

    model.compile(loss='sparse_categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
    

    【讨论】:

    • 谢谢你,是的,我明白这是有道理的。我已经进行了调整,但仍然收到原始错误:ValueError: Error when checks target: expected dense_1 to have 3 dimensions, but got array with shape (968, 1)
    • 已添加。感谢您查看此内容。
    • 你没有改变损失。
    • 我试过 sparse_ 而不是 sparse。如果我使用 sparse_ 它会说: ValueError: Error when checks target: Expected dense_1 to have 3 dimensions, but got array with shape (968, 1) 但是keras.io/losses 说“注意:使用 categorical_crossentropy 损失时,您的目标应该是以分类格式(例如,如果您有 10 个类,则每个样本的目标应该是一个全零的 10 维向量,除了对应于样本类的索引处的 1)。
    • 该注释让我认为 categorical_crossentropy 用于 1-hot 编码,这就是我正在使用的。
    猜你喜欢
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 2014-05-27
    • 2022-08-18
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多