python - TensorFlow:卷积网络中的维度不兼容错误

标签 python numpy machine-learning tensorflow

import tensorflow as tf
import numpy as np
import scipy as sci
import cv2
import input_data_conv


# Parameters
learning_rate = 0.001
training_iters = 200000
batch_size = 64
display_step = 20
n_classes=101 # number of classes

#Input data and classes
global train_data,train_class,test_data,test_classs,train_i,test_i
test_i, train_i = 0,0
train_data=input_data_conv.train_list_file
train_class=input_data_conv.train_single_classes
test_data=input_data_conv.test_single_frames
test_classs=input_data_conv.test_single_classes


# Network Parameters
n_input = [227, 227, 3 ]# MNIST data input (img shape: 227*227*3)
dropout = 0.5 # Dropout, probability to keep units

# tf Graph input
x = tf.placeholder(tf.float32, [None, 227,227,3])
y = tf.placeholder(tf.float32, [None, n_classes])
keep_prob = tf.placeholder(tf.float32) # dropout (keep probability)


def init_weights(shape):
    return tf.Variable(tf.random_normal(shape, stddev=0.01))

def conv2d(name, l_input, w, b,s):
    return tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(l_input, w, strides=[1, s, s, 1], padding='SAME'),b), name=name)

def max_pool(name, l_input, k,s):
    return tf.nn.max_pool(l_input, ksize=[1, k, k, 1], strides=[1, s, s, 1], padding='SAME', name=name)

def norm(name, l_input, lsize):
    return tf.nn.lrn(l_input, lsize, bias=1.0, alpha=0.0001 / 9.0, beta=0.75, name=name)

def vgg_single_frame(_X, _weights, _biases, _dropout):
    # Reshape input picture
    _X = tf.reshape(_X, shape=[-1, 227, 227, 3])

    conv1 = conv2d('conv1', _X, _weights['wc1'], _biases['bc1'],s=2)
    pool1 = max_pool('pool1', conv1, k=3,s=2)
    norm1 = norm('norm1', pool1, lsize=5)

    conv2 = conv2d('conv2', norm1, _weights['wc2'], _biases['bc2'],s=2)
    pool2 = max_pool('pool2', conv2, k=3,s=2)
    norm2 = norm('norm2', pool2, lsize=5)


    conv3 = conv2d('conv3', norm2, _weights['wc3'], _biases['bc3'],s=2)
    conv4 = conv2d('conv4', conv3, _weights['wc4'], _biases['bc4'],s=2)
    conv5 = conv2d('conv4', conv4, _weights['wc5'], _biases['bc5'],s=2)
    pool5 = max_pool('pool5', conv5, k=3,s=2)

    # Fully connected layer
    dense1 = tf.reshape(norm3, [-1, _weights['wd1'].get_shape().as_list()[0]]) # Reshape conv3 output to fit dense layer input
    dense1 = tf.nn.relu(tf.matmul(dense1, _weights['wd1']) + _biases['bd1'], name='fc6') # Relu activation
    dense1 = tf.nn.dropout(dense1, _dropout)
    dense2 = tf.nn.relu(tf.matmul(dense1, _weights['wd2']) + _biases['bd2'], name='fc7') # Relu activation
    dense2 = tf.nn.dropout(dense2, _dropout)

    # Output, class prediction
    out = tf.matmul(dense2, _weights['out']) + _biases['out']
    return out

weights = {
    'wc1': tf.Variable(tf.random_normal([7, 7, 1, 96])), # 7x7 conv, 1 input, 96 outputs ,stride 2
    'wc2': tf.Variable(tf.random_normal([5, 5, 96, 384])), # 5x5 conv, 32 inputs, 64 outputs
    'wc3': tf.Variable(tf.random_normal([3, 3, 384, 512])),#s 2 ,p a
    'wc4': tf.Variable(tf.random_normal([3, 3, 512, 512])),#s 2, p 1
    'wc5': tf.Variable(tf.random_normal([3, 3, 512, 384])),#s 2, p 1
    'wd1': tf.Variable(tf.random_normal([7*7*64, 4096])), # fully connected, 7*7*64 inputs, 1024 outputs
    'wd2': tf.Variable(tf.random_normal([4096, 4096])), # fully connected, 7*7*64 inputs, 1024 outputs
    'out': tf.Variable(tf.random_normal([4096, n_classes])) # 1024 inputs, 10 outputs (class prediction)
}

biases = {
    'bc1': tf.Variable(tf.random_normal([96])),
    'bc2': tf.Variable(tf.random_normal([384])),
    'bc3': tf.Variable(tf.random_normal([512])),
    'bc4': tf.Variable(tf.random_normal([512])),
    'bc5': tf.Variable(tf.random_normal([384])),
    'bd1': tf.Variable(tf.random_normal([4096])),
    'bd2': tf.Variable(tf.random_normal([4096])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

def train_next_batch(batch_size):
    temp_data=np.ndarray(shape=(batch_size,227,227,3),dtype=float)
    temp_data=np.ndarray(shape=(batch_size,n_classes),dtype=float)
    for num,x in train_data[train_i:train_i+batch_size]:
        temp_data[num,:,:,:]=cv2.imread(x,1)


pred = vgg_single_frame(x, weights, biases, keep_prob)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# Evaluate model
correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

# Initializing the variables
init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)
    step = 1
    # Keep training until reach max iterations
    while step * batch_size < training_iters:
        batch_xs, batch_ys = train_next_batch(batch_size)
        # Fit training using batch data
        sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys, keep_prob: dropout})
        if step % display_step == 0:
            # Calculate batch accuracy
            acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})
            # Calculate batch loss
            loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})
            print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + ", Training Accuracy= " + "{:.5f}".format(acc)
        step += 1
    print "Optimization Finished!"
    # Calculate accuracy for 256 mnist test images
    print "Testing Accuracy:", sess.run(accuracy, feed_dict={x: mnist.test.images[:256], y: mnist.test.labels[:256], keep_prob: 1.})

我想运行上面的代码并将大小为 [227, 227, 3] 的图像提供给该网络。但是,当我尝试构建网络时出现以下错误:

I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcublas.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcudnn.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcufft.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcurand.so locally
Traceback (most recent call last):
  File "/home/anilil/projects/pycharm-community-5.0.4/helpers/pydev/pydevd.py", line 2411, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/home/anilil/projects/pycharm-community-5.0.4/helpers/pydev/pydevd.py", line 1802, in run
    launch(file, globals, locals)  # execute the script
  File "/media/anilil/Data/charm/Cnn/build_vgg_model.py", line 104, in <module>
    pred = vgg_single_frame(x, weights, biases, keep_prob)
  File "/media/anilil/Data/charm/Cnn/build_vgg_model.py", line 50, in vgg_single_frame
    conv1 = conv2d('conv1', _X, _weights['wc1'], _biases['bc1'],s=2)
  File "/media/anilil/Data/charm/Cnn/build_vgg_model.py", line 38, in conv2d
    return tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(l_input, w, strides=[1, s, s, 1], padding='SAME'),b), name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_nn_ops.py", line 211, in conv2d
    use_cudnn_on_gpu=use_cudnn_on_gpu, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 655, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2042, in create_op
    set_shapes_for_outputs(ret)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1528, in set_shapes_for_outputs
    shapes = shape_func(op)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/common_shapes.py", line 187, in conv2d_shape
    input_shape[3].assert_is_compatible_with(filter_shape[2])
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_shape.py", line 94, in assert_is_compatible_with
    % (self, other))
ValueError: Dimensions Dimension(3) and Dimension(1) are not compatible

我假设权重变量 weights['wc1'] 的形状错误,但我不确定正确的是什么。

最佳答案

问题是您的输入图像(在 _X 中)有 3 个 channel (大概是红色、绿色和蓝色),而 conv1 层的卷积滤波器(在_weights['wc1']) 需要 1 个输入 channel 。

解决这个问题至少有两种可能:

  1. 重新定义 _weights['wc1'] 以接受 3 个输入 channel :

    weights = {
        'wc1': tf.Variable(tf.random_normal([7, 7, 3, 96])), # ...
        # ...
    }
    
  2. 使用 tf.image.rgb_to_grayscale() 操作将您的输入图像 _X 转换为具有 1 个输入 channel :

    _X = tf.image.rgb_to_grayscale(_X)
    

关于python - TensorFlow:卷积网络中的维度不兼容错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36286701/

相关文章:

Python3 将模块从文件夹导入到另一个文件夹

python - 张量值不正确

python - Windows 上的 Pandas read_csv 错误

python - 在两个数组中查找共同值的索引

machine-learning - 为具有 k-hot 标签的图像数据集创建 LMDB

python - 如何使用 yield 列出目录中的文件

python - GEMM 使用 Numpy einsum

python - Numpy AttributeError : 'float' object has no attribute 'exp'

python - 如何使用 Pattern 对西类牙语单词进行词形还原?

python - 将重新缩放层(或与此相关的任何层)添加到经过训练的 tensorflow keras 模型