亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

在不使用 get_shape、size 和 shape 函數的情況下提取張量的第一維?

在不使用 get_shape、size 和 shape 函數的情況下提取張量的第一維?

收到一只叮咚 2021-06-04 13:50:08
我用 Keras 寫了一個損失函數。它有兩個參數,y_true和y_pred。我的第一行代碼是:batch = y_pred.get_shape()[0]. 然后在我的batch變量中我有第一個維度y_pred,所以我循環range(batch)并寫下我寫的內容。那沒關系。問題是當我編譯所有內容時,我收到一條錯誤消息,告訴我批處理不是整數,而是張量。然后,作為 Tensorflow 的初學者,我開始思考如何從 中獲取一個整數batch,它應該是一個整數,但是一個張量。我試圖這樣做,sess.run(batch)但這根本沒有幫助。所以,我的問題是如何從表示整數變量的張量中獲取整數。我想使用一些真正給我一個整數而不是張量的函數。請幫忙。這是我的代碼:def custom_loss(y_true, y_pred):    batch = y_pred.get_shape()[0]    list_ones = returnListOnes(batch)    tensor_ones = tf.convert_to_tensor(list_ones)    loss = 0    for i in range(batch):      for j in range(S):        for k in range(S):            lista = returnListOnesIndex(batch, [j,k,0])            lista_bx = returnListOnesIndex(batch, [j,k,1])            lista_by = returnListOnesIndex(batch, [j,k,2])            lista_bw = returnListOnesIndex(batch, [j,k,3])            lista_bh = returnListOnesIndex(batch, [j,k,4])            lista_to_tensor = tf.convert_to_tensor(lista)            lista_bx_to_tensor = tf.convert_to_tensor(lista_bx)            lista_by_to_tensor = tf.convert_to_tensor(lista_by)            lista_bw_to_tensor = tf.convert_to_tensor(lista_bw)            lista_bh_to_tensor = tf.convert_to_tensor(lista_bh)            element = tf.reduce_sum(tf.multiply(lista_to_tensor,y_pred))            element_true = tf.reduce_sum(tf.multiply(lista_to_tensor, y_true))            element_bx = tf.reduce_sum(tf.multiply(lista_bx_to_tensor, y_pred))            element_bx_true = tf.reduce_sum(tf.multiply(lista_bx_to_tensor, y_true))            element_by = tf.reduce_sum(tf.multiply(lista_by_to_tensor, y_pred))            element_by_true = tf.reduce_sum(tf.multiply(lista_by_to_tensor, y_true))            element_bw = tf.reduce_sum(tf.multiply(lista_bw_to_tensor, y_pred))            element_bw_true = tf.reduce_sum(tf.multiply(lista_bw_to_tensor, y_true))正如你所看到的,我想要batch變量是int這樣我可以循環并做一些事情。我也用過size,shape它也行不通。
查看完整描述

1 回答

?
米琪卡哇伊

TA貢獻1998條經驗 獲得超6個贊

矢量化代碼肯定會更高效,我強烈建議您嘗試以不需要循環的方式編寫代碼。

但是,如果您無法這樣做,則可以求助于tf.map_fn.

從您的代碼中,我看不出在i您的循環中使用了什么地方。我猜這是一個錯誤(可能batch應該i在循環內)或我自己的失明 - 否則你可以將結果乘以批量大小......


查看完整回答
反對 回復 2021-06-09
  • 1 回答
  • 0 關注
  • 205 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號