【问题标题】:Wrapping array operation into a function将数组操作包装到函数中
【发布时间】:2020-06-01 08:44:35
【问题描述】:

我网络的输入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
  1. 有没有办法向箱线图添加图例,以便为每个特征命名?

【问题讨论】:

    标签: python arrays numpy multidimensional-array numpy-ndarray


    【解决方案1】:

    对于您的问题 1,您正在使用带有 NumPy 数组的 for 循环范围,而该数组应具有整数形式的参数。

    也许是,

    for i in range(len(k)):
    

    【讨论】:

      猜你喜欢
      • 2014-11-09
      • 1970-01-01
      • 2014-07-15
      • 2021-11-11
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 2016-04-29
      • 1970-01-01
      相关资源
      最近更新 更多