https://www.kaggle.com/kakauandme/tensorflow-deep-nn

本人只是负责将这个kernels的代码整理了一遍,具体还是请看原链接

import numpy as np
import pandas as pd
import tensorflow # settings
LEARNING_RATE = 1e-4
# set to 20000 on local environment to get 0.99 accuracy
TRAINING_ITERATIONS = 20000 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 # read training data from CSV file
data = pd.read_csv('D://kaggle//DigitRecognizer//data//train.csv') 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) 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)) labels_flat = data.iloc[:,0].values 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)) 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])) # 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)) # weight initialization
def weight_variable(shape):
initial = tensorflow.truncated_normal(shape, stddev=0.1)
return tensorflow.Variable(initial) def bias_variable(shape):
initial = tensorflow.constant(0.1, shape=shape)
return tensorflow.Variable(initial) # convolution
def conv2d(x, W):
return tensorflow.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 tensorflow.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # input & output of NN # images
x = tensorflow.placeholder('float', shape=[None, image_size])
# labels
y_ = tensorflow.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 = tensorflow.reshape(x, [-1,image_width , image_height,1])
#print (image.get_shape()) # =>(40000,28,28,1) h_conv1 = tensorflow.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 = tensorflow.reshape(h_conv1, (-1, image_height, image_width, 4 ,8)) # reorder so the channels are in the first dimension, x and y follow.
layer1 = tensorflow.transpose(layer1, (0, 3, 1, 4,2)) layer1 = tensorflow.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 = tensorflow.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 = tensorflow.reshape(h_conv2, (-1, 14, 14, 4 ,16)) # reorder so the channels are in the first dimension, x and y follow.
layer2 = tensorflow.transpose(layer2, (0, 3, 1, 4,2)) layer2 = tensorflow.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 = tensorflow.reshape(h_pool2, [-1, 7*7*64]) h_fc1 = tensorflow.nn.relu(tensorflow.matmul(h_pool2_flat, W_fc1) + b_fc1)
#print (h_fc1.get_shape()) # => (40000, 1024) # dropout
keep_prob = tensorflow.placeholder('float')
h_fc1_drop = tensorflow.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 = tensorflow.nn.softmax(tensorflow.matmul(h_fc1_drop, W_fc2) + b_fc2) #print (y.get_shape()) # => (40000, 10) # cost function
cross_entropy = -tensorflow.reduce_sum(y_*tensorflow.log(y)) # optimisation function
train_step = tensorflow.train.AdamOptimizer(LEARNING_RATE).minimize(cross_entropy) # evaluation
correct_prediction = tensorflow.equal(tensorflow.argmax(y,1),tensorflow.argmax(y_,1)) accuracy = tensorflow.reduce_mean(tensorflow.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 = tensorflow.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 = tensorflow.initialize_all_variables()
sess = tensorflow.InteractiveSession() sess.run(init) # 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}) # read test data from CSV file
test_images = pd.read_csv('D://kaggle//DigitRecognizer//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)) # 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])) # save results
np.savetxt('D://kaggle//DigitRecognizer//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})
sess.close()

tensorflow 手写数字识别的更多相关文章

  1. Tensorflow手写数字识别(交叉熵)练习

    # coding: utf-8import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data #pr ...

  2. Tensorflow手写数字识别训练(梯度下降法)

    # coding: utf-8 import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data #p ...

  3. Tensorflow手写数字识别---MNIST

    MNIST数据集:包含数字0-9的灰度图, 图片size为28x28.训练样本:55000,测试样本:10000,验证集:5000

  4. tensorflow手写数字识别(有注释)

    import tensorflow as tf import numpy as np # const = tf.constant(2.0, name='const') # b = tf.placeho ...

  5. 卷积神经网络应用于tensorflow手写数字识别(第三版)

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_dat ...

  6. 基于tensorflow的MNIST手写数字识别(二)--入门篇

    http://www.jianshu.com/p/4195577585e6 基于tensorflow的MNIST手写字识别(一)--白话卷积神经网络模型 基于tensorflow的MNIST手写数字识 ...

  7. Android+TensorFlow+CNN+MNIST 手写数字识别实现

    Android+TensorFlow+CNN+MNIST 手写数字识别实现 SkySeraph 2018 Email:skyseraph00#163.com 更多精彩请直接访问SkySeraph个人站 ...

  8. 手写数字识别 ----在已经训练好的数据上根据28*28的图片获取识别概率(基于Tensorflow,Python)

    通过: 手写数字识别  ----卷积神经网络模型官方案例详解(基于Tensorflow,Python) 手写数字识别  ----Softmax回归模型官方案例详解(基于Tensorflow,Pytho ...

  9. 手写数字识别 ----卷积神经网络模型官方案例注释(基于Tensorflow,Python)

    # 手写数字识别 ----卷积神经网络模型 import os import tensorflow as tf #部分注释来源于 # http://www.cnblogs.com/rgvb178/p/ ...

随机推荐

  1. zookeeper 学习 状态机复制的共识算法

    https://www.youtube.com/watch?v=BhosKsE8up8 state machine replication 的 共识(consensus) 算法 根据CAP理论,一个分 ...

  2. [转] iOS9系统自带字体

    Family: Thonburi Font: Thonburi-Bold Font: Thonburi Font: Thonburi-Light 1 2 3 4 Family: Khmer Sanga ...

  3. h5网页在微信里打开 右上角分享到微信好友或者朋友圈

    首先你需要一个分享接口地址,然后在自定义图片 标题 描述 如下: <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js& ...

  4. 【LGR-052】洛谷9月月赛II(加赛)

    题解: 没打... ab题满世界都过了应该没什么意思 c题是个比较有意思的思维题(先看了题解才会的...) 我们考虑这么一件事情 没钥匙的人出门后 门一定是开着的 他进来的时候,门一定是开着的 其他时 ...

  5. WebApi接口返回值不困惑:返回值类型详解

    前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi的园友们速速动起来,跟着博主一起来学习吧.作为程序猿,我们都知道参数和返回值是编程领域不可分割的两大块,此前分享了 ...

  6. WINDOWS 2008Server 配置nginx 反向代理服务器 安装成服务

    本案例有用过可行 反向代理就是是网站通过一台机器发布到公网,客户访问的时候是直接访问那台代理机器的,然后通过那台机器才访问到内网网站.   0.先要在域名官网上面配置域名对应的IP地址,然后要在自己路 ...

  7. javascript 和 下拉列表

    <form id="f"> <select size="1" name="s"> <option value= ...

  8. Codeforces 342D Xenia and Dominoes 状压dp

    码就完事了. #include<bits/stdc++.h> #define LL long long #define fi first #define se second #define ...

  9. BZOJ4003 [JLOI2015]城池攻占 左偏树 可并堆

    欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - BZOJ4003 题意概括 题意有点复杂,直接放原题了. 小铭铭最近获得了一副新的桌游,游戏中需要用 m 个骑 ...

  10. 不同路径II(一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?网格中的障碍物和空位置分别用 1 和 0 来表示。)

    示例 1: 输入: [   [0,0,0],   [0,1,0],   [0,0,0] ] 输出: 2 解释: 3x3 网格的正中间有一个障碍物. 从左上角到右下角一共有 2 条不同的路径: 1. 向 ...