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
When taking routes into consideration, __"Western"__ Subdivision, route 00500, has issued the most street sweeping citations.- Is route 00500 larger than other street sweeping routes?
top_3_routes = df_citations.groupby(['agency', 'route'])\ .size()\ .nlargest(3)\ .sort_index()\ .rename('num_citations')\ .reset_index()\ .sort_values(by='num...
_____no_output_____
MIT
MVP.ipynb
Promeos/LADOT-Street-Sweeping-Transition-Pan
What is the weekly distibution of citation times?
sns.set_context('talk') plt.figure(figsize=(13, 12)) sns.boxplot(data=df_citations, x="day_of_week", y="issue_time_num", order=["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], whis=3); plt.title("Distribution Citation Issue Times Througho...
_____no_output_____
MIT
MVP.ipynb
Promeos/LADOT-Street-Sweeping-Transition-Pan
New to Plotly?Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the client and [reading the primer](https://plot.ly/python/getting-started/).You can set up Plotly to work in [online](https://plot.ly/python/getting-started/initialization-for-online-pl...
import plotly plotly.__version__
_____no_output_____
CC-BY-3.0
_posts/python/style/colorscales/colorscales.ipynb
ayulockin/documentation
Custom Discretized Heatmap Colorscale
import plotly.plotly as py py.iplot([{ 'z': [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ], 'type': 'heatmap', 'colorscale': [ # Let first 10% (0.1) of the values have color rgb(0, 0, 0) [0, 'rgb(0, 0, 0)'], [0.1, 'rgb(0, 0, 0)'], # Let values between 10-20% of the min and ...
_____no_output_____
CC-BY-3.0
_posts/python/style/colorscales/colorscales.ipynb
ayulockin/documentation
Colorscale for Scatter Plots
import plotly.plotly as py import plotly.graph_objs as go data = [ go.Scatter( y=[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], marker=dict( size=16, cmax=39, cmin=0, color=[0,...
_____no_output_____
CC-BY-3.0
_posts/python/style/colorscales/colorscales.ipynb
ayulockin/documentation
Colorscale for Contour Plot
import plotly.plotly as py import plotly.graph_objs as go data = [ go.Contour( z=[[10, 10.625, 12.5, 15.625, 20], [5.625, 6.25, 8.125, 11.25, 15.625], [2.5, 3.125, 5., 8.125, 12.5], [0.625, 1.25, 3.125, 6.25, 10.625], [0, 0.625, 2.5, 5.625, 10]], colorsca...
_____no_output_____
CC-BY-3.0
_posts/python/style/colorscales/colorscales.ipynb
ayulockin/documentation
Custom Heatmap Colorscale
import plotly.plotly as py import plotly.graph_objs as go import six.moves.urllib import json response = six.moves.urllib.request.urlopen('https://raw.githubusercontent.com/plotly/datasets/master/custom_heatmap_colorscale.json') dataset = json.load(response) data = [ go.Heatmap( z=dataset['z'], c...
_____no_output_____
CC-BY-3.0
_posts/python/style/colorscales/colorscales.ipynb
ayulockin/documentation
Custom Contour Plot Colorscale
import plotly.plotly as py import plotly.graph_objs as go data = [ go.Contour( z=[[10, 10.625, 12.5, 15.625, 20], [5.625, 6.25, 8.125, 11.25, 15.625], [2.5, 3.125, 5., 8.125, 12.5], [0.625, 1.25, 3.125, 6.25, 10.625], [0, 0.625, 2.5, 5.625, 10]], colorsca...
_____no_output_____
CC-BY-3.0
_posts/python/style/colorscales/colorscales.ipynb
ayulockin/documentation
Custom Colorbar
import plotly.plotly as py import plotly.graph_objs as go import six.moves.urllib import json response = six.moves.urllib.request.urlopen('https://raw.githubusercontent.com/plotly/datasets/master/custom_heatmap_colorscale.json') dataset = json.load(response) data = [ go.Heatmap( z=dataset['z'], c...
_____no_output_____
CC-BY-3.0
_posts/python/style/colorscales/colorscales.ipynb
ayulockin/documentation
Dash Example
from IPython.display import IFrame IFrame(src= "https://dash-simple-apps.plotly.host/dash-colorscaleplot/" ,width="100%" ,height="650px", frameBorder="0")
_____no_output_____
CC-BY-3.0
_posts/python/style/colorscales/colorscales.ipynb
ayulockin/documentation
Find the dash app source code [here](https://github.com/plotly/simple-example-chart-apps/tree/master/colorscale) Reference See https://plot.ly/python/reference/ for more information and chart attribute options!
from IPython.display import display, HTML display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />')) display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-not...
_____no_output_____
CC-BY-3.0
_posts/python/style/colorscales/colorscales.ipynb
ayulockin/documentation
Clustering Chicago Public Libraries by Top 10 Nearby Venues Author: Kunyu HeUniversity of Chicago CAPP'20 Executive Summary In this notebook, I clustered 80 public libraries in the city of Chicago into 7 clusters, based on the categories of their top ten venues nearby. It would be a nice guide for those who would like...
import pandas as pd import numpy as np import re import requests import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties from pandas.io.json import json_normalize from sklearn.decomposition import TruncatedSVD from sklearn.cluster import KMeans from scipy.cluster.hierarchy import linkage, de...
_____no_output_____
MIT
Clustering Chicago Public Libraries.ipynb
KunyuHe/Clustering-Chicago-Public-Libraries
For visualization, install [folium](https://github.com/python-visualization/folium) and make an additional import.
!conda install --quiet -c conda-forge folium --yes import folium %matplotlib inline title = FontProperties() title.set_family('serif') title.set_size(16) title.set_weight('bold') axis = FontProperties() axis.set_family('serif') axis.set_size(12) plt.rcParams['figure.figsize'] = [12, 8]
_____no_output_____
MIT
Clustering Chicago Public Libraries.ipynb
KunyuHe/Clustering-Chicago-Public-Libraries
Hard-code the geographical coordinates of the City of Chicago based on [this]((https://www.latlong.net/place/chicago-il-usa-1855.html)) page. Also prepare formatting parameters for folium map markers.
LATITUDE, LOGITUDE = 41.881832, -87.623177 ICON_COLORS = ['red', 'blue', 'green', 'purple', 'orange', 'beige', 'darked'] HTML = """ <center><h4><b>Library {}</b></h4></center> <h5><b>Cluster:</b> {};</h5> <h5><b>Hours of operation:</b><br> {}</h5> <h5><b>Top five venues:</b><br>...
_____no_output_____
MIT
Clustering Chicago Public Libraries.ipynb
KunyuHe/Clustering-Chicago-Public-Libraries
Getting and Cleaning Data Public Library Data
!wget --quiet https://data.cityofchicago.org/api/views/x8fc-8rcq/rows.csv?accessType=DOWNLOAD -O libraries.csv lib = pd.read_csv('libraries.csv', usecols=['NAME ', 'HOURS OF OPERATION', 'LOCATION']) lib.columns = ['library', 'hours', 'location'] lib.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 80 entries, 0 to 79 Data columns (total 3 columns): library 80 non-null object hours 80 non-null object location 80 non-null object dtypes: object(3) memory usage: 2.0+ KB
MIT
Clustering Chicago Public Libraries.ipynb
KunyuHe/Clustering-Chicago-Public-Libraries
Notice that locations are stored as strings of tuples. Applying the following function to `lib`, we can convert `location` into two separate columns of latitudes and longitudes of the libraries.
def sep_location(row): """ Purpose: seperate the string of location in a given row, convert it into a tuple of floats, representing latitude and longitude of the library respectively Inputs: row (PandasSeries): a row from the `lib` dataframe Outputs: (tuple): of floats ...
_____no_output_____
MIT
Clustering Chicago Public Libraries.ipynb
KunyuHe/Clustering-Chicago-Public-Libraries
Now data on the public libraries is ready for analysis. Venue Data Use sensitive code cell below to enter FourSquare credentials.
# The code was removed by Watson Studio for sharing.
_____no_output_____
MIT
Clustering Chicago Public Libraries.ipynb
KunyuHe/Clustering-Chicago-Public-Libraries
Get top ten venues near to the libraries and store data into the `venues` dataframe, with radius set to 1000 meters by default. You can update the `VERSION` parameter to get up-to-date venue information.
VERSION = '20181206' FEATURES = ['venue.name', 'venue.categories', 'venue.location.lat', 'venue.location.lng'] def get_venues(libraries, latitudes, longitudes, limit=10, radius=1000.0): """ Purpose: download nearby venues information through FourSquare API in a dataframe Inputs: libraries (Pan...
_____no_output_____
MIT
Clustering Chicago Public Libraries.ipynb
KunyuHe/Clustering-Chicago-Public-Libraries
Count unique libraries, venues and vanue categories in our `venues` dataframe.
print('There are {} unique libraries, {} unique venues and {} unique categories.'.format( \ len(venues.Library.unique()), \ len(venues.Venue.unique()), \ len(venues['Venue Category'].unique())))
There are 80 unique libraries, 653 unique venues and 173 unique categories.
MIT
Clustering Chicago Public Libraries.ipynb
KunyuHe/Clustering-Chicago-Public-Libraries
Now our `venues` data is also ready for furtehr analysis. Data Analysis Data Preprocessing Apply one-hot encoding to get our feature matrix, group the venues by libraries and calculate the frequency of each venue category around specific library by taking the mean.
features = pd.get_dummies(venues['Venue Category'], prefix="", prefix_sep="") features.insert(0, 'Library Name', venues.Library) X = features.groupby(['Library Name']).mean().iloc[:, 1:] X.head()
_____no_output_____
MIT
Clustering Chicago Public Libraries.ipynb
KunyuHe/Clustering-Chicago-Public-Libraries
There are too many categories of venues in our features dataframe. Perform PCA to reduce the dimension of our data. Notice here most of the data entries in our feature matrix is zero, which means our data is sparse data, perform dimension reduction with truncated SVD. First, attempt to find the least number of dimensio...
tsvd = TruncatedSVD(n_components=X.shape[1]-1, random_state=0).fit(X) least_n = np.argmax(tsvd.explained_variance_ratio_.cumsum() > 0.85) print("In order to keep 85% of total variance, we need to keep at least {} dimensions.".format(least_n)) X_t = pd.DataFrame(TruncatedSVD(n_components=least_n, random_state=0).fit_tr...
In order to keep 85% of total variance, we need to keep at least 36 dimensions.
MIT
Clustering Chicago Public Libraries.ipynb
KunyuHe/Clustering-Chicago-Public-Libraries
Use KMeans on the transformed data and find the best number of k below.
ks = np.arange(1, 51) inertias = [] for k in ks: model = KMeans(n_clusters=k, random_state=0).fit(X_t) inertias.append(model.inertia_) plt.plot(ks, inertias, linewidth=2) plt.title("Figure 1 KMeans: Finding Best k", fontproperties=title) plt.xlabel('Number of Clusters (k)', fontproperties=axis) plt.ylabel('Wi...
_____no_output_____
MIT
Clustering Chicago Public Libraries.ipynb
KunyuHe/Clustering-Chicago-Public-Libraries
It's really hard to decide based on elbow plot, as the downward trend lasts until 50. Alternatively, try Ward Hierachical Clustering method.
merging = linkage(X_t, 'ward') plt.figure(figsize=[20, 10]) dendrogram(merging, leaf_rotation=90, leaf_font_size=10, distance_sort='descending', show_leaf_counts=True) plt.axhline(y=0.65, dashes=[6, 2], c='r') plt.xlabel('Library Names', fontproperties=axis) plt.title("Figur...
_____no_output_____
MIT
Clustering Chicago Public Libraries.ipynb
KunyuHe/Clustering-Chicago-Public-Libraries
The result is way better than KMeans. We see six clusters cutting at approximately 0.70. Label the clustered libraries below. Join the labelled library names with `lib` to bind geographical coordinates and hours of operation of the puclic libraries.
labels = fcluster(merging, t=0.65, criterion='distance') df = pd.DataFrame(list(zip(X.index.values, labels))) df.columns = ['library', 'cluster'] merged = pd.merge(lib, df, how='inner', on='library') merged.head()
_____no_output_____
MIT
Clustering Chicago Public Libraries.ipynb
KunyuHe/Clustering-Chicago-Public-Libraries
Results Create a `folium.Map` instance `chicago` with initial zoom level of 11.
chicago = folium.Map(location=[LATITUDE, LOGITUDE], zoom_start=11)
_____no_output_____
MIT
Clustering Chicago Public Libraries.ipynb
KunyuHe/Clustering-Chicago-Public-Libraries
Check the clustered map! Click on the icons to see the name, hours of operation and top five nearby venues of each public library in the city of Chicago!
for index, row in merged.iterrows(): venues_name = venues[venues.Library == row.library].Venue.values label = folium.Popup(HTML.format(row.library, row.cluster, row.hours, venues_name[0], venues_name[1], venues_name[2], venues_name[3], venues_name[4]), parse_html=False) folium.Marker([row.latitude, row.long...
_____no_output_____
MIT
Clustering Chicago Public Libraries.ipynb
KunyuHe/Clustering-Chicago-Public-Libraries
Simulation Test Introduction
import sys import random import numpy as np import pylab from scipy import stats sys.path.insert(0, '../simulation') from environment import Environment from predator import Predator params = { 'env_size': 1000, 'n_patches': 20, 'n_trials': 100, 'max_moves': 5000, 'max_entities_per_patch': 50, '...
_____no_output_____
MIT
src/ipython/45 Simulation_Test.ipynb
rah/optimal-search
Testing a hypothesis -- non-stationary or time-reversibleWe evaluate whether the GTR model is sufficient for a data set, compared with the GN (non-stationary general nucleotide model).
from cogent3.app import io, evo, sample loader = io.load_aligned(format="fasta", moltype="dna") aln = loader("../data/primate_brca1.fasta") tree = "../data/primate_brca1.tree" sm_args = dict(optimise_motif_probs=True) null = evo.model("GTR", tree=tree, sm_args=sm_args) alt = evo.model("GN", tree=tree, sm_args=sm_args...
_____no_output_____
BSD-3-Clause
doc/app/evo-hypothesis.ipynb
GavinHuttley/c3test
`result` is a `hypothesis_result` object. The `repr()` displays the likelihood ratio test statistic, degrees of freedom and associated p-value>
result
_____no_output_____
BSD-3-Clause
doc/app/evo-hypothesis.ipynb
GavinHuttley/c3test
In this case, we accept the null given the p-value is > 0.05. We still use this object to demonstrate the properties of a `hypothesis_result`. `hypothesis_result` has attributes and keys Accessing the test statistics
result.LR, result.df, result.pvalue
_____no_output_____
BSD-3-Clause
doc/app/evo-hypothesis.ipynb
GavinHuttley/c3test
The null hypothesisThis model is accessed via the `null` attribute.
result.null result.null.lf
_____no_output_____
BSD-3-Clause
doc/app/evo-hypothesis.ipynb
GavinHuttley/c3test
The alternate hypothesis
result.alt.lf
_____no_output_____
BSD-3-Clause
doc/app/evo-hypothesis.ipynb
GavinHuttley/c3test
1. Converting words or sentences into numeric vectors is fundamental when working with text data. To make sure you are solid on how these vectors work, please generate the tf-idf vectors for the last three sentences of the example we gave at the beginning of this checkpoint. If you are feeling uncertain, have your men...
# utility function for standard text cleaning def text_cleaner(text): # visual inspection identifies a form of punctuation spaCy does not # recognize: the double dash '--'. Better get rid of it now! text = re.sub(r'--',' ',text) text = re.sub("[\[].*?[\]]", "", text) text = re.sub(r"(\b|\s+\-?|^\-?...
_____no_output_____
MIT
NLPFE2.ipynb
AsterLaoWhy/Thinkful
2. In the 2-grams example above, we only used 2-grams as our features. This time, use both 1-grams and 2-grams together as your feature set. Run the same models in the example and compare the results.
# utility function for standard text cleaning def text_cleaner(text): # visual inspection identifies a form of punctuation spaCy does not # recognize: the double dash '--'. Better get rid of it now! text = re.sub(r'--',' ',text) text = re.sub("[\[].*?[\]]", "", text) text = re.sub(r"(\b|\s+\-?|^\-?...
----------------------Logistic Regression Scores---------------------- Training set score: 0.9036488027366021 Test set score: 0.8555555555555555 ----------------------Random Forest Scores---------------------- Training set score: 0.9694982896237172 Test set score: 0.8414529914529915 ----------------------Gradient Boo...
MIT
NLPFE2.ipynb
AsterLaoWhy/Thinkful
Training Collaborative Experts on MSR-VTTThis notebook shows how to download code that trains a Collaborative Experts model with GPT-1 + NetVLAD on the MSR-VTT Dataset. Setup* Download Code and Dependencies* Import Modules* Download Language Model Weights* Download Datasets* Generate Encodings for Dataset C...
%tensorflow_version 2.x !git clone https://github.com/googleinterns/via-content-understanding.git %cd via-content-understanding/videoretrieval/ !pip install -r requirements.txt !pip install --upgrade tensorflow_addons
_____no_output_____
Apache-2.0
videoretrieval/Demo notebook GPT-1.ipynb
googleinterns/via-content-understanding
Importing Modules
import tensorflow as tf import languagemodels import train.encoder_datasets import train.language_model import experts import datasets import datasets.msrvtt.constants import os import models.components import models.encoder import helper.precomputed_features from tensorflow_addons.activations import mish import tens...
_____no_output_____
Apache-2.0
videoretrieval/Demo notebook GPT-1.ipynb
googleinterns/via-content-understanding
Language Model Downloading* Download GPT-1
gpt_model = languagemodels.OpenAIGPTModel()
_____no_output_____
Apache-2.0
videoretrieval/Demo notebook GPT-1.ipynb
googleinterns/via-content-understanding
Dataset downloading* Downlaod Datasets* Download Precomputed Features
datasets.msrvtt_dataset.download_dataset()
_____no_output_____
Apache-2.0
videoretrieval/Demo notebook GPT-1.ipynb
googleinterns/via-content-understanding
Note: The system `curl` is more memory efficent than the download function in our codebase, so here `curl` is used rather than the download function in our codebase.
url = datasets.msrvtt.constants.features_tar_url path = datasets.msrvtt.constants.features_tar_path os.system(f"curl {url} > {path}") helper.precomputed_features.cache_features( datasets.msrvtt_dataset, datasets.msrvtt.constants.expert_to_features, datasets.msrvtt.constants.features_tar_path,)
_____no_output_____
Apache-2.0
videoretrieval/Demo notebook GPT-1.ipynb
googleinterns/via-content-understanding
Embeddings Generation* Generate Embeddings for MSR-VTT* **Note: this will take 20-30 minutes on a colab, depending on the GPU**
train.language_model.generate_and_cache_contextual_embeddings( gpt_model, datasets.msrvtt_dataset)
_____no_output_____
Apache-2.0
videoretrieval/Demo notebook GPT-1.ipynb
googleinterns/via-content-understanding
Training* Build Train Datasets* Initialize Models* Compile Encoders* Fit Model* Test Model Datasets Generation
experts_used = [ experts.i3d, experts.r2p1d, experts.resnext, experts.senet, experts.speech_expert, experts.ocr_expert, experts.audio_expert, experts.densenet, experts.face_expert] train_ds, valid_ds, test_ds = ( train.encoder_datasets.generate_encoder_datasets( gpt_model, datasets.msrvtt_...
_____no_output_____
Apache-2.0
videoretrieval/Demo notebook GPT-1.ipynb
googleinterns/via-content-understanding
Model Initialization
class MishLayer(tf.keras.layers.Layer): def call(self, inputs): return mish(inputs) mish(tf.Variable([1.0])) text_encoder = models.components.TextEncoder( len(experts_used), num_netvlad_clusters=28, ghost_clusters=1, language_model_dimensionality=768, encoded_expert_dimensionality=512, ...
_____no_output_____
Apache-2.0
videoretrieval/Demo notebook GPT-1.ipynb
googleinterns/via-content-understanding
Encoder Compliation
def build_optimizer(lr=0.001): learning_rate_scheduler = tf.keras.optimizers.schedules.ExponentialDecay( initial_learning_rate=lr, decay_steps=101, decay_rate=0.95, staircase=True) return tf.keras.optimizers.Adam(learning_rate_scheduler) encoder.compile(build_optimizer(0.1), met...
_____no_output_____
Apache-2.0
videoretrieval/Demo notebook GPT-1.ipynb
googleinterns/via-content-understanding
Model fitting
encoder.fit( train_ds_prepared, epochs=100, )
_____no_output_____
Apache-2.0
videoretrieval/Demo notebook GPT-1.ipynb
googleinterns/via-content-understanding
Tests
captions_per_video = 20 num_videos_upper_bound = 100000 ranks = [] for caption_index in range(captions_per_video): batch = next(iter(test_ds.shard(captions_per_video, caption_index).batch( num_videos_upper_bound))) video_embeddings, text_embeddings, mixture_weights = encoder.forward_pass( batc...
_____no_output_____
Apache-2.0
videoretrieval/Demo notebook GPT-1.ipynb
googleinterns/via-content-understanding
Ejercicio 4
import numpy as np import math as math import scipy.stats as stats import matplotlib.pyplot as plt def normalGenerator(media, desvio,nroMuestras): c = math.sqrt(2*math.exp(1)/np.pi); t = np.random.exponential(scale=1, size=nroMuestras); p = list(); for i in t: p.append(fx(i)/(c*fy(i))); ...
_____no_output_____
MIT
tp1/Ejercicio 4.ipynb
NicoGallegos/fiuba-simulacion-grupo6
VARIANZA
print(np.var(results));
25.0067772918
MIT
tp1/Ejercicio 4.ipynb
NicoGallegos/fiuba-simulacion-grupo6
MEDIA
print(np.mean(results));
34.9540678007
MIT
tp1/Ejercicio 4.ipynb
NicoGallegos/fiuba-simulacion-grupo6
DESVIACION ESTANDAR
print(np.std(results));
5.00067768325
MIT
tp1/Ejercicio 4.ipynb
NicoGallegos/fiuba-simulacion-grupo6
Un dictionnaire français-indonésienVous disposez d’un fichier tabulaire dans le répertoire *data* avec une liste de mots en français et, en regard, leur traduction en indonésien. Complétez le programme ci-dessous afin que, pour toute entrée saisie par un utilisateur, il renvoie la traduction en indonésien ou un messag...
#!/usr/bin/env python #-*- coding: utf-8 -*- # # Modules # import csv # # User functions # def load_data(path): """Loads a data in csv format path -- path to data """ lines = [] with open(path) as csvfile: reader = csv.reader(csvfile, delimiter='\t') for line in reader: ...
_____no_output_____
MIT
2.data-structures/exercises/5.french-indonesian-dictionary.ipynb
mdjamina/python-M1TAL
k-Nearest Neighbor (kNN) exercise*Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see the [assignments page](http://vision.stanford.edu/teaching/cs231n/assignments.html) on the course website.*The k...
# Run some setup code for this notebook. import random import numpy as np from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt from __future__ import print_function # This is a bit of magic to make matplotlib figures appear inline in the notebook # rather than in a new window. %matplotlib inlin...
_____no_output_____
MIT
assignment1/.ipynb_checkpoints/knn-checkpoint.ipynb
billzhao1990/CS231n-Spring-2017
We would now like to classify the test data with the kNN classifier. Recall that we can break down this process into two steps: 1. First we must compute the distances between all test examples and all train examples. 2. Given these distances, for each test example we find the k nearest examples and have them vote for t...
# Open cs231n/classifiers/k_nearest_neighbor.py and implement # compute_distances_two_loops. # Test your implementation: dists = classifier.compute_distances_two_loops(X_test) print(dists.shape) # We can visualize the distance matrix: each row is a single test example and # its distances to training examples plt.imsho...
_____no_output_____
MIT
assignment1/.ipynb_checkpoints/knn-checkpoint.ipynb
billzhao1990/CS231n-Spring-2017
**Inline Question 1:** Notice the structured patterns in the distance matrix, where some rows or columns are visible brighter. (Note that with the default color scheme black indicates low distances while white indicates high distances.)- What in the data is the cause behind the distinctly bright rows?- What causes the ...
# Now implement the function predict_labels and run the code below: # We use k = 1 (which is Nearest Neighbor). y_test_pred = classifier.predict_labels(dists, k=1) # Compute and print the fraction of correctly predicted examples num_correct = np.sum(y_test_pred == y_test) accuracy = float(num_correct) / num_test print...
_____no_output_____
MIT
assignment1/.ipynb_checkpoints/knn-checkpoint.ipynb
billzhao1990/CS231n-Spring-2017
You should expect to see approximately `27%` accuracy. Now lets try out a larger `k`, say `k = 5`:
y_test_pred = classifier.predict_labels(dists, k=5) num_correct = np.sum(y_test_pred == y_test) accuracy = float(num_correct) / num_test print('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))
_____no_output_____
MIT
assignment1/.ipynb_checkpoints/knn-checkpoint.ipynb
billzhao1990/CS231n-Spring-2017
You should expect to see a slightly better performance than with `k = 1`.
# Now lets speed up distance matrix computation by using partial vectorization # with one loop. Implement the function compute_distances_one_loop and run the # code below: dists_one = classifier.compute_distances_one_loop(X_test) # To ensure that our vectorized implementation is correct, we make sure that it # agrees ...
_____no_output_____
MIT
assignment1/.ipynb_checkpoints/knn-checkpoint.ipynb
billzhao1990/CS231n-Spring-2017
Cross-validationWe have implemented the k-Nearest Neighbor classifier but we set the value k = 5 arbitrarily. We will now determine the best value of this hyperparameter with cross-validation.
num_folds = 5 k_choices = [1, 3, 5, 8, 10, 12, 15, 20, 50, 100] X_train_folds = [] y_train_folds = [] ################################################################################ # TODO: # # Split up the training data into folds. After splittin...
_____no_output_____
MIT
assignment1/.ipynb_checkpoints/knn-checkpoint.ipynb
billzhao1990/CS231n-Spring-2017
Callback> Basic callbacks for Learner Callback -
#export _inner_loop = "begin_batch after_pred after_loss after_backward after_step after_cancel_batch after_batch".split() #export class Callback(GetAttr): "Basic class handling tweaks of the training loop by changing a `Learner` in various events" _default,learn,run,run_train,run_valid = 'learn',None,True,True...
_____no_output_____
Apache-2.0
nbs/13_callback.core.ipynb
aquietlife/fastai2
The training loop is defined in `Learner` a bit below and consists in a minimal set of instructions: looping through the data we:- compute the output of the model from the input- calculate a loss between this output and the desired target- compute the gradients of this loss with respect to all the model parameters- upd...
show_doc(Callback.__call__) tst_cb = Callback() tst_cb.call_me = lambda: print("maybe") test_stdout(lambda: tst_cb("call_me"), "maybe") show_doc(Callback.__getattr__)
_____no_output_____
Apache-2.0
nbs/13_callback.core.ipynb
aquietlife/fastai2
This is a shortcut to avoid having to write `self.learn.bla` for any `bla` attribute we seek, and just write `self.bla`.
mk_class('TstLearner', 'a') class TstCallback(Callback): def batch_begin(self): print(self.a) learn,cb = TstLearner(1),TstCallback() cb.learn = learn test_stdout(lambda: cb('batch_begin'), "1")
_____no_output_____
Apache-2.0
nbs/13_callback.core.ipynb
aquietlife/fastai2
Note that it only works to get the value of the attribute, if you want to change it, you have to manually access it with `self.learn.bla`. In the example below, `self.a += 1` creates an `a` attribute of 2 in the callback instead of setting the `a` of the learner to 2. It also issues a warning that something is probably...
learn.a class TstCallback(Callback): def batch_begin(self): self.a += 1 learn,cb = TstLearner(1),TstCallback() cb.learn = learn cb('batch_begin') test_eq(cb.a, 2) test_eq(cb.learn.a, 1)
/home/sgugger/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:16: UserWarning: You are setting an attribute (a) that also exists in the learner. Please be advised that you're not setting it in the learner but in the callback. Use `self.learn.a` if you would like to change it in the learner. app.launch_new...
Apache-2.0
nbs/13_callback.core.ipynb
aquietlife/fastai2
A proper version needs to write `self.learn.a = self.a + 1`:
class TstCallback(Callback): def batch_begin(self): self.learn.a = self.a + 1 learn,cb = TstLearner(1),TstCallback() cb.learn = learn cb('batch_begin') test_eq(cb.learn.a, 2) show_doc(Callback.name, name='Callback.name') test_eq(TstCallback().name, 'tst') class ComplicatedNameCallback(Callback): pass test_eq(Compl...
_____no_output_____
Apache-2.0
nbs/13_callback.core.ipynb
aquietlife/fastai2
TrainEvalCallback -
#export class TrainEvalCallback(Callback): "`Callback` that tracks the number of iterations done and properly sets training/eval mode" run_valid = False def begin_fit(self): "Set the iter and epoch counters to 0, put the model and the right device" self.learn.train_iter,self.learn.pct_train ...
_____no_output_____
Apache-2.0
nbs/13_callback.core.ipynb
aquietlife/fastai2
This `Callback` is automatically added in every `Learner` at initialization.
#hide #test of the TrainEvalCallback below in Learner.fit show_doc(TrainEvalCallback.begin_fit) show_doc(TrainEvalCallback.after_batch) show_doc(TrainEvalCallback.begin_train) show_doc(TrainEvalCallback.begin_validate) # export defaults.callbacks = [TrainEvalCallback]
_____no_output_____
Apache-2.0
nbs/13_callback.core.ipynb
aquietlife/fastai2
GatherPredsCallback -
#export #TODO: save_targs and save_preds only handle preds/targets that have one tensor, not tuples of tensors. class GatherPredsCallback(Callback): "`Callback` that saves the predictions and targets, optionally `with_loss`" def __init__(self, with_input=False, with_loss=False, save_preds=None, save_targs=None,...
_____no_output_____
Apache-2.0
nbs/13_callback.core.ipynb
aquietlife/fastai2
Callbacks control flow It happens that we may want to skip some of the steps of the training loop: in gradient accumulation, we don't aways want to do the step/zeroing of the grads for instance. During an LR finder test, we don't want to do the validation phase of an epoch. Or if we're training with a strategy of earl...
#export _ex_docs = dict( CancelFitException="Skip the rest of this batch and go to `after_batch`", CancelEpochException="Skip the rest of the training part of the epoch and go to `after_train`", CancelTrainException="Skip the rest of the validation part of the epoch and go to `after_validate`", CancelVa...
_____no_output_____
Apache-2.0
nbs/13_callback.core.ipynb
aquietlife/fastai2
You can detect one of those exceptions occurred and add code that executes right after with the following events:- `after_cancel_batch`: reached imediately after a `CancelBatchException` before proceeding to `after_batch`- `after_cancel_train`: reached imediately after a `CancelTrainException` before proceeding to `aft...
# export _events = L.split('begin_fit begin_epoch begin_train begin_batch after_pred after_loss \ after_backward after_step after_cancel_batch after_batch after_cancel_train \ after_train begin_validate after_cancel_validate after_validate after_cancel_epoch \ after_epoch after_cancel_fit after_fit') mk_cl...
_____no_output_____
Apache-2.0
nbs/13_callback.core.ipynb
aquietlife/fastai2
Here's the full list: *begin_fit begin_epoch begin_train begin_batch after_pred after_loss after_backward after_step after_cancel_batch after_batch after_cancel_train after_train begin_validate after_cancel_validate after_validate after_cancel_epoch after_epoch after_cancel_fit after_fit*. Export -
#hide from nbdev.export import notebook2script notebook2script()
Converted 00_torch_core.ipynb. Converted 01_layers.ipynb. Converted 02_data.load.ipynb. Converted 03_data.core.ipynb. Converted 04_data.external.ipynb. Converted 05_data.transforms.ipynb. Converted 06_data.block.ipynb. Converted 07_vision.core.ipynb. Converted 08_vision.data.ipynb. Converted 09_vision.augment.ipynb. Co...
Apache-2.0
nbs/13_callback.core.ipynb
aquietlife/fastai2
Calculating the Return of Indices *Suggested Answers follow (usually there are multiple ways to solve a problem in Python).* Consider three famous American market indices – Dow Jones, S&P 500, and the Nasdaq for the period of 1st of January 2000 until today.
import numpy as np import pandas as pd from pandas_datareader import data as wb import matplotlib.pyplot as plt tickers = ['^DJI', '^GSPC', '^IXIC'] ind_data = pd.DataFrame() for t in tickers: ind_data[t] = wb.DataReader(t, data_source='yahoo', start='2000-1-1')['Adj Close'] ind_data.head() ind_data.tail()
_____no_output_____
Apache-2.0
23 - Python for Finance/2_Calculating and Comparing Rates of Return in Python/11_Calculating the Rate of Return of Indices (5:03)/Calculating the Return of Indices - Solution_Yahoo_Py3.ipynb
olayinka04/365-data-science-courses
Normalize the data to 100 and plot the results on a graph.
(ind_data / ind_data.iloc[0] * 100).plot(figsize=(15, 6)); plt.show()
_____no_output_____
Apache-2.0
23 - Python for Finance/2_Calculating and Comparing Rates of Return in Python/11_Calculating the Rate of Return of Indices (5:03)/Calculating the Return of Indices - Solution_Yahoo_Py3.ipynb
olayinka04/365-data-science-courses
How would you explain the common and the different parts of the behavior of the three indices? ***** Obtain the simple returns of the indices.
ind_returns = (ind_data / ind_data.shift(1)) - 1 ind_returns.tail()
_____no_output_____
Apache-2.0
23 - Python for Finance/2_Calculating and Comparing Rates of Return in Python/11_Calculating the Rate of Return of Indices (5:03)/Calculating the Return of Indices - Solution_Yahoo_Py3.ipynb
olayinka04/365-data-science-courses
Estimate the average annual return of each index.
annual_ind_returns = ind_returns.mean() * 250 annual_ind_returns
_____no_output_____
Apache-2.0
23 - Python for Finance/2_Calculating and Comparing Rates of Return in Python/11_Calculating the Rate of Return of Indices (5:03)/Calculating the Return of Indices - Solution_Yahoo_Py3.ipynb
olayinka04/365-data-science-courses
Read the CSV and Perform Basic Data Cleaning
df = pd.read_csv("resources/exoplanet_data.csv") # Drop the null columns where all values are null df = df.dropna(axis='columns', how='all') # Drop the null rows df = df.dropna() df.head()
_____no_output_____
MIT
model_1 - DecisionTree.ipynb
RussellMcGrath/machine-learning-challenge
Select your features (columns)
# Set features. This will also be used as your x values. #selected_features = df[['names', 'of', 'selected', 'features', 'here']] feature_list = df.columns.to_list() feature_list.remove("koi_disposition") removal_list = [] for x in feature_list: if "err" in x: removal_list.append(x) print(removal_list) ...
['koi_period_err1', 'koi_period_err2', 'koi_time0bk_err1', 'koi_time0bk_err2', 'koi_impact_err1', 'koi_impact_err2', 'koi_duration_err1', 'koi_duration_err2', 'koi_depth_err1', 'koi_depth_err2', 'koi_prad_err1', 'koi_prad_err2', 'koi_insol_err1', 'koi_insol_err2', 'koi_steff_err1', 'koi_steff_err2', 'koi_slogg_err1', '...
MIT
model_1 - DecisionTree.ipynb
RussellMcGrath/machine-learning-challenge
Create a Train Test SplitUse `koi_disposition` for the y values
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(selected_features, df["koi_disposition"], random_state=13) X_train.head()
_____no_output_____
MIT
model_1 - DecisionTree.ipynb
RussellMcGrath/machine-learning-challenge
Pre-processingScale the data using the MinMaxScaler and perform some feature selection
# Scale your data from sklearn.preprocessing import MinMaxScaler X_scaler = MinMaxScaler().fit(X_train) #y_scaler = MinMaxScaler().fit(y_train) X_train_scaled = X_scaler.transform(X_train) X_test_scaled = X_scaler.transform(X_test) #y_train_scaled = y_scaler.transform(y_train) #y_test_scaled = y_scaler.transform(y_tra...
_____no_output_____
MIT
model_1 - DecisionTree.ipynb
RussellMcGrath/machine-learning-challenge
Train the Model
from sklearn import tree decision_tree_model = tree.DecisionTreeClassifier() decision_tree_model = decision_tree_model.fit(X_train, y_train) print(f"Training Data Score: {decision_tree_model.score(X_train_scaled, y_train)}") print(f"Testing Data Score: {decision_tree_model.score(X_test_scaled, y_test)}")
Training Data Score: 0.6055693305359527 Testing Data Score: 0.5835240274599542
MIT
model_1 - DecisionTree.ipynb
RussellMcGrath/machine-learning-challenge
Hyperparameter TuningUse `GridSearchCV` to tune the model's parameters
decision_tree_model.get_params() # Create the GridSearchCV model from sklearn.model_selection import GridSearchCV param_grid = {'C': [1, 5, 10, 50], 'gamma': [0.0001, 0.0005, 0.001, 0.005]} grid = GridSearchCV(decision_tree_model, param_grid, verbose=3) # Train the model with GridSearch grid.fit(X_train,y...
_____no_output_____
MIT
model_1 - DecisionTree.ipynb
RussellMcGrath/machine-learning-challenge
Save the Model
# save your model by updating "your_name" with your name # and "your_model" with your model variable # be sure to turn this in to BCS # if joblib fails to import, try running the command to install in terminal/git-bash import joblib filename = 'your_name.sav' joblib.dump(your_model, filename)
_____no_output_____
MIT
model_1 - DecisionTree.ipynb
RussellMcGrath/machine-learning-challenge
Negative Binomial Regression (Students absence example) Negative binomial distribution review I always experience some kind of confusion when looking at the negative binomial distribution after a while of not working with it. There are so many different definitions that I usually need to read everything more than onc...
import arviz as az import bambi as bmb import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy.stats import nbinom az.style.use("arviz-darkgrid") import warnings warnings.simplefilter(action='ignore', category=FutureWarning)
_____no_output_____
MIT
docs/notebooks/negative_binomial.ipynb
PsychoinformaticsLab/bambi
In SciPy, the definition of the negative binomial distribution differs a little from the one in our introduction. They define $Y$ = Number of failures until k successes and then $y$ starts at 0. In the following plot, we have the probability of observing $y$ failures before we see $k=3$ successes.
y = np.arange(0, 30) k = 3 p1 = 0.5 p2 = 0.3 fig, ax = plt.subplots(1, 2, figsize=(12, 4), sharey=True) ax[0].bar(y, nbinom.pmf(y, k, p1)) ax[0].set_xticks(np.linspace(0, 30, num=11)) ax[0].set_title(f"k = {k}, p = {p1}") ax[1].bar(y, nbinom.pmf(y, k, p2)) ax[1].set_xticks(np.linspace(0, 30, num=11)) ax[1].set_title(...
_____no_output_____
MIT
docs/notebooks/negative_binomial.ipynb
PsychoinformaticsLab/bambi
For example, when $p=0.5$, the probability of seeing $y=0$ failures before 3 successes (or in other words, the probability of having 3 successes out of 3 trials) is 0.125, and the probability of seeing $y=3$ failures before 3 successes is 0.156.
print(nbinom.pmf(y, k, p1)[0]) print(nbinom.pmf(y, k, p1)[3])
0.12499999999999997 0.15624999999999992
MIT
docs/notebooks/negative_binomial.ipynb
PsychoinformaticsLab/bambi
Finally, if one wants to show this probability mass function as if we are following the first definition of negative binomial distribution we introduced, we just need to shift the whole thing to the right by adding $k$ to the $y$ values.
fig, ax = plt.subplots(1, 2, figsize=(12, 4), sharey=True) ax[0].bar(y + k, nbinom.pmf(y, k, p1)) ax[0].set_xticks(np.linspace(3, 30, num=10)) ax[0].set_title(f"k = {k}, p = {p1}") ax[1].bar(y + k, nbinom.pmf(y, k, p2)) ax[1].set_xticks(np.linspace(3, 30, num=10)) ax[1].set_title(f"k = {k}, p = {p2}") fig.suptitle("...
_____no_output_____
MIT
docs/notebooks/negative_binomial.ipynb
PsychoinformaticsLab/bambi
Negative binomial in GLM The negative binomial distribution belongs to the exponential family, and the canonical link function is $$g(\mu_i) = \log\left(\frac{\mu_i}{k + \mu_i}\right) = \log\left(\frac{k}{\mu_i} + 1\right)$$but it is difficult to interpret. The log link is usually preferred because of the analogy with...
data = pd.read_stata("https://stats.idre.ucla.edu/stat/stata/dae/nb_data.dta") data.head()
_____no_output_____
MIT
docs/notebooks/negative_binomial.ipynb
PsychoinformaticsLab/bambi
We assign categories to the values 1, 2, and 3 of our `"prog"` variable.
data["prog"] = data["prog"].map({1: "General", 2: "Academic", 3: "Vocational"}) data.head()
_____no_output_____
MIT
docs/notebooks/negative_binomial.ipynb
PsychoinformaticsLab/bambi
The Academic program is the most popular program (167/314) and General is the least popular one (40/314)
data["prog"].value_counts()
_____no_output_____
MIT
docs/notebooks/negative_binomial.ipynb
PsychoinformaticsLab/bambi
Let's explore the distributions of math score and days of absence for each of the three programs listed above. The vertical lines indicate the mean values.
fig, ax = plt.subplots(3, 2, figsize=(8, 6), sharex="col") programs = list(data["prog"].unique()) programs.sort() for idx, program in enumerate(programs): # Histogram ax[idx, 0].hist(data[data["prog"] == program]["math"], edgecolor='black', alpha=0.9) ax[idx, 0].axvline(data[data["prog"] == program]["math"...
_____no_output_____
MIT
docs/notebooks/negative_binomial.ipynb
PsychoinformaticsLab/bambi
The first impression we have is that the distribution of math scores is not equal for any of the programs. It looks right-skewed for students under the Academic program, left-skewed for students under the Vocational program, and roughly uniform for students in the General program (although there's a drop in the highest...
model_additive = bmb.Model("daysabs ~ 0 + prog + scale(math)", data, family="negativebinomial") idata_additive = model_additive.fit()
Auto-assigning NUTS sampler... Initializing NUTS using jitter+adapt_diag... Multiprocess sampling (4 chains in 4 jobs) NUTS: [prog, scale(math), daysabs_alpha]
MIT
docs/notebooks/negative_binomial.ipynb
PsychoinformaticsLab/bambi
Model 2For this second model we just add `prog:scale(math)` to indicate the interaction. A shorthand would be to use `y ~ 0 + prog*scale(math)`, which uses the **full interaction** operator. In other words, it just means we want to include the interaction between `prog` and `scale(math)` as well as their main effects.
model_interaction = bmb.Model("daysabs ~ 0 + prog + scale(math) + prog:scale(math)", data, family="negativebinomial") idata_interaction = model_interaction.fit()
Auto-assigning NUTS sampler... Initializing NUTS using jitter+adapt_diag... Multiprocess sampling (4 chains in 4 jobs) NUTS: [prog, scale(math), prog:scale(math), daysabs_alpha]
MIT
docs/notebooks/negative_binomial.ipynb
PsychoinformaticsLab/bambi
Explore models The first thing we do is calling `az.summary()`. Here we pass the `InferenceData` object the `.fit()` returned. This prints information about the marginal posteriors for each parameter in the model as well as convergence diagnostics.
az.summary(idata_additive) az.summary(idata_interaction)
_____no_output_____
MIT
docs/notebooks/negative_binomial.ipynb
PsychoinformaticsLab/bambi
The information in the two tables above can be visualized in a more concise manner using a forest plot. ArviZ provides us with `plot_forest()`. There we simply pass a list containing the `InferenceData` objects of the models we want to compare.
az.plot_forest( [idata_additive, idata_interaction], model_names=["Additive", "Interaction"], var_names=["prog", "scale(math)"], combined=True, figsize=(8, 4) );
_____no_output_____
MIT
docs/notebooks/negative_binomial.ipynb
PsychoinformaticsLab/bambi
One of the first things one can note when seeing this plot is the similarity between the marginal posteriors. Maybe one can conclude that the variability of the marginal posterior of `scale(math)` is slightly lower in the model that considers the interaction, but the difference is not significant. We can also make conc...
az.plot_forest(idata_interaction, var_names=["prog:scale(math)"], combined=True, figsize=(8, 4)) plt.axvline(0);
_____no_output_____
MIT
docs/notebooks/negative_binomial.ipynb
PsychoinformaticsLab/bambi
Plot predicted mean responseWe finish this example showing how we can get predictions for new data and plot the mean response for each program together with confidence intervals.
math_score = np.arange(1, 100) # This function takes a model and an InferenceData object. # It returns of length 3 with predictions for each type of program. def predict(model, idata): predictions = [] for program in programs: new_data = pd.DataFrame({"math": math_score, "prog": [program] * len(math_sc...
_____no_output_____
MIT
docs/notebooks/negative_binomial.ipynb
PsychoinformaticsLab/bambi
As we can see in this plot, the interval for the mean response for the Vocational program does not overlap with the interval for the other two groups, representing the group of students who miss fewer classes. On the right panel we can also see that including interaction terms does not change the slopes significantly b...
%load_ext watermark %watermark -n -u -v -iv -w
Last updated: Wed Jun 01 2022 Python implementation: CPython Python version : 3.9.7 IPython version : 8.3.0 sys : 3.9.7 (default, Sep 16 2021, 13:09:58) [GCC 7.5.0] pandas : 1.4.2 numpy : 1.21.5 arviz : 0.12.1 matplotlib: 3.5.1 bambi : 0.7.1 Watermark: 2.3.0
MIT
docs/notebooks/negative_binomial.ipynb
PsychoinformaticsLab/bambi
Self-Driving Car Engineer Nanodegree Project: **Finding Lane Lines on the Road** ***In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a se...
#importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 %matplotlib inline
_____no_output_____
MIT
P1.ipynb
owennottank/CarND-LaneLines-P1
Read in an Image
#reading in an image image = mpimg.imread('test_images/solidWhiteRight.jpg') #printing out some stats and plotting print('This image is:', type(image), 'with dimensions:', image.shape) plt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gra...
This image is: <class 'numpy.ndarray'> with dimensions: (540, 960, 3)
MIT
P1.ipynb
owennottank/CarND-LaneLines-P1
Ideas for Lane Detection Pipeline **Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**`cv2.inRange()` for color selection `cv2.fillPoly()` for regions selection `cv2.line()` to draw lines on an image given endpoints `cv2.addWeighted()` to coadd / overlay two i...
import math def grayscale(img): """Applies the Grayscale transform This will return an image with only one color channel but NOTE: to see the returned image as grayscale (assuming your grayscaled image is called 'gray') you should call plt.imshow(gray, cmap='gray')""" return cv2.cvtColor(img, c...
_____no_output_____
MIT
P1.ipynb
owennottank/CarND-LaneLines-P1
Test ImagesBuild your pipeline to work on the images in the directory "test_images" **You should make sure your pipeline works well on these images before you try the videos.**
import os list_img = os.listdir("test_images/") os.listdir("test_images/")
_____no_output_____
MIT
P1.ipynb
owennottank/CarND-LaneLines-P1
Build a Lane Finding Pipeline Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.
# TODO: Build your pipeline that will draw lane lines on the test_images # then save them to the test_images_output directory. def lane_finding(image): # 1. convert image to grayscale gray = grayscale(image) cv2.imwrite('test_images_output/gray.jpg',gray) # 2. Gaussian smoothing of gray image kernel...
_____no_output_____
MIT
P1.ipynb
owennottank/CarND-LaneLines-P1
Test on VideosYou know what's cooler than drawing lanes over images? Drawing lanes over video!We can test our solution on two provided videos:`solidWhiteRight.mp4``solidYellowLeft.mp4`**Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel...
# Import everything needed to edit/save/watch video clips from moviepy.editor import VideoFileClip from IPython.display import HTML def process_image(image): # NOTE: The output you return should be a color image (3 channel) for processing video below # TODO: put your pipeline here, # you should return the f...
_____no_output_____
MIT
P1.ipynb
owennottank/CarND-LaneLines-P1
Let's try the one with the solid white lane on the right first ...
white_output = 'test_videos_output/solidWhiteRight.mp4' ## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video ## To do so add .subclip(start_second,end_second) to the end of the line below ## Where start_second and end_second are integer values representing the start and...
t: 0%| | 0/221 [00:00<?, ?it/s, now=None]
MIT
P1.ipynb
owennottank/CarND-LaneLines-P1