簡體   English   中英

將數組操作包裝成 function

[英]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. 有沒有辦法向箱線圖添加圖例,以便我可以為每個功能命名?

對於您的問題 1,您正在使用帶有 NumPy 數組的 for 循環范圍,而該數組應具有 integer 的參數。

也許是,

for i in range(len(k)):

包裝與

[英]Wrapping a Python function that uses with

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM