markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Time to build the networkBelow you'll build your network. We've built out the structure. You'll implement both the forward pass and backwards pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes.The network has two layers, a hid... | #############
# In the my_answers.py file, fill out the TODO sections as specified
#############
from my_answers import NeuralNetwork
def MSE(y, Y):
return np.mean((y-Y)**2) | _____no_output_____ | MIT | project-bikesharing/Predicting_bike_sharing_data.ipynb | pasbury/udacity-deep-learning-v2-pytorch |
Unit testsRun these unit tests to check the correctness of your network implementation. This will help you be sure your network was implemented correctly befor you starting trying to train it. These tests must all be successful to pass the project. | import unittest
inputs = np.array([[0.5, -0.2, 0.1]])
targets = np.array([[0.4]])
test_w_i_h = np.array([[0.1, -0.2],
[0.4, 0.5],
[-0.3, 0.2]])
test_w_h_o = np.array([[0.3],
[-0.1]])
class TestMethods(unittest.TestCase):
##########
# Un... | _____no_output_____ | MIT | project-bikesharing/Predicting_bike_sharing_data.ipynb | pasbury/udacity-deep-learning-v2-pytorch |
Training the networkHere 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 se... | import sys
####################
### Set the hyperparameters in you myanswers.py file ###
####################
from my_answers import iterations, learning_rate, hidden_nodes, output_nodes
N_i = train_features.shape[1]
network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate)
losses = {'train':[], 'val... | _____no_output_____ | MIT | project-bikesharing/Predicting_bike_sharing_data.ipynb | pasbury/udacity-deep-learning-v2-pytorch |
Check out your predictionsHere, 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. | fig, ax = plt.subplots(figsize=(8,4))
mean, std = scaled_features['cnt']
predictions = network.run(test_features).T*std + mean
ax.plot(predictions[0], label='Prediction')
ax.plot((test_targets['cnt']*std + mean).values, label='Data')
ax.set_xlim(right=len(predictions))
ax.legend()
dates = pd.to_datetime(rides.ix[test... | _____no_output_____ | MIT | project-bikesharing/Predicting_bike_sharing_data.ipynb | pasbury/udacity-deep-learning-v2-pytorch |
if 5 > 2:
print("Five is greater then two!")
#Comment
print("Hello World")
b = "sally"
b = int(4)
print(b)
b = float(4)
print(b)
x = 5
y = "John"
print(type(x))
print(type(y))
x, y, z = "one", "two", "three"
print(x)
print(y)
print(z)
x = y = z = "four"
print(x)
print(y)
print(z)
x = "enjoying"
y = "Python is "
z =... | _____no_output_____ | Apache-2.0 | Fundamentals_of_Python.ipynb | momonts/OOP-58001 | |
**Searching**Given our experience in thinking about computational complexity and correctness, I think we're ready to start thinking about a couple classic *algorithms* and problems.This week we will start with *searching*, and then move on to *sorting*We'll talk about:1. What we mean by searching2. How quickly can we s... | def simpleSearch(myList, item):
for i in range(len(myList)):
if myList[i] == item:
return i
return -1
Complexity of this is O(n)
| _____no_output_____ | BSD-3-Clause | cycle_6_searching/previous_years/Friday21stWed26_February_Searching (1).ipynb | magicicada/cs1px_2020 |
Exercise: What is the big-O time complexity of this algorithm? Can we do better? If not, why not? We can do better when we know the list is in sorted order. Example: (in class) the guessing game - trace an example. Example: (trace together on visualiser) searching in an alphabetically ordered list - looking for... | wordsList = ['android', 'badger', 'cat', 'door', 'ending', 'firefighter', 'garage', 'handle', 'iguana', 'jumper', 'kestrel', 'lemon'] | _____no_output_____ | BSD-3-Clause | cycle_6_searching/previous_years/Friday21stWed26_February_Searching (1).ipynb | magicicada/cs1px_2020 |
In-class exercise: Now, as an individual/group exercise, trace this method looking for 'handle' We have essentially been performing **binary search**. The idea is simple, but the implementation is very tricky! We will look at two implementations: one iterative, one recursive. | def iterative_binary_search(my_list, value):
lo= 0
hi = len(my_list)-1
while lo <= hi:
mid = (lo + hi) // 2
if my_list[mid] < value:
lo = mid + 1
elif value < my_list[mid]:
hi = mid - 1
else:
return mid
return -1 | _____no_output_____ | BSD-3-Clause | cycle_6_searching/previous_years/Friday21stWed26_February_Searching (1).ipynb | magicicada/cs1px_2020 |
Let's trace the operation of this code when called with: | iterative_binary_search([-3, 1, 0, 19, 20, 22, 32], 22) | _____no_output_____ | BSD-3-Clause | cycle_6_searching/previous_years/Friday21stWed26_February_Searching (1).ipynb | magicicada/cs1px_2020 |
Binary search can also be implemented recursively. I would like you to be familiar with both the iterative and the recursive versions.Let's try to translate from our iterative version to a recursive version. Look at the iterative version. Where might recursive calls go? Think back to the tracing - where might we ha... | def binary_search(my_list, lo, hi, value):
if len(my_list) < 1:
return -1
if lo > hi:
return -1
mid = lo + hi // 2
mid_value = my_list[mid]
if mid_value == value:
return mid
elif mid_value < value:
return binary_search(my_list, mid + 1, hi, value)
... | _____no_output_____ | BSD-3-Clause | cycle_6_searching/previous_years/Friday21stWed26_February_Searching (1).ipynb | magicicada/cs1px_2020 |
In lecture we will inspect this code very carefully!Let's trace it with a call of: | my_list = [-3, 1, 0, 19, 20, 22, 32]
def simplerBinary(myList, value):
if len(myList) < 1:
return None
if len(myList) == 1 and myList[0] != value:
return None
mid = (len(myList)-1)//2
mid_value = myList[mid]
if mid_value == value:
return mid
elif mid_value < value:
... | 3
| BSD-3-Clause | cycle_6_searching/previous_years/Friday21stWed26_February_Searching (1).ipynb | magicicada/cs1px_2020 |
Temporal-Difference MethodsIn this notebook, you will write your own implementations of many Temporal-Difference (TD) methods.While we have provided some starter code, you are welcome to erase these hints and write your code from scratch.--- Part 0: Explore CliffWalkingEnvWe begin by importing the necessary packages. | import sys
import gym
import numpy as np
from collections import defaultdict, deque
import matplotlib.pyplot as plt
%matplotlib inline
import check_test
from plot_utils import plot_values | _____no_output_____ | MIT | temporal-difference/Temporal_Difference.ipynb | laljarus/deep-reinforcement-learning |
Use the code cell below to create an instance of the [CliffWalking](https://github.com/openai/gym/blob/master/gym/envs/toy_text/cliffwalking.py) environment. | env = gym.make('CliffWalking-v0') | _____no_output_____ | MIT | temporal-difference/Temporal_Difference.ipynb | laljarus/deep-reinforcement-learning |
The agent moves through a $4\times 12$ gridworld, with states numbered as follows:```[[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35], [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]]```At the start of any episode, sta... | print(env.action_space)
print(env.observation_space) | Discrete(4)
Discrete(48)
| MIT | temporal-difference/Temporal_Difference.ipynb | laljarus/deep-reinforcement-learning |
In this mini-project, we will build towards finding the optimal policy for the CliffWalking environment. The optimal state-value function is visualized below. Please take the time now to make sure that you understand _why_ this is the optimal state-value function._**Note**: You can safely ignore the values of the cli... | # define the optimal state-value function
V_opt = np.zeros((4,12))
V_opt[0:13][0] = -np.arange(3, 15)[::-1]
V_opt[0:13][1] = -np.arange(3, 15)[::-1] + 1
V_opt[0:13][2] = -np.arange(3, 15)[::-1] + 2
V_opt[3][0] = -13
plot_values(V_opt) | _____no_output_____ | MIT | temporal-difference/Temporal_Difference.ipynb | laljarus/deep-reinforcement-learning |
Part 1: TD Control: SarsaIn this section, you will write your own implementation of the Sarsa control algorithm.Your algorithm has four arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction.- `alpha`... | Q = defaultdict(lambda: np.zeros(env.nA))
Q[36]
def get_probs(Q_s, epsilon, nA):
""" obtains the action probabilities corresponding to epsilon-greedy policy """
policy_s = np.ones(nA) * epsilon / nA
best_a = np.argmax(Q_s)
policy_s[best_a] = 1 - epsilon + (epsilon / nA)
return policy_s
def update_Q... | _____no_output_____ | MIT | temporal-difference/Temporal_Difference.ipynb | laljarus/deep-reinforcement-learning |
Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. If the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd ... | # obtain the estimated optimal policy and corresponding action-value function
Q_sarsa = sarsa(env, 5000, .01)
# print the estimated optimal policy
policy_sarsa = np.array([np.argmax(Q_sarsa[key]) if key in Q_sarsa else -1 for key in np.arange(48)]).reshape(4,12)
check_test.run_check('td_control_check', policy_sarsa)
p... | Episode 5000/5000 | MIT | temporal-difference/Temporal_Difference.ipynb | laljarus/deep-reinforcement-learning |
Part 2: TD Control: Q-learningIn this section, you will write your own implementation of the Q-learning control algorithm.Your algorithm has four arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction... | def q_learning(env, num_episodes, alpha, gamma=1.0, eps_start=1.0,eps_decay=0.9, eps_min=0.001,plot_every=100):
# initialize empty dictionary of arrays
nA = env.action_space.n
Q = defaultdict(lambda: np.zeros(env.nA))
# monitor performance
tmp_scores = deque(maxlen=plot_every) # deque for k... | _____no_output_____ | MIT | temporal-difference/Temporal_Difference.ipynb | laljarus/deep-reinforcement-learning |
Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. If the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd l... | # obtain the estimated optimal policy and corresponding action-value function
Q_sarsamax = q_learning(env, 5000, .01)
# print the estimated optimal policy
policy_sarsamax = np.array([np.argmax(Q_sarsamax[key]) if key in Q_sarsamax else -1 for key in np.arange(48)]).reshape((4,12))
check_test.run_check('td_control_chec... | Episode 5000/5000 | MIT | temporal-difference/Temporal_Difference.ipynb | laljarus/deep-reinforcement-learning |
Part 3: TD Control: Expected SarsaIn this section, you will write your own implementation of the Expected Sarsa control algorithm.Your algorithm has four arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment int... | def update_Q_expected_sarsa(alpha, gamma,epsilon,nA, Q, state, action, reward, next_state):
"""Returns updated Q-value for the most recent experience."""
current = Q[state][action] # estimate in Q-table (for current state, action pair)
# get value of state, action pair at next time step
policy_s=ge... | _____no_output_____ | MIT | temporal-difference/Temporal_Difference.ipynb | laljarus/deep-reinforcement-learning |
Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. If the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd ... | # obtain the estimated optimal policy and corresponding action-value function
Q_expsarsa = expected_sarsa(env, 5000, 0.5)
# print the estimated optimal policy
policy_expsarsa = np.array([np.argmax(Q_expsarsa[key]) if key in Q_expsarsa else -1 for key in np.arange(48)]).reshape(4,12)
check_test.run_check('td_control_ch... | Episode 5000/5000 | MIT | temporal-difference/Temporal_Difference.ipynb | laljarus/deep-reinforcement-learning |
Pandas | import pandas as pd | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
We introduced the Pandas module and the DataFrame object in the lesson on [basic data science modules](DS_Basic_DS_Modules.ipynb). We learned how to construct a DataFrame, add data, retrieve data, and [basic reading and writing to disk](DS_IO.ipynb). Now we'll explore the DataFrame object and its powerful analysis meth... | !ls -lh ./data/yelp.json.gz
import gzip
import simplejson as json
with gzip.open('./data/yelp.json.gz', 'r') as f:
yelp_data = [json.loads(line) for line in f]
yelp_df = pd.DataFrame(yelp_data)
yelp_df.head() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
Pandas DataFrame and SeriesThe Pandas DataFrame is a highly structured object. Each row corresponds with some physical entity or event. We think of all of the information in a given row as referring to one object (e.g. a business). Each column contains one type of data, both semantically (e.g. names, counts of reviews... | yelp_df.dtypes | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
We can reference the columns by name, like we would with a `dict`. | yelp_df['city'].head()
type(yelp_df['city']) | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
An individual column is a Pandas `Series`. A `Series` has a `name` and a `dtype` (similar to a NumPy array). A `DataFrame` is essentially a `dict` of `Series` objects. The `Series` has an `index` attribute, which label the rows. The index is essentially a set of keys for referencing the rows. We can have an index compo... | yelp_df['city'].index | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
The `DataFrame` has an `index` given by the union of indices of its constituent `Series` (we'll explore this later in more detail). Since a `DataFrame` is a `dict` of `Series`, we can select a column and then a row using square bracket notation, but not the reverse (however, the `loc` method works around this). | # this works
yelp_df['city'][100]
%%expect_exception KeyError
# this doesn't
yelp_df[100]['city']
yelp_df.loc[100, 'city'] | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
Understanding the underlying structure of the `DataFrame` object as a `dict` of `Series` will help you avoid errors and help you think about how the `DataFrame` should behave when we begin doing more complicated analysis.We can _aggregate_ data in a `DataFrame` using methods like `mean`, `sum`, `count`, and `std`. To v... | yelp_df.describe() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
The utility of a DataFrame comes from its ability to split data into groups, using the `groupby` method, and then perform custom aggregations using the `apply` or `aggregate` method. This process of splitting the data into groups, applying an aggregation, and then collecting the results is [discussed in detail in the P... | from string import ascii_letters, digits
import numpy as np
import datetime
usernames = ['alice36', 'bob_smith', 'eve']
passwords = [''.join(np.random.choice(list(ascii_letters + digits), 8)) for x in range(3)]
creation_dates = [datetime.datetime.now().date() - datetime.timedelta(int(x)) for x in np.random.randint(0, ... | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
The `DataFrame` is also closely related to the NumPy `ndarray`. | random_data = np.random.random((4,3))
random_data
df_random = pd.DataFrame(random_data, columns=['a', 'b', 'c'])
df_random | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
To add a new column or row, we simply use `dict`-like assignment. | emails = ['alice.chan@gmail.com', 'bwsmith1983@gmail.com', 'fakemail123@yahoo.com']
df['email'] = emails
df
# loc references index value, NOT position
# for position use iloc
df.loc[3] = ['2015-01-29', '38uzFJ1n', 'melvintherobot', 'moviesrgood@moviesrgood.com']
df | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
We can also drop columns and rows. | df.drop(3)
# to drop a column, need axis=1
df.drop('email', axis=1) | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
Notice when we dropped the `'email'` column, the row at index 3 was in the `DataFrame`, even though we just dropped it! Most operations in Pandas return a _copy_ of the `DataFrame`, rather than modifying the `DataFrame` object itself. Therefore, in order to permanently alter the `DataFrame`, we either need to reassign ... | df.drop(3, inplace=True)
df | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
Since the `index` and column names are important for interacting with data in the DataFrame, we should make sure to set them to useful values. We can do this during construction or after. | df = pd.DataFrame({'email': emails, 'password': passwords, 'date-created': creation_dates}, index=usernames)
df.index.name = 'users' # it can be helpful to give the index a name
df
# alternatively
df = pd.DataFrame(list(zip(usernames, emails, passwords, creation_dates)))
df
df.columns = ['username', 'email', 'password'... | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
We can have multiple levels to an index. We'll discover that for some data sets it is necessary to have multiple levels to the index in order to uniquely identify a row. | df.set_index(['username', 'email']) | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
Reading data from fileWe can also construct a DataFrame using data stored in a file or received from a website. The data source might be [JSON](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html), [HTML](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html), [CSV](http... | csv = [','.join(map(lambda x: str(x), row)) for row in np.vstack([df.columns, df])]
with open('./data/read_csv_example.csv', 'w') as f:
[f.write(line + '\n') for line in csv]
!cat ./data/read_csv_example.csv
csv
pd.read_csv('./data/read_csv_example.csv')
# we can also set an index from the data
pd.read_csv('./data... | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
Even within a single file format, data can be arranged and formatted in many ways. These have been just a few examples of the kinds of arguments you might need to use with `read_csv` in order to read data into a DataFrame in an organized way. Filtering DataFramesOne of the powerful analytical tools of the Pandas DataF... | yelp_df.head() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
We see the Yelp data set has a `'state'` column. If we are only interested in businesses in Arizona (AZ), we can filter the DataFrame and select only that data. | az_yelp_df = yelp_df[yelp_df['state'] == 'AZ']
az_yelp_df.head()
az_yelp_df['state'].unique() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
We can combine criteria using logic. What if we're only interested in businesses with more than 10 reviews in Arizona? | yelp_df[(yelp_df['state'] == 'AZ') & (yelp_df['review_count'] > 10)].head() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
How does this filtering work?When we write `yelp_df['state'] == 'AZ'`, Pandas selects the `'state'` column and checks whether each row is `'AZ'`. If so, that row is marked `True`, and if not, it is marked `False`. This is how we would normally expect a conditional to work, only now applied to an entire Pandas `Series`.... | (yelp_df['state'] == 'AZ').head() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
We can use a `Series` (or any similar object) of Boolean variables to index the DataFrame. | df
df[[True, False, True]] | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
This let's us filter a DataFrame using idiomatic logical expressions like `yelp_df['review_count'] > 10`.As another example, let's consider the `'open'` column, which is a `True`/`False` flag for whether a business is open. This is also a Boolean Pandas `Series`, so we can just use it directly. | # the open businesses
yelp_df[yelp_df['open']].head()
# the closed businesses
yelp_df[~yelp_df['open']].head() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
Notice in an earlier expression we wrote `(yelp_df['state'] == 'AZ') & (yelp_df['review_count'] > 10)`. Normally in Python we use the word `and` when we are working with logic. In Pandas we have to use _bit-wise_ logical operators; all that's important to know is the following equivalencies:`~` = `not` `&` = `and` `|... | vegas_yelp_df = yelp_df[yelp_df['city'].str.contains('Vegas')]
vegas_yelp_df.head()
vegas_yelp_df['city'].unique() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
Applying functions and data aggregationTo analyze the data in the dataframe, we'll need to be able to apply functions to it. Pandas has many mathematical functions built in already, and DataFrames and Series can be passed to NumPy functions (since they behave like NumPy arrays). | log_review_count = np.log(yelp_df['review_count'])
print(log_review_count.head())
print(log_review_count.shape)
mean_review_count = yelp_df['review_count'].mean()
print(mean_review_count) | 29.300648426379883
| MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
In the first example we took the _logarithm_ of the review count for each business. In the second case, we calculated the mean review count of all businesses. In the first case, we ended up with a number for each business. We _transformed_ the review counts using the logarithm. In the second case, we _summarized_ the r... | def get_delivery_attr(attr_dict):
return attr_dict.get('Delivery') | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
If we give this function a `dict` from the `'attributes'` column, it will look for the `'Delivery'` key. If it finds that key, it returns the value. If it doesn't find the key, it will return none. | print(get_delivery_attr(yelp_df.loc[0, 'attributes']))
print(get_delivery_attr(yelp_df.loc[1, 'attributes']))
print(get_delivery_attr(yelp_df.loc[2, 'attributes'])) | None
False
False
| MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
We could iterate over the rows of `yelp_df['attributes']` to get all of the values, but there is a better way. DataFrames and Series have an `apply` method that allows us to apply our function to the entire data set at once, like we did earlier with `np.log`. | delivery_attr = yelp_df['attributes'].apply(get_delivery_attr)
delivery_attr.head() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
We can make a new column in our DataFrame with this transformed (and useful) information. | yelp_df['delivery'] = delivery_attr
# to find businesses that deliver
yelp_df[yelp_df['delivery'].fillna(False)].head() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
It's less common (though possible) to use `apply` on an entire DataFrame rather than just one column. Since a DataFrame might contain many types of data, we won't usually want to apply the same transformation or aggregation across all of the columns. Exercise | # filter categories
categories_attr = yelp_df['categories'].apply(lambda x: 'Restaurants' in x)
categories_attr
yelp_df['Restaurants'] = categories_attr
portion = yelp_df[yelp_df['Restaurants']]['delivery'].fillna(False).mean() * 100
print("Portion of Restaurants that deliver: %.2f" % portion) | Portion of Restaurants that deliver: 16.25
| MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
Data aggregation with `groupby`Data aggregation is an [_overloaded_](https://en.wikipedia.org/wiki/Function_overloading) term. It refers to both data summarization (as above) but also to the combining of different data sets.With our Yelp data, we might be interested in comparing the star ratings of businesses in diffe... | stars_by_city = yelp_df.groupby('city')['stars'].mean()
stars_by_city.head() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
We can also apply multiple functions at once. It might be helpful to know the standard deviation of star ratings, the total number of reviews, and the count of businesses as well. | agg_by_city = yelp_df.groupby('city').agg({'stars': ['mean', 'std'], 'review_count': 'sum', 'business_id': 'count'})
agg_by_city.head()
new_columns = map(lambda x: '_'.join(x),
zip(agg_by_city.columns.get_level_values(0),
agg_by_city.columns.get_level_values(1)))
# unstacking the... | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
How does this work? What does `groupby` do? Let's start by inspecting the result of `groupby`. | by_city = yelp_df.groupby('city')
by_city
dir(by_city)
print(type(by_city.groups))
list(by_city.groups.items())[:5]
by_city.get_group('Anthem').head() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
When we use `groupby` on a column, Pandas builds a `dict`, using the unique elements of the column as the keys and the index of the rows in each group as the values. This `dict` is stored in the `groups` attribute. Pandas can then use this `dict` to direct the application of aggregating functions over the different gro... | yelp_df.sort_values('stars').head()
yelp_df.set_index('business_id').sort_index().head() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
Don't forget that most Pandas operations return a copy of the DataFrame, and do not update the DataFrame in place (unless we tell it to)! Joining data sets Often we will want to augment one data set with data from another. For instance, businesses in big cities probably get more reviews than those in small cities. It ... | census = pd.read_csv('./data/PEP_2016_PEPANNRES.csv', skiprows=[1])
census.head()
# construct city & state fields
census['city'] = census['GEO.display-label'].apply(lambda x: x.split(', ')[0])
census['state'] = census['GEO.display-label'].apply(lambda x: x.split(', ')[2])
# convert state names to abbreviations
print(... | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
The `merge` function looks through the `'state'` and `'city'` columns of `yelp_df` and `census` and tries to match up rows that share values. When a match is found, the rows are combined. What happens when a match is not found? We can imagine four scenarios: 1. We only keep rows from `yelp_df` and `census` if they mat... | print(yelp_df.shape)
print(merged_df.shape) | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
There are a lot of cities in `yelp_df` that aren't in `census`! We might want to keep these rows, but we don't need any census data where there are no businesses. Then we should use a _left join_. | merged_df = yelp_df.merge(census, on=['state', 'city'], how='left')
print(yelp_df.shape)
print(merged_df.shape) | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
Sometimes we don't need to merge together the columns of separate data sets, but just need to add more rows. For example, the New York City subway system [releases data about how many customers enter and exit the station each week](http://web.mta.info/developers/turnstile.html). Each weekly data set has the same column... | nov18 = pd.read_csv('http://web.mta.info/developers/data/nyct/turnstile/turnstile_171118.txt')
nov11 = pd.read_csv('http://web.mta.info/developers/data/nyct/turnstile/turnstile_171111.txt')
nov18.head()
nov11.head()
nov = pd.concat([nov18, nov11])
nov['DATE'].unique() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
We can also use `concat` to perform inner and outer joins based on index. For example, we can perform some data aggregation and then join the results onto the original DataFrame. | city_counts = yelp_df.groupby('city')['business_id'].count().rename('city_counts')
city_counts.head()
yelp_df.head()
pd.concat([yelp_df.set_index('city'), city_counts], axis=1, join='inner').reset_index().head() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
Pandas provides [extensive documentation](https://pandas.pydata.org/pandas-docs/stable/merging.html) with diagrammed examples on different methods and approaches for joining data. Working with time seriesPandas has a well-designed backend for inferring dates and times from strings and doing meaningful computations wit... | pop_growth = pd.read_html('https://web.archive.org/web/20170127165708/https://www.census.gov/population/international/data/worldpop/table_population.php', attrs={'class': 'query_table'}, parse_dates=[0])[0]
pop_growth.dropna(inplace=True)
pop_growth.head() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
By setting the `'Year'` column to the index, we can easily aggregate data by date using the `resample` method. The `resample` method allows us to decrease or increase the sampling frequency of our data. For instance, maybe instead of yearly data, we want to see average quantities for each decade. | pop_growth.set_index('Year', inplace=True)
pop_growth.resample('10AS').mean() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
This kind of resampling is called _downsampling_, because we are decreasing the sampling frequency of the data. We can choose how to aggregate the data from each decade (e.g. `mean`). Options for aggregation include `mean`, `median`, `sum`, `last`, and `first`.We can also _upsample_ data. In this case, we don't have da... | pop_growth.resample('1Q').bfill().head()
pop_growth.resample('1Q').ffill().head() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
Pandas' time series capabilities are built on the Pandas `Timestamp` class. | print(pd.Timestamp('January 8, 2017'))
print(pd.Timestamp('01/08/17 20:13'))
print(pd.Timestamp(1.4839*10**18))
print(pd.Timestamp('Feb. 11 2016 2:30 am') - pd.Timestamp('2015-08-03 5:14 pm'))
from pandas.tseries.offsets import BDay, Day, BMonthEnd
print(pd.Timestamp('January 9, 2017') - Day(4))
print(pd.Timestamp('Ja... | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
If we're entering time series data into a DataFrame it will often be useful to create a range of dates. | pd.date_range(start='1/8/2017', end='3/2/2017', freq='B') | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
The `Timestamp` class is compatible with Python's `datetime` module. | import datetime
pd.Timestamp('May 1, 2017') - datetime.datetime(2017, 1, 8) | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
Visualizing data with PandasVisualizing a data set is an important first step in drawing insights. We can easily pass data from Pandas to Matplotlib for visualizations, but Pandas also plugs into Matplotlib directly through methods like `plot` and `hist`. | yelp_df['review_count'].apply(np.log).hist(bins=30)
pop_growth['Annual Growth Rate (%)'].plot() | _____no_output_____ | MIT | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone |
Development of an End-to-End ML Model for Navigating an RC car with a Lidar Run in Google Colab View source on GitHub Environment Setup Import Dependencies | import os
import csv
import cv2
import matplotlib.pyplot as plt
import random
import pprint
import numpy as np
from numpy import expand_dims
%tensorflow_version 1.x
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
from keras import backend as K
from keras.models import Model, Sequential
from keras.... | Using TensorFlow backend.
| BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Confirm TensorFlow can see the GPU Simply select "GPU" in the Accelerator drop-down in Notebook Settings (either through the Edit menu or the command palette at cmd/ctrl-shift-P). | device_name = tf.test.gpu_device_name()
if device_name != '/device:GPU:0':
# Raise SystemError('GPU device not found')
print('GPU device not found')
else:
print('Found GPU at: {}'.format(device_name))
# GPU count and name
!nvidia-smi -L | Found GPU at: /device:GPU:0
GPU 0: Tesla P100-PCIE-16GB (UUID: GPU-47aa6e31-82c5-f73d-7d78-373fb85348e8)
| BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Load the Dataset Download and Extract the Dataset | # Download the dataset
!curl -O https://selbystorage.s3-us-west-2.amazonaws.com/research/office_3/office_3.tar.gz
data_set = 'office_3'
tar_file = data_set + '.tar.gz'
# Unzip the .tgz file
# -x for extract
# -v for verbose
# -z for gnuzip
# -f for file (should come at last just before file name)
# -C to extract the ... | office_3/
office_3/ml_training_2019-12-26-14-59-40_12.yaml
office_3/ml_training_2019-12-28-10-32-38_7.yaml
office_3/camera.csv
office_3/ml_training_2019-12-26-14-54-02_0.yaml
office_3/ml_training_2019-12-28-10-31-15_5.yaml
office_3/ml_training_2019-12-26-14-54-58_2.yaml
office_3/ml_training_2019-12-26-14-59-11_11.yaml
... | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Parse the CSV File | # Define path to csv file
csv_path = data_set + '/interpolated.csv'
# Load the CSV file into a pandas dataframe
df = pd.read_csv(csv_path, sep=",")
# Print the dimensions
print("Dataset Dimensions:")
print(df.shape)
# Print the first 5 lines of the dataframe for review
print("\nDataset Summary:")
df.head(5)
| Dataset Dimensions:
(6253, 8)
Dataset Summary:
| BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Clean and Pre-process the Dataset Remove Unneccessary Columns | # Remove 'index' and 'frame_id' columns
df.drop(['index','frame_id'],axis=1,inplace=True)
# Verify new dataframe dimensions
print("Dataset Dimensions:")
print(df.shape)
# Print the first 5 lines of the new dataframe for review
print("\nDataset Summary:")
df.head(5) | Dataset Dimensions:
(6253, 6)
Dataset Summary:
| BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Detect Missing Data | # Detect Missing Values
print("Any Missing Values?: {}".format(df.isnull().values.any()))
# Total Sum
print("\nTotal Number of Missing Values: {}".format(df.isnull().sum().sum()))
# Sum Per Column
print("\nTotal Number of Missing Values per Column:")
print(df.isnull().sum()) | Any Missing Values?: False
Total Number of Missing Values: 0
Total Number of Missing Values per Column:
timestamp 0
width 0
height 0
filename 0
angle 0
speed 0
dtype: int64
| BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Remove Zero Throttle Values | # Determine if any throttle values are zeroes
print("Any 0 throttle values?: {}".format(df['speed'].eq(0).any()))
# Determine number of 0 throttle values:
print("\nNumber of 0 throttle values: {}".format(df['speed'].eq(0).sum()))
# Remove rows with 0 throttle values
if df['speed'].eq(0).any():
df = df.query('speed ... | Any 0 throttle values?: True
Number of 0 throttle values: 55
New Dataset Dimensions:
(6198, 6)
| BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
View Label Statistics | # Steering Command Statistics
print("\nSteering Command Statistics:")
print(df['angle'].describe())
print("\nThrottle Command Statistics:")
# Throttle Command Statistics
print(df['speed'].describe()) |
Steering Command Statistics:
count 6198.000000
mean 0.822324
std 1.008619
min -1.533349
25% 0.471148
50% 1.380756
75% 1.466080
max 1.531508
Name: angle, dtype: float64
Throttle Command Statistics:
count 6198.000000
mean 0.129354
std 0.015255
m... | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
View Histogram of Steering Commands | #@title Select the number of histogram bins
num_bins = 25 #@param {type:"slider", min:5, max:50, step:1}
hist, bins = np.histogram(df['angle'], num_bins)
center = (bins[:-1]+ bins[1:]) * 0.5
plt.bar(center, hist, width=0.05)
#plt.plot((np.min(df['angle']), np.max(df['angle'])), (samples_per_bin, samples_per_bin))
# N... | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
View a Sample Image | # View a Single Image
index = random.randint(0,df.shape[0]-1)
img_name = data_set + '/' + df.loc[index,'filename']
angle = df.loc[index,'angle']
center_image = cv2.imread(img_name)
center_image_mod = cv2.resize(center_image, (320,180))
center_image_mod = cv2.cvtColor(center_image_mod,cv2.COLOR_RGB2BGR)
# Crop the i... | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
View Multiple Images | # Number of Images to Display
num_images = 4
# Display the images
i = 0
for i in range (i,num_images):
index = random.randint(0,df.shape[0]-1)
image_path = df.loc[index,'filename']
angle = df.loc[index,'angle']
img_name = data_set + '/' + image_path
image = cv2.imread(img_name)
image = cv2.resi... | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Split the Dataset Define an ImageDataGenerator to Augment Images | # Create image data augmentation generator and choose augmentation types
datagen = ImageDataGenerator(
#rotation_range=20,
zoom_range=0.15,
#width_shift_range=0.1,
#height_shift_range=0.2,
... | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
View Image Augmentation Examples | # load the image
index = random.randint(0,df.shape[0]-1)
img_name = data_set + '/' + df.loc[index,'filename']
original_image = cv2.imread(img_name)
original_image = cv2.cvtColor(original_image,cv2.COLOR_RGB2BGR)
original_image = cv2.resize(original_image, (320,180))
label = df.loc[index,'angle']
# convert to numpy ar... | Augmenting a Single Image:
| BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Define a Data Generator | def generator(samples, batch_size=32, aug=0):
num_samples = len(samples)
while 1: # Loop forever so the generator never terminates
for offset in range(0, num_samples, batch_size):
batch_samples = samples[offset:offset + batch_size]
#print(batch_samples)
images = []... | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Split the Dataset | samples = []
samples = df.values.tolist()
sklearn.utils.shuffle(samples)
train_samples, validation_samples = train_test_split(samples, test_size=0.2)
print("Number of traing samples: ", len(train_samples))
print("Number of validation samples: ", len(validation_samples)) | ('Number of traing samples: ', 4958)
('Number of validation samples: ', 1240)
| BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Define Training and Validation Data Generators | batch_size_value = 32
img_aug = 1
train_generator = generator(train_samples, batch_size=batch_size_value, aug=img_aug)
validation_generator = generator(
validation_samples, batch_size=batch_size_value, aug=0) | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Compile and Train the Model Build the Model | # Initialize the model
model = Sequential()
# trim image to only see section with road
# (top_crop, bottom_crop), (left_crop, right_crop)
model.add(Cropping2D(cropping=((height_min,bottom_crop), (width_min,right_crop)), input_shape=(180,320,3)))
# Preprocess incoming data, centered around zero with small standard dev... | /usr/local/lib/python2.7/dist-packages/ipykernel_launcher.py:14: UserWarning: Update your `SpatialDropout2D` call to the Keras 2 API: `SpatialDropout2D(0.5, data_format=None)`
| BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Setup Checkpoints | # checkpoint
model_path = './model'
!if [ -d $model_path ]; then echo 'Directory Exists'; else mkdir $model_path; fi
filepath = model_path + "/weights-improvement-{epoch:02d}-{val_loss:.2f}.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='auto', period=1) | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Setup Early Stopping to Prevent Overfitting | # The patience parameter is the amount of epochs to check for improvement
early_stop = EarlyStopping(monitor='val_loss', patience=10) | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Reduce Learning Rate When a Metric has Stopped Improving | reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2,
patience=5, min_lr=0.001) | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Setup Tensorboard | # Clear any logs from previous runs
!rm -rf ./Graph/
# Launch Tensorboard
!pip install -U tensorboardcolab
from tensorboardcolab import *
tbc = TensorBoardColab()
# Configure the Tensorboard Callback
tbCallBack = TensorBoard(log_dir='./Graph',
histogram_freq=1,
writ... | Requirement already up-to-date: tensorboardcolab in /usr/local/lib/python2.7/dist-packages (0.0.22)
Wait for 8 seconds...
TensorBoard link:
http://5deaa30c.ngrok.io
| BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Load Existing Model | load = True #@param {type:"boolean"}
if load:
# Returns a compiled model identical to the previous one
!curl -O https://selbystorage.s3-us-west-2.amazonaws.com/research/office_3/model_intensity.h5
!mv model_intensity.h5 model/
model_path_full = model_path + '/' + 'model_intensity.h5'
model = load_model(model... | % Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 8297k 100 8297k 0 0 10.4M 0 --:--:-- --:--:-- --:--:-- 10.4M
Loaded previous model: ./model/model_intensity.h5
| BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Train the Model | # Define step sizes
STEP_SIZE_TRAIN = len(train_samples) / batch_size_value
STEP_SIZE_VALID = len(validation_samples) / batch_size_value
# Define number of epochs
n_epoch = 50
# Define callbacks
# callbacks_list = [TensorBoardColabCallback(tbc)]
# callbacks_list = [TensorBoardColabCallback(tbc), early_stop]
# callbac... | Epoch 1/50
154/154 [==============================] - 87s 563ms/step - loss: 1.6989 - mean_squared_error: 1.6989 - mean_absolute_error: 1.2303 - mean_absolute_percentage_error: 2537433.2419 - cosine_proximity: -0.0099 - val_loss: 1.7245 - val_mean_squared_error: 1.7245 - val_mean_absolute_error: 1.2423 - val_mean_absol... | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Save the Model | # Save model
model_path_full = model_path + '/'
model.save(model_path_full + 'model.h5')
with open(model_path_full + 'model.json', 'w') as output_json:
output_json.write(model.to_json()) | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Evaluate the Model Plot the Training Results | # Plot the training and validation loss for each epoch
print('Generating loss chart...')
plt.plot(history_object.history['loss'])
plt.plot(history_object.history['val_loss'])
plt.title('model mean squared error loss')
plt.ylabel('mean squared error loss')
plt.xlabel('epoch')
plt.legend(['training set', 'validation set'... | Generating loss chart...
Done.
| BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Print Performance Metrics | scores = model.evaluate_generator(validation_generator, STEP_SIZE_VALID, use_multiprocessing=True)
metrics_names = model.metrics_names
for i in range(len(model.metrics_names)):
print("Metric: {} - {}".format(metrics_names[i],scores[i]))
| Metric: loss - 0.190782873646
Metric: mean_squared_error - 0.190782873646
Metric: mean_absolute_error - 0.330186681136
Metric: mean_absolute_percentage_error - 28329829.3002
Metric: cosine_proximity - -0.870888157895
| BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Compute Prediction Statistics | # Define image loading function
def load_images(dataframe):
# initialize images array
images = []
for i in dataframe.index.values:
name = data_set + '/' + dataframe.loc[i,'filename']
center_image = cv2.imread(name)
center_image = cv2.resize(center_image, (320,180))
images.append(center_image... | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Plot a Prediction | # Plot the image with the actual and predicted steering angle
index = random.randint(0,df_test.shape[0]-1)
img_name = data_set + '/' + df_test.loc[index,'filename']
center_image = cv2.imread(img_name)
center_image = cv2.cvtColor(center_image,cv2.COLOR_RGB2BGR)
center_image_mod = cv2.resize(center_image, (320,180))
plt... | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Visualize the Network Show the Model Summary | model.summary() | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Access Individual Layers | # Creating a mapping of layer name ot layer details
# We will create a dictionary layers_info which maps a layer name to its charcteristics
layers_info = {}
for i in model.layers:
layers_info[i.name] = i.get_config()
# Here the layer_weights dictionary will map every layer_name to its corresponding weights
layer_... | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Visualize the Filters | # Visualize the first filter of each convolution layer
layers = model.layers
layer_ids = [2,3,4,6,7]
#plot the filters
fig,ax = plt.subplots(nrows=1,ncols=5)
for i in range(5):
ax[i].imshow(layers[layer_ids[i]].get_weights()[0][:,:,:,0][:,:,0],cmap='gray')
ax[i].set_title('Conv'+str(i+1))
ax[i].set_xticks(... | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Visualize the Saliency Map | !pip install -I scipy==1.2.*
!pip install git+https://github.com/raghakot/keras-vis.git -U
# import specific functions from keras-vis package
from vis.utils import utils
from vis.visualization import visualize_saliency, visualize_cam, overlay
# View a Single Image
index = random.randint(0,df.shape[0]-1)
img_name = da... | _____no_output_____ | BSD-2-Clause | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS |
Task 0 (YOLOv5 note)용어, 개념, 궁금한 문제들 기록 (link) Task 1 (사전작업) YOLOv5 모델작업에 들어가기전, 데이터를 확인하고 정제한 작업 내용을 담고 있습니다(here) Putting data into a folder Convert the Annotations into the YOLOv5 Format Testing the annotations Partition the Dataset Task 2 (학습) YOLOv5 환경설정부터 학습한 작업내용을 담고 있습니다(link) Set up the environm... | ############ 경로설정 ############
from google.colab import drive
drive.mount('/content/gdrive')
%cd /content/gdrive/MyDrive/객체탐지
!ls
############ xml 파일 확인 ############
#!cat dataset/labels/Bright_20130218_153731_000210_v001_1.xml
############ XML파일에서 정보 긁어오는 함수 ############
def extract_info_from_xml(xml_file):
... | _____no_output_____ | MIT | yolov5/YOLOv5_Task1.ipynb | sosodoit/yolov5 |
**3. Testing the annotations**xml이 잘 변환되어서 bb 잘 잡는지 테스트 | %cd /content/gdrive/MyDrive/객체탐지
random.seed(0)
class_id_to_name_mapping = dict(zip(class_name_to_id_mapping.values(), class_name_to_id_mapping.keys()))
def plot_bounding_box(image, annotation_list):
annotations = np.array(annotation_list)
w, h = image.size
plotted_image = ImageDraw.Draw(image)... | _____no_output_____ | MIT | yolov5/YOLOv5_Task1.ipynb | sosodoit/yolov5 |
**4. Partition the Dataset**YOLOv5 학습 진행 하기전, train-valid dataset을 나누는 작업을 진행 | ########## 사진과 라벨링 파일명 읽어오기 ##########
images = [os.path.join('dataset/images', x) for x in os.listdir('dataset/images')]
annotations = [os.path.join('dataset/labels', x) for x in os.listdir('dataset/labels') if x[-3:] == "txt"]
images.sort()
annotations.sort()
########## train-valid 8:2 비율로 데이터셋 나누기 ##########
train_... | _____no_output_____ | MIT | yolov5/YOLOv5_Task1.ipynb | sosodoit/yolov5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.