人工智能專欄文章匯總:人工智能學(xué)習(xí)專欄文章匯總-CSDN博客
目錄
二、圖像分類問題
2.1 嘗試使用全連接神經(jīng)網(wǎng)絡(luò)
2.2 引入卷積神經(jīng)網(wǎng)絡(luò)
?2.3 分類函數(shù)Softmax
2.4?交叉熵?fù)p失函數(shù)
2.5?學(xué)習(xí)率優(yōu)化算法
2.6 圖像預(yù)處理算法
2.6.1?隨機(jī)改變亮暗、對比度和顏色等
2.6.2?隨機(jī)填充
2.6.3?隨機(jī)裁剪
2.6.4?隨機(jī)縮放
2.6.5?隨機(jī)翻轉(zhuǎn)
2.6.6?隨機(jī)打亂真實框排列順序
二、圖像分類問題
圖像分類問題是神經(jīng)網(wǎng)絡(luò)經(jīng)常遇到的處理任務(wù),需要將圖像按給定的類別進(jìn)行分類。
本篇通過手寫數(shù)字識別這個典型的圖像分類任務(wù)(0~9個數(shù)字一共是10個類別),來了解圖像分類問題的特點,原理和方法。
我們首先嘗試使用典型的全連接神經(jīng)網(wǎng)絡(luò),再引入適合圖像處理任務(wù)的卷積神經(jīng)網(wǎng)絡(luò)。
2.1 嘗試使用全連接神經(jīng)網(wǎng)絡(luò)
經(jīng)典的全連接神經(jīng)網(wǎng)絡(luò)來包含四層網(wǎng)絡(luò):輸入層、兩個隱含層和輸出層,將手寫數(shù)字識別任務(wù)通過全連接神經(jīng)網(wǎng)絡(luò)表示:
- 輸入層:將數(shù)據(jù)輸入給神經(jīng)網(wǎng)絡(luò)。在該任務(wù)中,輸入層的尺度為28×28的像素值。
- 隱含層:增加網(wǎng)絡(luò)深度和復(fù)雜度,隱含層的節(jié)點數(shù)是可以調(diào)整的,節(jié)點數(shù)越多,神經(jīng)網(wǎng)絡(luò)表示能力越強(qiáng),參數(shù)量也會增加。在該任務(wù)中,中間的兩個隱含層為10×10的結(jié)構(gòu),通常隱含層會比輸入層的尺寸小,以便對關(guān)鍵信息做抽象,激活函數(shù)使用常見的Sigmoid函數(shù)。
- 輸出層:輸出網(wǎng)絡(luò)計算結(jié)果,輸出層的節(jié)點數(shù)是固定的。如果是回歸問題,節(jié)點數(shù)量為需要回歸的數(shù)字?jǐn)?shù)量。如果是分類問題,則是分類標(biāo)簽的數(shù)量。在該任務(wù)中,模型的輸出是回歸一個數(shù)字,輸出層的尺寸為1。
Python源碼 - 激活函數(shù)為sigmoid的多層網(wǎng)絡(luò)參考代碼:
import paddle.nn.functional as F
from paddle.nn import Linear
# 定義多層全連接神經(jīng)網(wǎng)絡(luò)
class MNIST(paddle.nn.Layer):
def __init__(self):
super(MNIST, self).__init__()
# 定義兩層全連接隱含層,輸出維度是10,當(dāng)前設(shè)定隱含節(jié)點數(shù)為10,可根據(jù)任務(wù)調(diào)整
self.fc1 = Linear(in_features=784, out_features=10)
self.fc2 = Linear(in_features=10, out_features=10)
# 定義一層全連接輸出層,輸出維度是1
self.fc3 = Linear(in_features=10, out_features=1)
# 定義網(wǎng)絡(luò)的前向計算,隱含層激活函數(shù)為sigmoid,輸出層不使用激活函數(shù)
def forward(self, inputs):
# inputs = paddle.reshape(inputs, [inputs.shape[0], 784])
outputs1 = self.fc1(inputs)
outputs1 = F.sigmoid(outputs1)
outputs2 = self.fc2(outputs1)
outputs2 = F.sigmoid(outputs2)
outputs_final = self.fc3(outputs2)
return outputs_final
然而,全連接神經(jīng)網(wǎng)絡(luò)模型并不適合圖像分類模型,圖像分類任務(wù)需要考慮圖像數(shù)據(jù)的空間性,以及如何分類(波士頓房價預(yù)測是回歸任務(wù),是回歸到一個具體數(shù)字,手寫數(shù)字識別實際上是進(jìn)行分類判斷),對于圖像識別和分類任務(wù),我們需要引入卷積神經(jīng)網(wǎng)絡(luò),Softmax激活函數(shù)以及交叉熵?fù)p失函數(shù),整個流程如下圖:
2.2 引入卷積神經(jīng)網(wǎng)絡(luò)
圖像識別需要考慮數(shù)據(jù)的空間分布,更適合使用卷積神經(jīng)網(wǎng)絡(luò)模型,模型中包含卷積層(convolution)和池化層(subsampling),以及最后一個全連接層(fully connected)
關(guān)于卷積神經(jīng)網(wǎng)絡(luò),可以參考這一篇:
PyTorch學(xué)習(xí)系列教程:卷積神經(jīng)網(wǎng)絡(luò)【CNN】 - 知乎
關(guān)于卷積核和輸入,輸出通道,可以參考這一篇:
如何理解卷積神經(jīng)網(wǎng)絡(luò)中的通道(channel)_卷積通道數(shù)_嘆久01的博客-CSDN博客
??
Python源碼 - 卷積神經(jīng)網(wǎng)絡(luò)參考代碼:
# 定義 SimpleNet 網(wǎng)絡(luò)結(jié)構(gòu)
import paddle
from paddle.nn import Conv2D, MaxPool2D, Linear
import paddle.nn.functional as F
# 多層卷積神經(jīng)網(wǎng)絡(luò)實現(xiàn)
class MNIST(paddle.nn.Layer):
def __init__(self):
super(MNIST, self).__init__()
# 定義卷積層,輸出特征通道out_channels設(shè)置為20,卷積核的大小kernel_size為5,卷積步長stride=1,padding=2
self.conv1 = Conv2D(in_channels=1, out_channels=20, kernel_size=5, stride=1, padding=2)
# 定義池化層,池化核的大小kernel_size為2,池化步長為2
self.max_pool1 = MaxPool2D(kernel_size=2, stride=2)
# 定義卷積層,輸出特征通道out_channels設(shè)置為20,卷積核的大小kernel_size為5,卷積步長stride=1,padding=2
self.conv2 = Conv2D(in_channels=20, out_channels=20, kernel_size=5, stride=1, padding=2)
# 定義池化層,池化核的大小kernel_size為2,池化步長為2
self.max_pool2 = MaxPool2D(kernel_size=2, stride=2)
# 定義一層全連接層,輸出維度是1
self.fc = Linear(in_features=980, out_features=1)
# 定義網(wǎng)絡(luò)前向計算過程,卷積后緊接著使用池化層,最后使用全連接層計算最終輸出
# 卷積層激活函數(shù)使用Relu,全連接層不使用激活函數(shù)
def forward(self, inputs):
x = self.conv1(inputs)
x = F.relu(x)
x = self.max_pool1(x)
x = self.conv2(x)
x = F.relu(x)
x = self.max_pool2(x)
x = paddle.reshape(x, [x.shape[0], -1])
x = self.fc(x)
return x
?2.3 分類函數(shù)Softmax
?為了進(jìn)行分類判別,要通過引入Softmax函數(shù)到輸出層,使得輸出層的輸出為不同類別概率的集合,并且所有概率之和為1,比如[0.1, 0.2, 0.7]
??
比如,一個三個標(biāo)簽的分類模型(三分類)使用的Softmax輸出層,從中可見原始輸出的三個數(shù)字3、1、-3,經(jīng)過Softmax層后轉(zhuǎn)變成加和為1的三個概率值0.88、0.12、0。
??
2.4?交叉熵?fù)p失函數(shù)
分類網(wǎng)絡(luò)模型需要使用交叉熵?fù)p失函數(shù)不斷訓(xùn)練更新模型參數(shù),最終使得交叉熵趨于收斂,從而完成模型訓(xùn)練。
正確解標(biāo)簽對應(yīng)的輸出越大,交叉熵的值越接近0;當(dāng)輸出為1時,交叉熵誤差為0。反之,如果正確解標(biāo)簽對應(yīng)的輸出越小,則交叉熵的值越大。?
??
要想搞清楚交叉熵,推薦大家讀一下這篇文章:損失函數(shù):交叉熵詳解 - 知乎
里面又牽涉到極大似然估計理論,推薦閱讀這篇文章:極大似然估計思想的最簡單解釋_class_brick的博客-CSDN博客
2.5?學(xué)習(xí)率優(yōu)化算法
學(xué)習(xí)率是優(yōu)化器的一個參數(shù),調(diào)整學(xué)習(xí)率看似是一件非常麻煩的事情,需要不斷的調(diào)整步長,觀察訓(xùn)練時間和Loss的變化。經(jīng)過研究員的不斷的實驗,當(dāng)前已經(jīng)形成了四種比較成熟的優(yōu)化算法:SGD、Momentum、AdaGrad和Adam,效果如?圖所示。
?
圖3: 不同學(xué)習(xí)率算法效果示意圖
- SGD:?隨機(jī)梯度下降算法,每次訓(xùn)練少量數(shù)據(jù),抽樣偏差導(dǎo)致的參數(shù)收斂過程中震蕩。
- Momentum:?引入物理“動量”的概念,累積速度,減少震蕩,使參數(shù)更新的方向更穩(wěn)定。
- AdaGrad:?根據(jù)不同參數(shù)距離最優(yōu)解的遠(yuǎn)近,動態(tài)調(diào)整學(xué)習(xí)率。學(xué)習(xí)率逐漸下降,依據(jù)各參數(shù)變化大小調(diào)整學(xué)習(xí)率。
- Adam:?由于動量和自適應(yīng)學(xué)習(xí)率兩個優(yōu)化思路是正交的,因此可以將兩個思路結(jié)合起來,這就是當(dāng)前廣泛應(yīng)用的算法。
2.6 圖像預(yù)處理算法
在計算機(jī)視覺中,通常會對圖像做一些隨機(jī)的變化,產(chǎn)生相似但又不完全相同的樣本。主要作用是擴(kuò)大訓(xùn)練數(shù)據(jù)集,抑制過擬合,提升模型的泛化能力,常用的方法主要有以下幾種:
- 隨機(jī)改變亮暗、對比度和顏色
- 隨機(jī)填充
- 隨機(jī)裁剪
- 隨機(jī)縮放
- 隨機(jī)翻轉(zhuǎn)
- 隨機(jī)打亂真實框排列順序
下面是分別使用numpy 實現(xiàn)這些數(shù)據(jù)增強(qiáng)方法。文章來源:http://www.zghlxwxcb.cn/news/detail-830348.html
2.6.1?隨機(jī)改變亮暗、對比度和顏色等
import numpy as np
import cv2
from PIL import Image, ImageEnhance
import random
# 隨機(jī)改變亮暗、對比度和顏色等
def random_distort(img):
# 隨機(jī)改變亮度
def random_brightness(img, lower=0.5, upper=1.5):
e = np.random.uniform(lower, upper)
return ImageEnhance.Brightness(img).enhance(e)
# 隨機(jī)改變對比度
def random_contrast(img, lower=0.5, upper=1.5):
e = np.random.uniform(lower, upper)
return ImageEnhance.Contrast(img).enhance(e)
# 隨機(jī)改變顏色
def random_color(img, lower=0.5, upper=1.5):
e = np.random.uniform(lower, upper)
return ImageEnhance.Color(img).enhance(e)
ops = [random_brightness, random_contrast, random_color]
np.random.shuffle(ops)
img = Image.fromarray(img)
img = ops[0](img)
img = ops[1](img)
img = ops[2](img)
img = np.asarray(img)
return img
# 定義可視化函數(shù),用于對比原圖和圖像增強(qiáng)的效果
import matplotlib.pyplot as plt
def visualize(srcimg, img_enhance):
# 圖像可視化
plt.figure(num=2, figsize=(6,12))
plt.subplot(1,2,1)
plt.title('Src Image', color='#0000FF')
plt.axis('off') # 不顯示坐標(biāo)軸
plt.imshow(srcimg) # 顯示原圖片
# 對原圖做 隨機(jī)改變亮暗、對比度和顏色等 數(shù)據(jù)增強(qiáng)
srcimg_gtbox = records[0]['gt_bbox']
srcimg_label = records[0]['gt_class']
plt.subplot(1,2,2)
plt.title('Enhance Image', color='#0000FF')
plt.axis('off') # 不顯示坐標(biāo)軸
plt.imshow(img_enhance)
image_path = records[0]['im_file']
print("read image from file {}".format(image_path))
srcimg = Image.open(image_path)
# 將PIL讀取的圖像轉(zhuǎn)換成array類型
srcimg = np.array(srcimg)
# 對原圖做 隨機(jī)改變亮暗、對比度和顏色等 數(shù)據(jù)增強(qiáng)
img_enhance = random_distort(srcimg)
visualize(srcimg, img_enhance)
2.6.2?隨機(jī)填充
# 隨機(jī)填充
def random_expand(img,
gtboxes,
max_ratio=4.,
fill=None,
keep_ratio=True,
thresh=0.5):
if random.random() > thresh:
return img, gtboxes
if max_ratio < 1.0:
return img, gtboxes
h, w, c = img.shape
ratio_x = random.uniform(1, max_ratio)
if keep_ratio:
ratio_y = ratio_x
else:
ratio_y = random.uniform(1, max_ratio)
oh = int(h * ratio_y)
ow = int(w * ratio_x)
off_x = random.randint(0, ow - w)
off_y = random.randint(0, oh - h)
out_img = np.zeros((oh, ow, c))
if fill and len(fill) == c:
for i in range(c):
out_img[:, :, i] = fill[i] * 255.0
out_img[off_y:off_y + h, off_x:off_x + w, :] = img
gtboxes[:, 0] = ((gtboxes[:, 0] * w) + off_x) / float(ow)
gtboxes[:, 1] = ((gtboxes[:, 1] * h) + off_y) / float(oh)
gtboxes[:, 2] = gtboxes[:, 2] / ratio_x
gtboxes[:, 3] = gtboxes[:, 3] / ratio_y
return out_img.astype('uint8'), gtboxes
# 對原圖做 隨機(jī)改變亮暗、對比度和顏色等 數(shù)據(jù)增強(qiáng)
srcimg_gtbox = records[0]['gt_bbox']
img_enhance, new_gtbox = random_expand(srcimg, srcimg_gtbox)
visualize(srcimg, img_enhance)
2.6.3?隨機(jī)裁剪
隨機(jī)裁剪之前需要先定義兩個函數(shù),multi_box_iou_xywh
和box_crop
這兩個函數(shù)將被保存在box_utils.py文件中。文章來源地址http://www.zghlxwxcb.cn/news/detail-830348.html
import numpy as np
def multi_box_iou_xywh(box1, box2):
"""
In this case, box1 or box2 can contain multi boxes.
Only two cases can be processed in this method:
1, box1 and box2 have the same shape, box1.shape == box2.shape
2, either box1 or box2 contains only one box, len(box1) == 1 or len(box2) == 1
If the shape of box1 and box2 does not match, and both of them contain multi boxes, it will be wrong.
"""
assert box1.shape[-1] == 4, "Box1 shape[-1] should be 4."
assert box2.shape[-1] == 4, "Box2 shape[-1] should be 4."
b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2
b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2
b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2
b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2
inter_x1 = np.maximum(b1_x1, b2_x1)
inter_x2 = np.minimum(b1_x2, b2_x2)
inter_y1 = np.maximum(b1_y1, b2_y1)
inter_y2 = np.minimum(b1_y2, b2_y2)
inter_w = inter_x2 - inter_x1
inter_h = inter_y2 - inter_y1
inter_w = np.clip(inter_w, a_min=0., a_max=None)
inter_h = np.clip(inter_h, a_min=0., a_max=None)
inter_area = inter_w * inter_h
b1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1)
b2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1)
return inter_area / (b1_area + b2_area - inter_area)
def box_crop(boxes, labels, crop, img_shape):
x, y, w, h = map(float, crop)
im_w, im_h = map(float, img_shape)
boxes = boxes.copy()
boxes[:, 0], boxes[:, 2] = (boxes[:, 0] - boxes[:, 2] / 2) * im_w, (
boxes[:, 0] + boxes[:, 2] / 2) * im_w
boxes[:, 1], boxes[:, 3] = (boxes[:, 1] - boxes[:, 3] / 2) * im_h, (
boxes[:, 1] + boxes[:, 3] / 2) * im_h
crop_box = np.array([x, y, x + w, y + h])
centers = (boxes[:, :2] + boxes[:, 2:]) / 2.0
mask = np.logical_and(crop_box[:2] <= centers, centers <= crop_box[2:]).all(
axis=1)
boxes[:, :2] = np.maximum(boxes[:, :2], crop_box[:2])
boxes[:, 2:] = np.minimum(boxes[:, 2:], crop_box[2:])
boxes[:, :2] -= crop_box[:2]
boxes[:, 2:] -= crop_box[:2]
mask = np.logical_and(mask, (boxes[:, :2] < boxes[:, 2:]).all(axis=1))
boxes = boxes * np.expand_dims(mask.astype('float32'), axis=1)
labels = labels * mask.astype('float32')
boxes[:, 0], boxes[:, 2] = (boxes[:, 0] + boxes[:, 2]) / 2 / w, (
boxes[:, 2] - boxes[:, 0]) / w
boxes[:, 1], boxes[:, 3] = (boxes[:, 1] + boxes[:, 3]) / 2 / h, (
boxes[:, 3] - boxes[:, 1]) / h
return boxes, labels, mask.sum()
# 隨機(jī)裁剪
def random_crop(img,
boxes,
labels,
scales=[0.3, 1.0],
max_ratio=2.0,
constraints=None,
max_trial=50):
if len(boxes) == 0:
return img, boxes
if not constraints:
constraints = [(0.1, 1.0), (0.3, 1.0), (0.5, 1.0), (0.7, 1.0),
(0.9, 1.0), (0.0, 1.0)]
img = Image.fromarray(img)
w, h = img.size
crops = [(0, 0, w, h)]
for min_iou, max_iou in constraints:
for _ in range(max_trial):
scale = random.uniform(scales[0], scales[1])
aspect_ratio = random.uniform(max(1 / max_ratio, scale * scale), \
min(max_ratio, 1 / scale / scale))
crop_h = int(h * scale / np.sqrt(aspect_ratio))
crop_w = int(w * scale * np.sqrt(aspect_ratio))
crop_x = random.randrange(w - crop_w)
crop_y = random.randrange(h - crop_h)
crop_box = np.array([[(crop_x + crop_w / 2.0) / w,
(crop_y + crop_h / 2.0) / h,
crop_w / float(w), crop_h / float(h)]])
iou = multi_box_iou_xywh(crop_box, boxes)
if min_iou <= iou.min() and max_iou >= iou.max():
crops.append((crop_x, crop_y, crop_w, crop_h))
break
while crops:
crop = crops.pop(np.random.randint(0, len(crops)))
crop_boxes, crop_labels, box_num = box_crop(boxes, labels, crop, (w, h))
if box_num < 1:
continue
img = img.crop((crop[0], crop[1], crop[0] + crop[2],
crop[1] + crop[3])).resize(img.size, Image.LANCZOS)
img = np.asarray(img)
return img, crop_boxes, crop_labels
img = np.asarray(img)
return img, boxes, labels
# 對原圖做 隨機(jī)改變亮暗、對比度和顏色等 數(shù)據(jù)增強(qiáng)
srcimg_gtbox = records[0]['gt_bbox']
srcimg_label = records[0]['gt_class']
img_enhance, new_labels, mask = random_crop(srcimg, srcimg_gtbox, srcimg_label)
visualize(srcimg, img_enhance)
2.6.4?隨機(jī)縮放
# 隨機(jī)縮放
def random_interp(img, size, interp=None):
interp_method = [
cv2.INTER_NEAREST,
cv2.INTER_LINEAR,
cv2.INTER_AREA,
cv2.INTER_CUBIC,
cv2.INTER_LANCZOS4,
]
if not interp or interp not in interp_method:
interp = interp_method[random.randint(0, len(interp_method) - 1)]
h, w, _ = img.shape
im_scale_x = size / float(w)
im_scale_y = size / float(h)
img = cv2.resize(
img, None, None, fx=im_scale_x, fy=im_scale_y, interpolation=interp)
return img
# 對原圖做 隨機(jī)縮放
img_enhance = random_interp(srcimg, 640)
visualize(srcimg, img_enhance)
2.6.5?隨機(jī)翻轉(zhuǎn)
# 隨機(jī)翻轉(zhuǎn)
def random_flip(img, gtboxes, thresh=0.5):
if random.random() > thresh:
img = img[:, ::-1, :]
gtboxes[:, 0] = 1.0 - gtboxes[:, 0]
return img, gtboxes
# 對原圖做 隨機(jī)改變亮暗、對比度和顏色等 數(shù)據(jù)增強(qiáng)
img_enhance, box_enhance = random_flip(srcimg, srcimg_gtbox)
visualize(srcimg, img_enhance)
2.6.6?隨機(jī)打亂真實框排列順序
# 隨機(jī)打亂真實框排列順序
def shuffle_gtbox(gtbox, gtlabel):
gt = np.concatenate(
[gtbox, gtlabel[:, np.newaxis]], axis=1)
idx = np.arange(gt.shape[0])
np.random.shuffle(idx)
gt = gt[idx, :]
return gt[:, :4], gt[:, 4]
到了這里,關(guān)于人工智能學(xué)習(xí)與實訓(xùn)筆記(二):神經(jīng)網(wǎng)絡(luò)之圖像分類問題的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!