你是否曾想过你的智能设备上的面部识别是如何工作的?或者,你如何用你的母语与他们交流?卷积神经网络有助于实现这些目标。仔细阅读这篇文章,以获得一些见解。
背景
数字图像是由像素即图片元素组成的。计算机读取图像的过程包括:
- 图像分解: 在这个步骤中,数字图像被分解成RGB通道,即红、绿、蓝。特定的图像像素被映射到各自的颜色通道中。
- 像素值识别: 该系统识别每个像素的值,并因此用它来确定图像的大小。
在灰度图像的情况下,只有一个通道能够完成这一任务。
简介
卷积神经网络,简称CNN,与机器学习中使用的其他神经网络类似,具有神经元 (基本学习单元)以及偏见和可学习权重。每个单元接收输入,并在加权后通过激活函数,从而得到一个输出。
考虑一个验证码验证的例子。一个激活函数验证所选择的图像是否是一个交通灯。如果神经元早些时候见过,"交通灯 "的标签就会被激活。神经元经历的标记图像越多,验证就越强,这个过程被称为训练神经元。
人们不能在卷积神经网络中使用全连接网络,因为任何通用图像至少有200x200x3像素的大小,其中第一个隐藏层变得多达12万个。考虑到其他层,将需要非常多的神经元来处理整个图像集。
过度拟合和欠拟合
过度拟合
例如,你正在访问一个外国,出租车司机宰了你。你可能会想说那里所有的出租车司机都是小偷,这种倾向,通常被称为过度概括,在人类中很常见,但如果不注意的话,机器也会陷入同样的陷阱。在机器学习中,这被称为过度拟合。它表明模型在训练数据上表现良好,但它不能很好地概括。
为了解决过度拟合的问题,可以使用 Dropout、早期停止和正则化等 技术来防止模型与训练数据的拟合过于紧密。剔除涉及在训练期间随机剔除神经网络中的节点,以防止神经元的共同适应。
欠拟合
欠拟合是过度拟合的反面,也就是说,当你的模型过于简单而无法学习数据的基本结构时,就会发生欠拟合。例如,生活满意度的线性模型很容易出现欠拟合:现实就是比模型更复杂,所以它的预测必然是不准确的,即使是在训练的例子中。
为了解决欠拟合问题,可以通过增加更多的层和神经元,或使用不同的 激活函数,使模型结构更加复杂。此外,可以收集更多的数据,以提高模型捕捉潜在模式的能力。
CNN的历史
虽然人工神经网络的研究是由Rosenblatt在20世纪60年代完成的,但用神经网络引入深度学习几乎花了40多年时间。考虑到的关键点是计算能力和数据集,谷歌煽动了对深度学习的研究。最后,在2012年7月,谷歌的研究人员将一个先进的神经网络暴露在一系列未标记的静态图像中,这些图像是从youtube视频中切割出来的,网络在其中自行学习了一个猫咪检测的神经元。
CNN模型在一个四层的概念上工作:
- 卷积
- 卷积
- 集合
- 全连接性
四层概念
I.图像的卷积:
它是平移不变的,即每个卷积滤波器代表一个感兴趣的特征,CNN算法可以识别由字母组成的特征。卷积有四个步骤:
- 排列 特征和图像。
- 每个像素与它的特征****相乘 。
- 将得到的数值相加。
- 用总和****除以特征中的总像素。
在数学上,卷积是函数f和g的乘积,它们是Rⁿ中有限范围[0,t]的施瓦茨函数的对象,定义为::
F(t)*G(t) = ∫F(t-x)dG(x)
卷积图像的原因是为了平滑、锐化、强化 和 增强图像。
II.ReLu层:
Rectified Linear Unit或ReLu是一个激活函数,只有当输入越过某个数字时才会激活某个节点。当输入 为零时,输出为零,而随着输入超过阈值的增加,输出与 可依赖变量 呈线性增长。定义ReLu的**函数f(x)**等于零和可依赖变量的最大值。
f(x)=max(0,x)
ReLu的主要目的是去除卷积中的负值。在所有正值保持不变的同时,负值被改为零(如图所示)。
III.池化层:
在这里,图像堆栈缩小到一个较小的尺寸。它是在通过激活层后通过实施以下四个步骤完成的:
- 选择一个矩阵的窗口大小(2或3)。
- 挑选一个跨度(通常是2)
- 在过滤后的图像上行走你的窗口。
- 从每个窗口中,取最大值。
IV.全连接性:
在这一层中,神经元与前几层的所有激活完全连接。它们总是被放在网络的最后,即在完全连接层之后没有卷积层。在应用于softmax分类器之前,使用一个或两个FC层是一种常见的做法,如下图所示:
输入=>卷积=>回流=>池=>卷积=>回流=>池=>FC=>FC
使用Python对CIFAR-10照片进行分类的Cnn模型
CIFAR-10:
它是加拿大高级研究所的缩写。它是一个由60,000张32*32像素的彩色照片组成的数据集,包括10个类别的物体。每个类别都有一个与之相关的整数值:
- 0:飞机
- 1: 汽车
- 2: 鸟
- 3: 猫
- 4: 鹿
- 5: 狗
- 6: 青蛙
- 7: 马
- 8: 船
- 9:卡车
使用Keras API加载CIFAR-10
下面的例子加载了CIFAR-10,并创建了训练集中前九张图片的图。
from matplotlib import pyplotfrom keras.datasets import cifar10# load dataset(trainX, trainy), (testX, testy) = cifar10.load_data()# summarize loaded datasetprint('Train: X=%s, y=%s' % (trainX.shape, trainy.shape))print('Test: X=%s, y=%s' % (testX.shape, testy.shape))# plot first few imagesfor i in range(9): # define subplot pyplot.subplot(330 + 1 + i) # plot raw pixel data pyplot.imshow(trainX[i])# show the figurepyplot.show()
让我们运行这个例子来加载CIFAR-10训练和测试数据集并打印出形状。
Train: X=(50000, 32, 32, 3), y=(50000, 1)Test: X=(10000, 32, 32, 3), y=(10000, 1)
模型评估 测试线束
加载数据集
#load dataset(trainX, trainY), (testX, testY) = cifar10.load_data()#one hot encode target valuestrainY = to_categorical(trainY)testY = to_categorical(testY)
准备像素数据
#integers to float valuestrain_norm = train.astype('float32')test_norm = test.astype('float32')#normalise the range 0-1train_norm = train_norm / 255.0test_norm = test_norm / 255.0
定义模型
#define cnn modeldef def_model(): model = Sequential() return model
评估模型
# fit modelhistory = model.fit(trainX, trainY, epochs=100, batch_size=64, validation_data=(testX, testY), verbose=0)#evaluate model_, acc = model.evaluate(testX, testY, verbose=0)
显示结果
# plot diagnostic learning curvesdef summarize_diagnostics(history): # plot loss pyplot.subplot(211) pyplot.title('Cross Entropy Loss') pyplot.plot(history.history['loss'], color='blue', label='train') pyplot.plot(history.history['val_loss'], color='orange', label='test') # plot accuracy pyplot.subplot(212) pyplot.title('Classification Accuracy') pyplot.plot(history.history['accuracy'], color='blue', label='train') pyplot.plot(history.history['val_accuracy'], color='orange', label='test') # save plot to file filename = sys.argv[0].split('/')[-1] pyplot.savefig(filename + '_plot.png') pyplot.close()
现在,人们还可以报告测试数据集上的最终模型性能。这可以通过直接打印分类精度来实现。
print('> %.3f' % (acc * 100.0))
完整的代码
下面给出的是训练模型的完整代码:
# test harness for evaluating models on the cifar10 datasetimport sysfrom matplotlib import pyplotfrom keras.datasets import cifar10from keras.utils import to_categoricalfrom keras.models import Sequentialfrom keras.layers import Conv2Dfrom keras.layers import MaxPooling2Dfrom keras.layers import Densefrom keras.layers import Flattenfrom keras.optimizers import SGD# load train and test datasetdef load_dataset(): # load dataset (trainX, trainY), (testX, testY) = cifar10.load_data() # one hot encode target values trainY = to_categorical(trainY) testY = to_categorical(testY) return trainX, trainY, testX, testY# scale pixelsdef prep_pixels(train, test): # convert from integers to floats train_norm = train.astype('float32') test_norm = test.astype('float32') # normalize to range 0-1 train_norm = train_norm / 255.0 test_norm = test_norm / 255.0 # return normalized images return train_norm, test_norm# define cnn modeldef define_model(): model = Sequential() # ... return model# plot diagnostic learning curvesdef summarize_diagnostics(history): # plot loss pyplot.subplot(211) pyplot.title('Cross Entropy Loss') pyplot.plot(history.history['loss'], color='blue', label='train') pyplot.plot(history.history['val_loss'], color='orange', label='test') # plot accuracy pyplot.subplot(212) pyplot.title('Classification Accuracy') pyplot.plot(history.history['accuracy'], color='blue', label='train') pyplot.plot(history.history['val_accuracy'], color='orange', label='test') # save plot to file filename = sys.argv[0].split('/')[-1] pyplot.savefig(filename + '_plot.png') pyplot.close()# run the test harness for evaluating a modeldef run_test_harness(): # load dataset trainX, trainY, testX, testY = load_dataset() # prepare pixel data trainX, testX = prep_pixels(trainX, testX) # define model model = define_model() # fit model history = model.fit(trainX, trainY, epochs=100, batch_size=64, validation_data=(testX, testY), verbose=0) # evaluate model _, acc = model.evaluate(testX, testY, verbose=0) print('> %.3f' % (acc * 100.0)) # learning curves summarize_diagnostics(history)# entry point, run the test harnessrun_test_harness()
这个测试工具可以在CIFAR-10数据集上评估任何CNN模型,并且可以在GPU或CPU上运行。但是,这不可能在电脑上运行。所以下面是另一个例子,它首先加载并准备好图像,加载模型,然后正确预测加载的图像属于 "4 "类。
# make a prediction for a new image.from keras.preprocessing.image import load_imgfrom keras.preprocessing.image import img_to_arrayfrom keras.models import load_model# load and prepare the imagedef load_image(filename): # load the image img = load_img(filename, target_size=(32, 32)) # convert to array img = img_to_array(img) # reshape into a single sample with 3 channels img = img.reshape(1, 32, 32, 3) # prepare pixel data img = img.astype('float32') img = img / 255.0 return img# load an image and predict the classdef run_example(): # load the image img = load_image('sample_image.png') # load model model = load_model('final_model.h5') # predict the class result = model.predict_classes(img) print(result[0])# entry point, run the examplerun_example()
输出
4
结论
- CNN是一种流行的深度学习技术,用于当前的视觉识别任务。这些都取决于训练集的大小和质量。
- 这种神经网络能够在视觉识别任务上超过人类,然而,这些仍然对人类所能达到的视觉伪装(如眩光和噪音)不具有鲁棒性。
- 该理论仍在发展之中,研究人员正在努力赋予它许多属性,如主动注意和在线记忆等。