Tensorflow案例实战-07逻辑回归模型

该博客介绍了使用TensorFlow实现逻辑回归模型的过程,包括导入MNIST数据集、模型定义、构建逻辑回归框架、进行测试及迭代优化。训练结果显示模型表现良好。
摘要由CSDN通过智能技术生成

导入minst数据集

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import input_data
minst=input_data.read_data_sets('data/',one_hot=True)

导入成功

定义

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

逻辑回归模型框架

#x,y先不赋值 784个像素点,10个分类,None是无穷
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]))
#softmax传进去属于0-10哪一个数字的分值大
actv=tf.nn.softmax(tf.matmul(x,W)+b)
#cost function :-log(P),P:属于真实值的概率
cost=tf.reduce_mean(-tf.reduce_sum(y*tf.log(actv),reduction_indices=1))
#optimizer
learning_rate=0.01
optm=tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

测试

#prediction
pred=tf.equal(tf.argmax(actv,1),tf.argmax(y,1))
#accuracy
accr=tf.reduce_mean(tf.cast(pred,"float"))
#initializer
init=tf.global_variables_initializer()

迭代

#样本迭代50次,每次选择100个样本
training_epochs=50
batch_size=100
display_step=5
#session
sess=tf.Session()
sess.run(init)
#mini-batch leaning
for epoch in range(training_epochs):
    avg_cost=0
    num_batch=int(minst.train.num_examples/batch_size)
    for i in range(num_batch):
        batch_xs,batch_ys=minst.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
    #display
    if epoch % display_step==0:
        feeds_train={x:batch_xs,y:batch_ys}
        feeds_test={x:minst.test.images,y:minst.test.labels}
        train_acc=sess.run(accr,feed_dict=feeds_train)
        test_acc=sess.run(accr,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")

从结果看训练效果还不错:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值