将数组操作包装为函数

问题描述 投票:1回答:1

我的网络输入X的形状为(10, 1, 5, 4)。我对每个类的输入特征(四个)的分布进行箱线图绘制感兴趣。因此,例如:

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,我可以按这样的方式进行操纵,即以这种方式在每列(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

然后绘制特征:

sns.boxplot(data=transformer(class0))

enter image description here

这是我工作流程的总体思路。请注意,函数transformer被硬编码为仅访问其作为输入的类的第一个观察值(元素)。

问题:概括地说,如何修改函数以访问该类的所有观察结果,而不是每个示例。这样col1是该类中每个示例的第一列中的所有功能。

写以下内容:

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. 是否可以将图例添加到箱线图中,以便为每个功能命名?
python arrays numpy multidimensional-array numpy-ndarray
1个回答
0
投票

对于您的问题1,您正在使用带有NumPy数组的for循环范围,该数组应将参数作为整数。

也许是,

for i in range(len(k)):
© www.soinside.com 2019 - 2024. All rights reserved.