简体   繁体   English

块状(n,1,m)至(n,m)

[英]Numpy (n, 1, m) to (n,m)

I am working on a problem which involves a batch of 19 tokens each with 400 features. 我正在研究一个涉及19个令牌的批次,每个令牌具有400个功能。 I get the shape (19,1,400) when concatenating two vectors of size (1, 200) into the final feature vector. 将两个大小为(1,200)的向量连接到最终特征向量时,得到的形状为(19,1,400)。 If I squeeze the 1 out I am left with (19,) but I am trying to get (19,400). 如果我将1挤出,则剩下(19,),但我尝试获得(19,400)。 I have tried converting to list, squeezing and raveling but nothing has worked. 我尝试过转换为列表,压缩和整理,但没有任何效果。

Is there a way to convert this array to the correct shape? 有没有办法将此数组转换为正确的形状?

def attn_output_concat(sample):
  out_h, state_h = get_output_and_state_history(agent.model, sample)
  attns = get_attentions(state_h)
  inner_outputs = get_inner_outputs(state_h)
  if len(attns) != len(inner_outputs):
    print 'Length err'
  else:
    tokens = [np.zeros((400))] * largest
    print(tokens.shape)
    for j, (attns_token, inner_token) in enumerate(zip(attns, inner_outputs)):
      tokens[j] = np.concatenate([attns_token, inner_token], axis=1)
    print(np.array(tokens).shape)
    return tokens

The easiest way would be to declare tokens to be a numpy.shape=(19,400) array to start with. 最简单的方法是将标记声明为以numpy.shape =(19,400)开头的数组。 That's also more memory/time efficient. 这样还可以提高内存/时间效率。 Here's the relevant portion of your code revised... 这是修改后的代码的相关部分...

import numpy as np
attns_token = np.zeros(shape=(1,200))
inner_token = np.zeros(shape=(1,200))
largest = 19
tokens = np.zeros(shape=(largest,400))
for j in range(largest):
    tokens[j] = np.concatenate([attns_token, inner_token], axis=1)
print(tokens.shape)

BTW... It makes it difficult for people to help you if you don't include a self-contained and runnable segment of code (which is probably why you haven't gotten a response on this yet). 顺便说一句...如果您不包含独立且可运行的代码段,这将使人们难以为您提供帮助(这可能就是为什么您尚未对此做出回应的原因)。 Something like the above snippet is preferred and will help you get better answers because there's less guessing at what your trying to accomplish. 最好使用上面的代码片段,它可以帮助您获得更好的答案,因为您对要完成的目标的猜测较少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM