tensorflow实现逻辑回归模型


Posted in Python onSeptember 08, 2018

逻辑回归模型

逻辑回归是应用非常广泛的一个分类机器学习算法,它将数据拟合到一个logit函数(或者叫做logistic函数)中,从而能够完成对事件发生的概率进行预测。

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
#下载好的mnist数据集存在F:/mnist/data/中
mnist = input_data.read_data_sets('F:/mnist/data/',one_hot = True)
print(mnist.train.num_examples)
print(mnist.test.num_examples)

trainimg = mnist.train.images
trainlabel = mnist.train.labels
testimg = mnist.test.images
testlabel = mnist.test.labels

print(type(trainimg))
print(trainimg.shape,)
print(trainlabel.shape,)
print(testimg.shape,)
print(testlabel.shape,)

nsample = 5
randidx = np.random.randint(trainimg.shape[0],size = nsample)

for i in randidx:
  curr_img = np.reshape(trainimg[i,:],(28,28))
  curr_label = np.argmax(trainlabel[i,:])
  plt.matshow(curr_img,cmap=plt.get_cmap('gray'))
  plt.title(""+str(i)+"th Training Data"+"label is"+str(curr_label))
  print(""+str(i)+"th Training Data"+"label is"+str(curr_label))
  plt.show()


x = tf.placeholder("float",[None,784])
y = tf.placeholder("float",[None,10])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

#
actv = tf.nn.softmax(tf.matmul(x,W)+b)
#计算损失
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(actv),reduction_indices=1))
#学习率
learning_rate = 0.01
#随机梯度下降
optm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

#求1位置索引值 对比预测值索引与label索引是否一样,一样返回True
pred = tf.equal(tf.argmax(actv,1),tf.argmax(y,1))
#tf.cast把True和false转换为float类型 0,1
#把所有预测结果加在一起求精度
accr = tf.reduce_mean(tf.cast(pred,"float"))
init = tf.global_variables_initializer()
"""
#测试代码 
sess = tf.InteractiveSession()
arr = np.array([[31,23,4,24,27,34],[18,3,25,4,5,6],[4,3,2,1,5,67]])
#返回数组的维数 2
print(tf.rank(arr).eval())
#返回数组的行列数 [3 6]
print(tf.shape(arr).eval())
#返回数组中每一列中最大元素的索引[0 0 1 0 0 2]
print(tf.argmax(arr,0).eval())
#返回数组中每一行中最大元素的索引[5 2 5]
print(tf.argmax(arr,1).eval()) 
J"""
#把所有样本迭代50次
training_epochs = 50
#每次迭代选择多少样本
batch_size = 100
display_step = 5

sess = tf.Session()
sess.run(init)

#循环迭代
for epoch in range(training_epochs):
  avg_cost = 0
  num_batch = int(mnist.train.num_examples/batch_size)
  for i in range(num_batch):
    batch_xs,batch_ys = mnist.train.next_batch(batch_size)
    sess.run(optm,feed_dict = {x:batch_xs,y:batch_ys})
    feeds = {x:batch_xs,y:batch_ys}
    avg_cost += sess.run(cost,feed_dict = feeds)/num_batch

  if epoch % display_step ==0:
    feeds_train = {x:batch_xs,y:batch_ys}
    feeds_test = {x:mnist.test.images,y:mnist.test.labels}
    train_acc = sess.run(accr,feed_dict = feeds_train)
    test_acc = sess.run(accr,feed_dict = feeds_test)
    #每五个epoch打印一次信息
    print("Epoch:%03d/%03d cost:%.9f train_acc:%.3f test_acc: %.3f" %(epoch,training_epochs,avg_cost,train_acc,test_acc))

print("Done")

程序训练结果如下:

Epoch:000/050 cost:1.177228655 train_acc:0.800 test_acc: 0.855
Epoch:005/050 cost:0.440933891 train_acc:0.890 test_acc: 0.894
Epoch:010/050 cost:0.383387268 train_acc:0.930 test_acc: 0.905
Epoch:015/050 cost:0.357281335 train_acc:0.930 test_acc: 0.909
Epoch:020/050 cost:0.341473956 train_acc:0.890 test_acc: 0.913
Epoch:025/050 cost:0.330586549 train_acc:0.920 test_acc: 0.915
Epoch:030/050 cost:0.322370980 train_acc:0.870 test_acc: 0.916
Epoch:035/050 cost:0.315942993 train_acc:0.940 test_acc: 0.916
Epoch:040/050 cost:0.310728854 train_acc:0.890 test_acc: 0.917
Epoch:045/050 cost:0.306357428 train_acc:0.870 test_acc: 0.918
Done

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python 生成器协程运算实例
Sep 04 Python
Python发送http请求解析返回json的实例
Mar 26 Python
python实现将读入的多维list转为一维list的方法
Jun 28 Python
浅谈python写入大量文件的问题
Nov 09 Python
对python中dict和json的区别详解
Dec 18 Python
Python Datetime模块和Calendar模块用法实例分析
Apr 15 Python
Python 实现遥感影像波段组合的示例代码
Aug 04 Python
Python使用itchat 功能分析微信好友性别和位置
Aug 05 Python
Python 进程操作之进程间通过队列共享数据,队列Queue简单示例
Oct 11 Python
浅谈pytorch torch.backends.cudnn设置作用
Feb 20 Python
Python实现CAN报文转换工具教程
May 05 Python
Python pip安装模块提示错误解决方案
May 22 Python
Django实现表单验证
Sep 08 #Python
python实现排序算法解析
Sep 08 #Python
TensorFlow实现Logistic回归
Sep 07 #Python
tensorflow实现简单逻辑回归
Sep 07 #Python
Tensorflow使用支持向量机拟合线性回归
Sep 07 #Python
TensorFlow实现iris数据集线性回归
Sep 07 #Python
TensorFlow实现模型评估
Sep 07 #Python
You might like
PHP设计聊天室步步通
2006/10/09 PHP
PHP COOKIE及时生效的方法介绍
2014/02/14 PHP
php 无限级分类,超级简单的无限级分类,支持输出树状图
2014/06/29 PHP
在Win7 中为php扩展配置Xcache
2014/10/08 PHP
javascript实现unicode和字符的互相转换
2007/07/18 Javascript
js限制textarea每行输入字符串长度的代码
2012/10/31 Javascript
js捕获鼠标右键菜单中的粘帖事件实现代码
2013/04/01 Javascript
动态加载js和css(外部文件)
2013/04/17 Javascript
json数据处理技巧(字段带空格、增加字段、排序等等)
2013/06/14 Javascript
jQuery满屏焦点图左右滚动特效代码分享
2015/09/07 Javascript
JS实现状态栏跑马灯文字效果代码
2015/10/24 Javascript
详解JavaScript基于面向对象之继承实例
2015/12/16 Javascript
jquery实现图片放大点击切换
2017/06/06 jQuery
javascript+html5+css3自定义弹出窗口效果
2017/10/26 Javascript
解决Jstree 选中父节点时被禁用的子节点也会选中的问题
2017/12/27 Javascript
vuejs项目打包之后的首屏加载优化及打包之后出现的问题
2018/04/01 Javascript
详解react-redux插件入门
2018/04/19 Javascript
layui在form表单页面通过Validform加入简单验证的方法
2019/09/06 Javascript
JS实现的雪花飘落特效示例
2019/12/03 Javascript
Python基于动态规划算法计算单词距离
2015/07/25 Python
Pycharm之快速定位到某行快捷键的方法
2019/01/20 Python
Django如何防止定时任务并发浅析
2019/05/14 Python
Python Django框架防御CSRF攻击的方法分析
2019/10/18 Python
Django框架序列化与反序列化操作详解
2019/11/01 Python
使用Python实现正态分布、正态分布采样
2019/11/20 Python
Python配置pip国内镜像源的实现
2020/08/20 Python
Python3.9最新版下载与安装图文教程详解(Windows系统为例)
2020/11/28 Python
css3圆角样式分享自定义按钮样式
2013/12/27 HTML / CSS
Jack Rogers官网:美国经典的女性鞋靴品牌
2019/09/04 全球购物
双立人美国官方商店:ZWILLING集团餐具和炊具
2020/05/07 全球购物
大学生职业生涯设计书
2014/01/02 职场文书
上班上网检讨书
2014/01/29 职场文书
给校长的建议书600字
2014/05/15 职场文书
工商管理本科生求职信
2014/07/13 职场文书
python神经网络编程之手写数字识别
2021/05/08 Python
MySQL添加索引特点及优化问题
2022/07/23 MySQL