保存和恢复模型
一旦你训练了你的模型,你应该把它的参数保存到磁盘,所以你可以随时随地回到它,在另一个程序中使用它,与其他模型比较,等等。 此外,您可能希望在训练期间定期保存检查点,以便如果您的计算机在训练过程中崩溃,您可以从上次检查点继续进行,而不是从头开始。
TensorFlow 可以轻松保存和恢复模型。 只需在构造阶段结束(创建所有变量节点之后)创建一个保存节点; 那么在执行阶段,只要你想保存模型,只要调用它的save()方法:
[...]theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0), name="theta")[...]init = tf.global_variables_initializer()saver = tf.train.Saver()with tf.Session() as sess:sess.run(init)for epoch in range(n_epochs):if epoch % 100 == 0: # checkpoint every 100 epochssave_path = saver.save(sess, "/tmp/my_model.ckpt")sess.run(training_op)best_theta = theta.eval()save_path = saver.save(sess, "/tmp/my_model_final.ckpt")
恢复模型同样容易:在构建阶段结束时创建一个保存器,就像之前一样,但是在执行阶段的开始,而不是使用init节点初始化变量,你可以调用restore()方法 的保存器对象:
with tf.Session() as sess:saver.restore(sess, "/tmp/my_model_final.ckpt")[...]
默认情况下,保存器将以自己的名称保存并还原所有变量,但如果需要更多控制,则可以指定要保存或还原的变量以及要使用的名称。 例如,以下保存器将仅保存或恢复theta变量,它的键名称是weights:
saver = tf.train.Saver({"weights": theta})
完整代码
numpy as npfrom sklearn.datasets import fetch_california_housingimport tensorflow as tffrom sklearn.preprocessing import StandardScalerhousing = fetch_california_housing()m, n = housing.data.shapeprint("数据集:{}行,{}列".format(m,n))housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]scaler = StandardScaler()scaled_housing_data = scaler.fit_transform(housing.data)scaled_housing_data_plus_bias = np.c_[np.ones((m, 1)), scaled_housing_data]n_epochs = 1000 # not shown in the booklearning_rate = 0.01 # not shownX = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name="X") # not showny = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y") # not showntheta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta")y_pred = tf.matmul(X, theta, name="predictions") # not shownerror = y_pred - y # not shownmse = tf.reduce_mean(tf.square(error), name="mse") # not shownoptimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) # not showntraining_op = optimizer.minimize(mse) # not showninit = tf.global_variables_initializer()saver = tf.train.Saver()with tf.Session() as sess:sess.run(init)for epoch in range(n_epochs):if epoch % 100 == 0:print("Epoch", epoch, "MSE =", mse.eval()) # not shownsave_path = saver.save(sess, "/tmp/my_model.ckpt")sess.run(training_op)best_theta = theta.eval()save_path = saver.save(sess, "/tmp/my_model_final.ckpt") # 找到tmp文件夹就找到文件了
使用 TensorBoard 展现图形和训练曲线
所以现在我们有一个使用小批量梯度下降训练线性回归模型的计算图谱,我们正在定期保存检查点。 听起来很复杂,不是吗? 然而,我们仍然依靠print()函数可视化训练过程中的进度。 有一个更好的方法:进入 TensorBoard。如果您提供一些训练统计信息,它将在您的网络浏览器中显示这些统计信息的良好交互式可视化(例如学习曲线)。 您还可以提供图形的定义,它将为您提供一个很好的界面来浏览它。 这对于识别图中的错误,找到瓶颈等是非常有用的。
第一步是调整程序,以便将图形定义和一些训练统计信息(例如,training_error(MSE))写入 TensorBoard 将读取的日志目录。 您每次运行程序时都需要使用不同的日志目录,否则 TensorBoard 将会合并来自不同运行的统计信息,这将会混乱可视化。 最简单的解决方案是在日志目录名称中包含时间戳。 在程序开头添加以下代码:
from datetime import datetimenow = datetime.utcnow().strftime("%Y%m%d%H%M%S")root_logdir = "tf_logs"logdir = "{}/run-{}/".format(root_logdir, now)
接下来,在构建阶段结束时添加以下代码:
mse_summary = tf.summary.scalar('MSE', mse)file_writer = tf.summary.FileWriter(logdir, tf.get_default_graph())
第一行创建一个节点,这个节点将求出 MSE 值并将其写入 TensorBoard 兼容的二进制日志字符串(称为摘要)中。 第二行创建一个FileWriter,您将用它来将摘要写入日志目录中的日志文件中。 第一个参数指示日志目录的路径(在本例中为tf_logs/run-20160906091959/,相对于当前目录)。 第二个(可选)参数是您想要可视化的图形。 创建时,文件写入器创建日志目录(如果需要),并将其定义在二进制日志文件(称为事件文件)中。
接下来,您需要更新执行阶段,以便在训练期间定期求出mse_summary节点(例如,每 10 个小批量)。 这将输出一个摘要,然后可以使用file_writer写入事件文件。 以下是更新的代码:
[...]for batch_index in range(n_batches):X_batch, y_batch = fetch_batch(epoch, batch_index, batch_size)if batch_index % 10 == 0:summary_str = mse_summary.eval(feed_dict={X: X_batch, y: y_batch})step = epoch * n_batches + batch_indexfile_writer.add_summary(summary_str, step)sess.run(training_op, feed_dict={X: X_batch, y: y_batch})[...]
避免在每一个训练阶段记录训练数据,因为这会大大减慢训练速度(以上代码每 10 个小批量记录一次).
最后,要在程序结束时关闭FileWriter:
file_writer.close()
完整代码
import numpy as npfrom sklearn.datasets import fetch_california_housingimport tensorflow as tffrom sklearn.preprocessing import StandardScalerhousing = fetch_california_housing()m, n = housing.data.shapeprint("数据集:{}行,{}列".format(m,n))housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]scaler = StandardScaler()scaled_housing_data = scaler.fit_transform(housing.data)scaled_housing_data_plus_bias = np.c_[np.ones((m, 1)), scaled_housing_data]from datetime import datetimenow = datetime.utcnow().strftime("%Y%m%d%H%M%S")root_logdir = r"D://tf_logs"logdir = "{}/run-{}/".format(root_logdir, now)n_epochs = 1000learning_rate = 0.01X = tf.placeholder(tf.float32, shape=(None, n + 1), name="X")y = tf.placeholder(tf.float32, shape=(None, 1), name="y")theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta")y_pred = tf.matmul(X, theta, name="predictions")error = y_pred - ymse = tf.reduce_mean(tf.square(error), name="mse")optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)training_op = optimizer.minimize(mse)init = tf.global_variables_initializer()mse_summary = tf.summary.scalar('MSE', mse)file_writer = tf.summary.FileWriter(logdir, tf.get_default_graph())n_epochs = 10batch_size = 100n_batches = int(np.ceil(m / batch_size))def fetch_batch(epoch, batch_index, batch_size):np.random.seed(epoch * n_batches + batch_index) # not shown in the bookindices = np.random.randint(m, size=batch_size) # not shownX_batch = scaled_housing_data_plus_bias[indices] # not showny_batch = housing.target.reshape(-1, 1)[indices] # not shownreturn X_batch, y_batchwith tf.Session() as sess: # not shown in the booksess.run(init) # not shownfor epoch in range(n_epochs): # not shownfor batch_index in range(n_batches):X_batch, y_batch = fetch_batch(epoch, batch_index, batch_size)if batch_index % 10 == 0:summary_str = mse_summary.eval(feed_dict={X: X_batch, y: y_batch})step = epoch * n_batches + batch_indexfile_writer.add_summary(summary_str, step)sess.run(training_op, feed_dict={X: X_batch, y: y_batch})best_theta = theta.eval()file_writer.close()print(best_theta)

