網站首頁 編程語言 正文
引言
深度學習的第一個實例一般都是mnist,只要這個例子完全弄懂了,其它的就是舉一反三的事了。由于篇幅原因,本文不具體介紹配置文件里面每個參數的具體函義,如果想弄明白的,請參看我以前的博文:
數據層及參數
視覺層及參數
solver配置文件及參數
一、數據準備
官網提供的mnist數據并不是圖片,但我們以后做的實際項目可能是圖片。因此有些人并不知道該怎么辦。在此我將mnist數據進行了轉化,變成了一張張的圖片,我們練習就從圖片開始。mnist圖片數據我放在了百度云盤。
mnist圖片數據點擊下載
數據分成了訓練集(60000張共10類)和測試集(共10000張10類),每個類別放在一個單獨的文件夾里。并且將所有的圖片,都生成了txt列表清單(train.txt和test.txt)。大家下載下來后,直接解壓到當前用戶根目錄下就可以了。由于我是在windows下壓縮的,因此是winrar文件。如果大家要在linux下解壓縮,需要安裝rar的linux版本,也是十分簡單
sudo apt-get install rar
二、導入caffe庫,并設定文件路徑
我是將mnist直接放在根目錄下的,所以代碼如下:
# -*- coding: utf-8 -*-
import caffe
from caffe import layers as L,params as P,proto,to_proto
#設定文件的保存路徑
root='/home/xxx/' #根目錄
train_list=root+'mnist/train/train.txt' #訓練圖片列表
test_list=root+'mnist/test/test.txt' #測試圖片列表
train_proto=root+'mnist/train.prototxt' #訓練配置文件
test_proto=root+'mnist/test.prototxt' #測試配置文件
solver_proto=root+'mnist/solver.prototxt' #參數文件
其中train.txt 和test.txt文件已經有了,其它三個文件,我們需要自己編寫。
此處注意:一般caffe程序都是先將圖片轉換成lmdb文件,但這樣做有點麻煩。因此我就不轉換了,我直接用原始圖片進行操作,所不同的就是直接用圖片操作,均值很難計算,因此可以不減均值。
二、生成配置文件
配置文件實際上就是一些txt文檔,只是后綴名是prototxt,我們可以直接到編輯器里編寫,也可以用代碼生成。此處,我用python來生成。
#編寫一個函數,生成配置文件prototxt
def Lenet(img_list,batch_size,include_acc=False):
#第一層,數據輸入層,以ImageData格式輸入
data, label = L.ImageData(source=img_list, batch_size=batch_size, ntop=2,root_folder=root,
transform_param=dict(scale= 0.00390625))
#第二層:卷積層
conv1=L.Convolution(data, kernel_size=5, stride=1,num_output=20, pad=0,weight_filler=dict(type='xavier'))
#池化層
pool1=L.Pooling(conv1, pool=P.Pooling.MAX, kernel_size=2, stride=2)
#卷積層
conv2=L.Convolution(pool1, kernel_size=5, stride=1,num_output=50, pad=0,weight_filler=dict(type='xavier'))
#池化層
pool2=L.Pooling(conv2, pool=P.Pooling.MAX, kernel_size=2, stride=2)
#全連接層
fc3=L.InnerProduct(pool2, num_output=500,weight_filler=dict(type='xavier'))
#激活函數層
relu3=L.ReLU(fc3, in_place=True)
#全連接層
fc4 = L.InnerProduct(relu3, num_output=10,weight_filler=dict(type='xavier'))
#softmax層
loss = L.SoftmaxWithLoss(fc4, label)
if include_acc: # test階段需要有accuracy層
acc = L.Accuracy(fc4, label)
return to_proto(loss, acc)
else:
return to_proto(loss)
def write_net():
#寫入train.prototxt
with open(train_proto, 'w') as f:
f.write(str(Lenet(train_list,batch_size=64)))
#寫入test.prototxt
with open(test_proto, 'w') as f:
f.write(str(Lenet(test_list,batch_size=100, include_acc=True)))
配置文件里面存放的,就是我們所說的network。我這里生成的network,可能和原始的Lenet不太一樣,不過影響不大。
三、生成參數文件solver
同樣,可以在編輯器里面直接書寫,也可以用代碼生成。
#編寫一個函數,生成參數文件
def gen_solver(solver_file,train_net,test_net):
s=proto.caffe_pb2.SolverParameter()
s.train_net =train_net
s.test_net.append(test_net)
s.test_interval = 938 #60000/64,測試間隔參數:訓練完一次所有的圖片,進行一次測試
s.test_iter.append(100) #10000/100 測試迭代次數,需要迭代100次,才完成一次所有數據的測試
s.max_iter = 9380 #10 epochs , 938*10,最大訓練次數
s.base_lr = 0.01 #基礎學習率
s.momentum = 0.9 #動量
s.weight_decay = 5e-4 #權值衰減項
s.lr_policy = 'step' #學習率變化規則
s.stepsize=3000 #學習率變化頻率
s.gamma = 0.1 #學習率變化指數
s.display = 20 #屏幕顯示間隔
s.snapshot = 938 #保存caffemodel的間隔
s.snapshot_prefix =root+'mnist/lenet' #caffemodel前綴
s.type ='SGD' #優化算法
s.solver_mode = proto.caffe_pb2.SolverParameter.GPU #加速
#寫入solver.prototxt
with open(solver_file, 'w') as f:
f.write(str(s))
四、開始訓練模型
訓練過程中,也在不停的測試。
#開始訓練
def training(solver_proto):
caffe.set_device(0)
caffe.set_mode_gpu()
solver = caffe.SGDSolver(solver_proto)
solver.solve()
最后,調用以上的函數就可以了。
if __name__ == '__main__':
write_net()
gen_solver(solver_proto,train_proto,test_proto)
training(solver_proto)
五、完成的python文件
mnist.py
# -*- coding: utf-8 -*-
import caffe
from caffe import layers as L,params as P,proto,to_proto
#設定文件的保存路徑
root='/home/xxx/' #根目錄
train_list=root+'mnist/train/train.txt' #訓練圖片列表
test_list=root+'mnist/test/test.txt' #測試圖片列表
train_proto=root+'mnist/train.prototxt' #訓練配置文件
test_proto=root+'mnist/test.prototxt' #測試配置文件
solver_proto=root+'mnist/solver.prototxt' #參數文件
#編寫一個函數,生成配置文件prototxt
def Lenet(img_list,batch_size,include_acc=False):
#第一層,數據輸入層,以ImageData格式輸入
data, label = L.ImageData(source=img_list, batch_size=batch_size, ntop=2,root_folder=root,
transform_param=dict(scale= 0.00390625))
#第二層:卷積層
conv1=L.Convolution(data, kernel_size=5, stride=1,num_output=20, pad=0,weight_filler=dict(type='xavier'))
#池化層
pool1=L.Pooling(conv1, pool=P.Pooling.MAX, kernel_size=2, stride=2)
#卷積層
conv2=L.Convolution(pool1, kernel_size=5, stride=1,num_output=50, pad=0,weight_filler=dict(type='xavier'))
#池化層
pool2=L.Pooling(conv2, pool=P.Pooling.MAX, kernel_size=2, stride=2)
#全連接層
fc3=L.InnerProduct(pool2, num_output=500,weight_filler=dict(type='xavier'))
#激活函數層
relu3=L.ReLU(fc3, in_place=True)
#全連接層
fc4 = L.InnerProduct(relu3, num_output=10,weight_filler=dict(type='xavier'))
#softmax層
loss = L.SoftmaxWithLoss(fc4, label)
if include_acc: # test階段需要有accuracy層
acc = L.Accuracy(fc4, label)
return to_proto(loss, acc)
else:
return to_proto(loss)
def write_net():
#寫入train.prototxt
with open(train_proto, 'w') as f:
f.write(str(Lenet(train_list,batch_size=64)))
#寫入test.prototxt
with open(test_proto, 'w') as f:
f.write(str(Lenet(test_list,batch_size=100, include_acc=True)))
#編寫一個函數,生成參數文件
def gen_solver(solver_file,train_net,test_net):
s=proto.caffe_pb2.SolverParameter()
s.train_net =train_net
s.test_net.append(test_net)
s.test_interval = 938 #60000/64,測試間隔參數:訓練完一次所有的圖片,進行一次測試
s.test_iter.append(500) #50000/100 測試迭代次數,需要迭代500次,才完成一次所有數據的測試
s.max_iter = 9380 #10 epochs , 938*10,最大訓練次數
s.base_lr = 0.01 #基礎學習率
s.momentum = 0.9 #動量
s.weight_decay = 5e-4 #權值衰減項
s.lr_policy = 'step' #學習率變化規則
s.stepsize=3000 #學習率變化頻率
s.gamma = 0.1 #學習率變化指數
s.display = 20 #屏幕顯示間隔
s.snapshot = 938 #保存caffemodel的間隔
s.snapshot_prefix = root+'mnist/lenet' #caffemodel前綴
s.type ='SGD' #優化算法
s.solver_mode = proto.caffe_pb2.SolverParameter.GPU #加速
#寫入solver.prototxt
with open(solver_file, 'w') as f:
f.write(str(s))
#開始訓練
def training(solver_proto):
caffe.set_device(0)
caffe.set_mode_gpu()
solver = caffe.SGDSolver(solver_proto)
solver.solve()
#
if __name__ == '__main__':
write_net()
gen_solver(solver_proto,train_proto,test_proto)
training(solver_proto)
我將此文件放在根目錄下的mnist文件夾下,因此可用以下代碼執行
sudo python mnist/mnist.py
在訓練過程中,會保存一些caffemodel。多久保存一次,保存多少次,都可以在solver參數文件里進行設置。
我設置為訓練10 epoch,9000多次,測試精度可以達到99%
原文鏈接:https://www.cnblogs.com/denny402/p/5684431.html
相關推薦
- 2023-12-02 富文本組件中圖片間空白處理小技巧
- 2022-08-04 Android解決所有雙擊優化的問題_Android
- 2022-05-29 C++重載運算符你真的了解嗎_C 語言
- 2023-05-22 Redis數據結構原理淺析_Redis
- 2022-12-07 C++?Boost?Container庫示例詳細講解_C 語言
- 2023-01-05 Kotlin?泛型邊界型變及星投影使用詳解_Android
- 2022-07-22 CSS設置元素隱藏的4種方法
- 2023-03-27 Android進階之從IO到NIO的模型機制演進_Android
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支