用CNN解决手写体数字识别。--tensorflow

第一次解决这个问题是应用了机器学习中的Knn算法,发现排名并不是很高。再阅读了kaggle上其他人的一些笔记,知道了神经网络在图片分类上的优秀。我们可以用卷积层来得到数据图片中的某些特征,然后使用激活函数,再用汇聚层在空间维度上进行降维度操作。如此反复,最后使用全连接层,尺寸变为[1x1x10],就得到了10个类别的分类值。其中我们还是用了Adam来更新参数,用了随机失活防止过拟合。我使用了Tensorflow来搭建网络。
首先先引入一些需要的库。

import pandas as pd
import numpy as np

#加入%matplotlib inline才能在jupyter显示图像。
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import tensorflow as tf
# settings。CS231n上介绍学习率初始化一般都为1e-4
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

数据处理

kaggle上的数据并不是拿来就能用的,我们需要将它划分为像素,和标签。并且对像素进行归一化(不进行归一化可能会产生一些错误)。

# read training data from CSV file 
data = pd.read_csv('../input/train.csv')

print('data({0[0]},{0[1]})'.format(data.shape))
#展示前五行的数据
print (data.head())

这里写图片描述

#切片得到像素,不包括标签。
images = data.iloc[:, 1:].values
images = images.astype(np.float)

#归一化
images = np.multiply(images, 1.0 / 255.0)

print('images({0[0]},{0[1]})'.format(images.shape))

image_size = images.shape[1]

# in this case all images are square
image_width = image_height = np.ceil(np.sqrt(image_size)).astype(np.uint8)

>>>images(42000,784)

labels_flat = data.iloc[:,0].values.ravel()
#unique返回不同的数labels_count
labels_count = np.unique(labels_flat).shape[0]

print('labels_count => {0}'.format(labels_count))

>>>labels_count => 10
在分类问题中,我们经常使用one-hot vectors.在这个向量中,我们只有一个元素的值为1,其他的全为0。1的下标是什么就说明数字是多少。

#转化为one-hot vectors
#0 => [1 0 0 0 0 0 0 0 0 0 ]
#...
def dense_to_one_hot(labels_dense, num_classes):
    num_labels = labels_dense.shape[
  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值