TensorFlow实现 Logistic Regression

来源:互联网 发布:衣裤尺码软件 编辑:程序博客网 时间:2024/05/20 20:18

下面是用TensorFlow实现Logistic Regression,步骤都做了标注,不详细说了。

#encoding:utf-8import tensorflow as tf# 装在MNIST数据from tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets("MNIST_Data/data/", one_hot=True)# 一些参数learning_rate = 0.01training_epochs = 25batch_size = 100display_step = 1# tf Graph Inputx = tf.placeholder(tf.float32, [None, 784]) # mnist图像数据 28*28=784y = tf.placeholder(tf.float32, [None, 10]) # 图像类别,总共10类# 设置模型参数变量w和bW = tf.Variable(tf.zeros([784, 10]))b = tf.Variable(tf.zeros([10]))# 构建softmax模型pred = tf.nn.softmax(tf.matmul(x, W) + b)# 损失函数用cross entropycost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))# 梯度下降优化optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)# 初始化所有变量init = tf.initialize_all_variables()# Launch the graphwith tf.Session() as sess:    sess.run(init)    # Training cycle    for epoch in range(training_epochs):        avg_cost = 0.        total_batch = int(mnist.train.num_examples/batch_size)        # 每一轮迭代total_batches        for i in range(total_batch):            batch_xs, batch_ys = mnist.train.next_batch(batch_size)            # 使用batch data训练数据            _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,                                                          y: batch_ys})            # 将每个batch的损失相加求平均            avg_cost += c / total_batch        # 每一轮打印损失        if (epoch+1) % display_step == 0:            print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)    print "Optimization Finished!"    # 模型预测    # tf.argmax(pred,axis=1)是预测值每一行最大值的索引,这里最大值是概率最大    # tf.argmax(y,axis=1)是真实值的每一行最大值得索引,这里最大值就是1    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))    # 对3000个数据预测准确率    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))    print "Accuracy:", accuracy.eval({x: mnist.test.images[:3000], y: mnist.test.labels[:3000]})

这里说下accuracy.eval()函数的作用:

f.Tensor.eval(feed_dict=None, session=None):

作用:
在一个Seesion里面“评估”tensor的值(其实就是计算),首先执行之前的所有必要的操作来产生这个计算这个tensor需要的输入,然后通过这些输入产生这个tensor。在激发tensor.eval()这个函数之前,tensor的图必须已经投入到session里面,或者一个默认的session是有效的,或者显式指定session.
参数:
feed_dict:一个字典,用来表示tensor被feed的值(联系placeholder一起看)
session:(可选) 用来计算(evaluate)这个tensor的session.要是没有指定的话,那么就会使用默认的session。
返回:
表示“计算”结果值的numpy ndarray

0 0
原创粉丝点击