[英]Wrapping array operation into a function
我的網絡的輸入X
的形狀為(10, 1, 5, 4)
。 我有興趣為每個 class 繪制輸入特征(四個)的分布。 因此,例如:
X = np.random.randn(10, 1, 5, 4)
a = np.zeros(5, dtype=int)
b = np.ones(5, dtype=int)
y = np.hstack((a,b))
print(X.shape)
print(y.shape)
(10, 1, 5, 4)
(10,)
然后我將輸入X
分成各自的類,例如:
class0, class1 =[],[]
for i in range(len(y)):
if y[i]==0:
class0.append(X[i])
else:
class1.append(X[i])
class0 = np.array(class0)
class1 = np.array(class1)
考慮到 class0,我可以提前class0
以這種方式將四個特征按每列( col1, col2,col3,col4
)排列的方式對其進行操作。
def transformer(myclass):
#reshape the class
k = myclass.transpose((0,1,3,2))
#access individual feature
s = k[0][:,0].reshape(-1,1)
a = k[0][:,1].reshape(-1,1)
j = k[0][:, 2].reshape(-1,1)
b = k[0][:, 3].reshape(-1,1)
rslt = [s,a,j,b]
return rslt
那么plot的特點:
sns.boxplot(data=transformer(class0))
這是我工作流程的總體思路。 請注意,function transformer
是硬編碼的,以僅訪問它作為輸入的 class 的第一個觀測值(元素)。
問題:如何修改我的 function 以訪問 class 的所有觀察結果,而不是每個示例,以進行概括。 這樣col1
是 class 中的所有特征,在每個示例的第一列中。
請寫以下內容:
def mytransformer(myclass):
#first, transpose class
k = myclass.transpose((0,1,3,2))
#speed
for i in range(k):
s = k[i][:,0].reshape(-1,1)
return s
這給出了錯誤:
mytransformer(class0)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-15-5451e55f03d9> in <module>()
----> 1 mytransformer(class0)
<ipython-input-14-d1a2c8098caf> in mytransformer(myclass)
3 myclass = myclass.transpose((0,1,3,2))
4 #speed
----> 5 for i in range(myclass):
6 s = k[i][:,0].reshape(-1,1)
7 return s
TypeError: only integer scalar arrays can be converted to a scalar index
對於您的問題 1,您正在使用帶有 NumPy 數組的 for 循環范圍,而該數組應具有 integer 的參數。
也許是,
for i in range(len(k)):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.