import numpy as np
import tensorflow as tf算法
# 模型參數
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)函數
# 模型的輸入和輸出
x = tf.placeholder(tf.float32)
linear_model = W * x + b
y = tf.placeholder(tf.float32)優化
# 定義損失函數
loss = tf.reduce_sum(tf.square(linear_model - y)) # 均方偏差it
# 優化算法
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)io
# 訓練數據
x_train = [1,2,3,4]
y_train = [0,-1,-2,-3]import
# 訓練過程
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)tensorflow
for i in range(100):
sess.run(train, {x:x_train, y:y_train})model
# 訓練偏差
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x:x_train, y:y_train})
print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))float
========================================================================numpy
[-0.84079814] b: [ 0.53192717] loss: 0.146364