Pytorch_basics_main

2023-11-30 05:30
文章标签 pytorch main basics

本文主要是介绍Pytorch_basics_main,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

[Pytorch] First day

# import necessary packages
import torch
import torchvision
import torch.nn as nn
import numpy as np
import torchvision.transforms as transforms
Content one
# Basic autograd example 1# Create tensors.
x = torch.tensor(1., requires_grad=True)
w = torch.tensor(2., requires_grad=True)
b = torch.tensor(3., requires_grad=True)print(type(x), type(w), type(b))
<class 'torch.Tensor'> <class 'torch.Tensor'> <class 'torch.Tensor'>
# Build a computional graph.
y = w * x + b   # y = 2 * x + 3# Compute gadients.
y.backward()# Print out the gradients.
print(x.grad)   # x.grad = 2
print(w.grad)   # w.grad = 1
print(b.grad)   # b.grad = 1
tensor(2.)
tensor(1.)
tensor(1.)
Content two
# Basic autograd example 2# Create tensors of shape (10, 3) and (10, 2).
x = torch.randn(10, 3)
y = torch.randn(10, 2)# Build a fully connected layer.
linear = nn.Linear(3, 2)
print('w: ', linear.weight)
print('b: ', linear.bias)
w:  Parameter containing:
tensor([[ 0.2271,  0.4796, -0.4287],[ 0.3378, -0.5249,  0.2095]], requires_grad=True)
b:  Parameter containing:
tensor([0.4186, 0.1931], requires_grad=True)
# Build loss function and optimizer.
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(linear.parameters(), lr=0.01)# Forward pass.
pred = linear(x)# Compute loss.
loss = criterion(pred, y)
print('loss:', loss.item())
loss: 1.1817594766616821
# Backward pass.
loss.backward()# Print out the gradients.
print('dl/dw: ', linear.weight.grad)
print('dl/db: ', linear.bias.grad)
dl/dw:  tensor([[-0.5055,  0.2931, -0.8895],[ 0.0444,  0.0985,  0.4994]])
dl/db:  tensor([ 0.6998, -0.0333])
# 1-step gradient descent.
optimizer.step()# We can also perform gradient descent at the low level.
# linear.weight.data.sub_(0.01 * linear.weight.grad.data)
# linear.bias.data.sub_(0.01 * linear.bias.grad.data)# Print out the loss after 1-step gradient descent.
pred = linear(x)
loss = criterion(pred, y)
print('loss after 1 step optimization: ',loss.item())
loss after 1 step optimization:  1.1630728244781494
Content three
# Loading data from numpy# Create a numpy array.
x = np.array([[1, 2], [3, 4]])# Convert the numpy array to a torch tensor.
y = torch.from_numpy(x)# Convert the torch tensor to a numpy array.
z = y.numpy()print(type(x), type(y), type(z))
<class 'numpy.ndarray'> <class 'torch.Tensor'> <class 'numpy.ndarray'>
Content four
# Download and construct CIFAR-10 dataset.
train_dataset = torchvision.datasets.CIFAR10(root='../../data',train=True,transform=transforms.ToTensor(),download=True)
# Fetch one data pair (read data from disk).
print(type(train_dataset)) # <class 'torchvision.datasets.cifar.CIFAR10'>
image, label = train_dataset[0]print(image.size)
print(label)
Files already downloaded and verified
<class 'torchvision.datasets.cifar.CIFAR10'>
<built-in method size of Tensor object at 0x7fbbe5e40f90>
6
# Data loader (this provides queues and threads in a very simple way).
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,batch_size=64,shuffle=True)# When iteration starts, queue and thread start to load data from files.
data_iter = iter(train_loader)# Mini-batch images and labels.
images, labels = data_iter.__next__()# Actual usage of the data loader is as below.
for images, labels in train_loader:# Training code should be written here.pass
Content five
# Input pipline for custom dataset# We should build our custom dataset as below.
class CustomDataset(torch.utils.data.Dataset):def __init__(self):# TODO# 1.Initilize file paths or a list of file names.passdef __getitem__(self, index):# TODO# 1.Read one data from file (e.g.using numpy.fromfile, PIL.Image.open).# 2.Preprocess the data (e.g. torchvision.Transfrom).# 3.Return a data pair (e.g. image and label).passdef __len__(self):# We should change 0 to the total size of our dataset.return 0# You can then use the prebuilt data loader.
custom_dataset = CustomDataset()
train_loader = torch.utils.data.DataLoader(dataset=custom_dataset,batch_size=64,shuffle=False)
Content six
# Pretrained model# Download and load the pretrained ResNet-18.
resnet = torchvision.models.resnet18(pretrained=True)# If we want to finetune only the top layer of the model, set as below.
for param in resnet.parameters():param.requires_grad = False# Replace the top layer for fintuning.
resnet.fc = nn.Linear(resnet.fc.in_features, 100)   # 100 is an example.# Forward pass
images = torch.randn(64, 3, 224, 224)
outputs = resnet(images)print(outputs.size())   # result is torch.Size([64, 100])
/home/wsl_ubuntu/anaconda3/envs/xy_trans/lib/python3.8/site-packages/torchvision/models/_utils.py:208: UserWarning: The parameter 'pretrained' is deprecated since 0.13 and may be removed in the future, please use 'weights' instead.warnings.warn(
/home/wsl_ubuntu/anaconda3/envs/xy_trans/lib/python3.8/site-packages/torchvision/models/_utils.py:223: UserWarning: Arguments other than a weight enum or `None` for 'weights' are deprecated since 0.13 and may be removed in the future. The current behavior is equivalent to passing `weights=ResNet18_Weights.IMAGENET1K_V1`. You can also use `weights=ResNet18_Weights.DEFAULT` to get the most up-to-date weights.warnings.warn(msg)
Downloading: "https://download.pytorch.org/models/resnet18-f37072fd.pth" to /home/wsl_ubuntu/.cache/torch/hub/checkpoints/resnet18-f37072fd.pth
100%|██████████| 44.7M/44.7M [00:20<00:00, 2.34MB/s]torch.Size([64, 100])
Content seven
# Save and load the entire model.
torch.save(resnet, 'model.ckpt')
model = torch.load('model.ckpt')# Save and load only the model parameters (recommended).
torch.save(resnet.state_dict(), 'params.ckpt')
resnet.load_state_dict(torch.load('params.ckpt'))
<All keys matched successfully>

这篇关于Pytorch_basics_main的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/435806

相关文章

跟我一起玩《linux内核设计的艺术》第1章(四)——from setup.s to head.s,这回一定让main滚出来!(已解封)

看到书上1.3的大标题,以为马上就要见着main了,其实啊,还早着呢,光看setup.s和head.s的代码量就知道,跟bootsect.s没有可比性,真多……这确实需要包括我在内的大家多一些耐心,相信见着main后,大家的信心和干劲会上一个台阶,加油! 既然上篇已经玩转gdb,接下来的讲解肯定是边调试边分析书上的内容,纯理论讲解其实我并不在行。 setup.s: 目标:争取把setup.

Nn criterions don’t compute the gradient w.r.t. targets error「pytorch」 (debug笔记)

Nn criterions don’t compute the gradient w.r.t. targets error「pytorch」 ##一、 缘由及解决方法 把这个pytorch-ddpg|github搬到jupyter notebook上运行时,出现错误Nn criterions don’t compute the gradient w.r.t. targets error。注:我用

main函数执行前、后再执行的代码

一、main结束 不代表整个进程结束  (1)全局对象的构造函数会在main 函数之前执行,          全局对象的析构函数会在main函数之后执行;          用atexit注册的函数也会在main之后执行。  (2)一些全局变量、对象和静态变量、对象的空间分配和赋初值就是在执行main函数之前,而main函数执行完后,还要去执行一些诸如释放空间、释放资源使用权等操作   (3)

【超级干货】2天速成PyTorch深度学习入门教程,缓解研究生焦虑

3、cnn基础 卷积神经网络 输入层 —输入图片矩阵 输入层一般是 RGB 图像或单通道的灰度图像,图片像素值在[0,255],可以用矩阵表示图片 卷积层 —特征提取 人通过特征进行图像识别,根据左图直的笔画判断X,右图曲的笔画判断圆 卷积操作 激活层 —加强特征 池化层 —压缩数据 全连接层 —进行分类 输出层 —输出分类概率 4、基于LeNet

pytorch torch.nn.functional.one_hot函数介绍

torch.nn.functional.one_hot 是 PyTorch 中用于生成独热编码(one-hot encoding)张量的函数。独热编码是一种常用的编码方式,特别适用于分类任务或对离散的类别标签进行处理。该函数将整数张量的每个元素转换为一个独热向量。 函数签名 torch.nn.functional.one_hot(tensor, num_classes=-1) 参数 t

pytorch计算网络参数量和Flops

from torchsummary import summarysummary(net, input_size=(3, 256, 256), batch_size=-1) 输出的参数是除以一百万(/1000000)M, from fvcore.nn import FlopCountAnalysisinputs = torch.randn(1, 3, 256, 256).cuda()fl

Python(TensorFlow和PyTorch)两种显微镜成像重建算法模型(显微镜学)

🎯要点 🎯受激发射损耗显微镜算法模型:🖊恢复嘈杂二维和三维图像 | 🖊模型架构:恢复上下文信息和超分辨率图像 | 🖊使用嘈杂和高信噪比的图像训练模型 | 🖊准备半合成训练集 | 🖊优化沙邦尼尔损失和边缘损失 | 🖊使用峰值信噪比、归一化均方误差和多尺度结构相似性指数量化结果 | 🎯训练荧光显微镜模型和对抗网络图形转换模型 🍪语言内容分比 🍇Python图像归一化

Pytorch环境搭建时的各种问题

1 问题 1.一直soving environment,跳不出去。网络解决方案有:配置清华源,更新conda等,没起作用。2.下载完后,有3个要done的东西,最后那个exe开头的(可能吧),总是报错。网络解决方案有:用管理员权限打开prompt等,没起作用。3.有时候配置完源,安装包的时候显示什么https之类的东西,去c盘的用户那个文件夹里找到".condarc"文件把里面的网址都改成htt

【PyTorch】使用容器(Containers)进行网络层管理(Module)

文章目录 前言一、Sequential二、ModuleList三、ModuleDict四、ParameterList & ParameterDict总结 前言 当深度学习模型逐渐变得复杂,在编写代码时便会遇到诸多麻烦,此时便需要Containers的帮助。Containers的作用是将一部分网络层模块化,从而更方便地管理和调用。本文介绍PyTorch库常用的nn.Sequen

【python pytorch】Pytorch实现逻辑回归

pytorch 逻辑回归学习demo: import torchimport torch.nn as nnimport torchvision.datasets as dsetsimport torchvision.transforms as transformsfrom torch.autograd import Variable# Hyper Parameters input_si