1. 程式人生 > >TensorFlow學習筆記(1):最簡單的入門程式

TensorFlow學習筆記(1):最簡單的入門程式

1、Polynomial Regression

1.準備好資料、placeholder、Variable

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

n_examples = 300
xs = np.linspace(-3, 3, n_examples)
ys = np.sin(xs) + np.random.uniform(-0.5, 0.5, n_examples)

X = tf.placeholder(tf.float32, name='X')
Y = tf.placeholder(tf.float32, name='Y'
) W = tf.Variable(tf.random_normal([1]), name='W') W_2 = tf.Variable(tf.random_normal([1], name='W_2')) W_3 = tf.Variable(tf.random_normal([1]), name='W_3') b = tf.Variable(tf.random_normal([1]), name='b')

2.定義預測結果、損失函式值、優化方法

y_ = tf.add(tf.multiply(X,W),b)
y_ = tf.add(y_, tf.multiply(tf.pow(X,2
),W_2)) y_ = tf.add(y_, tf.multiply(tf.pow(X,3),W_3)) n_samples = xs.shape[0] loss = tf.reduce_sum(tf.square(Y-y_))/n_samples learning_rate = 0.03 optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)

3.在Session中執行Graph

with tf.Session() as sess:
    writer = tf.summary.FileWriter('./graphs/polynomial_reg'
,sess.graph) sess.run(tf.global_variables_initializer()) for i in range (201): total_loss = 0 for x,y in zip(xs, ys): _,l = sess.run([optimizer, loss],feed_dict={X:x, Y:y}) total_loss += l if i%20 == 0: print('Epoch{0}:{1}'.format(i,total_loss/n_samples)) writer.close() W,W_2,W_3,b = sess.run([W,W_2,W_3,b])

4.繪圖檢視結果

plt.plot(xs,ys,'bo',label='Real Data')
plt.plot(xs,xs*W+np.power(xs,2)*W_2+np.power(xs,3)*W_3+b,'r-',lw=5,label='Predicted Data')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Polynomial Regression')
plt.show()

這裡寫圖片描述
5.檢視Tensorboard中的Graph
開啟cmd,在終端輸入

$ python [yourprogram].py
$ tensorboard --logdir=./graphs/polynomial_reg

2、用Logistic Regression做MNIST手寫數字識別

1.準備好資料、placeholder、Variable

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

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

batch_size = 128
X = tf.placeholder(tf.float32,[batch_size,784],name='X_placeholder')
Y = tf.placeholder(tf.int16,[batch_size,10],name='Y_placeholder')

W = tf.Variable(tf.random_normal(shape=[784,10],stddev=0.01),name='weight')
b = tf.Variable(tf.zeros([1,10]),name='bias')

2.定義loss、optimizer

logits = tf.add(tf.matmul(X,W),b)
entropy = tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = Y, name = 'entropy')
loss = tf.reduce_mean(entropy)

learning_rate = 0.03
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)

3.在Session中執行Graph

n_epochs = 30
with tf.Session() as sess:
    writer = tf.summary.FileWriter('./graphs/logistic_reg2',sess.graph)
    start_time = time.time()
    sess.run(tf.global_variables_initializer())
    n_batchs = int(mnist.train.num_examples/batch_size)
    for i in range(n_epochs):
        total_loss = 0
        for _ in range (n_batchs):
            X_batch,Y_batch = mnist.train.next_batch(batch_size)
            _, loss_batch = sess.run([optimizer, loss],feed_dict={X:X_batch,Y:Y_batch})
            total_loss += loss_batch
        print('Average loss in a batch (Epoch {0}): {1}'.format(i,total_loss/n_batchs))
    print('Total time: {0} seconds '.format(time.time() - start_time))
    print('Optimization Done!')

    preds = tf.nn.softmax(logits)
    isCorrect_preds = tf.equal(tf.argmax(preds,1),tf.argmax(Y,1))
    accuracy = tf.reduce_sum(tf.cast(isCorrect_preds,tf.float32))

    n_batchs = int(mnist.test.num_examples/batch_size)
    total_correct_preds = 0
    for i in range(n_batchs):
        X_batch,Y_batch = mnist.test.next_batch(batch_size)
        accuracy_batch = sess.run([accuracy],feed_dict={X:X_batch,Y:Y_batch})
        total_correct_preds += accuracy_batch[0]
    print('Accuracy: {0}'.format(total_correct_preds/mnist.test.num_examples))
    writer.close()

正確率在0.9左右。

3、用DNN做MNIST手寫數字識別

1.準備好資料、placeholder、Variable

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

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

X = tf.placeholder(tf.float32,[None,784],name='X_placeholder')
Y = tf.placeholder(tf.int8,[None,10],name='Y_placeholder')
n_input = 784
n_hidden_1 = 256
n_hidden_2 = 256
n_hidden_3 = 256
n_output = 10
Weights = {'h1':tf.Variable(tf.random_normal([n_input,n_hidden_1]),name='W1'),
           'h2':tf.Variable(tf.random_normal([n_hidden_1,n_hidden_2]),name='W2'),
           'h3':tf.Variable(tf.random_normal([n_hidden_2,n_hidden_3]),name='W3'),
           'out':tf.Variable(tf.random_normal([n_hidden_3,n_output]),name='W4')}
biases = {'b1':tf.Variable(tf.random_normal([n_hidden_1]),name='b1'),
          'b2':tf.Variable(tf.random_normal([n_hidden_2]),name='b2'),
          'b3':tf.Variable(tf.random_normal([n_hidden_3]),name='b3'),
          'out':tf.Variable(tf.random_normal([n_output]),name='b4')}

2.定義loss、optimizer

def multilayer_perceptron(x, weights, biases):
    layer_1 = tf.add(tf.matmul(x, weights['h1']),biases['b1'])
    layer_1 = tf.nn.relu(layer_1)
    layer_2 = tf.add(tf.matmul(layer_1,weights['h2']),biases['b2'])
    layer_2 = tf.nn.relu(layer_2)
    layer_3 = tf.add(tf.matmul(layer_2,weights['h3']),biases['b3'])
    layer_3 = tf.nn.relu(layer_3)
    output_layer = tf.add(tf.matmul(layer_3,weights['out']),biases['out'])
    return output_layer

logits = multilayer_perceptron(X, Weights, biases)
entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=Y,name='entropy')
loss = tf.reduce_mean(entropy)
learning_rate = 0.003
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)

3.在Session中執行Graph

batch_size = 128
n_epochs = 51
n_batchs = int(mnist.train.num_examples/batch_size)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    writer = tf.summary.FileWriter('./graphs/MLP_DNN',sess.graph)
    for i in range (n_epochs):
        avg_loss = 0
        for _ in range (n_batchs):
            x_batch,y_batch = mnist.train.next_batch(batch_size)
            _,l = sess.run([optimizer,loss],feed_dict={X:x_batch,Y:y_batch})
            avg_loss += l / n_batchs
        if i%5 == 0:
            print('Epoch {0}: avg_loss = {1}'.format(i,avg_loss))
    print('Optimization Done!')
    isCorrect = tf.equal(tf.argmax(logits,1),tf.argmax(Y,1))
    accuracy = tf.reduce_mean(tf.cast(isCorrect,tf.float32))
    print('Accuracy: {0}'.format(accuracy.eval({X:mnist.test.images,Y:mnist.test.labels})))
    writer.close()

試了一下,兩個隱層的DNN正確率可達96%,三個隱層的DNN正確率可達97%。

相關推薦

TensorFlow學習筆記(1)簡單入門程式

1、Polynomial Regression 1.準備好資料、placeholder、Variable import numpy as np import tensorflow as tf import matplotlib.pyplot as plt

誠信線上私網申博包殺網 Tensorflow學習筆記1Get Started

█直接聯絡電話:18475600009█微信:18475600009 Tensorflow學習筆記1:Get Started 關於Tensorflow的基本介紹 Tensorflow是一個基於圖的計算系統,其主要應用於機器學習。 從Tensorflow名字的字面意思可以拆分成兩部

Sigmaplot學習筆記1——製作簡單的柱狀圖

什麼!居然是英文版。。。 然而搞科學研究不懂英文怎麼行呢? 製作最簡單的柱狀圖 開啟Sigmaplot14,建立空白資料表,點選OK 將資料複製或者輸入到表格中,不用管此時資料後面的4位小數,製圖時,年份後小數自動消失   點選簡單垂直柱狀圖

tensorflow學習筆記1tf.Variable、tf.get_variable與tf.get_variable、tf.variable_scope對比總結

** 0. 淺談tensorflow變數機制 ** tensorflow提供了通過變數名稱來建立或者獲取一個變數的機制。通過這個機制,在不同的函式中可以直接通過變數的名字來使用變數,而不需要將變數通過引數的形式到處傳遞,實現了變數共享。 ** 1. 對比tf.V

斯坦福CS20 TensorFlow學習筆記(1)Overview of Tensorflow

     斯坦福CS20 TensorFlow學習筆記(1):Overview of Tensorflow 1- TensorFlow是什麼? Google官方的介紹是: TensorFlow™ is an open source software

MyBatis學習記錄(1)牛刀小試,入門程式

終於開始學習三大框架了,首先從MyBatis入手。上學期學過一段時間Hibernate,不過學的並不好,當時被那些表之間的一對多,多對多關係搞的暈頭轉向。最後期末考試還好是四個人一組做課程設計,我就抱大腿了。 今天學MyBatis,感覺比Hibernate好上

1、spring-boot學習筆記(一)簡單入門

ava project nal run plugin mailto 5.4 安全 class a 一、新建普通Maven工程 pom.xml <parent> <groupId>org.springframework.boot</gr

Python學習筆記1簡單實現ssh客戶端和服務端

bsp dev bre 客戶端 break 基於 bin listen 客戶 實現基於python 3.6。 server端: 1 __author__ = "PyDev2018" 2 3 import socket,os 4 server = socket.s

Python3學習筆記1變量和簡單數據類型

tle 小數點 per port 小數 指導 day this python 2018-09-16 17:22:11 變量聲明:   變量名 = ?? 如: 1 message = "HelloWorld" 2 message = 1 3 message =

Docker學習筆記1入門使用

一、Docker簡介 Docker (訪問官網) 是一個開源的應用容器引擎,讓開發者可以打包他們的應用以及依賴包到一個可移植的容器中,然後釋出到任何流行的 Linux 機器上,也可以實現虛擬化。容器是完全使用沙箱機制,相互之間不會有任何介面。(以上資訊來源於百度百科)好吧,讀完之後,

tensorflow學習筆記1:影象資料的一些簡單操作

        博主學習TensorFlow不久,學習路上也是遇到不少問題。所以決定寫一個系列的學習筆記,算是記錄下學習歷程,方便以後翻閱。當然如果可以幫助到一些新手的話就更好了,高手請繞道。 1.影象資料的採集:     &nbs

TensorFlow學習筆記(1) TensorFlow入門

一、TensorFlow計算模型——計算圖(Computational Graph) TensorFlow——Tensor和Flow。Tensor意為張量,可以理解為多維陣列。Flow意為流,表達了張量之間通過計算相互轉化的過程。TensorFlow中每一個計算都是計算圖上的一個節點,節點之間的

ITK學習筆記1從一個簡單的例子出發學習ITK

看完東靈的vtk的相關教程,接下來就是對itk的學習了。不過網上itk的學習資源還是零零散散的,還是需要自己進行整合。 專案地址: Alxemade/ITKLearning 1. 參考資源 CSDN: ljp1919的專欄-ITK學習筆記 CSDN:

opencv-python 學習筆記1簡單的圖片處理

# -*- coding: utf-8 -*- """ @xiaowuyi:http://www.cnblogs.com/xiaowuyi """ import cv2 img=cv2.imread('1.jpg',cv2.IMREAD_COLOR)# 讀入彩色圖片 cv2.imsho

tensorflow學習筆記(三)實現自編碼器

sea start ear var logs cos soft 編碼 red 黃文堅的tensorflow實戰一書中的第四章,講述了tensorflow實現多層感知機。Hiton早年提出過自編碼器的非監督學習算法,書中的代碼給出了一個隱藏層的神經網絡,本人擴展到了多層,改進

Effictive Java學習筆記1創建和銷毀對象

安全 需要 () 函數 調用 bsp nbsp bean 成了 建議1:考慮用靜態工廠方法代替構造器 理由:1)靜態方法有名字啊,更容易懂和理解。構造方法重載容易讓人混淆,並不是好主意    2)靜態工廠方法可以不必每次調用時都創建一個新對象,而公共構造函數每次調用都會

golang學習筆記(1)安裝&helloworld

golang安裝:golang編譯器安裝過程比較簡單,也比較快,不同平臺下(win/linux/macos)都比較相似;https://dl.gocn.io/golang/1.9.2/go1.9.2.src.tar.gz 下載對應的系統版本的編譯器go的版本號由"." 分為3部分如當前的

寒假學習筆記1結構化程序設計

控制流程 ram 循環 只有一個 嚴格 學習筆記 程序編寫 ont 部分 結構化程序設計(structured programming)是進行以模塊功能和處理過程設計為主的詳細設計的基本原則。 - 內容 主張使用順序、選擇、循環三種基本結構來嵌套連結成具有復雜層次的“結構

hibernate框架學習筆記1搭建與測試

for this ble action 1.7 turn yiq targe cts hibernate框架屬於dao層,類似dbutils的作用,是一款ORM(對象關系映射)操作 使用hibernate框架好處是:操作數據庫不需要寫SQL語句,使用面向對象的方式完成

struts2框架學習筆記1搭建測試

method lang app org char 示例 重要 type img Servlet是線程不安全的,Struts1是基於Servlet的框架 而Struts2是基於Filter的框架,解決了線程安全問題 因此Struts1和Struts2基本沒有關系,只是創造者取