文件结构:
- classify
- train.py
- test.py
- train
- cat
- xxx.jpg xxx.jpg
- dog
- xxx.jpg xxx.jpg
- cat
- test
- xxx.jpg xxx.jpg
train.py:
import glob
from PIL import Image, ImageOps
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
import keras
from keras.utils import to_categorical
z = glob.glob('./train/*/*.jpg')
ori_label = []
ori_imgs = []
assert type(z) == list
img_size_x = 112
img_size_y = 112
for fn in z:
if fn[-3:] != 'jpg':
continue
ori_label.append(fn.split('/')[-2])
new_img = Image.open(fn)
ori_imgs.append(ImageOps.fit(new_img, (img_size_x, img_size_y), Image.ANTIALIAS).convert('RGB'))
imgs = np.array([np.array(im) for im in ori_imgs])
imgs = imgs.reshape(imgs.shape[0], img_size_x, img_size_y, 3) / 255
lb = LabelBinarizer()
label = lb.fit_transform(ori_label)
label = to_categorical(label)
trainX, validX, trainY, validY = train_test_split(imgs, label, test_size=0.2, random_state=42)
from keras.layers import Input, Conv2D, BatchNormalization, Activation, MaxPooling2D, GlobalMaxPooling2D, Dense, Dropout
from keras.models import Model, load_model
from keras.optimizers import SGD
IM_imput = Input((img_size_x, img_size_y, 3))
IM = Conv2D(32,(5,5))(IM_imput)
IM = BatchNormalization(axis = 3)(IM)
IM = Activation('relu')(IM)
IM = MaxPooling2D(strides=(2,2))(IM)
IM = Conv2D(64,(5,5))(IM_imput)
IM = BatchNormalization(axis = 3)(IM)
IM = Activation('relu')(IM)
IM = GlobalMaxPooling2D()(IM)
IM = Dense(64,activation='relu')(IM)
IM = Dropout(0.5)(IM)
IM = Dense(2,activation='relu')(IM)
model = Model(inputs=IM_input, outputs=IM)
model.summary()
sgd = SGD(lr=0.01, momentum=0.9, decay=0.002, nesterov=False)
model.compile(loss='binary_crossentropy',optimizer=sgd,metrics=['acc'])
from keras.callbacks import LearningRateScheduler, EarlyStopping, ModelCheckpoint
batch_size = 32
annealer = LearningRateScheduler(lambda x: 1e-3*0.9**x)
early_stop = EarlyStopping(patience=8)
modelsave = ModelCheckpoint(filepath='model.h5',save_best_only=True,verbose=1)
model.fit(
trainX, trainY, batch_size = batch_size,
epochs=20,
validation_data = (validX, validY),
callbacks = [annealer,early_stop,modelsave]
)
test.py:
import os
from keras.models import load_model
import numpy as np
from PIL import Image
import cv2
model = load_model('./model.h5')
#single_img:
input = cv2.imread('0_1.jpg',cv2.IMREAD_COLOR)
input = cv2.resize(input, (112, 112),interpolation = cv2.INTER_CUBIC)
input= np.array(input).reshape(1,112,112,3)/255
pre_y = model.predict(input)
label = np.argmax(pre_y)
print(label)
#file_img:
'''
predict_dir = 'train/wu'
def get_inputs(src=[]):
pre_x = []
for s in src:
input = cv2.imread('0_1.jpg',cv2.IMREAD_COLOR)
input = cv2.resize(input, (112, 112),interpolation = cv2.INTER_CUBIC)
#input= np.array(input).reshape(1,112,112,3)/255
pre_x.append(input)
pre_x = np.array(pre_x) / 255.0
return pre_x
test = os.listdir(predict_dir)
images = []
for testpath in test:
if testpath.endswith('jpg'):
fd = os.path.join(predict_dir,testpath)
images.append(fd)
pre_x = get_inputs(images)
pre_y = model.predict(pre_x)
print(pre_y)
'''