0

我想使用 keras 创建一个图像分类器,并用一些示例图像对其进行训练。然后,我将使用预训练模型并在最后添加几层,但首先,我想了解 keras 和 CNN。

我的控制台打印以下错误:

ValueError:检查目标时出错:预期dense_2具有形状(None,2)但得到形状为(321、3)的数组

这是我的代码:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys
import time

import numpy as np
import cv2
import time
from PIL import Image

import keras
import glob
from keras.models import Sequential
from keras.models import load_model
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import SGD
from sklearn.preprocessing import LabelBinarizer


labels = ['buena', 'mala', 'otro']

def to_one_hot(labels, ys):
    result = np.zeros((len(ys),len(labels)))
    for i in range(result.shape[0]):
        for j in range(result.shape[1]):
            result[i,j] = int(ys[i] == labels[j])
    return result

def build_dataset(labels):
    num_classes = len(labels)
    x = []
    y = []
    for label in labels:
        for filename in (glob.glob('./tf_files/papas_fotos/'+label+'/*.jpg')):
            img = cv2.imread(filename)
            img = np.resize(img,(100,100, 3))
            x.append(img)
            y.append(label)
    y = to_one_hot(labels, y)
    # y = keras.utils.to_categorical(y, num_classes=3)
    x = np.array(x)
    x_train = x[20:]
    y_train = y[20:]
    x_test = x[:19]
    y_test = y[:19]
    print (x.shape, y.shape)
    return x_train, y_train, x_test, y_test

model = Sequential()
# input: 100x100 images with 3 channels -> (100, 100, 3) tensors.
# this applies 32 convolution filters of size 3x3 each.
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3)))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(3, activation='softmax'))

sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd)

x_train, y_train, x_test, y_test = build_dataset(labels)

model = load_model('thebestmodel.h5')
print (model)
model.fit(x_train, y_train, batch_size=32, epochs=20)
score = model.evaluate(x_test, y_test, batch_size=32)
model.save('thebestmodel.h5')
print (score)

我犯了什么错误?我认为这可能是我的一个热编码标签的大小,但我无法让它工作。

谢谢!

4

1 回答 1

1

尽管您的代码已针对此特定错误进行了修复,但您正在加载已保存的模型:model = load_model('thebestmodel.h5')

这是撤消此行之前的所有内容。

于 2018-05-03T13:19:53.947 回答