第一個(gè)TensorFlow程序

本文介紹如何用TensorFlow求簡(jiǎn)單的線性回歸問題。

  1. 生成訓(xùn)練數(shù)據(jù)
import tensorflow as tf
import numpy as np

# Create 100 phony x, y data points in NumPy, y = x * 0.1 + 0.3
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3
  1. 創(chuàng)建數(shù)據(jù)流圖
# Try to find values for W and b that compute y_data = W * x_data + b
# (We know that W should be 0.1 and b 0.3, but TensorFlow will
# figure that out for us.)
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.zeros([1]))
y = W * x_data + b
  1. 設(shè)計(jì)目標(biāo)函數(shù)
# Minimize the mean squared errors.
loss = tf.reduce_mean(tf.square(y - y_data))
  1. 選擇訓(xùn)練算法(梯度下降)
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
  1. 創(chuàng)建TensorFlow的Session,初始化
# Before starting, initialize the variables.  We will 'run' this first.
init = tf.global_variables_initializer()
# Launch the graph.
sess = tf.Session()
sess.run(init)
  1. 開始訓(xùn)練過程
# Fit the line.
for step in range(201):
  sess.run(train)
  if step % 20 == 0:
      print(step, sess.run(W), sess.run(b))

# Learns best fit is W: [0.1], b: [0.3]
  1. 運(yùn)行結(jié)果
(0, array([ 0.40007937], dtype=float32), array([ 0.18186936], dtype=float32))
(20, array([ 0.16719148], dtype=float32), array([ 0.26199135], dtype=float32))
(40, array([ 0.11624231], dtype=float32), array([ 0.2908121], dtype=float32))
(60, array([ 0.10392629], dtype=float32), array([ 0.29777899], dtype=float32))
(80, array([ 0.1009491], dtype=float32), array([ 0.29946312], dtype=float32))
(100, array([ 0.10022942], dtype=float32), array([ 0.29987025], dtype=float32))
(120, array([ 0.10005546], dtype=float32), array([ 0.29996863], dtype=float32))
(140, array([ 0.10001341], dtype=float32), array([ 0.29999244], dtype=float32))
(160, array([ 0.10000324], dtype=float32), array([ 0.29999819], dtype=float32))
(180, array([ 0.10000078], dtype=float32), array([ 0.29999956], dtype=float32))
(200, array([ 0.1000002], dtype=float32), array([ 0.29999989], dtype=float32))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容