Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support numpy.array/asarray(tensor) -> ndarray, test=develop #32300

Merged
merged 1 commit into from
Apr 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion python/paddle/fluid/dygraph/varbase_patch_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,9 @@ def __nonzero__(self):
def __bool__(self):
return self.__nonzero__()

def __array__(self, dtype=None):
return self.numpy().astype(dtype)

for method_name, method in (
("__bool__", __bool__), ("__nonzero__", __nonzero__),
("_to_static_var", _to_static_var), ("set_value", set_value),
Expand All @@ -442,7 +445,7 @@ def __bool__(self):
("gradient", gradient), ("register_hook", register_hook),
("__str__", __str__), ("__repr__", __str__),
("__deepcopy__", __deepcopy__), ("__module__", "paddle"),
("__name__", "Tensor")):
("__name__", "Tensor"), ("__array__", __array__)):
setattr(core.VarBase, method_name, method)

# NOTE(zhiqiu): pybind11 will set a default __str__ method of enum class.
Expand Down
9 changes: 9 additions & 0 deletions python/paddle/fluid/tests/unittests/test_var_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,15 @@ def test_var_base_to_np(self):
np.array_equal(var.numpy(),
fluid.framework._var_base_to_np(var)))

def test_var_base_as_np(self):
with fluid.dygraph.guard():
var = fluid.dygraph.to_variable(self.array)
self.assertTrue(np.array_equal(var.numpy(), np.array(var)))
self.assertTrue(
np.array_equal(
var.numpy(), np.array(
var, dtype=np.float32)))

def test_if(self):
with fluid.dygraph.guard():
var1 = fluid.dygraph.to_variable(np.array([[[0]]]))
Expand Down