利用python,tensorflow,keras实现卷积神经网
2019-01-10 本文已影响13人
何同尘
准备环境
参照以前的内容。
下载数据
来自微软Petimages700M
数据描述:2万多张猫和狗的照片
下载后解压到任意路径。
数据处理
import numpy as np
import matplotlib.pyplot as plt
import os
import cv2
#这是我的数据路径
DATADIR = "E:/Datasets/PetImages"
CATEGPRIES = ["Dog","Cat"]
#生成规则大小的灰度图像训练数据
IMG_SIZE = 50
training_data = []
def create_training_data():
for category in CATEGPRIES:
path = os.path.join(DATADIR,category)
class_num = CATEGPRIES.index(category)
for img in os.listdir(path):
try:
img_array = cv2.imread(os.path.join(path,img),cv2.IMREAD_GRAYSCALE)
#将图像的大小统一到 50*50
new_array = cv2.resize(img_array,(IMG_SIZE,IMG_SIZE))
training_data.append([new_array,class_num])
except Exception as e:
pass
create_training_data()
#打乱数据顺序
import random
random.shuffle(training_data)
#随机抽取10个,观察
for sample in training_data[:10]:
print(sample[1])
X = []
y = []
#提取特征(像素值)和标签
for features, label in training_data:
X.append(features)
y.append(label)
X = np.array(X).reshape(-1,IMG_SIZE,IMG_SIZE,1)
#序列化,得到二进制文件
import pickle
pickle_out = open('X.pickle',"wb")
pickle.dump(X,pickle_out)
pickle_out.close()
pickle_out = open('y.pickle',"wb")
pickle.dump(y,pickle_out)
pickle_out.close()
图像数据处理结果
建立卷积神经网络模型
利用keras框架
#导入tensorflow,顺序模型,以及神经网络层
#导入序列化模块
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Dropout,Activation,Flatten,Conv2D,MaxPooling2D
import pickle
#反序列化
X = pickle.load(open('X.pickle','rb'))
y = pickle.load(open('y.pickle','rb'))
#归一化,像素值范围为0~255
X = X/255.0
#模型初始化
model = Sequential()
model.add(Conv2D(64,(3,3),input_shape = X.shape[1:]))#添加卷积层
model.add(Activation('relu'))#添加激活函数
model.add(MaxPooling2D(pool_size=(2,2)))#池化
#以下同理
model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
#模型配置 :损失函数,优化方法,评价指标
model.compile(loss = 'binary_crossentropy',
optimizer = 'adam',
metrics= ['accuracy'])
#训练模型
model.fit(X,y,batch_size=32,epochs=10,validation_split=0.1)
结果
可以看到,训练的结果精度达到0.9043。
高山仰止,景行行止,虽不能至,然欣然向往之