为什么keras层初始化不起作用

时间:2019-02-04 22:38:06

标签: tensorflow keras deep-learning

当我运行小型keras模型时,出现此错误

FailedPreconditionError:尝试使用未初始化的值bn6 / beta      [[{{node bn6 / beta / read}} = IdentityT = DT_FLOAT,_device =“ / job:localhost /副本:0 / task:0 / device:CPU:0”]]

full traceback error

代码:

"input layer"
command_input = keras.layers.Input(shape=(1,1))
image_measurements_features = keras.layers.Input(shape=(1, 640))
"command module"
command_module_layer1=keras.layers.Dense(128,activation='relu')(command_input)
command_module_layer2=keras.layers.Dense(128,activation='relu')(command_module_layer1)
"concatenation layer"
j=keras.layers.concatenate([command_module_layer2,image_measurements_features])
"desicion module"
desicion_module_layer1=keras.layers.Dense(512,activation='relu')(j)
desicion_module_layer2=keras.layers.Dense(256,activation='relu')(desicion_module_layer1)
desicion_module_layer3=keras.layers.Dense(128,activation='relu')(desicion_module_layer2)
desicion_module_layer4=keras.layers.Dense(3,activation='relu')(desicion_module_layer3)
initt = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(initt)
big_hero_4=keras.models.Model(inputs=[command_input, image_measurements_features], outputs=desicion_module_layer4)
big_hero_4.compile(optimizer='adam',loss='mean_squared_error',metrics=['accuracy'])
"train the model"
historyy=big_hero_4.fit([x, y],z,batch_size=None, epochs=1,steps_per_epoch=1000)

您对此错误有任何解决方案吗? 为什么keras在不使用全局变量初始值设定项的情况下不能自动初始化图层(错误在添加全局初始值设定项之前和之后存在)

2 个答案:

答案 0 :(得分:0)

您初始化模型,然后进行制作和编译。这是错误的顺序,首先定义模型,编译,然后初始化。相同的代码,只是顺序不同

答案 1 :(得分:0)

我让它起作用。忘记使用keras时的会话,只会使事情复杂化。

import keras
import tensorflow as tf
import numpy as np

command_input = keras.layers.Input(shape=(1,1))
image_measurements_features = keras.layers.Input(shape=(1, 640))

command_module_layer1 = keras.layers.Dense(128 ,activation='relu')(command_input)
command_module_layer2 = keras.layers.Dense(128 ,activation='relu')(command_module_layer1)

j = keras.layers.concatenate([command_module_layer2, image_measurements_features])

desicion_module_layer1 = keras.layers.Dense(512,activation='relu')(j)
desicion_module_layer2 = keras.layers.Dense(256,activation='relu')(desicion_module_layer1)
desicion_module_layer3 = keras.layers.Dense(128,activation='relu')(desicion_module_layer2)
desicion_module_layer4 = keras.layers.Dense(3,activation='relu')(desicion_module_layer3)

big_hero_4 = keras.models.Model(inputs=[command_input, image_measurements_features], outputs=desicion_module_layer4)
big_hero_4.compile(optimizer='adam',loss='mean_squared_error',metrics=['accuracy'])

# Mock data
x = np.zeros((1, 1, 1))
y = np.zeros((1, 1, 640))
z = np.zeros((1, 1, 3))

historyy=big_hero_4.fit([x, y], z, batch_size=None, epochs=1,steps_per_epoch=1000)

该代码应毫无问题地开始培训。如果仍然有相同的错误,则可能是由于代码的其他部分所致。