Skip to content

Instantly share code, notes, and snippets.

@nbortolotti
Created April 17, 2017 19:12
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 nbortolotti/4640032098f4c7dd4ec915f8dde19062 to your computer and use it in GitHub Desktop.
Save nbortolotti/4640032098f4c7dd4ec915f8dde19062 to your computer and use it in GitHub Desktop.
def run_training(train_X, train_Y):
# inputs
X = tf.placeholder(tf.float32, [m, n])
Y = tf.placeholder(tf.float32, [m, 1])
# weight and bias
W = tf.Variable(tf.zeros([n, 1], dtype=np.float32), name="weight")
b = tf.Variable(tf.zeros([1], dtype=np.float32), name="bias")
# linear model
with tf.name_scope("linear_Wx_b") as scope:
activation = tf.add(tf.matmul(X, W), b)
# cost
with tf.name_scope("cost") as scope:
cost = tf.reduce_sum(tf.square(activation - Y)) / (2 * m)
tf.summary.scalar("cost", cost)
# train
with tf.name_scope("train") as scope:
optimizer = tf.train.GradientDescentOptimizer(0.07).minimize(cost)
# tensorflow session
with tf.Session() as sess:
merged = tf.summary.merge_all()
writer = tf.summary.FileWriter(log_file, sess.graph)
init = tf.global_variables_initializer()
sess.run(init)
for step in range(1500):
result, _ = sess.run([merged, optimizer], feed_dict={X: np.asarray(train_X), Y: np.asarray(train_Y)})
writer.add_summary(result, step)
print "Optimization"
training_cost = sess.run(cost, feed_dict={X: np.asarray(train_X), Y: np.asarray(train_Y)})
print "Training Cost: ", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n'
print "Prediction for 3.5 years"
predict_X = np.array([3.5], dtype=np.float32).reshape([1, 1])
predict_X = (predict_X - mean) / std
predict_Y = tf.add(tf.matmul(predict_X, W), b)
print "Child height(Y) =", sess.run(predict_Y)
print "Predict for 7 years"
predict_X_2 = np.array([7], dtype=np.float32).reshape([1, 1])
predict_X_2 = (predict_X_2 - mean) / std
predict_Y_2 = tf.add(tf.matmul(predict_X_2, W), b)
print "Child height(Y) =", sess.run(predict_Y_2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment