I'm new to tensorflow and I'm trying to create a cnn and got this error 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].
this error is related to weight or input, how can i solved this thank you .
My code :
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 is Tensor("Placeholder:0", shape=(?, 784), dtype=float32)
m is Tensor("Placeholder_1:0", shape=(?, 784), dtype=float32)
inputs shape (?, 1568)
CodePudding user response:
I am not sure what you are trying to do, but you really need to read the docs regarding how conv2d operations work, because you are trying to feed a 2D tensor but actually need a 4D tensor. Anyway, here is a working example:
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)
