一、构建tensor
1 2 3 4 5 6 7 8 import torch a = torch.tensor(0.1 ) b = torch.tensor(0.3 , dtype=torch.float64) result = a + bprint (result)
tensor(0.4000, dtype=torch.float64)
1 2 3 4 5 6 7 import torch ones = torch.ones((3 , 2 )) range_tensor = torch.arange(1 , 11 , 1 ) print ('ones:' , ones, '\n' , 'range_tensor:' , range_tensor)
ones: tensor([[1., 1.],
[1., 1.],
[1., 1.]])
range_tensor: tensor([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
1 2 3 4 5 6 7 8 9 10 11 import torch output = torch.zeros((2 , 2 ), dtype=torch.float32)print ("1--->" , output)print ("2--->output: {}" .format (type (output))) n_output = output.numpy()print ("3--->n_output: {}" .format (type (n_output))) t_output = torch.from_numpy(n_output) print ("4--->t_output: {}" .format (type (t_output)))
1---> tensor([[0., 0.],
[0., 0.]])
2--->output: <class 'torch.Tensor'>
3--->n_output: <class 'numpy.ndarray'>
4--->t_output: <class 'torch.Tensor'>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import torchimport numpy as np data = [[1 , 2 ],[3 , 4 ]] x_data = torch.tensor(data) print ("1--->x_data:" , x_data)print ("x_data type:{}" .format (type (x_data))) np_array = np.array(data) print ("2--->np_array" , np_array) x_np = torch.from_numpy(np_array) print ("3--->x_np" , x_np)print ("x_np type:{}" .format (type (x_np))) x_ones = torch.ones_like(x_data) print (f"Ones Tensor: \n {x_ones} \n" ) x_rand = torch.rand_like(x_data, dtype=torch.float ) print (f"Random Tensor: \n {x_rand} \n" )
1--->x_data: tensor([[1, 2],
[3, 4]])
x_data type:<class 'torch.Tensor'>
2--->np_array [[1 2]
[3 4]]
3--->x_np tensor([[1, 2],
[3, 4]], dtype=torch.int32)
x_np type:<class 'torch.Tensor'>
Ones Tensor:
tensor([[1, 1],
[1, 1]])
Random Tensor:
tensor([[0.0282, 0.8095],
[0.2707, 0.1938]])
1 2 3 4 5 6 7 8 9 10 import torchimport numpy as np tensor = torch.rand(4 , 4 )print (f"First row: {tensor[1 ]} " )print (f"First column: {tensor[:, 0 ]} " )print (f"Last column: {tensor[..., -1 ]} " ) tensor[:,1 ] = 0 print (tensor)
First row: tensor([0.1094, 0.4258, 0.9837, 0.3118])
First column: tensor([0.3335, 0.1094, 0.4532, 0.2374])
Last column: tensor([0.7949, 0.3118, 0.5406, 0.5577])
tensor([[0.3335, 0.0000, 0.1649, 0.7949],
[0.1094, 0.0000, 0.9837, 0.3118],
[0.4532, 0.0000, 0.6070, 0.5406],
[0.2374, 0.0000, 0.7951, 0.5577]])
1 2 3 4 5 6 7 8 9 10 11 import torch t = torch.tensor([[1 , 2 ], [3 , 4 ]], dtype=torch.float32)print (t)print (t.data) print (t.data.numpy()) print (t.data.numpy().argmax(axis=1 )) x = torch.tensor([1.0 , 2.0 , 3.0 ], requires_grad=True )print (x)print (x.data)
tensor([[1., 2.],
[3., 4.]])
tensor([[1., 2.],
[3., 4.]])
[[1. 2.]
[3. 4.]]
[1 1]
tensor([1., 2., 3.], requires_grad=True)
tensor([1., 2., 3.])
1 2 3 4 5 6 import torchimport numpy as np tensor = torch.tensor([[2 , 3 ], [4 , 5 ], [6 , 7 ]], dtype=torch.float64)print (tensor) tensor.mean()
tensor([[2., 3.],
[4., 5.],
[6., 7.]], dtype=torch.float64)
tensor(4.5000, dtype=torch.float64)