参考博客地址
本博客采用Lenet5实现,也包含TensorFlow模型参数保存与加载参考我的博文,实用性比较好。在训练集准确率99.85%,测试训练集准确率99%+。
train文件
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
import pandas as pd
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('./1CNN/mnistcnn/data', one_hot=True)
#sess = tf.InteractiveSession()
#训练数据
x = tf.placeholder("float", shape=[None, 784],name="x")
#训练标签数据
y_ = tf.placeholder("float", shape=[None, 10],name="y_")
#把x更改为4维张量,第1维代表样本数量,第2维和第3维代表图像长宽, 第4维代表图像通道数, 1表示灰度
x_image = tf.reshape(x, [-1,28,28,1])
#第一层:卷积层
conv1_weights = tf.get_variable("conv1_weights", [5, 5, 1, 32], initializer=tf.truncated_normal_initializer(stddev=0.1)) #过滤器大小为5*5, 当前层深度为1, 过滤器的深度为32
conv1_biases = tf.get_variable("conv1_biases", [32], initializer=tf.constant_initializer(0.0))
conv1 = tf.nn.conv2d(x_image, conv1_weights, strides=[1, 1, 1, 1], padding='SAME') #移动步长为1, 使用全0填充
relu1 = tf.nn.relu( tf.nn.bias_add(conv1, conv1_biases) ) #激活函数Relu去线性化
#第二层:最大池化层
#池化层过滤器的大小为2*2, 移动步长为2,使用全0填充
pool1 = tf.nn.max_pool(relu1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
#第三层:卷积层
conv2_weights = tf.get_variable("conv2_weights", [5, 5, 32, 64], initializer=tf.truncated_normal_initializer(stddev=0.1)) #过滤器大小为5*5, 当前层深度为32, 过滤器的深度为64
conv2_biases = tf.get_variable("conv2_biases", [64], initializer=tf.constant_initializer(0.0))
conv2 = tf.nn.conv2d(pool1, conv2_weights, strides=[1, 1, 1, 1], padding='SAME') #移动步长为1, 使用全0填充
relu2 = tf.nn.relu( tf.nn.bias_add(conv2, conv2_biases) )
#第四层:最大池化层
#池化层过滤器的大小为2*2, 移动步长为2,使用全0填充
pool2 = tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
#第五层:全连接层
fc1_weights = tf.get_variable("fc1_weights", [7 * 7 * 64, 1024], initializer=tf.truncated_normal_initializer(stddev=0.1)) #7*7*64=3136把前一层的输出变成特征向量
fc1_baises = tf.get_variable("fc1_baises", [1024], initializer=tf.constant_initializer(0.1))
pool2_vector = tf.reshape(pool2, [-1, 7 * 7 * 64])
fc1 = tf.nn.relu(tf.matmul(pool2_vector, fc1_weights) + fc1_baises)
#为了减少过拟合,加入Dropout层
keep_prob = tf.placeholder(tf.float32,name="keep_prob")
fc1_dropout = tf.nn.dropout(fc1, keep_prob)
#第六层:全连接层
fc2_weights = tf.get_variable("fc2_weights", [1024, 10], initializer=tf.truncated_normal_initializer(stddev=0.1)) #神经元节点数1024, 分类节点10
fc2_biases = tf.get_variable("fc2_biases", [10], initializer=tf.constant_initializer(0.1))
fc2 = tf.matmul(fc1_dropout, fc2_weights) + fc2_biases
#第七层:输出层
# softmax
y_conv = tf.nn.softmax(fc2,name="y_conv")
y_conv_labels = tf.argmax(y_conv,1,name='y_conv_labels')
#定义交叉熵损失函数
y_conv = tf.clip_by_value(y_conv,1e-4,1.99)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))
#选择优化器,并让优化器最小化损失函数/收敛, 反向传播
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# tf.argmax()返回的是某一维度上其数据最大所在的索引值,在这里即代表预测值和真实值
# 判断预测值y和真实值y_中最大数的索引是否一致,y的值为1-10概率
correct_prediction = tf.equal(y_conv_labels, tf.argmax(y_,1))
# 用平均值来统计测试准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32),name="accuracy")
def convert2onehot(data):
# covert data to onehot representation
return pd.get_dummies(data)
file_path = "./1CNN/mnistcnn/datas/train.csv"
df_data = pd.read_csv(file_path, sep=",", header="infer")
np_data = df_data.values
trainx = np_data[:, 1:]/255
trainy = convert2onehot(np_data[:, 0]).values
with tf.Session() as sess:
#开始训练
srun = sess.run
srun(tf.global_variables_initializer())
saver = tf.train.Saver()
for i in range(6001):
start_step = i*100 % 42000
stop_step = start_step+100
batch_x, batch_y = trainx[start_step:stop_step], trainy[start_step:stop_step]
srun(train_step,feed_dict={x: batch_x, y_: batch_y, keep_prob: 0.5}) #训练阶段使用50%的Dropout
if i%100 == 0:
train_accuracy = srun(accuracy,feed_dict={x:batch_x, y_: batch_y, keep_prob: 1.0}) #评估阶段不使用Dropout
print("step %d, training accuracy %f" % (i, train_accuracy))
saver_path = saver.save(sess, "./1CNN/mnistcnn/ckpt/my_model.ckpt",global_step=i) # 将模型保存到save/model.ckpt文件
#print("W1:", sess.run(conv1_weights)) # 打印v1、v2的值一会读取之后对比
#print("W2:", sess.run(conv1_biases))
print("Model saved in file:", saver_path)
#在测试数据上测试准确率
print("test accuracy %g" % srun(accuracy,feed_dict={x: trainx, y_: trainy, keep_prob: 1.0}))
print("test accuracy %g" % srun(accuracy,feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
运行结果:
...
step 5800, training accuracy 1.000000
step 5900, training accuracy 0.990000
step 6000, training accuracy 1.000000
Model saved in file: ./1CNN/mnistcnn/ckpt/my_model.ckpt-6000
test accuracy 0.998571
test accuracy 0.9958
app文件:
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
import tensorflow as tf
import pandas as pd
file_path = "./1CNN/mnistcnn/datas/test.csv"
df_data = pd.read_csv(file_path, sep=",", header="infer")
np_data = df_data.values
testx = np_data[:, :]/255
file_path1 = "./1CNN/mnistcnn/datas/sample_submission.csv"
df_data1 = pd.read_csv(file_path1, sep=",", header="infer")
print(df_data1.head())
df_data1.drop(labels="Label",axis = 1,inplace=True)
print(df_data1.head())
with tf.Session() as sess:
#加载运算图
saver = tf.train.import_meta_graph('./1CNN/mnistcnn/ckpt/my_model.ckpt-6000.meta')
#加载参数
saver.restore(sess,tf.train.latest_checkpoint('./1CNN/mnistcnn/ckpt'))
graph = tf.get_default_graph()
#导入输入接口
x = graph.get_tensor_by_name("x:0")
#导入输出接口
y_ = graph.get_tensor_by_name("y_:0")
keep_prob = graph.get_tensor_by_name("keep_prob:0")
y_conv_labels = graph.get_tensor_by_name("y_conv_labels:0")
y_conv_labels_val = sess.run(y_conv_labels,{x:testx[:],keep_prob:1.0})
#进行预测
print("y: ",y_conv_labels_val[:10])
df_data1["Label"] = y_conv_labels_val
print(df_data1.head())
df_data1.to_csv(file_path1,columns=["ImageId","Label"],index=False)
print("Ok")
运行结果:
ImageId Label
0 1 0
1 2 0
2 3 0
3 4 0
4 5 0
ImageId
0 1
1 2
2 3
3 4
4 5
y: [2 0 9 9 3 7 0 3 0 3]
ImageId Label
0 1 2
1 2 0
2 3 9
3 4 9
4 5 3
Ok
Kaagle平台结果
Your Best Entry
You advanced 381 places on the leaderboard!
Your submission scored 0.98928, which is an improvement of your previous score of 0.98142. Great job!
通过这个cnn识别手写数字实战,加深了对于cnn的理解与运用能力。
使用TensorFlow模型参数保存与加载参考我的博文也使得代码应用更加灵活高效,条理也更加清晰了,推荐大家使用。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有