且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

KERAS:如何使用与权重所需形状相同的张量显式设置Conv2D层的权重?

更新时间:2023-12-02 20:47:22

在具有急切执行力的Tensorflow 2.0中,您可以执行以下一项操作:

In Tensorflow 2.0 with eager execution, you might be able to do 1 of the below:

1)您可以在使用 set_weights 方法之前,在 Oconv1 上调用 build 方法.您将得到 ValueError ,因为权重该图层中的变量尚未初始化,因此该图层在构建之前无法通过 set_weights 接受任何权重.

1) You can call the build method on Oconv1 before using the set_weights method. You are getting the ValueError as the weights Variables in the layer are not yet initialized, hence the layer cannot take in any weights via set_weights before building.

Oconv1= Conv2D(512, (7, 7), activation='relu', padding='valid',use_bias=False)
input_shape = tf.TensorShape([None, h, w, c])  # to define h, w, c based on shape of layer input
Oconv1.build(input_shape)
Oconv1.set_weights([K])

2)您也可以将 weights kwarg传递到 Conv2D 构造函数中.

2) You can also pass in a weights kwarg into the Conv2D constructor.

Oconv1= Conv2D(512, (7, 7), activation='relu', padding='valid',use_bias=False,weights=[K])