import numpy as np
import torch
# create a tensor in a similar way to numpy np array
x_numpy = np.array([0.1,0.2,0.3])
x_torch = torch.tensor([0.1,0.2,0.3])print('x_numpy','x_torch')print(x_numpy,x_torch)print()#to and from numpy ,pytorchprint('to and from numpy ,pytorch:')print(torch.from_numpy(x_numpy),x_torch.numpy)print()#basic operations
y_numpy = np.array([3,4,5])
y_torch = torch.tensor([3,4,5])print('add:')print(x_numpy+y_numpy,x_torch+y_torch)print()#many functions that are in numpy are also in pytorchprint('norm,即二范数:')print(np.linalg.norm(x_numpy),torch.norm(x_torch))print()#to apply an operation allong a dimensionprint('mean along the 0th dimension:')
z_numpy = np.array([[1,2],[3,4.]])
z_torch = torch.tensor([[1,2],[3,4.]])print(np.mean(z_numpy,axis=0),torch.mean(z_torch,dim=0))#keyword有些不一样'''result:
x_numpy x_torch
[0.1 0.2 0.3] tensor([0.1000, 0.2000, 0.3000])
to and from numpy ,pytorch:
tensor([0.1000, 0.2000, 0.3000], dtype=torch.float64) <built-in method numpy of Tensor object at 0x0000020A30088090>
add:
[3.1 4.2 5.3] tensor([3.1000, 4.2000, 5.3000])
norm,即二范数:
0.37416573867739417 tensor(0.3742)
mean along the 0th dimension:
[2. 3.] tensor([2., 3.])
'''