pytorch tensor创建tensor

目录

一、使用torch.Tensor创建

二、直接生成特殊的tensor

三、仿造其他tensor生成

四、从numpy生成

五、tensor中的to方法


一、使用torch.Tensor创建

python 复制代码
import torch
data=[[1,2],[3,4]]
x_data=torch.tensor(data)  # 将列表和数组传给tensor会自动转成tensor类型
x_data1=torch.tensor((1,2,3,4)) # 使用元组创建
print(x_data1)

二、直接生成特殊的tensor

python 复制代码
import torch
data1=torch.ones(1,2,3) # 创建一个维度为(1,2,3)的元素全为1的tensor
data2=torch.zeros(1,2,3) # 创建一个维度为(1,2,3)的元素全为0的tensor
data3=torch.randn(3,4,5) # 创建一个维度为(3,4,5)的符合正态分布的tensor
data4=torch.eye(4,5) # 创建一个维度为(4,5)的单位矩阵
data5=torch.randint(5,(5,8)) # 创建一个5一下的随机整数维度为(5,8)的tensot
print(type(data4))
print(data4)

三、仿造其他tensor生成

python 复制代码
import torch

data0=torch.Tensor([1,2,3,4])   
data1=torch.ones_like(data0)  # 仿造传入tensor生成相同形式的全为1的tensor
data2=torch.empty_like(data1)  # 生成全为0的tensor
print(data2)

四、从numpy生成

python 复制代码
import torch
import numpy as np

arr=np.array([1,2,3,4])
tensor0=torch.from_numpy(arr)  # 对arr进行了浅拷贝
tensor1=torch.Tensor(arr) # 对arr进行了深拷贝
arr[0]=100
data_numpy=tensor0.numpy() # 将tensor转成numpy
print(tensor0) # 和arr数组一起改变
print(tensor1)

五、tensor中的to方法

1.数据类型转换

python 复制代码
tensor0=torch.ones(4,5)
    tensor1=tensor0.to(torch.int64)  # 将数据类型转换成传入的数据类型
    tensor2=tensor0.to(tensor1)   # 将数据类型转换乘传入的tensor的类型
    print(tensor2)

2.device转化

python 复制代码
def tensor_device_demo():
    if torch.cuda.is_available():
        device=torch.device('cuda:0')
    else:
        device=torch.device('cpu')

    # 将数据转到gpu中运行
    tensor0=torch.randn(4,5)
    tensor1=tensor0.to(device)
相关推荐
李白你好6 分钟前
RedTeam-Agent无需手动操作,AI 接管所有渗透工具,让安全测试真正自动化
运维·人工智能·自动化
奇牙9 分钟前
DeepSeek V4 Agent 开发实战:用 deepseek-v4-pro 搭建多步骤工作流(2026 完整代码)
python
容智信息10 分钟前
国家级算力底座+企业级智能体:容智Agent OS 获选入驻移动云能中心,联手赋能千行百业
大数据·人工智能·自然语言处理·智慧城市
斯维赤10 分钟前
Python学习超简单第八弹:连接Mysql数据库
数据库·python·学习
彭祥.13 分钟前
ONNX模型多线程推理并解决线程踩踏问题
人工智能
Lonwayne24 分钟前
从提示词工程到驾驭工程:AI协作的三代进化
人工智能·ai·ai编程·ai智能体
herinspace32 分钟前
如何解决管家婆辉煌零售POS中显示的原价和售价不一致?
网络·人工智能·学习·excel·语音识别·零售
肖有米XTKF864633 分钟前
金木新零售模式系统开发介绍平台解析
人工智能·信息可视化·软件工程·团队开发·csdn开发云
qq_6543669834 分钟前
如何排查Oracle客户端连接慢_DNS解析超时与sqlnet配置优化
jvm·数据库·python