scramble_boy

Linear Regression

Nov 16th, 2017
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. import tensorflow as tf
  2. from sklearn import metrics, model_selection
  3. from sklearn.datasets import load_boston
  4. import numpy as np
  5.  
  6. dataset = load_boston()
  7. print(dataset.keys())
  8.  
  9. test_size = 0.2
  10. seed = 7
  11. x, y = dataset['data'], dataset['target']
  12. print("Info: ")
  13. print("Dim(x): ", x.shape, "\n", "Dim(y): ", y.shape)
  14. print("Average data: ", np.average(x, axis=0))
  15. print("Average target: ", np.average(y))
  16. x_train, x_test, y_train, y_test = model_selection.train_test_split(x, y, test_size=test_size, random_state=seed)
  17. y_train = np.array([y_train]).T
  18. y_test = np.array([y_test]).T
  19.  
  20. # build model
  21.  
  22. input_x = tf.placeholder(shape=[None, 13], dtype=tf.float64, name="Input_X")
  23. input_y = tf.placeholder(dtype=tf.float64, name="Input_Y")
  24.  
  25. weights = tf.Variable(tf.random_normal([13,1], dtype=tf.float64), name="Weight")
  26. bias = tf.Variable(0, dtype=tf.float64, name="Bias")
  27.  
  28. predict = tf.add(tf.matmul(input_x, weights), bias, name="Model")
  29. cost = tf.reduce_sum(tf.square(input_y-predict))
  30. optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01, name="GradientDescent").minimize(cost, name="Train_min")
  31.  
  32. sess = tf.Session()
  33. init = tf.global_variables_initializer()
  34.  
  35. # Train model
  36. sess.run(init)
  37. for i in range(10):
  38.     c, _ = sess.run([cost, optimizer], feed_dict={input_x: x_train, input_y: y_train})
  39.     print("Cost of ", i, " is ", c)
  40.  
  41. writter = tf.summary.FileWriter(logdir="/tmp/linear/1", graph=sess.graph)
  42.  
  43. w, b, pred = sess.run([weights, bias, predict], feed_dict={input_x: x_test})
  44. print("Weight: ", w, "\n Bias: ", b, "\nAverage pred: ", np.mean(pred, axis=0))
Advertisement
Add Comment
Please, Sign In to add comment