Issue
I have created a class called Tensor
import numpy as np
class Tensor:
def __init__(self, data):
self.data = np.array(data)
and I'd like to set elements of a numpy array using Tensor
:
x = np.array([[1,2,3,4],[4,3,2,1]])
x[:,::2] = Tensor([[0,0],[1,1]])
but it results an error ValueError: setting an array element with a sequence.
one workaround is to retrieve Tensor's data attribute: x[:,::2] = Tensor([[0,0],[1,1]]).data
, but I'd like to know how to do it without manually retrieving anything, like when you can set values with a list or numpy array: x[:,::2] = [[0,0],[1,1]]
or x[:,::2] = np.array([[0,0],[1,1]])
Solution
Numpy array objects all follow a protocol, as long as you implement __array__
method, you can use the object as an array:
>>> class Tensor:
... def __init__(self, data):
... self.data = np.array(data)
... def __array__(self, dtype=None):
... return self.data # self.data.astype(dtype, copy=False) maybe better
...
>>> x[:,::2] = Tensor([[0,0],[1,1]])
>>> x
array([[0, 2, 0, 4],
[1, 3, 1, 1]])
Reference: Writing custom array containers
Answered By - Mechanic Pig
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.