【发布时间】:2018-09-19 21:16:23
【问题描述】:
我想从张量中提取单个值并在保留反向传播的同时对其进行操作。我目前的实现:
import keras
from keras import backend as K
from keras.models import Model
from keras.layers import Dense, Activation, Input
import tensorflow as tf
input = Input(shape=(100,1), dtype='float32')
x = Dense(100)(input)
x = Activation('relu')(x)
x = Dense(5)(x)
x = Activation('tanh')(x)
start_pad = 40.0 + 5.0 * x[0] # important line
# ...
zs = K.arange(0.0, 1000, step=1.0)
zs = K.relu( zs - start_pad )
# ...
out = zs # + ...
out = Reshape( (trace_length,1) )(out)
model = Model(inputs = input, outputs = out)
然而, start_pad 似乎是一个张量,其维度为 x。运行上面的代码会报错:
ValueError:尺寸必须相等,但对于输入形状为 [1000]、[100,5] 的“sub”(操作:“Sub”)为 1000 和 5。
其中start_pad 对象是<tf.Tensor 'add_1:0' shape=(100, 5) dtype=float32>。
我希望start_pad 具有类似标量的值,并通过广播从zs 中减去。如何使用 Tensorflow/Keras 实现这一目标?
【问题讨论】:
-
在定义
start_pad的那一行,x的形状为(?, 100, 5),因为Keras添加了一个任意大小的初始batch维度,所以x[0]的形状为(100, 5)(层像Dense作用于最后一个维度)。不过,我不确定您要从x中提取什么值;例如,如果您使用x[0, 0, 0],您将获得第一个。
标签: python tensorflow keras