这是我的代码:
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。
答案 0 :(得分:2)
如果要在训练后获取嵌入,则需要使用get_weights()
层(这是第二层而不是第一层)的Embedding
方法:
embeddings = predict_green.layers[1].get_weights()
答案 1 :(得分:0)
您的最后一行显示为embeddings = predict_green.layers[0].W.get_values()
。
这意味着您期望predict_green.layers[0]
的InputLayer具有属性W
。该错误表明情况并非如此-您的InputLayer对象没有属性W
。
您可以在此处了解有关类属性的更多信息:https://www.geeksforgeeks.org/class-instance-attributes-python/