#!/usr/bin/env python# coding: utf-8# In[1]:import numpy as npimport tensorflow as tfimport matplotlib.pyplot as pltfrom tensorflow import keras as keras# In[2]:fashion_mnist=keras.datasets.fashion_mnist(train_images, train_labels),(test_images, test_labels)=fashion_mnist.load_data()print(train_images.shape,train_labels.shape)# In[3]:class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']# In[4]:def show_single_images(image,label,class_names):plt.figure()plt.imshow(image)plt.xlabel(class_names[label])plt.colorbar()plt.grid(False)plt.show()show_single_images(train_images[0],train_labels[0],class_names)# In[5]:model=keras.models.Sequential()model.add(keras.layers.Flatten(input_shape=[28,28]))model.add(keras.layers.Dense(128,activation='relu'))model.add(keras.layers.Dense(10))# In[6]:model.compile(optimizer='adam', loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])# In[7]:model.fit(train_images,train_labels,epochs=10)# In[8]:test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)print('\n Test accuracy',test_acc)# In[9]:probability_model=keras.Sequential([model,keras.layers.Softmax()])# In[10]:predictions=probability_model.predict(test_images)# In[11]:print(predictions[0])# In[12]:print(np.argmax(predictions[0]))# In[13]:print(test_labels[0])# In[14]:def plot_image(i, predictions_array, true_label, img):predictions_array, true_label, img=predictions_array[i],true_label[i],img[i]plt.grid(False)plt.xticks([])plt.yticks([])plt.imshow(img,cmap=plt.cm.binary)
predicted_label=np.argmax(predictions_array)if(true_label==predicted_label):color='blue'else:color='red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],100*np.max(predictions_array),class_names[true_label]),color=color)# In[15]:def plot_value_array(i, predictions_array, true_label):predictions_array, true_label= predictions_array[i], true_label[i]plt.grid(False)plt.xticks(range(10))plt.yticks([])thisplot = plt.bar(range(10), predictions_array, color="#777777")plt.ylim(0,1)predicted_label=np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')thisplot[true_label].set_color('blue')# In[16]:i=0plt.figure(figsize=(6,3))plt.subplot(1,2,1)plot_image(i,predictions, test_labels,test_images)plt.subplot(1,2,2)plot_value_array(i,predictions,test_labels)plt.show()# In[17]:i=12plt.figure(figsize=(6,3))plt.subplot(1,2,1)plot_image(i,predictions, test_labels,test_images)plt.subplot(1,2,2)plot_value_array(i,predictions,test_labels)plt.show()# In[18]:num_rows=5num_cols=3num_image=num_cols*num_rows
plt.figure(figsize=(2*2*num_cols,2*num_rows))for i in range(num_image):plt.subplot(num_rows,2*num_cols,2*i+1)plot_image(i,predictions,test_labels,test_images)plt.subplot(num_rows,2*num_cols,2*i+2)plot_value_array(i,predictions,test_labels)plt.tight_layout()plt.show()# In[ ]: