2 回答

TA貢獻1853條經(jīng)驗 獲得超18個贊
嘗試這樣做:
import tensorflow as tf
from tensorflow.keras import Sequential, backend as K
from tensorflow.keras.layers import Dense, LSTM, Dropout
from tensorflow.keras.losses import categorical_crossentropy
import numpy as np
X = tf.ones((10,10,10))
y = tf.ones((10,1))
def weight_fx(weights):
? ? weights = K.variable(weights)? ? ?
? ? def loss(y_true, y_pred):
? ? ? ? y_pred /= K.sum(y_pred, axis=-1, keepdims=True)
? ? ? ? tf.print(y_pred)
? ? ? ? loss = y_true * K.log(y_pred) * weights
? ? ? ? return loss
? ??
? ? return loss
regressor = Sequential()
regressor.add(LSTM(units = 10, dropout=0.10, return_sequences = True,?
? ? ? ? ? ? ? ? ? ?input_shape = (X.shape[1], X.shape[2])))
regressor.add(Dense(units = 4, activation='softmax'))
regressor.compile(optimizer = 'adam', loss = weight_fx(np.array([0.005,0.20,0.79,0.005])), metrics = ['categorical_accuracy'])
regressor.fit(X,y)
問:你為什么看到
Tensor("loss_13/dense_14_loss/strided_slice:0", shape=(), dtype=float32)
?答:Tensorflow 預計損失函數(shù)會被頻繁調(diào)用,因此盡可能對其進行優(yōu)化至關(guān)重要。Tensorflow 有一種方法可以做到這一點,稱為“追蹤”。這基本上意味著傳遞一個“檢測器”變量,該變量“體驗”函數(shù)中的所有操作并記住它們。然后,基于這些經(jīng)驗,Tensorflow 構(gòu)建了一個單獨的所謂“圖形”函數(shù),該函數(shù)速度更快,并且無法調(diào)用 python 中具有副作用的許多常見函數(shù)。喜歡
print()
。你看到的是一個檢測器或“示蹤劑”。它只運行一次。那我該如何調(diào)試呢?
有幾種方法可以做到這一點。如果要
print
調(diào)試,請使用tf.print
.?根據(jù)我的經(jīng)驗,這有時有效,有時無效。如果沒有,并且您仍然只看到檢測器變量,請使用model.run_eagerly = True
或?qū)⑵渥鳛閰?shù)傳遞給model.compile
.?即使你不使用tf.print
和設(shè)置run_eagerly
,python 的內(nèi)置print
仍然可以工作(試試這個)。最后但同樣重要的是,您可以將所有副作用函數(shù)包裝在一個tf.py_function
.?
另外,請確保先定義函數(shù),然后在 中使用它model.compile
,尤其是在使用 Jupyter notebook 時。一個有問題的舊聲明可能仍然存在于記憶中并且可能會毀了你的一天。
這有幫助嗎?
添加回答
舉報