【pytorch】1.7 pytorch与numpy,tensor与array的转换

1、pytorch与numpy 函数对比

在这里插入图片描述


2、array 转换为 tensor

  • torch.Tensor(array)
  • torch.tensor(array)
  • torch.as_tensor(array)
  • torch.from_array(array)
import torch
import numpy as np

array = np.array([1,2,3,4])
print(array.dtype)      #int64

# 用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(tensor.dtype)     #torch.int64
print(Tensor.dtype)     #torch.float32
print(as_tensor.dtype)  #torch.int64
print(from_array.dtype) #torch.int64

# ========== 判断是否共享内存 ===========

#修改数组的值
array[0] = 10

print(tensor)       #tensor([1, 2, 3, 4])
print(Tensor)       #tensor([1., 2., 3., 4.])
print(as_tensor)    #tensor([10,  2,  3,  4])
print(from_array)   #tensor([10,  2,  3,  4])

结论:
1)torch.Tensor() 和 torch.tensor() 在转换的时候,是开辟了新的内存空间来存储tensor的。

  • torch.Tensor 在生成tensor的时候,默认生成 float数据类型
  • torch.tensor 是根据的情况来推断长生什么样的数据类型。

2)torch.as_tensor() 和 torch.from_array() 转换的tensor,和 numpy array 是共享内存的;所以数据肯定也是一致的。


3、tensor 转换为 array

import numpy as np
import torch

a = torch.tensor([1, 2, 3])
b = np.array(a)

print(a)  # tensor([1, 2, 3])
print(b)  # [1 2 3]
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Enzo 想砸电脑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值