前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Pytorch的建议建模-Pytorch入门

Pytorch的建议建模-Pytorch入门

作者头像
一个有趣的灵魂W
发布2023-10-06 17:05:32
1660
发布2023-10-06 17:05:32
举报

Tensorflow的bug太多了,我只能转投Pytorch的怀抱

01

最近Tensorflow(下称TF)已死的言论不知道大家是否接收到:

放弃支持Windows GPU、bug多,TensorFlow被吐槽:2.0后慢慢死去 https://zhuanlan.zhihu.com/p/656241342

学习起步困难,但学习的成长过程总能有不断的收获,这种收获感是我们坚持下去的动力之一。随着谷歌减缓了在Windows上对TF的支持。底层开发者还需要不断学习,避免脱节。所以,Pytorch(下称torch)就成了我们在主流框架下不得不学习的内容之一。同时,让我们顺带复习一下基本的求导、前馈、权重、Loss等词汇在深度学习里是怎么运作的吧:

正文开始:

在前文Numpy简述神经网络模型权重搜索原理-Pytorch引文的基础上,我们开始使用torch库,进一步理解权重的更新、变化。

02

以下是代码部分

代码语言:javascript
复制
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch

x_data = torch.Tensor([[1.0], [2.0],[3.0]])
y_data = torch.Tensor([[2.0], [4.0],[6.0]])
##此处,正式使用torch的张量,显示了数据形式

class Model(torch.nn.Module):
    def __init__(self):
        """
        In the constructor we instantiate 2 nn.linear module
        """
        super(Model, self).__init__()
        self.linear = torch.nn.Linear(1,1) # One data in and one out for x and y

    def forward(self, x):
        """
        In forward function we accept the input variable and we return variable for the output
        We can use the modules defined in the constructor and arbitary operations
        on the variable as well"""
        y_pred = self.linear(x)
        return y_pred

# Our model
model = Model()
#以上,torch的模型组织形式与tensorflow相似,但与keras相差较大。
#因为keras是一个完整的封装包,较为傻瓜式;缺点就是改动不灵活

criterion = torch.nn.MSELoss(size_average = False)
optimum = torch.optim.SGD(model1.parameters(), lr = 0.01)
#此处都是正常的引入loss和优化器

# Training loop

for epoch in range (1000):
    # Using forward pass to calcuate the prediction
    y_pred = model1(x_data)

    # Compute and print the loss
    loss = criterion(y_pred, y_data)
    print(f'Epoch: {epoch}, Loss:  {loss.item()}')

    # Making the gradients zero and then doing a backward pass to calcuate
    # And then update the weights
    optimum.zero_grad()
    loss.backward()
    optimum.step()


# After training
new_val = torch.Tensor([4.0])
print('Predict (after training)', 4, model1.forward(new_val).item())
#以下显示结果。。。略

#Epoch: 997, Loss:  3.1845956982579082e-09
#Epoch: 998, Loss:  3.1388935894938186e-09
#Epoch: 999, Loss:  3.0900650926923845e-09
#Predict (after training) 4 7.999936103820801

结果处可以发现,输入4:理论上应该得到8(结果十分接近8)。意味着构建的模型生效了。

03

至此,对于torch的基本入门已经完成。接着就要学习如何扩大模型、加深模型(DNN)、修改模型组织模式(yolo、unet、GAN等)、优化组织架构(resnet、attention等)、loss、优化器等。

进一步,学习模型的可解释性、AI for science、国产深度学习框架(百度、华为)、硬件实现(边缘部署)等。

当然,任意的部分都可以进行二次扩展。例如AI for science的science,可以是蛋白质结构模拟预测、生态气象大模型、遥感大模型、智能交通等。

本文参与?腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2023-10-04 11:22,如有侵权请联系?cloudcommunity@tencent.com 删除

本文分享自 一个有趣的灵魂W 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com