Deep Learning for Computer Vision with Python
Deep Learning for Computer Vision with Python之CNN
前言
数据集为cifar10。
一、CNN是什么?
CNN是卷积神经网络,使用卷积操作完成。
二、使用步骤
1.引入库
代码如下(示例):
import ShallowNet
import argparse
from keras.optimizers import SGD
from sklearn.metrics import classification_report
from keras.datasets import cifar10
from sklearn.preprocessing import LabelBinarizer
2.代码
网络结构为CNN(32,(3*3))——>RELU——>FLATTEN——>FULL-CONNECT(输出10中类别概率)。
代码如下(示例):
parse = argparse.ArgumentParser()
parse.add_argument("--dataset_dir", type = str, help="input your input dataset")
arg = parse.parse_args()
labelNames = ["airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"]
(trainx,trainy), (testx,testy) = cifar10.load_data()
trainx = trainx.astype("float32")/255.0
testx = testx.astype("float32")/255.0
print(trainx.shape)
lb = LabelBinarizer()
trainy = lb.fit_transform(trainy)
testy = lb.fit_transform(testy)
s = ShallowNet.ShallowNet(width = 32, height = 32, depth = 3, classlist = labelNames)
model = s.start()
opt = SGD(0.01)
model.compile(loss=["categorical_crossentropy"], optimizer=opt,metrics=["accuracy"])
log = model.fit(trainx, trainy, validation_data=(testx, testy), batch_size=32, epochs=40, verbose=1)
pre = model.predict(trainx)
print("[INFO] evaluating network...")
print(classification_report(testy.argmax(axis=1),pre.argmax(axis=1), target_names=labelNames))
ShallowNet.py
from keras.models import Sequential
from keras.layers.convolutional import Conv2D
from keras.layers.core import Activation
from keras.layers.core import Flatten
from keras.layers.core import Dense
class ShallowNet:
def __init__(self, width, height, depth, classlist):
self.inputshape = [height, width, depth]
self.classlist = classlist
def start(self):
model = Sequential()
print(self.inputshape)
model.add(Conv2D(32,(3,3), padding = "same",input_shape = self.inputshape))
model.add(Activation("relu"))
model.add(Flatten())
print(len(self.classlist))
model.add(Dense(len(self.classlist)))
model.add(Activation("softmax"))
return model
总结
就这样啦