【问题标题】:TensorFlow (Neural Network) FC output sizeTensorFlow(神经网络)FC输出大小
【发布时间】:2017-11-25 20:09:01
【问题描述】:

不确定我的问题是特定于 TF 还是只是一般的 NN,但我已经使用 tensorflow 创建了一个 CNN。我无法理解为什么我的全连接层上的输出大小是这样的。

X = tf.placeholder(tf.float32, [None, 32, 32, 3])
y = tf.placeholder(tf.int64, [None])
is_training = tf.placeholder(tf.bool)

# define model
def complex_model(X,y,is_training):

    # conv layer
    wconv_1 = tf.get_variable('wconv_1', [7 ,7 ,3, 32])
    bconv_1 = tf.get_variable('bconv_1', [32])

    # affine layer 1
    w1 = tf.get_variable('w1', [26*26*32//4, 1024])  #LINE 13
    b1 = tf.get_variable('b1', [1024])

    # batchnorm params   

    bn_gamma = tf.get_variable('bn_gamma', shape=[32]) #scale
    bn_beta = tf.get_variable('bn_beta', shape=[32] ) #shift

    # affine layer 2
    w2 = tf.get_variable('w2', [1024, 10])
    b2 = tf.get_variable('b2', [10])


    c1_out = tf.nn.conv2d(X, wconv_1, strides=[1, 1, 1, 1], padding="VALID") + bconv_1
    activ_1 = tf.nn.relu(c1_out)

    mean, var = tf.nn.moments(activ_1, axes=[0,1,2], keep_dims=False)
    bn = tf.nn.batch_normalization(act_1, mean, var, bn_gamma, bn_beta, 1e-6)
    mp = tf.nn.max_pool(bn, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    affine_in_flat = tf.reshape(mp, [-1, 26*26*32//4])

    affine_1 = tf.matmul(affine_in_flat, w1) + b1
    activ_2 = tf.nn.relu(affine_1)

    affine_2 = tf.matmul(activ_2, w2) + b2
    return affine_2

    #print(affine_2.shape)

在第 13 行中,我设置了 w1 的值,我本来希望只放:

w1 = tf.get_variable('w1', [26*26*32, 1024])

但是,如果我使用上面显示的行和

运行代码
affine_in_flat = tf.reshape(mp, [-1, 26*26*32])

我的输出大小是 16,10 而不是 64,10,这是我在下面的初始化情况下所期望的:

x = np.random.randn(64, 32, 32,3)
with tf.Session() as sess:
    with tf.device("/cpu:0"): #"/cpu:0" or "/gpu:0"
        tf.global_variables_initializer().run()
        #print("train", x.size, is_training, y_out)
        ans = sess.run(y_out,feed_dict={X:x,is_training:True})
        %timeit sess.run(y_out,feed_dict={X:x,is_training:True})
        print(ans.shape)
        print(np.array_equal(ans.shape, np.array([64, 10])))

谁能告诉我为什么我需要将 w1[0] 的大小除以 4?

【问题讨论】:

    标签: machine-learning tensorflow neural-network computer-vision conv-neural-network


    【解决方案1】:

    为bn 和mp 添加print 语句我得到:

    bn:<tf.Tensor 'batchnorm/add_1:0' shape=(?, 26, 26, 32) dtype=float32>

    mp:<tf.Tensor 'MaxPool:0' shape=(?, 13, 13, 32) dtype=float32>

    这似乎是由于最大池中的strides=[1, 2, 2, 1](但要保持26, 26,您还需要padding='SAME')。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-14
      • 2016-10-21
      • 2021-12-15
      • 1970-01-01
      • 2015-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多