我编写代码来识别对象。我想使用CIFAR10训练模型,此后,我希望能够输入拍摄的新图像,并希望让模型告诉我图片中的对象。 我该怎么办?
这是我的第一个代码:
import keras
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import cifar10
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
#matplotlib inline
fig = plt.figure(figsize=(20,5))
for i in range(36):
ax = fig.add_subplot(3, 12, i + 1, xticks=[], yticks=[])
ax.imshow(np.squeeze(x_train[i]))
# rescale [0,255] --> [0,1]
x_train = x_train.astype('float32')/255
from keras.utils import np_utils
# one-hot encode the labels
num_classes = len(np.unique(y_train))
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
# break training set into training and validation sets
(x_train, x_valid) = x_train[5000:], x_train[:5000]
(y_train, y_valid) = y_train[5000:], y_train[:5000]
# print shape of training set
print('x_train shape:', x_train.shape)
# printing number of training, validation, and test images
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
print(x_valid.shape[0], 'validation samples')
x_test = x_test.astype('float32')/255
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
model = Sequential()
model.add(Conv2D(filters=16, kernel_size=2, padding='same',
activation='relu', input_shape=(32, 32, 3)))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same',
activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=64, kernel_size=2, padding='same',
activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same',
activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(500, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(10, activation='softmax'))
model.summary()
# compile the model
model.compile(loss='categorical_crossentropy', optimizer='rmsprop',
metrics=['accuracy'])
from keras.callbacks import ModelCheckpoint
# train the model
checkpointer = ModelCheckpoint(filepath='model.weights.best.hdf5',
verbose=1, save_best_only=True)
hist = model.fit(x_train, y_train, batch_size=32, epochs=10,
validation_data=(x_valid, y_valid), callbacks=
[checkpointer], verbose=2, shuffle=True)
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
谢谢!
答案 0 :(得分:0)
您可以save
使用模型。您可以将其另存为.h5
或json
或yml
。
from keras.models import load_model
model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'
# load new model
model2 = load_model('my_model.h5')
然后以numpy array
的形式加载图像,并像x_train = x_train.astype('float32')/255
一样重新缩放图像,然后以
from keras.preprocessing.image import img_to_array, load_img
img = load_img(image_path, color_mode='grayscale')
x = img_to_array(img)
x = x.reshape((1,) + x.shape)
model.predict(x)
#or
model.predict_classes(x)