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()
  • 测试结果我就不贴图了,太费事,直接运行自己看

结束语

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

相关推荐
ZhengEnCi5 小时前
09bad-斯坦福CS336作业一-构建优化器
人工智能
ZhengEnCi6 小时前
09bac-斯坦福CS336作业一-实现训练损失计算
人工智能
冬奇Lab6 小时前
Skill 系列(01):Skill 评测体系——如何量化一个 AI Skill 的质量
人工智能
IT_陈寒9 小时前
Redis内存爆了,原来我漏掉了这个致命配置
前端·人工智能·后端
用户35218024547511 小时前
🎆从 Prompt 到 Skill:让 Spring AI Agent 学会"装新技能"
人工智能·spring boot·ai编程
米小虾11 小时前
手把手教你搭建第一个生产级AI Agent:从选型到实战的完整指南
人工智能·agent
任沫11 小时前
Agent之Function Call
javascript·人工智能·go
米小虾11 小时前
2026年AI Agent全面爆发:从开源生态到企业级应用的进化之路
人工智能·agent
用户69190268133912 小时前
Vibe Coding 开发项目的基本范式
人工智能·设计模式·代码规范
To_OC12 小时前
别再跟 AI 死磕 prompt 了,我写了个 Loop 让它自己改到满意为止
人工智能·aigc·agent