当前位置: 首页 > news >正文

在pytorch中,读取GPU上张量的数值 (数据从GPU到CPU) 的几种常用方法

1、.cpu() 方法:
        使用 .cpu() 方法可以将张量从 GPU 移动到 CPU。这是一种简便的方法,常用于在进行 CPU 上的操作之前将数据从 GPU 取回

import torch# 在 GPU 上创建一个张量
gpu_tensor = torch.tensor([1, 2, 3], device='cuda')# 将 GPU 上的张量移动到 CPU
cpu_tensor = gpu_tensor.cpu()# 打印输出
print("GPU Tensor:", gpu_tensor)
print("CPU Tensor:", cpu_tensor)
GPU Tensor: tensor([1,2,3],device='cuda:')
CPU Array: tensor([1,2,3])

2、.to('cpu') 方法:
        使用 .to('cpu') 方法也可以将张量移动到 CPU。这是一个通用的设备转移方法,可以指定目标设备和其他参数。

import torch# 在 GPU 上创建一个张量
gpu_tensor = torch.tensor([1, 2, 3], device='cuda')# 将 GPU 上的张量移动到 CPU
cpu_tensor = gpu_tensor.to('cpu')# 打印输出
print("GPU Tensor:", gpu_tensor)
print("CPU Tensor:", cpu_tensor)
GPU Tensor: tensor([1,2,3],device='cuda:')
CPU Array: tensor([1,2,3])

3、.numpy() 方法:
        使用 .numpy() 方法将 GPU 上的张量转换为 NumPy 数组。这个方法实际上是先将张量移动到 CPU,然后转换为 NumPy 数组。

import torch# 在 GPU 上创建一个张量
gpu_tensor = torch.tensor([1, 2, 3], device='cuda')# 将 GPU 上的张量移动到 CPU,并转换为 NumPy 数组
cpu_array = gpu_tensor.cpu().numpy()# 打印输出
print("GPU Tensor:", gpu_tensor)
print("CPU Array:", cpu_array)
GPU Tensor: tensor([1,2,3],device='cuda:')
CPU Array: array([1,2,3])

4、.tolist() 方法:
        使用 .tolist() 方法将张量转换为 Python 列表。

import torch# 在 GPU 上创建一个张量
gpu_tensor = torch.tensor([1, 2, 3], device='cuda')# 将张量转换为 Python 列表
python_list = gpu_tensor.tolist()# 打印输出
print("GPU Tensor:",gpu_tensor)
print("\nPython_list:",python_list)
GPU Tensor: tensor([1,2,3],device='cuda:')
Python_list: [1,2,3]

5、.item() 方法:
        如果张量只包含一个元素,可以使用 .item() 方法直接获取该元素的 Python 数值。

import torch# 在 GPU 上创建一个张量
gpu_tensor = torch.tensor(3, device='cuda')# 获取张量的数值
value = gpu_tensor.item()# 打印输出
print("GPU Tensor:", gpu_tensor)
print("Value:", value)
GPU Tensor: tensor(3,device='cuda:')
Value: 3
http://www.lryc.cn/news/269508.html

相关文章:

  • 【mysql】—— 表的内连和外连
  • VSCode远程开发配置
  • 复数值神经网络可能是深度学习的未来
  • 【C语言】数据结构——排序二(快排)
  • 企业私有云容器化架构
  • SpringBoot+modbus4j实现ModebusTCP通讯读取数据
  • Linux性能优化全景指南
  • 树莓派 ubuntu20.04下 python调讯飞的语音API,语音识别和语音合成
  • 分布式系统架构设计之分布式系统实践案例和未来展望
  • 【办公软件】Excel双坐标轴图表
  • 彻底理解前端安全面试题(1)—— XSS 攻击,3种XSS攻击详解,建议收藏(含源码)
  • UE5.1_AI随机漫游
  • 智慧城市新型基础设施建设综合方案:文件全文52页,附下载
  • GitHub Copilot 终极详细介绍
  • LeetCode第63题 - 不同路径 II
  • python+django网上银行业务综合管理系统vue_bvj8b
  • 【软件工程】走进瀑布模型:传统软件开发的经典之路
  • 两个字符串间的最短路径问题 (100%用例)C卷 (JavaPythonNode.jsC语言C++)
  • 通过ADB来实现脚本来控制手机
  • 机器学习之K-means聚类
  • SSH 端口转发:如何将服务绑定到本地 IP 地址
  • 回归预测 | MATLAB实ZOA-LSTM基于斑马优化算法优化长短期记忆神经网络的多输入单输出数据回归预测模型 (多指标,多图)
  • python实现图像的二维傅里叶变换——冈萨雷斯数字图像处理
  • We are a team - 华为OD统一考试
  • NFC物联网智慧校园解决方案
  • 鸿蒙系列--组件介绍之容器组件
  • perl使用find函数踩坑
  • Java IDEA JUnit 单元测试
  • 深入理解 c++ 函数模板
  • 系列十二、Linux中安装Zookeeper