pytorch深度学习入门与实战代码与标注(一)

# _*_ coding: utf-8 _*_
"""
Time:     2021/11/13 21:14
Author:   LucifMonX
Version:  V 3.9
File:     第一章 入门篇.py.py
Describe: 入门简单介绍相关元素
"""
import torch

# 输出pytorch版本
print(torch.__version__)  # 1.9.0
print('--------------------1.张量Tensor--------------')
'''
数学中:
标量:一个单独的数
向量:一列或一行数组
矩阵:二维数组
若数组的维度超过2,则称该数组为Tensor张量
但在pytorch中,tensor包括了前面所有,甚至更高维度的数组
'''
# 1.1张量的数据类型
# 获取张量的数据类型 使用torch.tensor()函数生成一个张量,然后使用.dtype方法获取张量 torch中默认的数据类型是32位浮点型
torch_type = torch.tensor([1.2, 3.4]).dtype
print(torch_type)  # torch.float32
# 将张量的默认数据类型设置为双精度浮点double
torch.set_default_tensor_type(torch.DoubleTensor)
torch_type = torch.tensor([1.2, 3.4]).dtype
print(torch_type)  # torch.float64
# 还有其他数据类型
a = torch.tensor([1.2, 3.4])
print("a的数据类型(由于26行设置成64位浮点):", a.dtype)  # a的数据类型(由于26行设置成64位浮点): torch.float64
print("a转换成 长整型long:", a.long().dtype)  # a转换成 长整型long: torch.int64
print("a转换成 整型int:", a.int().dtype)  # a转换成 整型int: torch.int32
print("a转换成 32浮点数float:", a.float().dtype)  # a转换成 32浮点数float: torch.float32
# 设置回32位浮点float
torch.set_default_tensor_type(torch.FloatTensor)
# 获取默认的数据类型
print(torch.get_default_dtype())# torch.float32
# 1.2 张量的生成
# 1.2.1 使用torch.tensor()函数生成张量
A = torch.tensor([[1.0, 1.0], [2, 2]])
print(A)
'''
tensor([[1., 1.],
        [2., 2.]])
'''
# 获取张量的维度
print(A.shape)#torch.Size([2, 2])
# 获取张量的形状大小
print(A.size())# torch.Size([2, 2])
# 计算张量中包含的元素数量
print(A.numel())#4
# 在使用torch.tensor()函数时,可以使用参数dtype来指定张量的数据类型,使用参数requires_grad来指定张量是否需要计算梯度
B = torch.tensor((1, 2, 3), dtype=torch.float32, requires_grad=True)
print(B)#tensor([1., 2., 3.], requi
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值