【发布时间】:2020-10-12 18:29:44
【问题描述】:
我正在尝试使用自定义层在 TensorFlow 中训练模型。 我的最后一层有问题,我正在尝试构建一个获取一批图像 [None,100,100,1] 并返回 10 个不同方形区域的总和的层,因此输出应该是 [None ,10]。
我尝试了一些不同的方法,但没有成功。 我试过了:
output = tf.concat([tf.reshape(tf.math.reduce_sum(inputs[34:42, 28:40,0]), [1,]),
tf.reshape(tf.math.reduce_sum(inputs[34:42, 44:56,0]), [1,]),
tf.reshape(tf.math.reduce_sum(inputs[34:42, 60:72,0]), [1,]),
tf.reshape(tf.math.reduce_sum(inputs[46:54, 20:32,0]), [1,]),
tf.reshape(tf.math.reduce_sum(inputs[46:54, 36:48,0]), [1,]),
tf.reshape(tf.math.reduce_sum(inputs[46:54, 52:64,0]), [1,]),
tf.reshape(tf.math.reduce_sum(inputs[46:54, 68:80,0]), [1,]),
tf.reshape(tf.math.reduce_sum(inputs[58:66, 28:40,0]), [1,]),
tf.reshape(tf.math.reduce_sum(inputs[58:66, 44:56,0]), [1,]),
tf.reshape(tf.math.reduce_sum(inputs[58:66, 60:72,0]), [1,])], axis= 0)
和类似的求和函数,但无法将形状的第一维设为“无”。
我尝试通过将输入重新整形为正确的形状然后乘以 0 并添加大小为 [10] 的张量来“作弊”。这得到了正确的形状,但模型没有训练。
有没有合适的方法来做到这一点?我在这个问题上被困了几个星期,没有运气。
如果我放置一个不符合我要求的不同层,但它具有正确的输出形状,模型训练得很好:
class output_layer(tf.keras.Model):
def __init__(self, shape_input):
self.shape_input = shape_input
super(output_layer, self).__init__()
def call(self, inputs):
inputs = tf.math.multiply(inputs,tf.math.conj(inputs))
temp = tf.math.reduce_sum(inputs, axis=2)
temp = tf.reshape(temp, [-1,10,10])
temp = tf.math.reduce_sum(temp, axis=2)
output = tf.cast(temp, tf.float32)
output = tf.keras.activations.softmax(output, axis=-1)
return output
如果有人能帮我解决这个问题,我将不胜感激!
谢谢!
【问题讨论】:
标签: python tensorflow neural-network tensorflow2.0