我正在使用Colab创建一个简单的Keras模型,对其进行编译,训练,运行预测,然后尝试按照here所述保存模型
问题是我收到此错误:
FailedPreconditionError: Attempting to use uninitialized value input/kernel
[[Node: _retval_input/kernel_0_1 = _Retval[T=DT_FLOAT, index=1, _device="/job:localhost/replica:0/task:0/device:CPU:0"](input/kernel)]]
这是我的模特:
locModel = Sequential()
locModel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(240, 130,1), name='input'))
locModel.add(MaxPooling2D(pool_size=(2, 2)))
locModel.add(Conv2D(64, (3, 3), activation='relu'))
locModel.add(MaxPooling2D(pool_size=(2, 2)))
locModel.add(Conv2D(128, (2, 2), activation='relu'))
locModel.add(MaxPooling2D(pool_size=(2, 2)))
locModel.add(Flatten())
locModel.add(Dense(256, activation='relu'))
locModel.add(Dense(8, name='predicted_corners'))
sgd = SGD(lr=0.01, momentum=0.9, nesterov=True)
locModel.compile(loss='mean_squared_error',metrics=['accuracy'], optimizer=sgd)
培训:
hist = locModel.fit(imageData,
localization_labels,
epochs=100,
validation_split=0.2,
callbacks=[tbCallBack])
评估:
predictions = locModel.predict(testImages)
然后我尝试保存它,如上面的链接所述:
import tensorflow as tf
from keras import backend as K
KERAS_MODEL_NAME = "keras.hdf5"
# Save tf.keras model in HDF5 format.
tf.keras.models.save_model(locModel, KERAS_MODEL_NAME)
任何帮助表示赞赏!
TensorFlow版本: 1.10.0
Keras版本: 2.1.6
更新1:
locModel.save_weights('weights.h5')
完整无误-我的最终目标是转换为TFLite,所以我需要整个图形。
更新2:
为图层添加了初始化器:
locModel = Sequential()
locModel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(240, 130,1), name='input', kernel_initializer='random_uniform'))
locModel.add(MaxPooling2D(pool_size=(2, 2)))
locModel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='random_uniform'))
locModel.add(MaxPooling2D(pool_size=(2, 2)))
locModel.add(Conv2D(128, (2, 2), activation='relu', kernel_initializer='random_uniform'))
locModel.add(MaxPooling2D(pool_size=(2, 2)))
locModel.add(Flatten( ))
locModel.add(Dense(256, activation='relu'))
locModel.add(Dense(8, name='predicted_corners'))
sgd = SGD(lr=0.01, momentum=0.9, nesterov=True)
locModel.compile(loss='mean_squared_error',metrics=['accuracy'], optimizer=sgd)
上述更改后,出现以下错误
ValueError: Fetch argument <tf.Variable 'input_1/kernel:0' shape=(3, 3, 1, 32) dtype=float32_ref> cannot be interpreted as a Tensor. (Tensor Tensor("input_1/kernel:0", shape=(3, 3, 1, 32), dtype=float32_ref) is not an element of this graph.)
答案 0 :(得分:0)
更改自:
tf.keras.models.save_model(locModel, KERAS_MODEL_NAME)
变成:
keras.models.save_model(locModel, KERAS_MODEL_NAME)
您正在将tensorflow.keras与用于创建您的模型的keras软件包混合,这似乎是不允许的。确保重新启动笔记本计算机,以清除模型中的旧不一致之处。我遇到了完全相同的问题,一旦我对所有keras调用始终使用相同的程序包就起作用了。