1 回答

TA貢獻1811條經驗 獲得超4個贊
最簡單的方法是在循環內定義模型。這是一個例子。您會看到每次迭代,準確性都會隨機開始,然后才會提高。
import tensorflow as tf
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train.astype("float32") / 255
x_test = x_test.astype("float32") / 255
for i in range(5):
? ? model = tf.keras.Sequential([
? ? ? ? ? ? tf.keras.Input(shape=(28, 28)),
? ? ? ? ? ? tf.keras.layers.Flatten(),
? ? ? ? ? ? tf.keras.layers.Dense(32, activation='relu'),
? ? ? ? ? ? tf.keras.layers.Dense(64, activation='relu'),
? ? ? ? ? ? tf.keras.layers.Dense(10, activation="softmax"),
? ? ? ? ])
? ? model.compile(loss="sparse_categorical_crossentropy", optimizer="adam",
? ? ? ? ? ? ? ? ? metrics=["accuracy"])
? ? model.fit(x_train, y_train, batch_size=16, epochs=1, validation_split=0.1)
手動重置權重稍微復雜一些。
添加回答
舉報