Tensorflow深度学习应用(进阶篇)-1
生活随笔
收集整理的這篇文章主要介紹了
Tensorflow深度学习应用(进阶篇)-1
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
#coding=gbk'''
邏輯回歸:邏輯回歸需要將輸出控制在[0,1]之間,可以使用函數(shù)將值映射在[0,1]之間Sigmod函數(shù),邏輯回歸一般采用對數(shù)損失函數(shù);
'''
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] #設(shè)置顯示繪圖顯示中文
mpl.rcParams['axes.unicode_minus'] = False #防止中文亂碼,有時(shí)候第一句不能完全避免顯示錯(cuò)誤#導(dǎo)入tensorflow 模塊
import tensorflow.compat.v1 as tf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.datasets import load_boston
from sklearn.utils import shuffleimport tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)print("訓(xùn)練集:", mnist.train.num_examples,"測試集:", mnist.test.num_examples,"驗(yàn)證集", mnist.validation.num_examples)print("Image shape:", mnist.train.images.shape,"labels shape:",mnist.train.labels.shape)
'''運(yùn)行結(jié)果:
訓(xùn)練集: 55000 測試集: 10000 驗(yàn)證集 5000
Image shape: (55000, 784) labels shape: (55000, 10)
分析:圖像數(shù)據(jù),有55000條數(shù)據(jù),每條特征有784個(gè)(28x28的灰度圖,只有一個(gè)顏色通道)標(biāo)簽圖像數(shù)據(jù):有55000條,每條長度為10(one_hot編碼的數(shù)據(jù))
'''#顯示圖像函數(shù)定義
def plot_image(image):plt.imshow(image.reshape(28, 28), cmap='binary')plt.show()plot_image(mnist.train.images[3])
print(mnist.train.labels[3])
'''
顯示數(shù)字6;
[0. 0. 0. 0. 0. 0. 1. 0. 0. 0.],對應(yīng)的標(biāo)簽,為1的代表數(shù)字6這種編碼方式是one_hot獨(dú)熱編碼方式
'''#取得獨(dú)熱編碼的值,若one_hot設(shè)置為False,則標(biāo)簽中就直接為值
val = np.argmax(mnist.train.labels[3])#獲取編碼對應(yīng)的值,
print(val) #值為數(shù)字6#數(shù)據(jù)集的劃分,可以將數(shù)據(jù)分為訓(xùn)練集,測試集,驗(yàn)證集,可以大幅度減低過擬合的發(fā)生幾率#數(shù)據(jù)的批量讀取
mnist.train.images[0:10]#切片
batch_images_xs, batch_labels_ys = \mnist.train.next_batch(batch_size=10) #自動移動x = tf.placeholder(tf.float32, [None, 784], name='x')
y = tf.placeholder(tf.float32, [None, 10], name='y')
w = tf.Variable(tf.random_normal([784, 10], name='w'))#正態(tài)隨機(jī)數(shù)初始化
b = tf.Variable(tf.zeros([10], name='b'))#前向計(jì)算
f = tf.matmul(x, w) + b#計(jì)算結(jié)果分類,表示為哪一類的概率值,將值控制在[0,1]之間
p = tf.nn.softmax(f)#模型構(gòu)建
train_c = 80
#批量數(shù)據(jù)大小
b_size = 100
#全部需要幾個(gè)批次訓(xùn)練一次
total_b_size = int(mnist.train.num_examples / b_size)
step = 1
learning_rate = 0.01#損失函數(shù)(交叉熵?fù)p失函數(shù))
loss_Fun = tf.reduce_mean(-tf.reduce_sum(y * tf.log(p), reduction_indices=1))
#優(yōu)化器
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss_Fun)
#檢查預(yù)測類別tf.argmax(p,1)與實(shí)際類別tf.argmax(y,1)的匹配情況
correct_prediction = tf.equal(tf.argmax(p, 1), tf.argmax(y, 1))#準(zhǔn)確率,將bool轉(zhuǎn)換為浮點(diǎn)數(shù),計(jì)算平均值
ave = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)for i in range(train_c):for batch in range(total_b_size):x_, y_ = mnist.train.next_batch(b_size)sess.run(optimizer, feed_dict={x: x_, y: y_})#使用驗(yàn)證數(shù)據(jù)集計(jì)算誤差與準(zhǔn)確率loss, acc = sess.run([loss_Fun, ave], feed_dict={x: mnist.validation.images, y: mnist.validation.labels})print("Train count:", i + 1, "Loss=", "{:.9f}".format(loss), "acc=", "{:.4f}".format(acc))
print("訓(xùn)練結(jié)束!")#模型運(yùn)用
Predict_Result = sess.run(tf.argmax(p, 1), feed_dict={x: mnist.test.images})
print(Predict_Result[0:10])def plot_Result(images, labels, prediction, index, num=10):fig = plt.gcf()fig.set_size_inches(10, 12)if num > 25:num = 25for i in range(0, num):ax = plt.subplot(5, 5, i + 1)ax.imshow(np.reshape(images[index], (28, 28)), cmap='binary')title = "label=" + str(np.argmax(labels[index]))if len(prediction) > 0:title += ",predict=" + str(prediction[index])ax.set_title(title, fontsize=10)#不顯示坐標(biāo)軸ax.set_xticks([])ax.set_yticks([])index += 1plt.show()plot_Result(mnist.test.images,mnist.test.labels,Predict_Result,10,10)
附:
本文章學(xué)習(xí)自中國大學(xué)mooc-深度學(xué)習(xí)應(yīng)用開發(fā)-Tensorflow實(shí)戰(zhàn)
總結(jié)
以上是生活随笔為你收集整理的Tensorflow深度学习应用(进阶篇)-1的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机网络物理层-编码技术实现
- 下一篇: Tensorflow深度学习应用(进阶篇