Tensorflow 代码中的形状错误

Shape error in Tensorflow code

我想将 CNN 用于一维数据,因此决定使用 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")

有什么问题?

inputkernel 尺寸到 nn.conv1d 不正确。

来自API doc

  1. Input tensor should be of shape: [batch, in_width, num_input_channels]

  2. Kernel/weights should be of shape: [filter_width, num_input_channels, out_channels]

输入的形状为 [586,1,1040,1],应该是 [586, 1040, 1],内核在调用 new_conv_layer 时错误地定义了 num_input_channels。第一次调用应该是1,下次调用应该是6。