hwberry2/TensorFlowProject
0
1import gradio as gr2import tensorflow as tf3import numpy as np4import os5import PIL6import PIL.Image7 8# Create a Gradio App using Blocks 9with gr.Blocks() as demo:10 gr.Markdown(11 """12 # AI/ML Playground13 """14 )15 with gr.Accordion("Click for Instructions:"):16 gr.Markdown(17 """18 * uploading an image will engage the model in image classsification19 * trained on the following image types: 'T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'20 * Only accepts images 28x28. Trained on images with a black background.21 """)22 23 # Train, evaluate and test a ML24 # image classification model for25 # clothes images26 27 class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',28 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']29 30 # clothing dataset31 mnist = tf.keras.datasets.fashion_mnist32 33 #split the training data in to a train/test sets34 (x_train, y_train), (x_test, y_test) = mnist.load_data()35 x_train, x_test = x_train / 255.0, x_test / 255.036 37 # create the neural net layers38 model = tf.keras.models.Sequential([39 tf.keras.layers.Flatten(input_shape=(28, 28)),40 tf.keras.layers.Dense(128, activation='relu'),41 tf.keras.layers.Dropout(0.2),42 tf.keras.layers.Dense(10)43 ])44 45 #make a post-training predition on the 46 #training set data47 predictions = model(x_train[:1]).numpy()48 49 # converts the logits into a probability50 tf.nn.softmax(predictions).numpy()51 52 #create and train the loss function53 loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)54 loss_fn(y_train[:1], predictions).numpy()55 56 # compile the model with the loss function57 model.compile(optimizer='adam',58 loss=loss_fn,59 metrics=['accuracy'])60 61 # train the model - 5 runs62 # evaluate the model on the test set63 model.fit(x_train, y_train, epochs=5, validation_split=0.3)64 test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)65 post_train_results = f"Test accuracy: {test_acc} Test Loss: {test_loss}"66 print(post_train_results)67 68 # create the final model for production69 probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])70 71 72 def classifyImage(img): 73 # Normalize the pixel values74 img = np.array(img) / 255.075 76 input_array = np.expand_dims(img, axis=0) # add an extra dimension to represent the batch size77 78 # Make a prediction using the model79 prediction = probability_model.predict(input_array)80 81 # Postprocess the prediction and return it82 predicted_label = class_names[np.argmax(prediction)]83 84 return predicted_label85 86 def do_nothing():87 pass88 89 # Creates the Gradio interface objects90 with gr.Row():91 with gr.Column(scale=2):92 image_data = gr.Image(label="Upload Image", type="numpy", image_mode="L")93 with gr.Column(scale=1):94 model_prediction = gr.Text(label="Model Prediction", interactive=False)95 image_data.upload(classifyImage, image_data, model_prediction)96 image_data.clear(do_nothing, [], model_prediction)97 98 99# creates a local web s100# if share=True creates a public101# demo on huggingface.c102demo.launch(share=False)