CNN中的Tensorflow可变动态尺寸

时间:2018-12-15 13:46:44

标签: python tensorflow machine-learning conv-neural-network

我的CNN的输出层应使用RBF函数,描述为“每个神经元输出其输入向量与其权重向量之间的欧几里得距离的平方”。我已经实现为

dense2 = tf.square(tf.norm(dense1 - tf.transpose(dense2_W)))

其中dense1是形状(?, 84)的张量。我尝试将权重dense2_W声明为形状(84, 10)的变量,因为它正在进行数字分类并且应该有10个输出。以100批运行代码,出现以下错误:InvalidArgumentError: Incompatible shapes: [100,84] vs. [10,84]。我相信这是由于相减。

我通过迭代以下代码来训练网络:

x_batch, y_batch = mnist.train.next_batch(100)
x_batch = tf.pad(x_batch, [[0,0],[2,2],[2,2],[0,0]]).eval()  # Pad 28x28 -> 32x32
sess.run(train_step, {X: x_batch, Y: y_batch})

,然后使用整个测试集对其进行测试,因此网络中的批次大小必须是动态的。

我该如何解决?像dense1一样,批处理大小必须是动态的,但是我不明白如何使用动态大小创建变量并进行转置(dense2_W)。

1 个答案:

答案 0 :(得分:1)

您需要两个张量的形状匹配。假设您要在批次中共享权重,并为每个输出类分别设置权重集,则可以对两个张量进行整形以正确广播,例如:

setTimeout

生成的张量5,5,5,5,5的形状应为 // construct the ASN1Sequence with r and s ByteArrayOutputStream outs = new ByteArrayOutputStream(); byte radd = (byte)(((signed[0] & 0x80) > 0) ? 1 : 0); byte sadd = (byte)(((signed[32] & 0x80) > 0) ? 1 : 0); byte length = (byte)(0x44 + radd + sadd); outs.write(0x30); outs.write(length); // length 68 bytes + outs.write(0x02); // ASN1Integer outs.write(0x20 + radd); // length 32 bytes if(radd > 0) outs.write(0x00); // positive val outs.write(signed, 0, 32); outs.write(0x02); // ASN1Integer outs.write(0x20 + sadd); // length 32 bytes if(sadd > 0) outs.write(0x00); // positive val outs.write(signed, 32, 32); signed = outs.toByteArray(); ,在您的情况下为# broadcasting will copy the input to every output class neuron input_dense = tf.expand_dims(dense1, axis=2) # broadcasting here will copy the weights across the batch weights = tf.expand_dims(tf.transpose(dense2_W), axis=0) dense2 = tf.square(tf.norm(input_dense - weights, axis=1)) (因此它将保存输出类别数量上每个数据实例的logit)

编辑:在dense2调用中添加了[batch_size, num_classes]参数,以便在隐藏维度(而不是整个矩阵)中计算距离。