0

i have this code to train a restore a model in tensorflow . but how can I make predictions.

def train_neural_network(x):
    prediction=neural_network_model(x)
    cost=tf.nn.softmax_cross_entropy_with_logits_v2(logits = prediction, labels = y)
    optimizer=tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)

    saver = tf.train.Saver()

    with tf.Session() as sess:
        #sess.run(tf.initialize_all_variables())
        sess.run(tf.global_variables_initializer())
        for epoch in range(hm_epochs):
            epoch_loss = 0
            i = 0
            #while i < len(train_x):
            t = len(train_x)
            f = t%batch_size
            while i < (t-f):
                start = i
                end = i+batch_size
                batch_x = np.array(train_x[start:end])
                batch_y = np.array(train_y[start:end])


                _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})
                epoch_loss += c
                #epoch_loss = epoch_loss + c
                i+=batch_size
                #i = i + batch_size
            print('Epoch =', epoch+1, '/',hm_epochs,'loss:',epoch_loss)

        save_path = saver.save(sess, "sesionestensorflow/model1.ckpt")
        print("Model saved in path: %s" % save_path)


        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))

        print('Accuracy:',accuracy.eval({x:test_x, y:test_y}))

i see this answer but i can`t make the prediction. Using saved model for prediction in tensorflow

RenzoG
  • 31
  • 5

1 Answers1

0

You just have to create an empy graph, define the network, load the saved weights and thus run inference.

prediction = tf.argmax(neural_network_model(x), 1)
saver = tf.train.Saver()
with tf.Session() as sess:
    # load the trained weights into the model
    saver.restore(sess, "sesionestensorflow/model1.ckpt")
    # just use the model
    out = sess.run(prediction, feed_dict={x: <your input> })
nessuno
  • 26,493
  • 5
  • 83
  • 74
  • ok, the result is this, but i expect a zero array with one number 1 . feed dict = [[ 0.6737 0.6737 0.6737 41.606056 16.11666667]] out [[ 62.6507 -2025.7719 136.06538 -2349.9055 -4071.8032 -1727.9988 78.84228 -305.2752 -1380.6096 299.88174 1483.1726 1353.7816 2282.4849 1986.554 2496.1821 ]] – RenzoG Jun 12 '18 at 20:32
  • Because prediction is the output of your model. You're looking for the class with the higher probability. I update the answer – nessuno Jun 13 '18 at 07:58