|
| 1 | +--- |
| 2 | +Title: 'Specifying Data Types' |
| 3 | +Description: 'Determines how tensors are stored and processed, impacting precision, memory usage, and computation speed.' |
| 4 | +Subjects: |
| 5 | + - 'Data Science' |
| 6 | + - 'Machine Learning' |
| 7 | + - 'Deep Learning' |
| 8 | +Tags: |
| 9 | + - 'Pytorch' |
| 10 | + - 'Tensor' |
| 11 | + - 'Data Types' |
| 12 | +CatalogContent: |
| 13 | + - 'learn-Intro-to-PyTorch-and-Neural-Networks' |
| 14 | + - 'paths/data-science' |
| 15 | +--- |
| 16 | + |
| 17 | +In PyTorch, specifying the data types for [`tensors`](https://www.codecademy.com/resources/docs/pytorch/tensors) is crucial as they are the core data structures used to store and process data. Each tensor's data type (`dtype`) defines the kind of values it holds (e.g., `integer`, `float`, `boolean`), ensuring precision, improving performance, and maintaining compatibility during computations. |
| 18 | + |
| 19 | +## Syntax |
| 20 | + |
| 21 | +To specify a data type in a PyTorch tensor, use the `dtype` parameter when creating a tensor or the `.to()` method for converting an existing one. |
| 22 | + |
| 23 | +### For specifying `dtype` when creating a tensor |
| 24 | + |
| 25 | +```pseudo |
| 26 | +torch.tensor(data, dtype=torch.<data_type>) |
| 27 | +``` |
| 28 | + |
| 29 | +- `data`: The input data used to create the tensor. This can be a list, NumPy array, or another tensor. |
| 30 | +- `dtype`: Specifies the data type of the tensor. Common data types include: |
| 31 | + - `torch.float32` (default): 32-bit floating-point |
| 32 | + - `torch.float64`: 64-bit floating-point |
| 33 | + - `torch.int32`: 32-bit integer |
| 34 | + - `torch.int64`: 64-bit integer |
| 35 | + - `torch.bool`: Boolean |
| 36 | + |
| 37 | +### For converting an existing tensor to a different data type |
| 38 | + |
| 39 | +```pseudo |
| 40 | +tensor.to(torch.<data_type>) |
| 41 | +``` |
| 42 | + |
| 43 | +## Example |
| 44 | + |
| 45 | +In the example below a tensor is created with a specified data type, another with a different type, and one tensor is converted to a new data type: |
| 46 | + |
| 47 | +```py |
| 48 | +import torch |
| 49 | + |
| 50 | +# Creating a float32 tensor |
| 51 | +float_tensor = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float32) |
| 52 | +print(float_tensor) |
| 53 | + |
| 54 | +# Creating an int64 tensor |
| 55 | +int_tensor = torch.tensor([1, 2, 3], dtype=torch.int64) |
| 56 | +print(int_tensor) |
| 57 | + |
| 58 | +# Converting a tensor to a different data type |
| 59 | +converted_tensor = float_tensor.to(torch.int64) |
| 60 | +print(converted_tensor) |
| 61 | +``` |
| 62 | + |
| 63 | +The code above generates the output as: |
| 64 | + |
| 65 | +```shell |
| 66 | +tensor([1., 2., 3.]) |
| 67 | +tensor([1, 2, 3]) |
| 68 | +tensor([1, 2, 3]) |
| 69 | +``` |
0 commit comments