【问题标题】:Unable to broadcast numpy array, but .shape says they have the same shape无法广播 numpy 数组,但 .shape 表示它们具有相同的形状
【发布时间】:2018-08-08 20:30:53
【问题描述】:

这是我的函数的第一部分,它希望从经过训练的 LSTM 和暗 50 的词嵌入生成文本。当我尝试将 X 的第 i 行设置为等于嵌入向量 y_embed 时,问题就出现了。然而,这个问题只出现在 for 循环的第三次迭代中。这对我来说很奇怪,因为我希望 X 的每一行都具有相同的形状。

def generate_text(my_model, length):
    ix = np.random.randint(VOCAB_SIZE) #start generating by some 
         random index
    y_word = [reverse_dictionary[ix]] #get the word with that index
    y_embed = w2vec[ix] #get the embedding vector
    print(y_embed.shape)

    X = np.zeros((1, length, EMBED_DIM)) #make our numpy array
    print(X[0,2].shape)
    for i in range(length): #however many words we want
        print("i is "+str(i))
        X[0, i] = y_embed #current row of X is current word embedding
        y_embed = my_model.predict(X[:, :i+1, :])[0] 
        #input what we've generated so far, model.predict gives us a list, take the first one
        #we'll add it to our input on the next loop iteration

        y_word.append(vec2w(y_embed)) #lookup the word by its embedding

for 循环在其前两次迭代中工作,然后在 i=2 时抛出此错误:

 X[0, i] = y_embed #current row of X is current word embedding  
 ValueError: could not broadcast input array from shape (2,50) into shape (50)

这就是为什么我让它预先打印 y_embed 和 X[0,2] 的形状,然后控制台打印:

(50,)

(50,)

据我所知,它们确实具有相同的形状。我对 numpy 还是很陌生,所以也许这很明显,但我无法弄清楚这一点。我应该补充一点,我正在使用 Keras,而 model.predict 需要一个 3D 张量,这就是 X 以它的方式定义的原因。我也尝试设置 X[0,i,:] = y_embed 但同时产生了相同的错误。

【问题讨论】:

    标签: python arrays numpy shape broadcast


    【解决方案1】:
    X = np.zeros((1, length, EMBED_DIM))
    

    X 是 3d。

    X[0, i]
    

    选择前 2 个目录,所以是 (EMBED_DIM,),根据错误是 (50,)。

    错误认为y_embed 是 (2,50),2 列 50。显然它是由上次迭代创建的。

    my_model.predict(X[:, :i+1, :])[0] 
    

    对于i==1,它给出了predict X[:,:2,:],一个(2,50) 数组。我不知道predict 做了什么,但我认为输出与输入的形状相同并不是巧合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      相关资源
      最近更新 更多