Набор данных MNIST - один из самых популярных наборов данных, который дает практические навыки работы с изображениями. В этой статье мы:
- Используйте сверточные нейронные сети для данных изображений
- Создайте простую модель в TensorFlow
Давайте настроим нашу среду, импортировав библиотеки:
import tensorflow as tf import numpy as np import pandas as pd from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.python.framework import ops import matplotlib.pyplot as plt
Импортируйте файл training.csv из набора данных mnist:
#data reading data = pd.read_csv(“./train.csv”, sep=”,”)
Разделение данных на изображения и их целевые метки:
X = data.iloc[:,1:] Y = data.iloc[:,0]
Преобразование фрейма данных в ndarray:
X = X.as_matrix().reshape([X.shape[0], 28,28])
Взгляните на наши данные:
plt.imshow(X[10])
Итак, это изображение числа (8):
Чтобы обучить нашу модель, нам нужно преобразовать наши двухмерные данные в трехмерные:
#reshaping 2d examples in 3D X = X.reshape(X.shape[0], 28, 28, 1)
Получение мгновенного представления наших целевых меток:
#onehot encoding Y = pd.get_dummies(Y)
Разделение набора данных на 90% данных обучения и 10% данных тестирования:
x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.10, random_state=42)
Создание заполнителей для наших обучающих примеров и целевых результатов:
def create_placeholders(n_H0, n_W0, n_C0, n_y): X = tf.placeholder(tf.float32, shape=[None, n_H0, n_W0, n_C0], name=”x”) Y = tf.placeholder(tf.float32, shape=[None, n_y], name=”y”) return X, Y
Модель будет иметь два слоя, поэтому здесь инициализируются параметры для этих слоев:
def initialize_parameters(): tf.set_random_seed(1) # so that your "random" numbers match ours W1 = tf.get_variable("W1", [4,4,1,8], initializer=tf.contrib.layers.xavier_initializer(seed=0)) W2 = tf.get_variable("W2", [2,2,8,16], initializer=tf.contrib.layers.xavier_initializer(seed=0)) parameters = {"W1": W1, "W2": W2} return parameters
Сверточные нейронные сети используются с максимальным пулом для прямого распространения:
def forward_propagation(X, parameters, outputs): # Retrieve the parameters from the dictionary “parameters” W1 = parameters[‘W1’] W2 = parameters[‘W2’] # CONV2D: stride of 1, padding ‘SAME’ print (X.shape) Z1 = tf.nn.conv2d(X, W1, strides=[1,1,1,1], padding=”SAME”) print (Z1.shape) # RELU A1 = tf.nn.relu(Z1) # MAXPOOL: window 8x8, sride 8, padding ‘SAME’ P1 = tf.nn.max_pool(A1, ksize=[1,8,8,1], strides=[1,8,8,1], padding=”SAME”) print (P1.shape) # CONV2D: filters W2, stride 1, padding ‘SAME’ Z2 = tf.nn.conv2d(P1, W2, strides=[1,1,1,1], padding=”SAME”) print (Z2.shape) # RELU A2 = tf.nn.relu(Z2) # MAXPOOL: window 4x4, stride 4, padding ‘SAME’ P2 = tf.nn.max_pool(A2, ksize=[1,4,4,1], strides=[1,4,4,1], padding=”SAME”) print (P2.shape) # FLATTEN P2 = tf.contrib.layers.flatten(P2) print (P2.shape) # FULLY-CONNECTED without non-linear activation function (not not call softmax). # 10 neurons in output layer. Z3 = tf.contrib.layers.fully_connected(P2, outputs, activation_fn=None) print (Z3.shape) return Z3
Это позволит вычислить стоимость прямого распространения:
def compute_cost(Z3, Y): cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=Z3, labels=Y)) return cost
наконец пора построить модель:
def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.01, num_epochs = 1000, print_cost = True): ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables tf.set_random_seed(1) # to keep results consistent (tensorflow seed) seed = 3 # to keep results consistent (numpy seed) (m, n_H0, n_W0, n_C0) = X_train.shape n_y = Y_train.shape[1] costs = [] # To keep track of the cost # Create Placeholders of the correct shape X, Y = create_placeholders(n_H0, n_W0, n_C0, n_y) # Initialize parameters parameters = initialize_parameters() # Forward propagation: Build the forward propagation in the tensorflow graph Z3 = forward_propagation(X, parameters, len(Y_train.columns)) # Cost function: Add cost function to tensorflow graph cost = compute_cost(Z3, Y) # Backpropagation: Define the tensorflow optimizer. Use an AdamOptimizer that minimizes the cost. optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, name=”optimizer”).minimize(cost) # Initialize all the variables globally init = tf.global_variables_initializer() # Start the session to compute the tensorflow graph saver = tf.train.Saver() with tf.Session() as sess: # Run the initialization sess.run(init) # Do the training loop for epoch in range(num_epochs): seed = seed + 1 _ , temp_cost = sess.run([optimizer, cost], feed_dict={X:X_train, Y:Y_train}) # Print the cost every epoch if print_cost == True and epoch % 5 == 0: print (“Cost after epoch %i: %f” % (epoch, temp_cost)) if print_cost == True and epoch % 1 == 0: costs.append(temp_cost) # plot the cost plt.plot(np.squeeze(costs)) plt.ylabel(‘cost’) plt.xlabel(‘iterations (per tens)’) plt.title(“Learning rate =” + str(learning_rate)) plt.show() # Calculate the correct predictions predict_op = tf.argmax(Z3, 1) tf.add_to_collection(“predict_op”, predict_op) correct_prediction = tf.equal(predict_op, tf.argmax(Y, 1)) # Calculate accuracy on the test set accuracy = tf.reduce_mean(tf.cast(correct_prediction, “float”)) # print(accuracy) train_accuracy = accuracy.eval({X: X_train, Y: Y_train}) test_accuracy = accuracy.eval({X: X_test, Y: Y_test}) print(“Train Accuracy:”, train_accuracy) print(“Test Accuracy:”, test_accuracy) saver.save(sess, save_path=”graph”) return train_accuracy, test_accuracy, parameters
Проверьте производительность модели с помощью набора данных обучения и тестирования:
_, _, parameters = model(x_train, y_train, x_test, y_test)
(?, 28, 28, 1)
(?, 28, 28, 8)
(?, 4, 4, 8)
(?, 4, 4, 16)
(?, 1, 1, 16)
(?, 16)
(?, 10)
Стоимость после эпохи 0: 226.943893
Стоимость после эпохи 5: 41.436584 < br /> Стоимость после эпохи 10: 13,325080
Стоимость после эпохи 15: 6,645814
Стоимость после эпохи 20: 4,278826
Стоимость после эпохи 25: 3,050441
Стоимость после эпохи 30: 2,679555 < br /> Стоимость после эпохи 35: 2.461791
Стоимость после эпохи 40: 2.366124
Стоимость после эпохи 45: 2.303601
….
Стоимость после эпохи 960: 0,548924
Стоимость после эпохи 965: 0,546464
Стоимость после эпохи 970: 0,543844
Стоимость после эпохи 975: 0,541163
Стоимость после эпохи 980: 0,538230
Стоимость после эпохи 985: 0,535119
Стоимость после эпохи 990: 0,531743
Стоимость после эпохи 995: 0,528425
Точность поезда: 0,8350794
Точность теста: 0,8290476
Итак, мы видим, что мы достигли точности 0,83 при обучении и точности 0,82 на тестовых данных. Целью этого поста было дать вам краткое введение в tenorflow и объяснить его работу, надеюсь, это поможет. Спасибо.
Ссылки:
Код доступен по адресу: https://github.com/mubasharNazar/MNIST-TensorFlow
Набор данных доступен на kaggle: https://www.kaggle.com/c/digit-recognizer/data