2017-05-01 22 views
1

私はWindows 10、Python 3.5、およびtensorflow 1.1.0を使用しています。私は、次のスクリプトを持っている:Keras 2.x - レイヤーの重みを取得する

import tensorflow as tf 
import tensorflow.contrib.keras.api.keras.backend as K 
from tensorflow.contrib.keras.api.keras.layers import Dense 

tf.reset_default_graph() 
init = tf.global_variables_initializer() 
sess = tf.Session() 
K.set_session(sess) # Keras will use this sesssion to initialize all variables 

input_x = tf.placeholder(tf.float32, [None, 10], name='input_x')  
dense1 = Dense(10, activation='relu')(input_x) 

sess.run(init) 

dense1.get_weights() 

私はエラーを取得:AttributeError: 'Tensor' object has no attribute 'weights'

は私が間違って何をやっているが、どのように私はdense1の重みを得るのですか?私はthisthisの投稿を見ましたが、私はまだそれを動作させることはできません。

答えて

6

あなたが書く場合:

dense1 = Dense(10, activation='relu')(input_x)

はその後dense1は層ではない、それは層の出力です。層はDense(10, activation='relu')

あるので、あなたが意味するものと思われる:ここで

dense1 = Dense(10, activation='relu') 
y = dense1(input_x) 

がいっぱい抜粋です:

import tensorflow as tf 
from tensorflow.contrib.keras import layers 

input_x = tf.placeholder(tf.float32, [None, 10], name='input_x')  
dense1 = layers.Dense(10, activation='relu') 
y = dense1(input_x) 

weights = dense1.get_weights() 
+0

私は複数の層をしたい場合は、これを行うための適切な方法は何ですか?私。 'y = dense2(dense1(input_x)) 'より良い方法があります –

+0

この説明をありがとうございます。明快さを提供した。 –

5

あなたはすべての層の重みとバイアスを取得したい場合、あなたは、単に使用することができます:

for layer in model.layers: print(layer.get_config(), layer.get_weights()) 

これは関連するすべての情報を印刷します。

あなたは重みが直接numpyの配列として返され、あなたが使用することができますしたい場合:

first_layer_weights = model.layers[0].get_weights()[0] 
first_layer_biases = model.layers[0].get_weights()[1] 
second_layer_weights = model.layers[1].get_weights()[0] 
second_layer_biases = model.layers[1].get_weights()[1] 

など

関連する問題