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 |
|---|---|---|---|---|---|
Calculating aerial weight | SW2_df.loc[:, 'loadcell_1'] = SW2_df.loc[:, 'loadcell_1'] - rockwool_mean
SW2_df.loc[:, 'loadcell_2'] = SW2_df.loc[:, 'loadcell_2'] - rockwool_mean
SW2_df.loc[:, 'loadcell_3'] = SW2_df.loc[:, 'loadcell_3'] - rockwool_mean | _____no_output_____ | Apache-2.0 | 2_weight_label_maker.ipynb | ataraxno/weighing_dev |
Destructive crop weight | weight_df = pd.read_csv('./results/2020_S/weight_ct.csv', index_col='Unnamed: 0')
weight_df.index = pd.DatetimeIndex(weight_df.index)
weight_df.index = np.append(weight_df.index[:-20], pd.DatetimeIndex(['2020-07-03']*20))
wweight_df = weight_df[['Stem FW', 'Leaf FW', 'petiole FW', 'Idv fruit FW']].sum(axis=1) | _____no_output_____ | Apache-2.0 | 2_weight_label_maker.ipynb | ataraxno/weighing_dev |
Root DW to FW | roots_DW_mean = 297.27
DW_sum_df = weight_df.loc[:, [_ for _ in weight_df.columns if _.endswith('DW')]].sum(axis=1)
rs_ratio_df = (roots_DW_mean/(DW_sum_df.loc['2020-07-03']*4)).mean()
roots_df = pd.DataFrame(DW_sum_df * rs_ratio_df)
roots_df.columns = ['root DW']
roots_df['root FW'] = roots_df['root DW']/0.1325
roots_... | _____no_output_____ | Apache-2.0 | 2_weight_label_maker.ipynb | ataraxno/weighing_dev |
Excepting irrigation disturbance | night_df = SW2_df.loc[SW2_df['rad'] <= 0.2, 'loadcell_1':'loadcell_3']
fig = plt.figure(figsize=((8/2.54*2.5), (6/2.54*1.2)))
ax0 = plt.subplot()
ax0.spines['right'].set_visible(False)
ax0.spines['left'].set_position(('outward', 5))
ax0.spines['bottom'].set_position(('outward', 5))
ax0.plot(SW2_df.index, SW2_df['load... | _____no_output_____ | Apache-2.0 | 2_weight_label_maker.ipynb | ataraxno/weighing_dev |
2020 Winter Control weight | SW2_df = pd.read_csv('./results/2020_W/SW_CT_greenhouse.csv', index_col='Unnamed: 0')
SW2_df.index = pd.DatetimeIndex(SW2_df.index) | _____no_output_____ | Apache-2.0 | 2_weight_label_maker.ipynb | ataraxno/weighing_dev |
Cultivation period | SW2_df = SW2_df.loc['2020-08-26 00:00:00': '2021-01-25 23:59:00']
SW2_df = SW2_df.interpolate() | _____no_output_____ | Apache-2.0 | 2_weight_label_maker.ipynb | ataraxno/weighing_dev |
Rockwool weight | rockwool_mean = 887.20/1000 | _____no_output_____ | Apache-2.0 | 2_weight_label_maker.ipynb | ataraxno/weighing_dev |
water weight | substrate_volume = (120*12*7.5 + 10*10*6.5*3)/1000
water_w_df = substrate_volume*SW2_df['subs_VWC']/100
SW2_df['water'] = water_w_df | _____no_output_____ | Apache-2.0 | 2_weight_label_maker.ipynb | ataraxno/weighing_dev |
Calculating aerial weight | SW2_df.loc[:, 'loadcell_1'] = SW2_df.loc[:, 'loadcell_1'] - rockwool_mean
SW2_df.loc[:, 'loadcell_2'] = SW2_df.loc[:, 'loadcell_2'] - rockwool_mean
SW2_df.loc[:, 'loadcell_3'] = SW2_df.loc[:, 'loadcell_3'] - rockwool_mean | _____no_output_____ | Apache-2.0 | 2_weight_label_maker.ipynb | ataraxno/weighing_dev |
Destructive crop weight | weight_df = pd.read_csv('./results/2020_W/weight_ct.csv', index_col='Unnamed: 0')
weight_df.index = pd.DatetimeIndex(weight_df.index)
wweight_df = weight_df[['Stem FW', 'Leaf FW', 'petiole FW', 'Idv fruit FW']].sum(axis=1) | _____no_output_____ | Apache-2.0 | 2_weight_label_maker.ipynb | ataraxno/weighing_dev |
Root DW to FW | roots_DW_mean = 355.37
DW_sum_df = weight_df.loc[:, [_ for _ in weight_df.columns if _.endswith('DW')]].sum(axis=1)
rs_ratio_df = (roots_DW_mean/(DW_sum_df.loc['2021-01-25']*3)).mean()
roots_df = pd.DataFrame(DW_sum_df * rs_ratio_df)
roots_df.columns = ['root DW']
roots_df['root FW'] = roots_df['root DW']/0.1325
roots_... | _____no_output_____ | Apache-2.0 | 2_weight_label_maker.ipynb | ataraxno/weighing_dev |
Excepting irrigation disturbance | night_df = SW2_df.loc[SW2_df['rad'] <= 0.2, 'loadcell_1':'loadcell_3']
fig = plt.figure(figsize=((8/2.54*2.5), (6/2.54*1.2)))
ax0 = plt.subplot()
ax0.spines['right'].set_visible(False)
ax0.spines['left'].set_position(('outward', 5))
ax0.spines['bottom'].set_position(('outward', 5))
ax0.plot(SW2_df.index, SW2_df['load... | _____no_output_____ | Apache-2.0 | 2_weight_label_maker.ipynb | ataraxno/weighing_dev |
API detils | #hide
from nbdev.showdoc import *
#export
def say_hello(to):
"Say hello to somebody"
return f'Hello {to}!'
say_hello("george") | _____no_output_____ | Apache-2.0 | 00_core.ipynb | kenshih/nbdev_ken |
assertion | assert say_hello("Jeremy")=="Hello Jeremy!" | _____no_output_____ | Apache-2.0 | 00_core.ipynb | kenshih/nbdev_ken |
Testing out SVG | from IPython.display import display,SVG
display(SVG('<svg height="100"><circle cx="50" cy="50" r="40"/></svg>')) | _____no_output_____ | Apache-2.0 | 00_core.ipynb | kenshih/nbdev_ken |
XGBoost vs LightGBMIn this notebook we collect the results from all the experiments and reports the comparative difference between XGBoost and LightGBM | import matplotlib.pyplot as plt
import nbformat
import json
from toolz import pipe, juxt
import pandas as pd
import seaborn
from toolz import curry
from bokeh.io import show, output_notebook
from bokeh.charts import Bar
from bokeh.models.renderers import GlyphRenderer
from bokeh.models.glyphs import Rect
from bokeh.mo... | _____no_output_____ | BSD-3-Clause | 3rdparty/fast_retraining/experiments/XGBoostvsLightGBM.ipynb | JohnZed/gbm-bench |
We are going to read the results from the following notebooks | notebooks = {
'Airline':'01_airline.ipynb',
'Airline_GPU': '01_airline_GPU.ipynb',
'BCI': '02_BCI.ipynb',
'BCI_GPU': '02_BCI_GPU.ipynb',
'Football': '03_football.ipynb',
'Football_GPU': '03_football_GPU.ipynb',
'Planet': '04_PlanetKaggle.ipynb',
'Plannet_GPU': '04_PlanetKaggle_GPU.ipynb'... | _____no_output_____ | BSD-3-Clause | 3rdparty/fast_retraining/experiments/XGBoostvsLightGBM.ipynb | JohnZed/gbm-bench |
Here we collect the results from all the exeperiment notebooks. The method simply searches the notebooks for a cell that starts with Results. It then reads that cells output in as JSON. | results = {nb_key:process_nb(nb_name) for nb_key, nb_name in notebooks.items()}
results
datasets = [k for k in results.keys()]
print(datasets)
algos = [a for a in results[datasets[0]].keys()]
print(algos) | ['Football_GPU', 'Airline_GPU', 'Planet', 'Airline', 'HIGGS_GPU', 'HIGGS', 'BCI_GPU', 'Plannet_GPU', 'Football', 'Fraud', 'Fraud_GPU', 'BCI']
['xgb', 'lgbm', 'xgb_hist']
| BSD-3-Clause | 3rdparty/fast_retraining/experiments/XGBoostvsLightGBM.ipynb | JohnZed/gbm-bench |
We wish to compare LightGBM and XGBoost both in terms of performance as well as how long they took to train. | def average_performance_diff(dataset):
lgbm_series = pd.Series(dataset['lgbm']['performance'])
try:
perf = 100*((lgbm_series-pd.Series(dataset['xgb']['performance']))/lgbm_series).mean()
except KeyError:
perf = None
return perf
def train_time_ratio(dataset):
try:
val = datas... | _____no_output_____ | BSD-3-Clause | 3rdparty/fast_retraining/experiments/XGBoostvsLightGBM.ipynb | JohnZed/gbm-bench |
Plot of train time ratio for CPU experiments. | data = {
'Ratio': results_cpu['Train Time Ratio'].values.tolist() + results_cpu['Train Time Ratio Hist'].values.tolist(),
'label': results_cpu.index.values.tolist()*2,
'group': ['xgb/lgb']*len(results_cpu.index.values) + ['xgb_hist/lgb']*len(results_cpu.index.values)
}
bar = Bar(data, values='Ratio', agg='m... | _____no_output_____ | BSD-3-Clause | 3rdparty/fast_retraining/experiments/XGBoostvsLightGBM.ipynb | JohnZed/gbm-bench |
Plot of train time ratio for GPU experiments. | data = {
'Ratio': results_gpu['Train Time Ratio'].values.tolist() + results_gpu['Train Time Ratio Hist'].values.tolist(),
'label': results_gpu.index.values.tolist()*2,
'group': ['xgb/lgb']*len(results_gpu.index.values) + ['xgb_hist/lgb']*len(results_gpu.index.values)
}
bar = Bar(data, values='Ratio', agg='m... | WARNING:bokeh.io:The webdriver raised a TimeoutException while waiting for a 'bokeh:idle' event to signify that the layout has rendered. Something may have gone wrong.
| BSD-3-Clause | 3rdparty/fast_retraining/experiments/XGBoostvsLightGBM.ipynb | JohnZed/gbm-bench |
class NodoArbol:
def __init__(self, value, left=None,right=None):
self.data=value
self.left=left
self.right=right | _____no_output_____ | MIT | 13enero.ipynb | pandemicbat801/daa_2021_1 | |
Arbol Binario de búsqueda
Los nodos a la izq son menores a la raiz y los nodods a la derecha son mayores a la raiz.
Pueden ser recorridos en: pre-orden, in-orden y postt-orden. | class BinarySearchTree:
def __init__ (self):
self.__root__=None
def insert (self, value):
if self.__root__ == None:
self.__root__ = NodoArbol(value,None,None)
else:
#preguntar si value es menor que root, de ser el caso
#insertar a la izquierda. PERO ... Puede ser el caso que... | _____no_output_____ | MIT | 13enero.ipynb | pandemicbat801/daa_2021_1 |
Neuromatch Academy 2020 -- Week 3 Day 3 Tutorial 3 Causality Day - Simultaneous fitting/regression**Content creators**: Ari Benjamin, Tony Liu, Konrad Kording**Content reviewers**: Mike X Cohen, Madineh Sarvestani, Ella Batty, Michael Waskom --- Tutorial objectivesThis is tutorial 3 on our day of examining causality.... | import numpy as np
import matplotlib.pyplot as plt
from sklearn.multioutput import MultiOutputRegressor
from sklearn.linear_model import Lasso
#@title Figure settings
import ipywidgets as widgets # interactive display
%config InlineBackend.figure_format = 'retina'
plt.style.use("https://raw.githubusercontent.com... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D3_NetworkCausality/W3D3_Tutorial3.ipynb | mmyros/course-content |
--- Section 1: Regression | #@title Video 1: Regression approach
# Insert the ID of the corresponding youtube video
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="Av4LaXZdgDo", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W3D3_NetworkCausality/W3D3_Tutorial3.ipynb | mmyros/course-content |
You may be familiar with the idea that correlation only implies causation when there no hidden *confounders*. This aligns with our intuition that correlation only implies causality when no alternative variables could explain away a correlation.**A confounding example**:Suppose you observe that people who sleep more do ... | #@title Video 2: Fitting a GLM
# Insert the ID of the corresponding youtube video
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="GvMj9hRv5Ak", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W3D3_NetworkCausality/W3D3_Tutorial3.ipynb | mmyros/course-content |
Section 1.1: Recovering connectivity by model fittingRecall that in our system each neuron effects every other via:$$\vec{x}_{t+1} = \sigma(A\vec{x}_t + \epsilon_t), $$where $\sigma$ is our sigmoid nonlinearity from before: $\sigma(x) = \frac{1}{1 + e^{-x}}$Our system is a closed system, too, so there are no omitted v... | def get_regression_estimate(X, neuron_idx):
"""
Estimates the connectivity matrix using lasso regression.
Args:
X (np.ndarray): our simulated system of shape (n_neurons, timesteps)
neuron_idx (int): a neuron index to compute connectivity for
Returns:
V (np.ndarray): estimated ... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D3_NetworkCausality/W3D3_Tutorial3.ipynb | mmyros/course-content |
You should find that using regression, our estimated connectivity matrix has a correlation of 0.865 with the true connectivity matrix. With correlation, our estimated connectivity matrix has a correlation of 0.703 with the true connectivity matrix.We can see from these numbers that multiple regression is better than si... | #@markdown Execute this cell to visualize subsets of connectivity matrix
# Run this cell to visualize the subsets of variables we observe
n_neurons = 25
A = create_connectivity(n_neurons)
fig, axs = plt.subplots(2, 2, figsize=(10, 10))
ratio_observed = [0.75, 0.25] # the proportion of neurons observed in our system
... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D3_NetworkCausality/W3D3_Tutorial3.ipynb | mmyros/course-content |
Section 2.2: Effects of partial observability | #@title Video 3: Omitted variable bias
# Insert the ID of the corresponding youtube video
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="5CCib6CTMac", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W3D3_NetworkCausality/W3D3_Tutorial3.ipynb | mmyros/course-content |
**Video correction**: the labels "connectivity from"/"connectivity to" are swapped in the video but fixed in the figures/demos below Interactive Demo: Regression performance as a function of the number of observed neuronsWe will first change the number of observed neurons in the network and inspect the resulting estim... | #@markdown Execute this cell to enable demo
n_neurons = 50
A = create_connectivity(n_neurons, random_state=42)
X = simulate_neurons(A, 4000, random_state=42)
reg_args = {
"fit_intercept": False,
"alpha": 0.001
}
@widgets.interact
def plot_observed(n_observed=(5, 45, 5)):
to_neuron = 0
fig, axs = plt.subpl... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D3_NetworkCausality/W3D3_Tutorial3.ipynb | mmyros/course-content |
Next, we will inspect a plot of the correlation between true and estimated connectivity matrices vs the percent of neurons observed over multiple trials.What is the relationship that you see between performance and the number of neurons observed?**Note:** the cell below will take about 25-30 seconds to run. | #@title
#@markdown Plot correlation vs. subsampling
import warnings
warnings.filterwarnings('ignore')
# we'll simulate many systems for various ratios of observed neurons
n_neurons = 50
timesteps = 5000
ratio_observed = [1, 0.75, 0.5, .25, .12] # the proportion of neurons observed in our system
n_trials = 3 # run it... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D3_NetworkCausality/W3D3_Tutorial3.ipynb | mmyros/course-content |
--- Summary | #@title Video 4: Summary
# Insert the ID of the corresponding youtube video
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="T1uGf1H31wE", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W3D3_NetworkCausality/W3D3_Tutorial3.ipynb | mmyros/course-content |
In-Class Coding Lab: IterationsThe goals of this lab are to help you to understand:- How loops work.- The difference between definite and indefinite loops, and when to use each.- How to build an indefinite loop with complex exit conditions.- How to create a program from a complex idea. Understanding IterationsIterati... | i = 1
while i <= 3:
print(i,"Mississippi...")
i=i+1
print("Blitz!") | 1 Mississippi...
2 Mississippi...
3 Mississippi...
Blitz!
| MIT | content/lessons/05/Class-Coding-Lab/CCL-Iterations.ipynb | MahopacHS/spring2019-mollea1213 |
Breaking it down...The `while` statement on line 2 starts the loop. The code indented beneath it (lines 3-4) will repeat, in a linear fashion until the Boolean expression on line 2 `i <= 3` is `False`, at which time the program continues with line 5. Some TerminologyWe call `i <=3` the loop's **exit condition**. The v... | ## WARNING!!! INFINITE LOOP AHEAD
## IF YOU RUN THIS CODE YOU WILL NEED TO KILL YOUR BROWSER AND SHUT DOWN JUPYTER NOTEBOOK
i = 1
while i <= 3:
print(i,"Mississippi...")
# i=i+1
print("Blitz!") | _____no_output_____ | MIT | content/lessons/05/Class-Coding-Lab/CCL-Iterations.ipynb | MahopacHS/spring2019-mollea1213 |
For loopsTo prevent an infinite loop when the loop is definite, we use the `for` statement. Here's the same program using `for`: | for i in range(1,4):
print(i,"Mississippi...")
print("Blitz!") | 1 Mississippi...
2 Mississippi...
3 Mississippi...
Blitz!
| MIT | content/lessons/05/Class-Coding-Lab/CCL-Iterations.ipynb | MahopacHS/spring2019-mollea1213 |
One confusing aspect of this loop is `range(1,4)` why does this loop from 1 to 3? Why not 1 to 4? Well it has to do with the fact that computers start counting at zero. The easier way to understand it is if you subtract the two numbers you get the number of times it will loop. So for example, 4-1 == 3. Now Try ItIn the... | # TODO Write code here
for i in range(10,16):
print(i,"Mississippi...")
print("Blitz!") | 10 Mississippi...
11 Mississippi...
12 Mississippi...
13 Mississippi...
14 Mississippi...
15 Mississippi...
Blitz!
| MIT | content/lessons/05/Class-Coding-Lab/CCL-Iterations.ipynb | MahopacHS/spring2019-mollea1213 |
Indefinite loopsWith **indefinite loops** we do not know how many times the program will execute. This is typically based on user action, and therefore our loop is subject to the whims of whoever interacts with it. Most applications like spreadsheets, photo editors, and games use indefinite loops. They'll run on your ... | name = ""
while name != 'mike':
name = input("Say my name! : ")
print("Nope, my name is not %s! " %(name)) | Nope, my name is not yeee!
Nope, my name is not !
Nope, my name is not !
Nope, my name is not mike!
| MIT | content/lessons/05/Class-Coding-Lab/CCL-Iterations.ipynb | MahopacHS/spring2019-mollea1213 |
The classic problem with indefinite loops is that its really difficult to get the application's logic to line up with the exit condition. For example we need to set `name = ""` in line 1 so that line 2 start out as `True`. Also we have this wonky logic where when we say `'mike'` it still prints `Nope, my name is not mi... | while True:
name = input("Say my name!: ")
if name == 'mike':
break
print("Nope, my name is not %s!" %(name)) | Nope, my name is not anthony!
| MIT | content/lessons/05/Class-Coding-Lab/CCL-Iterations.ipynb | MahopacHS/spring2019-mollea1213 |
Multiple exit conditionsThis indefinite loop pattern makes it easy to add additional exit conditions. For example, here's the program again, but it now stops when you say my name or type in 3 wrong names. Make sure to run this program a couple of times. First enter mike to exit the program, next enter the wrong name 3... | times = 0
while True:
name = input("Say my name!: ")
times = times + 1
if name == 'mike':
print("You got it!")
break
if times == 3:
print("Game over. Too many tries!")
break
print("Nope, my name is not %s!" %(name)) | Nope, my name is not yee!
Nope, my name is not pee!
You got it!
| MIT | content/lessons/05/Class-Coding-Lab/CCL-Iterations.ipynb | MahopacHS/spring2019-mollea1213 |
Number sumsLet's conclude the lab with you writing your own program whichuses an indefinite loop. We'll provide the to-do list, you write the code. This program should ask for floating point numbers as input and stops looping when **the total of the numbers entered is over 100**, or **more than 5 numbers have been ent... | ## TO-DO List
#1 count = 0
#2 total = 0
#3 loop Indefinitely
#4. input a number
#5 increment count
#6 add number to total
#7 if count equals 5 stop looping
#8 if total greater than 100 stop looping
#9 print total and count
# Write Code here:
count = 0
total = 0
while True:
total = flo... | Your total is greater than 100.
The total is 113.4 and the count is 4
| MIT | content/lessons/05/Class-Coding-Lab/CCL-Iterations.ipynb | MahopacHS/spring2019-mollea1213 |
Cleaning First, we need to convert the "difference from reference" format back into a normal sequence.Using the Uniprot reference we can add back in the missing information. | pr_seq = 'PQITLWQRPLVTIKIGGQLKEALLDTGADDTVLEEMNLPGRWKPKMIGGIGGFIKVRQYDQILIEICGHKAIGTVLVGPTPVNIIGRNLLTQIGCTLNF'
# REF: https://hivdb.stanford.edu/pages/documentPage/consensus_amino_acid_sequences.html
seq_cols = [f'P{i}' for i in range(1,100)]
rep_dict = {}
for col, pr in zip(seq_cols, pr_seq):
rep_dict[col] = {'-'... | _____no_output_____ | CECILL-B | workflow/scripts/process_stanford_pr.py.ipynb | DamLabResources/hiv-transformers |
We also need to account for the data sparseness.The subset of drugs: FPV, IDV, NFV, and SQV have the highest mutual coverage. We'll use only those for downstream predictions. | wanted = ['FPV', 'IDV', 'NFV', 'SQV']
df.dropna(subset = wanted, inplace = True)
cutoff = 4 # fold increase over WT
resist = df[wanted]>4
resist['MULTI'] = resist.sum(axis=1)>0
resist.sum() | _____no_output_____ | CECILL-B | workflow/scripts/process_stanford_pr.py.ipynb | DamLabResources/hiv-transformers |
Dataset Creation | # TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@InProceedings{huggingface:dataset,
title = {HIV Protease Drug Resistance Prediction Dataset},
author={Will Dampier
},
year={2021}
}
"""
# TODO: Add a link to an official homepage for the dataset here
... | _____no_output_____ | CECILL-B | workflow/scripts/process_stanford_pr.py.ipynb | DamLabResources/hiv-transformers |
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
import os
%matplotlib inline | _____no_output_____ | MIT | P1.ipynb | mattlubbers/Udacity-SDC-Lane_Lines |
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 | mattlubbers/Udacity-SDC-Lane_Lines |
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 Grayscale transform"""
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
def canny(img, low_threshold, high_threshold):
"""Applies the Canny transform"""
return cv2.Canny(img, low_threshold, high_threshold)
def gaussian_blur(img, kernel_size):
"""Applies a Ga... | _____no_output_____ | MIT | P1.ipynb | mattlubbers/Udacity-SDC-Lane_Lines |
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.** | # Use a single Image to test the Pipeline
image = mpimg.imread('test_images/' + 'solidWhiteCurve.jpg')
#Start with Grayscale
ip_gray = grayscale(image)
plt.imshow(ip_gray)
# Apply Gaussian Blur
ip_gaussian = gaussian_blur(ip_gray, 3)
plt.imshow(ip_gaussian)
# Experiment with Canny Edge Parameters
ip_canny1 = canny(ip_g... | _____no_output_____ | MIT | P1.ipynb | mattlubbers/Udacity-SDC-Lane_Lines |
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. | def image_processing(image):
# Set Hough Parameters
rho = 2
theta = np.pi/180
threshold = 20 #Originally 10
min_line_len = 40 #Originally 20
max_line_gap = 10
#Set Canny Parameters
low_threshold = 60
high_threshold = 120
#Set Mask Vertices
vertices = np.arr... | _____no_output_____ | MIT | P1.ipynb | mattlubbers/Udacity-SDC-Lane_Lines |
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 | _____no_output_____ | MIT | P1.ipynb | mattlubbers/Udacity-SDC-Lane_Lines |
Let's try the one with the solid white lane on the right first ... | white_output = 'test_videos_output/solidWhiteRight.mp4'
clip1 = VideoFileClip("test_videos/solidWhiteRight.mp4")
white_clip = clip1.fl_image(image_processing) #NOTE: this function expects color images!!
%time white_clip.write_videofile(white_output, audio=False) | [MoviePy] >>>> Building video test_videos_output/solidWhiteRight.mp4
[MoviePy] Writing video test_videos_output/solidWhiteRight.mp4
| MIT | P1.ipynb | mattlubbers/Udacity-SDC-Lane_Lines |
Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice. | HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(white_output)) | _____no_output_____ | MIT | P1.ipynb | mattlubbers/Udacity-SDC-Lane_Lines |
Improve the draw_lines() function**At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about de... | yellow_output = 'test_videos_output/solidYellowLeft_houghTest.mp4'
clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4')
yellow_clip = clip2.fl_image(image_processing)
%time yellow_clip.write_videofile(yellow_output, audio=False)
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".fo... | _____no_output_____ | MIT | P1.ipynb | mattlubbers/Udacity-SDC-Lane_Lines |
Writeup and SubmissionIf you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_templat... | challenge_output = 'test_videos_output/challenge.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 e... | _____no_output_____ | MIT | P1.ipynb | mattlubbers/Udacity-SDC-Lane_Lines |
배열 다루기 연습문제___ | import numpy as np | _____no_output_____ | MIT | 02NumPy/03numpy배열다루기_연습.ipynb | aonekoda/YGL_1 |
Q1. x가 10x10x3의 다차원 배열일때, x의 두번째 차원이 150인 2차원 배열이 되도록 reshape하세요. | x = np.ones([10, 10, 3])
| _____no_output_____ | MIT | 02NumPy/03numpy배열다루기_연습.ipynb | aonekoda/YGL_1 |
Q2. x가 [[1, 2, 3], [4, 5, 6]]일 때, [1 2 3 4 5 6]로 변환하세요. | x = np.array([[1, 2, 3], [4, 5, 6]])
| _____no_output_____ | MIT | 02NumPy/03numpy배열다루기_연습.ipynb | aonekoda/YGL_1 |
Q3. x가 [[1, 2, 3], [4, 5, 6]]일 때, flatten한 후 5번째 원소를 가져오세요. | x = np.array([[1, 2, 3], [4, 5, 6]])
out = x.flatten()
out[?] | _____no_output_____ | MIT | 02NumPy/03numpy배열다루기_연습.ipynb | aonekoda/YGL_1 |
Q4. x= [[ 1 2 3][ 4 5 6].y = [[ 7 8 9][10 11 12]].x와 y를 연결해서[[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]를 만드세요 | x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.array([[7, 8, 9], [10, 11, 12]])
| _____no_output_____ | MIT | 02NumPy/03numpy배열다루기_연습.ipynb | aonekoda/YGL_1 |
Q5. x= [[ 1 2 3][ 4 5 6].y = [[ 7 8 9][10 11 12]].x와 y를 연결해서[[ 1 2 3] [ 4 5 6] [ 7 8 9] [10 11 12]]를 만드세요 | x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.array([[7, 8, 9], [10, 11, 12]])
| _____no_output_____ | MIT | 02NumPy/03numpy배열다루기_연습.ipynb | aonekoda/YGL_1 |
TensorFlow Transfer LearningThis notebook shows how to use pre-trained models from [TensorFlowHub](https://www.tensorflow.org/hub). Sometimes, there is not enough data, computational resources, or time to train a model from scratch to solve a particular problem. We'll use a pre-trained model to classify flowers with b... | import os
import pathlib
import IPython.display as display
import matplotlib.pylab as plt
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from PIL import Image
from tensorflow.keras import Sequential
from tensorflow.keras.layers import (
Conv2D,
Dense,
Dropout,
Flatten,
MaxP... | _____no_output_____ | Apache-2.0 | notebooks/image_models/solutions/3_tf_hub_transfer_learning.ipynb | Jonathanpro/asl-ml-immersion |
Exploring the dataAs usual, let's take a look at the data before we start building our model. We'll be using a creative-commons licensed flower photo dataset of 3670 images falling into 5 categories: 'daisy', 'roses', 'dandelion', 'sunflowers', and 'tulips'.The below [tf.keras.utils.get_file](https://www.tensorflow.or... | data_dir = tf.keras.utils.get_file(
"flower_photos",
"https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz",
untar=True,
)
# Print data path
print("cd", data_dir) | _____no_output_____ | Apache-2.0 | notebooks/image_models/solutions/3_tf_hub_transfer_learning.ipynb | Jonathanpro/asl-ml-immersion |
We can use python's built in [pathlib](https://docs.python.org/3/library/pathlib.html) tool to get a sense of this unstructured data. | data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob("*/*.jpg")))
print("There are", image_count, "images.")
CLASS_NAMES = np.array(
[item.name for item in data_dir.glob("*") if item.name != "LICENSE.txt"]
)
print("These are the available classes:", CLASS_NAMES) | _____no_output_____ | Apache-2.0 | notebooks/image_models/solutions/3_tf_hub_transfer_learning.ipynb | Jonathanpro/asl-ml-immersion |
Let's display the images so we can see what our model will be trying to learn. | roses = list(data_dir.glob("roses/*"))
for image_path in roses[:3]:
display.display(Image.open(str(image_path))) | _____no_output_____ | Apache-2.0 | notebooks/image_models/solutions/3_tf_hub_transfer_learning.ipynb | Jonathanpro/asl-ml-immersion |
Building the datasetKeras has some convenient methods to read in image data. For instance [tf.keras.preprocessing.image.ImageDataGenerator](https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator) is great for small local datasets. A tutorial on how to use it can be found [here](http... | !gsutil cat gs://cloud-ml-data/img/flower_photos/train_set.csv \
| head -5 > /tmp/input.csv
!cat /tmp/input.csv
!gsutil cat gs://cloud-ml-data/img/flower_photos/train_set.csv | \
sed 's/,/ /g' | awk '{print $2}' | sort | uniq > /tmp/labels.txt
!cat /tmp/labels.txt | _____no_output_____ | Apache-2.0 | notebooks/image_models/solutions/3_tf_hub_transfer_learning.ipynb | Jonathanpro/asl-ml-immersion |
Let's figure out how to read one of these images from the cloud. TensorFlow's [tf.io.read_file](https://www.tensorflow.org/api_docs/python/tf/io/read_file) can help us read the file contents, but the result will be a [Base64 image string](https://en.wikipedia.org/wiki/Base64). Hmm... not very readable for humans or Ten... | IMG_HEIGHT = 224
IMG_WIDTH = 224
IMG_CHANNELS = 3
BATCH_SIZE = 32
# 10 is a magic number tuned for local training of this dataset.
SHUFFLE_BUFFER = 10 * BATCH_SIZE
AUTOTUNE = tf.data.experimental.AUTOTUNE
VALIDATION_IMAGES = 370
VALIDATION_STEPS = VALIDATION_IMAGES // BATCH_SIZE
def decode_img(img, reshape_dims):
... | _____no_output_____ | Apache-2.0 | notebooks/image_models/solutions/3_tf_hub_transfer_learning.ipynb | Jonathanpro/asl-ml-immersion |
Is it working? Let's see!**TODO 1.a:** Run the `decode_img` function and plot it to see a happy looking daisy. | img = tf.io.read_file(
"gs://cloud-ml-data/img/flower_photos/daisy/754296579_30a9ae018c_n.jpg"
)
# Uncomment to see the image string.
# print(img)
img = decode_img(img, [IMG_WIDTH, IMG_HEIGHT])
plt.imshow(img.numpy()); | _____no_output_____ | Apache-2.0 | notebooks/image_models/solutions/3_tf_hub_transfer_learning.ipynb | Jonathanpro/asl-ml-immersion |
One flower down, 3669 more of them to go. Rather than load all the photos in directly, we'll use the file paths given to us in the csv and load the images when we batch. [tf.io.decode_csv](https://www.tensorflow.org/api_docs/python/tf/io/decode_csv) reads in csv rows (or each line in a csv file), while [tf.math.equal](... | def decode_csv(csv_row):
record_defaults = ["path", "flower"]
filename, label_string = tf.io.decode_csv(csv_row, record_defaults)
image_bytes = tf.io.read_file(filename=filename)
label = tf.math.equal(CLASS_NAMES, label_string)
return image_bytes, label | _____no_output_____ | Apache-2.0 | notebooks/image_models/solutions/3_tf_hub_transfer_learning.ipynb | Jonathanpro/asl-ml-immersion |
Next, we'll transform the images to give our network more variety to train on. There are a number of [image manipulation functions](https://www.tensorflow.org/api_docs/python/tf/image). We'll cover just a few:* [tf.image.random_crop](https://www.tensorflow.org/api_docs/python/tf/image/random_crop) - Randomly deletes th... | MAX_DELTA = 63.0 / 255.0 # Change brightness by at most 17.7%
CONTRAST_LOWER = 0.2
CONTRAST_UPPER = 1.8
def read_and_preprocess(image_bytes, label, random_augment=False):
if random_augment:
img = decode_img(image_bytes, [IMG_HEIGHT + 10, IMG_WIDTH + 10])
img = tf.image.random_crop(img, [IMG_HEIGH... | _____no_output_____ | Apache-2.0 | notebooks/image_models/solutions/3_tf_hub_transfer_learning.ipynb | Jonathanpro/asl-ml-immersion |
Finally, we'll make a function to craft our full dataset using [tf.data.dataset](https://www.tensorflow.org/api_docs/python/tf/data/Dataset). The [tf.data.TextLineDataset](https://www.tensorflow.org/api_docs/python/tf/data/TextLineDataset) will read in each line in our train/eval csv files to our `decode_csv` function.... | def load_dataset(csv_of_filenames, batch_size, training=True):
dataset = (
tf.data.TextLineDataset(filenames=csv_of_filenames)
.map(decode_csv)
.cache()
)
if training:
dataset = (
dataset.map(read_and_preprocess_with_augment)
.shuffle(SHUFFLE_BUFFER)
... | _____no_output_____ | Apache-2.0 | notebooks/image_models/solutions/3_tf_hub_transfer_learning.ipynb | Jonathanpro/asl-ml-immersion |
We'll test it out with our training set. A batch size of one will allow us to easily look at each augmented image. | train_path = "gs://cloud-ml-data/img/flower_photos/train_set.csv"
train_data = load_dataset(train_path, 1)
itr = iter(train_data) | _____no_output_____ | Apache-2.0 | notebooks/image_models/solutions/3_tf_hub_transfer_learning.ipynb | Jonathanpro/asl-ml-immersion |
**TODO 1.c:** Run the below cell repeatedly to see the results of different batches. The images have been un-normalized for human eyes. Can you tell what type of flowers they are? Is it fair for the AI to learn on? | image_batch, label_batch = next(itr)
img = image_batch[0]
plt.imshow(img)
print(label_batch[0]) | _____no_output_____ | Apache-2.0 | notebooks/image_models/solutions/3_tf_hub_transfer_learning.ipynb | Jonathanpro/asl-ml-immersion |
**Note:** It may take a 4-5 minutes to see result of different batches. MobileNetV2These flower photos are much larger than handwritting recognition images in MNIST. They are about 10 times as many pixels per axis **and** there are three color channels, making the information here over 200 times larger!How do our cur... | eval_path = "gs://cloud-ml-data/img/flower_photos/eval_set.csv"
nclasses = len(CLASS_NAMES)
hidden_layer_1_neurons = 400
hidden_layer_2_neurons = 100
dropout_rate = 0.25
num_filters_1 = 64
kernel_size_1 = 3
pooling_size_1 = 2
num_filters_2 = 32
kernel_size_2 = 3
pooling_size_2 = 2
layers = [
Conv2D(
num_fi... | _____no_output_____ | Apache-2.0 | notebooks/image_models/solutions/3_tf_hub_transfer_learning.ipynb | Jonathanpro/asl-ml-immersion |
If your model is like mine, it learns a little bit, slightly better then random, but *ugh*, it's too slow! With a batch size of 32, 5 epochs of 5 steps is only getting through about a quarter of our images. Not to mention, this is a much larger problem then MNIST, so wouldn't we need a larger model? But how big do we n... | module_selection = "mobilenet_v2_100_224"
module_handle = "https://tfhub.dev/google/imagenet/{}/feature_vector/4".format(
module_selection
)
transfer_model = tf.keras.Sequential(
[
hub.KerasLayer(module_handle, trainable=False),
tf.keras.layers.Dropout(rate=0.2),
tf.keras.layers.Dense(
... | _____no_output_____ | Apache-2.0 | notebooks/image_models/solutions/3_tf_hub_transfer_learning.ipynb | Jonathanpro/asl-ml-immersion |
Even though we're only adding one more `Dense` layer in order to get the probabilities for each of the 5 flower types, we end up with over six thousand parameters to train ourselves. Wow!Moment of truth. Let's compile this new model and see how it compares to our MNIST architecture. | transfer_model.compile(
optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"]
)
train_ds = load_dataset(train_path, BATCH_SIZE)
eval_ds = load_dataset(eval_path, BATCH_SIZE, training=False)
transfer_model.fit(
train_ds,
epochs=5,
steps_per_epoch=5,
validation_data=eval_ds,
val... | _____no_output_____ | Apache-2.0 | notebooks/image_models/solutions/3_tf_hub_transfer_learning.ipynb | Jonathanpro/asl-ml-immersion |
Code: Draw a 10 mm line from (0, 0) to (10, 0). | line_len = 10
line_n_points = 2
p = np.linspace(0, line_len, line_n_points, endpoint=True)
p
line_n_points = 3
p = np.linspace(0, line_len, line_n_points, endpoint=True)
p
line_n_points = 4
p = np.linspace(0, line_len, line_n_points, endpoint=True)
p
p
Y=0
for X in np.linspace(0, line_len, line_n_points, endpoint=True)... | _____no_output_____ | BSD-3-Clause | Drawing/OldDrawing/PathOptimization-Copy3.ipynb | jed-frey/python_cnc3018 |
Supervised Learning Supervised learning consists in learning the link between two datasets: the observed data X and an external variable y that we are trying to predict, usually called “target” or “labels”. Most often, y is a 1D array of length n_samples.If the prediction task is to classify the observations in a set ... | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from sklearn.decomposition import PCA
def pca_plot(data):
pca = PCA(n_components=2)
pca.fit(data.data)
data_pca = pca.transform(data.data)
for label in range(len(data.target_names)):
plt.scatter(data_pca[data.target==label, ... | _____no_output_____ | MIT | notebooks/06 Supervised Learning.ipynb | d9w/computational_intelligence |
Another dataset with more features is the wine classification dataset, which tries to determine the original cultivar, or plant family, of three different Italian wines. A chemical analysis determined the following samples:1. Alcohol2. Malic acid3. Ash4. Alcalinity of ash 5. Magnesium6. Total phenols7. Flavanoids8. No... | from sklearn.datasets import load_wine
wine = load_wine()
pca_plot(wine) | _____no_output_____ | MIT | notebooks/06 Supervised Learning.ipynb | d9w/computational_intelligence |
A final and more difficult dataset is a sample from the National Institute of Standards and Technology (NIST) dataset on handwritten numbers. A modified and larger version of this, Modified NIST or MNIST, is a current standard benchmark for state of the art machine learning algorithms. In this problem, each datapoint i... | from sklearn.datasets import load_digits
digits = load_digits()
images_and_labels = list(zip(digits.images, digits.target))
for index, (image, label) in enumerate(images_and_labels[:8]):
plt.subplot(2, 4, index + 1)
plt.axis('off')
plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
plt.titl... | _____no_output_____ | MIT | notebooks/06 Supervised Learning.ipynb | d9w/computational_intelligence |
Regression "In statistical modeling, regression analysis is a set of statistical processes for estimating the relationships among variables. It includes many techniques for modeling and analyzing several variables, when the focus is on the relationship between a dependent variable and one or more independent variables... | from sklearn.datasets import load_diabetes
diabetes = load_diabetes()
y = diabetes.target
features = ["AGE", "SEX", "BMI", "BP", "BL1", "BL2", "BL3", "BL4", "BL5", "BL6"]
plt.figure(figsize=(20,20))
for i in range(10):
plt.subplot(4, 4, i + 1)
plt.scatter(diabetes.data[:, i], y, edgecolors=(0, 0, 0));
plt.t... | _____no_output_____ | MIT | notebooks/06 Supervised Learning.ipynb | d9w/computational_intelligence |
Your first neural networkIn this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementation of the neural network up to you (for the most part). After you've submitted this project, feel free to explore the data and th... | %matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt | _____no_output_____ | Apache-2.0 | DLND-your-first-network/dlnd-your-first-neural-network.ipynb | zhaojijet/UdacityDeepLearningProject |
Load and prepare the dataA critical step in working with neural networks is preparing the data correctly. Variables on different scales make it difficult for the network to efficiently learn the correct weights. Below, we've written the code to load and prepare the data. You'll learn more about this soon! | data_path = 'Bike-Sharing-Dataset/hour.csv'
rides = pd.read_csv(data_path)
rides.head() | _____no_output_____ | Apache-2.0 | DLND-your-first-network/dlnd-your-first-neural-network.ipynb | zhaojijet/UdacityDeepLearningProject |
Checking out the dataThis dataset has the number of riders for each hour of each day from January 1 2011 to December 31 2012. The number of riders is split between casual and registered, summed up in the `cnt` column. You can see the first few rows of the data above.Below is a plot showing the number of bike riders ov... | rides[:24*10].plot(x='dteday', y='cnt') | _____no_output_____ | Apache-2.0 | DLND-your-first-network/dlnd-your-first-neural-network.ipynb | zhaojijet/UdacityDeepLearningProject |
Dummy variablesHere we have some categorical variables like season, weather, month. To include these in our model, we'll need to make binary dummy variables. This is simple to do with Pandas thanks to `get_dummies()`. | dummy_fields = ['season', 'weathersit', 'mnth', 'hr', 'weekday']
for each in dummy_fields:
dummies = pd.get_dummies(rides[each], prefix=each, drop_first=False)
rides = pd.concat([rides, dummies], axis=1)
fields_to_drop = ['instant', 'dteday', 'season', 'weathersit',
'weekday', 'atemp', 'mnth... | _____no_output_____ | Apache-2.0 | DLND-your-first-network/dlnd-your-first-neural-network.ipynb | zhaojijet/UdacityDeepLearningProject |
Scaling target variablesTo make training the network easier, we'll standardize each of the continuous variables. That is, we'll shift and scale the variables such that they have zero mean and a standard deviation of 1.The scaling factors are saved so we can go backwards when we use the network for predictions. | quant_features = ['casual', 'registered', 'cnt', 'temp', 'hum', 'windspeed']
# Store scalings in a dictionary so we can convert back later
scaled_features = {}
for each in quant_features:
mean, std = data[each].mean(), data[each].std()
scaled_features[each] = [mean, std]
data.loc[:, each] = (data[each] - me... | _____no_output_____ | Apache-2.0 | DLND-your-first-network/dlnd-your-first-neural-network.ipynb | zhaojijet/UdacityDeepLearningProject |
Splitting the data into training, testing, and validation setsWe'll save the last 21 days of the data to use as a test set after we've trained the network. We'll use this set to make predictions and compare them with the actual number of riders. | # Save the last 21 days
test_data = data[-21*24:]
data = data[:-21*24]
# Separate the data into features and targets
target_fields = ['cnt', 'casual', 'registered']
features, targets = data.drop(target_fields, axis=1), data[target_fields]
test_features, test_targets = test_data.drop(target_fields, axis=1), test_data[... | _____no_output_____ | Apache-2.0 | DLND-your-first-network/dlnd-your-first-neural-network.ipynb | zhaojijet/UdacityDeepLearningProject |
We'll split the data into two sets, one for training and one for validating as the network is being trained. Since this is time series data, we'll train on historical data, then try to predict on future data (the validation set). | # Hold out the last 60 days of the remaining data as a validation set
train_features, train_targets = features[:-60*24], targets[:-60*24]
val_features, val_targets = features[-60*24:], targets[-60*24:] | _____no_output_____ | Apache-2.0 | DLND-your-first-network/dlnd-your-first-neural-network.ipynb | zhaojijet/UdacityDeepLearningProject |
Time to build the networkBelow you'll build your network. We've built out the structure and the backwards pass. You'll implement the forward pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes.The network has two layers, a hidd... | class NeuralNetwork(object):
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
# Set number of nodes in input, hidden and output layers.
self.input_nodes = input_nodes
self.hidden_nodes = hidden_nodes
self.output_nodes = output_nodes
# Initialize we... | _____no_output_____ | Apache-2.0 | DLND-your-first-network/dlnd-your-first-neural-network.ipynb | zhaojijet/UdacityDeepLearningProject |
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 here ###
epochs = 1000
learning_rate = 0.1
hidden_nodes = 10
output_nodes = 1
N_i = train_features.shape[1]
network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate)
losses = {'train':[], 'validation':[]}
for e in range(epochs):
# Go through a random batch of ... | _____no_output_____ | Apache-2.0 | DLND-your-first-network/dlnd-your-first-neural-network.ipynb | zhaojijet/UdacityDeepLearningProject |
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)*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_d... | _____no_output_____ | Apache-2.0 | DLND-your-first-network/dlnd-your-first-neural-network.ipynb | zhaojijet/UdacityDeepLearningProject |
Thinking about your results Answer these questions about your results. How well does the model predict the data? Where does it fail? Why does it fail where it does?> **Note:** You can edit the text in this cell by double clicking on it. When you want to render the text, press control + enter Your answer belowBefore De... | import unittest
inputs = [0.5, -0.2, 0.1]
targets = [0.4]
test_w_i_h = np.array([[0.1, 0.4, -0.3],
[-0.2, 0.5, 0.2]])
test_w_h_o = np.array([[0.3, -0.1]])
class TestMethods(unittest.TestCase):
##########
# Unit tests for data loading
##########
def test_data_path(self... | .....
----------------------------------------------------------------------
Ran 5 tests in 0.006s
OK
| Apache-2.0 | DLND-your-first-network/dlnd-your-first-neural-network.ipynb | zhaojijet/UdacityDeepLearningProject |
model | import sys
sys.path.append('..')
from utils.dataset.ec import ECDataset
from utils.dataloader.ec import ECDataLoader
from models.han.word_model import WordAttention
from models.han.sentence_model import SentenceWithPosition
device = torch.device('cuda: 0')
batch_size = 16
vocab_size = 23071
num_classes = 2
sequence_len... | _____no_output_____ | MIT | notebook/.ipynb_checkpoints/Bi-LSTM-CRF-checkpoint.ipynb | stevehamwu/EmotionCauseExtraction |
init | def argmax(vec):
# return the argmax as a python int
_, idx = torch.max(vec, 1)
return idx.item()
def prepare_sequence(seq, to_ix):
idxs = [to_ix[w] for w in seq]
return torch.tensor(idxs, dtype=torch.long)
# Compute log sum exp in a numerically stable way for the forward algorithm
def log_sum_ex... | _____no_output_____ | MIT | notebook/.ipynb_checkpoints/Bi-LSTM-CRF-checkpoint.ipynb | stevehamwu/EmotionCauseExtraction |
forward | inputs = Embedding(clauses)
queries = Embedding(keywords)
documents, word_attn = word_rnn(inputs, queries)
outputs, sentence_attn = sentence_rnn(documents, poses)
s_c = torch.cat((documents, outputs), dim=-1)
outputs = fc(drop(s_c))
outputs.size()
lstm_feats = copy(outputs)
lstm_feats.size() | _____no_output_____ | MIT | notebook/.ipynb_checkpoints/Bi-LSTM-CRF-checkpoint.ipynb | stevehamwu/EmotionCauseExtraction |
_forward_alg | init_alphas = torch.full((1, tagset_size), -10000.).to(device)
# START_TAG has all of the score.
init_alphas[0][tag_to_ix[START_TAG]] = 0.
# Wrap in a variable so that we will get automatic backprop
forward_var = init_alphas
# Iterate through the sentence
for feat in lstm_feats:
alphas_t = [] # The forward tenso... | _____no_output_____ | MIT | notebook/.ipynb_checkpoints/Bi-LSTM-CRF-checkpoint.ipynb | stevehamwu/EmotionCauseExtraction |
_score_sentence | lstm_feats.size()
tags = copy(targets)
score = torch.zeros(1).to(device)
tags = torch.cat((torch.full((tags.size(0), 1), tag_to_ix[START_TAG], dtype=torch.long).to(device), tags), dim=-1)
for feats, tag in zip(lstm_feats, tags):
score = torch.zeros(1).to(device)
tag = torch.cat([torch.LongTensor([tag_to_ix[STAR... | _____no_output_____ | MIT | notebook/.ipynb_checkpoints/Bi-LSTM-CRF-checkpoint.ipynb | stevehamwu/EmotionCauseExtraction |
_viterbi_decode | backpointers = []
# Initialize the viterbi variables in log space
init_vvars = torch.full((1, tagset_size), -10000.).to(device)
init_vvars[0][tag_to_ix[START_TAG]] = 0
# forward_var at step i holds the viterbi variables for step i-1
forward_var = init_vvars
for feat in lstm_feats:
bptrs_t = [] # holds the backpo... | _____no_output_____ | MIT | notebook/.ipynb_checkpoints/Bi-LSTM-CRF-checkpoint.ipynb | stevehamwu/EmotionCauseExtraction |
Author[Koen Aerts](https://koenaerts.ca/) @ [Mobia Technology Innovations](https://mobia.io)[myOpenHealth](https://mobia.io/healthcare/) IntroThis notebook plots some of the individual heartbeat records that were generated from the "02_import_mitdb_data" notebook. InitializeImport dependencies. | import numpy as np
from matplotlib import pyplot as plt | _____no_output_____ | MIT | 03_view_imported_data.ipynb | JiaminXu1019/ECG_ML |
Load DataChange file name to select different file. The file must be CSV and each row should contain exactly 188 values. | data = np.loadtxt('data_ecg/210_MLII.csv', delimiter=',')
print(data.shape) | _____no_output_____ | MIT | 03_view_imported_data.ipynb | JiaminXu1019/ECG_ML |
VisualizeChange values to navigate around the data. Different colors are used for Normal vs Abnormal heartbeats. | for beatid in [0,1,2,3,99,200,502,2428,2443]:
times = np.arange(187, dtype = 'float') / 187
beat = data[beatid][:-1]
anno = data[beatid][-1]
plt.figure(figsize=(20,5))
if (anno == 0.0):
plt.plot(times, beat, 'b')
else:
plt.plot(times, beat, 'r')
plt.xlabel('Time [s]')
plt.yla... | _____no_output_____ | MIT | 03_view_imported_data.ipynb | JiaminXu1019/ECG_ML |
Lambda School Data Science*Unit 2, Sprint 1, Module 3*--- | %%capture
import sys
# If you're on Colab:
if 'google.colab' in sys.modules:
DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/'
!pip install category_encoders==2.*
# If you're working locally:
else:
DATA_PATH = '../data/' | _____no_output_____ | MIT | module3-ridge-regression/LS_DS_213_assignment.ipynb | ppmorgoun/DS-Unit-2-Linear-Models |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.