生成資料集
1.1 假設乙個w, b
1.2 設定資料集的大小
1.3 隨機化資料點,也就是資料集和標籤(feature, label)
torch.manual_seed 隨機數種子, 使每次生成的隨機資料集相同
np.random.seed 用法同於torch.manual_seed
編寫需要運用到的函式
2.1 mini_batch分割資料集
2.2 定義模型
2.3 定義損失函式
2.4 使用梯度下降法來更新w, b
np.random.shuffle 隨機打亂資料
index_select(軸, 需要查詢的元素) 按照索引查詢元素
torch.mm 矩陣相乘(注意兩個向量的維度)
訓練模型
3.1 初始化引數(w, b, 包括一些超引數)
3.2 呼叫已經寫好的函式, 按照分批資料集、構建模型、計算損失、反向傳播、更新引數的順序進行訓練模型
3.3 用假設的w, b 和已經訓練好的w, b進行對比, 來評測模型的效能
import numpy as np
import torch
# 生成資料集
torch.manual_seed(2)
true_w =[2
,-3.4]
true_b =
2.6input_shape =
2element_shape =
1000
feature= torch.randn(
(element_shape, input_shape)
, dtype=torch.float32)
label = true_w[0]
* feature[:,
0]+ true_w[1]
* feature[:,
1]+ true_b
np.random.seed(2)
label += torch.tensor(np.random.normal(0,
.001
, size=label.shape)
, dtype=torch.float32)
label = label.reshape(-1
,1)print
(feature.shape)
print
(label.shape)
def
mini_batch_data
(batch, feature, label)
:"""
batch: 每個批次大小
feature: 資料集
label: 標籤
return: iter
"""idxs =
list
(range
(len
(label)))
np.random.shuffle(idxs)
for i in
range(0
,len
(label)
, batch)
: index = torch.longtensor(idxs[i:
min(i + batch,
len(label))]
)yield feature.index_select(
0, index)
, label.index_select(
0, index)
# 設定每個批次為64
mini_batch =
64# for x, y in mini_batch_data(mini_batch, feature, label):
# print(x.shape, y.shape)
# break
defmodel_nn
(x, w, b)
:"""
x: 資料集
w: 權重
b: 偏置
return: 線性模型
"""return torch.mm(x, w)
+ bdef
mse_loss
(y, y_hat)
:"""
y: label真實值
y_hat: 模型**值
return: mseloss
"""return
(y_hat - y)**2
/2defoptim
(para, alpha, batch)
:"""
para: 引數
alpha: 學習率
batch: 批次大小
"""for i in para:
# 在沒有梯度的情況下操作引數
i.data -= i.grad * alpha / batch
# 初始化引數
w = torch.tensor(np.random.normal(0,
0.001
,(input_shape,1)
), dtype=torch.float32)
b = torch.zeros(
1, dtype=torch.float32)
# 讓w, b在計算中保留梯度
w.requires_grad_(requires_grad=
true
)b.requires_grad_(requires_grad=
true
)# 初始化超引數
lr =
0.01
epochs =
150for epoch in
range
(epochs)
:# 批次載入資料集
for x, y in mini_batch_data(mini_batch, feature, label)
:# 模型
net = model_nn(x, w, b)
# 損失
loss = mse_loss(y, net)
.sum()
# 反向傳播
loss.backward(
)# 梯度下降
optim(
[w, b]
, lr, mini_batch)
# 清零梯度
w.grad.data.zero_(
) w.grad.data.zero_(
)
test = model_nn(feature, w, b)
loss = mse_loss(label, test)
.mean(
)if epoch %
10==0:
print
(f"loss: "
)
print
(w, true_w)
print()
print
(b, true_b)
"""output:
tensor([[ 1.9820],
[-3.4100]], requires_grad=true) [2, -3.4]
tensor([2.1723], requires_grad=true) 2.6
"""
注意: 建好資料集最好加上資料型別, 我就在這個問題上糾結了半天 Python 小白的學習第2天
簡單的總結 縮排很重要,python省略了很多引號啊,中括號什麼的,靠縮進來進行劃分,縮排2個空格和縮排4個空格是不一樣的,這和matlab有著很大區別。語法還是很簡單的,感覺和matlab挺像的啊!在pycharm裡寫了第一行 print the big whale love the small ...
小白第3天
a 什麼是垃圾 當乙個值身上沒有繫結任何變數名 即該值的引用計數為0 時,該值就是乙個垃圾。b 引用計數增加 2 變數值的三個特徵 b type 反應資料型別.c 值d 總結 i.id位址相同,值一定相同 ii.值相同,id位址有可能不相同。3 is 與 b 判斷值是否相等 4 可變型與不可變型 a...
小白之深度學習入門
深度學習最近這幾年炒的特別熱,而且在計算機視覺方面應用廣泛,故而決定學習了解一波。那麼,第乙個問題就來了,什麼是機器學習?哇咔咔,這個光看名字就知道了,就是讓機器具有人類不斷學習的能力,並且解決我們現有的一些問題。先來說幾個簡單的概念 特徵 就是物體的屬性,我們人類經過學習之後,可以很快的將簡單的特...