深度学习入门笔记(5)——tensor
(1)定位:操作对象
(2)概念:张量,表示一个矩阵,与numpy中的ndarray对应。
(3)与numpy数组区别:tensor可以在GPU上运行,ndarray只能在CPU上运行。
(4)数据类型:int、float等等都可以,默认情况为float
(5)声明:
# 定义两行两列列给定数值的矩阵
matrix = torch.Tensor([[1, 1], [2, 2]])
# 打印矩阵数据类型、大小及样式
print("the matrix type is {}".format(type(matrix)))
print("the matrix size is {}".format(matrix.shape))
print("the matrix is \n{}".format(matrix))
运行结果
the matrix type is <class 'torch.Tensor'>
the matrix size is torch.Size([2, 2])
the matrix is
tensor([[1., 1.],
[2., 2.]])
Process finished with exit code 0
(6)zeros和ones:
# 定义矩阵
matrix_zero = torch.zeros((2,2))
matrix_one = torch.ones((2,2))
# 打印矩阵数据类型、大小及样式
print("the matrix type is {}".format(type(matrix_zero)))
print("the matrix size is {}".format(matrix_zero.shape))
print("the matrix is \n{}".format(matrix_zero))
print("the matrix type is {}".format(type(matrix_one)))
print("the matrix size is {}".format(matrix_one.shape))
print("the matrix is \n{}".format(matrix_one))
运行结果
the matrix type is <class 'torch.Tensor'>
the matrix size is torch.Size([2, 2])
the matrix is
tensor([[0., 0.],
[0., 0.]])
the matrix type is <class 'torch.Tensor'>
the matrix size is torch.Size([2, 2])
the matrix is
tensor([[1., 1.],
[1., 1.]])
Process finished with exit code 0
这里我们也可以发现,tensor默认为float
(7)索引
# 定义两行两列列给定数值的矩阵
matrix = torch.Tensor([[1,1],[2,2]])
# 索引
print("the last value of this matrix is {}".format(matrix[1,1]))
# 改变最后一个元素的值
matrix[1,1] = 6
print("after changed,the last value of this matrix is {}".format(matrix[1,1]))
运行结果
the last value of this matrix is 2.0
after changed,the last value of this matrix is 6.0
Process finished with exit code 0
(8)与ndarray格式转换
# 定义torch和numpy格式下的矩阵(数组)
matrix = torch.Tensor([[1,1],[2,2]])
array = np.array([[2,2],[1,1]])
# array转换为torch格式
print("before change , the array's type is {}".format(type(array)))
matrix_change = torch.from_numpy(array)
print("before change , the array's type is {}".format(type(matrix_change)))
运行结果
before change , the array's type is <class 'numpy.ndarray'>
before change , the array's type is <class 'torch.Tensor'>
Process finished with exit code 0
最后
欢迎大家在评论区留言讨论!