from tensorflow.keras.datasets import cifar10
from tensorflow.python.keras.utils import np_utils
import numpy as np
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
np.random.seed(10)
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train4D = x_train.reshape(x_train.shape[0],32,32,3).astype('float32')
x_test4D = x_test.reshape(x_test.shape[0],32,32,3).astype('float32')
x_train4D_normalize = x_train4D / 255
x_test4D_normalize = x_test4D / 255
y_trainOneHot = np_utils.to_categorical(y_train)
y_testOneHot = np_utils.to_categorical(y_test)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
model = Sequential()
model.add(Conv2D(filters=94, #滤波器个数为6
kernel_size=(5,5), #每个滤波器大小为5x5
padding='same', #进行边缘填充,使得卷积运算不会改变图像大小
input_shape=(32,32,3),
activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(filters=156,
kernel_size=(5,5),
padding='same',
activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu')) #隐藏层
model.add(Dropout(0.4))
model.add(Dense(10,activation='softmax')) #输出层
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
train_history = model.fit(x=x_train4D_normalize,
y=y_trainOneHot,
validation_split=0.2,
epochs=10,
batch_size=300,
verbose=2)
# PIL(Python Image Library)是python的第三方图像处理库,
# 但是由于其强大的功能与众多的使用人数,几乎已经被认为是python官方图像处理库了。。。
# 安装 pip install pillow
#使用PIL.Image.open(),是以 (w, h)即“宽 x 高”的方式读取图片,数据类型是PIL.Image.Image,
#如果将其转换为numpy.ndarray,格式为 (h, w, c)即“高 x 宽 x 通道”,像素顺序是RGB
#如果读取黑白图像,可以在读取后,用convert('L')方法将转换为“ 高 x 宽”。
# from PIL import Image
# import numpy as np
#
# img = Image.open('white_5.jpg').convert('L') #white_5.jpg
# print('img size:', img.size)
# img = np.array(img).reshape(1, 28, 28, 1).astype('float32')
# img = img / 255
# pred_label = model.predict_classes(img)
# print('predict my img',pred_label)



