You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

logistic_regression.py 3.7 kB

6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. '''
  2. A logistic regression learning algorithm example using TensorFlow library.
  3. This example is using the MNIST database of handwritten digits
  4. (http://yann.lecun.com/exdb/mnist/)
  5. Author: Aymeric Damien
  6. Project: https://github.com/aymericdamien/TensorFlow-Examples/
  7. '''
  8. from __future__ import print_function
  9. import tensorflow as tf
  10. # Import MNIST data
  11. from tensorflow.examples.tutorials.mnist import input_data
  12. mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
  13. # Parameters
  14. learning_rate = 0.01
  15. training_epochs = 10
  16. batch_size = 100
  17. display_step = 1
  18. # tf Graph Input
  19. x = tf.placeholder(tf.float32, [None, 784]) # mnist data image of shape 28*28=784
  20. y = tf.placeholder(tf.float32, [None, 10]) # 0-9 digits recognition => 10 classes
  21. # Set model weights
  22. W = tf.Variable(tf.zeros([784, 10]))
  23. b = tf.Variable(tf.zeros([10]))
  24. # Construct model
  25. pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax
  26. # Minimize error using cross entropy
  27. cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
  28. # Gradient Descent
  29. optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
  30. # Initialize the variables (i.e. assign their default value)
  31. init = tf.global_variables_initializer()
  32. # Start training
  33. with tf.Session() as sess:
  34. # Run the initializer
  35. sess.run(init)
  36. # Training cycle
  37. for epoch in range(training_epochs):
  38. avg_cost = 0.
  39. total_batch = int(mnist.train.num_examples/batch_size)
  40. # Loop over all batches
  41. for i in range(total_batch):
  42. batch_xs, batch_ys = mnist.train.next_batch(batch_size)
  43. # Run optimization op (backprop) and cost op (to get loss value)
  44. _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,
  45. y: batch_ys})
  46. # Compute average loss
  47. avg_cost += c / total_batch
  48. # Display logs per epoch step
  49. if (epoch+1) % display_step == 0:
  50. print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
  51. print("Optimization Finished!")
  52. # Test model
  53. correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
  54. # Calculate accuracy
  55. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  56. print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
  57. # predict
  58. # results = sess.run(pred, feed_dict={x: batch_xs[:1]})
  59. # save model
  60. saver = tf.train.Saver()
  61. save_path = saver.save(sess, "logistic_regression/model.ckpt")
  62. tf.train.write_graph(sess.graph.as_graph_def(),'logistic_regression','model.pbtxt', as_text=True)
  63. freeze_graph.freeze_graph(input_graph = 'logistic_regression/model.pbtxt',
  64. input_saver = "",
  65. input_binary = False,
  66. input_checkpoint = 'logistic_regression/model.ckpt',
  67. output_node_names = "Softmax",
  68. restore_op_name = "save/restore_all",
  69. filename_tensor_name = "save/Const:0",
  70. output_graph = 'logistic_regression/model.pb',
  71. clear_devices = True,
  72. initializer_nodes = "")
  73. # restoring the model
  74. saver = tf.train.import_meta_graph('logistic_regression/tensorflowModel.ckpt.meta')
  75. saver.restore(sess,tf.train.latest_checkpoint('logistic_regression'))
  76. # predict
  77. # pred = graph._nodes_by_name["Softmax"]
  78. # output = pred.outputs[0]
  79. # x = graph._nodes_by_name["Placeholder"]
  80. # input = x.outputs[0]
  81. # results = sess.run(output, feed_dict={input: batch_xs[:1]})

tensorflow框架的.NET版本,提供了丰富的特性和API,可以借此很方便地在.NET平台下搭建深度学习训练与推理流程。