MCPcopy Create free account
hub / github.com/PaddlePaddle/Paddle / as_numpy

Function as_numpy

python/paddle/base/executor.py:148–191  ·  view source on GitHub ↗

Convert a Tensor to a numpy.ndarray, its only support Tensor without LoD information. For higher dimensional sequence data, please use DenseTensor directly. Examples: .. code-block:: pycon >>> import paddle.base as base >>> import numpy >>>

(tensor, copy=False)

Source from the content-addressed store, hash-verified

146
147
148def as_numpy(tensor, copy=False):
149 """
150 Convert a Tensor to a numpy.ndarray, its only support Tensor without LoD information.
151 For higher dimensional sequence data, please use DenseTensor directly.
152
153 Examples:
154 .. code-block:: pycon
155
156 >>> import paddle.base as base
157 >>> import numpy
158
159 >>> new_scope = base.Scope()
160 >>> with base.scope_guard(new_scope):
161 ... base.global_scope().var("data").get_tensor().set(numpy.ones((2, 2)), base.CPUPlace())
162 >>> tensor = new_scope.find_var("data").get_tensor()
163 >>> base.executor.as_numpy(tensor) # or numpy.array(new_scope.find_var("data").get_tensor())
164
165 Args:
166 tensor(Variable): a instance of Tensor
167 copy(bool, optional): Whether to use deep copy.
168
169 Returns:
170 numpy.ndarray
171 """
172 if isinstance(tensor, core.DenseTensorArray):
173 return [as_numpy(t, copy) for t in tensor]
174 if isinstance(tensor, list):
175 return [as_numpy(t, copy) for t in tensor]
176 assert isinstance(tensor, core.DenseTensor)
177 lod = tensor.lod()
178 if len(lod) > 0:
179 raise RuntimeError(
180 "Some of your fetched tensors hold LoD information. \
181 They can not be completely cast to Python ndarray. \
182 Please set the parameter 'return_numpy' as 'False' to \
183 return DenseTensor itself directly."
184 )
185 if tensor._is_initialized():
186 if copy:
187 return np.array(tensor)
188 else:
189 return np.asarray(tensor)
190 else:
191 return None
192
193
194def dtype_is_compatible_with(first, second):

Callers 4

_fetch_varFunction · 0.85
runMethod · 0.85
_run_from_datasetMethod · 0.85
_run_pipelineMethod · 0.85

Calls 2

RuntimeErrorClass · 0.85
lodMethod · 0.45

Tested by

no test coverage detected