首页 > 解决方案 > 如何在 TF 2.0 中为 Keras 卷积层设置内核值?

问题描述

如何在 TF 2.0 中为 Conv1D 层设置内核值?

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]]]

我想得到与 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.]]]

标签: pythontensorflowkerasconv-neural-network

解决方案


资料

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.add(tf.keras.layers.Conv1D(1, 3, activation='relu', input_shape=(6,1), name='the_layer'))

设置权重

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

预测

output_data = model.predict(input_data)

如果这不应该是可训练层,则仅使用 TF 函数进行卷积。


推荐阅读