我創建了一個名為Tensor
import numpy as np
class Tensor:
def __init__(self, data):
self.data = np.array(data)
我想使用以下方法設定 numpy 陣列的元素Tensor:
x = np.array([[1,2,3,4],[4,3,2,1]])
x[:,::2] = Tensor([[0,0],[1,1]])
但它會導致錯誤ValueError: setting an array element with a sequence.
一種解決方法是檢索張量的資料屬性:x[:,::2] = Tensor([[0,0],[1,1]]).data,但我想知道如何在不手動檢索任何內容的情況下執行此操作,例如當您可以使用串列或 numpy 陣列設定值時:x[:,::2] = [[0,0],[1,1]]或x[:,::2] = np.array([[0,0],[1,1]])
uj5u.com熱心網友回復:
Numpy 陣列物件都遵循一個協議,只要實作__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]])
參考:撰寫自定義陣列容器
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484220.html
上一篇:如何檢索numpy保存的物件
下一篇:轉置和比較
