一、线性模型
import numpy as np import matplotlib.pyplot as plt x_data = [1.0, 2.0, 3.0] y_data = [2.0, 4.0, 6.0] def forward(x): return x * w def loss(x, y): y_pred = forward(x) return (y_pred - y) * (y_pred - y) w_list = [] mse_list = [] for w in np.arange(0.0, 4.1, 0.1): print('w=', w) l_sum = 0 for x_val, y_val in zip(x_data, y_data): y_pred_val = forward(x_val) loss_val = loss(x_val, y_val) l_sum += loss_val print('\t', x_val, y_val, y_pred_val, loss_val) print('MSE=', l_sum / 3) w_list.append(w) mse_list.append(l_sum / 3) plt.plot(w_list, mse_list) plt.ylabel('Loss') plt.xlabel('w') plt.show()
运行截图如下:
梯度下降
以模型 为例,梯度下降算法就是一种训练参数 到最佳值的一种算法, 每次变化的趋势由 (学习率:一种超参数,由人手动设置调节),以及 的导数来决定,具体公式如下:
注: 此时函数是指所有的损失函数之和
针对模型 的梯度下降算法的公式化简如下:
# 输入训练数据 x_data = [1.0, 2.0, 3.0] y_data = [2.0, 4.0, 6.0] # 设置初始参数 w = 1.0 # 初始权重 alpha = 0.005 #初始梯度下降法的学习率 # 定义计算y_hat的函数 def forward(x): return x * w # 定义计算平均损失的函数 def cost(xs, ys): sum_cost = 0 for x, y in zip(xs, ys): # zip函数的功能是打包为元组列表 y_pred = forward(x) sum_cost += (y_pred - y) ** 2 return sum_cost / len(xs) def gradient(xs, ys): grad = 0 for x, y in zip(xs, ys): grad += 2 * x * (x * w - y) return grad / len(xs) print('Predict (before training)', 4, forward(4)) # 计算训练前初始参数对应的y_hat值 for epoch in range(1000): cost_val = cost(x_data, y_data) # 计算平均损失值 grad_val = gradient(x_data, y_data) # 计算梯度值 w -= alpha * grad_val # 更新权重w print('Epoch', epoch, 'w = ', w, 'loss = ', cost_val) # 输出当前迭代次数的权重值和平均损失值 print('Predict (after training)', 4, forward(4)) #计算训练权重w后,对应的y_hat值
随机梯度下降
随机梯度下降算法与梯度下降算法的不同之处在于,随机梯度下降算法不再计算损失函数之和的导数,而是随机选取任一随机函数计算导数,随机的决定 下次的变化趋势,具体公式变化如图:
# 输入训练数据 x_data = [1.0, 2.0, 3.0] y_data = [2.0, 4.0, 6.0] # 设置初始参数 w = 1.0 # 初始权重 alpha = 0.005 #初始梯度下降法的学习率 # 定义计算y_hat的函数 def forward(x): return x * w # 定义计算单个样本损失的函数 def loss(xs, ys): y_pred = forward(x) # 计算预测值y_hat single_lost = (y_pred - ys) ** 2 # 计算误差 return single_lost def gradient(xs, ys): grad = 2 * x * (x * w - y) return grad print('Predict (before training)', 4, forward(4)) # 计算训练前初始参数对应的y_hat值 for epoch in range(1000): # 迭代次数 for x, y in zip(x_data, y_data): # 遍历数据 grad_val = gradient(x, y) # 计算当前数据的梯度值 w -= alpha * grad_val # 更新权重w print("\tgrad: ", x, y, grad_val) los = loss(x, y) # 计算当前数据的损失值 print('progress: ', epoch, 'w = ', w, 'loss = ', los) print('Predict (after training)', 4, forward(4)) # 计算训练权重w后,对应的y_hat值 反向传播 import torch x_data = [1.0, 2.0, 3.0] y_data = [2.0, 4.0, 6.0] w = torch.Tensor([1.0]) w.requires_grad = True # 需要计算梯度 def forward(x): return x * w # tensor def loss(x, y): y_pred = forward(x) return (y_pred - y) ** 2 print('predict (before training)', 4, forward(4).item()) for epoch in range(100): for x, y in zip(x_data, y_data): l = loss(x, y) # 前向,计算loss l.backward() # 做完后计算图会释放 print('\tgrad:', x, y, w.grad.item()) # item取值,要是张量计算图一直累积 w.data -= 0.01 * w.grad.data # 不取data会是TENSOR有计算图 w.grad.data.zero_() # 计算出来的梯度不清零会累加 print("progress:", epoch, l.item()) print('predict (after training)', 4, forward(4).item())
二、Pytorch实战--线性回归
# 1、算预测值 # 2、算loss # 3、梯度设为0,并反向传播 # 3、梯度更新 import torch x_data = torch.Tensor([[1.0], [2.0], [3.0]]) y_data = torch.Tensor([[2.0], [4.0], [6.0]]) # 构造线性模型,后面都是使用这样的模板 # 至少实现两个函数,__init__构造函数和forward()前馈函数 # backward()会根据我们的计算图自动构建 # 可以继承Functions来构建自己的计算块 class LinerModel(torch.nn.Module): def __init__(self): # 调用父类的构造 super(LinerModel, self).__init__() # 构造Linear这个对象,对输入数据做线性变换 # class torch.nn.Linear(in_features, out_features, bias=True) # in_features - 每个输入样本的大小 # out_features - 每个输出样本的大小 # bias - 若设置为False,这层不会学习偏置。默认值:True self.linear = torch.nn.Linear(1, 1) def forward(self, x): y_pred = self.linear(x) return y_pred model = LinerModel() # 实例化,可调用 # 定义MSE(均方差)损失函数,size_average=False不求均值 criterion = torch.nn.MSELoss(size_average=False) # optim优化模块的SGD,第一个参数就是传递权重,model.parameters()model的所有权重 # 优化器对象 optimizer = torch.optim.SGD(model.parameters(), lr=0.01) for epoch in range(100): y_pred = model(x_data) loss = criterion(y_pred, y_data) # loss为一个对象,loss不会产生计算图,但会自动调用__str__()所以不会出错 print(epoch, loss) # 梯度归零 optimizer.zero_grad() # 反向传播 loss.backward() # 根据梯度和预先设置的学习率进行更新(权重更新) optimizer.step() # 打印权重和偏置值,weight是一个值但是一个矩阵 print('w=', model.linear.weight.item()) print('b=', model.linear.bias.item()) # 测试 x_test = torch.Tensor([4.0]) y_test = model(x_test) print('y_pred=', y_test.data)
三、Pytorch实战--逻辑回归
import torch import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt x_data = torch.Tensor([[1.0], [2.0], [3.0]]) y_data = torch.Tensor([[0], [0], [1]]) ## class LogisticRegressionModel(torch.nn.Module): def __init__(self): #构造函数 super(LogisticRegressionModel, self).__init__() self.linear = torch.nn.Linear(1, 1) #线性层 def forward(self, x): y_pred = F.sigmoid(self.linear(x)) #激活函数 return y_pred model = LogisticRegressionModel() ## criterion = torch.nn.BCELoss(size_average = False) #计算损失 optimizer = torch.optim.SGD(model.parameters(), lr = 0.01) #优化器 ## for epoch in range(1000): y_pred = model(x_data) loss = criterion(y_pred, y_data) print(epoch, loss.item()) optimizer.zero_grad() # 梯度置0 loss.backward() # 计算梯度,反向传播 optimizer.step() # 更新参数 ## x = np.linspace(0, 10, 200) x_t = torch.Tensor(x).view((200, 1)) y_t = model(x_t) y = y_t.data.numpy() plt.plot(x, y) plt.plot([0, 10], [0.5, 0.5], c='r') plt.xlabel('Hours') plt.ylabel('Probability of Pass') plt.grid() plt.show() 处理多维特征的输入 import numpy as np import torch xy = np.loadtxt('diabetes.csv.gz', delimiter=',', dtype=np.float32) x_data = torch.from_numpy(xy[:, :-1]) # [-1]加中括号拿出来是矩阵,不加是向量 y_data = torch.from_numpy(xy[:, [-1]]) class Model(torch.nn.Module): def __init__(self): super(Model, self).__init__() self.linear1 = torch.nn.Linear(8, 6) self.linear2 = torch.nn.Linear(6, 4) self.linear3 = torch.nn.Linear(4, 1) # 这是nn下的Sigmoid是一个模块没有参数,在function调用的Sigmoid是函数 self.sigmoid = torch.nn.Sigmoid() def forward(self, x): x = self.sigmoid(self.linear1(x)) x = self.sigmoid(self.linear2(x)) x = self.sigmoid(self.linear3(x)) return x model = Model() criterion = torch.nn.BCELoss(size_average=True) # 损失函数 optimizer = torch.optim.SGD(model.parameters(), lr=0.1) # 优化函数,随机梯度递减 for epoch in range(100): # 前馈 y_pred = model(x_data) loss = criterion(y_pred, y_data) print(epoch, loss.item()) # 反馈 optimizer.zero_grad() loss.backward() # 更新 optimizer.step() 加载数据集 import numpy as np import torch from torch.utils.data import Dataset # Dataset是一个抽象类,只能被继承,不能实例化 from torch.utils.data import DataLoader # 可以直接实例化 ''' 四步:准备数据集-设计模型-构建损失函数和优化器-周期训练 ''' class DiabetesDataset(Dataset): def __init__(self, filepath): xy = np.loadtxt(filepath, delimiter=',', dtype=np.float32) self.len = xy.shape[0] self.x_data = torch.from_numpy(xy[:, :-1]) self.y_data = torch.from_numpy(xy[:, [-1]]) def __getitem__(self, index): # 实例化对象后,该类能支持下标操作,通过index拿出数据 return self.x_data[index], self.y_data[index] def __len__(self): return self.len dataset = DiabetesDataset('diabetes.csv.gz') # dataset数据集,batch_size小批量的容量,shuffle是否要打乱,num_workers要几个并行进程来读 # DataLoader的实例化对象不能直接使用,因为windows和linux的多线程运行不一样,所以一般要放在函数里运行 train_loader = DataLoader(dataset=dataset, batch_size=32, shuffle=True, num_workers=2) class Model(torch.nn.Module): def __init__(self): super(Model, self).__init__() self.linear1 = torch.nn.Linear(8, 6) self.linear2 = torch.nn.Linear(6, 4) self.linear3 = torch.nn.Linear(4, 1) # 这是nn下的Sigmoid是一个模块没有参数,在function调用的Sigmoid是函数 self.sigmoid = torch.nn.Sigmoid() def forward(self, x): x = self.sigmoid(self.linear1(x)) x = self.sigmoid(self.linear2(x)) x = self.sigmoid(self.linear3(x)) return x model = Model() criterion = torch.nn.BCELoss(size_average=True) # 损失函数 optimizer = torch.optim.SGD(model.parameters(), lr=0.1) # 优化函数,随机梯度递减 # 变成嵌套循环,实现Mini-Batch for epoch in range(100): # 从数据集0开始迭代 # 可以简写为for i, (inputs, labels) in enumerate(train_loader, 0): for i, data in enumerate(train_loader, 0): # 准备数据 inputs, labels = data # 前馈 y_pred = model(inputs) loss = criterion(y_pred, labels) print(epoch, i, loss.item()) # 反馈 optimizer.zero_grad() loss.backward() # 更新 optimizer.step() 多分类问题 import torch from torchvision import transforms # 对图像进行处理的工具 from torchvision import datasets from torch.utils.data import DataLoader import torch.nn.functional as F # 使用激活函数relu()的包 import torch.optim as optim # 优化器的包 batch_size = 64 # 对图像进行预处理,将图像转换为 transform = transforms.Compose([ # 将原始图像PIL变为张量tensor(H*W*C),再将[0,255]区间转换为[0.1,1.0] transforms.ToTensor(), # 使用均值和标准差对张量图像进行归一化 transforms.Normalize((0.1307,), (0.3081,)) ]) train_dataset = datasets.MNIST(root='dataset/mnist/', train=True, download=True, transform=transform) train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size) test_dataset = datasets.MNIST(root='dataset/mnist/', train=False, download=True, transform=transform) test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size) class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() self.l1 = torch.nn.Linear(784, 512) self.l2 = torch.nn.Linear(512, 256) self.l3 = torch.nn.Linear(256, 128) self.l4 = torch.nn.Linear(128, 64) self.l5 = torch.nn.Linear(64, 10) def forward(self, x): # 改变形状,相当于numpy的reshape # view中一个参数定为-1,代表动态调整这个维度上的元素个数,以保证元素的总数不变。 x = x.view(-1, 784) x = F.relu(self.l1(x)) x = F.relu(self.l2(x)) x = F.relu(self.l3(x)) x = F.relu(self.l4(x)) return self.l5(x) model = Net() # 交叉熵损失函数 criterion = torch.nn.CrossEntropyLoss() # model.parameters()直接使用的模型的所有参数 optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5) # momentum动量 def train(epoch): running_loss = 0.0 # 返回了数据下标和数据 for batch_idx, data in enumerate(train_loader, 0): # 送入两个张量,一个张量是64个图像的特征,一个张量图片对应的数字 inputs, target = data # 梯度归零 optimizer.zero_grad() # forward+backward+update outputs = model(inputs) # 计算损失,用的交叉熵损失函数 loss = criterion(outputs, target) # 反馈 loss.backward() # 随机梯度下降更新 optimizer.step() # 每300次输出一次 running_loss += loss.item() if batch_idx % 300 == 299: print('[%d,%5d] loss:%.3f' % (epoch + 1, batch_idx + 1, running_loss / 300)) running_loss = 0.0 def test(): correct = 0 total = 0 # 不会计算梯度 with torch.no_grad(): for data in test_loader: # 拿数据 images, labels = data outputs = model(images) # 预测 # outputs.data是一个矩阵,每一行10个量,最大值的下标就是预测值 _, predicted = torch.max(outputs.data, dim=1) # 沿着第一维度,找最大值的下标,返回最大值和下标 total += labels.size(0) # labels.size(0)=64 每个都是64个元素,就可以计算总的元素 # (predicted == labels).sum()这个是张量,而加了item()变为一个数字,即相等的数量 correct += (predicted == labels).sum().item() print('Accuracy on test set:%d %%' % (100 * correct / total)) # 正确的数量除以总数 if __name__ == '__main__': for epoch in range(10): train(epoch) test()
卷积神经网络
简单的构建
import torch # 输入的通道就是上图的n,输出的通道就是上图的m in_channels, out_channels = 5, 10 width, height = 100, 100 # 图像的大小 kernel_size = 3 # 卷积盒的大小 batch_size = 1 # 批量大小 # 随机生成了一个小批量=1的5*100*100的张量 input = torch.randn(batch_size, in_channels, width, height) # Conv2d对由多个输入平面组成的输入信号进行二维卷积 conv_layer = torch.nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size) output = conv_layer(input) # print(input) print(input.shape) print(output.shape) print(conv_layer.weight.shape)
torch.Size([1, 5, 100, 100]) torch.Size([1, 10, 98, 98]) torch.Size([10, 5, 3, 3]) padding import torch input = [3, 4, 6, 5, 7, 2, 4, 6, 8, 2, 1, 6, 7, 8, 4, 9, 7, 4, 6, 2, 3, 7, 5, 4, 1] input = torch.Tensor(input).view(1, 1, 5, 5) # bias=False不加偏置量 conv_layer = torch.nn.Conv2d(1, 1, kernel_size=3, padding=1, bias=False) kernel = torch.Tensor([1, 2, 3, 4, 5, 6, 7, 8, 9]).view(1, 1, 3, 3) # 把kernel赋值给卷积层权重,做初始化 conv_layer.weight.data = kernel.data output = conv_layer(input) print(output)
tensor([[[[ 91., 168., 224., 215., 127.], [114., 211., 295., 262., 149.], [192., 259., 282., 214., 122.], [194., 251., 253., 169., 86.], [ 96., 112., 110., 68., 31.]]]], grad_fn=<ThnnConv2DBackward>) Layer-stride步长 import torch input = [3, 4, 6, 5, 7, 2, 4, 6, 8, 2, 1, 6, 7, 8, 4, 9, 7, 4, 6, 2, 3, 7, 5, 4, 1] input = torch.Tensor(input).view(1, 1, 5, 5) # bias=False不加偏置量 conv_layer = torch.nn.Conv2d(1, 1, kernel_size=3, stride=2, bias=False) kernel = torch.Tensor([1, 2, 3, 4, 5, 6, 7, 8, 9]).view(1, 1, 3, 3) # 把kernel赋值给卷积层权重,做初始化 conv_layer.weight.data = kernel.data output = conv_layer(input) print(output)
tensor([[[[211., 262.], [251., 169.]]]], grad_fn=<ThnnConv2DBackward>) Max Pooling Layer最大池化层 最大池化层是没有权重的 import torch input = [3, 9, 6, 5, 2, 4, 6, 8, 1, 6, 2, 1, 3, 7, 4, 6] input = torch.Tensor(input).view(1, 1, 4, 4) maxpooling_layer = torch.nn.MaxPool2d(kernel_size=2) output = maxpooling_layer(input) print(output)
tensor([[[[9., 8.], [7., 6.]]]]) import torch from torchvision import transforms # 对图像进行处理的工具 from torchvision import datasets from torch.utils.data import DataLoader import torch.nn.functional as F # 使用激活函数relu()的包 import torch.optim as optim # 优化器的包 batch_size = 64 # 对图像进行预处理,将图像转换为 transform = transforms.Compose([ # 将原始图像PIL变为张量tensor(H*W*C),再将[0,255]区间转换为[0.1,1.0] transforms.ToTensor(), # 使用均值和标准差对张量图像进行归一化 transforms.Normalize((0.1307,), (0.3081,)) ]) train_dataset = datasets.MNIST(root='dataset/mnist/', train=True, download=True, transform=transform) train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size) test_dataset = datasets.MNIST(root='dataset/mnist/', train=False, download=True, transform=transform) test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size) class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() # 定义两个卷积层 self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5) self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5) # 定义一个池化层 self.pooling = torch.nn.MaxPool2d(2) # 定义一个全连接的线性层 self.fc = torch.nn.Linear(320, 10) def forward(self, x): # Flatten data from (n, 1, 28, 28) to (n, 784) # x.size(0)就是取的n batch_size = x.size(0) # 用relu做非线性激活 # 先做卷积再做池化再做relu x = F.relu(self.pooling(self.conv1(x))) x = F.relu(self.pooling(self.conv2(x))) # 做view把数据变为做全连接网络所需要的输入 x = x.view(batch_size, -1) return self.fc(x) # 因为最后一层要做交叉熵损失,所以最后一层不做激活 model = Net() device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model.to(device) # 交叉熵损失函数 criterion = torch.nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5) # momentum动量 def train(epoch): running_loss = 0.0 # 返回了数据下标和数据 for batch_idx, data in enumerate(train_loader, 0): # 送入两个张量,一个张量是64个图像的特征,一个张量图片对应的数字 inputs, target = data # 把输入输出迁入GPU inputs, target = inputs.to(device), target.to(device) # 梯度归零 optimizer.zero_grad() # forward+backward+update outputs = model(inputs) # 计算损失,用的交叉熵损失函数 loss = criterion(outputs, target) # 反馈 loss.backward() # 随机梯度下降更新 optimizer.step() # 每300次输出一次 running_loss += loss.item() if batch_idx % 300 == 299: print('[%d,%5d] loss:%.3f' % (epoch + 1, batch_idx + 1, running_loss / 300)) running_loss = 0.0 def test(): correct = 0 total = 0 # 不会计算梯度 with torch.no_grad(): for data in test_loader: # 拿数据 images, labels = data images, labels = images.to(device), labels.to(device) outputs = model(images) # 预测 # outputs.data是一个矩阵,每一行10个量,最大值的下标就是预测值 _, predicted = torch.max(outputs.data, dim=1) # 沿着第一维度,找最大值的下标,返回最大值和下标 total += labels.size(0) # labels.size(0)=64 每个都是64个元素,就可以计算总的元素 # (predicted == labels).sum()这个是张量,而加了item()变为一个数字,即相等的数量 correct += (predicted == labels).sum().item() print('Accuracy on test set:%d %%' % (100 * correct / total)) # 正确的数量除以总数 if __name__ == '__main__': for epoch in range(10): train(epoch) test()
卷积神经网络(高级)
import torch import torch.nn as nn from torchvision import transforms # 对图像进行处理的工具 from torchvision import datasets from torch.utils.data import DataLoader import torch.nn.functional as F # 使用激活函数relu()的包 import torch.optim as optim # 优化器的包 batch_size = 64 # 对图像进行预处理,将图像转换为 transform = transforms.Compose([ # 将原始图像PIL变为张量tensor(H*W*C),再将[0,255]区间转换为[0.1,1.0] transforms.ToTensor(), # 使用均值和标准差对张量图像进行归一化 transforms.Normalize((0.1307,), (0.3081,)) ]) train_dataset = datasets.MNIST(root='dataset/mnist/', train=True, download=True, transform=transform) train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size) test_dataset = datasets.MNIST(root='dataset/mnist/', train=False, download=True, transform=transform) test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size) class InceptionA(nn.Module): def __init__(self, in_channels): super(InceptionA, self).__init__() # 第一个通道,输入通道为in_channels,输出通道为16,卷积盒的大小为1*1的卷积层 self.branch1x1 = nn.Conv2d(in_channels, 16, kernel_size=1) # 第二个通道 self.branch5x5_1 = nn.Conv2d(in_channels, 16, kernel_size=1) self.branch5x5_2 = nn.Conv2d(16, 24, kernel_size=5, padding=2) # 第三个通道 self.branch3x3_1 = nn.Conv2d(in_channels, 16, kernel_size=1) self.branch3x3_2 = nn.Conv2d(16, 24, kernel_size=3, padding=1) self.branch3x3_3 = nn.Conv2d(24, 24, kernel_size=3, padding=1) # 第四个通道 self.branch_pool = nn.Conv2d(in_channels, 24, kernel_size=1) def forward(self, x): branch1x1 = self.branch1x1(x) branch5x5 = self.branch5x5_1(x) branch5x5 = self.branch5x5_2(branch5x5) branch3x3 = self.branch3x3_1(x) branch3x3 = self.branch3x3_2(branch3x3) branch3x3 = self.branch3x3_3(branch3x3) branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) branch_pool = self.branch_pool(branch_pool) # 拼接 outputs = [branch1x1, branch5x5, branch3x3, branch_pool] return torch.cat(outputs, dim=1) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(88, 20, kernel_size=5) self.incep1 = InceptionA(in_channels=10) self.incep2 = InceptionA(in_channels=20) self.mp = nn.MaxPool2d(2) self.fc = nn.Linear(1408, 10) def forward(self, x): in_size = x.size(0) x = F.relu(self.mp(self.conv1(x))) x = self.incep1(x) x = F.relu(self.mp(self.conv2(x))) x = self.incep2(x) x = x.view(in_size, -1) x = self.fc(x) return x model = Net() device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model.to(device) # 交叉熵损失函数 criterion = torch.nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5) # momentum动量 def train(epoch): running_loss = 0.0 # 返回了数据下标和数据 for batch_idx, data in enumerate(train_loader, 0): # 送入两个张量,一个张量是64个图像的特征,一个张量图片对应的数字 inputs, target = data # 把输入输出迁入GPU inputs, target = inputs.to(device), target.to(device) # 梯度归零 optimizer.zero_grad() # forward+backward+update outputs = model(inputs) # 计算损失,用的交叉熵损失函数 loss = criterion(outputs, target) # 反馈 loss.backward() # 随机梯度下降更新 optimizer.step() # 每300次输出一次 running_loss += loss.item() if batch_idx % 300 == 299: print('[%d,%5d] loss:%.3f' % (epoch + 1, batch_idx + 1, running_loss / 300)) running_loss = 0.0 def test(): correct = 0 total = 0 # 不会计算梯度 with torch.no_grad(): for data in test_loader: # 拿数据 images, labels = data images, labels = images.to(device), labels.to(device) outputs = model(images) # 预测 # outputs.data是一个矩阵,每一行10个量,最大值的下标就是预测值 _, predicted = torch.max(outputs.data, dim=1) # 沿着第一维度,找最大值的下标,返回最大值和下标 total += labels.size(0) # labels.size(0)=64 每个都是64个元素,就可以计算总的元素 # (predicted == labels).sum()这个是张量,而加了item()变为一个数字,即相等的数量 correct += (predicted == labels).sum().item() print('Accuracy on test set:%d %%' % (100 * correct / total)) # 正确的数量除以总数 if __name__ == '__main__': for epoch in range(10): train(epoch) test()
Residual net残差结构块
定义的该层输入和输出的大小是一样的
import torch.nn as nn import torch.nn.functional as F class ResidualBlock(nn.Module): def __init__(self,channels): super(ResidualBlock,self).__init__() self.channels = channels self.conv1 = nn.Conv2d(channels,channels,kernel_size=3,padding=1) self.conv2 = nn.Conv2d(channels,channels,kernel_size=3,padding=1) def forward(self,x): y = F.relu(self.conv1(x)) y = self.conv2(y) return F.relu(x+y) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 16, kernel_size=5) self.conv2 = nn.Conv2d(16, 32, kernel_size=5) self.mp = nn.MaxPool2d(2) self.rblock1 = ResidualBlock(16) self.rblock2 = ResidualBlock(32) self.fc = nn.Linear(512, 10) def forward(self, x): in_size = x.size(0) x = self.mp(F.relu(self.conv1(x))) x = self.rblock1(x) x = self.mp(F.relu(self.conv2(x))) x = self.rblock2(x) x = x.view(in_size, -1) x = self.fc(x) return x
RNN
RNN基础实战
任务介绍:通过PyTorch搭建一个用于处理序列的RNN。
当我们以sin值作为输入,其对应的cos作为输出的时候,你会发现,即使输入值sin相同,其输出结果也可以是不同的,这样的话,以前学过的FC, CNN就难以处理,因为你的输出结果不仅仅依赖于输出,而且还依赖于之前的程序结果。所以说,RNN在这里就派上了用场。
代码实现
RNN参数:torch.nn.RNN()
参数 含义
input_size 输入 x 的特征数量
hidden_size 隐状态 h 中的特征数量
num_layers RNN 的层数
nonlinearity 指定非线性函数使用 [‘tanh’|’relu’]. 默认: ‘tanh’
bias 如果是 False , 那么 RNN 层就不会使用偏置权重 b_ih 和 b_hh, 默认: True
batch_first 如果 True, 那么输入 Tensor 的 shape 应该是 (batch, seq, feature),并且输出也是一样
dropout 如果值非零, 那么除了最后一层外, 其它层的输出都会套上一个 dropout 层
bidirectional 如果 True , 将会变成一个双向 RNN, 默认为 False
首先,我们定义出RNN模型
import torch from torch import nn class Rnn(nn.Module): def __init__(self, INPUT_SIZE): super(Rnn, self).__init__() self.rnn = nn.RNN( input_size=INPUT_SIZE, hidden_size=32, num_layers=1, batch_first=True ) self.out = nn.Linear(32, 1) def forward(self, x, h_state): r_out, h_state = self.rnn(x, h_state) outs = [] for time in range(r_out.size(1)): outs.append(self.out(r_out[:, time, :])) return torch.stack(outs, dim=1), h_state
选择模型进行训练:
import numpy as np import matplotlib.pyplot as plt import torch from torch import nn import rnn # 定义一些超参数 TIME_STEP = 10 INPUT_SIZE = 1 LR = 0.02 # # 创造一些数据 # steps = np.linspace(0, np.pi*2, 100, dtype=np.float) # x_np = np.sin(steps) # y_np = np.cos(steps) # # # # “看”数据 # plt.plot(steps, y_np, 'r-', label='target(cos)') # plt.plot(steps, x_np, 'b-', label='input(sin)') # plt.legend(loc='best') # plt.show() # 选择模型 model = rnn.Rnn(INPUT_SIZE) print(model) # 定义优化器和损失函数 loss_func = nn.MSELoss() optimizer = torch.optim.Adam(model.parameters(), lr=LR) h_state = None # 第一次的时候,暂存为0 for step in range(300): start, end = step * np.pi, (step+1)*np.pi steps = np.linspace(start, end, TIME_STEP, dtype=np.float32) x_np = np.sin(steps) y_np = np.cos(steps) x = torch.from_numpy(x_np[np.newaxis, :, np.newaxis]) y = torch.from_numpy(y_np[np.newaxis, :, np.newaxis]) prediction, h_state = model(x, h_state) h_state = h_state.data loss = loss_func(prediction, y) optimizer.zero_grad() loss.backward() optimizer.step()
然后,画图看看最后拟合的结果
plt.plot(steps, y_np.flatten(), 'r-') plt.plot(steps, prediction.data.numpy().flatten(), 'b-') plt.show()
可以看到,真实的结果和拟合的效果已经十分接近了。
进阶实战
1.准备数据
定义一个数据集类,并读取数据文件。
from torch.utils.data import Dataset import pandas as pd class NameDataset(Dataset): """数据集类""" def __init__(self, is_train_set=True): filename = './name_data/names_train.csv' if is_train_set else './name_data/names_test.csv' data = pd.read_csv(filename, header=None) self.names = data[0] self.len = len(self.names) self.countries = data[1] self.country_list = list(sorted(set(self.countries))) self.country_dict = self.getCountryDict() self.country_num = len(self.country_list) def __getitem__(self, index): return self.names[index], self.country_dict[self.countries[index]] def __len__(self): return self.len def idx2country(self, index): return self.country_list[index] def getCountryDict(self): country_dict = dict() for idx, country_name in enumerate(self.country_list, 0): country_dict[country_name] = idx return country_dict def getCountriesNum(self): return self.country_num 定义函数,用于将读取到的数据转化为tensor。 def name2list(name): """返回ASCII码表示的姓名列表与列表长度""" arr = [ord(c) for c in name] return arr, len(arr) def make_tensors(names, countries): # 元组列表,每个元组包含ASCII码表示的姓名列表与列表长度 sequences_and_lengths = [name2list(name) for name in names] # 取出所有的ASCII码表示的姓名列表 name_sequences = [sl[0] for sl in sequences_and_lengths] # 取出所有的列表长度 seq_lengths = torch.LongTensor([sl[1] for sl in sequences_and_lengths]) # 将countries转为long型 countries = countries.long() # 接下来每个名字序列补零,使之长度一样。 # 先初始化一个全为零的tensor,大小为 所有姓名的数量*最长姓名的长度 seq_tensor = torch.zeros(len(name_sequences), seq_lengths.max()).long() # 将姓名序列覆盖到初始化的全零tensor上 for idx, (seq, seq_len) in enumerate(zip(name_sequences, seq_lengths), 0): seq_tensor[idx, :seq_len] = torch.LongTensor(seq) # 根据序列长度seq_lengths对补零后tensor进行降序怕排列,方便后面加速计算。 # 返回排序后的seq_lengths与索引变化列表 seq_lengths, perm_idx = seq_lengths.sort(dim=0, descending=True) # 根据索引变化列表对ASCII码表示的姓名列表进行排序 seq_tensor = seq_tensor[perm_idx] # 根据索引变化列表对countries进行排序,使姓名与国家还是一一对应关系 # seq_tensor.shape : batch_size*max_seq_lengths, # seq_lengths.shape : batch_size # countries.shape : batch_size countries = countries[perm_idx] return seq_tensor, seq_lengths, countries
2.定义模型
import torch from torch.nn.utils.rnn import pack_padded_sequence class RNNClassifier(torch.nn.Module): # input_size=128, hidden_size=100, output_size=18 def __init__(self, input_size, hidden_size, output_size, n_layers=1, bidirectional=True): super(RNNClassifier, self).__init__() self.hidden_size = hidden_size self.n_layers = n_layers self.n_directions = 2 if bidirectional else 1 # 是否双向 self.embedding = torch.nn.Embedding(input_size, hidden_size) # 输入大小128,输出大小100。 # 经过Embedding后input的大小是100,hidden_size的大小也是100,所以形参都是hidden_size。 self.gru = torch.nn.GRU(hidden_size, hidden_size, n_layers, bidirectional=bidirectional) # 如果是双向,会输出两个hidden层,要进行拼接,所以线形成的input大小是 hidden_size * self.n_directions,输出是大小是18,是为18个国家的概率。 self.fc = torch.nn.Linear(hidden_size * self.n_directions, output_size) def _init_hidden(self, batch_size): hidden = torch.zeros(self.n_layers * self.n_directions, batch_size, self.hidden_size) return hidden def forward(self, input, seq_lengths): # 先对input进行转置,input shape : batch_size*max_seq_lengths -> max_seq_lengths*batch_size 每一列表示姓名 input = input.t() batch_size = input.size(1) # 总共有多少列,既是batch_size的大小 hidden = self._init_hidden(batch_size) # 初始化隐藏层 embedding = self.embedding(input) # embedding.shape : max_seq_lengths*batch_size*hidden_size 12*64*100 # pack_padded_sequence方便批量计算 gru_input = pack_padded_sequence(embedding, seq_lengths) # 进入网络进行计算 output, hidden = self.gru(gru_input, hidden) # 如果是双向的,需要进行拼接 if self.n_directions == 2: hidden_cat = torch.cat([hidden[-1], hidden[-2]], dim=1) else: hidden_cat = hidden[-1] # 线性层输出大小为18 fc_output = self.fc(hidden_cat) return fc_output
3.定义训练函数
def time_since(since): s = time.time() - since m = math.floor(s/60) s-= m*60 return '%dm %ds' % (m, s) def trainModel(): total_loss = 0 for i, (names, countries) in enumerate(trainloader, 1): # 这里的1意思是 i 从1开始。 # make_tensors函数返回经过降序排列后的 姓名列表,列表长度,国家 inputs, seq_lengths, target = make_tensors(names, countries) # 输入姓名列表与列表长度向前计算 output = classifier(inputs, seq_lengths) loss = criterion(output, target) optimizer.zero_grad() loss.backward() optimizer.step() total_loss += loss.item() if i % 10 == 0: print(i) print(f'[{time_since(start)}] Epoch {epoch} ', end='') print(f'[{i * len(inputs)}/{len(trainset)}] ', end='') print(f'loss={total_loss / (i * len(inputs))}') return total_loss
4.定义测试函数,跟训练函数相差不大
def testModel(): correct = 0 total = len(testset) print("evaluating trained model ...") with torch.no_grad(): for i, (names, countries) in enumerate(testloader, 1): inputs, seq_lengths, target = make_tensors(names, countries) output = classifier(inputs, seq_lengths) pred = output.max(dim=1, keepdim=True)[1] correct += pred.eq(target.view_as(pred)).sum().item() percent = '%.2f' % (100 * correct / total) print(f'Test set: Accuracy {correct}/{total} {percent}%') return correct / total
5.主函数循环
from torch.utils.data import DataLoader import time import math if __name__ == '__main__': N_EPOCHS = 30 # epoch HIDDEN_SIZE = 100 # 隐藏层的大小,也是Embedding后输出的大小 BATCH_SIZE = 64 N_COUNTRY = 18 # 总共有18个类别的国家,为RNN后输出的大小 N_LAYER = 2 N_CHARS = 128 # 字母字典的大小,Embedding输入的大小 trainset = NameDataset(is_train_set=True) trainloader = DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True) testset = NameDataset(is_train_set=False) testloader = DataLoader(testset, batch_size=BATCH_SIZE, shuffle=False) # 建立分类模型 classifier = RNNClassifier(N_CHARS, HIDDEN_SIZE, N_COUNTRY, N_LAYER) # 建立损失函数与优化器 criterion = torch.nn.CrossEntropyLoss() optimizer = torch.optim.Adam(classifier.parameters(), lr=0.001) start = time.time() print("Training for %d epochs..." % N_EPOCHS) acc_list = [] for epoch in range(1, N_EPOCHS + 1): # Train cycle trainModel() acc = testModel() acc_list.append(acc)