# _*_ 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
pytorch深度学习入门与实战代码与标注(一)
最新推荐文章于 2024-06-17 18:07:58 发布
本文档提供了PyTorch深度学习的入门教程,包括基础概念讲解和实战代码示例,旨在帮助初学者快速掌握PyTorch进行AI开发。
摘要由CSDN通过智能技术生成