""""
https://www.kaggle.com/villoro/cnn-with-tensorflow-dlfn-udacity/comments
"""
#1.Libraries and settings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
# %matplotlib inline
import tensorflow as tf
import time
start_0=time.time()
# settings
LEARNING_RATE = 1e-4
# set to 20000 on local environment to get 0.99 accuracy
TRAINING_ITERATIONS = 2500
DROPOUT = 0.5
BATCH_SIZE = 50
# set to 0 to train on all available data
VALIDATION_SIZE = 2000
# image number to output
IMAGE_TO_DISPLAY = 10
# 2.Data preparation
# To start, we read provided data. The train.csv file contains 42000 rows and 785 columns. Each row represents an image of a handwritten digit and a label with the value of this digit.
print("1.开始读取数据")
start =time.time()
# read training data from CSV file
data = pd.read_csv('../0_data/train.csv')
print('data({0[0]},{0[1]})'.format(data.shape))#(42000,785)
print (data.head())
images = data.iloc[:,1:].values
images = images.astype(np.float)
# convert from [0:255] => [0.0:1.0]
images = np.multiply(images, 1.0 / 255.0)
print('images({0[0]},{0[1]})'.format(images.shape))
image_size = images.shape[1]
print ('image_size => {0}'.format(image_size))
# in this case all images are square
image_width = image_height = np.ceil(np.sqrt(image_size)).astype(np.uint8)
print ('image_width => {0}\nimage_height => {1}'.format(image_width,image_height))
# display image
def display(img):
# (784) => (28,28)
one_image = img.reshape(image_width, image_height)
plt.axis('off')
plt.imshow(one_image, cmap=cm.binary)
# output image
display(images[IMAGE_TO_DISPLAY])
labels_flat = data.iloc[:,0].values.ravel()
print('labels_flat({0})'.format(len(labels_flat)))
print ('labels_flat[{0}] => {1}'.format(IMAGE_TO_DISPLAY,labels_flat[IMAGE_TO_DISPLAY]))
labels_count = np.unique(labels_flat).shape[0]
print('labels_count => {0}'.format(labels_count))
end = time.time()
print("读取数据耗时%.2f秒"%(end-start))
print("2.开始标签one-hot")
# convert class labels from scalars to one-hot vectors
# 0 => [1 0 0 0 0 0 0 0 0 0]
# 1 => [0 1 0 0 0 0 0 0 0 0]
# ...
# 9 => [0 0 0 0 0 0 0 0 0 1]
def dense_to_one_hot(labels_dense, num_classes):
num_labels = labels_dense.shape[0]
index_offset = np.arange(num_labels) * num_classes
labels_one_hot = np.zeros((num_labels, num_classes))
labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
return labels_one_hot
labels = dense_to_one_hot(labels_flat, labels_count)
labels = labels.astype(np.uint8)
print('labels({0[0]},{0[1]})'.format(labels.shape))
print ('labels[{0}] => {1}'.format(IMAGE_TO_DISPLAY,labels[IMAGE_TO_DISPLAY]))
print("3.开始数据集拆分")
# split data into training & validation
validation_images = images[:VALIDATION_SIZE]
validation_labels = labels[:VALIDATION_SIZE]
train_images = images[VALIDATION_SIZE:]
train_labels = labels[VALIDATION_SIZE:]
print('train_images({0[0]},{0[1]})'.format(train_images.shape))
print('validation_images({0[0]},{0[1]})'.format(validation_images.shape))
print("4.开始搭建模型")
start =time.time()
# weight initialization
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)
# convolution
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
# pooling
# [[0,3],
# [4,2]] => 4
# [[0,1],
# [1,1]] => 1
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# input & output of NN
# images
x = tf.placeholder('float', shape=[None, image_size])
# labels
y_ = tf.placeholder('float', shape=[None, labels_count])
# first convolutional layer
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
# (40000,784) => (40000,28,28,1)
image = tf.reshape(x, [-1,image_width , image_height,1])
#print (image.get_shape()) # =>(40000,28,28,1)
h_conv1 = tf.nn.relu(conv2d(image, W_conv1) + b_conv1)
#print (h_conv1.get_shape()) # => (40000, 28, 28, 32)
h_pool1 = max_pool_2x2(h_conv1)
#print (h_pool1.get_shape()) # => (40000, 14, 14, 32)
# Prepare for visualization
# display 32 fetures in 4 by 8 grid
layer1 = tf.reshape(h_conv1, (-1, image_height, image_width, 4 ,8))
# reorder so the channels are in the first dimension, x and y follow.
layer1 = tf.transpose(layer1, (0, 3, 1, 4,2))
layer1 = tf.reshape(layer1, (-1, image_height*4, image_width*8))
# second convolutional layer
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)
#print (h_conv2.get_shape()) # => (40000, 14,14, 64)
h_pool2 = max_pool_2x2(h_conv2)
#print (h_pool2.get_shape()) # => (40000, 7, 7, 64)
# Prepare for visualization
# display 64 fetures in 4 by 16 grid
layer2 = tf.reshape(h_conv2, (-1, 14, 14, 4 ,16))
# reorder so the channels are in the first dimension, x and y follow.
layer2 = tf.transpose(layer2, (0, 3, 1, 4,2))
layer2 = tf.reshape(layer2, (-1, 14*4, 14*16))
# densely connected layer
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
# (40000, 7, 7, 64) => (40000, 3136)
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)
#print (h_fc1.get_shape()) # => (40000, 1024)
print("5.开始dropout")
# dropout
keep_prob = tf.placeholder('float')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# readout layer for deep net
W_fc2 = weight_variable([1024, labels_count])
b_fc2 = bias_variable([labels_count])
y = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
#print (y.get_shape()) # => (40000, 10)
# cost function
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
# optimisation function
train_step = tf.train.AdamOptimizer(LEARNING_RATE).minimize(cross_entropy)
# evaluation
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
# prediction function
#[0.1, 0.9, 0.2, 0.1, 0.1 0.3, 0.5, 0.1, 0.2, 0.3] => 1
predict = tf.argmax(y,1)
epochs_completed = 0
index_in_epoch = 0
num_examples = train_images.shape[0]
# serve data by batches
def next_batch(batch_size):
global train_images
global train_labels
global index_in_epoch
global epochs_completed
start = index_in_epoch
index_in_epoch += batch_size
# when all trainig data have been already used, it is reorder randomly
if index_in_epoch > num_examples:
# finished epoch
epochs_completed += 1
# shuffle the data
perm = np.arange(num_examples)
np.random.shuffle(perm)
train_images = train_images[perm]
train_labels = train_labels[perm]
# start next epoch
start = 0
index_in_epoch = batch_size
assert batch_size <= num_examples
end = index_in_epoch
return train_images[start:end], train_labels[start:end]
# start TensorFlow session
init = tf.initialize_all_variables()
sess = tf.InteractiveSession()
sess.run(init)
print("6.开始可视化输出")
# visualisation variables
train_accuracies = []
validation_accuracies = []
x_range = []
display_step = 1
for i in range(TRAINING_ITERATIONS):
# get new batch
batch_xs, batch_ys = next_batch(BATCH_SIZE)
# check progress on every 1st,2nd,...,10th,20th,...,100th... step
if i % display_step == 0 or (i + 1) == TRAINING_ITERATIONS:
train_accuracy = accuracy.eval(feed_dict={x: batch_xs,
y_: batch_ys,
keep_prob: 1.0})
if (VALIDATION_SIZE):
validation_accuracy = accuracy.eval(feed_dict={x: validation_images[0:BATCH_SIZE],
y_: validation_labels[0:BATCH_SIZE],
keep_prob: 1.0})
print('training_accuracy / validation_accuracy => %.2f / %.2f for step %d' % (
train_accuracy, validation_accuracy, i))
validation_accuracies.append(validation_accuracy)
else:
print('training_accuracy => %.4f for step %d' % (train_accuracy, i))
train_accuracies.append(train_accuracy)
x_range.append(i)
# increase display_step
if i % (display_step * 10) == 0 and i:
display_step *= 10
# train on batch
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: DROPOUT})
# check final accuracy on validation set
if(VALIDATION_SIZE):
validation_accuracy = accuracy.eval(feed_dict={x: validation_images,
y_: validation_labels,
keep_prob: 1.0})
print('validation_accuracy => %.4f'%validation_accuracy)
plt.plot(x_range, train_accuracies,'-b', label='Training')
plt.plot(x_range, validation_accuracies,'-g', label='Validation')
plt.legend(loc='lower right', frameon=False)
plt.ylim(ymax = 1.1, ymin = 0.7)
plt.ylabel('accuracy')
plt.xlabel('step')
plt.show()
end = time.time()
print("训练数据耗时%.2f秒"%(end-start))
print("7.开始读取测试数据")
# read test data from CSV file
test_images = pd.read_csv('../0_data/test.csv').values
test_images = test_images.astype(np.float)
# convert from [0:255] => [0.0:1.0]
test_images = np.multiply(test_images, 1.0 / 255.0)
print('test_images({0[0]},{0[1]})'.format(test_images.shape))
print("8.开始测试")
start =time.time()
# predict test set
#predicted_lables = predict.eval(feed_dict={x: test_images, keep_prob: 1.0})
# using batches is more resource efficient
predicted_lables = np.zeros(test_images.shape[0])
for i in range(0,test_images.shape[0]//BATCH_SIZE):
predicted_lables[i*BATCH_SIZE : (i+1)*BATCH_SIZE] = predict.eval(feed_dict={x: test_images[i*BATCH_SIZE : (i+1)*BATCH_SIZE],
keep_prob: 1.0})
print('predicted_lables({0})'.format(len(predicted_lables)))
# output test image and prediction
display(test_images[IMAGE_TO_DISPLAY])
print ('predicted_lables[{0}] => {1}'.format(IMAGE_TO_DISPLAY,predicted_lables[IMAGE_TO_DISPLAY]))
end = time.time()
print("测试数据耗时%.2f秒"%(end-start))
print("9.开始生成递交数据")
# save results
np.savetxt('submission_softmax.csv',
np.c_[range(1,len(test_images)+1),predicted_lables],
delimiter=',',
header = 'ImageId,Label',
comments = '',
fmt='%d')
layer1_grid = layer1.eval(feed_dict={x: test_images[IMAGE_TO_DISPLAY:IMAGE_TO_DISPLAY+1], keep_prob: 1.0})
plt.axis('off')
plt.imshow(layer1_grid[0], cmap=cm.seismic )
sess.close()
end_0 = time.time()
print("tf-nn-总耗时%.2f秒"%(end_0-start_0))
C:\ProgramData\Anaconda2\envs\py36\python.exe C:/Users/hjz/python-project/project/02_lianxi/01_DigitRecognizer/02_DL/01_NN_TF.py
C:\ProgramData\Anaconda2\envs\py36\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
1.开始读取数据
data(42000,785)
label pixel0 pixel1 ... pixel781 pixel782 pixel783
0 1 0 0 ... 0 0 0
1 0 0 0 ... 0 0 0
2 1 0 0 ... 0 0 0
3 4 0 0 ... 0 0 0
4 0 0 0 ... 0 0 0
[5 rows x 785 columns]
images(42000,784)
image_size => 784
image_width => 28
image_height => 28
labels_flat(42000)
labels_flat[10] => 8
labels_count => 10
读取数据耗时6.99秒
2.开始标签one-hot
labels(42000,10)
labels[10] => [0 0 0 0 0 0 0 0 1 0]
3.开始数据集拆分
train_images(40000,784)
validation_images(2000,784)
4.开始搭建模型
5.开始dropout
WARNING:tensorflow:From C:\ProgramData\Anaconda2\envs\py36\lib\site-packages\tensorflow\python\util\tf_should_use.py:118: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
2020-07-30 09:52:46.953594: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
6.开始可视化输出
training_accuracy / validation_accuracy => 0.14 / 0.12 for step 0
training_accuracy / validation_accuracy => 0.04 / 0.06 for step 1
training_accuracy / validation_accuracy => 0.20 / 0.20 for step 2
training_accuracy / validation_accuracy => 0.20 / 0.22 for step 3
training_accuracy / validation_accuracy => 0.20 / 0.26 for step 4
training_accuracy / validation_accuracy => 0.26 / 0.26 for step 5
training_accuracy / validation_accuracy => 0.16 / 0.26 for step 6
training_accuracy / validation_accuracy => 0.34 / 0.28 for step 7
training_accuracy / validation_accuracy => 0.30 / 0.38 for step 8
training_accuracy / validation_accuracy => 0.30 / 0.36 for step 9
training_accuracy / validation_accuracy => 0.48 / 0.38 for step 10
training_accuracy / validation_accuracy => 0.46 / 0.54 for step 20
training_accuracy / validation_accuracy => 0.56 / 0.64 for step 30
training_accuracy / validation_accuracy => 0.60 / 0.72 for step 40
training_accuracy / validation_accuracy => 0.68 / 0.74 for step 50
training_accuracy / validation_accuracy => 0.76 / 0.84 for step 60
training_accuracy / validation_accuracy => 0.84 / 0.88 for step 70
training_accuracy / validation_accuracy => 0.82 / 0.90 for step 80
training_accuracy / validation_accuracy => 0.88 / 0.88 for step 90
training_accuracy / validation_accuracy => 0.88 / 0.90 for step 100
training_accuracy / validation_accuracy => 0.96 / 0.92 for step 200
training_accuracy / validation_accuracy => 0.90 / 0.90 for step 300
training_accuracy / validation_accuracy => 0.92 / 0.88 for step 400
training_accuracy / validation_accuracy => 1.00 / 0.90 for step 500
training_accuracy / validation_accuracy => 0.96 / 0.88 for step 600
training_accuracy / validation_accuracy => 0.88 / 0.90 for step 700
training_accuracy / validation_accuracy => 0.92 / 0.90 for step 800
training_accuracy / validation_accuracy => 1.00 / 0.92 for step 900
training_accuracy / validation_accuracy => 0.94 / 0.90 for step 1000
training_accuracy / validation_accuracy => 0.94 / 0.96 for step 2000
training_accuracy / validation_accuracy => 0.98 / 0.98 for step 2499
validation_accuracy => 0.9800
训练数据耗时350.02秒
7.开始读取测试数据
test_images(28000,784)
8.开始测试
predicted_lables(28000)
predicted_lables[10] => 5.0
测试数据耗时19.41秒
9.开始生成递交数据
tf-nn-总耗时379.02秒
Process finished with exit code 0
训练模型结构-纯手打
input(x) | [42000,28,28,1] |
---|---|
First Layer | |
W_conv1 | [5, 5, 1, 32] |
b_conv1 | [32] |
h_conv1 | [42000,28,28,1] |
h_pool1 | (42000, 14, 14, 32) |
Second Layer | |
W_conv2 | [5, 5, 32, 64] |
b_conv2 | [64] |
h_conv2 | (42000, 14,14, 64) |
h_pool2 | (40000, 7, 7, 64) |
FC Layer | |
W_fc1 | [7 * 7 * 64, 1024] |
b_fc1 | [1024] |
h_fc1 | (42000, 1024) |
Output Layer | |
W_fc2 | [1024,10] |
b_fc2 | [10] |
output(y) | (42000, 10) |