iT邦幫忙

2021 iThome 鐵人賽

DAY 22
0
AI & Data

30Day 從一介凡人羽化成資料科學初學者系列 第 22

Day22-pytorch(5)簡單示範regression模型

先import各種會用到的套件
https://ithelp.ithome.com.tw/upload/images/20210904/20140416ExUeliHPAo.png

使用sklearn的datasets套件建立要regression的資料集
https://ithelp.ithome.com.tw/upload/images/20210904/20140416KikrDlEINW.png

pytorch做regression時,y資料的dimension需改成2,shape為(資料個數,1)
使用reshape來改變成想要的shape
https://ithelp.ithome.com.tw/upload/images/20210904/20140416K6z5uKSGjR.png

對特徵值做正規畫以利訓練model
https://ithelp.ithome.com.tw/upload/images/20210904/20140416D2dgM0QEom.png

須將資料型態轉為tensor,不然pytorch寫出來的模型不會裡你
https://ithelp.ithome.com.tw/upload/images/20210904/20140416aQc7DnkuQJ.png

建立Dataset
https://ithelp.ithome.com.tw/upload/images/20210904/20140416Su2t50h2P7.png

建立DataLoader
https://ithelp.ithome.com.tw/upload/images/20210904/20140416Xf3jYxeGQP.png

建立model
https://ithelp.ithome.com.tw/upload/images/20210904/20140416RPU4Dxx5EZ.png

設置loss function、optimizer、epoch、n_batch
critirion就是loss function,使用MSE
optimizer使用adam
epoch設置資料要訓練幾次
n_batch為dataloader的長度,也就是每一個epoch裡面能分成幾個組合
我們在dataloader時設置batch_size為100
資料集總共有1000個,所以n_batch等於1000/100=10
https://ithelp.ithome.com.tw/upload/images/20210904/20140416ulqe6HtWXA.png

開始訓練
最外面的迴圈range為epoch,表示會根據epoch設計的次數來訓練資料
裡面的迴圈使用了enumerate後方參數放入data_loader,因batch_size設為100
j會從0~99(batch_size-1)
samples會獲得100(batch_size)筆特徵值資料,也就是x_data
labels會獲得100(batch_size)筆目標值資料,也就是y_data
https://ithelp.ithome.com.tw/upload/images/20210904/20140416903J3SBk9j.png
print出的訓練過程
https://ithelp.ithome.com.tw/upload/images/20210904/20140416Qof4prdkyN.png

送上colab連結,可自行在上面多做點練習更加熟悉pytorch
https://colab.research.google.com/drive/14fN4RhEF-jIjkjuifJDYyaVLgKYRKyuV?usp=sharing


上一篇
Day21-pytorch(4)Dataset、DataLoader
下一篇
Day23-pytorch(6)iris資料集示範classifier模型pytorch完整訓練過程
系列文
30Day 從一介凡人羽化成資料科學初學者30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言