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
In the previous notebook we used `model = KNeighborsClassifier()`. Allscikit-learn models can be created without arguments, which means that youdon't need to understand the details of the model to use it in scikit-learn.One of the `KNeighborsClassifier` parameters is `n_neighbors`. It controlsthe number of neighbors we...
# Write your code here.
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_ex_00.ipynb
khanfarhan10/scikit-learn-mooc
Fit this model on the data and target loaded above
# Write your code here.
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_ex_00.ipynb
khanfarhan10/scikit-learn-mooc
Use your model to make predictions on the first 10 data points inside thedata. Do they match the actual target values?
# Write your code here.
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_ex_00.ipynb
khanfarhan10/scikit-learn-mooc
Compute the accuracy on the training data.
# Write your code here.
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_ex_00.ipynb
khanfarhan10/scikit-learn-mooc
Now load the test data from `"../datasets/adult-census-numeric-test.csv"` andcompute the accuracy on the test data.
# Write your code here.
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_ex_00.ipynb
khanfarhan10/scikit-learn-mooc
The next step in the gap analysis is to calculate the Turbine Ideal Energy (TIE) for the wind farm based on SCADA data
%load_ext autoreload %autoreload 2
_____no_output_____
BSD-3-Clause
examples/03_turbine_ideal_energy.ipynb
nbodini/OpenOA
This notebook provides an overview and walk-through of the turbine ideal energy (TIE) method in OpenOA. The TIE metric is defined as the amount of electricity generated by all turbines at a wind farm operating under normal conditions (i.e., not subject to downtime or significant underperformance, but subject to wake lo...
# Import required packages import matplotlib.pyplot as plt import numpy as np import pandas as pd from project_ENGIE import Project_Engie from operational_analysis.methods import turbine_long_term_gross_energy
_____no_output_____
BSD-3-Clause
examples/03_turbine_ideal_energy.ipynb
nbodini/OpenOA
In the call below, make sure the appropriate path to the CSV input files is specfied. In this example, the CSV files are located directly in the 'examples/data/la_haute_borne' folder
# Load plant object project = Project_Engie('./data/la_haute_borne/') # Load and prepare the wind farm data project.prepare() # Let's take a look at the columns in the SCADA data frame project._scada.df.columns
_____no_output_____
BSD-3-Clause
examples/03_turbine_ideal_energy.ipynb
nbodini/OpenOA
TIE calculation without uncertainty quantificationNext we create a TIE object which will contain the analysis to be performed. The method has the ability to calculate uncertainty in the TIE metric through a Monte Carlo sampling of filtering thresholds, power data, and reanalysis product choices. For now, we turn this ...
ta = turbine_long_term_gross_energy.TurbineLongTermGrossEnergy(project)
INFO:operational_analysis.methods.turbine_long_term_gross_energy:Initializing TurbineLongTermGrossEnergy Object INFO:operational_analysis.methods.turbine_long_term_gross_energy:Note: uncertainty quantification will NOT be performed in the calculation INFO:operational_analysis.methods.turbine_long_term_gross_energy:Proc...
BSD-3-Clause
examples/03_turbine_ideal_energy.ipynb
nbodini/OpenOA
All of the steps in the TI calculation process are pulled under a single run() function. These steps include:1. Processing reanalysis data to daily averages.2. Filtering the SCADA data3. Fitting the daily reanalysis data to daily SCADA data using a Generalized Additive Model (GAM)4. Apply GAM results to calculate long-...
# Specify filter threshold values to be used wind_bin_thresh = 2.0 # Exclude data outside 2 m/s of the median for each power bin max_power_filter = 0.90 # Don't apply bin filter above 0.9 of turbine capacity
_____no_output_____
BSD-3-Clause
examples/03_turbine_ideal_energy.ipynb
nbodini/OpenOA
We also must decide how to deal with missing data when computing daily sums of energy production from each turbine. Here we set the threshold at 0.9 (i.e., if greater than 90% of SCADA data are available for a given day, scale up the daily energy by the fraction of data missing. If less than 90% data recovery, exclude ...
# Set the correction threshold to 90% correction_threshold = 0.90
_____no_output_____
BSD-3-Clause
examples/03_turbine_ideal_energy.ipynb
nbodini/OpenOA
Now we'll call the run() method to calculate TIE, choosing two reanalysis products to be used in the TIE calculation process.
# We can choose to save key plots to a file by setting enable_plotting = True and # specifying a directory to save the images. For now we turn off this feature. ta.run(reanal_subset = ['era5', 'merra2'], enable_plotting = False, plot_dir = None, wind_bin_thresh = wind_bin_thresh, max_power_filter = max_power_f...
0%| | 0/2 [00:00<?, ?it/s]INFO:operational_analysis.methods.turbine_long_term_gross_energy:Filtering turbine data INFO:operational_analysis.methods.turbine_long_term_gross_energy:Processing reanalysis data to daily averages INFO:operational_analysis.methods.turbine_long_term_gross_energy:Processing scada dat...
BSD-3-Clause
examples/03_turbine_ideal_energy.ipynb
nbodini/OpenOA
Now that we've finished the TIE calculation, let's examine results
ta._plant_gross # What is the long-term annual TIE for whole plant print('Long-term turbine ideal energy is %s GWh/year' %np.round(np.mean(ta._plant_gross/1e6),1))
Long-term turbine ideal energy is 13.7 GWh/year
BSD-3-Clause
examples/03_turbine_ideal_energy.ipynb
nbodini/OpenOA
The long-term TIE value of 13.7 GWh/year is based on the mean TIE resulting from the two reanalysis products considered. Next, we can examine how well the filtering worked by examining the power curves for each turbine using the plot_filtered_power_curves() function.
# Currently saving figures in examples folder. The folder where figures are saved can be changed if desired. ta.plot_filtered_power_curves(save_folder = "./", output_to_terminal = True)
_____no_output_____
BSD-3-Clause
examples/03_turbine_ideal_energy.ipynb
nbodini/OpenOA
Overall these are very clean power curves, and the filtering algorithms seem to have done a good job of catching the most egregious outliers. Now let's look at the daily data and how well the power curve fit worked
# Currently saving figures in examples folder. The folder where figures are saved can be changed if desired. ta.plot_daily_fitting_result(save_folder = "./", output_to_terminal = True)
_____no_output_____
BSD-3-Clause
examples/03_turbine_ideal_energy.ipynb
nbodini/OpenOA
Overall the fit looks good. The modeled data sometimes estimate higher energy at low wind speeds compared to the observed, but keep in mind the model fits to long term wind speed, wind direction, and air density, whereas we are only showing the relationship to wind speed here.Note that 'imputed' means daily power data ...
ta = turbine_long_term_gross_energy.TurbineLongTermGrossEnergy(project, UQ = True, # enable uncertainty quantification num_sim = 100 # number of Monte Carlo simulations to perform ...
INFO:operational_analysis.methods.turbine_long_term_gross_energy:Initializing TurbineLongTermGrossEnergy Object INFO:operational_analysis.methods.turbine_long_term_gross_energy:Note: uncertainty quantification will be performed in the calculation INFO:operational_analysis.methods.turbine_long_term_gross_energy:Processi...
BSD-3-Clause
examples/03_turbine_ideal_energy.ipynb
nbodini/OpenOA
With uncertainty quantification enabled (UQ = True), we can specify the assumed uncertainty of the SCADA power data (0.5% by default) and ranges of two key filtering thresholds from which the Monte Carlo simulations will sample. Specifically, these thresholds are applied to the bin_filter() function in the toolkits.fil...
uncertainty_scada=0.005 # Assumed uncertainty of SCADA power data (0.5%) # Range of filter threshold values to be used by Monte Carlo simulations # Data outside of a range of wind speeds from 1 to 3 m/s of the median for each power bin are considered wind_bin_thresh=(1, 3) # The bin filter will be applied up to fra...
_____no_output_____
BSD-3-Clause
examples/03_turbine_ideal_energy.ipynb
nbodini/OpenOA
We will consider a range of availability thresholds for dealing with missing data when computing daily sums of energy production from each turbine (i.e., if greater than the given threshold of SCADA data are available for a given day, scale up the daily energy by the fraction of data missing. If less than the given thr...
correction_threshold=(0.85, 0.95)
_____no_output_____
BSD-3-Clause
examples/03_turbine_ideal_energy.ipynb
nbodini/OpenOA
Now we'll call the run() method to calculate TIE with uncertainty quantification, again choosing two reanalysis products to be used in the TIE calculation process.Note that without uncertainty quantification (UQ = False), a separate TIE value is calculated for each reanalysis product specified. However, when UQ = True,...
# We can choose to save key plots to a file by setting enable_plotting = True and # specifying a directory to save the images. For now we turn off this feature. ta.run(reanal_subset = ['era5', 'merra2'], enable_plotting = False, plot_dir = None, uncertainty_scada = uncertainty_scada, wind_bin_thresh = wind_bin...
_____no_output_____
BSD-3-Clause
examples/03_turbine_ideal_energy.ipynb
nbodini/OpenOA
Now that we've finished the Monte Carlo TIE calculation simulations, let's examine results
np.mean(ta._plant_gross) np.std(ta._plant_gross) # Mean long-term annual TIE for whole plant print('Mean long-term turbine ideal energy is %s GWh/year' %np.round(np.mean(ta._plant_gross/1e6),1)) # Uncertainty in long-term annual TIE for whole plant print('Uncertainty in long-term turbine ideal energy is %s GWh/year, o...
Mean long-term turbine ideal energy is 13.7 GWh/year Uncertainty in long-term turbine ideal energy is 0.1 GWh/year, or 0.8 percent
BSD-3-Clause
examples/03_turbine_ideal_energy.ipynb
nbodini/OpenOA
Code Review 1 Purpose: To introduce the group to looking at code analyticallyCreated By: Hawley HelmbrechtCreation Date: 10-12-21 Introduction to Analyzing Code All snipets within this section are taken from the Hitchhiker's Guide to Python (https://docs.python-guide.org/writing/style/) Example 1: Explicit Code
def make_complex(*args): x, y = args return dict(**locals()) def make_complex(x, y): return {'x': x, 'y': y}
_____no_output_____
MIT
code_reviews/Code_review_1.ipynb
Nance-Lab/textile
Example 2: One Statement per Line
print('one'); print('two') if x == 1: print('one') if <complex comparison> and <other complex comparison>: # do something print('one') print('two') if x == 1: print('one') cond1 = <complex comparison> cond2 = <other complex comparison> if cond1 and cond2: # do something
_____no_output_____
MIT
code_reviews/Code_review_1.ipynb
Nance-Lab/textile
Intro to Pep 8 Example 1: Limit all lines to a maximum of 79 characters.
#Wrong: income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest) #Correct: income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest)
_____no_output_____
MIT
code_reviews/Code_review_1.ipynb
Nance-Lab/textile
Example 2: Line breaks around binary operators
# Wrong: # operators sit far away from their operands income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest) # Correct: # easy to match operators with operands income = (gross_wages + taxable_interest ...
_____no_output_____
MIT
code_reviews/Code_review_1.ipynb
Nance-Lab/textile
Example 3: Import formatting
# Correct: import os import sys # Wrong: import sys, os
_____no_output_____
MIT
code_reviews/Code_review_1.ipynb
Nance-Lab/textile
Let's look at some code! Sci-kit images Otsu Threshold code! (https://github.com/scikit-image/scikit-image/blob/main/skimage/filters/thresholding.py)
def threshold_otsu(image=None, nbins=256, *, hist=None): """Return threshold value based on Otsu's method. Either image or hist must be provided. If hist is provided, the actual histogram of the image is ignored. Parameters ---------- image : (N, M[, ..., P]) ndarray, optional Grayscale ...
_____no_output_____
MIT
code_reviews/Code_review_1.ipynb
Nance-Lab/textile
What do you observe about the code that makes it pythonic?
Do the pythonic conventions make it easier to understand?
_____no_output_____
MIT
code_reviews/Code_review_1.ipynb
Nance-Lab/textile
______ Python Crash Course Exercises - Solutions ExercisesAnswer the questions or complete the tasks outlined in bold below, use the specific method described if applicable. ** What is 7 to the power of 4?**
7**4
_____no_output_____
MIT
03-Python Crash Course Exercises - Solutions.ipynb
avinash-nahar/Learning
** Split this string:** s = "Hi there Sam!" **into a list. **
s = 'Hi there Sam!' s.split()
_____no_output_____
MIT
03-Python Crash Course Exercises - Solutions.ipynb
avinash-nahar/Learning
** Given the variables:** planet = "Earth" diameter = 12742** Use .format() to print the following string: ** The diameter of Earth is 12742 kilometers.
planet = "Earth" diameter = 12742 print("The diameter of {} is {} kilometers.".format(planet,diameter))
The diameter of Earth is 12742 kilometers.
MIT
03-Python Crash Course Exercises - Solutions.ipynb
avinash-nahar/Learning
** Given this nested list, use indexing to grab the word "hello" **
lst = [1,2,[3,4],[5,[100,200,['hello']],23,11],1,7] lst[-3][1][2][0]
_____no_output_____
MIT
03-Python Crash Course Exercises - Solutions.ipynb
avinash-nahar/Learning
** Given this nest dictionary grab the word "hello". Be prepared, this will be annoying/tricky **
d = {'k1':[1,2,3,{'tricky':['oh','man','inception',{'target':[1,2,3,'hello']}]}]} d['k1'][3]['tricky'][3]['target'][3]
_____no_output_____
MIT
03-Python Crash Course Exercises - Solutions.ipynb
avinash-nahar/Learning
** What is the main difference between a tuple and a list? **
# Tuple is immutable
_____no_output_____
MIT
03-Python Crash Course Exercises - Solutions.ipynb
avinash-nahar/Learning
** Create a function that grabs the email website domain from a string in the form: ** user@domain.com **So for example, passing "user@domain.com" would return: domain.com**
def domainGet(email): return email.split('@')[-1] domainGet('user@domain.com')
_____no_output_____
MIT
03-Python Crash Course Exercises - Solutions.ipynb
avinash-nahar/Learning
** Create a basic function that returns True if the word 'dog' is contained in the input string. Don't worry about edge cases like a punctuation being attached to the word dog, but do account for capitalization. **
def findDog(st): return 'dog' in st.lower().split() findDog('Is there a dog here?')
_____no_output_____
MIT
03-Python Crash Course Exercises - Solutions.ipynb
avinash-nahar/Learning
** Create a function that counts the number of times the word "dog" occurs in a string. Again ignore edge cases. **
def countDog(st): count = 0 for word in st.lower().split(): if word == 'dog': count += 1 return count countDog('This dog runs faster than the other dog dude!')
_____no_output_____
MIT
03-Python Crash Course Exercises - Solutions.ipynb
avinash-nahar/Learning
** Use lambda expressions and the filter() function to filter out words from a list that don't start with the letter 's'. For example:** seq = ['soup','dog','salad','cat','great']**should be filtered down to:** ['soup','salad']
seq = ['soup','dog','salad','cat','great'] list(filter(lambda word: word[0]=='s',seq))
_____no_output_____
MIT
03-Python Crash Course Exercises - Solutions.ipynb
avinash-nahar/Learning
Final Problem**You are driving a little too fast, and a police officer stops you. Write a function to return one of 3 possible results: "No ticket", "Small ticket", or "Big Ticket". If your speed is 60 or less, the result is "No Ticket". If speed is between 61 and 80 inclusive, the result is "Small Ticket". If sp...
def caught_speeding(speed, is_birthday): if is_birthday: speeding = speed - 5 else: speeding = speed if speeding > 80: return 'Big Ticket' elif speeding > 60: return 'Small Ticket' else: return 'No Ticket' caught_speeding(81,True) caught_speeding(81,...
_____no_output_____
MIT
03-Python Crash Course Exercises - Solutions.ipynb
avinash-nahar/Learning
TV Script GenerationIn this project, you'll generate your own [Seinfeld](https://en.wikipedia.org/wiki/Seinfeld) TV scripts using RNNs. You'll be using part of the [Seinfeld dataset](https://www.kaggle.com/thec03u5/seinfeld-chroniclesscripts.csv) of scripts from 9 seasons. The Neural Network you'll build will genera...
""" DON'T MODIFY ANYTHING IN THIS CELL """ # load in data import helper data_dir = './data/Seinfeld_Scripts.txt' text = helper.load_data(data_dir)
_____no_output_____
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
Explore the DataPlay around with `view_line_range` to view different parts of the data. This will give you a sense of the data you'll be working with. You can see, for example, that it is all lowercase text, and each new line of dialogue is separated by a newline character `\n`.
view_line_range = (2, 12) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ import numpy as np print('Dataset Stats') print('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()}))) lines = text.split('\n') print('Number of lines: {}'.format(len(lines))) word_count...
Dataset Stats Roughly the number of unique words: 46367 Number of lines: 109233 Average number of words in each line: 5.544240293684143 The lines 2 to 12: jerry: (pointing at georges shirt) see, to me, that button is in the worst possible spot. the second button literally makes or breaks the shirt, look at it. its too...
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
--- Implement Pre-processing FunctionsThe first thing to do to any dataset is pre-processing. Implement the following pre-processing functions below:- Lookup Table- Tokenize Punctuation Lookup TableTo create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:- Di...
import problem_unittests as tests from collections import Counter def create_lookup_tables(text): """ Create lookup tables for vocabulary :param text: The text of tv scripts split into words :return: A tuple of dicts (vocab_to_int, int_to_vocab) """ # TODO: Implement Function #reference so...
Tests Passed
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
Tokenize PunctuationWe'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks can create multiple ids for the same word. For example, "bye" and "bye!" would generate two different word ids.Implement the function `token_lookup` to return a dict...
def token_lookup(): """ Generate a dict to turn punctuation into a token. :return: Tokenized dictionary where the key is the punctuation and the value is the token """ # TODO: Implement Function retval = { ".": "||Period||", ",": "||Comma||", "\"": "||QuotationMark||", ";": "...
Tests Passed
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
Pre-process all the data and save itRunning the code cell below will pre-process all the data and save it to file. You're encouraged to lok at the code for `preprocess_and_save_data` in the `helpers.py` file to see what it's doing in detail, but you do not need to change this code.
""" DON'T MODIFY ANYTHING IN THIS CELL """ # pre-process training data helper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables)
_____no_output_____
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
Check PointThis is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.
""" DON'T MODIFY ANYTHING IN THIS CELL """ import helper import problem_unittests as tests int_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess() len(int_text)
_____no_output_____
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
Build the Neural NetworkIn this section, you'll build the components necessary to build an RNN by implementing the RNN Module and forward and backpropagation functions. Check Access to GPU
""" DON'T MODIFY ANYTHING IN THIS CELL """ import torch # Check for a GPU train_on_gpu = torch.cuda.is_available() if not train_on_gpu: print('No GPU found. Please use a GPU to train your neural network.')
_____no_output_____
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
InputLet's start with the preprocessed input data. We'll use [TensorDataset](http://pytorch.org/docs/master/data.htmltorch.utils.data.TensorDataset) to provide a known format to our dataset; in combination with [DataLoader](http://pytorch.org/docs/master/data.htmltorch.utils.data.DataLoader), it will handle batching, ...
from torch.utils.data import TensorDataset, DataLoader nb_samples = 6 features = torch.randn(nb_samples, 10) labels = torch.empty(nb_samples, dtype=torch.long).random_(10) dataset = TensorDataset(features, labels) loader = DataLoader( dataset, batch_size=2 ) for batch_idx, (x, y) in enumerate(loader): pri...
_____no_output_____
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
Test your dataloader You'll have to modify this code to test a batching function, but it should look fairly similar.Below, we're generating some test text data and defining a dataloader using the function you defined, above. Then, we are getting some sample batch of inputs `sample_x` and targets `sample_y` from our da...
# test dataloader test_text = range(50) t_loader = batch_data(test_text, sequence_length=6, batch_size=10) data_iter = iter(t_loader) sample_x, sample_y = data_iter.next() print(sample_x.shape) print(sample_x) print(sample_y.shape) print(sample_y)
torch.Size([10, 6]) tensor([[ 13, 14, 15, 16, 17, 18], [ 20, 21, 22, 23, 24, 25], [ 30, 31, 32, 33, 34, 35], [ 2, 3, 4, 5, 6, 7], [ 16, 17, 18, 19, 20, 21], [ 24, 25, 26, 27, 28, 29], [ 0, 1, 2, 3, 4, 5], [ 38, 39, ...
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
--- Build the Neural NetworkImplement an RNN using PyTorch's [Module class](http://pytorch.org/docs/master/nn.htmltorch.nn.Module). You may choose to use a GRU or an LSTM. To complete the RNN, you'll have to implement the following functions for the class: - `__init__` - The initialize function. - `init_hidden` - The ...
#reference source: inspired/copied from course samples import numpy as np def one_hot_encode(arr, n_labels): arr = arr.cpu().numpy() # Initialize the the encoded array one_hot = np.zeros((np.multiply(*arr.shape), n_labels), dtype=np.float32) # Fill the appropriate elements with ones o...
Tests Passed
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
Define forward and backpropagationUse the RNN class you implemented to apply forward and back propagation. This function will be called, iteratively, in the training loop as follows:```loss = forward_back_prop(decoder, decoder_optimizer, criterion, inp, target)```And it should return the average loss over a batch and ...
def forward_back_prop(rnn, optimizer, criterion, inp, target, hidden): """ Forward and backward propagation on the neural network :param decoder: The PyTorch Module that holds the neural network :param decoder_optimizer: The PyTorch optimizer for the neural network :param criterion: The PyTorch loss...
Tests Passed
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
Neural Network TrainingWith the structure of the network complete and data ready to be fed in the neural network, it's time to train it. Train LoopThe training loop is implemented for you in the `train_decoder` function. This function will train the network over all the batches for the number of epochs given. The mode...
""" DON'T MODIFY ANYTHING IN THIS CELL """ def train_rnn(rnn, batch_size, optimizer, criterion, n_epochs, show_every_n_batches=100): batch_losses = [] rnn.train() print("Training for %d epoch(s), %d batch size, %d show every..." % (n_epochs, batch_size, show_every_n_batches)) for epoch_i in range...
_____no_output_____
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
HyperparametersSet and train the neural network with the following parameters:- Set `sequence_length` to the length of a sequence.- Set `batch_size` to the batch size.- Set `num_epochs` to the number of epochs to train for.- Set `learning_rate` to the learning rate for an Adam optimizer.- Set `vocab_size` to the numbe...
# Data params # Sequence Length, # of words in a sequence sequence_length = 10 # Batch Size if(train_on_gpu): batch_size = 512 #128 #64 else: batch_size = 5 # data loader - do not change train_loader = batch_data(int_text, sequence_length, batch_size) # Training parameters myGlobalLoss = 5 myDropout = 0.5 #0....
_____no_output_____
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
TrainIn the next cell, you'll train the neural network on the pre-processed data. If you have a hard time getting a good loss, you may consider changing your hyperparameters. In general, you may get better results with larger hidden and n_layer dimensions, but larger models take a longer time to train. > **You should...
#for debugging purposes # import os # os.environ['CUDA_LAUNCH_BLOCKING'] = "1" """ DON'T MODIFY ANYTHING IN THIS CELL """ # create model and move to gpu if available rnn = RNN(vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=myDropout) if train_on_gpu: rnn.cuda() # defining loss and optimizat...
could not load any model RNN( (dropout): Dropout(p=0.5) (embed): Embedding(21389, 300) (lstm): LSTM(300, 512, num_layers=2, batch_first=True, dropout=0.5) (fc): Linear(in_features=512, out_features=21389, bias=True) ) Training for 10 epoch(s), 512 batch size, show every 200, global loss 5.0000... Epoch: 1/10...
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
Question: How did you decide on your model hyperparameters? For example, did you try different sequence_lengths and find that one size made the model converge faster? What about your hidden_dim and n_layers; how did you decide on those? **Answer:** (Write answer, here)- Tried with multiple combinations of hyperparamet...
""" DON'T MODIFY ANYTHING IN THIS CELL """ import torch import helper import problem_unittests as tests _, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess() trained_rnn = helper.load_model('./save/trained_rnn')
_____no_output_____
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
Generate TV ScriptWith the network trained and saved, you'll use it to generate a new, "fake" Seinfeld TV script in this section. Generate TextTo generate the text, the network needs to start with a single word and repeat its predictions until it reaches a set length. You'll be using the `generate` function to do this...
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ import torch.nn.functional as F def generate(rnn, prime_id, int_to_vocab, token_dict, pad_value, predict_len=100): """ Generate text using the neural network :param decoder: The PyTorch Module that holds the trained neural network :para...
_____no_output_____
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
Generate a New ScriptIt's time to generate the text. Set `gen_length` to the length of TV script you want to generate and set `prime_word` to one of the following to start the prediction:- "jerry"- "elaine"- "george"- "kramer"You can set the prime word to _any word_ in our dictionary, but it's best to start with a nam...
# run the cell multiple times to get different results! gen_length = 400 # modify the length to your preference prime_word = 'jerry' # name for starting the script """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ pad_word = helper.SPECIAL_WORDS['PADDING'] generated_script = generate(trained_rnn, voca...
/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:51: UserWarning: RNN module weights are not part of single contiguous chunk of memory. This means they need to be compacted at every call, possibly greatly increasing memory usage. To compact weights again call flatten_parameters().
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
Save your favorite scriptsOnce you have a script that you like (or find interesting), save it to a text file!
# save script to a text file f = open("generated_script_1.txt","w") f.write(generated_script) f.close()
_____no_output_____
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
ankursial/Deep-Learning-ND
**Recursion and Higher Order Functions**Today we're tackling recursion, and touching on higher-order functions in Python. A **recursive** function is one that calls itself. A classic example: the Fibonacci sequence.The Fibonacci sequence was originally described to model population growth, and is self-referential in...
def factorial(n): if n == 1: return 1 else: return n*factorial(n-1) print(factorial(5)) def fibonacci(n): if n == 1: return 0 elif n == 2: return 1 else: # print('working on number ' + str(n)) return fibonacci(n-1)+fibonacci(n-2) fibon...
120
BSD-3-Clause
cycle_2_fancy_functions/cycle_2_lecture_recursion_higher_post_recording.ipynb
magicicada/cs1px_2020
There are two very important parts of these functions: a base case (or two) and a recursive case. When designing recursive functions it can help to think about these two cases!The base case is the case when we know we are done, and can just return a value. (e.g. in fibonacci above there are two base cases, `n ==1` and...
def countdown(n): # base case if n == 0: print('Blastoff!') # recursive case else: print(n) countdown(n-1) countdown(10)
10 9 8 7 6 5 4 3 2 1 Blastoff!
BSD-3-Clause
cycle_2_fancy_functions/cycle_2_lecture_recursion_higher_post_recording.ipynb
magicicada/cs1px_2020
Let's write a recursive function that adds up the elements of a list:
def add_up_list(my_list): # base case if len(my_list) == 0: return 0 # recursive case else: first_elem = my_list[0] return first_elem + add_up_list(my_list[1:]) my_list = [1, 2, 1, 3, 4] print(add_up_list(my_list))
11
BSD-3-Clause
cycle_2_fancy_functions/cycle_2_lecture_recursion_higher_post_recording.ipynb
magicicada/cs1px_2020
**Higher-order functions**are functions that takes a function as an argument or returns a function. We will talk briefly about functions that take a function as an argument. Let's look at an example.
def h(x): return x+4 def g(x): return x**2 def doItTwice(f, x): return f(f(x)) print(doItTwice(h, 3)) print(doItTwice(g, 3))
11 81
BSD-3-Clause
cycle_2_fancy_functions/cycle_2_lecture_recursion_higher_post_recording.ipynb
magicicada/cs1px_2020
A common reason for using a higher-order function is to apply a parameter-specified function repeatedly over a data structure (like a list or a dictionary).Let's look at an example function that applies a parameter function to every element of a list:
def sampleFunction1(x): return 2*x def sampleFunction2(x): return x % 2 def applyToAll(func, myList): newList = [] for element in myList: newList.append(func(element)) return newList aList = [2, 3, 4, 5] print(applyToAll(sampleFunction1, aList)) print(applyToAll(sampleF...
[4, 6, 8, 10] [0, 1, 0, 1]
BSD-3-Clause
cycle_2_fancy_functions/cycle_2_lecture_recursion_higher_post_recording.ipynb
magicicada/cs1px_2020
Something like this applyToAll function is built into Python, and is called map
def sampleFunction1(x): return 2*x def sampleFunction2(x): return x % 2 aList = [2, 3, 4, 5] print(list(map(sampleFunction1, aList))) bList = [2, 3, 4, 5] print(list(map(sampleFunction2, aList)))
[4, 6, 8, 10] [0, 1, 0, 1]
BSD-3-Clause
cycle_2_fancy_functions/cycle_2_lecture_recursion_higher_post_recording.ipynb
magicicada/cs1px_2020
Python has quite a few built-in functions (some higher-order, some not). You can find lots of them here: https://docs.python.org/3.3/library/functions.html (I **will not** by default require you to remember those for an exam!!) Example: zip does something that may be familiar from last week's lab.
x = [1, 2, 3] y = [4, 5, 6] zipped = zip(x, y) print(list(zipped))
[(1, 4), (2, 5), (3, 6)]
BSD-3-Clause
cycle_2_fancy_functions/cycle_2_lecture_recursion_higher_post_recording.ipynb
magicicada/cs1px_2020
Introduction to `pandas`
import numpy as np import pandas as pd
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Series and Data Frames Series objects A `Series` is like a vector. All elements must have the same type or are nulls.
s = pd.Series([1,1,2,3] + [None]) s
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Size
s.size
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Unique Counts
s.value_counts()
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Special types of series Strings
words = 'the quick brown fox jumps over the lazy dog'.split() s1 = pd.Series([' '.join(item) for item in zip(words[:-1], words[1:])]) s1 s1.str.upper() s1.str.split() s1.str.split().str[1]
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Categories
s2 = pd.Series(['Asian', 'Asian', 'White', 'Black', 'White', 'Hispanic']) s2 s2 = s2.astype('category') s2 s2.cat.categories s2.cat.codes
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
DataFrame objects A `DataFrame` is like a matrix. Columns in a `DataFrame` are `Series`.- Each column in a DataFrame represents a **variale**- Each row in a DataFrame represents an **observation**- Each cell in a DataFrame represents a **value**
df = pd.DataFrame(dict(num=[1,2,3] + [None])) df df.num
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
IndexRow and column identifiers are of `Index` type.Somewhat confusingly, index is also a a synonym for the row identifiers.
df.index
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Setting a column as the row index
df df1 = df.set_index('num') df1
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Making an index into a column
df1.reset_index()
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
ColumnsThis is just a different index object
df.columns
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Getting raw valuesSometimes you just want a `numpy` array, and not a `pandas` object.
df.values
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Creating Data Frames Manual
from collections import OrderedDict n = 5 dates = pd.date_range(start='now', periods=n, freq='d') df = pd.DataFrame(OrderedDict(pid=np.random.randint(100, 999, n), weight=np.random.normal(70, 20, n), height=np.random.normal(170, 15, n), ...
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
From fileYou can read in data from many different file types - plain text, JSON, spreadsheets, databases etc. Functions to read in data look like `read_X` where X is the data type.
%%file measures.txt pid weight height date 328 72.654347 203.560866 2018-11-11 14:16:18.148411 756 34.027679 189.847316 2018-11-12 14:16:18.148411 185 28.501914 158.646074 2018-11-13 14:16:18.148411 507 17.396343 180.795993 2018-11-14 14:16:18.148411 919 64.724301 173.564725 2018-11-15 14:16:18.148411 df = pd.read_tabl...
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Indexing Data Frames Implicit defaultsif you provide a slice, it is assumed that you are asking for rows.
df[1:3]
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
If you provide a singe value or list, it is assumed that you are asking for columns.
df[['pid', 'weight']]
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Extracting a column Dictionary style access
df['pid']
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Property style accessThis only works for column names tat are also valid Python identifier (i.e., no spaces or dashes or keywords)
df.pid
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Indexing by locationThis is similar to `numpy` indexing
df.iloc[1:3, :] df.iloc[1:3, [True, False, True]]
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Indexing by name
df.loc[1:3, 'weight':'height']
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
**Warning**: When using `loc`, the row slice indicates row names, not positions.
df1 = df.copy() df1.index = df.index + 1 df1 df1.loc[1:3, 'weight':'height']
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Structure of a Data Frame Data types
df.dtypes
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Converting data types Using `astype` on one column
df.pid = df.pid.astype('category')
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Using `astype` on multiple columns
df = df.astype(dict(weight=float, height=float))
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Using a conversion function
df.date = pd.to_datetime(df.date)
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Check
df.dtypes
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Basic properties
df.size df.shape df.describe()
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Inspection
df.head(n=3) df.tail(n=3) df.sample(n=3) df.sample(frac=0.5)
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Selecting, Renaming and Removing Columns Selecting columns
df.filter(items=['pid', 'date']) df.filter(regex='.*ght')
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Note that you can also use regular string methods on the columns
df.loc[:, df.columns.str.contains('d')]
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Renaming columns
df.rename(dict(weight='w', height='h'), axis=1) orig_cols = df.columns df.columns = list('abcd') df df.columns = orig_cols df
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Removing columns
df.drop(['pid', 'date'], axis=1) df.drop(columns=['pid', 'date']) df.drop(columns=df.columns[df.columns.str.contains('d')])
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Selecting, Renaming and Removing Rows Selecting rows
df[df.weight.between(60,70)] df[(69 <= df.weight) & (df.weight < 70)] df[df.date.between(pd.to_datetime('2018-11-13'), pd.to_datetime('2018-11-15 23:59:59'))]
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Renaming rows
df.rename({i:letter for i,letter in enumerate('abcde')}) df.index = ['the', 'quick', 'brown', 'fox', 'jumphs'] df df = df.reset_index(drop=True) df
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Dropping rows
df.drop([1,3], axis=0)
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Dropping duplicated data
df['something'] = [1,1,None,2,None] df.loc[df.something.duplicated()] df.drop_duplicates(subset='something')
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019
Dropping missing data
df df.something.fillna(0) df.something.ffill() df.something.bfill() df.something.interpolate() df.dropna()
_____no_output_____
BSD-3-Clause
notebooks/03_Using_Pandas_Annotated.ipynb
abbarcenasj/bios-823-2019