Python 将数组操作包装到函数中

Python 将数组操作包装到函数中,python,arrays,numpy,multidimensional-array,numpy-ndarray,Python,Arrays,Numpy,Multidimensional Array,Numpy Ndarray,输入到我的网络的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 =[],[] f

输入到我的网络的
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))

这是我的工作流程的总体思路。注意,函数
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
mytransformer(0类)
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在()
---->1个mytransformer(0级)
在mytransformer(myclass)中
3 myclass=myclass.transpose((0,1,3,2))
4#速度
---->范围内的i为5(myclass):
6 s=k[i][:,0]。重塑(-1,1)
7回s
TypeError:只能将整数标量数组转换为标量索引
  • 是否有办法将图例添加到箱线图中,以便我可以为每个功能命名

  • 对于问题1,您使用的是带有NumPy数组的For循环范围,该数组的参数应为整数

    也许是,

    for i in range(len(k)):