Advertisement
eedubraz

Untitled

Oct 17th, 2017
450
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.58 KB | None | 0 0
  1.  
  2. # coding: utf-8
  3.  
  4. # # Your first neural network
  5. #
  6. # In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementation of the neural network up to you (for the most part). After you've submitted this project, feel free to explore the data and the model more.
  7. #
  8. #
  9.  
  10. # In[ ]:
  11.  
  12.  
  13. get_ipython().magic('matplotlib inline')
  14. get_ipython().magic("config InlineBackend.figure_format = 'retina'")
  15.  
  16. import numpy as np
  17. import pandas as pd
  18. import matplotlib.pyplot as plt
  19.  
  20.  
  21. # ## Load and prepare the data
  22. #
  23. # A critical step in working with neural networks is preparing the data correctly. Variables on different scales make it difficult for the network to efficiently learn the correct weights. Below, we've written the code to load and prepare the data. You'll learn more about this soon!
  24.  
  25. # In[ ]:
  26.  
  27.  
  28. data_path = 'Bike-Sharing-Dataset/hour.csv'
  29.  
  30. rides = pd.read_csv(data_path)
  31.  
  32.  
  33. # In[ ]:
  34.  
  35.  
  36. rides.head()
  37.  
  38.  
  39. # ## Checking out the data
  40. #
  41. # This dataset has the number of riders for each hour of each day from January 1 2011 to December 31 2012. The number of riders is split between casual and registered, summed up in the `cnt` column. You can see the first few rows of the data above.
  42. #
  43. # Below is a plot showing the number of bike riders over the first 10 days or so in the data set. (Some days don't have exactly 24 entries in the data set, so it's not exactly 10 days.) You can see the hourly rentals here. This data is pretty complicated! The weekends have lower over all ridership and there are spikes when people are biking to and from work during the week. Looking at the data above, we also have information about temperature, humidity, and windspeed, all of these likely affecting the number of riders. You'll be trying to capture all this with your model.
  44.  
  45. # In[ ]:
  46.  
  47.  
  48. rides[:24*10].plot(x='dteday', y='cnt')
  49.  
  50.  
  51. # ### Dummy variables
  52. # Here we have some categorical variables like season, weather, month. To include these in our model, we'll need to make binary dummy variables. This is simple to do with Pandas thanks to `get_dummies()`.
  53.  
  54. # In[ ]:
  55.  
  56.  
  57. dummy_fields = ['season', 'weathersit', 'mnth', 'hr', 'weekday']
  58. for each in dummy_fields:
  59. dummies = pd.get_dummies(rides[each], prefix=each, drop_first=False)
  60. rides = pd.concat([rides, dummies], axis=1)
  61.  
  62. fields_to_drop = ['instant', 'dteday', 'season', 'weathersit',
  63. 'weekday', 'atemp', 'mnth', 'workingday', 'hr']
  64. data = rides.drop(fields_to_drop, axis=1)
  65. data.head()
  66.  
  67.  
  68. # ### Scaling target variables
  69. # To make training the network easier, we'll standardize each of the continuous variables. That is, we'll shift and scale the variables such that they have zero mean and a standard deviation of 1.
  70. #
  71. # The scaling factors are saved so we can go backwards when we use the network for predictions.
  72.  
  73. # In[ ]:
  74.  
  75.  
  76. quant_features = ['casual', 'registered', 'cnt', 'temp', 'hum', 'windspeed']
  77. # Store scalings in a dictionary so we can convert back later
  78. scaled_features = {}
  79. for each in quant_features:
  80. mean, std = data[each].mean(), data[each].std()
  81. scaled_features[each] = [mean, std]
  82. data.loc[:, each] = (data[each] - mean)/std
  83.  
  84.  
  85. # ### Splitting the data into training, testing, and validation sets
  86. #
  87. # We'll save the data for the last approximately 21 days to use as a test set after we've trained the network. We'll use this set to make predictions and compare them with the actual number of riders.
  88.  
  89. # In[ ]:
  90.  
  91.  
  92. # Save data for approximately the last 21 days
  93. test_data = data[-21*24:]
  94.  
  95. # Now remove the test data from the data set
  96. data = data[:-21*24]
  97.  
  98. # Separate the data into features and targets
  99. target_fields = ['cnt', 'casual', 'registered']
  100. features, targets = data.drop(target_fields, axis=1), data[target_fields]
  101. test_features, test_targets = test_data.drop(target_fields, axis=1), test_data[target_fields]
  102.  
  103.  
  104. # We'll split the data into two sets, one for training and one for validating as the network is being trained. Since this is time series data, we'll train on historical data, then try to predict on future data (the validation set).
  105.  
  106. # In[ ]:
  107.  
  108.  
  109. # Hold out the last 60 days or so of the remaining data as a validation set
  110. train_features, train_targets = features[:-60*24], targets[:-60*24]
  111. val_features, val_targets = features[-60*24:], targets[-60*24:]
  112.  
  113.  
  114. # ## Time to build the network
  115. #
  116. # Below you'll build your network. We've built out the structure and the backwards pass. You'll implement the forward pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes.
  117. #
  118. # The network has two layers, a hidden layer and an output layer. The hidden layer will use the sigmoid function for activations. The output layer has only one node and is used for the regression, the output of the node is the same as the input of the node. That is, the activation function is $f(x)=x$. A function that takes the input signal and generates an output signal, but takes into account the threshold, is called an activation function. We work through each layer of our network calculating the outputs for each neuron. All of the outputs from one layer become inputs to the neurons on the next layer. This process is called *forward propagation*.
  119. #
  120. # We use the weights to propagate signals forward from the input to the output layers in a neural network. We use the weights to also propagate error backwards from the output back into the network to update our weights. This is called *backpropagation*.
  121. #
  122. # > **Hint:** You'll need the derivative of the output activation function ($f(x) = x$) for the backpropagation implementation. If you aren't familiar with calculus, this function is equivalent to the equation $y = x$. What is the slope of that equation? That is the derivative of $f(x)$.
  123. #
  124. # Below, you have these tasks:
  125. # 1. Implement the sigmoid function to use as the activation function. Set `self.activation_function` in `__init__` to your sigmoid function.
  126. # 2. Implement the forward pass in the `train` method.
  127. # 3. Implement the backpropagation algorithm in the `train` method, including calculating the output error.
  128. # 4. Implement the forward pass in the `run` method.
  129. #
  130.  
  131. # In[ ]:
  132.  
  133.  
  134. class NeuralNetwork(object):
  135. def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
  136. # Set number of nodes in input, hidden and output layers.
  137. self.input_nodes = input_nodes
  138. self.hidden_nodes = hidden_nodes
  139. self.output_nodes = output_nodes
  140.  
  141. # Initialize weights
  142. self.weights_input_to_hidden = np.random.normal(0.0, self.hidden_nodes**-0.5,
  143. (self.hidden_nodes, self.input_nodes))
  144.  
  145. self.weights_hidden_to_output = np.random.normal(0.0, self.output_nodes**-0.5,
  146. (self.output_nodes, self.hidden_nodes))
  147. self.lr = learning_rate
  148.  
  149. #### TODO: Set self.activation_function to your implemented sigmoid function ####
  150. #
  151. # Note: in Python, you can define a function with a lambda expression,
  152. # as shown below.
  153. self.activation_function = lambda x : 0 # Replace 0 with your sigmoid calculation.
  154.  
  155. ### If the lambda code above is not something you're familiar with,
  156. # You can uncomment out the following three lines and put your
  157. # implementation there instead.
  158. #
  159. #def sigmoid(x):
  160. # return 0 # Replace 0 with your sigmoid calculation here
  161. #self.activation_function = sigmoid
  162.  
  163.  
  164. def train(self, inputs_list, targets_list):
  165. # Convert inputs list to 2d array
  166. inputs = np.array(inputs_list, ndmin=2).T
  167. targets = np.array(targets_list, ndmin=2).T
  168.  
  169. #### Implement the forward pass here ####
  170. ### Forward pass ###
  171. # TODO: Hidden layer - Replace these values with your calculations.
  172. hidden_inputs = None # signals into hidden layer
  173. hidden_outputs = None # signals from hidden layer
  174.  
  175. # TODO: Output layer - Replace these values with your calculations.
  176. final_inputs = None # signals into final output layer
  177. final_outputs = None # signals from final output layer
  178.  
  179. #### Implement the backward pass here ####
  180. ### Backward pass ###
  181.  
  182. # TODO: Output error - Replace this value with your calculations.
  183. output_errors = None # Output layer error is the difference between desired target and actual output.
  184.  
  185. # TODO: Backpropagated error - Replace these values with your calculations.
  186. hidden_errors = None # errors propagated to the hidden layer
  187. hidden_grad = None # hidden layer gradients
  188.  
  189. # TODO: Update the weights - Replace these values with your calculations.
  190. self.weights_hidden_to_output += 0 # update hidden-to-output weights with gradient descent step
  191. self.weights_input_to_hidden += 0 # update input-to-hidden weights with gradient descent step
  192.  
  193.  
  194. def run(self, inputs_list):
  195. # Run a forward pass through the network
  196. inputs = np.array(inputs_list, ndmin=2).T
  197.  
  198. #### Implement the forward pass here ####
  199. # TODO: Hidden layer - replace these values with the appropriate calculations.
  200. hidden_inputs = None # signals into hidden layer
  201. hidden_outputs = None # signals from hidden layer
  202.  
  203. # TODO: Output layer - Replace these values with the appropriate calculations.
  204. final_inputs = None # signals into final output layer
  205. final_outputs = np.zeros((1, len(inputs_list))) # signals from final output layer
  206.  
  207. return final_outputs
  208.  
  209.  
  210. # In[ ]:
  211.  
  212.  
  213. def MSE(y, Y):
  214. return np.mean((y-Y)**2)
  215.  
  216.  
  217. # ## Training the network
  218. #
  219. # Here you'll set the hyperparameters for the network. The strategy here is to find hyperparameters such that the error on the training set is low, but you're not overfitting to the data. If you train the network too long or have too many hidden nodes, it can become overly specific to the training set and will fail to generalize to the validation set. That is, the loss on the validation set will start increasing as the training set loss drops.
  220. #
  221. # You'll also be using a method know as Stochastic Gradient Descent (SGD) to train the network. The idea is that for each training pass, you grab a random sample of the data instead of using the whole data set. You use many more training passes than with normal gradient descent, but each pass is much faster. This ends up training the network more efficiently. You'll learn more about SGD later.
  222. #
  223. # ### Choose the number of epochs
  224. # This is the number of times the dataset will pass through the network, each time updating the weights. As the number of epochs increases, the network becomes better and better at predicting the targets in the training set. You'll need to choose enough epochs to train the network well but not too many or you'll be overfitting.
  225. #
  226. # ### Choose the learning rate
  227. # This scales the size of weight updates. If this is too big, the weights tend to explode and the network fails to fit the data. A good choice to start at is 0.1. If the network has problems fitting the data, try reducing the learning rate. Note that the lower the learning rate, the smaller the steps are in the weight updates and the longer it takes for the neural network to converge.
  228. #
  229. # ### Choose the number of hidden nodes
  230. # The more hidden nodes you have, the more accurate predictions the model will make. Try a few different numbers and see how it affects the performance. You can look at the losses dictionary for a metric of the network performance. If the number of hidden units is too low, then the model won't have enough space to learn and if it is too high there are too many options for the direction that the learning can take. The trick here is to find the right balance in number of hidden units you choose.
  231.  
  232. # In[ ]:
  233.  
  234.  
  235. import sys
  236.  
  237. ### Set the hyperparameters here ###
  238. epochs = 100
  239. learning_rate = 0.1
  240. hidden_nodes = 2
  241. output_nodes = 1
  242.  
  243. N_i = train_features.shape[1]
  244. network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate)
  245.  
  246. losses = {'train':[], 'validation':[]}
  247. for e in range(epochs):
  248. # Go through a random batch of 128 records from the training data set
  249. batch = np.random.choice(train_features.index, size=128)
  250. for record, target in zip(train_features.ix[batch].values,
  251. train_targets.ix[batch]['cnt']):
  252. network.train(record, target)
  253.  
  254. # Printing out the training progress
  255. train_loss = MSE(network.run(train_features), train_targets['cnt'].values)
  256. val_loss = MSE(network.run(val_features), val_targets['cnt'].values)
  257. sys.stdout.write("\rProgress: " + str(100 * e/float(epochs))[:4] + "% ... Training loss: " + str(train_loss)[:5] + " ... Validation loss: " + str(val_loss)[:5])
  258.  
  259. losses['train'].append(train_loss)
  260. losses['validation'].append(val_loss)
  261.  
  262.  
  263. # In[ ]:
  264.  
  265.  
  266. plt.plot(losses['train'], label='Training loss')
  267. plt.plot(losses['validation'], label='Validation loss')
  268. plt.legend()
  269. plt.ylim(ymax=0.5)
  270.  
  271.  
  272. # ## Check out your predictions
  273. #
  274. # Here, use the test data to view how well your network is modeling the data. If something is completely wrong here, make sure each step in your network is implemented correctly.
  275.  
  276. # In[ ]:
  277.  
  278.  
  279. fig, ax = plt.subplots(figsize=(8,4))
  280.  
  281. mean, std = scaled_features['cnt']
  282. predictions = network.run(test_features)*std + mean
  283. ax.plot(predictions[0], label='Prediction')
  284. ax.plot((test_targets['cnt']*std + mean).values, label='Data')
  285. ax.set_xlim(right=len(predictions))
  286. ax.legend()
  287.  
  288. dates = pd.to_datetime(rides.ix[test_data.index]['dteday'])
  289. dates = dates.apply(lambda d: d.strftime('%b %d'))
  290. ax.set_xticks(np.arange(len(dates))[12::24])
  291. _ = ax.set_xticklabels(dates[12::24], rotation=45)
  292.  
  293.  
  294. # ## OPTIONAL: Thinking about your results(this question will not be evaluated in the rubric).
  295. #
  296. # Answer these questions about your results. How well does the model predict the data? Where does it fail? Why does it fail where it does?
  297. #
  298. # > **Note:** You can edit the text in this cell by double clicking on it. When you want to render the text, press control + enter
  299. #
  300. # #### Your answer below
  301.  
  302. # ## Unit tests
  303. #
  304. # Run these unit tests to check the correctness of your network implementation. These tests must all be successful to pass the project.
  305.  
  306. # In[ ]:
  307.  
  308.  
  309. import unittest
  310.  
  311. inputs = [0.5, -0.2, 0.1]
  312. targets = [0.4]
  313. test_w_i_h = np.array([[0.1, 0.4, -0.3],
  314. [-0.2, 0.5, 0.2]])
  315. test_w_h_o = np.array([[0.3, -0.1]])
  316.  
  317. class TestMethods(unittest.TestCase):
  318.  
  319. ##########
  320. # Unit tests for data loading
  321. ##########
  322.  
  323. def test_data_path(self):
  324. # Test that file path to dataset has been unaltered
  325. self.assertTrue(data_path.lower() == 'bike-sharing-dataset/hour.csv')
  326.  
  327. def test_data_loaded(self):
  328. # Test that data frame loaded
  329. self.assertTrue(isinstance(rides, pd.DataFrame))
  330.  
  331. ##########
  332. # Unit tests for network functionality
  333. ##########
  334.  
  335. def test_activation(self):
  336. network = NeuralNetwork(3, 2, 1, 0.5)
  337. # Test that the activation function is a sigmoid
  338. self.assertTrue(np.all(network.activation_function(0.5) == 1/(1+np.exp(-0.5))))
  339.  
  340. def test_train(self):
  341. # Test that weights are updated correctly on training
  342. network = NeuralNetwork(3, 2, 1, 0.5)
  343. network.weights_input_to_hidden = test_w_i_h.copy()
  344. network.weights_hidden_to_output = test_w_h_o.copy()
  345.  
  346. network.train(inputs, targets)
  347. self.assertTrue(np.allclose(network.weights_hidden_to_output,
  348. np.array([[ 0.37275328, -0.03172939]])))
  349. self.assertTrue(np.allclose(network.weights_input_to_hidden,
  350. np.array([[ 0.10562014, 0.39775194, -0.29887597],
  351. [-0.20185996, 0.50074398, 0.19962801]])))
  352.  
  353. def test_run(self):
  354. # Test correctness of run method
  355. network = NeuralNetwork(3, 2, 1, 0.5)
  356. network.weights_input_to_hidden = test_w_i_h.copy()
  357. network.weights_hidden_to_output = test_w_h_o.copy()
  358.  
  359. self.assertTrue(np.allclose(network.run(inputs), 0.09998924))
  360.  
  361. suite = unittest.TestLoader().loadTestsFromModule(TestMethods())
  362. unittest.TextTestRunner().run(suite)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement