【Tensorflow笔记】

逻辑回归

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('MNIST_data/',one_hot=true)

x=tf.placeholder(tf.float32,[None,784])
y=tf.placeholder(tf.float32,[None,10])
w=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))
pred=tf.nn.softmax(tf.matmul(x,w)+b)

sess=tf.InteractiveSession()

cost=tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred)))
optimizer=tf.train.GradientDescentOptimizer(0.01).minimize(cost)
corr=tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
accr=tf.reduce_mean(tf.cast(corr,tf.float32))
init=tf.global_variables_initializer()

sess=tf.Session()
sess.run(init)

epoch_n=100
batch_size=64
batch_n=int(mnist.train.num_examples/batch_size)

for epoch in range(epoch_n):
    avg_cost=0
    for _ in range(batch_n):
        batch_xs,batch_ys=mnist.train.next_batch(batch_size)
        feeds={x:batch_xs,y:batch_ys}
        sess.run(optimizer,feed_dict=feeds)
        avg_cost+=sess.run(cost,feed_dict=feeds)/batch_size
    print(avg_cost)

one_hot=true    独热表示:一位有效编码   

                           读取到的mnist lables:   [1,0,0,0,0,0,0,0,0,0]     [0,1,0,0,0,0,0,0,0,0]      [0,0,1,0,0,0,0,0,0,0]  ........

x=tf.placeholder(tf.float32,[None,784])   未赋值,先占位      None 可传任意个数

pred=tf.nn.softmax(tf.matmul(x,w)+b)

猜你喜欢

转载自blog.csdn.net/afeiererer/article/details/82146363
今日推荐