Skip to content

Instantly share code, notes, and snippets.

@TranNgocMinh
Created May 29, 2019 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TranNgocMinh/ad32c026f5bd725b7ec842ec9f52949c to your computer and use it in GitHub Desktop.
Save TranNgocMinh/ad32c026f5bd725b7ec842ec9f52949c to your computer and use it in GitHub Desktop.
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
x_train = np.linspace(0, 10, 100)
y_train = x_train + np.random.normal(0,1,100)
learning_rate = 0.01
training_epoches = 100
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
w0 = tf.Variable(0.0, name="W0")
w1 = tf.Variable(0.0, name="W1")
# f(xi) = xi*w1 + w0
def f(X, w1, w0):
return tf.add(tf.multiply(X, w1), w0)
f_xi = f(X, w1, w0)
# loss function
lossF = tf.square(Y-f_xi)
train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(lossF)
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
for epoch in range(training_epoches):
for (x, y) in zip(x_train, y_train):
sess.run(train_op, feed_dict={X: x, Y: y})
w_val_0 = sess.run(w0)
w_val_1 = sess.run(w1)
sess.close()
plt.scatter(x_train, y_train)
y_learned = x_train*w_val_1 + w_val_0
plt.plot(x_train, y_learned, 'r')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment