Skip to content

Instantly share code, notes, and snippets.

@randcode-generator
Created September 14, 2017 01:37
Show Gist options
  • Save randcode-generator/2e71284e641cb19a315c8e58ba68ddc0 to your computer and use it in GitHub Desktop.
Save randcode-generator/2e71284e641cb19a315c8e58ba68ddc0 to your computer and use it in GitHub Desktop.
import tensorflow as tf
import numpy
# Parameters
learning_rate = 0.01
training_epochs = 5300
datapoints_count = 100
# Training Data
train_X = []
train_Y = []
for i in range(datapoints_count):
train_X.append(i)
train_Y.append(5*i+8.0)
train_X = numpy.asarray(train_X)
train_Y = numpy.asarray(train_Y)
n_samples = train_X.shape[0]
# tf Graph Input
X = tf.placeholder("float")
Y = tf.placeholder("float")
# Set model weights
W = tf.Variable(0.0, name="weight")
b = tf.Variable(0.0, name="bias")
# Construct a linear model
y_pred = X * W + b
# Mean squared error
cost = tf.reduce_sum(tf.square(y_pred-Y))/(2*n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# Start training
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# Fit all training data
for epoch in range(training_epochs):
for (x, y) in zip(train_X, train_Y):
sess.run(optimizer, feed_dict={X: x, Y: y})
# Display logs for every 50 epoch step
if (epoch+1) % 50 == 0:
c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
print("Epoch: %04d cost=%.9f W=%f b=%f" % \
((epoch+1), c, sess.run(W), sess.run(b)))
training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
print("Training cost=%.9f W=%f b=%f" % \
(training_cost, sess.run(W), sess.run(b)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment