tensorflow实现卷积神经网络案例(识别手写数字)

本文详细介绍了如何利用TensorFlow实现一个卷积神经网络(CNN)来识别手写数字。首先,文章加载并预处理了MNIST数据集,然后通过定义权重、偏差、卷积层和池化层构建CNN模型。接着,设置了训练参数并进行了模型训练,最终展示了模型在测试数据上的表现,实现了对手写数字的准确识别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

tensorflow实现卷积神经网络经典案例--识别手写数字

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import matplotlib.cm as cm %matplotlib inline

import tensorflow as tf

#参数设置

learning_rate=1e-4

training_iterations=2000

dropout=0.5

batch_size=50 #所有的训练样本分批训练的效率最高,每一批的训练样本数量就是batch validation_size=2000

image_to_display=10

数据准备:

data=pd.read_csv('.../train.csv')

images=data.iloc[:,1:].values

images=images.astype(np.float)

#对训练数据进行归一化处理,[0:255]=>[0.0:1.0] images=np.multiply(images,1.0/255.0) #print('images({0[0]},{0[1]})'.format(images.shape))可以查看数据格式,输出结果为'data(42000,784)' 

image_size=images.shape[1] image_width=image_height=np.ceil(np.sqrt(image_size)).astype(np.uint8)

#定义显示图片的函数 

def display(img): 

#784=>28*28 

one_img=img.reshape(image_width,image_height)

plt.axis('off')

plt.imshow(one_img,cmap=cm.binary)

display(images[10]) #显示数据表格中第十条数据代表的数字,结果如下图

labels_flat=data.iloc[:,0].values.ravel() labels_count=np.unique(labels_flat).shape[0]

 

#定义one-hot编码函数 

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[10])的输出结果为'[0 0 0 0 0 0 0 0 1 0]',代表数据集中第10个数字的实际值为'8' 

 

#将数据拆分成用于训练和验证两部分 validation_images=images[:validation_size]

#将训练的数据分为trainvalidationvalidation的部分是为了对比不同模型参数的训练效果,如:learning_rate, training_iterations, dropout validation_labels=labels[:validation_size]

 

train_images = images[validation_size:]

train_labels = labels[validation_size:]

 

定义权重、偏差、卷积图层、池化图层:

#定义weight 

def weight_variable(shape): 

initial=tf.truncated_normal(shape,stddev=0.1)

return tf.Variable(initial)

 

#定义bias 

def bias_variable(shape): 

initial=tf.constant(0.1,shape=shape)

return tf.Variable(initial)

 

#定义二维的卷积图层 

def conv2d(x,W): 

return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值