pytorch学習1インストールと入門

9708 ワード

インストール


condaとpipはすべてできて、pipは速く自分でダウンロードして、端末で入力してリンクすることができます:link.vscodeはデバッグでjypter notebookかipythonを使いました

入門(python参照)


torchとnumpy変換
import torch
import numpy as np
np_data = np.arange(6).reshape((2, 3))
torch_data = torch.from_numpy(np_data)
tensor2array = torch_data.numpy()
print(
    '
numpy array:'
, np_data, # [[0 1 2], [3 4 5]] '
torch tensor:'
, torch_data, # 0 1 2
3 4 5 [torch.LongTensor of size 2x3]
'
tensor to array:'
, tensor2array, # [[0 1 2], [3 4 5]] )

tensor
tensorはpytorchのデータ構造で、高次元配列1.5*3配列に似ています.
x=t.tensor(5,3)

2.ランダム2 D配列
x=t.rand(5,3)
print(x.size(),x.size()[0],x.size(1))#   

3.add
t.add(x,y)
x+y
result=t.Tensor(5,3)
t.add(x,y,out=result)
print(result)
y.add(x)
print(y,"y")
##inplace add,y   ,        tensor  
y.add_(x)
print(y,"y")

4.5行1行
##    2
x[:,2]
a=t.ones(5)
print(a)

5.numpyとtensor変換
import numpy as np
np_data = np.arange(6).reshape((2, 3))
torch_data = torch.from_numpy(np_data)
tensor2array = torch_data.numpy()
print(
    '
numpy array:'
, np_data, # [[0 1 2], [3 4 5]] '
torch tensor:'
, torch_data, # 0 1 2
3 4 5 [torch.LongTensor of size 2x3]
'
tensor to array:'
, tensor2array, # [[0 1 2], [3 4 5]] )

6.gpu
if t.cuda.is_available():    
    x=x.cuda()

7.others
# abs      
data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data)  #    32    tensor
print(
    '
abs'
, '
numpy: '
, np.abs(data), # [1 2 1 2] '
torch: '
, torch.abs(tensor) # [1 2 1 2] ) # sin sin print( '
sin'
, '
numpy: '
, np.sin(data), # [-0.84147098 -0.90929743 0.84147098 0.90929743] '
torch: '
, torch.sin(tensor) # [-0.8415 -0.9093 0.8415 0.9093] ) # mean print( '
mean'
, '
numpy: '
, np.mean(data), # 0.0 '
torch: '
, torch.mean(tensor) # 0.0 )
# matrix multiplication
data = [[1,2], [3,4]]
tensor = torch.FloatTensor(data)  # 32-bit floating point
# correct method
print(
    '
matrix multiplication (matmul)'
, '
numpy: '
, np.matmul(data, data), # [[7, 10], [15, 22]] '
torch: '
, torch.mm(tensor, tensor) # [[7, 10], [15, 22]] ) # incorrect method data = np.array(data) print( '
matrix multiplication (dot)'
, '
numpy: '
, data.dot(data), # [[7, 10], [15, 22]] '
torch: '
, tensor.dot(tensor) # this will convert tensor to [1,2,3,4], you'll get 30.0 )