单变量线性回归y=wx+b使用TensorFlow实现代码
import tensorflow as tf
import numpy as np
import matplotlib. pyplot as plt
import pandas as pd
from sklearn. utils import shuffle
import pickle as p
% matplotlib inline
x_data = np. linspace( - 1 , 1 , 100 )
y_data = 2 * x_data+ 1.0 + np. random. randn( * x_data. shape) * 0.4
x= tf. placeholder( 'float' , name= 'x' )
y= tf. placeholder( 'float' , name= 'y' )
def model ( x, w, b) :
return tf. multiply( x, w) + b
w= tf. Variable( 1.0 , name= 'w0' )
b= tf. Variable( 0.0 , name= 'b0' )
pred = model( x, w, b)
train_epochs = 10
learning_rate = 0.05
loss_function = tf. reduce_mean( tf. square( y- pred) )
optimizer = tf. train. GradientDescentOptimizer( learning_rate) . minimize( loss_function)
sess= tf. Session( )
init = tf. global_variables_initializer( )
sess. run( init)
step= 0
loss_list= [ ]
for epoch in range ( train_epochs) :
for xs, ys in zip ( x_data, y_data) :
_, loss = sess. run( [ optimizer, loss_function] , feed_dict= { x: xs, y: ys} )
loss_list. append( loss)
step+= 1
display_step= 10
if step% display_step == 0 :
print ( 'train epoch:' , '%02d' % ( epoch+ 1 ) , 'step:%03d' % ( step) , 'loss=' , '{:.9f}' . format ( loss) )
b0temp= b. eval ( session= sess)
w0temp= w. eval ( session= sess)
plt. plot( x_data, w0temp* x_data+ b0temp)
plt. plot( loss_list)