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 smtplib模块实现发送邮件带附件sendmail
May 22 Python
浅谈dataframe中更改列属性的方法
Jul 10 Python
Python3.7 dataclass使用指南小结
Feb 22 Python
python3.6使用tkinter实现弹跳小球游戏
May 09 Python
Python使用type关键字创建类步骤详解
Jul 23 Python
使用TensorFlow-Slim进行图像分类的实现
Dec 31 Python
运行tensorflow python程序,限制对GPU和CPU的占用操作
Feb 06 Python
如何基于Python实现数字类型转换
Feb 07 Python
python实现梯度下降法
Mar 24 Python
如何利用Python写个坦克大战
Nov 18 Python
python用tkinter开发的扫雷游戏
Jun 01 Python
实例讲解Python中sys.argv[]的用法
Jun 03 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
推荐一篇入门级的Class文章
2007/03/19 PHP
简单示例AJAX结合PHP代码实现登录效果代码
2008/07/25 PHP
php之CodeIgniter学习笔记
2013/06/17 PHP
ThinkPHP的Widget扩展实例
2014/06/19 PHP
php商品对比功能代码分享
2015/09/24 PHP
PHP生成随机数的方法总结
2018/03/01 PHP
使用jQuery的ajax功能实现的RSS Reader 代码
2009/09/03 Javascript
JS动态增删表格行的方法
2016/03/03 Javascript
js实现淡入淡出轮播切换功能
2017/01/13 Javascript
js实现百度搜索提示框
2017/02/05 Javascript
vue-resource 拦截器使用详解
2017/02/21 Javascript
详解angular中通过$location获取路径(参数)的写法
2017/03/21 Javascript
JS按钮闪烁功能的实现代码
2017/07/21 Javascript
vue的全局提示框组件实例代码
2018/02/26 Javascript
JS动态插入脚本和插入引用外部链接脚本的方法
2018/05/21 Javascript
vue接入腾讯防水墙代码
2019/05/07 Javascript
vue spa应用中的路由缓存问题与解决方案
2019/05/31 Javascript
vue-cli+iview项目打包上线之后图标不显示问题及解决方法
2019/10/16 Javascript
Python 过滤字符串的技巧,map与itertools.imap
2008/09/06 Python
python字典基本操作实例分析
2015/07/11 Python
python爬虫_自动获取seebug的poc实例
2017/08/05 Python
Python实现识别手写数字 简易图片存储管理系统
2018/01/29 Python
python opencv实现图像边缘检测
2019/04/29 Python
Python3实现定时任务的四种方式
2019/06/03 Python
Tensorflow获取张量Tensor的具体维数实例
2020/01/19 Python
Python for循环通过序列索引迭代过程解析
2020/02/07 Python
Python jieba结巴分词原理及用法解析
2020/11/05 Python
HTML5 Notification(桌面提醒)功能使用实例
2014/03/17 HTML / CSS
跑步爱好者一站式服务网站:Jack Rabbit
2016/09/01 全球购物
来自全球大都市的高级街头服饰:Pegador
2018/01/03 全球购物
策划创业计划书
2014/02/06 职场文书
英语专业自荐书
2014/06/13 职场文书
身边的榜样活动方案
2014/08/20 职场文书
2015年中学校长工作总结
2015/05/19 职场文书
2015年秋季运动会前导词
2015/07/20 职场文书
利用Python实现模拟登录知乎
2022/05/25 Python