生活随笔
收集整理的這篇文章主要介紹了
逻辑回归实现多分类任务(python+TensorFlow+mnist)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
邏輯回歸實現多分類任務(python+TensorFlow+mnist)
? ? ? ?邏輯回歸是統計學中的一種經典方法,雖然叫回歸,但在機器學習領域,邏輯回歸通常情況下當成一個分類任務,softmax就是由其演變而來,邏輯回歸一般用于二分類任務,但通過softmax可以輕易的擴展至多分類任務。
下面的程序,通過邏輯回歸實現對手寫數字的分類:
- 環境:python3.6、TensorFlow框架
- 數據集:MNIST
# 邏輯回歸實現手寫數字分類
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
import matplotlib.pyplot as pltmnist = input_data.read_data_sets('D:\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]), tf.float32)
b = tf.Variable(tf.zeros([10]), tf.float32)
pre = tf.nn.softmax(tf.matmul(x, W) + b)
# cost function
cost = tf.reduce_mean(tf.reduce_sum(-y*tf.log(pre), reduction_indices=1))
train = tf.train.GradientDescentOptimizer(0.01).minimize(cost)
pred = tf.equal(tf.argmax(y, 1), tf.argmax(pre, 1))
# accuracy
acc = tf.reduce_mean(tf.cast(pred, tf.float32))# initializer
init = tf.global_variables_initializer()
batch_size = 100
display_step = 5
step = 100
with tf.Session() as sess:sess.run(init)num_batch = int(mnist.train.num_examples/batch_size)for i in range(step):for j in range(num_batch):batch_xs, batch_ys = mnist.train.next_batch(100)sess.run(train, feed_dict={x: batch_xs, y: batch_ys})if i % display_step == 0:train_acc = sess.run(acc, feed_dict={x: batch_xs, y: batch_ys})test_acc = sess.run(acc, feed_dict={x: mnist.test.images, y: mnist.test.labels})print('Train accuracy:%2f'% train_acc, ' Test accuracy:%2f' % test_acc)
訓練100次之后的測試精度為:
Train accuracy:0.940000 Test accuracy:0.921500
?
?
總結
以上是生活随笔為你收集整理的逻辑回归实现多分类任务(python+TensorFlow+mnist)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。