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
Priming and generating text Typically you'll want to prime the network so you can build up a hidden state. Otherwise the network will start out generating characters at random. In general the first bunch of characters will be a little rough since it hasn't built up a long history of characters to predict from.
def sample(net, size, prime='The', top_k=None): if(train_on_gpu): net.cuda() else: net.cpu() net.eval() # eval mode # First off, run through the prime characters chars = [ch for ch in prime] h = net.init_hidden(1) for ch in prime: char, h = predict(...
Annad and she samidad hit and the serstaly to would the had the ware a sompal it his warl on the him and and have to his all some the shings at a mile of thoughs. And he his are whrouther stell wouse as it her words with him had wounds, his the called wint, and wame to mare the witt the hed and andarisched a than the s...
Apache-2.0
Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb
sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course
Loading a checkpoint
# Here we have loaded in a model that trained over 20 epochs `rnn_20_epoch.net` with open('rnn_sayak_5.net', 'rb') as f: checkpoint = torch.load(f) loaded = CharRNN(checkpoint['tokens'], n_hidden=checkpoint['n_hidden'], n_layers=checkpoint['n_layers']) loaded.load_state_dict(checkpoint['state_dict']) # Sample ...
And Levin said." "The was wame that thet have and shy whis seid wost has as with the had havled, her was a shas to seall have the cond whor had thile to dere to to this toming and that were to the wourd of a derited his andad wom and whith the whas alladide thet and the wert the promass. The hessing he hive wos there...
Apache-2.0
Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb
sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course
Fine-tune T5 locally for machine translation on COVID-19 Health Service Announcements with Hugging Face[![Open in SageMaker Studio Lab](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/aws/studio-lab-examples/blob/main/natural-language-processing/NLP_Disaster_Recovery_Trans...
%%writefile requirements.txt ipywidgets git+https://github.com/huggingface/transformers datasets sacrebleu torch sentencepiece %pip install -r requirements.txt import IPython # make sure to restart your kernel to use the newly install packages # IPython.Application.instance().kernel.do_shutdown(True)
_____no_output_____
Apache-2.0
natural-language-processing/NLP_Disaster_Recovery_Translation.ipynb
dr-natetorious/studio-lab-examples
Step 1. Explore the available datasets on Translators without Borders Next, download a preferred language pair for training the translation model. This notebook chose English to Spanish, but you can select any two languages.- Overall site page: https://tico-19.github.io/- Page with all language pairs: https://tico-19....
path_to_my_data = 'https://tico-19.github.io/data/TM/all.en-es-LA.tmx.zip' !wget {path_to_my_data} local_file = path_to_my_data.split('/')[-1] print (local_file) filename = local_file.split('.zip')[0] print (filename) !unzip {local_file}
_____no_output_____
Apache-2.0
natural-language-processing/NLP_Disaster_Recovery_Translation.ipynb
dr-natetorious/studio-lab-examples
Step 2: Extract data from `.tmx` file type Next, you can use this local function to extract data from the `.tmx` file type and format for local training with Hugging Face.
# paste the name of your file and language codes here source_code_1 = 'en' target_code_2 = 'es' def parse_tmx(filename, source_code_1, target_code_2): ''' Takes a local TMX filename and codes for source and target languages. Walks through your file, row by row, looking for tmx / html specific formatting. ...
_____no_output_____
Apache-2.0
natural-language-processing/NLP_Disaster_Recovery_Translation.ipynb
dr-natetorious/studio-lab-examples
Step 3. Format extracted data for machine translation with Hugging FaceHugging Face’s translation module is documented on [GitHub](https://github.com/huggingface/transformers/tree/master/examples/pytorch/translation), and their official documentation also includes additional details for [loading the data set](https://...
import pandas as pd df = pd.read_csv('language_pairs.csv') df.head()
_____no_output_____
Apache-2.0
natural-language-processing/NLP_Disaster_Recovery_Translation.ipynb
dr-natetorious/studio-lab-examples
The translation task only supports custom [JSONLINES formatted files](https://jsonlines.org/). Each line is a dictionary with a key "translation" and its value another dictionary whose keys are the language pair. For example:```json{ "translation": { "en": "Others have dismissed him as a joke.", "ro": "Alții l-au numit...
objs = [] for idx, row in df.iterrows(): obj = {"translation": {source_code_1: row[source_code_1], target_code_2: row[target_code_2]}} objs.append(obj) objs[:5] import json !mkdir data with open('data/train.json', 'w') as f: for row in objs: j = json.dumps(row, ensure_ascii = False) ...
_____no_output_____
Apache-2.0
natural-language-processing/NLP_Disaster_Recovery_Translation.ipynb
dr-natetorious/studio-lab-examples
Step 4 - Finetune a machine translation model locallyFourth, download the raw Python file from Hugging Face to fine-tune your model.
!wget https://raw.githubusercontent.com/huggingface/transformers/master/examples/pytorch/translation/run_translation.py # full hugging face Trainer API args available here # https://github.com/huggingface/transformers/blob/de635af3f1ef740aa32f53a91473269c6435e19e/src/transformers/training_args.py # T5 trainig args avai...
_____no_output_____
Apache-2.0
natural-language-processing/NLP_Disaster_Recovery_Translation.ipynb
dr-natetorious/studio-lab-examples
Step 5. Test your newly fine-tuned translation model
from transformers import AutoTokenizer, AutoModelWithLMHead tokenizer = AutoTokenizer.from_pretrained("t5-small") model = AutoModelWithLMHead.from_pretrained(pretrained_model_name_or_path = 'output/tst-translation') # line to make sure your model supports local inference model.eval()
_____no_output_____
Apache-2.0
natural-language-processing/NLP_Disaster_Recovery_Translation.ipynb
dr-natetorious/studio-lab-examples
Fifth, let's test it! Remember that, in using the default settings of only three epochs, your translation is probably not going to be SOTA. For achieving state of the art, (SOTA), we recommend migrating to Amazon SageMaker to scale up and out. Scaling up means moving your code to more advanced compute types, such as th...
input_sequences = ['about how long have these symptoms been going on?', 'and all chest pain should be treated this way especially with your age ', 'and along with a fever ', 'and also needs to be checked your cholesterol blood pressure', 'and are you having a fever now? ', 'and are you having any of the following sym...
_____no_output_____
Apache-2.0
natural-language-processing/NLP_Disaster_Recovery_Translation.ipynb
dr-natetorious/studio-lab-examples
%matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd def load(): fremont_bridge = 'https://data.seattle.gov/api/views/65db-xm6k/rows.csv?accessType=DOWNLOAD' bicycle_weather = 'https://raw.githubusercontent.com/jakevdp/PythonDataScienceHandbook/master/notebooks/data/Bi...
_____no_output_____
MIT
LS_DS_243_Model_Interpretation_Assignment.ipynb
bkrant/DS-Unit-2-Sprint-4-Practicing-Understanding
![JohnSnowLabs](https://nlp.johnsnowlabs.com/assets/images/logo.png)[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/JohnSnowLabs/nlu/blob/master/examples/colab/component_examples/named_entity_recognition_(NER)/NLU_ner_CONLL_2003_5class_example.ipynb)...
!wget https://setup.johnsnowlabs.com/nlu/colab.sh -O - | bash import nlu
--2021-05-01 21:59:41-- https://raw.githubusercontent.com/JohnSnowLabs/nlu/master/scripts/colab_setup.sh Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133, 185.199.109.133, 185.199.108.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.110.133|:443... ...
Apache-2.0
nlu/colab/component_examples/named_entity_recognition_(NER)/NLU_ner_CONLL_2003_5class_example.ipynb
fcivardi/spark-nlp-workshop
NLU makes NER easy. You just need to load the NER model via ner.load() and predict on some dataset. It could be a pandas dataframe with a column named text or just an array of strings.
import nlu example_text = ["A person like Jim or Joe", "An organisation like Microsoft or PETA", "A location like Germany", "Anything else like Playstation", "Person consisting of multiple tokens like Angela Merkel or Donald Trump", "Organisations consisting of multiple tokens like JP Morgan", "Locations con...
_____no_output_____
Apache-2.0
nlu/colab/component_examples/named_entity_recognition_(NER)/NLU_ner_CONLL_2003_5class_example.ipynb
fcivardi/spark-nlp-workshop
Lets explore our data which the predicted NER tags and visalize them! We specify [1:] so we dont se the count for the O-tag wich is the most common, since most words in a sentence are not named entities and thus not part of a chunk
ner_df['entities'].value_counts()[1:].plot.bar(title='Occurence of Named Entity tokens in dataset') ner_type_to_viz = 'LOC' ner_df[ner_df.entities_class == ner_type_to_viz]['entities'].value_counts().plot.bar(title='Most often occuring LOC labeled tokens in the dataset') ner_type_to_viz = 'ORG' ner_df[ner_df.entities_c...
_____no_output_____
Apache-2.0
nlu/colab/component_examples/named_entity_recognition_(NER)/NLU_ner_CONLL_2003_5class_example.ipynb
fcivardi/spark-nlp-workshop
Calculate Mutual Information Values
num_cols = df.select_dtypes('number').columns.tolist() cat_cols = df.select_dtypes('object').columns.tolist() print(f'{len(num_cols)} numerical columns, {len(cat_cols)} categorical columns') cat_cols # encoding the categorical columns from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import O...
_____no_output_____
MIT
docs/Prelim Analysis.ipynb
Cemlyn/CreditRiskVAE
![PPGI_UFRJ](imagens/ppgi-ufrj.png) Fundamentos de Ciência de Dados ---[![DOI](https://zenodo.org/badge/335308405.svg)](https://zenodo.org/badge/latestdoi/335308405) --- PPGI/UFRJ 2020.3 Prof Sergio Serra e Jorge Zavaleta --- Módulo 2 - Numpy Avançado - Tensores Tensor>Um **tensor** é uma matriz **ndimensional** (narr...
# importando o pacote numpy import numpy as np
_____no_output_____
CC0-1.0
FCD_M2_1_Numpy_avancado.ipynb
zavaleta/Fundamentos_DS
Tensores básicos > Tensor escalar ou de categoria "0".> Um escalar contém um único valor e nenhum "eixo".
# tensor escalar rank_0_tensor = np.array(4,dtype=np.int64) print('T:',rank_0_tensor) print('R:',rank_0_tensor.shape)
_____no_output_____
CC0-1.0
FCD_M2_1_Numpy_avancado.ipynb
zavaleta/Fundamentos_DS
> Tensor de "vetor" ou categoria "1"> Lista de valores. Este tensor tem um eixo.
# tensor de vetor ou categoria 1 rank_1_tensor = np.array([2,3,4],dtype=np.float64) print('T:',rank_1_tensor) print('R:',rank_1_tensor.shape) # dimensão da matriz/vetor
_____no_output_____
CC0-1.0
FCD_M2_1_Numpy_avancado.ipynb
zavaleta/Fundamentos_DS
> Tensor de "Matriz" ou categoria 2> O tensor matriz tem dois eixos.
# tensor de matriz ou categoria 2 rank_2_tensor = np.array([[1,2],[3,4],[5,6]],dtype=np.float64) print('T:',rank_2_tensor) print('R:',rank_2_tensor.shape) # dimensão da matriz
_____no_output_____
CC0-1.0
FCD_M2_1_Numpy_avancado.ipynb
zavaleta/Fundamentos_DS
![TensoresBasicos](attachment:image.png)
# tensor de matriz pxqxr ou categoria 3 rank_3_tensor = np.array( [[[0, 1, 2, 3, 4],[5, 6, 7, 8, 9]], [[10, 11, 12, 13, 14],[15, 16, 17, 18, 19]], [[20, 21, 22, 23, 24],[25, 26, 27, 28, 29]]],dtype=np.float64) print('T:',rank_3_tensor) print('R:',rank_3_tensor.shap...
_____no_output_____
CC0-1.0
FCD_M2_1_Numpy_avancado.ipynb
zavaleta/Fundamentos_DS
![Tensor_rank_3](attachment:image.png) > Sobre as formas:> - **Forma** : O comprimento (número de elementos) de cada um dos eixos de um tensor.> - **Rank** : Número de eixos tensores. Um escalar tem posto 0, um vetor tem posto 1, uma matriz tem posto 2.> - **Eixo ou dimensão** : uma dimensão particular de um tensor.> ...
# exemplo de adicao de tensores # define o tensor A A = np.array([[[1,2,3], [4,5,6], [7,8,9]], [[11,12,13], [14,15,16], [17,18,19]], [[21,22,23], [24,25,26], [27,28,29]]]) print('Tensor A:') print(A) print('D:',A.shape) # define o tensor B B = np.array([[[1,2,3], [4,5,6], [7,8,9]], ...
_____no_output_____
CC0-1.0
FCD_M2_1_Numpy_avancado.ipynb
zavaleta/Fundamentos_DS
Subtração de Tensores> Os tensores devem pertencer à mesma categoria e ter as mesmas dimensões. A substração de tensores é outro tensor. O elemento solução é o resultado da operação entre elementos correspondentes dos tensores.
# tensor subtraction # define tensor A A = np.array([[[1,2,3], [4,5,6], [7,8,9]], [[11,12,13], [14,15,16], [17,18,19]], [[21,22,23], [24,25,26], [27,28,29]]]) print('Tensor A:') print(A) print('D:',A.shape) # define o tensor B B = np.array([[[1,2,3], [4,5,6], [7,8,9]], [[11,12,...
_____no_output_____
CC0-1.0
FCD_M2_1_Numpy_avancado.ipynb
zavaleta/Fundamentos_DS
Multiplicação de Tensores (hadamart*)> Os tensores devem pertencer à mesma categoria e ter as mesmas dimensões. O produto de tensores é outro tensor. O elemento solução é o resultado da operação entre elementos correspondentes dos tensores.
# define o tensor A A = np.array([[[1,2,3], [4,5,6], [7,8,9]], [[11,12,13], [14,15,16], [17,18,19]], [[21,22,23], [24,25,26], [27,28,29]]]) print('Tensor A:') print('D:',A.shape) print(A) # define tensor B B = np.array([[[1,2,3], [4,5,6], [7,8,9]], [[11,12,13], [14,15,16], [17,18,19]...
_____no_output_____
CC0-1.0
FCD_M2_1_Numpy_avancado.ipynb
zavaleta/Fundamentos_DS
Divisão de Tensores> Os tensores devem pertencer à mesma categoria e ter as mesmas dimensões. A divisão de tensores é outro tensor. O elemento solução é o resultado da operação entre elementos correspondentes dos tensores.
# define o tensor A A = np.array([[[1,2,3], [4,5,6], [7,8,9]], [[11,12,13], [14,15,16], [17,18,19]], [[21,22,23], [24,25,26], [27,28,29]]]) print('Tensor A:') print('D:',A.shape) print(A) # define o tensor B B = np.array([[[1,2,3], [4,5,6], [7,8,9]], [[11,12,13], [14,15,16], [17,...
_____no_output_____
CC0-1.0
FCD_M2_1_Numpy_avancado.ipynb
zavaleta/Fundamentos_DS
Produto de Tensores ($\otimes$)> O produto de tensores de dimensôes diferentes é otro tensor de dimensão (dim(T1)+dim(T2)). Seja o tensor A de **q** dimensões e o tensor B de **r** dimensões. O produto dos tensores C = $A \otimes B$ de **q+r** dimensões. O numpy usa a função **tensordot()** para calcular o tensor prod...
# produto de tensores # define tensor A (vetor) A = np.array([1,2]) print('Tensor A:') print('D:',A.shape) print(A) # define tensor B (vetor) B = np.array([3,4]) print('Tensor B:') print('D:',B.shape) print(B) # calculate tensor produto: C = A x B C = np.tensordot(A, B, axes=0) print('Tensor C:') print('D:',C.shape) p...
_____no_output_____
CC0-1.0
FCD_M2_1_Numpy_avancado.ipynb
zavaleta/Fundamentos_DS
TensorFlow> ![TensorFlow](attachment:image.png) > **TensorFlow** é uma biblioteca de aprendizado profundo (deep learning) desenvolvida pela Google. Ela fornece primitivas parafunções defininda em **tensores** e cálculos automaticos de suas operações derivadas. O que é um tensor?> Formalmente, os tensores são aplicaçõ...
# definir dois tensores em numpy Ta = np.zeros((2,2)) # tensor A Tb = np.ones((2,2)) # Tensor B print('DTa:',Ta.shape) # dimensão do tensor Ta print('Ta:') print(Ta) print('DTb:',Tb.shape) # dimensão do tensor Tb print('Tb:') print(Tb) sTb = np.sum(Tb, axis=1) # soma do tensor Tb, axis =1 (vetor) print('Soma Tb:...
_____no_output_____
CC0-1.0
FCD_M2_1_Numpy_avancado.ipynb
zavaleta/Fundamentos_DS
Exemplo em TensorFlow
# usando o tensorflow import tensorflow as tf # importar a biblioteca # sess = tf.compat.v1.InteractiveSession() # ativa a sessão para tensorflow 2.0 ou inferior # ta = tf.zeros((2,2), dtype = tf.float32) # cria o tenso a print('Tensor A:') print(ta) print() tb = t...
_____no_output_____
CC0-1.0
FCD_M2_1_Numpy_avancado.ipynb
zavaleta/Fundamentos_DS
---_You are currently looking at **version 1.1** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._--- Assignment 1In this assignm...
import pandas as pd import numpy as np import re doc = [] with open('dates.txt') as file: for line in file: doc.append(line) df = pd.Series(doc) list(df) #df.size ''' def date_sorter1(): # Your code here dates1 = [] dates2 = [] dates3 = [] for line in df: match = re.search...
_____no_output_____
MIT
4_Applied Text Mining in Python/Assignment 1.ipynb
Pankaj-Ra/Coursera-Data-Science-in-Python
Contextual Bandits data Load data
import pandas as pd df = pd.read_csv(r'test_data/cb/01.csv', parse_dates=['t']).set_index('t') df.head()
_____no_output_____
BSD-3-Clause
from_mwt_ds/DataScience/estimate.ipynb
cheng-tan/data-science
Apply estimators
from cb.estimators import ips_snips def init_ips_snips(r, p, p_log, n): result = ips_snips() result.add(r, p_log, p, n * int(p > 0)) return result policies = ['random', 'baseline1'] for p in policies: df[p] = df.apply(lambda r: init_ips_snips(r['r'], r[f"('b', '{p}')"], r['p'], r['n']), axis = 1) df...
_____no_output_____
BSD-3-Clause
from_mwt_ds/DataScience/estimate.ipynb
cheng-tan/data-science
Visualize
import matplotlib.pyplot as plt df.apply(lambda r: r['random'].get('snips'), axis=1).plot(label='random') df.apply(lambda r: r['baseline1'].get('snips'), axis=1).plot(label='baseline1') plt.legend(loc='best')
_____no_output_____
BSD-3-Clause
from_mwt_ds/DataScience/estimate.ipynb
cheng-tan/data-science
Reaggregate (if needed)
df = df.resample('10min').sum() df
_____no_output_____
BSD-3-Clause
from_mwt_ds/DataScience/estimate.ipynb
cheng-tan/data-science
Visualize
df.apply(lambda r: r['random'].get('snips'), axis=1).plot(label='random') df.apply(lambda r: r['baseline1'].get('snips'), axis=1).plot(label='baseline1') plt.legend(loc='best')
_____no_output_____
BSD-3-Clause
from_mwt_ds/DataScience/estimate.ipynb
cheng-tan/data-science
Conditional Contextual Bandits
import pandas as pd df = pd.read_pickle(r'test_data\ccb\01.pickle') df.head()
_____no_output_____
BSD-3-Clause
from_mwt_ds/DataScience/estimate.ipynb
cheng-tan/data-science
Understanding Factors in Animal Shelter Pet Adoption - Data StoryIn efforts to understand trends in pet adoption outcomes, the Austin Animal Center has provided data relating to the pets in their adoption center. Understanding this data and using it to model the factors that influence pet adoption could lead to recomm...
# For working with dataframes and manipulation import numpy as np import pandas as pd # Used to create and customize graphics/plots import matplotlib.pyplot as plt import matplotlib.patches as mpatches # Used to work with datetime and timedelta objects from datetime import datetime, timedelta # Load the formatted dat...
_____no_output_____
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
1. How Likely are adoptions for Cats vs. Dogs?It is very important to understand the general distributions of outcomes for cats and dogs, as well as the total number of each that the center recieves, in order to efficiently provide resources to shelter these animals. This section will break down the outcomes for both ...
# Separate dataset entries into those for cats and dogs cats = data[data['Animal Type'] == 'Cat'] dogs = data[data['Animal Type'] == 'Dog'] # Set figure and font size plt.subplots(figsize=(12, 7)) plt.rc('font', size=14) # Create pie chart for cat outcomes plt.subplot(1, 2, 1) cat_homes = [(cats['Found Home'] == 1).su...
_____no_output_____
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
We can see here that dogs are much more likely to have an outcome resulting in a permanent home than cats.We can also break these outcomes down further by their specific outcome type:
# Set figure and font size plt.subplots(figsize=(12, 10)) plt.rc('font', size=14) # Create pie chart for cat outcomes plt.subplot(1, 2, 1) cats['Outcome Type'].value_counts().plot(kind='pie', autopct='%1.1f%%', labels=None, ...
_____no_output_____
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
While numbers for adoption are similar for both cats and dogs, many more dogs are classified as 'Return to Owner' than cats, which denotes dogs that were lost and returned to their owners. A large majority of cats are transferred to other facilities, which may indicate that other facilities are either better equipped t...
# Separate Cats by Sex upon Outcome male_n = cats[cats['Sex upon Outcome'] == 'Neutered Male'] male_i = cats[cats['Sex upon Outcome'] == 'Intact Male'] female_s = cats[cats['Sex upon Outcome'] == 'Spayed Female'] female_i = cats[cats['Sex upon Outcome'] == 'Intact Female'] unknown = cats[cats['Sex upon Outcome'] == 'Un...
_____no_output_____
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
The distribution of outcomes for male and females in the cases of both cats and dogs shows that there is not a strong preference for either gender. Naturally, since animals are spayed and neutered when possible at animal shelters, most adoptions occur for these types rather than intact gender animals. ii. Age
# Convert ages to years cat_ages_in_years = cats['Age upon Outcome'].apply(lambda x: x//timedelta(days=365.25)) dog_ages_in_years = dogs['Age upon Outcome'].apply(lambda x: x//timedelta(days=365.25)) # Plot distribution of cat ages plt.subplots(figsize=(14,8)) plt.subplot(1, 2, 1) plt.hist(cat_ages_in_years, bins=23, ...
_____no_output_____
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
There seems to be a wide spread of ages for both cats and dogs, up to 22 years for cats and 20 years for dogs. Most of the animals are less than 4 years old in both cases. It would also be helpful to see the breakdown of outcomes for each of these age groups.
cat_ages_in_years[cats['Found Home'] == 0] # Plot distribution of cat ages for cats who found homes plt.subplots(figsize=(14,8)) plt.subplot(1, 2, 1) cats_fh_freq, cats_bins, _ = plt.hist(cat_ages_in_years[cats['Found Home'] == 1], bins=23, c...
_____no_output_____
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
As shown above, we can see that while all age groups have a higher frequency of dogs that are placed/returned to their homes, cats have a more complicated distribution. Both young ( 12 years old) seem to have mixed chances of being placed in a permanent home.One interesting note is that in both cases, the oldest animal...
# Generate Top 10 ranking breeds for cats by frequency top10_cat_breeds = pd.DataFrame(data= {'Cat Breed': cats['Breed'].value_counts().index.values[:10], '# of Cats': cats['Breed'].value_counts().values[:10]}, columns = ['Cat Breed', '# of Cats'], index=range(1,11) ...
10 Most Common Cat Breeds Cat Breed # of Cats Rank 1 Domestic Shorthair Mix 22773 2 Domestic Medium Hair Mix 2257 3 Domestic Longhair Mix 1204 4 Siamese Mix 997 5 Domestic Shorthair 378...
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
In both categories, we can see that mixed breeds are the most common. This is not surprising, though the distribution above shows that the breeds of dogs are much more varied than cats. The 10 most common breeds of dogs only account for about 58% of the total population of dogs that have gone through the center, but f...
plt.subplots(figsize=(14, 8)) # Create plot to show distribution of most common cat breeds by percent of total cats plt.subplot(1, 2, 1) (100*cats['Breed'].value_counts()[:10]/cats['Breed'].value_counts().sum()).plot(kind='bar', color='gold', edgecolor='k') plt.ylabel('% of Total Cats') plt.xlabel('Breed') plt.title('...
_____no_output_____
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
In the plot shown above, we can see that Domestic Shorthair mixed breeds in cats account for almost 80% of the cat entries alone. All entries in the most common cat breeds are mixed, since 'Domestic Shorthair' and 'Domestic Medium Hair' breeds are themselves mixed breed classifications.Next we can investigate the outco...
# Find percentage of cats that found homes by breed cat_breeds_fh = {} for breed in cats['Breed'].unique(): fh_temp = cats.loc[(cats['Found Home'] == 1) & (cats['Breed'] == breed)].shape[0] total_temp = cats.loc[cats['Breed'] == breed].shape[0] cat_breeds_fh[breed] = fh_temp/total_temp # Create ranking lis...
Cat Breeds with highest percentage of Homes Found Breed % of Breed that Found Home Rank 1 Turkish Van Mix 100.0 2 British Shorthair 100.0 3 Devon Rex Mix ...
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
All of the cat breeds with the highest percentages of placement in permanent homes represent breeds that are somewhat exotic when compared to the population that can be found in Austin, TX. We can also see that the Domestic Shorthair Mix that dominates the cat population in this dataset has a fairly low rate of adoptio...
# Find percentage of dogs that found homes by breed dog_breeds_fh = {} for breed in dogs['Breed'].unique(): fh_temp = dogs.loc[(dogs['Found Home'] == 1) & (dogs['Breed'] == breed)].shape[0] total_temp = dogs.loc[dogs['Breed'] == breed].shape[0] dog_breeds_fh[breed] = fh_temp/total_temp # Create ranking lis...
Dog Breeds with highest percentage of Homes Found Breed % of Breed that Found Home Rank 1 Affenpinscher Mix 100.0 2 Norfolk Terrier 100.0 3 Boerboel 100.0 4 ...
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
The distribution for dogs similarly shows that exotic breeds seem to occupy many of the top ranking spots for adoption rates, although the wide variety of dog breeds also shows that there are many breeds that don't fare well. This might indicate that breed alone is not a good enough indication of the chances of adoptio...
# Cat Breed vs. Mixed mixed_cats = cats[cats['Breed'].str.contains('Mix')]['Found Home'] pure_cats = cats[~cats['Breed'].str.contains('Mix')]['Found Home'] pure_cats_fh = 100*(pure_cats == 1).sum()/pure_cats.shape[0] mixed_cats_fh = 100*(mixed_cats == 1).sum()/mixed_cats.shape[0] # Dog Breed vs. Mixed mixed_dogs = do...
_____no_output_____
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
We can see that there are two opposing trends for cats and dogs here. For cats, purebreeds have a noticeably higher rate of adoption, while dogs see a drop in adoption rates for those that are not mixed breeds. This may be related to the high occurences of Domestic Shorthair cats at the center. When people come in to b...
# Most Common Colors plt.subplots(figsize=(14, 8)) # Create plot to show distribution of most common cat colors by percent of total cats plt.subplot(1, 2, 1) cat_colors=['brown', 'black', 'orange', 'lightsteelblue', 'white', 'lightsteelblue', 'saddlebrown', 'sandybrown', 'saddlebrown', 'wheat'] (100*cats['Primary Colo...
_____no_output_____
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
Above are the 10 most common colors for both cats and dogs. If we investigate the rates of placement in permanent homes by color, it may be possible to extract information on which color animals are preferred by people looking for pets at the Austin Animal Center.
## Find percentage of cats that found homes by primary color cat_colors_fh = {} for color in cats['Primary Color'].unique(): fh_temp = cats.loc[(cats['Found Home'] == 1) & (cats['Primary Color'] == color)].shape[0] total_temp = cats.loc[cats['Primary Color'] == color].shape[0] cat_colors_fh[color] = fh_temp...
_____no_output_____
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
The respective ranks in highest adoption rates for cats and dogs are denoted above the bars for each of the 10 most common colors. We can see again that none of the most common colors for both cats and dogs appear in their respective top lists of adoption rates. This further supports that a sense of exotic appearance o...
# % of Homes Found vs. cats with secondary colors cats_secondary = cats[cats['Secondary Color'].notnull()] cats_no_secondary = cats[~cats['Secondary Color'].notnull()] cats_secondary_fh = 100*(cats_secondary['Found Home'] == 1).sum()/cats_secondary.shape[0] cats_no_secondary_fh = 100*(cats_no_secondary['Found Home'] =...
_____no_output_____
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
The data above shows that for both cats and dogs, a secondary color slightly improves the rates of adoption. Animals with distinctive color combinations in their coats may stand out more visually to potential pet owners. 3. Analysis of Adoption Outcomes vs. YearFinally, I will take a brief look at the trends of cat an...
print('The dataset covers a time period between {0} and {1}'.format(data['DateTime'].min(), data['DateTime'].max())) # Reset indices for cats and dogs cats.reset_index(drop=True, inplace=True) dogs.reset_index(drop=True, inplace=True) # Separate data into years and months cat_years = [] cat_months = [] for cat in ca...
_____no_output_____
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
The graph above shows the average rates of placement in permanent homes for cats and dogs broken down by year. Although dogs have experienced a relative upward trend with time, cats seem to show a drop in rates from 2013 to 2014, but then the same relative upward trend. This may be an anomaly of our dataset, since we o...
# cat outcomes vs. year cat_month_fh = [] for month in range(1,13): cat_month = 100*(cats[cat_months == month]['Found Home'] == 1).sum()/(cats[cat_months == month].shape[0]) cat_month_fh.append(cat_month) # dog outcomes vs. year dog_month_fh = [] for month in range(1,13): dog_month = 100*(dogs[dog_months...
_____no_output_____
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
By looking at the average adoption rates broken down by month we can see that for both cats and dogs, there seems to be spikes in adoptions around winter months (Nov. - Feb.) and summer months (Jun. - Aug.). The main difference here is that cats seem to have a much stronger dependence on the month of the year than dogs...
# cat outcomes vs. year cat_monthyear_fh = [] for year in range(2014,2018): for month in range(1,13): cat_month = 100*(cats.loc[(cat_years == year) & (cat_months == month)]['Found Home'] == 1).sum()/(cats.loc[(cat_years == year) & (cat_months == month)].shape[0]) cat_monthyear_fh.append(cat_month) ...
_____no_output_____
Apache-2.0
Capstone Project 1/Data Story - Pet Adoption.ipynb
emenriquez/Springboard-Coursework
Cirq to Tensor NetworksHere we demonstrate turning circuits into tensor network representations of the circuit's unitary, final state vector, final density matrix, and final noisy density matrix. Imports
import cirq import numpy as np import pandas as pd from cirq.contrib.svg import SVGCircuit import cirq.contrib.quimb as ccq import quimb import quimb.tensor as qtn
_____no_output_____
Apache-2.0
cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb
anonymousr007/Cirq
Create a random circuit
qubits = cirq.LineQubit.range(3) circuit = cirq.testing.random_circuit(qubits, n_moments=10, op_density=0.8, random_state=52) circuit = cirq.drop_empty_moments(circuit) SVGCircuit(circuit)
_____no_output_____
Apache-2.0
cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb
anonymousr007/Cirq
Circuit to TensorsThe circuit defines a tensor network representation. By default, the initial state is the `|0...0>` state (represented by the "zero qubit" operations labeled "Q0" in the legend. "Q1" are single qubit operations and "Q2" are two qubit operations. The open legs are the indices into the state vector and...
tensors, qubit_frontier, fix = ccq.circuit_to_tensors(circuit, qubits) tn = qtn.TensorNetwork(tensors) print(qubit_frontier) from matplotlib import pyplot as plt tn.graph(fix=fix, color=['Q0', 'Q1', 'Q2'], figsize=(8,8))
_____no_output_____
Apache-2.0
cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb
anonymousr007/Cirq
To dense
psi_tn = ccq.tensor_state_vector(circuit, qubits) psi_cirq = cirq.final_state_vector(circuit, qubit_order=qubits) np.testing.assert_allclose(psi_cirq, psi_tn, atol=1e-7)
_____no_output_____
Apache-2.0
cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb
anonymousr007/Cirq
Circuit UnitaryWe can also leave the input legs open which gives a tensor network representation of the unitary
tensors, qubit_frontier, fix = ccq.circuit_to_tensors(circuit, qubits, initial_state=None) tn = qtn.TensorNetwork(tensors) print(qubit_frontier) tn.graph(fix=fix, color=['Q0', 'Q1', 'Q2'], figsize=(8, 8))
_____no_output_____
Apache-2.0
cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb
anonymousr007/Cirq
To dense
u_tn = ccq.tensor_unitary(circuit, qubits) u_cirq = circuit.unitary(qubit_order=qubits) np.testing.assert_allclose(u_cirq, u_tn, atol=1e-7)
_____no_output_____
Apache-2.0
cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb
anonymousr007/Cirq
Density MatrixWe can also turn a circuit into its density matrix. The density matrix resulting from the evolution of the `|0><0|` initial state can be thought of as two copies of the circuit: one going "forwards" and one going "backwards" (i.e. use the complex conjugate of each operation). Kraus operator noise operati...
tensors, qubit_frontier, fix = ccq.circuit_to_density_matrix_tensors(circuit=circuit, qubits=qubits) tn = qtn.TensorNetwork(tensors) tn.graph(fix=fix, color=['Q0', 'Q1', 'Q2'])
_____no_output_____
Apache-2.0
cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb
anonymousr007/Cirq
NoiseNoise operations entangle the forwards and backwards evolutions. The new tensors labeled "kQ1" are 1-qubit Kraus operators.
noise_model = cirq.ConstantQubitNoiseModel(cirq.DepolarizingChannel(p=1e-3)) circuit = cirq.Circuit(noise_model.noisy_moments(circuit.moments, qubits)) SVGCircuit(circuit) tensors, qubit_frontier, fix = ccq.circuit_to_density_matrix_tensors(circuit=circuit, qubits=qubits) tn = qtn.TensorNetwork(tensors) tn.graph(fix=fi...
_____no_output_____
Apache-2.0
cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb
anonymousr007/Cirq
For 6 or fewer qubits, we specify the contraction ordering.For low-qubit-number circuits, a reasonable contraction ordering is to go in moment order (as a normal simulator would do). Otherwise, quimb will try to find an optimal ordering which was observed to take longer than it takes to do the contraction itself. We s...
partial = 12 tags_seq = [(f'i{i}b', f'i{i}f') for i in range(partial)] tn.graph(fix=fix, color = [x for x, _ in tags_seq] + [y for _, y in tags_seq], figsize=(8, 8))
_____no_output_____
Apache-2.0
cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb
anonymousr007/Cirq
The result of a partial contraction
tn2 = tn.contract_cumulative(tags_seq, inplace=False) tn2.graph(fix=fix, color=['Q0', 'Q1', 'Q2', 'kQ1'], figsize=(8, 8))
_____no_output_____
Apache-2.0
cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb
anonymousr007/Cirq
To Dense
rho_tn = ccq.tensor_density_matrix(circuit, qubits) rho_cirq = cirq.final_density_matrix(circuit, qubit_order=qubits) np.testing.assert_allclose(rho_cirq, rho_tn, atol=1e-5)
_____no_output_____
Apache-2.0
cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb
anonymousr007/Cirq
ProfileFor low-qubit-number, deep, noisy circuits, the quimb contraction is faster.
import timeit def profile(n_qubits: int, n_moments: int): qubits = cirq.LineQubit.range(n_qubits) circuit = cirq.testing.random_circuit(qubits, n_moments=n_moments, op_density=0.8) noise_model = cirq.ConstantQubitNoiseModel(cirq.DepolarizingChannel(p=1e-3)) circuit = cirq.Circuit(noise_model.noisy_mome...
_____no_output_____
Apache-2.0
cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb
anonymousr007/Cirq
MNIST Dataset NotebookThe MNIST dataset is a dataset that is built up of hand written digits derived from the NIST dataset. It is used for people to derive machine learning models for pattern recognition from a real world set of data. The MNIST data set is widely used for training image recognition classifiers. The da...
%%html <style> table { display: inline-block } </style>
_____no_output_____
MIT
mnist-dataset.ipynb
lanodburke/Emerging-Technologies-Project
MNIST Dataset File format> All the integers in the files are stored in the MSB first (high endian) format used by most non-Intel processors. Users of Intel processors and other low-endian machines must flip the bytes of the header.The MNIST dataset is stored with the IDX file format extension. The IDX file format is a...
import gzip # Open zip file with gzip with gzip.open('data/t10k-images-idx3-ubyte.gz', 'rb') as f: file_content = f.read() # Read in first 4 bytes which we know is the magic number # Convert bytes to int with big endian byte order (most intel CPUs are big endian) magic = int.from_bytes(file_content[0:4], byt...
Magic number: 2051 Number of images: 10000 Number of rows: 28 Number of columns: 28
MIT
mnist-dataset.ipynb
lanodburke/Emerging-Technologies-Project
Display an ImageWe will use the matplotlib.pyplot package and the numpy package to display the first image in the dataset. The first image in the dataset is known to be a 7. We can see this by the plot below but can also validate this when we read in the labels from the labels file.
%matplotlib inline import matplotlib.pyplot as plt import numpy as np # flip the bytes from black/white with tilda(~). image = ~np.array(list(file_content[16:800])).reshape(28,28).astype(np.uint8) # use the imshow method and map the image to gray scale plt.imshow(image, cmap='gray')
_____no_output_____
MIT
mnist-dataset.ipynb
lanodburke/Emerging-Technologies-Project
Read labels
with gzip.open('data/t10k-labels-idx1-ubyte.gz', 'rb') as f: labels = f.read() magic = int.from_bytes(labels[0:4], byteorder="big") print("Magic number is: ", magic) # Read in number of labels num_labels = int.from_bytes(labels[4:8], byteorder="big") print("Number of labels: ", num_labels) # Finally read in the ...
Magic number is: 2049 Number of labels: 10000 First label: 7
MIT
mnist-dataset.ipynb
lanodburke/Emerging-Technologies-Project
Read entire dataset into memoryTo read the dataset into memory we will use gzip as described above. We will then reshape the files into a format that can be used by our model by normalizing the inputs and one-hot encoding the outputs (labels).
import gzip # Read in entire training set with gzip with gzip.open('data/train-images-idx3-ubyte.gz', 'rb') as f: train_img = f.read() # Read in training labels with gzip.open('data/train-labels-idx1-ubyte.gz', 'rb') as f: train_labels = f.read() # Read in training images # Convert images from black backgrou...
_____no_output_____
MIT
mnist-dataset.ipynb
lanodburke/Emerging-Technologies-Project
Build a simple modelWe will build a simple linear model with keras. The model will have an input layer of 784 (number of pixels in a single image) represents an image with dimensions 28 x 28. We will read in all 784 pixels as we reshaped the input array into a two dimensional vector with the dimesionsions 60,000 x 784...
# For building neural networks. import keras as kr # For interacting with data sets. import pandas as pd # For encoding categorical variables. import sklearn.preprocessing as pre # For splitting into training and test sets. import sklearn.model_selection as mod # Use keras Sequential model model = kr.models.Sequent...
_____no_output_____
MIT
mnist-dataset.ipynb
lanodburke/Emerging-Technologies-Project
One Hot encodingOne Hot encoding is a pre proccessing process for data that is used for ML algorithms. It is mainly used for categorical data such as the MNIST dataset. One hot encoding is used because a majority of ML algorithms as they cannot use label data and they can only read data in a numeric format.In this exa...
# Encode the classes as above. encoder = pre.LabelBinarizer() encoder.fit(train_labels) # One hot encode output labels outputs = encoder.transform(train_labels) # first digit is 5, represented by the 6th position in array with value 1 print(train_labels[0], outputs[0])
5 [0 0 0 0 0 1 0 0 0 0]
MIT
mnist-dataset.ipynb
lanodburke/Emerging-Technologies-Project
Example of One hot encoding
# Example of one-hot encoding values from 1-10 for i in range(10): print(i, encoder.transform([i]))
0 [[1 0 0 0 0 0 0 0 0 0]] 1 [[0 1 0 0 0 0 0 0 0 0]] 2 [[0 0 1 0 0 0 0 0 0 0]] 3 [[0 0 0 1 0 0 0 0 0 0]] 4 [[0 0 0 0 1 0 0 0 0 0]] 5 [[0 0 0 0 0 1 0 0 0 0]] 6 [[0 0 0 0 0 0 1 0 0 0]] 7 [[0 0 0 0 0 0 0 1 0 0]] 8 [[0 0 0 0 0 0 0 0 1 0]] 9 [[0 0 0 0 0 0 0 0 0 1]]
MIT
mnist-dataset.ipynb
lanodburke/Emerging-Technologies-Project
Fit the model
# Fit the model with inputs and outputs set number of epochs to 1 and batch size to 100 model.fit(inputs, outputs, epochs=10, batch_size=200)
Epoch 1/10 60000/60000 [==============================] - 10s 172us/step - loss: 14.5262 - acc: 0.0988 Epoch 2/10 60000/60000 [==============================] - 9s 144us/step - loss: 14.5270 - acc: 0.0987 Epoch 3/10 60000/60000 [==============================] - 9s 149us/step - loss: 14.5270 - acc: 0.0987 Epoch 4/10 60...
MIT
mnist-dataset.ipynb
lanodburke/Emerging-Technologies-Project
Test modelTo test the model that we created we will read in the test images and labels files with gzip.
with gzip.open('data/t10k-images-idx3-ubyte.gz', 'rb') as f: test_img = f.read() with gzip.open('data/t10k-labels-idx1-ubyte.gz', 'rb') as f: test_lbl = f.read() test_img = ~np.array(list(test_img[16:])).reshape(10000, 784).astype(np.uint8) / 255.0 test_lbl = np.array(list(test_lbl[ 8:])).astype(np.uint8...
_____no_output_____
MIT
mnist-dataset.ipynb
lanodburke/Emerging-Technologies-Project
Model accuracy
acc = (encoder.inverse_transform(model.predict(test_img)) == test_lbl).sum() print("Accuracy: %.0f%%" % (acc / 100))
Accuracy: 10%
MIT
mnist-dataset.ipynb
lanodburke/Emerging-Technologies-Project
#@title Students'Grade in OOP student_name = "Ericka Jane A. Alegre" #@param {type:"string"} prelim = 96#@param {type:'number'} midterm = 98#@param {type:'number'} final = 98#@param {type:'number'} semestral_grade = round((prelim + midterm+ final)/3,2) print("My prelim grade is " + str(prelim)) print("My midterm grade...
My prelim grade is 96 My midterm grade is 98 My final grade is 98 My semestral grade is: 97.33 My birthdate is: 2003-11-24
Apache-2.0
GUI.ipynb
erickaalgr/OOP-1-1
Import Dependencies
# COCO related libraries from samples.coco import coco # MaskRCNN libraries from mrcnn.config import Config import mrcnn.utils as utils from mrcnn import visualize import mrcnn.model as modellib # Misc import os import sys import json import numpy as np import time from PIL import Image, ImageDraw
Using TensorFlow backend.
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Constants
# Number of classes in dataset. Must be of type integer NUM_CLASSES = 3 # Relative path to .h5 weights file WEIGHTS_FILE = None # Relative path to annotations JSON file TRAIN_ANNOTATIONS_FILE = "datasets/Downtown_Sliced/train/annotations_split.json" # Relative path to directory of images that pertain to annotations ...
_____no_output_____
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Additional setup
# Set the ROOT_DIR variable to the root directory of the Mask_RCNN git repo ROOT_DIR = os.getcwd() # Directory to save logs and trained model MODEL_DIR = os.path.join(ROOT_DIR, "logs") # Select which GPU to use os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"; os.environ["CUDA_VISIBLE_DEVICES"]="0";
_____no_output_____
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Declare training configuration
class TrainConfig(coco.CocoConfig): """ """ # Give the configuration a recognizable name NAME = MODEL_NAME # Train on 1 image per GPU. Batch size is 1 (GPUs * images/GPU). GPU_COUNT = 1 IMAGES_PER_GPU = 1 # Number of classes (including background) NUM_CLASSES = 1 + NUM_CLASSES ...
_____no_output_____
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Display configuration
TrainConfig().display()
Configurations: BACKBONE resnet101 BACKBONE_STRIDES [4, 8, 16, 32, 64] BATCH_SIZE 1 BBOX_STD_DEV [0.1 0.1 0.2 0.2] COMPUTE_BACKBONE_SHAPE None DETECTION_MAX_INSTANCES 114 DETECTION_MIN_CONFIDENCE 0.1 DETECTION_NMS_THRESHOLD ...
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Create class to load dataset
class CocoLikeDataset(utils.Dataset): """ Generates a COCO-like dataset, i.e. an image dataset annotated in the style of the COCO dataset. See http://cocodataset.org/#home for more information. """ def load_data(self, annotation_json, images_dir): """ Load the coco-like dataset from json ...
_____no_output_____
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Load train and validation datasets
dataset_train = CocoLikeDataset() dataset_train.load_data(TRAIN_ANNOTATIONS_FILE, TRAIN_ANNOTATION_IMAGE_DIR) dataset_train.prepare() dataset_val = CocoLikeDataset() dataset_val.load_data(VALIDATION_ANNOTATIONS_FILE, VALIDATION_ANNOTATION_IMAGE_DIR) dataset_val.prepare()
_____no_output_____
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Build MaskRCNN Model
# Create model in training mode model = modellib.MaskRCNN(mode = "training", config = TrainConfig(), model_dir = MODEL_DIR)
WARNING: Logging before flag parsing goes to stderr. W0805 20:55:55.028046 139871543367488 deprecation_wrapper.py:119] From /home/venv/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:508: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. W0805 20:55:55.066967 139871543...
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Load weights into model if weights file is not None This is meant to be used if you are refining on a set of preexisting weights
if WEIGHTS_FILE is not None: model.load_weights(WEIGHTS_FILE, by_name = True)
_____no_output_____
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Train model The model after each epoch will be saved in the logs folder
start_train = time.time() model.train(dataset_train, dataset_val, learning_rate = TrainConfig().LEARNING_RATE, epochs = NUM_EPOCHS, layers = 'all') end_train = time.time() minutes = round((end_train - start_train) / 60, 2) print(f'Training took {minutes} minutes')
Starting at epoch 0. LR=0.001 Checkpoint Path: /home/logs/model_220190805T2055/mask_rcnn_model_2_{epoch:04d}.h5 Selecting layers to train conv1 (Conv2D) bn_conv1 (BatchNorm) res2a_branch2a (Conv2D) bn2a_branch2a (BatchNorm) res2a_branch2b (Conv2D) bn2a_branch2b ...
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Include evaluation scripts in training script so that the kernel does not have to be reloaded. Eases the process of rapidly training and evaluating models Import dependencies
# COCO related libraries from pycocotools.cocoeval import COCOeval from pycocotools import mask as maskUtils from samples.coco import coco from samples.coco.coco import evaluate_coco from pycocotools.coco import COCO # MaskRCNN libraries import mrcnn.model as modellib import mrcnn.utils as utils import mrcnn.visualize...
_____no_output_____
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Declare evaluation configuration
class EvalConfig(coco.CocoConfig): """ Configuration for evaluation """ # Give the configuration a recognizable name NAME = MODEL_NAME # How many GPUs GPU_COUNT = 1 # How many images per gpu IMAGES_PER_GPU = 1 # Number of classes (including background) NUM_CLASSES = 1...
_____no_output_____
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Display configuration
EvalConfig().display()
Configurations: BACKBONE resnet101 BACKBONE_STRIDES [4, 8, 16, 32, 64] BATCH_SIZE 1 BBOX_STD_DEV [0.1 0.1 0.2 0.2] COMPUTE_BACKBONE_SHAPE None DETECTION_MAX_INSTANCES 114 DETECTION_MIN_CONFIDENCE 0.1 DETECTION_NMS_THRESHOLD ...
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Build class to load ground truth data
class CocoDataset(utils.Dataset): def load_coco_gt(self, annotations_file, dataset_dir): """Load a COCO styled ground truth dataset """ # Create COCO object coco = COCO(annotations_file) # Load all classes class_ids = sorted(coco.getCatIds()) # Load...
_____no_output_____
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Build MaskRCNN Model
# Create the model in inference mode model = modellib.MaskRCNN(mode = "inference", config = EvalConfig(), model_dir = MODEL_DIR)
W0806 02:20:35.781523 139871543367488 deprecation_wrapper.py:119] From /home/venv/src/mask-rcnn/mrcnn/model.py:720: The name tf.sets.set_intersection is deprecated. Please use tf.sets.intersection instead. W0806 02:20:35.898080 139871543367488 deprecation.py:323] From /home/venv/src/mask-rcnn/mrcnn/model.py:772: to_fl...
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Load weights from last trained model
# Load weights by name model.load_weights(model.find_last(), by_name = True)
Re-starting from epoch 80
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Load dataset
# Relative path to ground truth annotations JSON file GT_ANNOTATIONS_FILE = "datasets/Downtown_Sliced/test/annotations_split.json" # Relative path to images associated with ground truth JSON file GT_DATASET_DIR = "datasets/Downtown_Sliced/test/images" dataset_val = CocoDataset() coco = dataset_val.load_coco_gt(annota...
loading annotations into memory... Done (t=1.24s) creating index... index created!
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Evaluate model with COCO test If your results come back as a bunch of zeros, check to make sure that the "width" and "height" tag in your COCO dataset are correct
evaluate_coco(model, dataset_val, coco, "segm")
_____no_output_____
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Calculating mAP as per example in train_shapes.ipynb
# Compute VOC-Style mAP @ IoU=0.5 # Running on 10 images. Increase for better accuracy. image_ids = np.random.choice(dataset_val.image_ids, len(dataset_val.image_ids)) # Instanciate arrays to create our metrics APs = [] precisions_arr = [] recalls_arr = [] overlaps_arr = [] class_ids_arr = [] scores_arr = [] for id i...
_____no_output_____
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
Plot precision recall curve
visualize.plot_precision_recall(AP, precisions, recalls)
_____no_output_____
Apache-2.0
Train.ipynb
MrDemeanor/AerialPipeline
#authenticatiopn script in gcp !apt-get install -y -qq software-properties-common python-software-properties module-init-tools !apt-get install software-properties-common !apt-get install -y -qq software-properties-common module-init-tools !apt-get install -y -qq python-software-properties module-init-tools !add-ap...
_____no_output_____
MIT
FileOperations.ipynb
DannyML-DSC/Hash-analytics
Making a version of *Quantum Rogues*[*Quantum Rogues*](https://github.com/qiskit-community/qiskit-camp-europe-19/issues/5) was a game created at the [Qiskit Camp Europe](https://qiskit.camp/europe/) hackathon in September 2019. In this notebook we create a new game, which takes the basic idea of the original *Quantum ...
%matplotlib notebook
_____no_output_____
Apache-2.0
versions/MicroPython/tutorials/Quantum-Rogues.ipynb
TigrisCallidus/MicroQiskit
In this game, the player controls a flying avatar that can move around a room. I think of it as a bat - a qubat, in fact - but you can interpret it as you wish.First we simply create the room and the bat, and set up the controls. The **O** button makes the bat flap its wings. The ◀︎ and ► buttons move left and right.
import pew pew.init() screen = pew.Pix() # create a border of B=2 pixels for A in range(8): for B in [0,7]: screen.pixel(A,B,2) screen.pixel(B,A,2) # the player is a B=3 pixel X,Y = 4,6 screen.pixel(X,Y,3) while True: # loop which checks for user input and responds # use key presses to det...
_____no_output_____
Apache-2.0
versions/MicroPython/tutorials/Quantum-Rogues.ipynb
TigrisCallidus/MicroQiskit
Each room will have doors, through which it can move to neighbouring rooms. There are four possible doors: one in each direction.Whether a door is open or closed is generated randomly from a two qubit quantum circuit. The left door depends on the result from one of the qubits when a z measurement is made: `0` for open ...
import pew from microqiskit import * pew.init() screen = pew.Pix() # set positions of doors l = (0,4) r = (7,4) u = (3,0) d = (3,7) doors = [l,r,u,d] # create a border of B=2 pixels for A in range(8): for B in [0,7]: screen.pixel(A,B,2) screen.pixel(B,A,2) # the player is a B=3 pixel X,Y = 4,6 ...
_____no_output_____
Apache-2.0
versions/MicroPython/tutorials/Quantum-Rogues.ipynb
TigrisCallidus/MicroQiskit
Obviously what *should* happen when you pass through a door is that you end up in another room. This is implemented in the program below. The new room will again has open and closed doors, generated randomly by the circuit.
import pew from microqiskit import * pew.init() screen = pew.Pix() # set positions of doors l = (0,4) r = (7,4) u = (3,0) d = (3,7) doors = [l,r,u,d] # create a border of B=2 pixels for A in range(8): for B in [0,7]: screen.pixel(A,B,2) screen.pixel(B,A,2) # the player is a B=3 pixel X,Y = 4,6 ...
_____no_output_____
Apache-2.0
versions/MicroPython/tutorials/Quantum-Rogues.ipynb
TigrisCallidus/MicroQiskit