簡體   English   中英

為什么我的 Keras model 加載后會進行訓練,即使我實際上沒有提供任何新的訓練數據?

[英]Why does my Keras model train after I load it, even though I have not actually supplied any new training data?

我正在嘗試使用 tf.keras 使用 LSTM model 進行訓練和預測。 I have written code in two different files, LSTMTraining.py which trains the Keras Model (and save it to a file), and Predict.py, which is supposed to load in the Keras model and use it to make predictions. 出於某種原因,當我在 Predict.py 中加載 model 時,它開始訓練,即使我沒有在該文件中使用 model.fit() 命令。 為什么會這樣?

我已將 model 保存為多種不同的文件格式。 例如,我嘗試將模型的架構保存到 JSON 文件中(使用 model_to_json()),並分別保存權重,然后分別加載這兩個文件,然后將它們組合起來。 我還嘗試將它們一起保存到一個文件中(使用 model.save()),然后將其加載。

在 LSTMTraining.py 中創建和訓練 Model(注意:log_similarity_loss 只是我為模型創建的自定義損失 function):

# Machine learning
import tensorflow as tf
from tensorflow.python.keras import layers
import numpy as np

# Load/save data
import pickle
import os

# Shuffling
from sklearn.utils import shuffle

# Parameters
epochs = 5
display_step = 1000
n_input = 5
wordvec_len = 5
n_hidden = 512
recurrent_dropout = 0
dropout = 0

# Load data
with open("Vectorized_Word_By_Word.txt", "rb") as data:
    vectorized_txt = pickle.load(data)

# Prepare data into format for training (x: [prev-words], y: [next-word])
x_train, y_train = [], []
for n in range(0, len(vectorized_txt) - n_input - 1):
    prev_words = vectorized_txt[n: n+5]
    next_word = vectorized_txt[n+6]
    x_train.append(prev_words)
    y_train.append(next_word)
x_train, y_train = np.array(x_train), np.array(y_train)
x_train, y_train = shuffle(x_train, y_train, random_state=0)


def log_similarity_loss(y_actual, y_pred):
    """Log similarity loss calculation."""
    cos_similarity = tf.keras.losses.CosineSimilarity(axis=0)(y_actual, y_pred)
    scaled_similarity = tf.add(tf.multiply(0.5, cos_similarity), 0.5)
    return -0.5*tf.math.log(scaled_similarity)


log_similarity_loss(
    [0.05, 0.01, 0.05, 1.2], [0.05, -0.01, 0.05, -1.2])

model = tf.keras.Sequential([
    layers.LSTM(n_hidden, input_shape=(n_input, wordvec_len),
                dropout=dropout, recurrent_dropout=recurrent_dropout,
                return_sequences=True),
    layers.LSTM(n_hidden, dropout=dropout,
                recurrent_dropout=recurrent_dropout),
    layers.Dense(wordvec_len)
])

model.compile(loss=log_similarity_loss,
              optimizer='adam', metrics=['cosine_proximity'])

model.fit(x_train, y_train, epochs=epochs, batch_size=12)

model.save("Keras_Model.h5", include_optimizer=True, save_format='h5')

# Save model weights and architecture
model.save_weights('model_weights.h5')
with open("model_architecture.json", "w") as json_file:
    json_file.write(model.to_json())

在 Predict.py 中加載 model (注意:從“WordModel.py”導入的所有函數都只是我編寫的與 Keras 無關的文本處理函數):

from WordModel import word_by_word, word_to_vec, vec_to_word
import gensim

import tensorflow as tf
from tensorflow.python.keras.models import load_model, model_from_json

with open('model_architecture.json', 'r') as json_file:
    model_json = json_file.read()

keras_model = model_from_json(model_json)
keras_model.load_weights("model_weights.h5")

我期待沒有 output,只加載 model。 但是,我得到了 model 的詳細訓練 output 像這樣(運行 Predict.py 時):

  12/1212 [..............................] - ETA: 3:32 - loss: 0.2656 - cosine_proximity: 0.0420
  24/1212 [..............................] - ETA: 1:55 - loss: 0.2712 - cosine_proximity: 0.2066
  36/1212 [..............................] - ETA: 1:24 - loss: 0.2703 - cosine_proximity: 0.2294
  48/1212 [>.............................] - ETA: 1:08 - loss: 0.2394 - cosine_proximity: 0.2690
  60/1212 [>.............................] - ETA: 58s - loss: 0.2286 - cosine_proximity: 0.2874 
  72/1212 [>.............................] - ETA: 52s - loss: 0.2247 - cosine_proximity: 0.2750
  84/1212 [=>............................] - ETA: 47s - loss: 0.2115 - cosine_proximity: 0.2924 

等等。

請注意,我沒有在我的 Predict.py 文件中創建任何訓練命令。 我已經多次重新運行代碼,並確保我運行的是正確的文件。 不過,似乎沒有任何效果。

謝謝您的幫助!

問題可能出在您的 VSCode IDE 上,它需要額外的配置才能與 Python 及其軟件包一起使用——當您運行一個腳本時,您可能正在運行所有腳本,因此會出現這種行為。 我推薦的一個解決方案是切換到Spyder並使用Anaconda安裝您的軟件包。 兩者都安裝好后,在 PC 上搜索“anaconda command prompt”或“anaconda powershell”,然后在終端中輸入:

conda update conda
conda update --all
conda install numpy # optional (sort of)
conda install matplotlib # optional (sort of)
# SEE BELOW
conda install -c conda-forge keras
conda update --all # final 'cleanup' command - ensures package compatibility

如果您打算使用 GPU(強烈推薦),您需要先下載 CUDA - 此處的說明(獲取 CUDA 10 而不是文章中的 9)。 然后按照文章中的方式運行conda install tensorflow-gpu

然后,在 Spyder 中: Tools -> Preferences -> PYTHONPATH manager -> 添加您計划使用的模塊/數據的所有文件夾,這樣您就不必每次都%cd或擔心相對路徑,可以直接導入。 最后,確保 Anaconda 和 Spyder 使用正確的Python 解釋器

重新啟動 Spyder,運行腳本 - 假設沒有錯誤,一切都應該很好。

暫無
暫無

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

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