如何重新初始化张量流变量?

How to reinitialize tensorflow variables?

在 tensorflow 1 中,我曾经使用 运行 tf.global_variables_initializer() 来(重新)初始化图中的所有变量。我已经离开 tensorflow 一段时间了,我没有看到可以重新初始化变量的方法。我正在 运行 宁 sequential tutorial 并且我希望能够多次调用 model.fit 而无需热启动它目前正在做的先前进展

tf.kerasAPI中,您可以get/set模型对象的权重值,方法是使用get_weights()set_weights()方法。

请看下面这个可能比较简单的例子:

import numpy as np
import tensorflow as tf

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(1, input_shape=(3,)))
model.compile(loss="mse", optimizer="sgd")
initial_weight_values = model.get_weights()  # <-- Remember the initial weight values.

num_examples = 100
xs = np.ones([num_examples, 3])
ys = np.zeros([num_examples, 1])
model.fit(xs, ys, epochs=10)

model.set_weights(initial_weight_values)  # <-- Restore the weight values to the initial ones.
model.fit(xs, ys, epochs=10)  # <-- The new fit() call should start from a high loss value like the one in the previous fit() call.

警告:此方法每次都会将权重值重新初始化为完全相同的值。如果你每次都想要不同的值,你可以使用 numpy.random 之类的东西来生成与 initial_weight_values.

具有相同数据类型和形状的值