torch.device()
时间: 2023-09-28 16:07:12 浏览: 45
torch.device() is a function in PyTorch that returns a device object representing the current device. It can be used to set the device for a tensor or a model, to move tensors between devices, and to check the current device used by PyTorch.
For example, the following code sets the device to GPU if available, otherwise to CPU:
```
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
```
And the following code moves a tensor to the specified device:
```
x = torch.randn(3, 3)
x = x.to(device)
```
相关问题
torch.device
torch.device is a class in PyTorch that represents the device on which tensors and neural network models are located. It can be used to specify the device on which operations should be performed, and to move tensors and models between different devices (e.g., between CPU and GPU).
For example, to create a tensor on the CPU, you can use:
```python
import torch
x = torch.tensor([1, 2, 3], device=torch.device('cpu'))
```
To move a tensor to the GPU, you can use:
```python
x = x.to(torch.device('cuda'))
```
Similarly, to create a neural network model on the GPU, you can use:
```python
import torch.nn as nn
model = nn.Linear(10, 1).to(torch.device('cuda'))
```
Note that the device argument can also be set when creating a tensor or a model, e.g. `x = torch.tensor([1, 2, 3], device='cpu')`.
Device =torch.device
= torch.device is a function in PyTorch that returns a device object representing the device on which the tensor is allocated. The device can be "cpu" or "cuda" for GPU. It is commonly used to move tensors between CPU and GPU. Here is an example of how to use it:
```
import torch
# Move tensor to GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x = torch.randn(3, 3).to(device)
# Move tensor back to CPU
x = x.to("cpu")
```