计算一个简单的tensorflow层



我有一个简单的tensorflow模型,我想把一个张量推过去,但是尽管我努力定义了一个初始化器,但模型声称它没有初始化。我需要对模型做些什么来把它放在一个我可以评估它的状态(即运行数学)?


import tensorflow as tf
import keras
from keras.layers import *
from keras.models import Model
import numpy as np
def tfDenseTest(dim1,dim2):
vecs_input = Input(shape=(dim1,dim2),dtype='float32')
user_att = Dense(100,activation='tanh', kernel_initializer= 'random_uniform', bias_initializer= 'random_uniform')(vecs_input)
model = Model(vecs_input,user_att)
return model
dim1 = 5
dim2 = 10
dense = tfDenseTest(dim1, dim2)
for layer in dense.layers:
print(layer.name, layer.output_shape, [w.shape for w in layer.get_weights()]) 
x = tf.convert_to_tensor(np.random.random((2,dim1,dim2)).astype('float32'))
dense(x).eval(session=tf.compat.v1.Session())

结果:

input_4 (None, 5, 10) []
dense_4 (None, 5, 100) [(10, 100), (100,)]  <-- dense layer has weights

FailedPreconditionError: Attempting to use uninitialized value dense_4/bias
[[{{node dense_4/bias/read}}]]
[[{{node model_4/dense_4/Tanh}}]]

.eval()仅在会话中启动图形模式时可调用。当您使用TF 2.x功能时,您可以使用.numpy()代替。

请看看这个:

import tensorflow as tf
import keras
from keras.layers import *
from keras.models import Model
import numpy as np
def tfDenseTest(dim1,dim2):
vecs_input = Input(shape=(dim1,dim2),dtype='float32')
user_att = Dense(100,activation='tanh', kernel_initializer= 'random_uniform', bias_initializer= 'random_uniform')(vecs_input)
model = Model(vecs_input,user_att)
return model
dim1 = 5
dim2 = 10
dense = tfDenseTest(dim1, dim2)
for layer in dense.layers:
print(layer.name, layer.output_shape, [w.shape for w in layer.get_weights()]) 
x = tf.convert_to_tensor(np.random.random((2,dim1,dim2)).astype('float32'))
#dense(x).numpy()
dense(x).numpy().shape
#dense(x).eval(session=tf.compat.v1.Session())

输出:

input_4 [(None, 5, 10)] []
dense_3 (None, 5, 100) [(10, 100), (100,)]
(2, 5, 100)

相关内容

  • 没有找到相关文章

最新更新