如何使用经过训练的 Tensorflow 模型预测值

新手上路,请多包涵

我已经在 Tensorflow 中训练了我的神经网络并像这样保存了模型:

 def neural_net(x):
   layer_1 = tf.layers.dense(inputs=x, units=195, activation=tf.nn.sigmoid)
   out_layer = tf.layers.dense(inputs=layer_1, units=6)
   return out_layer

train_x = pd.read_csv("data_x.csv", sep=" ")
train_y = pd.read_csv("data_y.csv", sep=" ")
train_x = train_x / 6 - 0.5

train_size = 0.9
train_cnt = int(floor(train_x.shape[0] * train_size))
x_train = train_x.iloc[0:train_cnt].values
y_train = train_y.iloc[0:train_cnt].values
x_test = train_x.iloc[train_cnt:].values
y_test = train_y.iloc[train_cnt:].values

x = tf.placeholder("float", [None, 386])
y = tf.placeholder("float", [None, 6])

nn_output = neural_net(x)

cost = tf.reduce_mean(tf.losses.mean_squared_error(labels=y, predictions=nn_output))
optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)

training_epochs = 5000
display_step = 1000
batch_size = 30

keep_prob = tf.placeholder("float")

saver = tf.train.Saver()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for epoch in range(training_epochs):
        total_batch = int(len(x_train) / batch_size)
        x_batches = np.array_split(x_train, total_batch)
        y_batches = np.array_split(y_train, total_batch)
        for i in range(total_batch):
            batch_x, batch_y = x_batches[i], y_batches[i]
            _, c = sess.run([optimizer, cost],
                            feed_dict={
                                x: batch_x,
                                y: batch_y,
                                keep_prob: 0.8
                            })
    saver.save(sess, 'trained_model', global_step=1000)

现在我想在不同的文件中使用经过训练的模型。当然有很多很多恢复和保存模型的例子,我经历了很多。我仍然无法使它们中的任何一个工作,总会有某种错误。这是我的恢复文件,你能帮我恢复保存的模型吗?

 saver = tf.train.import_meta_graph('trained_model-1000.meta')
y_pred = []
with tf.Session() as sess:
    saver.restore(sess, tf.train.latest_checkpoint('./'))
    sess.run([y_pred], feed_dict={x: input_values})

例如,这次尝试给了我错误“会话图是空的。在调用 run() 之前向图中添加操作。”那么我应该向图中添加什么操作以及如何添加?我不知道在我的模型中该操作应该是什么…我不理解 Tensorflow 中保存/恢复的整个概念。或者我应该完全不同地进行恢复吗?提前致谢!

原文由 T.Poe 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 458
1 个回答

如果我错了请原谅我 tf.train.Saver() 只保存变量值而不是图表本身。这意味着如果你想在不同的文件中加载模型,你需要重建图形或以某种方式加载图形。 Tensorflow 文档指出:

tf.train.Saver 对象不仅将变量保存到检查点文件,它还恢复变量。请注意,当您从文件中恢复变量时,您不必事先初始化它们。

考虑以下示例:

保存模型的一个文件:

 # Create some variables.
v1 = tf.get_variable("v1", shape=[3], initializer = tf.zeros_initializer)
v2 = tf.get_variable("v2", shape=[5], initializer = tf.zeros_initializer)

inc_v1 = v1.assign(v1+1)
dec_v2 = v2.assign(v2-1)

# Add an op to initialize the variables.
init_op = tf.global_variables_initializer()

# Add ops to save and restore all the variables.
saver = tf.train.Saver()

# Later, launch the model, initialize the variables, do some work, and save the
# variables to disk.
with tf.Session() as sess:
    sess.run(init_op)
    # Do some work with the model.
    inc_v1.op.run()
    dec_v2.op.run()
    # Save the variables to disk.
    save_path = saver.save(sess, "/tmp/model.ckpt")
    print("Model saved in file: %s" % save_path)

加载先前保存的模型的另一个文件:

 tf.reset_default_graph()

# Create some variables.
v1 = tf.get_variable("v1", shape=[3])
v2 = tf.get_variable("v2", shape=[5])

# Add ops to save and restore all the variables.
saver = tf.train.Saver()

# Later, launch the model, use the saver to restore variables from disk, and
# do some work with the model.
with tf.Session() as sess:
   # Restore variables from disk.
   saver.restore(sess, "/tmp/model.ckpt")
   print("Model restored.")
   # Check the values of the variables
   print("v1 : %s" % v1.eval())
   print("v2 : %s" % v2.eval())

原文由 Lasse Jacobs 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题