Jul-08-2018, 02:11 PM
Hey,
I need to build an 'exe' for a python script. Actually, I don't really care what it is, as long as I can distribute it on other Windows PCs. I tryed pyinstaller and a few others but didn't manage to get them to work. Right now, I'm trying cx_freeze.
My app: It's build using Anaconda, so all the deps are installed in an Anaconda environment, including the cx_freeze or pyinstaller or whatever.
ooda.py
My question is: How do I make an exe or something from this code?
I need to build an 'exe' for a python script. Actually, I don't really care what it is, as long as I can distribute it on other Windows PCs. I tryed pyinstaller and a few others but didn't manage to get them to work. Right now, I'm trying cx_freeze.
My app: It's build using Anaconda, so all the deps are installed in an Anaconda environment, including the cx_freeze or pyinstaller or whatever.
ooda.py
""" Neural Network with Eager API. A 2-Hidden Layers Fully Connected Neural Network (a.k.a Multilayer Perceptron) implementation with TensorFlow's Eager API. This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/). This example is using TensorFlow layers, see 'neural_network_raw' example for a raw implementation with variables. Links: [MNIST Dataset](http://yann.lecun.com/exdb/mnist/). Author: Aymeric Damien Project: https://github.com/aymericdamien/TensorFlow-Examples/ """ from __future__ import print_function import tensorflow as tf import tensorflow.contrib.eager as tfe from datetime import datetime from traits.api import HasTraits, CInt, CFloat from traitsui.api import View, Item, Handler, Action import matplotlib.pyplot as plt import os print('1') input() # Set Eager API tfe.enable_eager_execution() print('2') input() # Import MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=False) # Parameters learning_rate = 0.001 num_steps = 5 batch_size = 128 display_step = 10 # OODA tries eps = 0.002 lower_bound = 0.005 upper_bound = 100 ooda_step = 5 epochs = 50 # Network Parameters n_hidden_1 = 256 # 1st layer number of neurons n_hidden_2 = 256 # 2nd layer number of neurons num_input = 784 # MNIST data input (img shape: 28*28) num_classes = 10 # MNIST total classes (0-9 digits) # Using TF Dataset to split data into batches dataset = tf.data.Dataset.from_tensor_slices( (mnist.train.images, mnist.train.labels)).batch(batch_size) dataset_iter = tfe.Iterator(dataset) # Define the neural network. To use eager API and tf.layers API together, # we must instantiate a tfe.Network class as follow: class NeuralNet(tfe.Network): # SGD Optimizer optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) # Compute gradients #grad = 0# = tfe.implicit_gradients(NeuralNet.loss_fn) def __init__(self): # Define each layer super(NeuralNet, self).__init__() # Hidden fully connected layer with 256 neurons self.layer1 = self.track_layer( tf.layers.Dense(n_hidden_1, activation=tf.nn.relu)) # Hidden fully connected layer with 256 neurons self.layer2 = self.track_layer( tf.layers.Dense(n_hidden_2, activation=tf.nn.relu)) # Output fully connected layer with a neuron for each class self.out_layer = self.track_layer(tf.layers.Dense(num_classes)) NeuralNet.grad = tfe.implicit_gradients(NeuralNet.loss_fn) def call(self, x): x = self.layer1(x) x = self.layer2(x) return self.out_layer(x) # Cross-Entropy loss function @staticmethod def loss_fn(inference_fn, inputs, labels): # Using sparse_softmax cross entropy return tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits( logits=inference_fn(inputs), labels=labels)) # Calculate accuracy @staticmethod def accuracy_fn(inference_fn, inputs, labels): prediction = tf.nn.softmax(inference_fn(inputs)) correct_pred = tf.equal(tf.argmax(prediction, 1), labels) return tf.reduce_mean(tf.cast(correct_pred, tf.float32)) @staticmethod def trainNN(): testId = 0 #files if os.path.exists('tests.txt'): #get id from file file = open('tests.txt', 'r') lines = file.read().splitlines() if lines != []: testId = int(lines[-1].split()[0]) + 1 file.close() logs = open('logs.txt', 'a+') graphslog = open('graphs.txt', 'a+') testslog = open('tests.txt', 'a+') # Training lossevol = [] accevol = [] dataset_iter = tfe.Iterator(dataset) neural_net = NeuralNet() average_loss = 0. average_acc = 0. start = datetime.now() for epoch in range(epochs): for step in range(num_steps): # Iterate through the dataset try: d = dataset_iter.next() except StopIteration: # Refill queue dataset_iter = tfe.Iterator(dataset) d = dataset_iter.next() # Images x_batch = d[0] # Labels y_batch = tf.cast(d[1], dtype=tf.int64) # Compute the batch loss batch_loss = NeuralNet.loss_fn(neural_net, x_batch, y_batch) average_loss += batch_loss # Compute the batch accuracy batch_accuracy = NeuralNet.accuracy_fn(neural_net, x_batch, y_batch) average_acc += batch_accuracy if step == 0: # Display the initial cost, before optimizing print("Initial loss= {:.9f}".format(average_loss)) logs.write("Initial loss= {:.9f}\n".format(average_loss)) # Update the variables following gradients info if epoch < ooda_step or (batch_loss > lower_bound and batch_loss < upper_bound and epoch > ooda_step): NeuralNet.optimizer.apply_gradients(NeuralNet.grad(neural_net, x_batch, y_batch)) # Display info if (step + 1) % display_step == 0 or step == 0: if step > 0: average_loss /= display_step average_acc /= display_step lossevol.append(average_loss) accevol.append(batch_accuracy) print("Epoch:", '%02d' % (epoch + 1), "Step:", '%04d' % (step + 1), " loss=", "{:.9f}".format(average_loss), " accuracy=", "{:.4f}".format(average_acc)) logs.write('Epoch: %02d ' % (epoch + 1) + 'Step: %04d ' % (step + 1) + 'loss={:.9f} '.format(average_loss) + 'accuracy={:.4f}\n'.format(average_acc)) average_loss = 0. average_acc = 0. end = datetime.now() print("Training took: ", (end - start), logs) trainingTime = end-start # Evaluate model on the test image set testX = mnist.test.images testY = mnist.test.labels test_acc = NeuralNet.accuracy_fn(neural_net, testX, testY) print("Testset Accuracy: {:.4f}".format(test_acc)) # 9694 9753 9763 9783 9762 logs.write("Testset Accuracy: {:.4f}\n".format(test_acc)) aux = range(len(lossevol)) plt.figure() plt.xlabel("Display steps") plt.ylabel("Loss") plt.plot(aux, lossevol, color = "red") plt.show() plt.figure() plt.xlabel("Display steps") plt.ylabel("Batch Accuaracy") plt.plot(aux, accevol , color = "blue") plt.show() logs.write("-----------------------------------------\n") print("%d " % testId + "{:.4f} ".format(test_acc) + "\n") graphslog.write("%d " % testId + "{:.4f} ".format(test_acc) + str(trainingTime) + "\n") testslog.write("%d " % testId + "Epochs: %d " % epochs + "Steps number: %d " % num_steps + "Batch size: %d " % batch_size + "OODA step: %d " % ooda_step + "Lower bound: %f " % lower_bound + "Upper bound: %f " % upper_bound + "Display step: %d\n" % display_step) logs.close() graphslog.close() testslog.close() #GUI Configuration class NNHandler(Handler): def setattr(self, info, object, name, value): Handler.setattr(self, info, object, name, value) info.object._updated = True def object__updated_changed(self, info): if info.initialized: info.ui.title += "*" #info.ui.camera.epochs = 500 def test(self, info): global epochs global num_steps global batch_size global ooda_step global lower_bound global upper_bound global display_step epochs = info.epochs.value num_steps = info.num_steps.value batch_size = info.batch_size.value ooda_step = info.ooda_step.value lower_bound = info.lower_bound.value upper_bound = info.upper_bound.value display_step = info.display_step.value NeuralNet.trainNN() def graphs(self, info): if os.path.exists('graphs.txt') == False: return file = open('graphs.txt', 'r') tests = file.read().splitlines() test_num = range(len(tests)) test_acc = [] test_time = [] for line in tests: words = line.split() test_acc.append(float(words[1])) test_time.append((datetime.strptime(words[2], '%H:%M:%S.%f') - datetime.strptime('1900 1 1', '%Y %m %d')).total_seconds()) print(test_num) print(test_acc) print(test_time) plt.figure() plt.xlabel("Test ID") plt.ylabel("Time") plt.scatter(test_num, test_time, color = "red") plt.show() plt.figure() plt.xlabel("Test ID") plt.ylabel("Accuaracy") plt.scatter(test_num, test_acc , color = "blue") plt.show() class Camera(HasTraits): epochs = CInt(50, label = "Epochs") num_steps = CInt(5, label = "Number of steps") batch_size = CInt(128, label = "Batch size") ooda_step = CInt(2, label = "OODA step") lower_bound = CFloat(0.005, label = "Lower bound") upper_bound = CFloat(100, label = "Upper bound") display_step = CInt(10, label = "Display step") train = Action(name = "Run NN", action = "test") generateGraph = Action(name = "Generate graphs", action = "graphs") view = View( Item('epochs'), Item('num_steps'), Item('batch_size'), Item('ooda_step'), Item('lower_bound'), Item('upper_bound'), Item('display_step'), # Item('figure', editor=MPLFigureEditor(), # show_label=False), handler = NNHandler(), buttons = [train, generateGraph] ) cam = Camera() #cam.configure_traits() if __name__ == "__main__": print("wtf") cam.configure_traits() input()I've added those inputs and prints with hopes I get something, but nothing. cx_freeze builds it with no errors (As far as I managed to see), but the .exe does nothing. I tried opening it from the console, it prints nothing, instantly closes and so on.
My question is: How do I make an exe or something from this code?