您好,登錄后才能下訂單哦!
#必須放開頭,否則報(bào)錯(cuò)。作用:把python新版本中print_function函數(shù)的特性導(dǎo)入到當(dāng)前版本
from future import print_function
import tensorflow.compat.v1 as tf#將v2版本轉(zhuǎn)化成v1版本使用
tf.disable_v2_behavior()
import numpy as np
import matplotlib.pyplot as plt
#Construct a function that adds a neural layer
#inputs指輸入,in_size指輸入層維度,out_size指輸出層維度,activation_function()指激勵(lì)函數(shù),默認(rèn)None
def add_layer(inputs,in_size,out_size,activation_function=None):
Weights=tf.Variable(tf.random.normal([in_size,out_size]))#權(quán)重
biases=tf.Variable(tf.zeros([1,out_size])+0.1)#偏置,因?yàn)橐话闫貌粸?,于是人為加上0.1
Wx_plus_b=tf.matmul(inputs,Weights)+biases#tf.matmul矩陣相乘
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
#Make up some real data
#隨機(jī)x_data,這里一定要定義dtype,[:,np.newaxis]指降低一個(gè)維度
x_data = np.linspace(-1,1,300,dtype=np.float32)[:,np.newaxis]
#概率密度函數(shù)np.random.normal(loc,scale,size),loc指分布中心,scale指標(biāo)準(zhǔn)差(越小擬合的越好),size指類型(默認(rèn)size=None)
noise = np.random.normal(0,0.05,x_data.shape).astype(np.float32)
#real y_data
y_data = np.square(x_data) - 0.5 + noise
#defind placeholder for inputs to network
#此函數(shù)可以理解為形參,用于定義過程,在執(zhí)行的時(shí)候再賦具體的值
xs = tf.placeholder(tf.float32,[None,1])#一定要定義tf.float32,系統(tǒng)不默認(rèn)
ys = tf.placeholder(tf.float32,[None,1])
#add hidden layer
#這里的激勵(lì)函數(shù)為relu函數(shù),指輸入層一個(gè)神經(jīng)元,輸出層十個(gè)神經(jīng)元
l1 = add_layer(xs,1,10,activation_function = tf.nn.relu)
#add outputs layer
#這里激勵(lì)函數(shù)為None
prediction = add_layer(l1,10,1,activation_function = None)
#the error between real data and prediction
function(){ //常見問題:http://www.fx61.com/faq
#定義loss,指損失函數(shù)總和的平均值,注意這里必須得加上一個(gè)reduction_indices=[]。(會(huì)說明)
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),reduction_indices=[1]))
#這里用GradientDescentOptimizer做為優(yōu)化器,就是梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
#Activate
sess = tf.Session()#非常重要
#定義全局初始化(兩種表示方法:global_variables_initializer,initialize_all_variables)
#建議用global_variables_initializer新版本
init = tf.global_variables_initializer()
sess.run(init)
for i in range(1000):
#train,這里的feed_dict是一個(gè)字典,用于導(dǎo)入數(shù)據(jù)x_data和y_data
sess.run(train_step,feed_dict = {xs : x_data, ys : y_data})
#每50步打印一次
if i % 50 == 0:
print(sess.run(loss,feed_dict = {xs : x_data, ys : y_data}))
可視化結(jié)果
#Visualization of results
fig = plt.figure()#建立一個(gè)背景
ax = fig.add_subplot(1,1,1)#建立標(biāo)注
ax.scatter(x_data , y_data)#scatter指散點(diǎn)
plt.ion()#全局變量時(shí),最好注釋掉。作用:使圖像連續(xù)
plt.show()
for i in range(1000):
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
if i % 50 == 0:
# to visualize the result and improvement
#指沒有圖像就跳過(簡(jiǎn)單理解:先抹去線,再出現(xiàn)下一次線)
try:
ax.lines.remove(lines[0])
except Exception:
pass
prediction_value = sess.run(prediction, feed_dict={xs: x_data})
# plot the prediction
lines = ax.plot(x_data, prediction_value, 'r-', lw=3)#紅色,寬度為3
plt.pause(0.1)#指暫停幾秒,作者實(shí)驗(yàn)表明0.1~0.3可視化效果明顯
https://blog.csdn.net/qq_45603919/article/details/103331515
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。