Tensorflow逻辑回归(Case 2)

import os   #设置使用机器的gpu
os.environ["CUDA_VISIBLE_DEVICES"] = "2"

#import os   #设置使用机器的cpu
#os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"  
#os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import time
mnist=input_data.read_data_sets('/data/mnist',one_hot=True)

在这里插入图片描述

mnist.train.images.shape, mnist.train.labels.shape
# ((55000, 784), (55000, 10))
batch_size=16
X=tf.placeholder(tf.float32, [batch_size, 784], name='X_placeholder')
Y=tf.placeholder(tf.float32, [batch_size, 10], name='Y_placeholder')
w=tf.get_variable('weights', initializer=tf.random_normal(shape=[784, 10], stddev=0.01))
b=tf.get_variable('bias', initializer=tf.zeros([1, 10]))
final=tf.matmul(X, w)+ b
entropy=tf.nn.softmax_cross_entropy_with_logits(logits=final, labels=Y, name='loss')
loss=tf.reduce_mean(entropy)
learning_rate=0.01
optimizer=tf.train.AdamOptimizer(learning_rate).minimize(loss)
# 测试模型的图
preds=tf.nn.softmax(final)
correct_preds=tf.equal(tf.argmax(preds,1), tf.argmax(Y,1))
accuracy=tf.reduce_sum(tf.cast(correct_preds, tf.float32))
import random
def batch_iter(x,y,batch_size=16):   #手动划分batch
    data_len=len(x)
    num_batch=data_len // batch_size
    data_len=num_batch * batch_size
    x=x[:data_len]
    y=y[:data_len]
    data=list(zip(x,y))
    random.shuffle(data)
    x_shuffle,y_shuffle=zip(*data)
    
    for i in range(num_batch):
        start_id=i * batch_size
        end_id=min((i+1) * batch_size, data_len)
        yield list(x_shuffle)[start_id:end_id], list(y_shuffle)[start_id:end_id]

只有两类0/1的对数损失:
− 1 N ∑ i = 1 N ( y i l o g p i + ( 1 − y i ) l o g ( 1 − p i ) ) \displaystyle -\frac{1}{N}\sum_{i=1}^N \big(y_i log p_i + (1-y_i)log(1- p_i)\big) N1i=1N(yilogpi+(1yi)log(1pi))

n_epochs=10
with tf.Session() as sess:   
    writer=tf.summary.FileWriter('./graphs/logistic_reg_train', sess.graph)
    start=time.time()
    sess.run(tf.global_variables_initializer())
    
    n_batches=int(mnist.train.num_examples/batch_size)
    for i in range(n_epochs):
        total_loss=0
        for X_batch,Y_batch in batch_iter(mnist.train.images, mnist.train.labels):   ###
            _,loss_batch=sess.run([optimizer,loss],feed_dict={X:X_batch,Y:Y_batch})   #一个batch优化更新一次loss
            total_loss+=loss_batch
        print('Average loss epoch {0}:{1}'.format(i,total_loss/n_batches))
    print('Time:{0} seconds'.format(time.time()-start))
    print(sess.run([w,b]))
    
    n_batches=int(mnist.test.num_examples/batch_size)   #测试集
    total_correct_preds=0
    for X_batch,Y_batch in batch_iter(mnist.test.images, mnist.test.labels):
        accuracy_batch=sess.run([accuracy],feed_dict={X:X_batch,Y:Y_batch})
        total_correct_preds+=accuracy_batch[0]
    print('Accuracy {0}'.format(total_correct_preds/mnist.test.num_examples))
    
    writer.close()

在这里插入图片描述

# 针对mnist数据集的分batch特殊写法

n_epochs=10
with tf.Session() as sess:   
    writer=tf.summary.FileWriter('./graphs/logistic_reg_train', sess.graph)
    start=time.time()
    sess.run(tf.global_variables_initializer())
    
    n_batches=int(mnist.train.num_examples/batch_size)
    for i in range(n_epochs):
        total_loss=0
        for _ in range(n_batches):
            X_batch,Y_batch=mnist.train.next_batch(batch_size)   ###
            _,loss_batch=sess.run([optimizer,loss],feed_dict={X:X_batch,Y:Y_batch})   #一个batch优化更新一次loss
            total_loss+=loss_batch
        print('Average loss epoch {0}:{1}'.format(i,total_loss/n_batches))
    print('Time:{0} seconds'.format(time.time()-start))
    print(sess.run([w,b]))
    
    n_batches=int(mnist.test.num_examples/batch_size)   #测试集
    total_correct_preds=0
    for i in range(n_batches):
        X_batch,Y_batch=mnist.test.next_batch(batch_size)
        accuracy_batch=sess.run([accuracy],feed_dict={X:X_batch,Y:Y_batch})
        total_correct_preds+=accuracy_batch[0]
    print('Accuracy {0}'.format(total_correct_preds/mnist.test.num_examples))
    
    writer.close()

cmd=> tensorboard --logdir=“C:\Users\86151\TensorFlow\graphs”
浏览器输入=> localhost:6006
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值