首页 > 分享 > Tensorflow基于卷积神经网络(CNN)的手写数字识别

Tensorflow基于卷积神经网络(CNN)的手写数字识别

这是一个基于TensorFlow框架实现的手写数字图像识别代码,使用的是卷积神经网络(CNN)模型。 首先,导入需要的库: ``` import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data ``` 然后,定义一些常量和超参数: ``` learning_rate = 0.001 training_epochs = 15 batch_size = 100 n_classes = 10 dropout = 0.75 # 输入数据的维度 n_input = 784 # 28*28 ``` 接着,定义占位符: ``` x = tf.placeholder(tf.float32, [None, n_input]) y = tf.placeholder(tf.float32, [None, n_classes]) keep_prob = tf.placeholder(tf.float32) ``` 定义卷积层和池化层函数: ``` def conv2d(x, W, b, strides=1): x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME') x = tf.nn.bias_add(x, b) return tf.nn.relu(x) def maxpool2d(x, k=2): return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME') ``` 接下来,定义卷积神经网络模型: ``` def conv_net(x, weights, biases, dropout): x = tf.reshape(x, shape=[-1, 28, 28, 1]) # 第一层卷积层 conv1 = conv2d(x, weights['wc1'], biases['bc1']) conv1 = maxpool2d(conv1, k=2) # 第二层卷积层 conv2 = conv2d(conv1, weights['wc2'], biases['bc2']) conv2 = maxpool2d(conv2, k=2) # 全连接层 fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]]) fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1']) fc1 = tf.nn.relu(fc1) fc1 = tf.nn.dropout(fc1, dropout) # 输出层 out = tf.add(tf.matmul(fc1, weights['out']), biases['out']) return out ``` 然后,初始化权重和偏置: ``` weights = { 'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])), 'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])), 'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])), 'out': tf.Variable(tf.random_normal([1024, n_classes])) } biases = { 'bc1': tf.Variable(tf.random_normal([32])), 'bc2': tf.Variable(tf.random_normal([64])), 'bd1': tf.Variable(tf.random_normal([1024])), 'out': tf.Variable(tf.random_normal([n_classes])) } ``` 接着,定义损失函数和优化器: ``` pred = conv_net(x, weights, biases, keep_prob) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) ``` 定义评估模型的准确率函数: ``` correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) ``` 最后,训练模型: ``` mnist = input_data.read_data_sets('/tmp/data/', one_hot=True) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # 训练循环 for epoch in range(training_epochs): avg_cost = 0. total_batch = int(mnist.train.num_examples/batch_size) # 遍历所有批次(batch) for i in range(total_batch): batch_x, batch_y = mnist.train.next_batch(batch_size) # 运行优化器 sess.run(optimizer, feed_dict={x: batch_x, y: batch_y, keep_prob: dropout}) # 计算损失值 avg_cost += sess.run(cost, feed_dict={x: batch_x, y: batch_y, keep_prob: 1.}) / total_batch # 显示每一轮训练的结果 if epoch % 1 == 0: print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)) # 计算测试数据的准确率 print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels, keep_prob: 1.})) ``` 这样,一个基于TensorFlow框架实现的手写数字图像识别代码就完成了。

相关知识

深度学习之基于Tensorflow卷积神经网络花卉识别系统
基于卷积神经网络的农作物病虫害识别系统
几个卷积神经网络(CNN)可视化的网站
基于TensorFlow实现的CNN神经网络 花卉识别系统Demo
TensorFlow框架下cnn卷积神经网络识别花卉
基于卷积神经网络的花卉图像分类研究(32页)
基于深度卷积神经网络的移动端花卉识别系统
基于深度卷积神经网络的植物病虫害识别
基于卷积神经网络的花卉识别技术 Flower Recognition Based on Convolutional Neural Networks
毕设分享 基于深度学习卷积神经网络的花卉识别

网址: Tensorflow基于卷积神经网络(CNN)的手写数字识别 https://m.huajiangbk.com/newsview764110.html

所属分类:花卉
上一篇: Search Support
下一篇: 爱字体下载安装