溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

TensorFlow實現(xiàn)Logistic回歸

發(fā)布時間:2020-09-13 12:02:03 來源:腳本之家 閱讀:190 作者:不凡De老五 欄目:開發(fā)技術

本文實例為大家分享了TensorFlow實現(xiàn)Logistic回歸的具體代碼,供大家參考,具體內容如下

1.導入模塊

import numpy as np
import pandas as pd
from pandas import Series,DataFrame

from matplotlib import pyplot as plt
%matplotlib inline

#導入tensorflow
import tensorflow as tf

#導入MNIST(手寫數(shù)字數(shù)據(jù)集)
from tensorflow.examples.tutorials.mnist import input_data

2.獲取訓練數(shù)據(jù)和測試數(shù)據(jù)

import ssl 
ssl._create_default_https_context = ssl._create_unverified_context

mnist = input_data.read_data_sets('./TensorFlow',one_hot=True)

test = mnist.test
test_images = test.images

train = mnist.train
images = train.images


3.模擬線性方程

#創(chuàng)建占矩陣位符X,Y
X = tf.placeholder(tf.float32,shape=[None,784])
Y = tf.placeholder(tf.float32,shape=[None,10])

#隨機生成斜率W和截距b
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

#根據(jù)模擬線性方程得出預測值
y_pre = tf.matmul(X,W)+b

#將預測值結果概率化
y_pre_r = tf.nn.softmax(y_pre)

4.構造損失函數(shù)

# -y*tf.log(y_pre_r) --->-Pi*log(Pi)  信息熵公式

cost = tf.reduce_mean(-tf.reduce_sum(Y*tf.log(y_pre_r),axis=1))

5.實現(xiàn)梯度下降,獲取最小損失函數(shù)

#learning_rate:學習率,是進行訓練時在最陡的梯度方向上所采取的「步」長;
learning_rate = 0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

6.TensorFlow初始化,并進行訓練

#定義相關參數(shù)

#訓練循環(huán)次數(shù)
training_epochs = 25
#batch 一批,每次訓練給算法10個數(shù)據(jù)
batch_size = 10
#每隔5次,打印輸出運算的結果
display_step = 5


#預定義初始化
init = tf.global_variables_initializer()

#開始訓練
with tf.Session() as sess:
  #初始化
  sess.run(init)
  #循環(huán)訓練次數(shù)
  for epoch in range(training_epochs):
    avg_cost = 0.
    #總訓練批次total_batch =訓練總樣本量/每批次樣本數(shù)量
    total_batch = int(train.num_examples/batch_size)
    for i in range(total_batch):
      #每次取出100個數(shù)據(jù)作為訓練數(shù)據(jù)
      batch_xs,batch_ys = mnist.train.next_batch(batch_size)
      _, c = sess.run([optimizer,cost],feed_dict={X:batch_xs,Y:batch_ys})
      avg_cost +=c/total_batch
    if(epoch+1)%display_step == 0:
      print(batch_xs.shape,batch_ys.shape)
      print('epoch:','%04d'%(epoch+1),'cost=','{:.9f}'.format(avg_cost))
  print('Optimization Finished!')

  #7.評估效果
  # Test model
  correct_prediction = tf.equal(tf.argmax(y_pre_r,1),tf.argmax(Y,1))
  # Calculate accuracy for 3000 examples
  # tf.cast類型轉換
  accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
  print("Accuracy:",accuracy.eval({X: mnist.test.images[:3000], Y: mnist.test.labels[:3000]}))

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI