import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
x_data = np.random.rand(100)
noise = np.random.normal(0,0.01,x_data.shape)
y_data = x_data*0.1 + 0.2 + noise
plt.scatter(x_data, y_data)
plt.show()
# build a linear Model
d = tf.Variable(np.random.rand(1))
k = tf.Variable(np.random.rand(1))
y = k*x_data + d
# Quadratic cost function
loss = tf.losses.mean_squared_error(y_data, y)
# Define a gradient descent method optimizer
optimizer = tf.train.GradientDescentOptimizer(0.3)
# Minimize the cost function
train = optimizer.minimize(loss)
# Initialize variables
init= tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(201):
sess.run(train)
if i%20==0:
print(i,sess.run([k,d]) )
y_pred = sess.run(y)
plt.scatter(x_data,y_data)
plt.plot(x_data,y_pred,'r-',lw=3)
plt.show()
0 [array([0.42558686]), array([0.07772181])]
20 [array([0.24686251]), array([0.1212207])]
40 [array([0.17103131]), array([0.16282419])]
60 [array([0.13410329]), array([0.18308412])]
80 [array([0.1161202]), array([0.19295024])]
100 [array([0.10736286]), array([0.1977548])]
120 [array([0.10309823]), array([0.20009452])]
140 [array([0.10102146]), array([0.2012339])]
160 [array([0.10001012]), array([0.20178875])]
180 [array([0.09951763]), array([0.20205895])]
200 [array([0.09927779]), array([0.20219054])]
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
x_data = np.random. rand(100)
noise = np.random.normal(0,0.01,x_data.shape)
y_data = x_data*0.1 + 0.2 + noise
plt.scatter(x_data, y_data)
plt.show()
# Build a linear model
d = tf.Variable(np.random.rand(1))
k = tf.Variable(np.random.rand(1))
y = k*x_data + d
# Quadratic cost function
loss = tf.losses.mean_squared_error(y_data, y)
# Define a gradient descent method optimizer
optimizer = tf.train.GradientDescentOptimizer(0.3)
# Minimize the cost function
train = optimizer.minimize(loss)
# Initialize variables
init= tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(201):
sess.run(train)
if i%20==0:
print(i,sess.run([k,d]) )
y_pred = sess.run(y)
plt.scatter(x_data,y_data)
plt.plot(x_data,y_pred,'r-',lw=3)
plt.show()