简体   繁体   中英

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

Here is my code:

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()

While running this code I am getting the following error:

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

What does this error mean here? How to overcome this?

Python:3.6, Keras: 2.2.4 & 2.2.0, backend: Theano.

如果要在训练后获取嵌入,则需要使用Embedding层(第二层而不是第一层get_weights()方法:

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

Your last line reads embeddings = predict_green.layers[0].W.get_values() . This implies that you expect the InputLayer from predict_green.layers[0] to have an attribute W . The error is saying this is not the case - your InputLayer object does not have an attribute W .

You can read more about class attributes here: https://www.geeksforgeeks.org/class-instance-attributes-python/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM