深度学习入门笔记(5)——什么是tensor?

深度学习入门笔记(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

最后

欢迎大家在评论区留言讨论!

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZRX_GIS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值