MNIST数据集手写数字识别(softmax回归模型)

机器学习入门之MNIST数据集

使用平台:python35自带的IDLE

>>>from tensorflow.examples.tutorials.mnist import input_data
>>> mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)//从MNIST_data/中读取数据到mnist对象,数据不存在是自动执行下载

另外一种方法:
yana Lecun博客—MNIST数据集下载链接
下载完成放入MNIST_data/文件夹中执行上述代码提取数据到mnist对象
在这里插入图片描述

>>> import os
>>> import scipy.misc
>>> save_dir='MNIST_data/raw/' //定义一个文件存储路径
>>> if os.path.exists(save_dir) is False:                                   
                os.makedirs(save_dir)
        //如果文件目录不存在,则新建一个文件目录
for i in range(40)://生成40张手写数字图片(28*28规格)在MNIST_data/raw
	image_array=mnist.train.images[i,:]
	image_array=image_array.reshape(28,28) //reshape ,本来是1维784width的向量
	filename=save_dir+'mnist_train_%d.jpg'%i //保存图片文件的文件名格式
	scipy.misc.toimage(image_array,cmin=0.0,cmax=1.0).save(filename)
	//通过scipy.misc.toimage将二维数组向量转为图像,然后以相应的文件名存储起来

在这里插入图片描述

>>> print(mnist.train.labels[0,:])//打印第0张训练图片的标签的独热
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
import numpy as np
for i in range(40):
	one_hot_label=mnist.train.labels[i,:]//独热形式表示
	label=np.argmax(one_hot_label)//通过np.argmax,可以直接获得原始的label
	print('mnist_train_%d.jpg label: %d'%(i,label))//打印显示40张图片的标签
>>> x=tf.placeholder(tf.float32,[None,784])
//x是一个占位符,None为任意数量图片,784向量
>>> w=tf.Variable(tf.zeros([784,10]))
//w变量,是softmax模型的参数,将输入的784维的图片转化为一个10维的输出,初始值是0
>>> b=tf.Variable(tf.zeros([10]))//模型参数,作为一个偏置项
>>> y=tf.nn.softmax(tf.matmul(x,w)+b)//y表示模型的输出
>>> y_=yf.placeholder(tf.float32,[None,10])//实际的图像标签,以占位符表示
 cross_entropy=\
		tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y))) 
		//y为模型输出,y_为实际标签,根据y和y_构造交叉熵损失
train_step=tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
 //针对损失进行用梯度下降进行模型参数的优化
  0.01是优化中的学习率,TensorFlow会默认对所有变量进行优化,而这里只有w和b参数

sess=tf.InteractiveSession()//创建会话
tf.global_variables_initializer().run()//初始化所有变量,分配内存
for _ in range(1000)://进行1000次优化
	batch_xs,batch_ys=mnist.train.next_batch(100)
	//batch_xs,batch_ys对应两个占位符,每次从mnist.trian中抽取100个训练数据
	sess.run(train_step,feed_dict={x:batch_xs,y_:batch_ys})
	//在会话中运行train_step,运行是传入占位符的值
>>> correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
//tf.argmax是用来将独热表示以及模型的输出转化为数字标签,取出最大值的下标
//tf.equal用以比较模型输出和实际标签是否相等,并将结果保存到
>>> accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
//tf.cast是将correct_prediction中的值转化成float32型的变量
//tf.reduce_mean计算数组中所有元素的平均值
>>> print(sess.run(accuracy,feed_dict={x:mnist.test.images,y_:mnist.test.labels}))
0.911
//使用全体测试样本进行测试,准确率为0.911,准确率并不是很高

softmax回归是一个简单的模型,由上图可见准确率并不高

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是实现MNIST识别逻辑回归的步骤: 1. 导入依赖库 ```python import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers ``` 2. 加载数据集 ```python (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() ``` 3. 数据预处理 ```python x_train = x_train.reshape(-1, 28*28).astype("float32") / 255.0 x_test = x_test.reshape(-1, 28*28).astype("float32") / 255.0 y_train = y_train.astype("float32") y_test = y_test.astype("float32") ``` 4. 定义模型 ```python model = keras.Sequential([ layers.Dense(10, input_shape=(784,), activation='softmax') ]) ``` 这里我们使用了一个仅包含一个全连接层的简单模型,输出层使用了softmax激活函数。 5. 编译模型 ```python model.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'], ) ``` 6. 训练模型 ```python history = model.fit( x_train, y_train, batch_size=32, epochs=5, verbose=1, validation_split=0.1, ) ``` 7. 评估模型 ```python model.evaluate(x_test, y_test, batch_size=32, verbose=2) ``` 完整代码如下: ```python import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() x_train = x_train.reshape(-1, 28*28).astype("float32") / 255.0 x_test = x_test.reshape(-1, 28*28).astype("float32") / 255.0 y_train = y_train.astype("float32") y_test = y_test.astype("float32") model = keras.Sequential([ layers.Dense(10, input_shape=(784,), activation='softmax') ]) model.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'], ) history = model.fit( x_train, y_train, batch_size=32, epochs=5, verbose=1, validation_split=0.1, ) model.evaluate(x_test, y_test, batch_size=32, verbose=2) ``` 希望能对你有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值