Tensorflow代码中的形状错误

时间:2018-05-14 12:37:58

标签: python tensorflow convolutional-neural-network

我想将CNN用于1D数据,因此决定使用conv1d图层。前两层很好,但是当我创建第二个转换层时,我有错误:

ValueError: Dimensions must be equal, but are 1 and 586 for 'conv1_43/conv1d/Conv2D' (op: 'Conv2D') with input shapes: [586,1,1040,1], [1,5,586,6].

这是我的日期形状:

trainX = dataX[0:616]
trainY = dataY[0:616]
testX = dataX[616:646]
testY = dataY[616:646]

trainX = np.expand_dims(trainX, axis=2)
testX = np.expand_dims(testX, axis=2)
#final shapes: train:(586,1040,1) test:(30,1040,1)

有代码:

def new_conv_layer(input, num_input_channels, filter_size, num_filters, name):

    with tf.variable_scope(name) as scope:
        # Shape of the filter-weights for the convolution
        shape = [filter_size, num_input_channels, num_filters]

        # Create new weights (filters) with the given shape
        weights = tf.Variable(tf.truncated_normal(shape, stddev=0.05))

        # Create new biases, one for each filter
        #biases = tf.Variable(tf.constant(0.05, shape=[num_filters]))

        # TensorFlow operation for convolution
        layer = tf.nn.conv1d(input, weights, 1, 'SAME')

        # Add the biases to the results of the convolution.
        #layer += biases

        return layer, weights


# Function for creating a new ReLU Layer

def new_relu_layer(input, name):

    with tf.variable_scope(name) as scope:
        # TensorFlow operation for convolution
        layer = tf.nn.relu(input)

        return layer

 # Convolutional Layer 1
layer_conv1, weights_conv1 = new_conv_layer(trainX, num_input_channels=586, filter_size=5, num_filters=6, name ="conv1")

# Pooling Layer 1new_pool_layer
layer_pool1 = max_pooling1d(layer_conv1, 3, 1, name="pool1")

# RelU layer 1
layer_relu1 = new_relu_layer(layer_pool1, name="relu1")

# Convolutional Layer 2
layer_conv2, weights_conv2 = new_conv_layer(input=layer_relu1, num_input_channels=1, filter_size=5, num_filters=16, name= "conv2")

# Pooling Layer 2
layer_pool2 = max_pooling1d(layer_conv2, 2, 1, name="pool2")

# RelU layer 2
layer_relu2 = new_relu_layer(layer_pool2, name="relu2")

什么问题?

1 个答案:

答案 0 :(得分:1)

input的{​​{1}}和kernel尺寸不正确。

来自API doc

  
      
  1. 输入张量应该是形状:nn.conv1d

  2.   
  3. 内核/重量应该是形状:[batch, in_width, num_input_channels]

  4.   

输入的形状为[filter_width, num_input_channels, out_channels]且应为[586,1,1040,1],并且在调用[586, 1040, 1]时内核错误地定义了num_input_channels。第一次通话时应为1,下次通话时应为6。