

tensorflowでcnnをしようとモデルを作っていたのですがうまくできていないので質問させていただきます.

以下コードです

[code]

    import numpy as np
    import tensorflow as tf
    import tensorflow.python.platform
    
    def inference(image_placeholder, keep_prob):
    
      #define weight functioln
      def weight_variable(shape):
        initial = tf.truncated_normal(shape, stddev = 0.1)
          return tf.Variable(initial)
    
      #define bias function
      def bias_variable(shape):
        initial = tf.constant(0.1, shape = shape)
        return tf.Variable(initial)
    
      #define ConvNet function
      def conv2d(x,W):
        return tf.nn.conv2d(x,W,strides = [1,1,1,1],padding = 'VALID')
    
      #define max pooling
      def max_pool_nxn(x,n):
        return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
    
      #　reshape input array to 1,32,32,3
      x_images = tf.reshape(image_placeholder, [-1,32,32,3])
    
      #define model
    
      #ConvNet 1
      with tf.name_scope('conv1') as scope:
        W_conv1 = weight_variable([3, 3, 3, 32])
        b_conv1 = bias_variable([32])
        h_conv1 = tf.nn.relu(
                conv2d(x_images, W_conv1) +  b_conv1
            )
    
      #Pooling1
      with tf.name_scope('pool1') as scope:
        h_pool1 = max_pool_nxn(h_conv1,2)
    
      #ConvNet2
      with tf.name_scope('conv2') as scope:
        W_conv2 = weight_variable([3,3,32,64])
        b_conv2 = bias_variable([64])
        h_conv2 = tf.nn.relu(
                conv2d(h_pool1, W_conv2) +  b_conv2
            )
    
      #Pooling2
      with tf.name_scope('pool2') as scope:
        h_pool2 = max_pool_nxn(h_conv2,2)
    
      #　fully conected layer 1
      with tf.name_scope('fc1') as scope:
        W_fc1 = weight_variable([6 * 6 * 64, 1024])
        b_fc1 = bias_variable([1024])
        h_pool2_flat = tf.reshape(h_pool2, [-1, 6 * 6 * 64])
        h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
        h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
    
      # fully conected layer 2
      with tf.name_scope('fc2') as scope:
        W_fc2 = weight_variable([1024,20])
        b_fc2 = bias_variable([20])
    
      # softmax layer
      with tf.name_scope('softmax') as scope:
        y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
    
      return y_conv
    
    def loss(logits, labels):
      cross_entropy = -tf.reduce_sum(labels * 
      tf.log(tf.clip_by_value(logits, 1e-10, 1.0)))
      tf.summary.scalar("cross_entropy", cross_entropy)
      return cross_entropy
    
    def training(loss):
      train_step = 
      tf.train.AdamOptimizer(0.01).minimize(loss)
      return train_step
    
    def accuracy(logits, labels):
      correct_prediction = tf.equal(tf.argmax(logits, 1), 
      tf.argmax(labels, 1))
      accuracy = tf.reduce_mean(tf.cast(correct_prediction, 
      "float"))
      tf.summary.scalar("accuracy", accuracy)
      return accuracy
    
[/code]

以下学習のコードです

[code]

    image_placeholder = tf.placeholder(tf.float32, shape = (400, 32 * 32 * 3))
    label_placeholder = tf.placeholder(tf.float32, shape = (400, 20))
    keep_prob = tf.placeholder(tf.float32)
    
    
    logits = inference(image_placeholder, keep_prob)
    loss_value = loss(logits,label_placeholder)
    train_op = training(loss_value)
    acc = accuracy(logits, label_placeholder)
    
    
    
    with tf.Session() as sess:
      sess.run(tf.global_variables_initializer())
      for epoch in range(epochs):
        for batch in range(1250):
            x,t = train_generator.__next__()
            sess.run(train_op, feed_dict = {
                image_placeholder : x,
                label_placeholder   : t,
                keep_prob : 0.5
            })
    
        if epoch % 10 == 0:
            x_validarion, t_validation = validation_generator.__next__()
            train_accuracy = sess.run(acc, feed_dict = {
                image_placeholder : x_validation,
                label_placeholder : t_validation,
                keep_prob : 1.
            })
    
            print("step: {} , accracy{}".format(epoch + 1, train_accuracy))
    
    x_test, t_test = test_generator.__next__()
    test_acc = sess.run(acc, feed_dict = {
        image_placeholder : x_test,
        label_placeholder : t_test,
        keep_prob : 1.0
    })
    print("test accuracy : {}".format(test_acc))
    
[/code]

以下エラーです.

[code]

    ValueError                                Traceback 
    (most recent call last)
    <ipython-input-19-1528997ebea5> in <module>()
    19                 image_placeholder : x,
    20                 label_placeholder   : t,
    ---> 21                 keep_prob : 0.5
    22             })
    23 
    /usr/local/lib/python3.6/dist- 
    packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    927     try:
    928       result = self._run(None, fetches, feed_dict, options_ptr,
    --> 929                          run_metadata_ptr)
    930       if run_metadata:
    931         proto_data = 
    tf_session.TF_GetBuffer(run_metadata_ptr)
    
    /usr/local/lib/python3.6/dist- 
    packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    1126                              'which has shape %r' %
    1127                              (np_val.shape, subfeed_t.name,
    -> 1128                               
    str(subfeed_t.get_shape())))
    1129           if not self.graph.is_feedable(subfeed_t):
    1130             raise ValueError('Tensor %s may not be fed.' % subfeed_t)
    
    ValueError: Cannot feed value of shape (400, 32, 32, 3) for Tensor 'Placeholder_21:0', which has shape '(400, 3072)'
    
[/code]

モデルのでconv2dで出力のシェイプが悪いと思われるのですが,リファレンスを読んでみても何が間違っているのかわかりませんでした.  
よろしくお願いいたします.


CC BY-SA 4.0
2019-03-21T12:50:40.133
53629
2019-03-21T12:50:40.133
31609
question
tensorflow
tensorflowでcnnした時のエラーについて