Python ConvNet 图像分类器 - 为二值图像分类拟合模型时出现“ValueError”

我是深度学习和 TensorFlow/Keras 的新手,所以我无法理解为什么我在尝试拟合模型以将图像分类为“狗”或“猫”时抛出错误。第一个代码块涉及创建和保存模型(使用 pickle),第二个代码块是训练实际卷积网络的部分。

下载图像数据库,保存到文件目录,编写模型训练分类器。代码如下:

import numpy as np

import matplotlib.pyplot as plt

import os

import cv2


DATADIR = "Pictures\\kagglecatsanddogs_3367a\\PetImages" 

#Workspace directory changed for posting

CATEGORIES = ["Dog", "Cat"]


#Iterate between all photos of dogs and cats

for category in CATEGORIES:

    path = os.path.join(DATADIR, category) #path to cats or dogs dir

    for img in os.listdir(path):

        img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) #Converts to grayscale, does not need color in this specific instance)

        plt.imshow(img_array, cmap = "gray")

        break

    break


#Print image dimensions

print(img_array.shape)


#All the images are different-shaped photos, so they must be normalized

#Everything must be made the same shape

#Decide on the image size you want to go with

IMG_SIZE = 180

new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))


training_data = []


def create_training_data(): #With goal of iterating through everything and building the dataset

    for category in CATEGORIES:

        path = os.path.join(DATADIR, category) #path to cats or dogs dir

        class_num = CATEGORIES.index(category)

        for img in os.listdir(path):

            try:

                img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) #Converts to grayscale, does not need color in this specific instance)

                new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))

                training_data.append([new_array, class_num])

            except Exception as e:

                pass


一只斗牛犬
浏览 100回答 4
4回答

青春有我

您应该对 y 的 numpy 数组进行转换过程,而不仅仅是 X。X = []y = []for features,label in training_data:    X.append(features)    y.append(label)print(X[0].reshape(-1, IMG_SIZE, IMG_SIZE, 1))X = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 1)y = np.array(y)

翻翻过去那场雪

import numpy as np X = np.array(X).reshape(-1,IMG_SIZE,IMG_SIZE,1)  y = np.array(y) import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Activation, Flattenfrom tensorflow.keras.layers import Conv2D, MaxPooling2Dimport pickle  . . .并继续。我也遇到过同样的问题,但它在将数据加载到 NumPy 数组后起作用,正如我通过添加定义 X 和 y 的额外行所提到的那样。

繁花不似锦

只需添加 y = np.array(y) 在您之后的最后一个程序中 #Load models generated in previous tutorial x = pickle.load(open("x.pickle", "rb")) y = pickle.load(open("y.pickle", "rb")) y = np.array(y) 

芜湖不芜

该模型期望输入采用 numpy 数组的形式。它收到的是一个整数列表。您必须将加载的数据转换为 numpy 数组,然后将它们传递到模型中
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python