博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
机器学习实战:TensorFlow构建逻辑回归模型
阅读量:2052 次
发布时间:2019-04-28

本文共 3140 字,大约阅读时间需要 10 分钟。

import tensorflow as tfimport matplotlib.pyplot as pltfrom tensorflow .examples .tutorials .mnist import input_data#使用MNIST数据集-10个手写体数据,对其进行分类print("Download and Extract MNIST dataset")mnist = input_data .read_data_sets('data/',one_hot=True)trainimg = mnist.train.imagestrainlabel = mnist.train.labelstestimg = mnist.test.imagestestlabel = mnist.test.labelsprint("MNIST loaded")print(trainimg.shape)print(trainlabel.shape)print(testimg.shape)print(testlabel.shape)x = tf.placeholder("float",[None,784])#float表示数据类型,None表示多少个数据,784表示网络中输入层的特征个数y = tf.placeholder("float",[None,10])W = tf.Variable(tf.zeros([784,10]))#W的维度是根据特征个数(784)和该层神经元个数(10)b = tf.Variable(tf.zeros([10]))#逻辑回归解决二分类问题,将之变形为softmaxactv = tf.nn.softmax(tf.matmul(x,W)+b)#损失函数cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(actv),axis=1))'''求最大值tf.reduce_max(input_tensor, reduction_indices=None, keep_dims=False, name=None)求平均值tf.reduce_mean(input_tensor, reduction_indices=None, keep_dims=False, name=None)reduce_sum应该理解为压缩求和,用于降维reduce_sum (     input_tensor ,     axis = None ,     keep_dims = False ,     name = None ,     reduction_indices = None )input_tensor:要减少的张量.应该有数字类型.axis:要减小的尺寸.如果为None(默认),则缩小所有尺寸.必须在范围[-rank(input_tensor), rank(input_tensor))内.0-列求和,1-行求和keep_dims:如果为true,则保留长度为1的缩小尺寸.name:操作的名称(可选).reduction_indices:axis的废弃的名称.'''#梯度下降中需要给的学习率参数值learning_rate = 0.01#tf.train.GradientDescentOptimizer()使用随机梯度下降算法,使参数沿着 梯度的反方向,即总损失减小的方向移动,实现更新参数.里面的参数是步长(学习率)optm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)#训练的过程就是最小化这个误差值#找出每个样本的最大预测值与真正所属是否相同pred = tf.equal(tf.argmax(actv,1),tf.argmax(y,1))'''tf.argmax(input, axis=None, name=None, dimension=None)--返回最大值的索引,从0开始input:输入值axis:0表示按列计算每列最大数的下标,1表示按行计算每行最大数的下标name:名称dimension:和axis功能一样,默认axis取值优先equal(x, y, name=None)equal,相等的意思。顾名思义,就是判断,x, y 是不是相等,它的判断方法不是整体判断,而是逐个元素进行判断,如果相等就是 True,不相等,就是 False。由于是逐个元素判断,所以 x,y 的维度要一致。'''acc = tf.reduce_mean(tf.cast(pred,'float'))'''cast(   x,    dtype,    name=None)将x的数据格式转化成dtype.例如,原来x的数据格式是bool, 那么将其转化成float以后,就能够将其转化成0和1的序列。反之也可以'''init = tf.global_variables_initializer()#逻辑框架已经完成。training_epochs = 50#所有的样本迭代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}) #avg_cost += sess.run(cost,feed_dict={
x:batch_xs,y:batch_ys})/num_batch avg_cost = avg_cost +sess.run(cost,feed_dict={
x:batch_xs,y:batch_ys})#迭代一次时,整个数据集被划分成多个块,for一次循环中是求的每个块的损失 avg_cost = avg_cost /num_batch#这边将所有块的损失求和取平均得到平均损失 if epoch % display_step ==0:#每5个epoch打印一次 feeds_train = {
x:batch_xs,y:batch_ys} feeds_test = {
x:mnist.test.images,y:mnist.test.labels} train_acc = sess.run(acc,feed_dict=feeds_train) test_acc = sess.run(acc,feed_dict=feeds_test) print("Epoch: %03d/%03d cost: %.9f train_acc: %.3f test_acc: %.3f" % ( epoch, training_epochs, avg_cost, train_acc, test_acc))print("DONE")

转载地址:http://sfulf.baihongyu.com/

你可能感兴趣的文章
(PAT 1096) Consecutive Factors (质因子分解)
查看>>
(PAT 1019) General Palindromic Number (进制转换)
查看>>
(PAT 1073) Scientific Notation (字符串模拟题)
查看>>
(PAT 1080) Graduate Admission (排序)
查看>>
Play on Words UVA - 10129 (欧拉路径)
查看>>
mininet+floodlight搭建sdn环境并创建简答topo
查看>>
【UML】《Theach yourself uml in 24hours》——hour2&hour3
查看>>
【linux】nohup和&的作用
查看>>
【UML】《Theach yourself uml in 24hours》——hour4
查看>>
Set、WeakSet、Map以及WeakMap结构基本知识点
查看>>
【NLP学习笔记】(一)Gensim基本使用方法
查看>>
【NLP学习笔记】(二)gensim使用之Topics and Transformations
查看>>
【深度学习】LSTM的架构及公式
查看>>
【深度学习】GRU的结构图及公式
查看>>
【python】re模块常用方法
查看>>
剑指offer 19.二叉树的镜像
查看>>
剑指offer 20.顺时针打印矩阵
查看>>
剑指offer 21.包含min函数的栈
查看>>
剑指offer 23.从上往下打印二叉树
查看>>
剑指offer 25.二叉树中和为某一值的路径
查看>>