第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 python 中矢量化這個(numpy)操作?

如何在 python 中矢量化這個(numpy)操作?

尚方寶劍之說 2021-12-08 14:41:43
我有兩個 shape 向量,(batch, dim)我試圖將它們相減。目前,我正在使用一個簡單的循環(huán)從 1 中減去error基于第二個向量(即label)的向量(即)中的特定條目:per_ts_loss=0for i, idx in enumerate(np.argmax(label, axis=1)):    error[i, idx] -=1    per_ts_loss += error[i, idx]我怎樣才能矢量化這個?例如,錯誤和標簽可能如下所示:error :array([[ 0.5488135   0.71518937  0.60276338  0.54488318  0.4236548 ]       [ 0.64589411  0.43758721  0.891773    0.96366276  0.38344152]])label:    array([[0, 0, 0, 1, 0 ],           [0, 1, 0, 0, 0]])對于此示例,運行以下代碼會產(chǎn)生以下結果:for i, idx in enumerate(np.argmax(label,axis=1)):    error[i,idx] -=1    ls_loss += error[i,idx]結果 :error:  [[ 0.5488135   0.71518937  0.60276338  0.54488318  0.4236548 ] [ 0.64589411  0.43758721  0.891773    0.96366276  0.38344152]]label:  [[ 0.  0.  0.  1.  0.] [ 0.  1.  0.  0.  0.]]error(indexes 3 and 1 are changed): [[ 0.5488135   0.71518937  0.60276338 -0.45511682  0.4236548 ] [ 0.64589411 -0.56241279  0.891773    0.96366276  0.38344152]]per_ts_loss:  -1.01752960574這是代碼本身:https : //ideone.com/e1k8ra我被困在如何使用 的結果上np.argmax,因為結果是一個新的索引向量,它不能簡單地像這樣使用: error[:, np.argmax(label, axis=1)] -=1所以我被困在這里了!
查看完整描述

2 回答

?
慕婉清6462132

TA貢獻1804條經(jīng)驗 獲得超2個贊

代替:

error[:, np.argmax(label, axis=1)] -=1

和:

error[np.arange(error.shape[0]), np.argmax(label, axis=1)] -=1

而且當然

loss = error[np.arange(error.shape[0]), np.argmax(label, axis=1)].sum()

在您的示例中,您正在更改、求和、error[0,3]error[1,1],或簡而言之error[[0,1],[3,1]]


查看完整回答
反對 回復 2021-12-08
?
慕雪6442864

TA貢獻1812條經(jīng)驗 獲得超5個贊

也許這個:


import numpy as np



error = np.array([[0.32783139, 0.29204386, 0.0572163 , 0.96162543, 0.8343454 ],

       [0.67308787, 0.27715222, 0.11738748, 0.091061  , 0.51806117]])


label= np.array([[0, 0, 0, 1, 0 ],

           [0, 1, 0, 0, 0]])




def f(error, label):

    per_ts_loss=0

    t=np.zeros(error.shape)

    argma=np.argmax(label, axis=1)

    t[[i for i in range(error.shape[0])],argma]=-1

    print(t)

    error+=t

    per_ts_loss += error[[i for i in range(error.shape[0])],argma]



f(error, label)

輸出:


[[ 0.  0.  0. -1.  0.]

 [ 0. -1.  0.  0.  0.]]


查看完整回答
反對 回復 2021-12-08
  • 2 回答
  • 0 關注
  • 233 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號