目錄
Tensorflow的使用入門
1、TF:使用Tensorflow輸出一句話
2、TF實作加法
3、TF實作乘法
4、TF實作計算功能
5、TF:Tensorflow完成一次線性函數計算
Tensorflow的基礎案例
1、TF根據三維資料拟合平面
Tensorflow的經典案例
#TF:使用Tensorflow輸出一句話
import tensorflow as tf
import numpy as np
greeting = tf.constant('Hello Google Tensorflow!')
sess = tf.Session() #啟動一個會話
result = sess.run(greeting) #使用會話執行greeting計算子產品
print(result)
sess.close() #關閉會話,這是一種顯式關閉會話的方式
張量和圖的兩種方式實作:聲明兩個常量 a 和 b,并定義一個加法運算。先定義一張圖,然後運作它,
# -*- coding: utf-8 -*-
#1、張量和圖的兩種方式實作:聲明兩個常量 a 和 b,并定義一個加法運算。先定義一張圖,然後運作它,
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
#T1
a=tf.constant([1,0,1,4])
b=tf.constant([ 1 , 0 , 0 , 4 ])
result=a+b
sess=tf. Session ()
print (sess.run(result))
sess.close
#T2
with tf.Session() as sess:
a=tf.constant([ 1 , 0 , 1 , 4 ])
b=tf.constant([ 1 , 0 , 0 , 4 ])
result=a+b
print (sess.run(result))
#2、常量和變量
#TensorFlow 中最基本的機關是常量(Constant)、變量(Variable)和占位符(Placeholder)。常量定義後值和次元不可變,變量定義後值可變而次元不可變。在神經網絡中,變量一般可作為儲存權重和其他資訊的矩陣,而常量可作為儲存超參數或其他結構資訊的變量。下面我們分别定義了常量與變量
#聲明了不同的常量(tf.constant())
a = tf.constant( 2 , tf.int16) #聲明了不同的整數型資料
b = tf.constant( 4 , tf.float32) #聲明了不同的浮點型資料
c = tf.constant( 8 , tf.float32)
#聲明了不同的變量(tf.Variable())
d = tf. Variable ( 2 , tf.int16)
e = tf. Variable ( 4 , tf.float32)
f = tf. Variable ( 8 , tf.float32)
g = tf.constant(np.zeros(shape=( 2 , 2 ), dtype=np.float32))#聲明結合了 TensorFlow 和 Numpy
h = tf.zeros([ 11 ], tf.int16) #産生全是0的矩陣
i = tf.ones([ 2 , 2 ], tf.float32) #産生全是 1的矩陣
j = tf.zeros([ 1000 , 4 , 3 ], tf.float64)
k = tf. Variable (tf.zeros([ 2 , 2 ], tf.float32))
l = tf. Variable (tf.zeros([ 5 , 6 , 5 ], tf.float32))
#聲明一個 2 行 3 列的變量矩陣,該變量的值服從标準差為 1 的正态分布,并随機生成
w1=tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))
#TensorFlow 還有 tf.truncated_normal() 函數,即截斷正态分布随機數,它隻保留 [mean-2*stddev,mean+2*stddev] 範圍内的随機數
#案例應用:應用變量來定義神經網絡中的權重矩陣和偏置項向量
weights = tf.Variable(tf.truncated_normal([256 * 256, 10]))
biases = tf. Variable (tf.zeros([10]))
print (weights.get_shape().as_list())
print (biases.get_shape().as_list())
Tensorflow之session會話的使用,定義兩個矩陣,兩種方法輸出2個矩陣相乘的結果
matrix1 = tf.constant([[3, 20]])
matrix2 = tf.constant([[6],
[100]])
product = tf.matmul(matrix1, matrix2)
# method 1,正常方法
sess = tf.Session()
result = sess.run(product)
print(result)
sess.close()
# # method 2,with方法
# with tf.Session() as sess: #
# result2 = sess.run(product)
# print(result2)