【发布时间】:2021-01-06 04:00:35
【问题描述】:
我尝试在线搜索文档,但找不到任何可以给我答案的内容。 .numpy() 函数有什么作用?给出的示例代码是:
y_true = []
for X_batch, y_batch in mnist_test:
y_true.append(y_batch.numpy()[0].tolist())
【问题讨论】:
标签: numpy tensorflow pytorch
我尝试在线搜索文档,但找不到任何可以给我答案的内容。 .numpy() 函数有什么作用?给出的示例代码是:
y_true = []
for X_batch, y_batch in mnist_test:
y_true.append(y_batch.numpy()[0].tolist())
【问题讨论】:
标签: numpy tensorflow pytorch
在 Pytorch 和 Tensorflow 中,.numpy() 方法都非常简单。它将tensor 对象转换为numpy.ndarray 对象。这隐含地意味着转换后的张量现在将在 CPU 上进行处理。
【讨论】:
This implicitly means that the converted tensor will be now processed on the CPU. 这是支持此声明的relevant docstring
在理解某些 PyTorch 功能时遇到问题,您可以询问 help()。
import torch
t = torch.tensor([1,2,3])
help(t.numpy)
输出:
Help on built-in function numpy:
numpy(...) method of torch.Tensor instance
numpy() -> numpy.ndarray
Returns :attr:`self` tensor as a NumPy :class:`ndarray`. This tensor and the
returned :class:`ndarray` share the same underlying storage. Changes to
:attr:`self` tensor will be reflected in the :class:`ndarray` and vice versa.
这个numpy()函数是从torch.Tensor到numpy数组的转换器。
【讨论】:
如果我们查看下面的这段代码,我们会看到一个简单的示例,其中 .numpy() 自动将张量转换为 numpy 数组。
import numpy as np
ndarray = np.ones([3, 3])
print("TensorFlow operations convert numpy arrays to Tensors automatically")
tensor = tf.multiply(ndarray, 42)
print(tensor)
print("And NumPy operations convert Tensors to numpy arrays automatically")
print(np.add(tensor, 1))
print("The .numpy() method explicitly converts a Tensor to a numpy array")
print(tensor.numpy())
在最后第二行代码中,我们看到 tensorflow 官方声明它是 Tensor 到 numpy 数组的转换器。 您可以查看here
【讨论】: