tensorflow实现逻辑回归模型
作者:Missayaa 发布时间:2022-01-18 20:10:28
标签:tensorflow,逻辑回归
逻辑回归模型
逻辑回归是应用非常广泛的一个分类机器学习算法,它将数据拟合到一个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
来源:https://blog.csdn.net/Missayaaa/article/details/80063512


猜你喜欢
- 原来工作中曾经碰到过UL列表里一些异常的表现,加上昨天看到了http://bbs.blueidea.com/thread-2984871-1
- 终端输出彩色文字开发工具:Mac,Goland,Mac自带shell。这是基于Mac的测试结果,根据读者留言,在Windows上不生效,标识
- close()方法方法关闭打开的文件。关闭的文件无法读取或写入更多东西。文件已被关闭之后任何操作会引发ValueError。但是
- Paddle模型性能分析Profiler定位性能瓶颈点优化程序提升性能Paddle Profiler是飞桨框架自带的低开销性能分析器,可以对
- 1.默认已经有python环境和vscode2.pip安装PyQt5执行命令:pip install PyQt5pip install Py
- json的作用JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式json.dumps(): 对数
- 以下为引用的内容:DROP PROCEDURE test_insert ;DELIMITER ;;CREATE PROCEDURE test
- 配置日志在Django中,可以通过logging模块来记录日志。日志记录器是将日志消息传递给日志处理器的对象。当需要记录日志时,可以使用以下
- 最近脱离了googlecolab想使用本地的anaconda进行机器学习课题的演练,在安装tensorflow时报错 : Unsatisfi
- 假设三节点MGR某个节点异常,需要重新把这个节点加入到MGR集群中,具体操作过程如下:贡献者端执行(192.168.1.11)DROP US
- 新手小白,一直在为cmd窗口的暗白色文字感到苦恼,在网上找了许多方法(也就那两种吐舌头),现在稍微整理了一下,便于使用。效果图:import
- Python函数函数就是把具有独立功能的代码块封装成一个小模块,可以直接调用,从而提高代码的编写效率以及重用性, 需要注意的是, 函数需要被
- 1. 随机数np.random.random()是最常用的随机数生成函数,该函数生成的随机数随机均匀分布于[0, 1)区间。如果不提供参数,
- 相信大家都知道jQuery是最优秀的Javascript框架之一。以其语法简单灵活而大受Web designer欢迎。所以很多网页设计师结合
- 一、概述OLAP的系统(即Online Aanalyse Process)一般用于系统决策使用。通常和数据仓库、数据分析、数据挖掘等概念联系
- 在给客户做个程序时,突然遇到个问题,就是产品页用户提交视频播放文件时,如何根据提交的网址内的视频格式进行正确的播放呢....郁闷了一会,想好
- 文件下载1.通过a标签点击直接下载<a href="https:xxx.xlsx" rel="exter
- SQLPrompt是Sql Server 开发智能提示插件,方便查询表结果,避免了开发人员一个个敲查询语句、执行语句等,下面带大家仔细了解一
- original article by sp(’Sergio Pereira’) Sergio Pereiralast update: Ma
- 目录Pyppeteer 是什么Pyppeteer能做什么截图导出PDF公众号链接导出PDF示例Pyppeteer 是什么介绍 Pyppete