python - 运行时保存 TensorFlow 状态(权重)
问题描述
我有一个在模型上运行的 python 程序。我没有实现保护程序,所以我想知道是否有一种方法可以在配件运行时直接从内存中恢复权重(也许从临时文件中?)
解决方案
我认为应该可以使用命令,tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
.
在不保存模型的情况下提取/恢复模型权重的代码如下所示。
import tensorflow as tf
import numpy as np
X_ = tf.placeholder(tf.float64, [None, 5], name="Input")
Y_ = tf.placeholder(tf.float64, [None, 1], name="Output")
X = np.random.randint(1,10,[10,5])
Y = np.random.randint(0,2,[10,1])
with tf.variable_scope("LogReg"):
pred = tf.layers.dense(X_, 1, activation=tf.nn.sigmoid, name = 'fc1')
loss = tf.losses.mean_squared_error(labels=Y_, predictions=pred)
training_ops = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
with tf.Session() as sess:
all_vars= tf.global_variables()
def get_var(name):
for i in range(len(all_vars)):
if all_vars[i].name.startswith(name):
return all_vars[i]
return None
sess.run(tf.global_variables_initializer())
for i in range(200):
sess.run([training_ops], feed_dict={X_: X,Y_: Y})
Weight_Vars = sess.run([tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)], feed_dict={X_: X,Y_: Y})
print(Weight_Vars)
推荐阅读
- c# - 一段时间的统一行动
- ruby-on-rails - 如何修复共享相同 ID 的 Rails Active Storage blob
- python-3.x - 在创建具有已知不良数据的数据帧时强制执行数据类型
- python - 我不明白为什么范围函数增量参数适用于切片运算符
- .net - 我的 .Net 代码在命名管道中出现 40 错误,但 Excel 连接正常
- java - 继承中的方法调用有问题
- php - WooCommerce 在快速编辑时保存自定义产品字段
- bash - 计算机启动后 Anacrontab 未运行计划的 bash 脚本
- java - 为什么 return 不尊重 finally 块中变量的值?
- python-3.x - 如何计算分段线性斜率