Pytorchスタディノート2.1:ディープラーニングライブラリ

ディープラーニングライブラリで何ができるでしょうか?

  • GPUアクセラレーション

import torch
import time
print(torch.__version__)
print(torch.cuda.is_available())

a = torch.randn(10000, 1000)  # 随机生成服从正态分布10000行x1000列的张量
b = torch.randn(1000, 2000)

t0 = time.time()
c = torch.matmul(a, b)
t1 = time.time()
print(a.device, t1 - t0, c.norm(2))  # cpu 0.41573262214660645 tensor(140925.6406)

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

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:0 0.006535530090332031 tensor(141469.8906, device='cuda:0')

1. torch.rand()とtorch.randn()の違いは何ですか?
torch.randn(* size、out = None)
randnは、正規分布に従うデータをランダムに生成するためのものであり、戻り値はテンソルです。

パラメータ:

sizes (int...) - 整数序列,定义了输出张量的形状
out (Tensor, optinal) - 结果张量

torch.rand(* size、out = None)

randは、一様分布に従うランダムに生成されたデータであり、戻り値はテンソルです。

パラメータ:

sizes (int...) - 整数序列,定义了输出张量的形状
out (Tensor, optinal) - 结果张量

2. pytorchノルム機能-torch.norm

torch.norm(input、p = 'fro'、dim = None、keepdim = False、out = None、dtype = None)

指定されたテンソル
3の行列ノルムまたはベクトルノルムを返します。pytorchの.cuda()と.to(device)
違いはありますか。Cuda()は、
スクリーンショットを実行している.to(device)と同等です。
ここに画像の説明を挿入

  • 自動導関数

yからabcへの偏導関数を見つけます。
ここに画像の説明を挿入

import torch
from torch import autograd


x = torch.tensor(1.)
a = torch.tensor(1., requires_grad=True)  # requires_grad=True 是告诉pytorch我们是对a b c求导
b = torch.tensor(2., requires_grad=True)
c = torch.tensor(3., requires_grad=True)

y = a**2 * x + b * x + c

print('\nbefore: ', a.grad, b.grad, c.grad)
grads = autograd.grad(y, [a, b, c])
print('\nafter: ', grads[0], grads[1], grads[2])

Pytorchでのtorch.autograd.grad()関数の使用例

autograd.grad(outputs、inputs、grad_outputs = None、retain_graph = None、
create_graph = False、only_inputs = True、allow_unused = False)

出力:導出の従属変数(導出を必要とする関数)

入力:導出される独立変数

grad_outputs:outputsがスカラーの場合、grad_outputs = None、つまり、書き込む必要はありません。outputsがベクトルの場合、このパラメーターを書き込む必要があります。書き込まない場合、エラーが報告されます。

  • 共通のネットワーク層API

ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/weixin_44145452/article/details/113041708