import tensorflow as tf
import numpy as np
import random
import time
import matplotlib.pyplot as plt


sizeof_x = 784
nb_classes = 10
nb_branch = 256
epoch = 15
batch_size = 100
learning_rate=0.001
alg = 0
val_keep_prob = 1.0

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
print( "x_train.shape=", x_train.shape )
print( "x_train.shape=", x_train.shape[0] )

num_iterations = int(x_train.shape[0] / batch_size)

x_train = x_train.reshape(x_train.shape[0], -1).astype('float32') / 255
x_test = x_test.reshape(x_test.shape[0], -1).astype('float32') / 255
print( "x_train.shape=", x_train.shape )
print( "x_test.shape=", x_test.shape )

y_train = tf.keras.utils.to_categorical(y_train, nb_classes)
y_test = tf.keras.utils.to_categorical(y_test, nb_classes)

print( "y_train.shape=", y_train.shape )
print( "y_test.shape=", y_test.shape )


model = tf.keras.Sequential()

model.add(tf.keras.layers.Dense(nb_classes, activation="softmax"))
model.compile(optimizer='adam', loss=tf.keras.losses.categorical_crossentropy, metrics=['accuracy'])

print( "Now training..." )
model.fit(x=x_train, y=y_train, verbose=1, epochs = epoch, batch_size=batch_size)



print( "Now evaluating..." )
result = model.predict(x_test)

v_result = np.argmax(result, 1)
v_y_test= np.argmax(y_test,1)

is_correct = np.equal(v_result, v_y_test).astype('float32')
accuracy = np.mean(is_correct)
print( "accuracy=", accuracy )

for i in range(100):
    r = random.randint(0, x_test.shape[0] - 1)
    image= x_test[r:r+1]
    predict = v_result[r:r+1]
    label = v_y_test[r:r+1]
    if label != predict :
      print("{} {} Label={} Predict={}".format(i, label==predict, label, predict))
      plt.imshow(image.reshape(28, 28),        cmap="Greys",
          interpolation="nearest"
          )
      plt.show()

+ Recent posts