MNIST softmax——tensorflow初学

花了一上午终于搞定了anaconda,tensorflow,使用spyder IDE写机器学习代码

tensorflow入门 MNIST手写数字识别。模仿着教程的代码写,也算小有收获。

以下代码:

# -*- coding: utf-8 -*-
"""
Created on Fri Jul 20 14:12:45 2018

@author: czx
"""

# create a softmax regression 

import tensorflow as tf 
from tensorflow.examples.tutorials.mnist import input_data 

#读入数据,由于使用"MNIST_data/"需要翻墙,在这里建议先将MNIST数据包下载下来。
#MNIST下载地址http://yann.lecun.com/exdb/mnist/
#将四个文件下载下来放在一个文件夹中即可
mnist = input_data.read_data_sets("E:\桌面上的文件\MNIST", one_hot=True) 

#使用占位符,读入数据组数可变
x = tf.placeholder(tf.float32,[None, 784]) 
W = tf.Variable(tf.zeros([784, 10])) 
b = tf.Variable(tf.zeros([10])) 

#softmax回归,y = x*W+b
y = tf.nn.softmax(tf.matmul(x,W)+b) 
y_ = tf.placeholder(tf.float32,[None, 10])
#交叉熵
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) 
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) 

#通过tensorflow进行运算
init = tf.global_variables_initializer() 
sess = tf.Session() 
sess.run(init) 

#循环1w次
for i in range(10000): 
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict = {x: batch_xs, y_: batch_ys}) 
    
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1)) 
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 

#输出精确度
print(sess.run(accuracy, feed_dict={x:mnist.test.images, y_: mnist.test.labels}))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Softmax回归模型对MNIST数据集进行分类的示例代码: ```python import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # 读取MNIST数据集 mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # 创建输入占位符 x = tf.placeholder(tf.float32, [None, 784]) # 创建权重和偏置变量 W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) # 创建Softmax模型 y = tf.nn.softmax(tf.matmul(x, W) + b) # 创建损失函数 y_ = tf.placeholder(tf.float32, [None, 10]) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) # 创建优化器 train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) # 创建会话并训练模型 sess = tf.InteractiveSession() tf.global_variables_initializer().run() for _ in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # 测试模型准确率 correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) ``` 该示例代码使用TensorFlow实现了一个简单的Softmax回归模型,用于对MNIST数据集进行分类。首先读取MNIST数据集,然后创建输入占位符、权重和偏置变量以及Softmax模型。接着创建损失函数和优化器,并使用训练数据对模型进行训练。最后,使用测试数据评估模型的准确率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值