pytroch-基础案例

# 自动求导
import torch
from torch import autograd


x = torch.tensor(1.)
a = torch.tensor(1., requires_grad=True)  # 标量
b = torch.tensor(2., requires_grad=True)
c = torch.tensor(3., requires_grad=True)

y = a**2 * x + b * x + c
print("a.dim():", a.dim())  # dimension = 0
print('before:', a.grad, b.grad, c.grad)
grads = autograd.grad(y, [a, b, c])
print('after :', grads[0], grads[1], grads[2])  # y对a求导=2x, y对b求导=x, y对c求导=1
# GPU加速
import torch
import time
print(torch.__version__)
print(torch.cuda.is_available())


a = torch.randn(10000, 1000)
b = torch.randn(1000, 2000)

t0 = time.time()
c = torch.matmul(a, b)  # 矩阵乘法
t1 = time.time()
print(a.device, t1 - t0, c.norm(2))

device = torch.device('cuda')
a = a.to(device)
b = b.to(device)

t0 = time.time()
c = torch.matmul(a, b)  # 此次加载数据
t2 = time.time()
print(a.device, t2 - t0, c.norm(2))

t0 = time.time()
c = torch.matmul(a, b)
t2 = time.time()
print(a.device, t2 - t0, c.norm(2))
# 验证cuda环境是否可用
import torch

print(torch.__version__)
print('gpu:', torch.cuda.is_available())
# 简单线性回归问题
import numpy as np


# y = wx + b 这里的point代表(x,y) ==> 其维度为(len(points), 2)
def compute_error_for_line_given_points(b, w, points):
    totalError = 0
    for i in range(0, len(points)):
        x = points[i, 0]
        y = points[i, 1]
        totalError += (y - (w * x + b)) ** 2
    return totalError / float(len(points))  # 平均损失


# x'=x- lr*grad
def step_gradient(b_current, w_current, points, learningRate):
    b_gradient = 0
    w_gradient = 0
    N = float(len(points))
    for i in range(0, len(points)):
        x = points[i, 0]
        y = points[i, 1]
        b_gradient += -(2/N) * (y - ((w_current * x) + b_current))
        w_gradient += -(2/N) * x * (y - ((w_current * x) + b_current))
    new_b = b_current - (learningRate * b_gradient)
    new_w = w_current - (learningRate * w_gradient)
    return [new_b, new_w]


# 梯度迭代
def gradient_descent_runner(points, starting_b, starting_w, learning_rate, num_iterations):
    b = starting_b
    w = starting_w
    for i in range(num_iterations):
        b, m = step_gradient(b, w, np.array(points), learning_rate)
    return [b, m]


def run():
    points = np.genfromtxt("data.csv", delimiter=",")
    learning_rate = 0.0001
    initial_b = 0  # initial y-intercept guess
    initial_w = 0  # initial slope guess
    num_iterations = 1000   # 迭代次数
    """开始参数和损失"""
    print("Starting gradient descent at b = {0}, w = {1}, error = {2}"
          .format(initial_b, initial_w,
                  compute_error_for_line_given_points(initial_b, initial_w, points))
          )
    """参数和损失更新"""
    print("Running...")
    [b, w] = gradient_descent_runner(points, initial_b, initial_w, learning_rate, num_iterations)
    print("After {0} iterations b = {1}, w = {2}, error = {3}".
          format(num_iterations, b, w,
                 compute_error_for_line_given_points(b, w, points))
          )


if __name__ == '__main__':
    run()
"""手写数字识别案列"""
1.mnist_train.py
import torch
from torch import nn
from torch.nn import functional as F
from torch import optim

import torchvision
from matplotlib import pyplot as plt
from utils import plot_image, plot_curve, one_hot

batch_size = 512
# step1. load dataset
train_loader = torch.utils.data.DataLoader(
    torchvision.datasets.MNIST('mnist_data', train=True, download=True,
                               transform=torchvision.transforms.Compose([
                                   torchvision.transforms.ToTensor(),
                                   torchvision.transforms.Normalize(
                                       (0.1307,), (0.3081,))
                               ])),
    batch_size=batch_size, shuffle=True)

test_loader = torch.utils.data.DataLoader(
    torchvision.datasets.MNIST('mnist_data/', train=False, download=True,
                               transform=torchvision.transforms.Compose([
                                   torchvision.transforms.ToTensor(),
                                   torchvision.transforms.Normalize(
                                       (0.1307,), (0.3081,))  # 分布是在[0,1],转化为到0附近
                               ])),
    batch_size=batch_size, shuffle=False)

x, y = next(iter(train_loader))   # iter(可迭代对象):可迭代对象==>生成器对象, next()和iter()一起使用, next(iter(可迭代对象))返回迭代器的下一个项目
print(x.shape, y.shape, x.min(), x.max())
plot_image(x, y, 'image sample')  # 绘制数据集中的图片


# 创建一个网络
class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()

        # xw+b
        self.fc1 = nn.Linear(28*28, 256)
        self.fc2 = nn.Linear(256, 64)
        self.fc3 = nn.Linear(64, 10)

    def forward(self, x):
        # x: [b, 1, 28, 28]  # b代表b张图片,batchsize
        # h1 = relu(xw1+b1)
        x = F.relu(self.fc1(x))
        # h2 = relu(h1w2+b2)
        x = F.relu(self.fc2(x))
        # h3 = h2w3+b3  # 分类任务一般情况下加softmax
        x = self.fc3(x)

        return x


net = Net()
# [w1, b1, w2, b2, w3, b3]
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)  # 优化器

'''网络训练'''
train_loss = []
for epoch in range(3):  # 对数据集迭代3遍

    for batch_idx, (x, y) in enumerate(train_loader):  # batch: 512张图片 batch_idx为序号,从零开始

        # x: [b, 1, 28, 28], y: [512]
        # [b, 1, 28, 28] => [b, 784]
        x = x.view(x.size(0), 28*28)  # size(0)代表batch, view将向量打平
        # => [b, 10]
        out = net(x)
        # [b, 10]
        y_onehot = one_hot(y)
        # loss = mse(out, y_onehot)
        loss = F.mse_loss(out, y_onehot)  # 计算机均方差

        optimizer.zero_grad()  # 防止梯度累加,这里做梯度清零
        loss.backward()  # 梯度更新
        # w' = w - lr*grad
        optimizer.step()  # 更新梯度

        train_loss.append(loss.item())  # loss是一个tensor数据类型, 取出来转化为numpy类型

        if batch_idx % 10 == 0:  # 每隔10batch打印loss
            print(epoch, batch_idx, loss.item())

plot_curve(train_loss)
# we get optimal [w1, b1, w2, b2, w3, b3]

'''准确度测试(网络测试)'''
total_correct = 0
for x, y in test_loader:
    x = x.view(x.size(0), 28*28)
    out = net(x)
    # out: [b, 10] => pred: [b]
    pred = out.argmax(dim=1)  # 返回概率值最大的索引,dim代表第二个维度,即标签
    correct = pred.eq(y).sum().float().item()  # 判断正确的个数
    total_correct += correct

total_num = len(test_loader.dataset)
acc = total_correct / total_num
print('test acc:', acc)


# 预测结果
x, y = next(iter(test_loader))
out = net(x.view(x.size(0), 28*28))
pred = out.argmax(dim=1)  # 取dimension=1的最大值标签
plot_image(x, pred, 'test')

2.utils.py
import torch
from matplotlib import pyplot as plt


def plot_curve(data):  # 绘制曲线
    fig = plt.figure()
    plt.plot(range(len(data)), data, color='blue')
    plt.legend(['value'], loc='upper right')
    plt.xlabel('step')
    plt.ylabel('value')
    plt.show()


def plot_image(img, label, name):  # 画图片

    fig = plt.figure()
    for i in range(6):
        plt.subplot(2, 3, i + 1)
        plt.tight_layout()  # Light_layout会自动调整子图参数
        plt.imshow(img[i][0]*0.3081+0.1307, cmap='gray', interpolation='none')
        plt.title("{}: {}".format(name, label[i].item()))
        plt.xticks([])
        plt.yticks([])
    plt.show()


def one_hot(label, depth=10):  # 设置one-hot编码
    print(label.size(0))  # 这部分有疑问
    out = torch.zeros(label.size(0), depth)
    idx = torch.LongTensor(label).view(-1, 1)
    out.scatter_(dim=1, index=idx, value=1)
    return out

猜你喜欢

转载自blog.csdn.net/MasterCayman/article/details/109387020