栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

torch 和numpy的相互转化

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

torch 和numpy的相互转化

import math
import torch
import numpy as np
import pandas as pd

A = np.array([[1,2,3],[6,5,3]])
print(A, 'n')
B = torch.from_numpy(A)  #将numpy 转换化为 tensor
print(B)
C = B.numpy()#tensor 转换化为 numpy 但是对该numpy进行修改会改变其他的的值
 # 对C该表 A,B 都会相应的改变
C[1] = 0
print(A, 'n')
print(B)
print(C)
import torch
import numpy as np

#创建一个numpy array的数组
array = np.array([1,2,3,4])

#将numpy array转换为torch tensor
tensor = torch.tensor(array)
Tensor = torch.Tensor(array)
as_tensor = torch.as_tensor(array)
from_array = torch.from_numpy(array)

print(array.dtype)      #int32
#查看torch默认的数据类型
print(torch.get_default_dtype())    #torch.float32

#对比几种不同方法之间的异同
print(tensor.dtype)     #torch.int32
print(Tensor.dtype)     #torch.float32
print(as_tensor.dtype)  #torch.int32
print(from_array.dtype) #torch.int32
array[0] = 10

print(tensor)     # tensor([1, 2, 3, 4], dtype=torch.int32)
print(Tensor)     # tensor([1., 2., 3., 4.])
print(as_tensor)  #tensor([10,  2,  3,  4], dtype=torch.int32)
print(from_array) #tensor([10,  2,  3,  4], dtype=torch.int32)
# 后面两种数据改变,前面不变

tensor 转化为numpy 只有找到 a.numpy

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/503909.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号