1.資料準備
2.搭建模型
3.迭代訓練
4.使用模型
以y=2x作為主體,加入一些干擾雜訊。
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
train_x = np.linspace(-1
,1,100
)train_y =
2*train_x + np.random.randn(
*train_x.shape)
*0.3
#建立模型
x = tf.placeholder(
"float"
)y = tf.placeholder(
"float"
)#模型引數
w = tf.variable(tf.random_normal([1
]),name=
'weight'
)b = tf.variable(tf.zeros([1
]),name=
'bias'
)#前向結構
z = tf.multiply(x,w)
+b#反向優化
cost = tf.reduce_mean(tf.square(y-z)
)learning_rate =
0.01
optimizer = tf.train.gradientdescentoptimizer(learning_rate)
.minimize(cost)
說明:
x,y:佔位符,使用placeholder函式進行定義。
w,b: w被初始化成[-1,1]的隨機數,形狀為一維的數字,b被初始化為0,形狀也是一維的數字。
cost:成本變數,它等於生成值與真實值的平方差
learning_rate:學習率,值越小越精確
#訓練模型
#初始化所有變數
init = tf.global_variables_initializer(
)#定義引數
training_epochs =
20display_step =
2#啟動session
with tf.session(
)as sess:
sess.run(init)
plotdata=
#向模型中輸入資料
for epoch in
range
(training_epochs)
:for
(x,y)
inzip
(train_x,train_y)
: sess.run(optimizer,feed_dict=
)#顯示訓練中的詳細資訊
if epoch % display_step ==0:
loss = sess.run(cost,feed_dict=
)print
("epoch:"
,epoch+1,
"cost="
,loss,
"w="
,sess.run(w)
,"b="
,sess.run(b))if
not(loss==
"na"):
plotdata[
"batchsize"
] plotdata[
"loss"
]print
("finished!"
)print
("cost="
,sess.run(cost,feed_dict=),
"w="
,sess.run(w)
,"b="
,sess.run(b)
)
執行結果:
))說明:**x=0.2,y的值
結果:x=0.2,z= [0.417329]
找出一組資料中只出現一次的資料
有一組資料,假設除了某乙個元素出現了一次外,其餘元素都出現了兩次,找出這個元素。如 array 在這個陣列中,怎麼找出這個只出現了一次的5呢?依次拿出乙個元素與其他元素進行比較,設定乙個中間變數result,每次讓resul等於該值,根據是否有與其相同的值來改變result的值,最後根據result...
SQL Server 從一組數字中隨機獲取乙個數
很多人在開發需求中想獲取乙個隨機數,或者從一組數字中獲取乙個數,這個需求很簡單,而且有很多方式可以實現,下面就介紹幾種常見的方式,以作為筆記或供有需要的人參考.比如有一組數字 57 59 63 66 89 92 95,我們要從中隨機取出乙個 方法一 建表 建立中間表存放隨機數字 create tab...
找出一組數中只出現一次的元素
coding utf 8 python2.7 author ll ying 找出一組數中只出現一次的元素。注 其它元素都出現過兩次。classsolution defsinglenumber self a parama a list of integer return integer returnr...