機(jī)器學(xué)習(xí) | CNN卷積神經(jīng)網(wǎng)絡(luò)

由于近期學(xué)業(yè)繁忙,所以廢話少說啦~

測試結(jié)果

最后兩行分別為預(yù)測類別與真實(shí)類別。

測試結(jié)果


數(shù)據(jù)預(yù)覽

這里的數(shù)據(jù)使用的是mnist數(shù)據(jù)集,大家可以將代碼中的DOWNLOAD_MNIST值修改為True進(jìn)行自動(dòng)下載。

數(shù)據(jù)
數(shù)據(jù)


代碼

import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision      # 數(shù)據(jù)庫模塊
import matplotlib.pyplot as plt

#訓(xùn)練整批數(shù)據(jù)多少次,這里為了節(jié)約時(shí)間,只訓(xùn)練一次
EPOCH=1
#每次批處理50個(gè)數(shù)據(jù)
BATCH_SIZE=50
#學(xué)習(xí)效率
LR=0.001
# 如果已經(jīng)下載好了mnist數(shù)據(jù)就寫上False
DOWNLOAD_MNIST = False  


#訓(xùn)練的數(shù)據(jù)集:Mnist手寫數(shù)字
train_data=torchvision.datasets.MNIST(
    #保存或提取數(shù)據(jù)集的位置
    root='./mnist/',
    #該數(shù)據(jù)是訓(xùn)練數(shù)據(jù)
    train=True,
    #轉(zhuǎn)換PIL.Image or numpy.ndarray成torch.FloatTensor (C x H x W), 訓(xùn)練的時(shí)候 normalize 成 [0.0, 1.0] 區(qū)間
    transform=torchvision.transforms.ToTensor(),
     #沒下載就下載,下載了就不用再下了
    download=DOWNLOAD_MNIST,
)


#繪制一下數(shù)據(jù)集
#黑色的地方的值都是0, 白色的地方值大于0.
print(train_data.train_data.size())                 # (60000, 28, 28)
print(train_data.train_labels.size())               # (60000)
plt.imshow(train_data.train_data[2].numpy(), cmap='gray')
plt.title('%i' % train_data.train_labels[2])
plt.show()

#測試數(shù)據(jù)
test_data=torchvision.datasets.MNIST(root='./mnist/',train=False)

#批訓(xùn)練50samples,1 channel,28x28 (50, 1, 28, 28)
train_loader=Data.DataLoader(dataset=train_data,batch_size=BATCH_SIZE,shuffle=True)

#這里只測試了前2000個(gè)
#特征
test_x=torch.unsqueeze(test_data.test_data,dim=1).type(torch.FloatTensor)[:2000]/255.
#標(biāo)簽
test_y=test_data.test_labels[:2000]

#構(gòu)建CNN模型
class CNN(nn.Module):
    def __init__(self):
        super(CNN,self).__init__()
        #input shape(1,28,28)
        self.conv1=nn.Sequential(
            #卷積
            nn.Conv2d(
                in_channels=1,
                out_channels=16,
                #filter size
                kernel_size=5,
                #filter movement/step
                stride=1,
                 #如果想要con2d出來的圖片長寬沒有變化, 
                 #padding=(kernel_size-1)/2當(dāng)stride=1
                padding=2,
            ),
            #output shape(16,28,28)
            #激勵(lì)函數(shù)
            nn.ReLU(),
            #池化
            # 在2x2空間里向下采樣,output shape(16,14,14)
            nn.MaxPool2d(kernel_size=2),
        )
        #input shape(16,14,14)
        self.conv2=nn.Sequential(
            nn.Conv2d(16,32,5,1,2),
            #output shape(32,14,14)
            #激勵(lì)函數(shù)
            nn.ReLU(),
            #output shape(32,7,7)
            nn.MaxPool2d(2),
        )
        #全連接層——進(jìn)行分類。這里將其分成了10類
        self.out=nn.Linear(32*7*7,10)

    def forward(self,x):
        x=self.conv1(x)
        x=self.conv2(x)
        #展平多維的卷積圖成(batch_size,32*7*7)
        x=x.view(x.size(0),-1)
        output=self.out(x)
        return output

cnn=CNN()
print(cnn)


#訓(xùn)練
#優(yōu)化器
optimizer=torch.optim.Adam(cnn.parameters(),lr=LR)
#損失函數(shù)
loss_func=nn.CrossEntropyLoss()

#開始訓(xùn)練
for epoch in range(EPOCH):
    for step,(b_x,b_y) in enumerate(train_loader):
        #將數(shù)據(jù)輸入nn并且得到output
        output=cnn(b_x)
        #計(jì)算output與真實(shí)值之間的誤差
        loss=loss_func(output,b_y)
        #清空上一步殘余更新參數(shù)值
        optimizer.zero_grad()
        #誤差反向傳播,讓參數(shù)進(jìn)行更新
        loss.backward()
        #將更新后的參數(shù)值施加到nn的parameters上
        optimizer.step()



#測試:選取10個(gè)數(shù)據(jù)
test_output=cnn(test_x[:10])
pred_y=torch.max(test_output,1)[1].data.numpy().squeeze()
print(pred_y, 'prediction number')
print(test_y[:10].numpy(), 'real number')

# if __name__=='__main__':
#     print("hello word")
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容