python torch学習(一)

2252 ワード

1.torchとnumpyの比較と両者の間の変換.
import torch
import numpy as np

numpy_data = np.arange(15).reshape(3,5)
print 'numpy_data',numpy_data
torch_data = torch.from_numpy(numpy_data)
print 'torch_data',torch_data
numpy_data1 = torch_data.numpy()
print 'numpy_data1',numpy_data1

2.torchマトリクスの構築
#coding=utf-8
import torch

data = torch.Tensor(3,5)   #    3×5       
print data

data1 = torch.rand(5,3)    #            
print data1
print data1.size()

3.torch加算
#coding=utf-8
import torch

x = torch.rand(5,3)    #            
y = torch.rand(5,3)

print x + y

print torch.add(x,y)

#          
result = torch.Tensor(5,3)
torch.add(x,y,out=result)
print result

#    
y.add_(x)
print y

  :                _   

4.スライスおよびview方法
#coding=utf-8
import torch

x = torch.rand(4,4)    #            
print x[:,1]  #    
y = x.view(16)
print y
z = x.view(-1,8)   #2*8
print z

5.tensorの作成
#coding=utf-8
import torch
import numpy as np

x = torch.rand(4,4)    #            
print torch.is_tensor(x)   #  True
print torch.numel(x)     #  16
#    
#1.     1
y = torch.eye(3,4)   #     1,   0
print y

#2. numpy.ndarray     tensor 
a = np.array([1,2,3])
t = torch.from_numpy(a)
print t
t[0] = -1
print a   #[-1  2  3],        tensor  ndarray       

#3.  torch.linspace
b = torch.linspace(2,10,steps=10)  #  step start  end       
print b

#4.torch.logspace()   10^start 10^end       
c = torch.logspace(0.1,1.0,steps=5)
print c

#5.  1
d = torch.ones(4,4)
print d

#6.torch.arange()
e = torch.arange(1,4)  #  step = 1
print e

#7.torch.zeros()
f = torch.zeros(6)
print f
g = torch.zeros(2,3)
print g


6.インデックス、スライス、接続、シフト
#coding=utf-8
import torch

#cat      ,              
x = torch.randn(2,3)

y = torch.cat((x,x),0) #      
print y

z = torch.cat((x,x),1)  #      
print z

#chunk               。chunks:         
g = torch.chunk(x,2,1)
print g

print '--'*20
#split           size chunks。      ,          
w = torch.split(z,3,dim=1)  #3:         3
print w

#stack                 
f = torch.stack((x,x),dim=0)
print f

#  
e = torch.t(x)
print e