pytorch学习第一次打卡
目录
Task01
线性回归
线性回归假设输出与各个输入之间是线性关系,如
p
r
i
c
e
=
w
a
r
e
a
⋅
a
r
e
a
+
w
a
g
e
⋅
a
g
e
+
b
price=w_{area} ⋅ area + w_{age} ⋅ age + b
price=warea⋅area+wage⋅age+b
损失函数表达式:
$$
l^{(i)}(w,b)=\frac{ 1}{2 }(y{(i)}−y{(i)})^2,
$$
L ( w , b ) = 1 n ∑ l ( i ) ( w , b ) = 1 n ∑ i = 1 n 1 2 ( w ⊤ x ( i ) + b − y ( i ) ) 2 . L(w,b)=\frac{1}{n}∑l^{(i)}(w,b)=\frac{1}{n}∑_{i=1}^n\frac{1}{2}(w^⊤x^{(i)}+b−y^{(i)})^2. L(w,b)=n1∑l(i)(w,b)=n1i=1∑n21(w⊤x(i)+b−y(i))2.
代码实现:
import torch
from torch import nn
import numpy as np
torch.manual_seed(1)
#定义模型
class LinearNet(nn.Module):
def __init__(self, n_feature):
super(LinearNet, self).__init__()
self.linear = nn.Linear(n_feature, 1)
def forward(self, x):
y = self.linear(x)
return y
net = LinearNet(num_inputs)
print(net)
net = nn.Sequential(
nn.Linear(num_inputs, 1)
)
print(net)
print(net[0])
#初始化模型参数
from torch.nn import init
init.normal_(net[0].weight, mean=0.0, std=0.01)
init.constant_(net[0].bias, val=0.0)
for param in net.parameters():
print(param)
#定义损失函数
loss = nn.MSELoss()
#定义优化函数
import torch.optim as optim
optimizer = optim.SGD(net.parameters(), lr=0.03)
print(optimizer)
softmax和分类模型
softmax回归是一个单层神经网络
分类问题需要得到离散的预测输出,一个简单的办法是将输出值oi当作预测类别是i的置信度,并将值最大的输出所对应的类作为预测输出,即输出 argmaxioi。例如,如果o1,o2,o3分别为0.1,10,0.1由于o2最大,那么预测类别为2,其代表猫。
softmax可以拿来做归一化。
部分定义代码:
#定义损失函数
def softmax(X):
X_exp = X.exp()
partition = X_exp.sum(dim=1, keepdim=True)
return X_exp / partition # 这里应用了广播机制
#softmax回归模型
def net(X):
return softmax(torch.mm(X.view((-1, num_inputs)), W) + b)
#定义损失函数
y_hat = torch.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
y = torch.LongTensor([0, 2])
y_hat.gather(1, y.view(-1, 1))
def cross_entropy(y_hat, y):
return - torch.log(y_hat.gather(1, y.view(-1, 1)))
#定义准确率
def accuracy(y_hat, y):
return (y_hat.argmax(dim=1) == y).float().mean().item()
多层感知机
多层感知机就是含有至少一个隐藏层的由全连接层组成的神经网络,且每个隐藏层的输出通过激活函数进行变换。多层感知机的层数和各隐藏层中隐藏单元个数都是超参数。以单隐藏层为例并沿用本节之前定义的符号,多层感知机按以下方式计算输出:
H
=
ϕ
(
X
W
h
+
b
h
)
,
H=ϕ(XW_h+b_h),
H=ϕ(XWh+bh),
O = H W o + b o , O=HW_o+b_o, O=HWo+bo,
其中ϕ表示激活函数。
部分代码:
#初始化模型和各个参数
num_inputs, num_outputs, num_hiddens = 784, 10, 256
net = nn.Sequential(
d2l.FlattenLayer(),
nn.Linear(num_inputs, num_hiddens),
nn.ReLU(),
nn.Linear(num_hiddens, num_outputs),
)
for params in net.parameters():
init.normal_(params, mean=0, std=0.01)
未完待续