torch.from_numpy
时间: 2023-11-28 13:05:22 浏览: 111
Pyorch之numpy与torch之间相互转换方式
torch.from_numpy是一个函数,用于从numpy.ndarray创建一个张量。返回的张量和numpy.ndarray共用内存,对张量的修改将反映在numpy.ndarray,反之亦然。返回的张量不可调整大小。\[1\]这个函数的语法是torch.from_numpy(ndarray)。举例如下:
```python
import torch
import numpy as np
a = np.array(\[1, 2, 3\])
t = torch.from_numpy(a)
print(t) # tensor(\[1, 2, 3\])
t\[0\] = -1
print(a) # array(\[-1, 2, 3\])
```
在这个例子中,我们首先创建了一个numpy数组a,然后使用torch.from_numpy函数将其转换为张量t。修改张量t的值会反映在原始的numpy数组a上。\[2\]
另外一个例子如下:
```python
import numpy as np
import torch
data1 = np.array(\[12, 56, 9, 6\])
print('data1的数据类型为:', type(data1))
print('data1的值为:', data1)
data2 = torch.from_numpy(data1)
print('data2的数据类型为:', type(data2))
print('data2的值为:', data2)
data2\[1\] = 3
print('data2的数据类型为:', type(data2))
print('data2的值为:', data2)
```
在这个例子中,我们首先创建了一个numpy数组data1,然后使用torch.from_numpy函数将其转换为张量data2。修改张量data2的值会反映在原始的numpy数组data1上。\[3\]
#### 引用[.reference_title]
- *1* [深入浅出Pytorch函数——torch.from_numpy](https://blog.csdn.net/hy592070616/article/details/129309583)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [torch.from_numpy(ndarray) 功能及举例](https://blog.csdn.net/zhaoyunduan1958/article/details/108603945)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [torch.from_numpy() 函数《torch学习篇》](https://blog.csdn.net/m0_56654441/article/details/120645753)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文