【发布时间】:2021-01-28 18:04:53
【问题描述】:
class SimpleDense(Layer):
def __init__(self, units=1, name='SimpleDense', **kwargs):
'''Initializes the instance attributes'''
super(SimpleDense, self).__init__()
self.units = units
super(SimpleDense, self).__init__(**kwargs)
def build(self, input_shape):
'''Create the state of the layer (weights)'''
# initialize the weights
w_init = tf.random_normal_initializer()
self.w = tf.Variable(name="kernel",
initial_value=w_init(shape=(input_shape[-1], self.units),
dtype='float32'),
trainable=True)
# initialize the biases
b_init = tf.zeros_initializer()
self.b = tf.Variable(name="bias",
initial_value=b_init(shape=(self.units,), dtype='float32'),
trainable=True)
def call(self, inputs):
'''Defines the computation from inputs to outputs'''
return tf.matmul(inputs, self.w) + self.b
def get_config(self):
config = super().get_config().copy()
config.update({
'units': self.units,
})
return config
my_layer = SimpleDense(units=1)
model = tf.keras.Sequential([my_layer])
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(xs, ys, epochs=500, verbose=1)
tf.keras.models.save_model(model, os.path.join(model_path, 'my_model'), save_format='h5')
cls.model = tf.keras.models.load_model(model_path + "/my_model", custom_objects={'SimpleDense': SimpleDense})
当我运行上面的代码时,我在尝试加载模型时不断收到此错误:ValueError: Attempt to convert a value (None) with an unsupported type (<class 'NoneType'>) to a Tensor.
我有使用 numpy==1.18.1 的限制,所以我无法升级 tensorflow,有没有办法解决这个问题或某种解决方法?谢谢。
【问题讨论】:
-
也许您应该在保存模型时使用相同的模块。你试过
tf.keras.models.save() -
我确实做到了,它给出了同样的错误,我编辑了我的问题,因为这样更有意义,但我尝试了各种保存方法,但找不到有效的解决方案。
标签: python python-3.x tensorflow tensorflow2.0