Pytorch
1.torch语法基本学习
基本上与numpy非常相似
1.1 生成数组
1.2 shape属性
访问张量(沿每个轴的长度)的形状
1.3 统计元素个数
1.4 reshape
重新构造形状
1.5 zeros ones randn(均值为0、标准差为1的标准高斯分布(正态分布))
1.6 cat(链接数组)
1.7 索引和切片
回顾之前所学的python 线性代数 概率论 高等数学的知识
2.线性神经网络
2.1 生成数据集
def synthetic_data(w, b, num_examples):
//"""生成y=Xw+b+噪声"""
X = torch.normal(0, 1, (num_examples, len(w)))
y = torch.matmul(X, w) + b
y += torch.normal(0, 0.01, y.shape) //添加噪声
return X, y.reshape((-1, 1)) //reshape 将y转变成列向量
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = synthetic_data(true_w, true_b, 1000)
2.2 读取数据集
def data_iter(batch_size, features, labels):
num_examples = len(features)
indices = list(range(num_examples))
# 这些样本是随机读取的,没有特定的顺序
random.shuffle(indices) //打乱样本的数据
for i in range(0, num_examples, batch_size):
//10个样本一组
batch_indices = torch.tensor(
indices[i: min(i + batch_size, num_examples)])
yield features[batch_indices], labels[batch_indices]
2.3 初始化模型
w = torch.normal(0, 0.01, size=(2,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
2.4 定义模型
def linreg(X, w, b):
"""线性回归模型"""
return torch.matmul(X, w) + b
2.5 定义损失函数
def squared_loss(y_hat, y): #@save
"""均方损失"""
return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2 //除2是为了让求导数时前面系数设置为1
2.6 定义优化算法
def sgd(params, lr, batch_size): #@save
"""小批量随机梯度下降"""
with torch.no_grad():
for param in params:
param -= lr * param.grad / batch_size //找到更好的一组w,b 让Loss尽可能地小
param.grad.zero_()
2.7 训练
lr = 0.03
num_epochs = 3
net = linreg
loss = squared_loss
for epoch in range(num_epochs):
for X, y in data_iter(batch_size, features, labels):
l = loss(net(X, w, b), y) # X和y的小批量损失
# 因为l形状是(batch_size,1),而不是一个标量。l中的所有元素被加到一起,
# 并以此计算关于[w,b]的梯度
l.sum().backward()
sgd([w, b], lr, batch_size) # 使用参数的梯度更新参数
with torch.no_grad():
train_l = loss(net(features, w, b), labels)
print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')
以上的方法比较复杂,较为简洁的方法已在nn中实现
3.Softmax回归
多分类问题
3.1 softmax运算
softmax运算不会改变未规范化的预测𝑜之间的大小次序,只会确定分配给每个类别的概率。
3.2 softmax及其导数
4.多层感知机
通过增加层数也就是deep 来找到更好的feature
线性模型比较单调 对数据的变化较为敏感 任何特征的增大都会导致模型输出的增大(如果对应的权重为正), 或者导致模型输出的减小(如果对应的权重为负)
通过在网络中加入一个或多个隐藏层来克服线性模型的限制, 使其能处理更普遍的函数关系类型。 要做到这一点,最简单的方法是将许多全连接层堆叠在一起。 每一层都输出到上面的层,直到生成最后的输出。 我们可以把前𝐿−1层看作表示,把最后一层看作线性预测器。 这种架构通常称为多层感知机(multilayer perceptron)。
4.卷积神经网络
对于高维感知数据,这种缺少结构的网络可能会变得不实用 卷积神经网络正是将空间不变性(spatial invariance)的这一概念系统化,从而基于这个模型使用较少的参数来学习有用的表示。