# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# + [markdown] deletable=true editable=true
# <h4>Intro to TF</h4>
# <p>Document how the input stages using tf.nn.conv2d have to match the dimensions using filters
# and strides. Google Vincent does a good job. Document this here. </p>
#
# <p></p>
# There are 2 tf APIS, the old/original tf.nn and the newer tf.layers API. Layers was built after the success
# of keras. 
# <p></p>
# An input into a TF graph consists of in input stage which specifies the input dimension of the input tensor. 
# If an image you can give it RGB or BGR(openCV compatability) order. The input specifications require 
#

# + deletable=true editable=true
# this is a little different interface than tf.layers. Is it good or bad? 
# Don't need to add the weights, those are included automatically!!

import tensorflow as tf
from tensorflow import layers
import numpy as np

def mlp(x):
    fc1 = tf.contrib.layers.fully_connected(x,256,activation_fn=tf.nn.relu)
    fc2 = tf.contrib.layers.fully_connected(fc1,256,activation_fn = tf.nn.relu)
    out = tf.contrib.layers.fully_connected(fc2,10,activation_fn=None)
    return out

x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])

pred = mlp(x)

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred,labels=y))
train_op = tf.train.AdamOptimizer(learning_rate=.01).minimize(loss)

def train(session):
    batch_size=200
    session.run(tf.initialize_all_variables())
    
    for epoch in range(10):
        epoch_loss = 0.0
        batch_steps = mnist.train.num_examples/batch_size
        for step in range(batch_steps):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            _,c = session.run([train_op,loss],{x:batch_x, y:batch_y})
            epoch_loss += c/batch_steps
        print(epoch,epoc_loss)
 





# + deletable=true editable=true


# + deletable=true editable=true


# + deletable=true editable=true
#MNIST fully connected TF not CNN

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))


# + deletable=true editable=true
#cnn mnist shows accuracy is better than multi layer perceptron or fully connected NN. 

import time
import tensorflow as tf

def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)


def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

def timing(f):
    def wrap(*args):
        time1 = time.time()
        ret = f(*args)
        time2 = time.time()
        print ('%s function took %0.3f ms' % (f.func_name, (time2-time1)*1000.0))
        return ret
    return wrap



time1 = time.time()
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1,28,28,1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])

h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])

h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y_conv ))
#LEARNING RATE SHOULD DECREASE CLOSER TO END
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#sess = tf.Session() add session=sess
sess.run(tf.global_variables_initializer())
for i in range(4000):
    batch = mnist.train.next_batch(50)
    if i%100 == 0:
        train_accuracy = accuracy.eval(session=sess,feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})
        print("step %d, training accuracy %g"%(i, train_accuracy))
    train_step.run(session=sess,feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

print("test accuracy %g"%accuracy.eval(session=sess,feed_dict={
    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

time2 = time.time()
print ('minutes:' , (time2-time1)/60)

# + [markdown] deletable=true editable=true
# <h4> Refactor to a model. This is a basic template. </h4>
# <code>
# class Model:
#     def __init__(self, params):
#         pass
#     def _create_placeholders(self):
#         """ Step 1: define the placeholders for input and output. Placeholders are initialized
#         at runtime, variables are initialized when you create them. """
#         pass
#     def _create_embedding(self):
#         """ Step 2: define weights. Weights are supposed to be reused for transfer learning and
#         for generating incremental updated models as new data arrives in realtime. Embeddings are
#         the exported weights as in word2vec and entity embeddings"""
#         pass
#     def _create_loss(self):
#          """ Step 3 + 4: define the inference + the loss function.  """
#         pass
#     def _create_optimizer(self):
#         """ Step 5: define optimization"""
#     def _train(self):
#         """Step 6: train the model"""
#     def _test(self):
#         """Step 7: test and display summaries"""
# </code>
#
#

# + deletable=true editable=true
#add global_step to training
#add save/restore 

import tensorflow as tf

tf.reset_default_graph()

class Model:
    def __init__(self, mnist):
        self.mnist = mnist
        self.learning_rate = .1
    def create_placeholders(self):
        self.x = tf.placeholder(tf.float32,shape = [None,784],name="x")
        self.y = tf.placeholder(tf.float32,shape = [None,10],name="y")
    def create_embeddings(self):
        self.W = tf.Variable(tf.zeros([784,10]),name="W")
        self.b = tf.Variable(tf.zeros([10]),name="b")
        self.output = tf.nn.softmax(tf.add(tf.matmul(self.x,self.W), self.b),name="output")
    def create_loss(self):
        self.loss = tf.reduce_mean(-tf.reduce_sum(self.y * tf.log(self.output), reduction_indices=[1]),name="loss")
    def create_optimizer(self):
        self.optimizer = tf.train.GradientDescentOptimizer(self.learning_rate,name="optimizer").minimize(self.loss)
    def train(self):
        global_step = tf.Variable(0)
        self.sess = tf.Session()
        init = tf.global_variables_initializer()
        self.sess.run(init)
        for x in range(100):
            batch_xs, batch_ys = mnist.train.next_batch(100)
            self.sess.run(self.optimizer, feed_dict={self.x: batch_xs, self.y: batch_ys})
    def test(self):
        correct_prediction = tf.equal(tf.argmax(self.output,1), tf.argmax(self.y,1),name="equal")
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32),name="accuracy")
        print(self.sess.run(accuracy, feed_dict={self.x: self.mnist.test.images, self.y: self.mnist.test.labels}))

        
mnist = input_data.read_data_sets(".", one_hot=True)
model = Model(mnist)
model.create_placeholders()
model.create_embeddings()
model.create_loss()
model.create_optimizer()
model.train()
model.test()

# + deletable=true editable=true


StarcoderdataJupyterScriptsDedupFiltered