📅  最后修改于: 2023-12-03 15:19:37.133000             🧑  作者: Mango
PyTorch是一个基于Python的科学计算库,其主要优势在于支持动态计算图和GPU加速。所以PyTorch在深度学习领域中广受欢迎。本文将介绍PyTorch的基本使用方法和逆向工程。
!pip install torch
import torch
a = torch.Tensor(3, 3)
print(a)
输出结果:
tensor([[7.0453e+22, 3.0821e+23, 6.3828e+28],
[2.5262e-18, 2.3147e-12, 1.2725e-11],
[7.5338e+28, 7.0365e+22, 5.2499e+22]])
a = torch.ones(3, 3)
b = torch.rand(3, 3)
print(a)
print(b)
c = a + b
print(c)
输出结果:
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
tensor([[0.2718, 0.1872, 0.4394],
[0.7485, 0.4800, 0.4665],
[0.2032, 0.4461, 0.9247]])
tensor([[1.2718, 1.1872, 1.4394],
[1.7485, 1.4800, 1.4665],
[1.2032, 1.4461, 1.9247]])
import torch
import numpy as np
import torch.autograd as autograd
from torch import Tensor
from typing import Tuple
class MyNet(torch.nn.Module):
def __init__(self) -> None:
super(MyNet, self).__init__()
self.fc1 = torch.nn.Linear(100, 50)
self.fc2 = torch.nn.Linear(50, 10)
def forward(self, x: Tensor) -> Tensor:
x = self.fc1(x)
x = torch.nn.functional.relu(x)
x = self.fc2(x)
x = torch.nn.functional.softmax(x)
return x
input = autograd.Variable(torch.randn(1, 100), requires_grad=True)
label = autograd.Variable(torch.LongTensor([5]))
model = MyNet()
output = model(input)
loss_fn = torch.nn.CrossEntropyLoss()
loss = loss_fn(output, label)
loss.backward()
grads = list()
for name, layer in model.named_parameters():
if layer.grad is not None:
grads.append(layer.grad.view(-1))
grads = torch.cat(grads).data.cpu().numpy()
以上就是PyTorch的基本使用方法和逆向工程的介绍。你可以通过这篇文章学到一些基础知识及逆向工程的实现方式,欢迎有兴趣的人加入深度学习领域,共同探索。