Advertisement
Guest User

Untitled

a guest
Nov 20th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.70 KB | None | 0 0
  1. # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. #     http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15.  
  16. # Norbert Batfai, 27 Nov 2016
  17. # Some modifications and additions to the original code:
  18. # https://github.com/tensorflow/tensorflow/blob/r0.11/tensorflow/examples/tutorials/mnist/mnist_softmax.py
  19. # See also http://progpater.blog.hu/2016/11/13/hello_samu_a_tensorflow-bol
  20. # ==============================================================================
  21.  
  22. """A very simple MNIST classifier.
  23.  
  24. See extensive documentation at
  25. http://tensorflow.org/tutorials/mnist/beginners/index.md
  26. """
  27. from __future__ import absolute_import
  28. from __future__ import division
  29. from __future__ import print_function
  30.  
  31. import argparse
  32.  
  33. import numpy
  34.  
  35. # Import data
  36. from tensorflow.examples.tutorials.mnist import input_data
  37.  
  38. import tensorflow as tf
  39.  
  40. import matplotlib.pyplot as plt
  41. import matplotlib as mpl
  42.  
  43. FLAGS = None
  44.  
  45.  
  46. def readimg():
  47.     file = tf.read_file("harom.png")
  48.     img = tf.image.decode_png(file)
  49.     return img
  50.  
  51.  
  52. def main(_):
  53.     model_path = "/tmp/model.ckpt"
  54.  
  55.     mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
  56.  
  57.     # Create the model
  58.     x = tf.placeholder(tf.float32, [None, 784])
  59.     #W = tf.Variable(tf.zeros([784, 10]))
  60.     W = tf.Variable(numpy.random.normal(0, 0.001, size=(784,10)),dtype=tf.float32)
  61.     b = tf.Variable(tf.zeros([10]))
  62.     y = tf.matmul(x, W) + b
  63.  
  64.     # Define loss and optimizer
  65.     y_ = tf.placeholder(tf.float32, [None, 10])
  66.  
  67.     # The raw formulation of cross-entropy,
  68.     #
  69.     #   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),
  70.     #                                 reduction_indices=[1]))
  71.     #
  72.     # can be numerically unstable.
  73.     #
  74.     # So here we use tf.nn.softmax_cross_entropy_with_logits on the raw
  75.     # outputs of 'y', and then average across the batch.
  76.     cross_entropy = tf.reduce_mean(
  77.         tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_))
  78.     train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
  79.  
  80.     # 'Saver' op to save and restore all the variables
  81.     saver = tf.train.Saver()
  82.  
  83.     sess = tf.InteractiveSession()
  84.     # Train
  85.     sess.run(tf.global_variables_initializer())
  86.     # tf.initialize_all_variables().run()
  87.     # tf.global_variables_initializer().run
  88.     print("-- A halozat tanitasa")
  89.     for i in range(1000+1):
  90.         if i in range(0,9):
  91.             img = W[:,0]
  92.             image = img.eval()
  93.           #  plt.text(1, 1, "Iteracio: {}".format(i))
  94.           #  plt.imshow(image.reshape(28, 28), cmap="hot")
  95.           #  plt.savefig("w0.png")
  96.           #  plt.title(i)
  97.           #  plt.show()
  98.         j=0
  99.         if i % 2 == 0 :
  100.             print(i / 10, "%")
  101.             img = W[:,0]
  102.             image = img.eval()
  103.             plt.text(1, 1, "Iteracio: {}".format(i))
  104.         plt.imshow(image.reshape(28, 28), cmap = mpl.colors.ListedColormap(['red', 'black', 'blue']))
  105.             #plt.imshow(image.reshape(28, 28), cmap="seismic_r")
  106.             plt.savefig('w' + str(j) + '.png')
  107.             plt.title(i)
  108.             plt.show()
  109.             j+=1
  110.  
  111.         batch_xs, batch_ys = mnist.train.next_batch(4)
  112.         sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
  113.  
  114.     print("-"*20)
  115.  
  116.     # Test trained model
  117.     print("-- A halozat tesztelese")
  118.     #saver.restore(sess, model_path)
  119.     correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
  120.     accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  121.     print("-- Pontossag: ", sess.run(accuracy, feed_dict={x: mnist.test.images,
  122.                                                           y_: mnist.test.labels}))
  123.  
  124.     print("-"*20)
  125.     j=0
  126.     writer = tf.summary.FileWriter("/tmp/mnist_softmax_UDPROG61", sess.graph)
  127.     img = W[:,0]
  128.     image = img.eval()
  129.     print("-- W_0[14,14] =", image[14*28+14])
  130.     print("-- Egy vedesi reszfeladat az elso heten: a W_0 sulyok abrazolasa, mutatom, a tovabblepeshez csukd be az ablakat")
  131.     #plt.imshow(image.reshape(28, 28))#, cmap=plt.cm.binary)
  132.     plt.imshow(image.reshape(28, 28), cmap = mpl.colors.ListedColormap(['red', 'black', 'blue']))
  133.     #plt.imshow(image.reshape(28, 28), cmap="seismic_r")
  134.     plt.savefig('w' + str(j) + '.png')
  135.     j+=1
  136.     #plt.show()
  137.     print("----------------------------------------------------------")
  138.  
  139.  
  140.     print("-- A MNIST 42. tesztkepenek felismerese, mutatom a szamot, a tovabblepeshez csukd be az ablakat")
  141.  
  142.     img = mnist.test.images[42]
  143.     image = img
  144.     plt.imshow(image.reshape(
  145.         28, 28), cmap=plt.cm.binary)
  146.     plt.savefig("4.png")
  147.     plt.show()
  148.  
  149.     classification = sess.run(tf.argmax(y, 1), feed_dict={x: [image]})
  150.  
  151.     print("-- Ezt a halozat ennek ismeri fel: ", classification[0])
  152.     print("----------------------------------------------------------")
  153.  
  154.     print("-- A sajat kezi 7-esem felismerese, mutatom a szamot, a tovabblepeshez csukd be az ablakat")
  155.  
  156.     img = mnist.test.images[41]
  157.     image = img
  158.     image = image.reshape(28 * 28)
  159.  
  160.     plt.imshow(image.reshape(
  161.         28, 28), cmap=plt.cm.binary)
  162.     plt.savefig("7.png")
  163.     plt.show()
  164.  
  165.     classification = sess.run(tf.argmax(y, 1), feed_dict={x: [image]})
  166.  
  167.     print("-- Ezt a halozat ennek ismeri fel: ", classification[0])
  168.     print("----------------------------------------------------------")
  169.  
  170.  
  171.     print("-- A sajat kezi 3-asom felismerese, mutatom a szamot, a tovabblepeshez csukd be az ablakat")
  172.  
  173.     img = readimg()
  174.     image = img.eval().flatten()
  175.     for i, img in enumerate(image):
  176.     image[i] =abs(image[i]-255)
  177.  
  178.  
  179.     plt.imshow(image.reshape(28, 28), cmap=plt.cm.binary)
  180.     plt.savefig("3.png")
  181.     plt.show()
  182.  
  183.     classification = sess.run(tf.argmax(y, 1), feed_dict={x: [image]})
  184.  
  185.     print("-- Ezt a halozat ennek ismeri fel: ", classification[0])
  186.     print("----------------------------------------------------------")
  187.  
  188.  
  189.  
  190. if __name__ == '__main__':
  191.     parser = argparse.ArgumentParser()
  192.     parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',
  193.                         help='Directory for storing input data')
  194.     FLAGS = parser.parse_args()
  195.     tf.app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement