2022.2.27科研记录

2022.2.27科研记录

1.《pytorch深度学习入门》曾芃壹
ch3.深度学习基础
3.2线性回归
①其他知识
Epoch(时期):当一个完整的数据集通过了神经网络一次并且返回了一次,这个过程称为一次epoch。(也就是说,所有训练样本在神经网络中都 进行了一次正向传播和一次反向传播 )
再通俗一点,一个Epoch就是将所有训练样本训练一次的过程。然而,当一个Epoch的样本(也就是所有的训练样本)数量可能太过庞大(对于计算机而言),就需要把它分成多个小块,也就是就是分成多个Batch 来进行训练。
Batch(批 / 一批样本):将整个训练样本分成若干个Batch。
Iteration(一次迭代):训练一个Batch就是一次Iteration(这个概念跟程序语言中的迭代器相似)。
from:https://www.jianshu.com/p/22c50ded4cf7

import torch
import matplotlib.pyplot as plt


def Produce_X(x):
    x0=torch.ones(x.numpy().size)
    X=torch.stack((x,x0),dim=1)
    return X


x=torch.Tensor([1.4,5,11,16,21])
y=torch.Tensor([14.4,29.6,62,85.5,113.4])
X=Produce_X(x)

inputs = X #注意这里的大小写
target = y
w = torch.rand(2, requires_grad=True)


def train(epochs=1, learning_rate=0.01):  #这里epochs和learning_rate的值都只是个例子,实际要看调用时的参数
    for epoch in range(epochs):
        output = inputs.mv(w)
        loss = (output-target).pow(2).sum()  #损失函数公式
        loss.backward()
        w.data -= learning_rate * w.grad
        w.grad.zero_()  #更新完w后必须清空w的grad值
        '''
        
        if epoch % 80 == 0:
            draw(output,loss)'''
    return w, loss


def draw(output, loss):
    plt.cla()
    plt.scatter(x.numpy(), y.numpy())
    plt.plot(x.numpy(), output.data.numpy(), 'r-', lw=5)
    plt.text(0.5, 0, 'loss=%s' % (loss.item()), fontdict={'size': 20, 'color': 'red'})
    plt.pause(0.005)


w, loss = train(10000, learning_rate=1e-4)
print("final loss:", loss.item())
print("weight:", w.data)
draw(inputs.mv(w),loss = (inputs.mv(w) - target).pow(2).sum())

大规模数据实例

import torch
import matplotlib.pyplot as plt
from time import perf_counter
#产生输入X,X有两个维度n行2列,2列对应x1w1+x0w0,x0=1
def Produce_X(x):
    x0=torch.ones(x.numpy().size)#x.numpy()将Tensor转化为numpy
    X=torch.stack((x,x0),dim=1)#将x与x0在第二个维度进行连接组合成n行2列的矩阵
    return X


x=torch.linspace(-3,3,100000) #在-3到3之间划分出100000个点
X=Produce_X(x)
y=x+1.2*torch.rand(x.size()) #为了使数据符合线性分布且真实,y在x的基础上增加一些误差
w=torch.rand(2)

plt.scatter(x.numpy(), y.numpy(),s=0.001)
plt.show()

CUDA = torch.cuda.is_available()
if CUDA:
    print("CUDA success")
    inputs = X.cuda()
    target = y.cuda()
    w = w.cuda()
    w.requires_grad = True
else:
    print("CUDA fail")
    inputs = X
    target = y
    w = w
    w.requires_grad = True


def draw(output, loss):
    if CUDA:
        output = output.cpu()  # 若使用了CUDA加速这一步要还原为CPU数据类型
    plt.cla()
    plt.scatter(x.numpy(), y.numpy())
    plt.plot(x.numpy(), output.data.numpy(), 'r-', lw=5)
    plt.text(0.5, 0, 'loss=%s' % (loss.item()), fontdict={'size': 20, 'color': 'red'})
    plt.pause(0.005)


# 训练
def train(epochs=1, learning_rate=0.01):
    #global loss
    for epoch in range(epochs):
        output = inputs.mv(w)
        loss = (output - target).pow(2).sum() / 100000  # 将均方误差除以数据个数
        loss.backward()
        w.data -= learning_rate * w.grad
        w.grad.zero_()  # 调用zero_函数清空grad属性值,避免grad值持续积累
        if epoch % 80 == 0:  # 每80个epoch
            draw(output, loss)
    return w, loss


start = perf_counter()
w, loss = train(10000, learning_rate=1e-4)
finish = perf_counter()
time = finish - start

print("计算时间:%s" % time)
print("fina loss:", loss.item())
print("wights", w.data)

奇怪,怎么用了CUDA加速也没有很快?

CUDA success
计算时间:69.6718703
fina loss: 0.12507939338684082
wights tensor([1.0000, 0.5282], device='cuda:0')

Process finished with exit code 0

明白了,和这段代码有关:

        if epoch % 1000 == 0:  # 每80个epoch
            draw(output, loss)

书上写的是80个epoch draw一次,但我试了基本都是70s左右
1000个epoch draw一次,基本是11s
2000个epoch draw一次,基本是8s
所以还是不要太经常draw(笑

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值