# 什么是Pytorch - Pytorch入门笔记2

Mr::Z::
9个月前 阅读 39 点赞 0

## NumPy桥

Torch Tensor 和 NumPy 数组将共享其基础内存位置（如果Torch Tensor在CPU上），并且更改一个将更改另一个。

### 将 Tensor 张量转换为NumPy数组

a = torch.ones(5)
print(a)


tensor([1., 1., 1., 1., 1.])


b = a.numpy()
print(b)


[1. 1. 1. 1. 1.]


a.add_(1)
print(a)
print(b)


tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]


### 将NumPy数组转换为Torch张量

import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
print(a)
print(b)


[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)


## CUDA张量

# let us run this cell only if CUDA is available
# We will use torch.device objects to move tensors in and out of GPU
if torch.cuda.is_available():
device = torch.device("cuda")          # a CUDA device object
y = torch.ones_like(x, device=device)  # directly create a tensor on GPU
x = x.to(device)                       # or just use strings .to("cuda")
z = x + y
print(z)
print(z.to("cpu", torch.double))       # .to can also change dtype together!


tensor([-1.0408], device='cuda:0')
tensor([-1.0408], dtype=torch.float64)