Skip to content

Instantly share code, notes, and snippets.

@hadifar
Created November 10, 2018 09:19
Show Gist options
  • Save hadifar/37dc45e7821c97d01a6ff098ed4b4607 to your computer and use it in GitHub Desktop.
Save hadifar/37dc45e7821c97d01a6ff098ed4b4607 to your computer and use it in GitHub Desktop.
import numpy as np
import tensorflow as tf
tf.enable_eager_execution()
X_raw = np.array([2013, 2014, 2015, 2016, 2017], dtype=np.float32)
y_raw = np.array([12000, 14000, 15000, 16500, 17500], dtype=np.float32)
X = (X_raw - X_raw.min()) / (X_raw.max() - X_raw.min())
y = (y_raw - y_raw.min()) / (y_raw.max() - y_raw.min())
X = tf.constant(X)
y = tf.constant(y)
a = tf.get_variable(name='a', initializer=0.)
b = tf.get_variable(name='b', initializer=0.)
epoch = 10000
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-3)
for e in range(epoch):
with tf.GradientTape() as tape:
y_pred = a * X + b
cost = 0.5 * tf.reduce_sum(tf.square(y_pred - y))
grads = tape.gradient(cost, [a, b])
optimizer.apply_gradients(grads_and_vars=zip(grads, [a, b]))
print(a.numpy(), b.numpy())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment