首页 > 解决方案 > CIFAR-10 TensorFlow:InvalidArgumentError(参见上文的追溯):logits 和标签必须是可广播的

问题描述

我正在按如下方式实现 CNN,但出现此错误:

InvalidArgumentError(参见上面的回溯):logits 和标签必须是可广播的

我在下面附上了我的部分代码。我怀疑错误来自我的体重和偏差的形状和尺寸。

我想要实现的 - 我想将 CNN 层从两个完全连接的层减少到一个完全连接的层,意思是,out=tf.add(tf.add(fc1....)并停在那里。

nInput = 32
nChannels = 3
nClasses = 10

# Placeholder and drop-out
X = tf.placeholder(tf.float32, [None, nInput, nInput, nChannels])
Y = tf.placeholder(tf.float32, [None, nClasses])
keep_prob = tf.placeholder(tf.float32)

def conv2d(x, W, b, strides=1):
    x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
    x = tf.nn.bias_add(x, b)
    return tf.nn.relu(x)


def maxpool2d(x, k=2):
    return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')


def normalize_layer(pooling):
    #norm = tf.nn.lrn(pooling, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm1')
    norm = tf.contrib.layers.batch_norm(pooling, center=True, scale=True)
    return norm


def drop_out(fc, keep_prob=0.4):
    drop_out = tf.layers.dropout(fc, rate=keep_prob)
    return drop_out


weights = {
    'WC1': tf.Variable(tf.random_normal([5, 5, 3, 32]), name='W0'),
    'WC2': tf.Variable(tf.random_normal([5*5*32, 64]), name='W1'),
    #'WD1': tf.Variable(tf.random_normal([8 * 8 * 64, 64]), name='W2'),
    #'WD2': tf.Variable(tf.random_normal([64, 128]), name='W3'),
    'out': tf.Variable(tf.random_normal([64, nClasses]), name='W5')
}

biases = {
    'BC1': tf.Variable(tf.random_normal([32]), name='B0'),
    'BC2': tf.Variable(tf.random_normal([64]), name='B1'),
    #'BD1': tf.Variable(tf.random_normal([64]), name='B2'),
    #'BD2': tf.Variable(tf.random_normal([128]), name='B3'),
    'out': tf.Variable(tf.random_normal([nClasses]), name='B5')
}

def conv_net(x, weights, biases):
    conv1 = conv2d(x, weights['WC1'], biases['BC1'])
    conv1 = maxpool2d(conv1)
    conv1 = normalize_layer(conv1)

    #conv2 = conv2d(conv1, weights['WC2'], biases['BC2'])
    #conv2 = maxpool2d(conv2)
    #conv2 = normalize_layer(conv2)

    fc1 = tf.reshape(conv1, [-1, weights['WC2'].get_shape().as_list()[0]])
    fc1 = tf.add(tf.matmul(fc1, weights['WC2']), biases['BC2'])
    fc1 = tf.nn.relu(fc1)  # Using self-normalization activation
    fc1 = drop_out(fc1)

    #fc2 = tf.add(tf.matmul(fc1, weights['WD2']), biases['BD2'])
    #fc2 = tf.nn.selu(fc2)  # Using self-normalization activation
    #fc2 = drop_out(fc2)

    out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
    out = tf.nn.softmax(out)

    return out

标签: python-3.xtensorflowconv-neural-network

解决方案


我认为权重字典的“WC2”参数有问题。它应该是'WC2': tf.Variable(tf.random_normal([16*16*32, 64]), name='W1')

在应用1卷积和最大池操作之后,您正在对输入图像进行下采样32 x 32 x 316 x 16 x 3现在您需要展平这个下采样的输出,以将其作为输入提供给全连接层。这就是你需要通过的原因16*16*32


推荐阅读