reshape Error / ValueError:新数组的总大小必须保持不变

时间:2017-10-19 18:45:29

标签: python python-3.x

我有一个使用CNN进行图像分类的代码,因此有训练数据集和测试数据集。当我执行系统时,我有这个错误:

ValueError                                Traceback (most recent call last)
<ipython-input-44-cb7ec1a13881> in <module>()
      1 optimize(num_iterations=1)
      2 
----> 3 print_validation_accuracy()

<ipython-input-43-7f1a17e48e41> in print_validation_accuracy(show_example_errors, show_confusion_matrix)
     21 
     22         # Get the images from the test-set between index i and j.
---> 23         images = data.valid.images[i:j, :].reshape(batch_size, img_size_flat)
     24         #images = data.valid.images[i:j, :].reshape(1, 128)
     25 

ValueError: total size of new array must be unchanged

以及出现此错误的代码的步骤是:

def print_validation_accuracy(show_example_errors=False,
                        show_confusion_matrix=False):

    # Number of images in the test-set.
    num_test = len(data.valid.images)

    # Allocate an array for the predicted classes which
    # will be calculated in batches and filled into this array.
    cls_pred = np.zeros(shape=num_test, dtype=np.int)

    # Now calculate the predicted classes for the batches.
    # We will just iterate through all the batches.
    # There might be a more clever and Pythonic way of doing this.

    # The starting index for the next batch is denoted i.
    i = 0

    while i < num_test:
        # The ending index for the next batch is denoted j.
        j = min(i + batch_size, num_test)

        # Get the images from the test-set between index i and j.
        images = data.valid.images[i:j, :].reshape(batch_size, img_size_flat)

        # Get the associated labels.
        labels = data.valid.labels[i:j, :]

        # Create a feed-dict with these images and labels.
        feed_dict = {x: images,
                     y_true: labels}

        # Calculate the predicted class using TensorFlow.
        cls_pred[i:j] = session.run(y_pred_cls, feed_dict=feed_dict)

        # Set the start-index for the next batch to the
        # end-index of the current batch.
        i = j

    cls_true = np.array(data.valid.cls)
    cls_pred = np.array([classes[x] for x in cls_pred]) 

    # Create a boolean array whether each image is correctly classified.
    correct = (cls_true == cls_pred)

    # Calculate the number of correctly classified images.
    # When summing a boolean array, False means 0 and True means 1.
    correct_sum = correct.sum()

    # Classification accuracy is the number of correctly classified
    # images divided by the total number of images in the test-set.
    acc = float(correct_sum) / num_test

    # Print the accuracy.
    msg = "Accuracy on Test-Set: {0:.1%} ({1} / {2})"
    print(msg.format(acc, correct_sum, num_test))

    # Plot some examples of mis-classifications, if desired.
    if show_example_errors:
        print("Example errors:")
        plot_example_errors(cls_pred=cls_pred, correct=correct)

    # Plot the confusion matrix, if desired.
    if show_confusion_matrix:
        print("Confusion Matrix:")
        plot_confusion_matrix(cls_pred=cls_pred)

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

如错误消息所示,此声明中的重塑形式不匹配。

images = data.valid.images[i:j, :].reshape(batch_size, img_size_flat)

发生的事情是这个等式不相等,即 (j - i)*(data.valid.images的column_size)不等于batch_size * img_size_flat。 让它平等,问题就会解决。