简体   繁体   中英

How to set kernel values for Keras convolutional layer in TF 2.0?

How can I set kernel values for Conv1D layer in TF 2.0?

model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv1D(1, 3, activation='relu', input_shape=(6, 1)))
inp = tf.reshape(tf.constant([1,3,3,0,1,2.]), (1, 6, 1))
print(f'{model(inp)}')
# [[[3.6809962 ]
#   [5.356483  ]
#   [2.4707034 ]
#   [0.94388485]]]

I'd like to get the same result as with mxnet:

conv = mx.gluon.nn.Conv1D(channels=1, kernel_size=3)

input_data = mx.nd.array((1,3,3,0,1,2))
kernel = mx.nd.array((2,0,1))

output_data = apply_conv(input_data, kernel, conv)
print(output_data)
# [[[5. 6. 7. 2.]]]

Data :

import numpy as np

input_data = np.array([1,3,3,0,1,2]).reshape((1,-1,1)) #(1 sample, length, 1 channel)
kernel = np.array([2,0,1]).reshape((3,1,1)) #(size, input_channels, output_channels)   
bias = np.zeros((1,)) # 1 channel

Model :

Give a name to the layer to make it easier.

model.add(tf.keras.layers.Conv1D(1, 3, activation='relu', input_shape=(6,1), name='the_layer'))

Set weights :

model.get_layer('the_layer').set_weights([kernel, bias])

Prediction :

output_data = model.predict(input_data)

If this is not supposed to be a trainable layer, use just a TF function for convolution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM