Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """
- Created on Sun Jul 7 15:02:20 2019
- """
- import pandas as pd
- import numpy as np
- import tensorflow as tf
- import matplotlib.pyplot as plt
- # ---------------
- # Prepation of Data
- # ---------------
- # Import in the required files
- xexxar = pd.read_csv("Xexxar.csv")
- # We want to analyze Speed and Speed Rating since they are likely to be
- # linearly related.
- # It is grouped by Speed (Index) and Aggregated with .mean()
- xexxar_filtered = xexxar[['Speed', 'Speed Rating']].groupby("Speed").mean()
- # Extract x and y (x in nested in the index)
- data_x = np.array(xexxar_filtered.index.tolist(), dtype = 'float')
- data_y = xexxar_filtered['Speed Rating']
- # ---------------
- # TensorFlow Preparation
- # ---------------
- # Define Feeding placeholders, placeholders are slots where data is fed during
- # the training process.
- feed_x = tf.placeholder(tf.float32)
- feed_y = tf.placeholder(tf.float32)
- # We define the model as a linear relationship where, y = f(x) = w * x
- def model(x, w):
- return(tf.multiply(x, w))
- # Initialize w as 1.0, named weight
- var_w = tf.Variable(1.0, 'weight')
- # Create model with placeholder x and weight variable
- model_y = model(feed_x, var_w)
- # Define the cost. Square is required to make sure the value is always positive
- cost = tf.square(model_y - feed_y)
- # We define the optimizer (ADAM) with learning rate = 0.001 and the cost.
- cost_op = tf.train.AdamOptimizer(0.001).minimize(cost)
- # These are Tensorboard writers
- # This defines var_w (weight) to be tracked
- summary_w = tf.summary.scalar("Weight", var_w)
- # This defines the Tensorboard summary writer
- summary_writer = tf.summary.FileWriter("logs_speed")
- # This merges all summaries (Not required since there's only 1 summary
- # excluding summary_writer)
- summary_merged = tf.summary.merge_all()
- # Automatically initalize all variables
- init = tf.global_variables_initializer()
- # Define number of epochs
- epochs = 50
- # ---------------
- # TensorFlow Session
- # ---------------
- with tf.Session() as sess:
- # Initialize all variables
- sess.run(init)
- # Step is used for Tensorboard Summary
- step = 0
- for epoch in range(epochs):
- for x, y in zip(data_x, data_y):
- step += 1
- # We extract summary_str from the sess.run
- # summary_merged outputs to summary_str
- # cost_op outputs to _ (placeholder)
- summary_str, _ = sess.run([summary_merged, cost_op],
- feed_dict={
- feed_x: x,
- feed_y: y
- })
- # Append to Tensorboard Summary
- summary_writer.add_summary(summary_str, step)
- print("Epoch {} \t Weight {}".format(epoch, var_w.eval(sess)))
- # Extract calculated w
- trained_w = var_w.eval(sess)
- # ---------------
- # Evaluate using matplotlib.pyplot
- # ---------------
- # Get new trained_y with new trained_y
- trained_y = trained_w * data_x
- # Plot original
- plt.scatter(data_x, data_y)
- # Plot new
- plt.scatter(data_x, trained_y, c = 'r')
- # Show
- plt.show()
- # Clears Graph when sessions don't close properly sometimes
- tf.reset_default_graph()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement