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
Build the GraphBuild the graph using the neural network you implemented.
""" DON'T MODIFY ANYTHING IN THIS CELL """ from tensorflow.contrib import seq2seq train_graph = tf.Graph() with train_graph.as_default(): vocab_size = len(int_to_vocab) input_text, targets, lr = get_inputs() input_data_shape = tf.shape(input_text) cell, initial_state = get_init_cell(input_data_shape[0]...
_____no_output_____
Apache-2.0
project-3-tv-script-generation/dlnd_tv_script_generation.ipynb
vwiart/deeplearning-udacity
TrainTrain the neural network on the preprocessed data. If you have a hard time getting a good loss, check the [forms](https://discussions.udacity.com/) to see if anyone is having the same problem.
""" DON'T MODIFY ANYTHING IN THIS CELL """ batches = get_batches(int_text, batch_size, seq_length) with tf.Session(graph=train_graph) as sess: sess.run(tf.global_variables_initializer()) for epoch_i in range(num_epochs): state = sess.run(initial_state, {input_text: batches[0][0]}) for batch_i...
Epoch 0 Batch 0/4 train_loss = 8.849 Epoch 2 Batch 2/4 train_loss = 5.364 Epoch 5 Batch 0/4 train_loss = 4.697 Epoch 7 Batch 2/4 train_loss = 4.241 Epoch 10 Batch 0/4 train_loss = 3.752 Epoch 12 Batch 2/4 train_loss = 3.367 Epoch 15 Batch 0/4 train_loss = 2.984 Epoch 17 Ba...
Apache-2.0
project-3-tv-script-generation/dlnd_tv_script_generation.ipynb
vwiart/deeplearning-udacity
Save ParametersSave `seq_length` and `save_dir` for generating a new TV script.
""" DON'T MODIFY ANYTHING IN THIS CELL """ # Save parameters for checkpoint helper.save_params((seq_length, save_dir))
_____no_output_____
Apache-2.0
project-3-tv-script-generation/dlnd_tv_script_generation.ipynb
vwiart/deeplearning-udacity
Checkpoint
""" DON'T MODIFY ANYTHING IN THIS CELL """ import tensorflow as tf import numpy as np import helper import problem_unittests as tests _, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess() seq_length, load_dir = helper.load_params()
_____no_output_____
Apache-2.0
project-3-tv-script-generation/dlnd_tv_script_generation.ipynb
vwiart/deeplearning-udacity
Implement Generate Functions Get TensorsGet tensors from `loaded_graph` using the function [`get_tensor_by_name()`](https://www.tensorflow.org/api_docs/python/tf/Graphget_tensor_by_name). Get the tensors using the following names:- "input:0"- "initial_state:0"- "final_state:0"- "probs:0"Return the tensors in the foll...
def get_tensors(loaded_graph): """ Get input, initial state, final state, and probabilities tensor from <loaded_graph> :param loaded_graph: TensorFlow graph loaded from file :return: Tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor) """ # TODO: Implement Function input_t...
Tests Passed
Apache-2.0
project-3-tv-script-generation/dlnd_tv_script_generation.ipynb
vwiart/deeplearning-udacity
Choose WordImplement the `pick_word()` function to select the next word using `probabilities`.
def pick_word(probabilities, int_to_vocab): """ Pick the next word in the generated text :param probabilities: Probabilites of the next word :param int_to_vocab: Dictionary of word ids as the keys and words as the values :return: String of the predicted word """ word = np.random.choice(list(...
Tests Passed
Apache-2.0
project-3-tv-script-generation/dlnd_tv_script_generation.ipynb
vwiart/deeplearning-udacity
Generate TV ScriptThis will generate the TV script for you. Set `gen_length` to the length of TV script you want to generate.
gen_length = 200 # homer_simpson, moe_szyslak, or Barney_Gumble prime_word = 'moe_szyslak' """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ loaded_graph = tf.Graph() with tf.Session(graph=loaded_graph) as sess: # Load saved model loader = tf.train.import_meta_graph(load_dir + '.meta') loa...
moe_szyslak:(lifts index finger) to the scooter store! moe_szyslak: i did not think this through. kemi: no. carl_carlson: oh, now we're talkin'. but why me? you still not? homer_simpson: what? i'm not where anything for you, crazy. kent_brockman: this is kent brockman with a channel 6 exclusive: the evil ned. kent_br...
Apache-2.0
project-3-tv-script-generation/dlnd_tv_script_generation.ipynb
vwiart/deeplearning-udacity
Random Signals and LTI-Systems*This jupyter notebook is part of a [collection of notebooks](../index.ipynb) on various topics of Digital Signal Processing. Please direct questions and suggestions to [Sascha.Spors@uni-rostock.de](mailto:Sascha.Spors@uni-rostock.de).* Measurement of Acoustic Impulse ResponsesThe propag...
import numpy as np import matplotlib.pyplot as plt import scipy.signal as sig import sounddevice as sd
_____no_output_____
MIT
random_signals_LTI_systems/acoustic_impulse_response_measurement.ipynb
ZeroCommits/digital-signal-processing-lecture
Generation of the Measurement SignalWe generate white noise with a uniform distribution between $\pm 0.5$ as the excitation signal $x[k]$
fs = 44100 # sampling rate T = 5 # length of the measurement signal in sec Tr = 2 # length of the expected system response in sec x = np.random.uniform(-.5, .5, size=T*fs)
_____no_output_____
MIT
random_signals_LTI_systems/acoustic_impulse_response_measurement.ipynb
ZeroCommits/digital-signal-processing-lecture
Playback of Measurement Signal and Recording of Room ResponseThe measurement signal $x[k]$ is played through the output of the soundcard and the response $y[k]$ is captured synchronously by the input of the soundcard. The length of the played/captured signal has to be of equal length when using the soundcard. The meas...
x = np.concatenate((x, np.zeros(Tr*fs))) y = sd.playrec(x, fs, channels=1) sd.wait() y = np.squeeze(y) print('Playback level: ', 20*np.log10(max(x)), ' dB') print('Input level: ', 20*np.log10(max(y)), ' dB')
Playback level: -6.02060087394 dB Input level: -2.23183822753 dB
MIT
random_signals_LTI_systems/acoustic_impulse_response_measurement.ipynb
ZeroCommits/digital-signal-processing-lecture
Estimation of the Acoustic Impulse ResponseThe acoustic impulse response is estimated by cross-correlation $\varphi_{yx}[\kappa]$ of the output with the input signal. Since the cross-correlation function (CCF) for finite-length signals is given as $\varphi_{yx}[\kappa] = \frac{1}{K} \cdot y[\kappa] * x[-\kappa]$, the ...
h = 1/len(y) * sig.fftconvolve(y, x[::-1], mode='full') h = h[fs*(T+Tr):fs*(T+2*Tr)] plt.figure(figsize=(10, 5)) t = 1/fs * np.arange(len(h)) plt.plot(t, h) plt.axis([0.0, 1.0, -1.1*np.max(np.abs(h)), 1.1*np.max(np.abs(h))]) plt.xlabel(r'$t$ in s') plt.ylabel(r'$\hat{h}[k]$')
_____no_output_____
MIT
random_signals_LTI_systems/acoustic_impulse_response_measurement.ipynb
ZeroCommits/digital-signal-processing-lecture
Lab 01 - Modelling and Systems Dynamics
import math, pandas from matplotlib import pyplot
_____no_output_____
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Section 01 - Starting Jupyter Notebook
print(math.sin(4))
-0.7568024953079282
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Section 02 - Number and Arithmetic
print(5 / 8) print(5 / 8.0) # or print(5 / float(8)) print(5 * 8) print((1 / 2.0) ** 2)
0.625 0.625 40 0.25
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Review Question
print(math.exp(10))
22026.465794806718
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Section 03 - Variables and Assignments
ans = 5 * math.pi ans += 1 print(ans + 2)
18.707963267948966
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Review Question
vel = 5 print((7 + (vel / 3)) ** 2)
75.1111111111111
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Section 04 - User Defined Functions
def f(x): return x ** 2 + 1 print(f(4)) print(f(2.5)) def sum_squares(x, y): return x ** 2 + y ** 2 print(sum_squares(3, 4))
17 7.25 25
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Review Question Part A
def p(t): return 100 * math.exp(0.1 * t) print(p(12))
332.01169227365483
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Part B
def pop(init_pop, r, t): return init_pop * math.exp(r * t) print(pop(1000, 0.15, 12))
6049.647464412945
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Section 05 - Printing
x = 3.0 print("x =", x, "and its square is", x ** 2)
x = 3.0 and its square is 9.0
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Section 06 - Loops and Lists
list_1 = [1, 3, 5.0] list_2 = [1, "one", 2, "two"] list_3 = [] print(list_1, list_2, list_3) list_4 = list(range(15)) list_5 = list(range(5, 15)) list_6 = list(range(4, 15, 3)) print(list_4, list_5, list_6)
[1, 3, 5.0] [1, 'one', 2, 'two'] [] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] [4, 7, 10, 13]
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Review Question 01
print(list(range(3, 16, 4))) dist = 0 for i in range(7): dist += 0.25 print(dist) for i in range(10): print(i, " ", i ** 2)
[3, 7, 11, 15] 0.25 0.5 0.75 1.0 1.25 1.5 1.75 0 0 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Review Question 02
dist = 1 for i in range(20): dist *= 2 print(dist)
2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Section 07 - Supplementary Python Programming Exercises Exercise 01
def sim(initial_pop, growth_rate_unit, sim_len, time_step): pops = [] times = [] pop = initial_pop time = 0 pops.append(pop) times.append(time) GROWTH_RATE = growth_rate_unit * time_step while (time <= sim_len): time += time_step pop += pop * GROWTH_RATE pops.app...
_____no_output_____
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Part A
INITAL_POP = 100 GROWTH_RATE_PER_HOUR = 0.1 SIM_LEN = 200 pops_0_0001, times_0_0001, actual_pop, relative_err = sim(INITAL_POP, GROWTH_RATE_PER_HOUR, SIM_LEN, 0.0001) pops_0_025, times_0_025, actual_pop, relative_err = sim(INITAL_POP, GROWTH_RATE_PER_HOUR, SIM_LEN, 0.025) pops_0_5, times_0_5, actual_pop, relative_err =...
The number of bacteria at the end of one week = 1317056747.0776892
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Part B
for i in range(len(pops_0_0001)): if pops_0_0001[i] < INITAL_POP_DOUBLE: continue index = i break if index != -1: print("The time taken for the population to double lies between", round(times_0_0001[index - 1], 4), "hrs and", round(times_0_0001[index], 4), "hrs")
The time taken for the population to double lies between 6.9315 hrs and 6.9316 hrs
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Part C
pyplot.title("Population growth simulation") pyplot.ylabel("Population") pyplot.xlabel("Time (hrs)") pyplot.plot(times_0_0001, pops_0_0001, label="0.0001hrs") pyplot.plot(times_0_025, pops_0_025, label="0.025hrs") pyplot.plot(times_0_5, pops_0_5, label="0.5hrs") pyplot.legend() pyplot.show()
_____no_output_____
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Exercise 02 Part A
INITAL_POP = 15000 INITAL_POP_DOUBLE = INITAL_POP * 2 GROWTH_RATE_PER_YEAR = 0.02 TIME_STEP = 0.25 SIM_LEN = 20 ACTUAL_POP_20_YRS = INITAL_POP * (GROWTH_RATE_PER_YEAR ** SIM_LEN) pops, times, actual_pop, relative_err = sim(INITAL_POP, GROWTH_RATE_PER_YEAR, SIM_LEN, TIME_STEP) print("Actual population after", SIM_LEN, ...
Actual population after 20 yrs is 22289.210939675322
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Part B
pyplot.title("Animal population growth simulation") pyplot.ylabel("Population") pyplot.xlabel("Time (yrs)") pyplot.plot(times, pops) pyplot.show()
_____no_output_____
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Part C
TIME_PAD = 10 POP_PAD = 20 print("Time (yrs)".ljust(TIME_PAD), "Population".ljust(POP_PAD), "Growth") print("0".ljust(TIME_PAD), str(INITAL_POP).ljust(POP_PAD), "INTERVAL") for i in range(1, len(pops)): GROWTH = str(100 * round((pops[i] - pops[i - 1]) / pops[i - 1], 8)) + "%" print(str(times[i]).ljust(TIME_PAD...
Time (yrs) Population Growth 0 15000 INTERVAL 0.25 15075.0 0.5% 0.5 15150.375 0.5% 0.75 15226.126875 0.5% 1.0 15302.257509375 0.5% 1.25 15378.768796921875 0.5% 1.5 15455.662640906485 0.5% 1.75 15532.9...
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Part D
INDEX = int(1 / TIME_STEP) pop = pops[INDEX] print("Population at end of 1 year:", pop, "growth of", pop - INITAL_POP, "(" + str(100 * round((pop - INITAL_POP) / INITAL_POP, 8)) + "%)") pop = pops[2 * INDEX] print("Population at end of 2 years:", pop, "growth of", pop - INITAL_POP, "(" + str(100 * round((pop - INITAL_P...
Population at end of 1 year: 15302.257509375 growth of 302.25750937500015 (2.01505%) Population at end of 2 years: 15610.605658881574 growth of 610.6056588815736 (4.070704%) Population at end of 3 years: 15925.167177967494 growth of 925.1671779674944 (6.167781%)
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Exercise 03 Part A
INITIAL_SAMPLE = 20 GROWTH_RATE = -0.000120968 SIM_LEN = 25000 def carbon_date(sample, proportion, sim_len, time_step): carbons = [] times = [] carbon = sample time = 0 carbons.append(carbon) times.append(time) while (time <= sim_len): time += time_step carbon = 20 * math.e...
_____no_output_____
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Part B
print("Estimation of carbon-14 remaining after 25,000yrs =", str(carbons[25000 * 4]) + "g")
Estimation of carbon-14 remaining after 25,000yrs = 0.9719336613934643g
MIT
Lab 01.ipynb
shipstone98/AdvCompLabs
Visualize real dataGet to know the real data
import pandas as pd import os import numpy as np import matplotlib.pyplot as plt import seaborn as sns savefolder = 'figures_real_data' folder = 'data' df = pd.read_excel(os.path.join(folder, '20211128 - Full DART Data (Model & Test).xlsx'), header=2) df.head() import pylab labeled_df = df[df['Sample Types'] == 'Model...
_____no_output_____
MIT
vizualize_real_data.ipynb
MichaelHopwood/MLMassSpectrom
It appears there are more than 3 measurement iterations? Why?
Xcols = [f'Col{i}' for i in range(len(recol))] df.columns = list(df.columns[:4]) + Xcols df.head(n=10) df[df.columns[4:]].iloc[0:3]
_____no_output_____
MIT
vizualize_real_data.ipynb
MichaelHopwood/MLMassSpectrom
Data formatting
def build_data_structure(df, labels, column_name_mass_locations): """ Convert dataframe which has columns of the mass locations and values of the intensities to array format where the sample is a list of peaks and the samples are grouped by the number of peaks. Input: df: dataframe with columns of ...
_____no_output_____
MIT
vizualize_real_data.ipynb
MichaelHopwood/MLMassSpectrom
Investigate test-train partition
df['Sample Types'].value_counts() df['Class'].value_counts() df[df['Sample Types'] == 'Model']['Class'].value_counts() df[df['Sample Types'] == 'Test']['Class'].value_counts()
_____no_output_____
MIT
vizualize_real_data.ipynb
MichaelHopwood/MLMassSpectrom
Seeing no labels in the Test split, we must split the train for a supervised evaluation
labeled_df = df[df['Sample Types'] == 'Model'] X = build_data_structure(df[df.columns[4:]]) from sklearn import model_selection from sklearn import preprocessing lb = preprocessing.LabelBinarizer() lb.fit(labeled_df['Class']) train_labeled_df, test_labeled_df = model_selection.train_test_split(labeled_df, train_size...
_____no_output_____
MIT
vizualize_real_data.ipynb
MichaelHopwood/MLMassSpectrom
Read the CSV and Perform Basic Data Cleaning
df = pd.read_csv("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_____
ADSL
svm.ipynb
eaganjm1102/Machine-learning-challenge
Create a Train Test SplitUse `koi_disposition` for the y values
from sklearn.model_selection import train_test_split y = df["koi_disposition"] X = df.drop(columns=["koi_disposition"]) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1, stratify=y)
_____no_output_____
ADSL
svm.ipynb
eaganjm1102/Machine-learning-challenge
Pre-processingScale the data using the MinMaxScaler
from sklearn.preprocessing import MinMaxScaler X_scaler = MinMaxScaler().fit(X_train) X_train_scaled = X_scaler.transform(X_train) X_test_scaled = X_scaler.transform(X_test)
_____no_output_____
ADSL
svm.ipynb
eaganjm1102/Machine-learning-challenge
Train the Model
# Support vector machine linear classifier from sklearn.svm import SVC model2 = SVC(kernel='linear') model2.fit(X_train_scaled, y_train) print(f"Training Data Score: {model2.score(X_train_scaled, y_train)}") print(f"Testing Data Score: {model2.score(X_test_scaled, y_test)}")
_____no_output_____
ADSL
svm.ipynb
eaganjm1102/Machine-learning-challenge
Hyperparameter TuningUse `GridSearchCV` to tune model's parameters
from sklearn.model_selection import GridSearchCV param_grid = {'C': [1, 5, 10], 'gamma': [0.0001, 0.001, 0.01]} grid = GridSearchCV(model2, param_grid, verbose=3) grid.fit(X_train_scaled, y_train) print(grid.best_params_) print(grid.best_score_)
_____no_output_____
ADSL
svm.ipynb
eaganjm1102/Machine-learning-challenge
Save the Model
# save the fitted model to file import joblib filename = 'svm.sav' joblib.dump(grid, filename)
_____no_output_____
ADSL
svm.ipynb
eaganjm1102/Machine-learning-challenge
Pylabel End to End Example Coco JSON to VOC XMLUse this notebook to try out importing, analyzing, and exporting datasets of image annotations.
!pip install -i https://test.pypi.org/simple/ pylabel==0.1.1 from pylabel import importer
_____no_output_____
MIT
coco2yolov5.ipynb
pylabelalpha/pylabel
Import coco annotations First we will import annotations from the coco dataset, which are in coco json format.
import os import zipfile #Download sample coco dataset os.makedirs("data", exist_ok=True) !wget "https://github.com/pylabelalpha/notebook/blob/main/BCCD_coco.zip?raw=true" -O data/BCCD_coco.zip with zipfile.ZipFile("data/BCCD_coco.zip", 'r') as zip_ref: zip_ref.extractall("data") #Specify path to the coco.json f...
--2021-10-18 20:42:09-- https://github.com/pylabelalpha/notebook/blob/main/BCCD_coco.zip?raw=true Resolving github.com (github.com)... 192.30.255.112 Connecting to github.com (github.com)|192.30.255.112|:443... connected. HTTP request sent, awaiting response... 302 Found Location: https://github.com/pylabelalpha/noteb...
MIT
coco2yolov5.ipynb
pylabelalpha/pylabel
Analyze annotationsPylabel can calculate basic summary statisticts about the dataset such as the number of files and the classes. The dataset is stored as a pandas frame so the developer can do additional exploratory analysis on the dataset.
print(f"Number of images: {dataset.analyze.num_images}") print(f"Number of classes: {dataset.analyze.num_classes}") print(f"Classes:{dataset.analyze.classes}") print(f"Class counts:\n{dataset.analyze.class_counts}") print(f"Path to annotations:\n{dataset.path_to_annotations}")
Number of images: 364 Number of classes: 3 Classes:['RBC' 'WBC' 'Platelets'] Class counts: RBC 4155 WBC 372 Platelets 361 Name: cat_name, dtype: int64 Path to annotations: data
MIT
coco2yolov5.ipynb
pylabelalpha/pylabel
Visualize Annotations You can render the bounding boxes for your image to inspect them and confirm that they imported correctly.
from IPython.display import Image, display display(dataset.visualize.ShowBoundingBoxes(dataset, 100)) display(dataset.visualize.ShowBoundingBoxes(dataset, "BloodImage_00315.jpg"))
data/BloodImage_00407.jpg
MIT
coco2yolov5.ipynb
pylabelalpha/pylabel
Export to Yolo v5The PyLabel exporter will export all of the annotations in the dataframe to the desired target format.Yolo creates one text file for each image in the dataset.
# Inspect one of the files dataset.path_to_annotations = "data/yolo" dataset.export.ExportToYoloV5(dataset)
data/yolo
MIT
coco2yolov5.ipynb
pylabelalpha/pylabel
TCLab Function Help![connections.png](attachment:connections.png) Connect/Disconnect```lab = tclab.TCLab()``` Connect and create new lab object, ```lab.close()``` disconnects lab. LED```lab.LED()``` Percentage of output light for __Hot__ Light. Heaters```lab.Q1()``` and ```lab.Q2()``` Percentage of power to heaters. T...
# install tclab try: import tclab except: # Needed to communicate through usb port !pip install --user pyserial # The --user is put in for accounts without admin privileges !pip install --user tclab # restart kernel if this doesn't import import tclab
_____no_output_____
MIT
TCLab Help.ipynb
monocilindro/data_science
Update Temperature Control LabUpdates package to latest version.
!pip install tclab --upgrade --user
_____no_output_____
MIT
TCLab Help.ipynb
monocilindro/data_science
Connection Check![usb.png](attachment:usb.png)The following code connects, reads temperatures 1 and 2, sets heaters 1 and 2, turns on the LED to 45%, and then disconnects from the TCLab. If an error is shown, try unplugging your lab and/or restarting Jupyter's kernel from the Jupyter notebook menu.
import tclab lab = tclab.TCLab() print(lab.T1,lab.T2) lab.Q1(50); lab.Q2(40) lab.LED(45) lab.close()
_____no_output_____
MIT
TCLab Help.ipynb
monocilindro/data_science
![expert.png](attachment:expert.png)Another way to connect to the TCLab is the `with` statement. The advantage of the `with` statement is that the connection automatically closes if there is a fatal error (bug) in the code and the program never reaches the `lab.close()` statement. This prevents a kernel restart to rese...
import tclab import time with tclab.TCLab() as lab: print(lab.T1,lab.T2) lab.Q1(50); lab.Q2(40) lab.LED(45)
_____no_output_____
MIT
TCLab Help.ipynb
monocilindro/data_science
Face GenerationIn this project, you'll use generative adversarial networks to generate new images of faces. Get the DataYou'll be using two datasets in this project:- MNIST- CelebASince the celebA dataset is complex and you're doing GANs in a project for the first time, we want you to test your neural network on MNIST...
data_dir = './data' # FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe" data_dir = '/input' """ DON'T MODIFY ANYTHING IN THIS CELL """ import helper helper.download_extract('mnist', data_dir) helper.download_extract('celeba', data_dir)
Downloading mnist: 9.92MB [00:02, 4.02MB/s] Extracting mnist: 100%|██████████| 60.0K/60.0K [00:24<00:00, 2.46KFile/s] Downloading celeba: 1.44GB [02:28, 9.73MB/s]
MIT
face_generation/.ipynb_checkpoints/dlnd_face_generation-floyd-checkpoint.ipynb
syednasar/deep-learning
Explore the Data MNISTAs you're aware, the [MNIST](http://yann.lecun.com/exdb/mnist/) dataset contains images of handwritten digits. You can view the first number of examples by changing `show_n_images`.
show_n_images = 25 """ DON'T MODIFY ANYTHING IN THIS CELL """ %matplotlib inline import os from glob import glob from matplotlib import pyplot mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'mnist/*.jpg'))[:show_n_images], 28, 28, 'L') pyplot.imshow(helper.images_square_grid(mnist_images, 'L'), cmap='gra...
_____no_output_____
MIT
face_generation/.ipynb_checkpoints/dlnd_face_generation-floyd-checkpoint.ipynb
syednasar/deep-learning
CelebAThe [CelebFaces Attributes Dataset (CelebA)](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html) dataset contains over 200,000 celebrity images with annotations. Since you're going to be generating faces, you won't need the annotations. You can view the first number of examples by changing `show_n_images`.
show_n_images = 25 """ DON'T MODIFY ANYTHING IN THIS CELL """ mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))[:show_n_images], 28, 28, 'RGB') pyplot.imshow(helper.images_square_grid(mnist_images, 'RGB'))
_____no_output_____
MIT
face_generation/.ipynb_checkpoints/dlnd_face_generation-floyd-checkpoint.ipynb
syednasar/deep-learning
Preprocess the DataSince the project's main focus is on building the GANs, we'll preprocess the data for you. The values of the MNIST and CelebA dataset will be in the range of -0.5 to 0.5 of 28x28 dimensional images. The CelebA images will be cropped to remove parts of the image that don't include a face, then resi...
""" DON'T MODIFY ANYTHING IN THIS CELL """ from distutils.version import LooseVersion import warnings import tensorflow as tf # Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__) print('TensorFlow V...
TensorFlow Version: 1.0.0
MIT
face_generation/.ipynb_checkpoints/dlnd_face_generation-floyd-checkpoint.ipynb
syednasar/deep-learning
InputImplement the `model_inputs` function to create TF Placeholders for the Neural Network. It should create the following placeholders:- Real input images placeholder with rank 4 using `image_width`, `image_height`, and `image_channels`.- Z input placeholder with rank 2 using `z_dim`.- Learning rate placeholder with...
import problem_unittests as tests def model_inputs(image_width, image_height, image_channels, z_dim): """ Create the model inputs :param image_width: The input image width :param image_height: The input image height :param image_channels: The number of image channels :param z_dim: The dimension...
Tests Passed
MIT
face_generation/.ipynb_checkpoints/dlnd_face_generation-floyd-checkpoint.ipynb
syednasar/deep-learning
DiscriminatorImplement `discriminator` to create a discriminator neural network that discriminates on `images`. This function should be able to reuse the variabes in the neural network. Use [`tf.variable_scope`](https://www.tensorflow.org/api_docs/python/tf/variable_scope) with a scope name of "discriminator" to all...
def discriminator(images, reuse=False): """ Create the discriminator network :param image: Tensor of input image(s) :param reuse: Boolean if the weights should be reused :return: Tuple of (tensor output of the discriminator, tensor logits of the discriminator) """ # TODO: Implement Function ...
Tests Passed
MIT
face_generation/.ipynb_checkpoints/dlnd_face_generation-floyd-checkpoint.ipynb
syednasar/deep-learning
GeneratorImplement `generator` to generate an image using `z`. This function should be able to reuse the variabes in the neural network. Use [`tf.variable_scope`](https://www.tensorflow.org/api_docs/python/tf/variable_scope) with a scope name of "generator" to allow the variables to be reused. The function should ret...
def generator(z, out_channel_dim, is_train=True): """ Create the generator network :param z: Input z :param out_channel_dim: The number of channels in the output image :param is_train: Boolean if generator is being used for training :return: The tensor output of the generator """ # TODO:...
Tests Passed
MIT
face_generation/.ipynb_checkpoints/dlnd_face_generation-floyd-checkpoint.ipynb
syednasar/deep-learning
LossImplement `model_loss` to build the GANs for training and calculate the loss. The function should return a tuple of (discriminator loss, generator loss). Use the following functions you implemented:- `discriminator(images, reuse=False)`- `generator(z, out_channel_dim, is_train=True)`
def model_loss(input_real, input_z, out_channel_dim): """ Get the loss for the discriminator and generator :param input_real: Images from the real dataset :param input_z: Z input :param out_channel_dim: The number of channels in the output image :return: A tuple of (discriminator loss, generator...
Tests Passed
MIT
face_generation/.ipynb_checkpoints/dlnd_face_generation-floyd-checkpoint.ipynb
syednasar/deep-learning
OptimizationImplement `model_opt` to create the optimization operations for the GANs. Use [`tf.trainable_variables`](https://www.tensorflow.org/api_docs/python/tf/trainable_variables) to get all the trainable variables. Filter the variables with names that are in the discriminator and generator scope names. The func...
def model_opt(d_loss, g_loss, learning_rate, beta1): """ Get optimization operations :param d_loss: Discriminator loss Tensor :param g_loss: Generator loss Tensor :param learning_rate: Learning Rate Placeholder :param beta1: The exponential decay rate for the 1st moment in the optimizer :ret...
Tests Passed
MIT
face_generation/.ipynb_checkpoints/dlnd_face_generation-floyd-checkpoint.ipynb
syednasar/deep-learning
Neural Network Training Show OutputUse this function to show the current output of the generator during training. It will help you determine how well the GANs is training.
""" DON'T MODIFY ANYTHING IN THIS CELL """ import numpy as np def show_generator_output(sess, n_images, input_z, out_channel_dim, image_mode): """ Show example output for the generator :param sess: TensorFlow session :param n_images: Number of Images to display :param input_z: Input Z Tensor :p...
_____no_output_____
MIT
face_generation/.ipynb_checkpoints/dlnd_face_generation-floyd-checkpoint.ipynb
syednasar/deep-learning
TrainImplement `train` to build and train the GANs. Use the following functions you implemented:- `model_inputs(image_width, image_height, image_channels, z_dim)`- `model_loss(input_real, input_z, out_channel_dim)`- `model_opt(d_loss, g_loss, learning_rate, beta1)`Use the `show_generator_output` to show `generator` o...
def train(epoch_count, batch_size, z_dim, learning_rate, beta1, get_batches, data_shape, data_image_mode): """ Train the GAN :param epoch_count: Number of epochs :param batch_size: Batch Size :param z_dim: Z dimension :param learning_rate: Learning Rate :param beta1: The exponential decay ra...
_____no_output_____
MIT
face_generation/.ipynb_checkpoints/dlnd_face_generation-floyd-checkpoint.ipynb
syednasar/deep-learning
MNISTTest your GANs architecture on MNIST. After 2 epochs, the GANs should be able to generate images that look like handwritten digits. Make sure the loss of the generator is lower than the loss of the discriminator or close to 0.
batch_size = 128 z_dim = 100 learning_rate = 0.0001 beta1 = 0.5 """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ epochs = 2 mnist_dataset = helper.Dataset('mnist', glob(os.path.join(data_dir, 'mnist/*.jpg'))) with tf.Graph().as_default(): train(epochs, batch_size, z_dim, learning_rate, beta1, m...
Epoch 1/2... Discriminator Loss: 0.9857... Generator Loss: 0.9119 Epoch 1/2... Discriminator Loss: 1.1420... Generator Loss: 0.9622 Epoch 1/2... Discriminator Loss: 1.4581... Generator Loss: 0.7679 Epoch 1/2... Discriminator Loss: 1.4356... Generator Loss: 0.7823 Epoch 1/2... Discriminator Loss: 1.2925... Generator Los...
MIT
face_generation/.ipynb_checkpoints/dlnd_face_generation-floyd-checkpoint.ipynb
syednasar/deep-learning
CelebARun your GANs on CelebA. It will take around 20 minutes on the average GPU to run one epoch. You can run the whole epoch or stop when it starts to generate realistic faces.
batch_size = 128 z_dim = 100 learning_rate = 0.0001 beta1 = 0.5 """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ epochs = 1 celeba_dataset = helper.Dataset('celeba', glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))) with tf.Graph().as_default(): train(epochs, batch_size, z_dim, learning_r...
_____no_output_____
MIT
face_generation/.ipynb_checkpoints/dlnd_face_generation-floyd-checkpoint.ipynb
syednasar/deep-learning
Modeling and Simulation in PythonChapter 21Copyright 2017 Allen DowneyLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)
# Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import functions from the modsim.py module from modsim import *
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
With air resistance Next we'll add air resistance using the [drag equation](https://en.wikipedia.org/wiki/Drag_equation) I'll start by getting the units we'll need from Pint.
m = UNITS.meter s = UNITS.second kg = UNITS.kilogram
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
Now I'll create a `Params` object to contain the quantities we need. Using a Params object is convenient for grouping the system parameters in a way that's easy to read (and double-check).
params = Params(height = 381 * m, v_init = 0 * m / s, g = 9.8 * m/s**2, mass = 2.5e-3 * kg, diameter = 19e-3 * m, rho = 1.2 * kg/m**3, v_term = 18 * m / s)
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
Now we can pass the `Params` object `make_system` which computes some additional parameters and defines `init`.`make_system` uses the given radius to compute `area` and the given `v_term` to compute the drag coefficient `C_d`.
def make_system(params): """Makes a System object for the given conditions. params: Params object returns: System object """ unpack(params) area = np.pi * (diameter/2)**2 C_d = 2 * mass * g / (rho * area * v_term**2) init = State(y=height, v=v_init) t_end = 30 * s ...
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
Let's make a `System`
system = make_system(params)
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
Here's the slope function, including acceleration due to gravity and drag.
def slope_func(state, t, system): """Compute derivatives of the state. state: position, velocity t: time system: System object returns: derivatives of y and v """ y, v = state unpack(system) f_drag = rho * v**2 * C_d * area / 2 a_drag = f_drag / mass dydt ...
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
As always, let's test the slope function with the initial conditions.
slope_func(system.init, 0, system)
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
We can use the same event function as last time.
def event_func(state, t, system): """Return the height of the penny above the sidewalk. """ y, v = state return y
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
And then run the simulation.
results, details = run_ode_solver(system, slope_func, events=event_func) details.message
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
Here are the results.
results
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
The final height is close to 0, as expected.Interestingly, the final velocity is not exactly terminal velocity, which suggests that there are some numerical errors.We can get the flight time from `results`.
t_sidewalk = get_last_label(results)
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
Here's the plot of position as a function of time.
def plot_position(results): plot(results.y) decorate(xlabel='Time (s)', ylabel='Position (m)') plot_position(results) savefig('figs/chap09-fig02.pdf')
Saving figure to file figs/chap09-fig02.pdf
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
And velocity as a function of time:
def plot_velocity(results): plot(results.v, color='C1', label='v') decorate(xlabel='Time (s)', ylabel='Velocity (m/s)') plot_velocity(results)
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
From an initial velocity of 0, the penny accelerates downward until it reaches terminal velocity; after that, velocity is constant. **Exercise:** Run the simulation with an initial velocity, downward, that exceeds the penny's terminal velocity. Hint: You can create a new `Params` object based on an existing one, like ...
# Solution params = Params(params, v_init = -30 * m / s) system = make_system(params) results, details = run_ode_solver(system, slope_func, events=event_func) details.message plot_position(results) # Solution plot_velocity(results)
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
**Exercise:** Suppose we drop a quarter from the Empire State Building and find that its flight time is 19.1 seconds. Use this measurement to estimate the terminal velocity.1. You can get the relevant dimensions of a quarter from https://en.wikipedia.org/wiki/Quarter_(United_States_coin).2. Create a `Params` object wi...
# Solution # Here's a `Params` object with the dimensions of a quarter, # the observed flight time and our initial guess for `v_term` params = Params(params, mass = 5.67e-3 * kg, diameter = 24.26e-3 * m, v_term = 18 * m / s, flight_time = 19.1 * s) # Sol...
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
Bungee jumping Suppose you want to set the world record for the highest "bungee dunk", [as shown in this video](https://www.youtube.com/watch?v=UBf7WC19lpw). Since the record is 70 m, let's design a jump for 80 m.We'll make the following modeling assumptions:1. Initially the bungee cord hangs from a crane with the at...
m = UNITS.meter s = UNITS.second kg = UNITS.kilogram N = UNITS.newton params = Params(y_attach = 80 * m, v_init = 0 * m / s, g = 9.8 * m/s**2, mass = 75 * kg, area = 1 * m**2, rho = 1.2 * kg/m**3, v_term = 60 * m / s, ...
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
Now here's a version of `make_system` that takes a `Params` object as a parameter.`make_system` uses the given value of `v_term` to compute the drag coefficient `C_d`.
def make_system(params): """Makes a System object for the given params. params: Params object returns: System object """ unpack(params) C_d = 2 * mass * g / (rho * area * v_term**2) init = State(y=y_attach, v=v_init) t_end = 30 * s return System(params, C_d=C_d, ...
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
Let's make a `System`
system = make_system(params) system
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
`spring_force` computes the force of the cord on the jumper:
def spring_force(y, system): """Computes the force of the bungee cord on the jumper: y: height of the jumper Uses these variables from system| y_attach: height of the attachment point L: resting length of the cord k: spring constant of the cord returns: force in N """ ...
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
The spring force is 0 until the cord is fully extended. When it is extended 1 m, the spring force is 40 N.
spring_force(80*m, system) spring_force(55*m, system) spring_force(54*m, system)
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
`drag_force` computes drag as a function of velocity:
def drag_force(v, system): """Computes drag force in the opposite direction of `v`. v: velocity returns: drag force """ unpack(system) f_drag = -np.sign(v) * rho * v**2 * C_d * area / 2 return f_drag
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
Now here's the slope function:
def slope_func(state, t, system): """Compute derivatives of the state. state: position, velocity t: time system: System object containing g, rho, C_d, area, and mass returns: derivatives of y and v """ y, v = state unpack(system) a_drag = drag_force(v, syst...
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
As always, let's test the slope function with the initial params.
slope_func(system.init, 0, system)
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
And then run the simulation.
ts = linspace(0, system.t_end, 301) results, details = run_ode_solver(system, slope_func, t_eval=ts) details
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
Here's the plot of position as a function of time.
plot_position(results)
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
After reaching the lowest point, the jumper springs back almost to almost 70 m, and oscillates several times. That looks like more osciallation that we expect from an actual jump, which suggests that there some dissipation of energy in the real world that is not captured in our model. To improve the model, that might...
min(results.y)
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
At the lowest point, the jumper is still too high, so we'll need to increase `L` or decrease `k`. Here's velocity as a function of time:
plot_velocity(results) subplot(1, 2, 1) plot_position(results) subplot(1, 2, 2) plot_velocity(results) savefig('figs/chap09-fig03.pdf')
Saving figure to file figs/chap09-fig03.pdf
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
Although we compute acceleration inside the slope function, we don't get acceleration as a result from `run_ode_solver`.We can approximate it by computing the numerical derivative of `ys`:
a = gradient(results.v) plot(a) decorate(xlabel='Time (s)', ylabel='Acceleration (m/$s^2$)')
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
And we can compute the maximum acceleration the jumper experiences:
max_acceleration = max(a) * m/s**2
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
Relative to the acceleration of gravity, the jumper "pulls" about "1.7 g's".
max_acceleration / g
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
Solving for lengthAssuming that `k` is fixed, let's find the length `L` that makes the minimum altitude of the jumper exactly 0.Here's the error function:
def error_func(L, params): """Minimum height as a function of length. length: length in m params: Params object returns: height in m """ params = Params(params, L=L) system = make_system(params) ts = linspace(0, system.t_end, 201) results, details = run_ode_solver(system, ...
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
Let's test it with the same initial guess, `L = 100 m`:
guess = 150 * m error_func(guess, params)
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy
And find the value of `L` we need for the world record jump:
solution = fsolve(error_func, guess, params)
_____no_output_____
MIT
code/soln/chap21soln.ipynb
rsmxingu/ModSimPy