机器学习 - PyTorch tensor 和 numpy

因为numpy是一个python numerical computing library, PyTorch 可以 interact with it nicely.

The two main methods you will want to use for NumPy to PyTorch (and back again) are:

  • torch.from_numpy(ndarray) - NumPy array -> PyTorch tensor
  • torch.Tensor.numpy() - PyTorch tensor -> NumPy array
import numpy as np

array = np.arange(1.0, 8.0)
tensor = torch.from_numpy(array)
print(array)
print(tensor)

# 输出结果
[1. 2. 3. 4. 5. 6. 7.]
tensor([1., 2., 3., 4., 5., 6., 7.], dtype=torch.float64)


这里稍微介绍一下:
By default, NumPy arrays are created with the datatype float64 and if you convert it to a PyTorch tensor, it’ll keep the same datatype.

However, many PyTorch calculations default to using float32.

So if you want to convert your numpy array (float64) -> PyTorch tensor (float64) -> PyTorch tensor (float32), you can use tensor = torch.from_numpy(array).type(torch.float32)


下面是代码来展示,让tensor和numpy做两者之间的互相转换

import numpy as np

# Array to Tensor 
array = np.arange(1.0, 8.0)
tensor = torch.from_numpy(array)
print(f"array: {array}")
print(f"tensor 1: {tensor}")

array = array + 1
print(f"array: {array}")
tensor = tensor + 1
print(f"tensor 2: {tensor}")

# Tensor to Numpy array
tensor = torch.ones(7)
print(f"tensor 3: {tensor}")
numpy_tensor = tensor.numpy()
print(f"numpy_tensor: {numpy_tensor} | numpy_tensor datatype: {numpy_tensor.dtype}")

# Change the tensor, keep the array the same 
tensor = tensor + 1
print(f"tensor: {tensor}") 
print(f"numpy_tensor: {numpy_tensor}")

# 结果如下
array: [1. 2. 3. 4. 5. 6. 7.]
tensor 1: tensor([1., 2., 3., 4., 5., 6., 7.], dtype=torch.float64)
array: [2. 3. 4. 5. 6. 7. 8.]
tensor 2: tensor([2., 3., 4., 5., 6., 7., 8.], dtype=torch.float64)
tensor 3: tensor([1., 1., 1., 1., 1., 1., 1.])
numpy_tensor: [1. 1. 1. 1. 1. 1. 1.] | numpy_tensor datatype: float32

看到这了,点个赞支持一下咯~

  • 15
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值