python - 如何在 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.]]]
解决方案
资料:
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 函数进行卷积。
推荐阅读
- c - 从多个线程调用相同的函数
- xamarin - Xamarin.iOS.dll' 与此运行时不匹配,nfloat 映射为双精度,期望单精度
- php - 从 foreach 循环中删除数组项
- leaflet - 传单 - 仅加载一个图块
- php - 基于模式解析字符串
- django - 模板没有收到完整的上下文字典
- grafana - 从累计总数计算 Prometheus 中的 Mbps
- jquery - jQuery一个点击事件添加类
- python - TypeError:__init__() 缺少 2 个必需的位置参数:“消息”和“代码”
- postgresql - 为什么通过 Postgres file_fdw 从二进制文件查询比文本文件使用更多的主内存空间?