线性回归

第一步:构建数据

1
2
3
4
5
import torch

# y_hat = w*x + b
x_data = torch.Tensor([[1.0], [2.0], [3.0]]) # 3*1的矩阵
y_data = torch.Tensor([[2.0], [4.0], [6.0]])

第二步:设计模型

1
2
3
4
5
6
7
8
9
10
11
class LinearModle(torch.nn.Module):  # 定义为一个类。应该继承自nn.Module,它是所有nn模块的基类。
def __init__(self): # 构造函数
super(LinearModle, self).__init__()
self.linear = torch.nn.Linear(1, 1) # 构造nn.Linear(in维度,out维度)对象,含有W和b。

def forwar(self, x): # 前馈计算,必须有这个
y_pred = self.linear(x) # linear 是可调用对象
return y_pred
# 不需要定义反向传播函数,torch会自动生成计算图

model = LinearModle() # model同样是可调用对象,model(x)

第三步:损失函数和优化器

1
2
3
4
5
6
criterion = torch.nn.MSELoss(size_average=False, reduce=True)  # 是否求均值=True,是否求和=True

# SGD(params(哪些tenser需要优化), lr=<object object>(学习率),
# momentum=0,dampening=1,weight_decay=0,nesterov=False)
# model.parameters()可以找到所有可优化的参数。
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

第四步:训练(前馈,反馈,更新)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
for epoch in range(100):
y_pred = model(x_data) # 算y_hat
loss = criterion(y_pred, y_data) # 算损失
print(epoch, loss)

optimizer.zero_grad() # 梯度归零
loss.backward() # 反向传播
optimizer.step() # 更新


# 打印权重的值
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)

多维输入处理

第一步:构建数据

1
2
3
4
5
6
import numpy as np
import torch

xy = np.loadtxt('diabetes.csv.gz', delimiter=',', dtype=np.float32) #使用np读入数据
x_data = torch.from_numpy(xy[:,:-1]) #提取x
y_data = torch.from_numpy(xy[:, [-1]])

第二步:设计模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)
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()

后两步基本一样

Dataset和DataLoader

Dataset,数据集,需要支持索引。

DataLoader,主要是支持拿出Mini-Batch

Epoch:所有训练样本都进行一次前向传播和一次反向传播。

Batch-Size:每次训练所用样本数量

Iteration: = 样本数 / Batch-Size

1
2
3
4
# Training cycle
for epoch in range(training_epochs):
# Loop over all batches
for i in range(total_batch):

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import torch
from torch.utils.data import Dataset # 抽象类,不能实例化
from torch.utils.data import DataLoader # 帮助加载数据


class DiabetesDataset(Dataset):
def __init__(self):
pass

def __getitem__(self, index): # 魔法方法,使之支持索引操作
pass

def __len__(self): # 使之支持返回长度
pass


dataset = DiabetesDataset()

#shuffle 是否打乱 num_workers进程数目
train_loader = DataLoader(dataset=dataset, batch_size=32, shuffle=True, num_workers=2)

#构造模型和优化器

for epoch in range(100):
for i, data in enumerate(train_loader, 0):
# 1. Prepare data
inputs, labels = data
# 2. Forward
y_pred = model(inputs)
loss = criterion(y_pred, labels)
print(epoch, i, loss.item())
# 3. Backward
optimizer.zero_grad()
loss.backward()
# 4. Update
optimizer.step()

CNN实现1

input output 卷积核 大小

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import torch

in_channels, out_channels = 5, 10
width, height = 100, 100
kernel_size = 3
batch_size = 1

input = torch.randn(batch_size, in_channels, width, height)
conv_layer = torch.nn.Conv2d(in_channels, out_channels, padding=1,
stride=2,kernel_size=kernel_size) # 创建卷积层对象
output = conv_layer(input)

print(input.shape)
print(output.shape)
print(conv_layer.weight.shape)

# torch.Size([1, 5, 100, 100])
# torch.Size([1, 10, 50, 50])
# torch.Size([10, 5, 3, 3])

一次简单的卷积

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)

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)#用view,reshape成1*1*3*3的矩阵
conv_layer.weight.data = kernel.data # 为卷积核填充参数

output = conv_layer(input) # 卷积计算
print(output)

网络模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import torch
import torch.nn.functional as F

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(kernel_size=2)
self.fc = torch.nn.Linear(320, 10)

def forward(self, x):
# Flatten data from (n, 1, 28, 28) to (n, 784) n是bach_size
batch_size = x.size(0)
x = F.relu(self.pooling(self.conv1(x)))
x = F.relu(self.pooling(self.conv2(x)))

x = x.view(batch_size, -1) # flatten
x = self.fc(x) # 最后一层不用激活,因为要做交叉熵
return x

model = Net()
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")#模型放进显卡
model.to(device)

训练

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def train(epoch):
running_loss = 0.0
for batch_idx, data in enumerate(train_loader, 0):
inputs, target = data
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()
running_loss += loss.item()

if batch_idx % 300 == 299:
print('[%d, %5d] loss: %.3f' % (epoch + 1, batch_idx + 1, running_loss / 2000))
running_loss = 0.0

测试

1
2
3
4
5
6
7
8
9
10
11
12
def test():
correct = 0
total = 0
with torch.no_grad(): #因为是测试,所有计算得出的tensor的requires_grad都自动设置为False。
for data in test_loader:
inputs, target = data
inputs, target = inputs.to(device), target.to(device) #放入显卡
outputs = model(inputs)
_, predicted = torch.max(outputs.data, dim=1)
total += target.size(0) # 总数
correct += (predicted == target).sum().item() # 预测正确的数目
print('Accuracy on test set: %d %% [%d/%d]' % (100 * correct / total, correct, total))

CNN实现2

GoogLeNet

如上图,从左到右编号1 2 3 4,见注释

Inception块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import torch
import torch.nn as nn
import torch.nn.functional as F


class InceptionA(nn.Module):
def __init__(self, in_channels):
super(InceptionA, self).__init__()
self.branch_pool = nn.Conv2d(in_channels, 24, kernel_size=1) # 1
self.branch1x1 = nn.Conv2d(in_channels, 16, kernel_size=1) # 2
self.branch5x5_1 = nn.Conv2d(in_channels, 16, kernel_size=1) # 3
self.branch5x5_2 = nn.Conv2d(16, 24, kernel_size=5, padding=2) # 3
self.branch3x3_1 = nn.Conv2d(in_channels, 16, kernel_size=1) # 4
self.branch3x3_2 = nn.Conv2d(16, 24, kernel_size=3, padding=1) # 4
self.branch3x3_3 = nn.Conv2d(24, 24, kernel_size=3, padding=1) # 4


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) # 1*1卷积,升维24

outputs = [branch1x1, branch5x5, branch3x3, branch_pool]
return torch.cat(outputs, dim=1) # 用cat,dim=1表示沿着通道拼接

用Inception构建一个简单网络

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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) # 两个inception
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))) # 一次卷积,一次池化,一次relu
x = self.incep1(x) # 一次inception
x = F.relu(self.mp(self.conv2(x))) # 再进行卷积,通道数88-->20
x = self.incep2(x) # 第二次一次inception
x = x.view(in_size, -1) # 变成向量
x = self.fc(x) # 全连接
return x

ResNet

残差块

1
2
3
4
5
6
7
8
9
10
11
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)

网络

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import torch
import torch.nn as nn
import torch.nn.functional as F


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