PyTorch 入门学习数据操作之创建

简介

在深度学习中,我们通常会频繁地对数据进行操作;要操作一般就需要先创建。

官方介绍

The torch package contains data structures for multi-dimensional tensors and defines mathematical operations over these tensors. Additionally, it provides many utilities for efficient serialization of Tensors and arbitrary types, and other useful utilities

It has a CUDA counterpart, that enables you to run your tensor computations on an NVIDIA GPU with compute capability >= 3.0

我的介绍

在 PyTorch 中,torch.Tensor是进行存储和进行变换数据的主要工具

  • tensor 是什么意思?上翻译:

    一般可译作张量,张量可以看作是一个多维数组

创建

  • 这里直接上代码
python 复制代码
# 导入PyTorch
import torch



"""
    官方文档地址:https://pytorch.org/docs/2.1/torch.html#creation-ops
"""


#
def create_empty_torch(a,b):
    """
    Args:
    a:
    b:
    创建一个 [a] x [b] 的未初始化的 Tensor
    :return: Returns a tensor filled with uninitialized data.
    """

    empty = torch.empty(a,b)
    print(empty)



def create_zero_torch():
    """
    创建一个 7x5 的 long 类型全是 0 的 Tensor
    Returns:
        Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size
    """

    zero = torch.zeros(7,5,dtype=torch.long)
    print(zero)

def create_data_torch():
    """
    Constructs a tensor with no autograd history (also known as a "leaf tensor", see Autograd mechanics) by copying data
    :return:
    """
    data = torch.tensor([12.5,7])
    print(data)

def create_data_2_torch():
    data = torch.tensor([12.5, 7])
    # 返回的 tensor 默认具有相同的 torch.dtype 和 torch.device
    data = data.new_ones(2, 1, dtype=torch.float64)
    print(data)
    # 指定新的数据类型
    data = torch.randn_like(data, dtype=torch.float)
    print(data)


if __name__ == '__main__':
    create_data_2_torch()
  • 测试结果我就不贴图了,太费事,直接运行自己看

结束语

本系列教程仅针对入门初学者或者非此行业人员,敬请期待!

相关推荐
昇腾知识体系1 分钟前
昇腾训练性能分析实战:torch_npu profiler 从采集到 kernel_details 解读
人工智能·华为·知识图谱
residual_fan5 分钟前
航空发动机故障诊断专用智能体(一):小样本与高不平衡下的工程挑战
人工智能·数据挖掘·数据分析
兔兔爱学习兔兔爱学习12 分钟前
DeepSeek-V4.1-Flash:突破 KV 缓存压缩的极限
人工智能
Raas10013 分钟前
MAI Gateway(魔芋企业级AI网关)能力解析:AI网关支持DeepSeek吗?AI网关核心功能详解
人工智能·网关·ai网关·mai gateway·企业级产品
zhangfeng113318 分钟前
昇腾 950PR/950DT 新增regbase 编程方式和MemBase SIMD/SIMT 混合编程模型
人工智能·华为·ai编程·npu·cann
JoyCong199820 分钟前
鸿蒙用户等来的是ToDesk:折叠屏适配、星闪笔、互动Tab一次补齐
人工智能·智能手机·电脑·鸿蒙·鸿蒙系统·远程工作·ipad
飞猫的边缘AI21 分钟前
边缘AI时事:从豆包手机二代和Rokid×WorkBuddy联名AI眼镜看AI智能体进终端的必然与边界
人工智能·ai智能体·rokid眼镜·workbuddy·豆包手机二代
艾醒(AiXing-w)22 分钟前
LangChain 1.0 智能体开发(三):Agent 记忆管理——从短期对话到跨会话长期记忆
数据库·人工智能·langchain
知几蜗牛23 分钟前
部署大模型别先选GPU,先回答你愿意承担多少运维
人工智能
知几蜗牛24 分钟前
AI写了80万行Rust,最值得学的却是它花十倍精力读代码
人工智能