【问题标题】:AttributeError:'InputLayer' object has no attribute 'W'AttributeError:“InputLayer”对象没有属性“W”
【发布时间】:2018-11-30 09:12:21
【问题描述】:

这是我的代码:

import itertools
import numpy as np
sentences = '''
sam is red
hannah not red
hannah is green
bob is green
bob not red
sam not green
sarah is red
sarah not green'''.strip().split('\n')
is_green = np.asarray([[0, 1, 1, 1, 1, 0, 0, 0]], dtype='int32').T
for s, g in zip(sentences, is_green):
 print(s, '->', g)
tokenize = lambda x: x.strip().lower().split(' ')
sentences_tokenized = [tokenize(sentence) for sentence in sentences]
words = set(itertools.chain(*sentences_tokenized))
word2idx = dict((v, i) for i, v in enumerate(words))
idx2word = list(words)
print('Vocabulary:')
print(word2idx, end='\n\n')
to_idx = lambda x: [word2idx[word] for word in x] # convert a list of words to a list of indices
sentences_idx = [to_idx(sentence) for sentence in sentences_tokenized]
sentences_array = np.asarray(sentences_idx, dtype='int32')
print('Sentences:')
print(sentences_array)
sentence_maxlen = 3
n_words = len(words)
n_embed_dims = 2
print('%d words per sentence, %d in vocabulary, %d dimensions for embedding' % (sentence_maxlen, n_words, n_embed_dims))
from keras.layers import Input, Embedding, merge, Flatten, Reshape, Lambda
import keras.backend as K
from keras.models import Model
input_sentence = Input(shape=(sentence_maxlen,), dtype='int32')
input_embedding = Embedding(n_words, n_embed_dims)(input_sentence)
avepool = Lambda(lambda x: K.mean(x, axis=1, keepdims=True), output_shape=lambda x: (x[0], 1))
color_prediction = avepool(Reshape((sentence_maxlen * n_embed_dims,))
(input_embedding))
predict_green = Model(inputs=[input_sentence], outputs=[color_prediction])
predict_green.compile(optimizer='sgd', loss='binary_crossentropy')
predict_green.fit([sentences_array], [is_green], epochs=5000, verbose=1)
embeddings = predict_green.layers[0].W.get_values()

运行此代码时出现以下错误:

AttributeError:'InputLayer' object has no attribute 'W'

这个错误在这里意味着什么?如何克服?

Python:3.6,Keras:2.2.4 和 2.2.0,后端:Theano。

【问题讨论】:

标签: python python-3.x keras nlp theano


【解决方案1】:

如果你想在训练后得到embeddings,那么你需要使用Embedding层的get_weights()方法(这是第二层而不是第一层):

embeddings = predict_green.layers[1].get_weights()

【讨论】:

    【解决方案2】:

    你的最后一行是embeddings = predict_green.layers[0].W.get_values()。 这意味着您希望来自 predict_green.layers[0] 的 InputLayer 具有属性 W。错误是说情况并非如此 - 您的 InputLayer 对象没有属性W

    您可以在此处阅读有关类属性的更多信息:https://www.geeksforgeeks.org/class-instance-attributes-python/

    【讨论】:

      猜你喜欢
      • 2018-07-07
      • 2018-10-19
      • 2012-12-01
      • 2021-04-19
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      相关资源
      最近更新 更多