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
Here I'm looking through a sample of values in each column, choosing the columns to explore based on the their headings, a bit of contextual info from colleagues and the `df.describe()` above.
df["Subject"]
_____no_output_____
MIT
notebooks/archive_exploration/notebooks/01 - subject coocurrence.ipynb
wellcomecollection/data-science
After much trial and error...Subjects look like an interesting avenue to explore further. Where subjects have _actually_ been filled in and the entry is not `None`, a list of subjects is returned. We can explore some of these subjects' subtleties by creating an adjacency matrix. We'll count the number of times each s...
subjects = flatten(df["Subject"].dropna().tolist()) print(len(subjects)) subjects = list(set(map(clean, subjects))) print(len(subjects))
_____no_output_____
MIT
notebooks/archive_exploration/notebooks/01 - subject coocurrence.ipynb
wellcomecollection/data-science
At this point it's often helpful to index our data, ie transform words into numbers. We'll create two dictionaries which map back and forth between the subjects and their corresponding indicies:
index_to_subject = {index: subject for index, subject in enumerate(subjects)} subject_to_index = {subject: index for index, subject in enumerate(subjects)}
_____no_output_____
MIT
notebooks/archive_exploration/notebooks/01 - subject coocurrence.ipynb
wellcomecollection/data-science
Lets instantiate an empty numpy array which we'll then fill with our coocurrence data. Each column and each row will represent a subject - each cell (the intersection of a column and row) will therefore represent the 'strength' of the interaction between those subjects. As we haven't seen any interactions yet, we'll se...
adjacency = np.empty((len(subjects), len(subjects)), dtype=np.uint16)
_____no_output_____
MIT
notebooks/archive_exploration/notebooks/01 - subject coocurrence.ipynb
wellcomecollection/data-science
To populate the matrix, we want to find every possible combination of subject in each sub-list from our original column, ie if we had the subjects`[Disease, Heart, Heart Diseases, Cardiology]`we would want to return `[['Disease', 'Disease'], ['Heart', 'Disease'], ['Heart Diseases', 'Disease'], ['Cardiology', 'Disease']...
for row_of_subjects in tqdm(df["Subject"].dropna()): for subject_pair in cartesian(row_of_subjects, row_of_subjects): subject_index_1 = subject_to_index[clean(subject_pair[0])] subject_index_2 = subject_to_index[clean(subject_pair[1])] adjacency[subject_index_1, subject_index_2] += 1
_____no_output_____
MIT
notebooks/archive_exploration/notebooks/01 - subject coocurrence.ipynb
wellcomecollection/data-science
We can do all sorts of fun stuff now - adjacency matrices are the foundation on which all of graph theory is built. However, because it's a bit more interesting, I'm going to start with some dimensionality reduction. We'll get to the graphy stuff later. Using [UMAP](https://github.com/lmcinnes/umap), we can squash the...
embedding_2d = pd.DataFrame(UMAP(n_components=2).fit_transform(adjacency)) embedding_2d.plot.scatter(x=0, y=1);
_____no_output_____
MIT
notebooks/archive_exploration/notebooks/01 - subject coocurrence.ipynb
wellcomecollection/data-science
We can isolate the clusters we've found above using a number of different methods - `scikit-learn` provides easy access to some very powerful algorithms. Here I'll use a technique called _agglomerative clustering_, and make a guess that 15 is an appropriate number of clusters to look for.
n_clusters = 15 embedding_2d["labels"] = AgglomerativeClustering(n_clusters).fit_predict( embedding_2d.values ) embedding_2d.plot.scatter(x=0, y=1, c="labels", cmap="Paired");
_____no_output_____
MIT
notebooks/archive_exploration/notebooks/01 - subject coocurrence.ipynb
wellcomecollection/data-science
We can now use the `index_to_subject` mapping that we created earlier to examine which subjects have been grouped together into clusters
for i in range(n_clusters): print(str(i) + " " + "-" * 80 + "\n") print( np.sort( [ index_to_subject[index] for index in embedding_2d[embedding_2d["labels"] == i].index.values ] ) ) print("\n")
_____no_output_____
MIT
notebooks/archive_exploration/notebooks/01 - subject coocurrence.ipynb
wellcomecollection/data-science
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
NorahAlshaya/TV-Script-Generation-Project
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 = (0, 10) """ 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 0 to 10: jerry: do you know what this is all about? do you know, why were here? to be out, this is out...and out is one of the single most enjoyable experiences of life. peo...
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
NorahAlshaya/TV-Script-Generation-Project
--- 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 #define count ...
Tests Passed
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
NorahAlshaya/TV-Script-Generation-Project
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 tokens = dict() tokens['.'] = '||period||' tokens[','] = '||comma||' tokens['"'] = '||quo...
Tests Passed
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
NorahAlshaya/TV-Script-Generation-Project
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
NorahAlshaya/TV-Script-Generation-Project
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()
_____no_output_____
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
NorahAlshaya/TV-Script-Generation-Project
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
NorahAlshaya/TV-Script-Generation-Project
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 def batch_data(words, sequence_length, batch_size): """ Batch the neural network data using DataLoader :param words: The word ids of the TV scripts :param sequence_length: The sequence length of each batch :param batch_size: The size of each b...
_____no_output_____
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
NorahAlshaya/TV-Script-Generation-Project
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=5, batch_size=10) data_iter = iter(t_loader) sample_x, sample_y = data_iter.next() print(sample_x.shape) print(sample_x) print() print(sample_y.shape) print(sample_y)
torch.Size([10, 5]) tensor([[ 0, 1, 2, 3, 4], [ 1, 2, 3, 4, 5], [ 2, 3, 4, 5, 6], [ 3, 4, 5, 6, 7], [ 4, 5, 6, 7, 8], [ 5, 6, 7, 8, 9], [ 6, 7, 8, 9, 10], [ 7, 8, 9, 10, 11], [ 8, 9, ...
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
NorahAlshaya/TV-Script-Generation-Project
--- 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 ...
import torch.nn as nn class RNN(nn.Module): def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5): """ Initialize the PyTorch RNN Module :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary) ...
Tests Passed
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
NorahAlshaya/TV-Script-Generation-Project
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
NorahAlshaya/TV-Script-Generation-Project
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)..." % n_epochs) for epoch_i in range(1, n_epochs + 1): # initialize hidden state ...
_____no_output_____
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
NorahAlshaya/TV-Script-Generation-Project
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 sequence_length = 12 # of words in a sequence # Batch Size batch_size = 120 # data loader - do not change train_loader = batch_data(int_text, sequence_length, batch_size) # Training parameters # Number of Epochs num_epochs = 10 # Learning Rate learning_rate = 0.001 # Model parameters ...
_____no_output_____
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
NorahAlshaya/TV-Script-Generation-Project
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...
""" 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=0.5) if train_on_gpu: rnn.cuda() # defining loss and optimization functions for training optimizer = torch.optim.Adam(rnn.parameters(), lr=learning...
Training for 10 epoch(s)... Epoch: 1/10 Loss: 5.531735227108002 Epoch: 1/10 Loss: 4.930219256401062 Epoch: 1/10 Loss: 4.637746600151062 Epoch: 1/10 Loss: 4.442910384654999 Epoch: 1/10 Loss: 4.507025374412537 Epoch: 1/10 Loss: 4.437873532295227 Epoch: 1/10 Loss: 4.49948018...
MIT
project-tv-script-generation/dlnd_tv_script_generation.ipynb
NorahAlshaya/TV-Script-Generation-Project
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:** I trained the model with the following parameters:10 epochslearning ra...
""" 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
NorahAlshaya/TV-Script-Generation-Project
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
NorahAlshaya/TV-Script-Generation-Project
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:40: 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
NorahAlshaya/TV-Script-Generation-Project
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
NorahAlshaya/TV-Script-Generation-Project
Problem 3 Use this notebook to write your code for problem 3 by filling in the sections marked ` TODO` and running all cells.
import numpy as np import matplotlib.pyplot as plt import itertools import urllib.request urllib.request.urlretrieve('https://raw.githubusercontent.com/lakigigar/Caltech-CS155-2021/main/psets/set1/perceptron_helper.py', 'perceptron_helper.py') from perceptron_helper import ( predict, plot_data, boundary, ...
_____no_output_____
BSD-2-Clause
psets/set1/set1_prob3.ipynb
ichakraborty/CS155-iniproject
Implementation of Perceptron First, we will implement the perceptron algorithm. Fill in the `update_perceptron()` function so that it finds a single misclassified point and updates the weights and bias accordingly. If no point exists, the weights and bias should not change.Hint: You can use the `predict()` helper meth...
def update_perceptron(X, Y, w, b): """ This method updates a perceptron model. Takes in the previous weights and returns weights after an update, which could be nothing. Inputs: X: A (N, D) shaped numpy array containing N D-dimensional points. Y: A (N, ) shaped numpy array containin...
_____no_output_____
BSD-2-Clause
psets/set1/set1_prob3.ipynb
ichakraborty/CS155-iniproject
Next you will fill in the `run_perceptron()` method. The method performs single updates on a misclassified point until convergence, or max_iter updates are made. The function will return the final weights and bias. You should use the `update_perceptron()` method you implemented above.
def run_perceptron(X, Y, w, b, max_iter): """ This method runs the perceptron learning algorithm. Takes in initial weights and runs max_iter update iterations. Returns final weights and bias. Inputs: X: A (N, D) shaped numpy array containing N D-dimensional points. Y: A (N, ) shaped...
_____no_output_____
BSD-2-Clause
psets/set1/set1_prob3.ipynb
ichakraborty/CS155-iniproject
Problem 3A Visualizing a Toy Dataset We will begin by training our perceptron on a toy dataset of 3 points. The green points are labelled +1 and the red points are labelled -1. We use the helper function `plot_data()` to do so.
X = np.array([[ -3, -1], [0, 3], [1, -2]]) Y = np.array([ -1, 1, 1]) fig = plt.figure(figsize=(5,4)) ax = fig.gca(); ax.set_xlim(-4.1, 3.1); ax.set_ylim(-3.1, 4.1) plot_data(X, Y, ax)
_____no_output_____
BSD-2-Clause
psets/set1/set1_prob3.ipynb
ichakraborty/CS155-iniproject
Running the Perceptron Next, we will run the perceptron learning algorithm on this dataset. Update the code to show the weights and bias at each timestep and the misclassified point used in each update. Run the below code, and fill in the corresponding table in the set.
# Initialize weights and bias. weights = np.array([0.0, 1.0]) bias = 0.0 weights, bias = run_perceptron(X, Y, weights, bias, 16) print() print ("final w = %s, final b = %.1f" % (weights, bias))
_____no_output_____
BSD-2-Clause
psets/set1/set1_prob3.ipynb
ichakraborty/CS155-iniproject
Visualizating the Perceptron Getting all that information in table form isn't very informative. Let us visualize what the decision boundaries are at each timestep instead. The helper functions `boundary()` and `plot_perceptron()` plot a decision boundary given a perceptron weights and bias. Note that the equation for ...
def run_perceptron(X, Y, w, b, axs, max_iter): """ This method runs the perceptron learning algorithm. Takes in initial weights and runs max_iter update iterations. Returns final weights and bias. Inputs: X: A (N, D) shaped numpy array containing N D-dimensional points. Y: A (N, ) s...
_____no_output_____
BSD-2-Clause
psets/set1/set1_prob3.ipynb
ichakraborty/CS155-iniproject
Run the below code to get a visualization of the perceptron algorithm. The red region are areas the perceptron thinks are negative examples.
# Initialize weights and bias. weights = np.array([0.0, 1.0]) bias = 0.0 f, ax_arr = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(9,8)) axs = list(itertools.chain.from_iterable(ax_arr)) for ax in axs: ax.set_xlim(-4.1, 3.1); ax.set_ylim(-3.1, 4.1) run_perceptron(X, Y, weights, bias, axs, 4) f.tight_layo...
_____no_output_____
BSD-2-Clause
psets/set1/set1_prob3.ipynb
ichakraborty/CS155-iniproject
Problem 3C Visualize a Non-linearly Separable Dataset. We will now work on a dataset that cannot be linearly separated, namely one that is generated by the XOR function.
X = np.array([[0, 1], [1, 0], [0, 0], [1, 1]]) Y = np.array([1, 1, -1, -1]) fig = plt.figure(figsize=(5,4)) ax = fig.gca(); ax.set_xlim(-0.1, 1.1); ax.set_ylim(-0.1, 1.1) plot_data(X, Y, ax)
_____no_output_____
BSD-2-Clause
psets/set1/set1_prob3.ipynb
ichakraborty/CS155-iniproject
We will now run the perceptron algorithm on this dataset. We will limit the total timesteps this time, but you should see a pattern in the updates. Run the below code.
# Initialize weights and bias. weights = np.array([0.0, 1.0]) bias = 0.0 f, ax_arr = plt.subplots(4, 4, sharex=True, sharey=True, figsize=(9,8)) axs = list(itertools.chain.from_iterable(ax_arr)) for ax in axs: ax.set_xlim(-0.1, 1.1); ax.set_ylim(-0.1, 1.1) run_perceptron(X, Y, weights, bias, axs, 16) f.tight...
_____no_output_____
BSD-2-Clause
psets/set1/set1_prob3.ipynb
ichakraborty/CS155-iniproject
!apt-get -qq install tree import os import numpy as np import pandas as pd from getpass import getpass from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_absolute_error from sklearn.impute import SimpleImputer from sklearn.preproc...
imputer imputer: -------------------- RandomForestRegressor(bootstrap=True, ccp_alpha=0.0, criterion='mse', max_depth=None, max_features='auto', max_leaf_nodes=None, max_samples=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1...
MIT
Pipeline_multiple_imputers_and_models.ipynb
chrismarkella/Kaggle-access-from-Google-Colab
In this tutorial you'll learn all about **histograms** and **density plots**. Set up the notebookAs always, we begin by setting up the coding environment. (_This code is hidden, but you can un-hide it by clicking on the "Code" button immediately below this text, on the right._)
#$HIDE$ import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns print("Setup Complete")
_____no_output_____
Apache-2.0
notebooks/data_viz_to_coder/raw/tut5.ipynb
stephenramthun/learntools
Select a datasetWe'll work with a dataset of 150 different flowers, or 50 each from three different species of iris (*Iris setosa*, *Iris versicolor*, and *Iris virginica*).![tut4_iris](https://i.imgur.com/RcxYYBA.png) Load and examine the dataEach row in the dataset corresponds to a different flower. There are four ...
# Path of the file to read iris_filepath = "../input/iris.csv" # Read the file into a variable iris_data iris_data = pd.read_csv(iris_filepath, index_col="Id") # Print the first 5 rows of the data iris_data.head()
_____no_output_____
Apache-2.0
notebooks/data_viz_to_coder/raw/tut5.ipynb
stephenramthun/learntools
HistogramsSay we would like to create a **histogram** to see how petal length varies in iris flowers. We can do this with the `sns.distplot` command.
# Histogram sns.distplot(a=iris_data['Petal Length (cm)'], kde=False)
_____no_output_____
Apache-2.0
notebooks/data_viz_to_coder/raw/tut5.ipynb
stephenramthun/learntools
We customize the behavior of the command with two additional pieces of information:- `a=` chooses the column we'd like to plot (_in this case, we chose `'Petal Length (cm)'`_).- `kde=False` is something we'll always provide when creating a histogram, as leaving it out will create a slightly different plot. Density plot...
# KDE plot sns.kdeplot(data=iris_data['Petal Length (cm)'], shade=True)
_____no_output_____
Apache-2.0
notebooks/data_viz_to_coder/raw/tut5.ipynb
stephenramthun/learntools
2D KDE plotsWe're not restricted to a single column when creating a KDE plot. We can create a **two-dimensional (2D) KDE plot** with the `sns.jointplot` command.In the plot below, the color-coding shows us how likely we are to see different combinations of sepal width and petal length, where darker parts of the figur...
# 2D KDE plot sns.jointplot(x=iris_data['Petal Length (cm)'], y=iris_data['Sepal Width (cm)'], kind="kde")
_____no_output_____
Apache-2.0
notebooks/data_viz_to_coder/raw/tut5.ipynb
stephenramthun/learntools
Note that in addition to the 2D KDE plot in the center,- the curve at the top of the figure is a KDE plot for the data on the x-axis (in this case, `iris_data['Petal Length (cm)']`), and- the curve on the right of the figure is a KDE plot for the data on the y-axis (in this case, `iris_data['Sepal Width (cm)']`). Colo...
# Paths of the files to read iris_set_filepath = "../input/iris_setosa.csv" iris_ver_filepath = "../input/iris_versicolor.csv" iris_vir_filepath = "../input/iris_virginica.csv" # Read the files into variables iris_set_data = pd.read_csv(iris_set_filepath, index_col="Id") iris_ver_data = pd.read_csv(iris_ver_filepath,...
_____no_output_____
Apache-2.0
notebooks/data_viz_to_coder/raw/tut5.ipynb
stephenramthun/learntools
In the code cell below, we create a different histogram for each species by using the `sns.distplot` command (_as above_) three times. We use `label=` to set how each histogram will appear in the legend.
# Histograms for each species sns.distplot(a=iris_set_data['Petal Length (cm)'], label="Iris-setosa", kde=False) sns.distplot(a=iris_ver_data['Petal Length (cm)'], label="Iris-versicolor", kde=False) sns.distplot(a=iris_vir_data['Petal Length (cm)'], label="Iris-virginica", kde=False) # Add title plt.title("Histogram ...
_____no_output_____
Apache-2.0
notebooks/data_viz_to_coder/raw/tut5.ipynb
stephenramthun/learntools
In this case, the legend does not automatically appear on the plot. To force it to show (for any plot type), we can always use `plt.legend()`.We can also create a KDE plot for each species by using `sns.kdeplot` (_as above_). Again, `label=` is used to set the values in the legend.
# KDE plots for each species sns.kdeplot(data=iris_set_data['Petal Length (cm)'], label="Iris-setosa", shade=True) sns.kdeplot(data=iris_ver_data['Petal Length (cm)'], label="Iris-versicolor", shade=True) sns.kdeplot(data=iris_vir_data['Petal Length (cm)'], label="Iris-virginica", shade=True) # Add title plt.title("Di...
_____no_output_____
Apache-2.0
notebooks/data_viz_to_coder/raw/tut5.ipynb
stephenramthun/learntools
📝 Exercise M6.02The aim of this exercise it to explore some attributes available inscikit-learn's random forest.First, we will fit the penguins regression dataset.
import pandas as pd from sklearn.model_selection import train_test_split penguins = pd.read_csv("../datasets/penguins_regression.csv") feature_names = ["Flipper Length (mm)"] target_name = "Body Mass (g)" data, target = penguins[feature_names], penguins[target_name] data_train, data_test, target_train, target_test = t...
_____no_output_____
CC-BY-4.0
notebooks/ensemble_ex_02.ipynb
lesteve/scikit-learn-mooc
NoteIf you want a deeper overview regarding this dataset, you can refer to theAppendix - Datasets description section at the end of this MOOC. Create a random forest containing three trees. Train the forest andcheck the generalization performance on the testing set in terms of meanabsolute error.
# Write your code here.
_____no_output_____
CC-BY-4.0
notebooks/ensemble_ex_02.ipynb
lesteve/scikit-learn-mooc
The next steps of this exercise are to:- create a new dataset containing the penguins with a flipper length between 170 mm and 230 mm;- plot the training data using a scatter plot;- plot the decision of each individual tree by predicting on the newly created dataset;- plot the decision of the random forest using this...
# Write your code here.
_____no_output_____
CC-BY-4.0
notebooks/ensemble_ex_02.ipynb
lesteve/scikit-learn-mooc
IMPORTING THE LIBRARIES
import os import pandas as pd import pickle import numpy as np import seaborn as sns from sklearn.datasets import load_files from keras.utils import np_utils import matplotlib.pyplot as plt from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D from keras.layers import Dropout, Flatten, Dense from keras....
csv_files 'Distracted Driver Detection CNN Scratch.ipynb' 'Distracted Driver Detection VGG16.ipynb' imgs model pickle_files 'Self Trained Model Evaluation.ipynb' temp_dir
Apache-2.0
Distracted Driver Detection CNN Scratch.ipynb
vk16309/Distracted-Driver-Detection
Defining the train,test and model directoriesWe will create the directories for train,test and model training paths if not present
TEST_DIR = os.path.join(os.getcwd(),"imgs","test") TRAIN_DIR = os.path.join(os.getcwd(),"imgs","train") MODEL_PATH = os.path.join(os.getcwd(),"model","self_trained") PICKLE_DIR = os.path.join(os.getcwd(),"pickle_files") if not os.path.exists(TEST_DIR): print("Testing data does not exists") if not os.path.exists(TRA...
_____no_output_____
Apache-2.0
Distracted Driver Detection CNN Scratch.ipynb
vk16309/Distracted-Driver-Detection
Data Preparation We will create a csv file having the location of the files present for training and test images and their associated class if present so that it is easily traceable.
def create_csv(DATA_DIR,filename): class_names = os.listdir(DATA_DIR) data = list() if(os.path.isdir(os.path.join(DATA_DIR,class_names[0]))): for class_name in class_names: file_names = os.listdir(os.path.join(DATA_DIR,class_name)) for file in file_names: data...
_____no_output_____
Apache-2.0
Distracted Driver Detection CNN Scratch.ipynb
vk16309/Distracted-Driver-Detection
Observation:1. There are total 22424 training samples2. There are total 79726 training samples3. The training dataset is equally balanced to a great extent and hence we need not do any downsampling of the data Converting into numerical values
labels_list = list(set(data_train['ClassName'].values.tolist())) labels_id = {label_name:id for id,label_name in enumerate(labels_list)} print(labels_id) data_train['ClassName'].replace(labels_id,inplace=True) with open(os.path.join(os.getcwd(),"pickle_files","labels_list.pkl"),"wb") as handle: pickle.dump(labels_i...
(22424, 10)
Apache-2.0
Distracted Driver Detection CNN Scratch.ipynb
vk16309/Distracted-Driver-Detection
Splitting into Train and Test sets
from sklearn.model_selection import train_test_split xtrain,xtest,ytrain,ytest = train_test_split(data_train.iloc[:,0],labels,test_size = 0.2,random_state=42)
_____no_output_____
Apache-2.0
Distracted Driver Detection CNN Scratch.ipynb
vk16309/Distracted-Driver-Detection
Converting into 64*64 images You can substitute 64,64 to 224,224 for better results only if ram is >32gb
def path_to_tensor(img_path): # loads RGB image as PIL.Image.Image type img = image.load_img(img_path, target_size=(64, 64)) # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3) x = image.img_to_array(img) # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D te...
_____no_output_____
Apache-2.0
Distracted Driver Detection CNN Scratch.ipynb
vk16309/Distracted-Driver-Detection
Defining the Model
model = Sequential() model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu', input_shape=(64,64,3), kernel_initializer='glorot_normal')) model.add(MaxPooling2D(pool_size=2)) model.add(Conv2D(filters=128, kernel_size=2, padding='same', activation='relu', kernel_initializer='glorot_normal')) model...
_____no_output_____
Apache-2.0
Distracted Driver Detection CNN Scratch.ipynb
vk16309/Distracted-Driver-Detection
Model AnalysisFinding the Confusion matrix,Precision,Recall and F1 score to analyse the model thus created
def print_confusion_matrix(confusion_matrix, class_names, figsize = (10,7), fontsize=14): df_cm = pd.DataFrame( confusion_matrix, index=class_names, columns=class_names, ) fig = plt.figure(figsize=figsize) try: heatmap = sns.heatmap(df_cm, annot=True, fmt="d") except ValueError: ...
_____no_output_____
Apache-2.0
Distracted Driver Detection CNN Scratch.ipynb
vk16309/Distracted-Driver-Detection
Precision Recall F1 Score
ypred_class = np.argmax(ypred,axis=1) # print(ypred_class[:10]) ytest = np.argmax(ytest,axis=1) accuracy = accuracy_score(ytest,ypred_class) print('Accuracy: %f' % accuracy) # precision tp / (tp + fp) precision = precision_score(ytest, ypred_class,average='weighted') print('Precision: %f' % precision) # recall: tp / (t...
Accuracy: 0.992865 Precision: 0.992910 Recall: 0.992865 F1 score: 0.992871
Apache-2.0
Distracted Driver Detection CNN Scratch.ipynb
vk16309/Distracted-Driver-Detection
WeatherPy---- Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.
# Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests import time import json import random import csv as csv # Import API key from api_keys import api_key # Incorporated citipy to determine city based on latitude and longitude from citipy import citipy # Out...
_____no_output_____
MIT
Instructions/starter_code/weatherpy1.ipynb
bshub6/API-Challenge
Generate Cities List
# List for holding lat_lngs and cities counter = 0 randlat = [] randlngs = [] cities = [] # Create a set of random lat and lng combinations while len(randlat)< 500: lats = np.random.uniform(low=-90, high=90) lngs = np.random.uniform(low=-180, high=180) randlat.append(lats) randlngs.append(lngs) ...
634
MIT
Instructions/starter_code/weatherpy1.ipynb
bshub6/API-Challenge
Perform API Calls* Perform a weather check on each city using a series of successive API calls.* Include a print log of each city as it'sbeing processed (with the city number and city name).
url = "http://api.openweathermap.org/data/2.5/weather?" units = "metric" # Build query URL to begin call url = "http://api.openweathermap.org/data/2.5/weather?units=metric&appid=" + api_key #Set up list for responses date = [] country = [] lat = [] lon = [] temp_max = [] humidity = [] cloud = [] wind = [] _cities = [...
_____no_output_____
MIT
Instructions/starter_code/weatherpy1.ipynb
bshub6/API-Challenge
Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame
df.count() #Convert file to csv and save df.to_csv("weather_data.csv", encoding="utf-8", index=False)
_____no_output_____
MIT
Instructions/starter_code/weatherpy1.ipynb
bshub6/API-Challenge
Plotting the Data* Use proper labeling of the plots using plot titles (including date of analysis) and axes labels.* Save the plotted figures as .pngs. Latitude vs. Temperature Plot
# Build a scatter plot for each data type plt.scatter(df["latitude"], df["max temp"], marker="o") # Incorporate the other graph properties plt.title("City Latitude vs. Temperature (F)") plt.ylabel("Temperature (F)") plt.xlabel("Latitude") plt.grid(True) # Save the figure plt.savefig("Temperature (F).png") # Show plo...
_____no_output_____
MIT
Instructions/starter_code/weatherpy1.ipynb
bshub6/API-Challenge
Latitude vs. Humidity Plot
# Build a scatter plot for each data type plt.scatter(df["latitude"], df["humidity"], marker="o") # Incorporate the other graph properties plt.title("City Latitude vs. Humidity %") plt.ylabel("Humidity %") plt.xlabel("Latitude") plt.grid(True) # Save the figure plt.savefig("Humidity%.png") # Show plot plt.show()
_____no_output_____
MIT
Instructions/starter_code/weatherpy1.ipynb
bshub6/API-Challenge
Latitude vs. Cloudiness Plot
# Build a scatter plot for each data type plt.scatter(df["latitude"], df["cloudiness"], marker="o") # Incorporate the other graph properties plt.title("City Latitude vs. Cloudiness %") plt.ylabel("Cloudiness %") plt.xlabel("Latitude") plt.grid(True) # Save the figure plt.savefig("Clouds%.png") # Show plot plt.show()
_____no_output_____
MIT
Instructions/starter_code/weatherpy1.ipynb
bshub6/API-Challenge
Latitude vs. Wind Speed Plot
# Build a scatter plot for each data type plt.scatter(df["latitude"], df["windspeed"], marker="o") # Incorporate the other graph properties plt.title("City Latitude vs. Windspeed (mph)") plt.ylabel("Windspeed (mph)") plt.xlabel("Latitude") plt.grid(True) # Save the figure plt.savefig("Windspeed(mph).png") # Show plo...
_____no_output_____
MIT
Instructions/starter_code/weatherpy1.ipynb
bshub6/API-Challenge
Here you have a collection of guided exercises for the first class on Python. The exercises are divided by topic, following the topics reviewed during the theory session, and for each topic you have some mandatory exercises, and other optional exercises, which you are invited to do if you still have time after the mand...
#Your Code Here
_____no_output_____
Apache-2.0
M1_Python/d3_Intro_to_Python/02_exercises/Intro to Python - Easy.ipynb
succeedme/Strive_Main
**Exercise 1.2:** When something is wrong with your code, Python will raise errors. Often these will be "syntax errors" that signal that something is wrong with the form of your code (e.g., the code in the previous exercise raised a `SyntaxError`). There are also "runtime errors", which signal that your code was in its...
#Your Code Here
_____no_output_____
Apache-2.0
M1_Python/d3_Intro_to_Python/02_exercises/Intro to Python - Easy.ipynb
succeedme/Strive_Main
**Exercise 5.1**: Create a countdown function that starts at a certain count, and counts down to zero. Instead of zero, print "Blast off!". Use a `for` loop.
# Countdown def countdown(): """ 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Blast off! """ return
_____no_output_____
Apache-2.0
M1_Python/d3_Intro_to_Python/02_exercises/Intro to Python - Easy.ipynb
succeedme/Strive_Main
**Exercise 5.2:** Write and test three functions that return the largest, the smallest, and the number of dividables by 3 in a given collection of numbers. Use the algorithm described earlier in the Part 5 lecture :)
# Your functions def main(): """ a = [2, 4, 6, 12, 15, 99, 100] 100 2 4 """ return
_____no_output_____
Apache-2.0
M1_Python/d3_Intro_to_Python/02_exercises/Intro to Python - Easy.ipynb
succeedme/Strive_Main
Mauna-Loa CO2 concentration exampleExperiment of CO2 measurements in Mauna Loa, Hawaii, using a single output Gaussian process with a spectral mixture kernel. The data set contains daily measurements of CO2 in the air from 1958 to 2001. We will resample the data to obtain 10 averaged samples per year. That is, any yea...
import mogptk import numpy as np from sklearn.datasets import fetch_openml def load_mauna_loa_atmospheric_co2(): ml_data = fetch_openml(data_id=41187) months = [] ppmv_sums = [] counts = [] y = ml_data.data['year'] m = ml_data.data['month'] month_float = y + (m - 1) / 12 ppmvs = ml_dat...
_____no_output_____
MIT
examples/example_mauna_loa.ipynb
vishalbelsare/mogptk
First we load the dataset, and define a variable `stop` with the index that separates between train and test
# load dataset x, y = load_mauna_loa_atmospheric_co2() # stop omde to separate train from test stop = 200 data = mogptk.Data(x, y, name='Mauna Loa') data.remove_range(start=x[stop]) data.transform(mogptk.TransformDetrend(3)) data.plot();
_____no_output_____
MIT
examples/example_mauna_loa.ipynb
vishalbelsare/mogptk
We initialize the model with random parameters and show the spectral density of the kernel. As we are only taking random values, there is no relation with the data.
# create model model = mogptk.SM(data, Q=10) model.plot_spectrum(title='SD with random parameters');
_____no_output_____
MIT
examples/example_mauna_loa.ipynb
vishalbelsare/mogptk
Then we initialize the parameters before training, using Bayesian Nonparametric spectral estimation (BNSE) (Tobar 2017), and use the estimated Power spectral density (PSD) to define initial spectral mean and magnitudes.
method = 'BNSE' model.init_parameters(method) model.plot_spectrum(title='PSD with {} initialization'.format(method));
_____no_output_____
MIT
examples/example_mauna_loa.ipynb
vishalbelsare/mogptk
Then we train the model and show the power spectral density of the trained model.
model.log_marginal_likelihood() model.train(method='Adam', iters=1000, lr=0.1, plot=True, error='MAE') model.plot_spectrum(title='PSD with model trained');
Start Adam: 0/1000 loss= 322.484 error= 1.88645 10/1000 loss= 313.976 error= 1.88665 20/1000 loss= 307.505 error= 1.88656 30/1000 loss= 301.477 error= 1.88645 40/1000 loss= 295.067 error= 1.88634 50/1000 loss= 288.609 error= 1.88603 60/1000 loss= 282.216 er...
MIT
examples/example_mauna_loa.ipynb
vishalbelsare/mogptk
Lastly we predict in the test set.
model.predict() data.plot();
_____no_output_____
MIT
examples/example_mauna_loa.ipynb
vishalbelsare/mogptk
TensorFlow Neural Machine Translation on Cloud TPUsThis tutorial demonstrates how to translate text using a LSTM Network from one language to another (from English to German in this case). We will work with a dataset that contains pairs of English-German phrases. Given a sequence of words in English, we train a model ...
!ls !wget http://www.manythings.org/anki/deu-eng.zip !unzip deu-eng.zip !head deu.txt
Hi. Hallo! Hi. Grüß Gott! Run! Lauf! Wow! Potzdonner! Wow! Donnerwetter! Fire! Feuer! Help! Hilfe! Help! Zu Hülf! Stop! Stopp! Wait! Warte!
MIT
labs/Lab 5A - Neural Machine Translation on TPUs.ipynb
rish-16/machine-learning-workshop
Importing TensorFlow and other libraries
import string import numpy as np from numpy import array import pandas as pd import tensorflow as tf from tensorflow.keras.models import Sequential, load_model from tensorflow.keras.layers import Dense, Embedding, RepeatVector, LSTM from tensorflow.keras.optimizers import RMSprop from tensorflow.keras.preprocessing.tex...
_____no_output_____
MIT
labs/Lab 5A - Neural Machine Translation on TPUs.ipynb
rish-16/machine-learning-workshop
Extracting lines from dataset and into arrayHere, we can examine how the dataset is structures. The English-German dataset comprises of an English and German phrase separted by a tab `\t`
deu_eng = open('./deu.txt', mode='rt', encoding='utf-8') deu_eng = deu_eng.read() deu_eng = deu_eng.strip().split('\n') deu_eng = [i.split('\t') for i in deu_eng] deu_eng = array(deu_eng) deu_eng = deu_eng[:50000, :] print (deu_eng[:5])
[['Hi.' 'Hallo!'] ['Hi.' 'Grüß Gott!'] ['Run!' 'Lauf!'] ['Wow!' 'Potzdonner!'] ['Wow!' 'Donnerwetter!']]
MIT
labs/Lab 5A - Neural Machine Translation on TPUs.ipynb
rish-16/machine-learning-workshop
Removing punctuationWe will be removing punctuation from the phrases and converting them to lowercase. We will not be creating embeddings for punctuations or uppercase characters as it adds to the complexity of the NMT model
deu_eng[:, 0] = [s.translate((str.maketrans('', '', string.punctuation))) for s in deu_eng[:, 0]] deu_eng[:, 1] = [s.translate((str.maketrans('', '', string.punctuation))) for s in deu_eng[:, 1]] for i in range(len(deu_eng)): deu_eng[i, 0] = deu_eng[i, 0].lower() deu_eng[i, 1] = deu_eng[i, 1].lower() print (d...
[['hi' 'hallo'] ['hi' 'grüß gott'] ['run' 'lauf'] ['wow' 'potzdonner'] ['wow' 'donnerwetter']]
MIT
labs/Lab 5A - Neural Machine Translation on TPUs.ipynb
rish-16/machine-learning-workshop
Tokenising the phrasesTokenisation is the process of taking a sequence and chopping it up into smaller pieces called `tokens`. For example, suppose we have a sentence `"Bob returned home after the party"`The tokenised sentence will return an array with the tokens:`["Bob", "returned", "home", "after", "the", "party"]`I...
def tokenize(lines): tokenizer = Tokenizer() tokenizer.fit_on_texts(lines) return tokenizer eng_tokenizer = tokenize(deu_eng[:, 0]) eng_vocab_size = len(eng_tokenizer.word_index) + 1 eng_sequence_length = 8 print ('English vocabulary size: {}'.format(eng_vocab_size)) deu_tokenizer = tokenize(deu_...
English vocabulary size: 6352 German vocabulary size: 10678
MIT
labs/Lab 5A - Neural Machine Translation on TPUs.ipynb
rish-16/machine-learning-workshop
Convert lines into sequences as input for the NMT modelWe will now be using our Tokeniser to create tokenised sequences of the original English and German phrases from our dataset.
def encode_sequences(tokenizer, sequence_length, lines): sequence = tokenizer.texts_to_sequences(lines) sequence = pad_sequences(sequence, sequence_length, padding="post") # 0s after the actual sequence return sequence
_____no_output_____
MIT
labs/Lab 5A - Neural Machine Translation on TPUs.ipynb
rish-16/machine-learning-workshop
Splitting the dataset into training and testing sets
train, test = train_test_split(deu_eng, test_size=.2, random_state=12) x_train = encode_sequences(deu_tokenizer, deu_sequence_length, train[:, 1]) y_train = encode_sequences(eng_tokenizer, eng_sequence_length, train[:, 0]) x_test = encode_sequences(deu_tokenizer, deu_sequence_length, test[:, 1]) y_test = encode_seque...
(40000, 8) (40000, 8) (10000, 8) (10000, 8)
MIT
labs/Lab 5A - Neural Machine Translation on TPUs.ipynb
rish-16/machine-learning-workshop
Training on a TPUIn order to connect to a TPU, we can follow 4 easy steps:1. Connect to a TPU instance2. Initialise a parallelly-distributed training `strategy`3. Build our NMT model under the `strategy`4. Train the model on a TPUFor more details on training on TPUs for free, feel free to check out [this](https://medi...
tpu = tf.distribute.cluster_resolver.TPUClusterResolver() # TPU detection # Initialising a parallelly-distributed training strategy tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.experimental.TPUStrategy(tpu, steps_per_run=128) print('Running on TPU ', tpu.cluster_spec().as_dict()['worker']) ...
Epoch 1/30 500/500 [==============================] - 12s 23ms/step - loss: 2.2086 Epoch 2/30 500/500 [==============================] - 7s 15ms/step - loss: 1.7406 Epoch 3/30 500/500 [==============================] - 8s 15ms/step - loss: 1.5482 Epoch 4/30 500/500 [==============================] - 8s 16ms/step - loss...
MIT
labs/Lab 5A - Neural Machine Translation on TPUs.ipynb
rish-16/machine-learning-workshop
Checking the loss values
plt.plot(history.history['loss']) plt.xlabel('Epochs') plt.ylabel('Sparse Categorical Loss') plt.legend(['train']) plt.show()
_____no_output_____
MIT
labs/Lab 5A - Neural Machine Translation on TPUs.ipynb
rish-16/machine-learning-workshop
Running our model on testing dataset
# Getting the predictions from the testing dataset preds = model.predict_classes(x_test.reshape(x_test.shape[0], x_test.shape[1])[:10]) # only predicting over 10 instances print (preds) # A function to convert a sequence back into words def convert_words(n, tokenizer): for word, idx in tokenizer.word_index.items():...
_____no_output_____
MIT
labs/Lab 5A - Neural Machine Translation on TPUs.ipynb
rish-16/machine-learning-workshop
Translating the text from German to EnglishWe can see that our model does a relatively good job in translating the German text to English. However, there are instances that seem to have the wrong translation or are outright incorrect. Nonetheless, for a basic NMT model that was trained for 30 epochs, the model's gener...
pred_df = pd.DataFrame({'actual': test[:10, 0], 'prediction': pred_texts}) pred_df
_____no_output_____
MIT
labs/Lab 5A - Neural Machine Translation on TPUs.ipynb
rish-16/machine-learning-workshop
Daymet
from pynhd import NLDI import pydaymet as daymet import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore")
_____no_output_____
MIT
docs/examples/daymet.ipynb
DavidChoi76/hydrodata
The Daymet database provides climatology data at 1-km resolution. First, we use [PyNHD](https://github.com/cheginit/pynhd) to get the contributing watershed geometry of a NWIS station with the ID of `USGS-01031500`:
geometry = NLDI().getfeature_byid("nwissite", "USGS-01031500", basin=True).geometry[0]
_____no_output_____
MIT
docs/examples/daymet.ipynb
DavidChoi76/hydrodata
[PyDaymet](https://github.com/cheginit/pynhd) allows us to get the data for a single pixel or for a region as gridded data. The function to get single pixel is called `pydaymet.get_byloc` and for gridded data is called `pydaymet.get_bygeom`. Both have identical arguments where the first positional argument is a coordin...
variables = ["prcp", "tmin"] clm_g = daymet.get_bygeom(geometry, ("2000-01-01", "2000-01-31"), variables=variables, pet=True)
_____no_output_____
MIT
docs/examples/daymet.ipynb
DavidChoi76/hydrodata
Note that the default CRS is EPSG:4326. If the input geometry (or coordinate) is in a different CRS we can pass it to the function. The gridded data are automatically masked to the input geometry. Now, Let's get the data for a coordinate in EPSG:3542 CRS.
coords = (-1431147.7928, 318483.4618) crs = "epsg:3542" clm_p = daymet.get_byloc(coords, 2001, crs=crs, variables=variables, pet=True)
_____no_output_____
MIT
docs/examples/daymet.ipynb
DavidChoi76/hydrodata
Now, let's plot the data.
fig = plt.figure(figsize=(20, 8), dpi=300) gs = fig.add_gridspec(2, 2) ax = fig.add_subplot(gs[:, 0]) clm_g.prcp.isel(time=10).plot(ax=ax) ax.set_aspect("auto") axes = gs[:,1].subgridspec(2, 1, hspace=0).subplots(sharex=True) clm_p["tmin (deg c)"].plot(ax=axes[0], color="r") axes[0].set_ylabel("$T_{min}$ (deg C)") a...
_____no_output_____
MIT
docs/examples/daymet.ipynb
DavidChoi76/hydrodata
*Practical Data Science 19/20* Programming Assignment In this programming assignment you need to apply your new `numpy`, `pandas` and `matplotlib` knowledge. You will need to do several [`groupby`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html)s and [`join`](https://pandas.pydata....
import pandas as pd %matplotlib inline
_____no_output_____
MIT
Assignment_1.ipynb
NikoStein/_a2-template
Load Data
DATA_URL = 'https://raw.githubusercontent.com/pds1920/_a1-template/master/data/' transactions = pd.read_csv(DATA_URL + '/sales_train.csv.gz') items = pd.read_csv(DATA_URL + '/items.csv') item_categories = pd.read_csv(DATA_URL + '/item_categories.csv')
_____no_output_____
MIT
Assignment_1.ipynb
NikoStein/_a2-template
Get to know the dataPrint the **shape** of the loaded dataframes.- You can use a list comprehension here
# Write your code here
_____no_output_____
MIT
Assignment_1.ipynb
NikoStein/_a2-template
Use [`df.head`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.head.html) function to print several rows of each data frame. Examine the features you are given.
# Write your code here # Write your code here # Write your code here
_____no_output_____
MIT
Assignment_1.ipynb
NikoStein/_a2-template
Now use your `pandas` skills to get answers for the following questions. What was the maximum total revenue among all the shops in June, 2014?* Revenue refers to total sales minus value of goods returned.* Sometimes items are returned, find such examples in the dataset. * It is handy to split `date` field into [`day`...
# Write your code here max_revenue = # Write your code here max_revenue
_____no_output_____
MIT
Assignment_1.ipynb
NikoStein/_a2-template
How many items are there?* Let's assume, that the items are returned for the same price as they had been sold
num_items_constant_price = # Write your code here num_items_constant_price
_____no_output_____
MIT
Assignment_1.ipynb
NikoStein/_a2-template
What was the variance of the number of sold items per day sequence for the shop with `shop_id = 25` in December, 2014?* Do not count the items that were sold but returned back later.* Fill `total_num_items_sold`: An (ordered) array that contains the total number of items sold on each day * Fill `days`: An (ordered) ar...
shop_id = 25 # Write your code here total_num_items_sold = # Write your code here days = # Write your code here total_num_items_sold_var = # Write your code here total_num_items_sold_var
_____no_output_____
MIT
Assignment_1.ipynb
NikoStein/_a2-template
Vizualization of the daily items soldUse `total_num_items_sold` and `days` arrays to and plot the daily revenue of `shop_id = 25` in December, 2014.* plot-title: 'Daily items sold for shop_id = 25'
# Write your code here
_____no_output_____
MIT
Assignment_1.ipynb
NikoStein/_a2-template
What item category that generated the highest revenue in spring 2014? Spring is the period from March to Mai.
# Write your code here category_id_with_max_revenue =# Write your code here category_id_with_max_revenue
_____no_output_____
MIT
Assignment_1.ipynb
NikoStein/_a2-template
Demo Notebook for CPW Kappa Calculation Let's start by importing Qiskit Metal:
import qiskit_metal as metal from qiskit_metal import designs, draw from qiskit_metal import MetalGUI, Dict, open_docs
_____no_output_____
Apache-2.0
tutorials/6 Analysis/CPW_kappa_calculation_demo.ipynb
mtreinish/qiskit-metal