簡體   English   中英

tf.gradients() 返回 [None] 的列表

[英]tf.gradients() returns a list of [None]

對不起,如果這聽起來像重復。 我已經解決了所有相關問題,但沒有找到適合我的問題背景的解決方案。

我正在嘗試構建一個生成的 model,它輸出 COVID 的每個跟蹤日的概率,以輸入基於 SEIR 的流行病學 model。

一代工作。 但是,我不知道如何訓練 model。 我必須編寫一個自定義損失 function,它通過一個步驟 function 運行每日參數,用於流行病學 model 的每個“已刪除”數據集和“將填充” 然后,我將該數據與John Hopkin 在 GitHub 上的 COVID 數據集中記錄的“確認”和“刪除”數據進行比較。

我使用平均絕對誤差根據生成的概率和 JHU 數據集中的實際值來計算“確認”和“刪除”之間的損失。 我遇到的問題是,當我調用the tf.gradient() function 時,它返回None的列表。 我被困在這里,任何幫助將不勝感激。

這是我正在使用的代碼:

訓練步驟

# Define function to train the model based on one input
loss_fn = MeanAbsoluteError()
optimizer = Adam(learning_rate=0.005)

@tf.function
def train_step(x, y):

  y_pred = np.zeros((3, latent_dim))

  N = tf.constant(int(7_000_000_000), dtype=tf.float64)
  E0 = tf.Variable(int(1000), trainable=False, dtype=tf.float64)
  I0 = tf.Variable(covid_df.iloc[0]["Confirmed"], trainable=False, dtype=tf.float64)
  R0 = tf.Variable(covid_df.iloc[0]["Removed"], trainable=False, dtype=tf.float64)
  S0 = tf.Variable(N - E0 - I0 - R0, trainable=False, dtype=tf.float64)
  u0 = tf.Variable(0, trainable=False, dtype=tf.float64)

  SuEIRs = tf.stack([S0,u0,E0,I0,R0])

  with tf.GradientTape() as tape:
    logits = generator(tf.reshape(x, (batch_size, 4, latent_dim)), training=True)

    betas = logits[0][0]
    sigmas = logits[0][1]
    mus = logits[0][2]
    gammas = logits[0][3]

    for t in range(latent_dim):
      SuEIR_diffs = SuEIR_step(SuEIRs, t, N, betas, sigmas, mus, gammas)

      SuEIRs = SuEIRs + SuEIR_diffs

      confirmed = SuEIRs[3]
      removed = SuEIRs[4]

      # update y_pred
      y_pred[0,t] = float(t+1)
      y_pred[1,t] = confirmed.numpy()
      y_pred[2,t] = removed.numpy()

    # Convert predictions
    y_pred = tf.convert_to_tensor(y_pred)

    # Calculate loss
    loss_value = loss_fn(y[1], y_pred[1]) + loss_fn(y[2], y_pred[2])

  # Calculate the gradient
  grads = tape.gradient(loss_value, generator.trainable_weights)

  print(grads) ##==>> outputs [None, None, None, None]

  # Apply gradients to model
  optimizer.apply_gradients(zip(grads, generator.trainable_weights))
  return loss_value

訓練循環

import time

epochs = 2
for epoch in range(epochs):
  print("\nStart of epoch %d" % (epoch,))
  start_time = time.time()

  # Iterate over the batches of the dataset.
  for step in range(sample_size):
    loss_value = train_step(x_input[step], y_true)

    # Log every 5 batches.
    if step % 5 == 0:
      print(
        "Training loss (for one batch) at step %d: %.4f"
        % (step, float(loss_value))
      )
    print("Time taken: %.2fs" % (time.time() - start_time))

錯誤 output

ValueError: No gradients provided for any variable: ['dense/kernel:0', 'dense/bias:0', 'dense_1/kernel:0', 'dense_1/bias:0'].

loss_valuegenerator.trainable_weights按預期填充。

編輯:更新代碼以反映Myrl Marmarelis的建議和TensorFlow 的自定義訓練循環指南的架構。 仍然有相同的梯度問題是None的列表。

在計算np.array(...)的損失(特別是在y_pred上)之前,嘗試將您的調用更改為tf.convert_to_tensor(...) 您需要通過將所有內容保存為tf.Tensor來構建適當的符號圖。 事實上,確保在 model 參數和損失之間的計算鏈中的任何地方都沒有將任何東西轉換為非張量。

我還建議將您的訓練過程包裝在@tf.function中,以便 Tensorflow 可以將其編譯成 static 圖表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM