首页 > 解决方案 > 在张量中操作标量 (Tensorflow)

问题描述

我想从张量中提取单个值并在保留反向传播的同时对其进行操作。我目前的实现:

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 实现这一目标?

标签: pythontensorflowkeras

解决方案


好的,我找到的解决方案是

x = tf.unstack(x, axis=1)

它返回一个 tf 张量列表


推荐阅读