形状必须是等级 4 但对于 '{{node Conv2D}} 是等级 2

Shape must be rank 4 but is rank 2 for '{{node Conv2D}}

我是 tensorflow 的新手,我正在尝试创建一个 cnn 并遇到此错误 ValueError: Shape must be rank 4 but is rank 2 for '{{node Conv2D}} = Conv2D[T=DT_FLOAT, data_format="NHWC", dilations=[1, 1, 1, 1], explicit_paddings=[], padding="SAME", strides=[1, 1, 1, 1], use_cudnn_on_gpu=true](concat, Variable_6/read)' with input shapes: [?,1568], [1568,784]. 这个错误与重量或输入有关,我该如何解决谢谢。 我的代码:

def conv2d(x, W, b, strides=1):
    # Conv2D wrapper, with bias and relu activation
    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 xavier_init(size):
  '''Xavier initialization.
  
  Args:
    - size: vector size
    
  Returns:
    - initialized random vector.
  '''
  in_dim = size[0]
  xavier_stddev = 1. / tf.sqrt(in_dim / 2.)
  return tf.random_normal(shape = size, stddev = xavier_stddev)

inputs = tf.concat(values = [x, m], axis = 1)
G_W1 = tf.Variable(xavier_init([dim*2, h_dim]))#[dim*2, h_dim]))  
G_b1 = tf.Variable(tf.zeros(shape = [h_dim]))
#in this layer a have the problem
conv1 = conv2d(inputs, G_W1, G_b1)

x 是 Tensor("Placeholder:0", shape=(?, 784), dtype=float32)
m 是 Tensor("Placeholder_1:0", shape=(?, 784), dtype=float32) 输入形状 (?, 1568)

我不确定您要做什么,但您确实需要阅读 docs 关于 conv2d 操作如何工作的内容,因为您正在尝试提供 2D 张量但实际上需要一个 4D 张量。无论如何,这是一个工作示例:

import tensorflow as tf

def conv2d(x, W, b, strides=1):
    # Conv2D wrapper, with bias and relu activation
    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 xavier_init(size):
  '''Xavier initialization.
  
  Args:
    - size: vector size
    
  Returns:
    - initialized random vector.
  '''
  in_dim = size[0]
  xavier_stddev = 1. / tf.sqrt(in_dim / 2.)
  return tf.random_normal(shape = size, stddev = xavier_stddev)

height, width, channels = 64, 64, 3
samples = 200
inputs = tf.random_normal(shape = (samples, height, width, channels))
G_W1 = tf.Variable(xavier_init([height, width, channels, channels]))
G_b1 = tf.Variable(tf.zeros(shape = [channels,]))
conv1 = conv2d(inputs, G_W1, G_b1)