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
MXNet Model ObjectThe `MXNetModel` class allows you to define an environment for making inference using yourmodel artifact. Like `MXNet` class we discussed [in this notebook for training an MXNet model](get_started_mnist_train.ipynb), it is high level API used to set up a docker image for your model hosting service.On...
model = MXNetModel( entry_point="inference.py", source_dir="code", role=role, model_data=mx_mnist_model_data, framework_version="1.7.0", py_version="py3", )
_____no_output_____
Apache-2.0
frameworks/mxnet/get_started_mnist_deploy.ipynb
Amirosimani/amazon-sagemaker-examples
Entry Point for the Inference ImageYour model artifacts pointed by `model_data` is pulled by the `MXNetModel` and it is decompressed and saved inin the docker image it defines. They become regular model checkpoint files that you would produce outside SageMaker. This means in order to use your trained model for serving...
from sagemaker.serializers import JSONSerializer from sagemaker.deserializers import JSONDeserializer # set local_mode to False if you want to deploy on a remote # SageMaker instance local_mode = False if local_mode: instance_type = "local" else: instance_type = "ml.c4.xlarge" predictor = model.deploy( ...
_____no_output_____
Apache-2.0
frameworks/mxnet/get_started_mnist_deploy.ipynb
Amirosimani/amazon-sagemaker-examples
The `predictor` we get above can be used to make prediction requests agaist a SageMaker endpoint. For moreinformation, check [the api reference for SageMaker Predictor](https://sagemaker.readthedocs.io/en/stable/api/inference/predictors.htmlsagemaker.predictor.Predictor)Now, let's test the endpoint with some dummy data...
import random dummy_data = {"inputs": [random.random() for _ in range(784)]}
_____no_output_____
Apache-2.0
frameworks/mxnet/get_started_mnist_deploy.ipynb
Amirosimani/amazon-sagemaker-examples
In `transform_fn`, we declared that the parsed data is a python dictionary with a key `inputs` and its value should be a 1D array of length 784. Hence, the definition of `dummy_data`.
res = predictor.predict(dummy_data) print("Predicted digit:", *map(int, res))
_____no_output_____
Apache-2.0
frameworks/mxnet/get_started_mnist_deploy.ipynb
Amirosimani/amazon-sagemaker-examples
If the input data does not look exactly like `dummy_data`, the endpoint will raise an exception. This is because of the stringent way we defined the `transform_fn`. Let's test the following example.
dummy_data = [random.random() for _ in range(784)]
_____no_output_____
Apache-2.0
frameworks/mxnet/get_started_mnist_deploy.ipynb
Amirosimani/amazon-sagemaker-examples
When the `dummy_data` is parsed in `transform_fn`, it does not have an `inputs` field, so `transform_fn` will crush.
# uncomment the following line to make inference on incorrectly formated input data # res = predictor.predict(dummy_data)
_____no_output_____
Apache-2.0
frameworks/mxnet/get_started_mnist_deploy.ipynb
Amirosimani/amazon-sagemaker-examples
Now, let's use real MNIST test to test the endpoint. We use helper functions defined in `code.utils` to download MNIST data set and normalize the input data.
import random import boto3 import matplotlib.pyplot as plt import os import numpy as np import gzip import json %matplotlib inline # Donwload MNIST test set from a public bucket with open("code/config.json", "rb") as f: CONFIG = json.load(f) fname = "t10k-images-idx3-ubyte.gz" bucket = CONFIG["public_bucket"] ke...
_____no_output_____
Apache-2.0
frameworks/mxnet/get_started_mnist_deploy.ipynb
Amirosimani/amazon-sagemaker-examples
First, let us use the model to infer the samples one-by-one. This is the typical use casefor an online application.
# convert to float and normalize normalize the input def normalize(x, axis): eps = np.finfo(float).eps mean = np.mean(x, axis=axis, keepdims=True) # avoid division by zero std = np.std(x, axis=axis, keepdims=True) + eps return (x - mean) / std samples = normalize(samples.astype(np.float32), axis...
_____no_output_____
Apache-2.0
frameworks/mxnet/get_started_mnist_deploy.ipynb
Amirosimani/amazon-sagemaker-examples
Since in `transform_fn`, the parsed numpy array could have take on any value for its batchdimension, we can send the entire `samples` at once and let the model do a batch inference.
data = {"inputs": samples.tolist()} res = predictor.predict(data) print("Predictions: ", *map(int, res))
_____no_output_____
Apache-2.0
frameworks/mxnet/get_started_mnist_deploy.ipynb
Amirosimani/amazon-sagemaker-examples
Test and debug the entry point before deploymentWhen deploying a model to a SageMaker endpoint, it is a good practice to test the entry point. The following snippet shows you how you can test and debug the `model_fn` and `transform_fn` you implemented in the entry point for the inference image.
!pygmentize code/test_inference.py
_____no_output_____
Apache-2.0
frameworks/mxnet/get_started_mnist_deploy.ipynb
Amirosimani/amazon-sagemaker-examples
The `test` function simulates how the inference container works. It pulls the modelartifact and loads the model into memory by calling `model_fn` and parse it with `model_dir`. When it receives a request, it calls `transform_fn` and parse it with the loaded model, the payload of the request, request content type and re...
import os if not local_mode: predictor.delete_endpoint() else: # detach the inference container from port 8080 (in local mode) os.system("docker container ls | grep 8080 | awk '{print $1}' | xargs docker container rm -f")
_____no_output_____
Apache-2.0
frameworks/mxnet/get_started_mnist_deploy.ipynb
Amirosimani/amazon-sagemaker-examples
Nova Tarefa - ExperimentoPreencha aqui com detalhes sobre a tarefa. **Em caso de dúvidas, consulte os [tutoriais da PlatIAgro](https://platiagro.github.io/tutorials/).** Declaração de parâmetros e hiperparâmetrosDeclare parâmetros com o botão na barra de ferramentas.O parâmetro `dataset` identifica os conjuntos de d...
dataset = "" #@param {type:"string"}
_____no_output_____
Apache-2.0
projects/config/Experiment.ipynb
Matheus158257/projects
Acesso ao conjunto de dadosO conjunto de dados utilizado nesta etapa será o mesmo carregado através da plataforma.O tipo da variável retornada depende do arquivo de origem:- [pandas.DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) para CSV e compressed CSV: .csv .csv.zip .cs...
import pandas as pd data = pd.read_csv(f'/tmp/data/{dataset}') data
_____no_output_____
Apache-2.0
projects/config/Experiment.ipynb
Matheus158257/projects
Acesso aos metadados do conjunto de dadosUtiliza a função `stat_dataset` do [SDK da PlatIAgro](https://platiagro.github.io/sdk/) para carregar metadados.Por exemplo, arquivos CSV possuem `metadata['featuretypes']` para cada coluna no conjunto de dados (ex: categorical, numerical, or datetime).
from platiagro import stat_dataset metadata = stat_dataset(name=dataset) metadata
_____no_output_____
Apache-2.0
projects/config/Experiment.ipynb
Matheus158257/projects
Conteúdo da tarefa
# adicione seu código aqui...
_____no_output_____
Apache-2.0
projects/config/Experiment.ipynb
Matheus158257/projects
Salva alterações no conjunto de dadosO conjunto de dados será salvo (e sobrescrito com as respectivas mudanças) localmente, no container da experimentação, utilizando a função `pandas.DataFrame.to_csv`.
df.to_csv(f'/tmp/data/{dataset}', index=False)
_____no_output_____
Apache-2.0
projects/config/Experiment.ipynb
Matheus158257/projects
Salva métricasUtiliza a função `save_metrics` do [SDK da PlatIAgro](https://platiagro.github.io/sdk/) para salvar métricas. Por exemplo: `accuracy`, `precision`, `r2_score`, `custom_score` etc.
from platiagro import save_metrics save_metrics(accuracy=0.5, custom_score=1000)
_____no_output_____
Apache-2.0
projects/config/Experiment.ipynb
Matheus158257/projects
Salva figurasUtiliza a função `save_figures` do [SDK da PlatIAgro](https://platiagro.github.io/sdk/) para salvar figuras do [matplotlib](https://matplotlib.org/3.2.1/gallery/index.html).
from platiagro import save_figures save_figures(figure=matplotfig)
_____no_output_____
Apache-2.0
projects/config/Experiment.ipynb
Matheus158257/projects
Salva modelo e outros artefatosUtiliza a função `save_model` do [SDK da PlatIAgro](https://platiagro.github.io/sdk/) para salvar modelos e outros artefatos.Essa função torna estes artefatos disponíveis para o notebook de implantação.
from platiagro import save_model save_model(model=model, other_artifact={"key": "value"})
_____no_output_____
Apache-2.0
projects/config/Experiment.ipynb
Matheus158257/projects
12-Web-Scraping-and-Document-DatabasesEric Nordstrom Setup
# dependencies from selenium import webdriver from bs4 import BeautifulSoup as BS import requests import pandas as pd # set up selenium driver driver = webdriver.Firefox()
_____no_output_____
ADSL
mission_to_mars.ipynb
eanord4/scraping-challenge
NASA Mars News
# get html to parse url = "https://mars.nasa.gov/news" driver.get(url) soup = BS(driver.page_source, "html.parser") # parse html item = soup.find('li', class_="slide") date = item.find('div', class_="list_date").text title_a = item.find('div', class_="content_title").a title = title_a.text href = title_a['href'] para ...
February 27, 2020 The MarCO Mission Comes to an End The pair of briefcase-sized satellites made history when they sailed past Mars in 2019. More: https://mars.nasa.gov/news/8408/the-marco-mission-comes-to-an-end/
ADSL
mission_to_mars.ipynb
eanord4/scraping-challenge
JPL Mars Space Images - Featured Image
# get html to parse url = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars" r = requests.get(url) assert(r.status_code == 200) soup = BS(r.text, "html.parser") # parse html button_a = soup.find('a', id="full_image") featured_image_url = "https://www.jpl.nasa.gov" + button_a['data-fancybox-href'] title = bu...
Curiosity Self-Portrait at 'Big Sky' Drilling Site This self-portrait of NASA's Curiosity Mars rover shows the vehicle at the 'Big Sky' site, where its drill collected the mission's fifth taste of Mount Sharp. Image: https://www.jpl.nasa.gov/spaceimages/images/mediumsize/PIA19920_ip.jpg
ADSL
mission_to_mars.ipynb
eanord4/scraping-challenge
Mars Weather
# get html to parse url = "https://twitter.com/marswxreport?lang=en" r = requests.get(url) assert(r.status_code == 200) soup = BS(r.text, "html.parser") # parse html # for some reason this shows up as a `span` via the inspector, but something # goes wrong via requests and even selenium. the 'p' tag below was found via...
InSight sol 448 (2020-02-29) low -94.1ºC (-137.3ºF) high -8.3ºC (17.0ºF) winds from the SSW at 5.5 m/s (12.4 mph) gusting to 19.9 m/s (44.6 mph) pressure at 6.30 hPa
ADSL
mission_to_mars.ipynb
eanord4/scraping-challenge
Mars Facts
#get html to parse url = "http://space-facts.com/mars/" r = requests.get(url) assert(r.status_code == 200) # parse html # "HTML table string"? i think just a data frame makes sense? tables = pd.read_html(r.text) # display results tables[0] tables[1] # assign variables mars_facts = tables[0].rename(columns={0: "Proper...
<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>Value</th> </tr> <tr> <th>Property</th> <th></th> </tr> </thead> <tbody> <tr> <th>Equatorial Diameter:</th> <td>6,792 km</td> </tr> <tr> <th>Polar Diamet...
ADSL
mission_to_mars.ipynb
eanord4/scraping-challenge
Mars Hemispheres
# get html to parse url = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars" driver.get(url) # parse html on main page imgs = {} # initially the urls of the images pages, then replaced with actual image urls for a in driver.find_elements_by_tag_name('a'): if a.get_attribute('cl...
_____no_output_____
ADSL
mission_to_mars.ipynb
eanord4/scraping-challenge
PyTorch 1.0 Distributed Trainer with Amazon AWS===============================================**Author**: `Nathan Inkawhich `_**Edited by**: `Teng Li `_ In this tutorial we will show how to setup, code, and run a PyTorch 1.0distributed trainer across two multi-gpu Amazon AWS nodes. We will startwith describing the AWS ...
import time import sys import torch if __name__ == '__main__': torch.multiprocessing.set_start_method('spawn') import torch.nn as nn import torch.nn.parallel import torch.distributed as dist import torch.optim import torch.utils.data import torch.utils.data.distributed import torchvision.transforms as transforms ...
_____no_output_____
BSD-3-Clause
docs/_downloads/e72ffa33b709a3d3f5b3f4c195c07637/aws_distributed_training_tutorial.ipynb
leejh1230/PyTorch-tutorials-kr
Helper Functions~~~~~~~~~~~~~~~~We must also define some helper functions and classes that will maketraining easier. The ``AverageMeter`` class tracks training statisticslike accuracy and iteration count. The ``accuracy`` function computesand returns the top-k accuracy of the model so we can track learningprogress. Bot...
class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val...
_____no_output_____
BSD-3-Clause
docs/_downloads/e72ffa33b709a3d3f5b3f4c195c07637/aws_distributed_training_tutorial.ipynb
leejh1230/PyTorch-tutorials-kr
Train Functions~~~~~~~~~~~~~~~To simplify the main loop, it is best to separate a training epoch stepinto a function called ``train``. This function trains the input modelfor one epoch of the *train\_loader*. The only distributed trainingartifact in this function is setting the`non\_blocking `__attributes of the data a...
def train(train_loader, model, criterion, optimizer, epoch): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() # switch to train mode model.train() end = time.time() for i, (input, target) in enumerate(train_...
_____no_output_____
BSD-3-Clause
docs/_downloads/e72ffa33b709a3d3f5b3f4c195c07637/aws_distributed_training_tutorial.ipynb
leejh1230/PyTorch-tutorials-kr
Validation Function~~~~~~~~~~~~~~~~~~~To track generalization performance and simplify the main loop furtherwe can also extract the validation step into a function called``validate``. This function runs a full validation step of the inputmodel on the input validation dataloader and returns the top-1 accuracyof the mode...
def validate(val_loader, model, criterion): batch_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() # switch to evaluate mode model.eval() with torch.no_grad(): end = time.time() for i, (input, target) in enumerate(val_loader): ...
_____no_output_____
BSD-3-Clause
docs/_downloads/e72ffa33b709a3d3f5b3f4c195c07637/aws_distributed_training_tutorial.ipynb
leejh1230/PyTorch-tutorials-kr
Inputs~~~~~~With the helper functions out of the way, now we have reached theinteresting part. Here is where we will define the inputs for the run.Some of the inputs are standard model training inputs such as batch sizeand number of training epochs, and some are specific to our distributedtraining task. The required in...
print("Collect Inputs...") # Batch Size for training and testing batch_size = 32 # Number of additional worker processes for dataloading workers = 2 # Number of epochs to train for num_epochs = 2 # Starting Learning Rate starting_lr = 0.1 # Number of distributed processes world_size = 4 # Distributed backend type...
_____no_output_____
BSD-3-Clause
docs/_downloads/e72ffa33b709a3d3f5b3f4c195c07637/aws_distributed_training_tutorial.ipynb
leejh1230/PyTorch-tutorials-kr
Initialize process group~~~~~~~~~~~~~~~~~~~~~~~~One of the most important parts of distributed training in PyTorch is toproperly setup the process group, which is the **first** step ininitializing the ``torch.distributed`` package. To do this, we will usethe ``torch.distributed.init_process_group`` function which takes...
print("Initialize Process Group...") # Initialize Process Group # v1 - init with url dist.init_process_group(backend=dist_backend, init_method=dist_url, rank=int(sys.argv[1]), world_size=world_size) # v2 - init with file # dist.init_process_group(backend="nccl", init_method="file:///home/ubuntu/pt-distributed-tutorial/...
_____no_output_____
BSD-3-Clause
docs/_downloads/e72ffa33b709a3d3f5b3f4c195c07637/aws_distributed_training_tutorial.ipynb
leejh1230/PyTorch-tutorials-kr
Initialize Model~~~~~~~~~~~~~~~~The next major step is to initialize the model to be trained. Here, wewill use a resnet18 model from ``torchvision.models`` but any model maybe used. First, we initialize the model and place it in GPU memory.Next, we make the model ``DistributedDataParallel``, which handles thedistributi...
print("Initialize Model...") # Construct Model model = models.resnet18(pretrained=False).cuda() # Make model DistributedDataParallel model = torch.nn.parallel.DistributedDataParallel(model, device_ids=dp_device_ids, output_device=local_rank) # define loss function (criterion) and optimizer criterion = nn.CrossEntropyL...
_____no_output_____
BSD-3-Clause
docs/_downloads/e72ffa33b709a3d3f5b3f4c195c07637/aws_distributed_training_tutorial.ipynb
leejh1230/PyTorch-tutorials-kr
Initialize Dataloaders~~~~~~~~~~~~~~~~~~~~~~The last step in preparation for the training is to specify whichdataset to use. Here we use the `STL-10dataset `__ from`torchvision.datasets.STL10 `__.The STL10 dataset is a 10 class dataset of 96x96px color images. For usewith our model, we resize the images to 224x224px in...
print("Initialize Dataloaders...") # Define the transform for the data. Notice, we must resize to 224x224 with this dataset and model. transform = transforms.Compose( [transforms.Resize(224), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) # Initialize Datasets. STL10 will...
_____no_output_____
BSD-3-Clause
docs/_downloads/e72ffa33b709a3d3f5b3f4c195c07637/aws_distributed_training_tutorial.ipynb
leejh1230/PyTorch-tutorials-kr
Training Loop~~~~~~~~~~~~~The last step is to define the training loop. We have already done mostof the work for setting up the distributed training so this is notdistributed training specific. The only detail is setting the currentepoch count in the ``DistributedSampler``, as the sampler shuffles thedata going to each...
best_prec1 = 0 for epoch in range(num_epochs): # Set epoch count for DistributedSampler train_sampler.set_epoch(epoch) # Adjust learning rate according to schedule adjust_learning_rate(starting_lr, optimizer, epoch) # train for one epoch print("\nBegin Training Epoch {}".format(epoch+1)) ...
_____no_output_____
BSD-3-Clause
docs/_downloads/e72ffa33b709a3d3f5b3f4c195c07637/aws_distributed_training_tutorial.ipynb
leejh1230/PyTorch-tutorials-kr
Figure 1.1: Three types of Iris flowers: Setosa, Versicolor and Virginica. Used with kind permission of Dennis Kramb and SIGNA
#@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts %reload_ext aut...
_____no_output_____
MIT
pml1/figure_notebooks/chapter1_introduction_figures.ipynb
brickbitbot/pml-book
Figure 1.2: Illustration of the image classification problem. From https://cs231n.github.io/ . Used with kind permission of Andrej Karpathy
#@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts %reload_ext aut...
_____no_output_____
MIT
pml1/figure_notebooks/chapter1_introduction_figures.ipynb
brickbitbot/pml-book
Figure 1.3: Visualization of the Iris data as a pairwise scatter plot. On the diagonal we plot the marginal distribution of each feature for each class. The off-diagonals contain scatterplots of all possible pairs of features. Figure(s) generated by [iris_plot.py](https://github.com/probml/pyprobml/blob/master/sc...
#@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts %reload_ext aut...
_____no_output_____
MIT
pml1/figure_notebooks/chapter1_introduction_figures.ipynb
brickbitbot/pml-book
Figure 1.4: Example of a decision tree of depth 2 applied to the Iris data, using just the petal length and petal width features. Leaf nodes are color coded according to the predicted class. The number of training samples that pass from the root to a node is shown inside each box; we show how many values of each cl...
#@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts %reload_ext aut...
_____no_output_____
MIT
pml1/figure_notebooks/chapter1_introduction_figures.ipynb
brickbitbot/pml-book
Figure 1.5: (a) Linear regression on some 1d data. (b) The vertical lines denote the residuals between the observed output value for each input (blue circle) and its predicted value (red cross). The goal of least squares regression is to pick a line that minimizes the sum of squared residuals. Figure(s) generated...
#@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts %reload_ext aut...
_____no_output_____
MIT
pml1/figure_notebooks/chapter1_introduction_figures.ipynb
brickbitbot/pml-book
Figure 1.6: Linear and polynomial regression applied to 2d data. Vertical axis is temperature, horizontal axes are location within a room. Data was collected by some remote sensing motes at Intel's lab in Berkeley, CA (data courtesy of Romain Thibaux). (a) The fitted plane has the form $ f ( \bm x ) = w_0 + w_1 x_...
#@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts %reload_ext aut...
_____no_output_____
MIT
pml1/figure_notebooks/chapter1_introduction_figures.ipynb
brickbitbot/pml-book
Figure 1.7: (a-c) Polynomials of degrees 2, 14 and 20 fit to 21 datapoints (the same data as in \cref fig:linreg ). (d) MSE vs degree. Figure(s) generated by [linreg_poly_vs_degree.py](https://github.com/probml/pyprobml/blob/master/scripts/linreg_poly_vs_degree.py)
#@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts %reload_ext aut...
_____no_output_____
MIT
pml1/figure_notebooks/chapter1_introduction_figures.ipynb
brickbitbot/pml-book
Figure 1.8: (a) A scatterplot of the petal features from the iris dataset. (b) The result of unsupervised clustering using $K=3$. Figure(s) generated by [iris_kmeans.py](https://github.com/probml/pyprobml/blob/master/scripts/iris_kmeans.py)
#@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts %reload_ext aut...
_____no_output_____
MIT
pml1/figure_notebooks/chapter1_introduction_figures.ipynb
brickbitbot/pml-book
Figure 1.9: (a) Scatterplot of iris data (first 3 features). Points are color coded by class. (b) We fit a 2d linear subspace to the 3d data using PCA. The class labels are ignored. Red dots are the original data, black dots are points generated from the model using $ \bm x = \mathbf W \bm z + \bm \mu $, wh...
#@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts %reload_ext aut...
_____no_output_____
MIT
pml1/figure_notebooks/chapter1_introduction_figures.ipynb
brickbitbot/pml-book
Figure 1.10: Examples of some control problems. (a) Space Invaders Atari game. From https://gym.openai.com/envs/SpaceInvaders-v0/ . (b) Controlling a humanoid robot in the MuJuCo simulator so it walks as fast as possible without falling over. From https://gym.openai.com/envs/Humanoid-v2/
#@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts %reload_ext aut...
_____no_output_____
MIT
pml1/figure_notebooks/chapter1_introduction_figures.ipynb
brickbitbot/pml-book
Figure 1.11: The three types of machine learning visualized as layers of a chocolate cake. This figure (originally from https://bit.ly/2m65Vs1 ) was used in a talk by Yann LeCun at NIPS'16, and is used with his kind permission
#@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts %reload_ext aut...
_____no_output_____
MIT
pml1/figure_notebooks/chapter1_introduction_figures.ipynb
brickbitbot/pml-book
Figure 1.12: (a) Visualization of the MNIST dataset. Each image is $28 \times 28$. There are 60k training examples and 10k test examples. We show the first 25 images from the training set. Figure(s) generated by [mnist_viz_tf.py](https://github.com/probml/pyprobml/blob/master/scripts/mnist_viz_tf.py) [emnist_viz_p...
#@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts %reload_ext aut...
_____no_output_____
MIT
pml1/figure_notebooks/chapter1_introduction_figures.ipynb
brickbitbot/pml-book
Figure 1.13: (a) Visualization of the Fashion-MNIST dataset [XRV17] . The dataset has the same size as MNIST, but is harder to classify. There are 10 classes: T-shirt/top, Trouser, Pullover, Dress, Coat, Sandal, Shirt, Sneaker, Bag, Ankle-boot. We show the first 25 images from the training set. Figure(s) generated ...
#@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts %reload_ext aut...
_____no_output_____
MIT
pml1/figure_notebooks/chapter1_introduction_figures.ipynb
brickbitbot/pml-book
Figure 1.14: (a) Sample images from the \bf ImageNet dataset [Rus+15] . This subset consists of 1.3M color training images, each of which is $256 \times 256$ pixels in size. There are 1000 possible labels, one per image, and the task is to minimize the top-5 error rate, i.e., to ensure the correct label is within ...
#@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts %reload_ext aut...
_____no_output_____
MIT
pml1/figure_notebooks/chapter1_introduction_figures.ipynb
brickbitbot/pml-book
Figure 1.15: Example of a term-document matrix, where raw counts have been replaced by their TF-IDF values (see \cref sec:tfidf ). Darker cells are larger values. From https://bit.ly/2kByLQI . Used with kind permission of Christoph Carl Kling
#@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts %reload_ext aut...
_____no_output_____
MIT
pml1/figure_notebooks/chapter1_introduction_figures.ipynb
brickbitbot/pml-book
Introduction
import jupyter_bifrost import pandas as pd import numpy as np from sklearn.datasets import load_iris cols = ["foo","y", "bar", "baz", "something", "else"] dist = np.random.uniform(0,1, size=(1000,len(cols))) scatter_df = pd.DataFrame(dist, columns=cols) bar_df = pd.DataFrame([ ["John", "Developer", 1], ["Jay",...
_____no_output_____
BSD-3-Clause
examples/introduction.ipynb
jahn96/Jupyter-Bifrost
Using -pipe- notation **Connecting unit operations can be simplified through -pipe- notation. As an example, here we create a process with multiple units and connect them as a demonstration.** With -pipe- notation you can get stream outputs and set stream inputs in the following format:
# U1-n -> U1.outs[n] # U1-[0, 1] -> [U1.outs[i] for i in [0, 1]] # s1-U1 -> U1.ins[:] = [s1] # s1-n-U1 -> U1.ins[n] = s1 # [s1, s2]-U1 -> U1.ins[:] = [s1, s2] # U1-n1-n2-U2 -> U2.ins[n2] = U1.outs[n1]
_____no_output_____
MIT
docs/tutorial/Using -pipe- notation.ipynb
Ecoent/biosteam
As an example, create 2 feeds, 2 Mixers and 2 Splitters:
import biosteam as bst import thermosteam as tmo from biosteam.units import Mixer, Splitter # Set property pacakge chemicals = tmo.Chemicals(['Water']) tmo.settings.set_thermo(chemicals) # Set feed stream and units feed1 = tmo.Stream('feed1') M1 = Mixer('M1', outs='s1') S1 = Splitter('S1', outs=('s2', 'product1'), sp...
_____no_output_____
MIT
docs/tutorial/Using -pipe- notation.ipynb
Ecoent/biosteam
Now connect streams linearly along the units, and create a loop between S2 and M1:
# In -pipe- notation: (feed1, S2-0)-M1-S1 (feed2, S1-0)-M2-S2 # Without -pipe- notation: # M1.ins[:] = (feed1, S2.outs[0]) # S1.ins[:] = M1.outs # M2.ins[:] = (feed2, S1.outs[0]) # S2.ins[:] = M2.outs bst.find.diagram(format='png')
_____no_output_____
MIT
docs/tutorial/Using -pipe- notation.ipynb
Ecoent/biosteam
Python Indention
if 5<2: print("Five is less than two") else: print("Five is greater than two")
Five is greater than two
Apache-2.0
Intro_to_Python.ipynb
Daenarics/Elective-1-3
Python Comments
# This is a program that displays Hello, World print("Hello, World") print('Welcome to Python Programming')
Hello, World Welcome to Python Programming
Apache-2.0
Intro_to_Python.ipynb
Daenarics/Elective-1-3
Common Workflow Language with BioExcel Building Blocks Based on the Protein MD Setup tutorial using BioExcel Building Blocks (biobb)***This tutorial aims to illustrate the process of **building up a CWL workflow** using the **BioExcel Building Blocks library (biobb)**. The tutorial is based on the **Protein Gromacs MD...
hints: DockerRequirement: dockerPull: quay.io/biocontainers/biobb_io:latest
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
* **namespaces and schemas**: Input and output **metadata** may be represented within a tool or workflow. Such **metadata** must use a **namespace prefix** listed in the **$namespaces and $schemas sections** of the document. All **BioExcel building blocks CWL specifications** use the **EDAM ontology** (http://edamontol...
$namespaces: edam: http://edamontology.org/ $schemas: - http://edamontology.org/EDAM_1.22.owl
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
* **inputs**: The **inputs section** of a **tool** contains a list of input parameters that **control how to run the tool**. Each parameter has an **id** for the name of parameter, and **type** describing what types of values are valid for that parameter. Available primitive types are *string, int, long, float, double,...
inputs: output_pdb_path: type: string inputBinding: position: 1 prefix: --output_pdb_path default: 'downloaded_structure.pdb' config: type: string? inputBinding: position: 2 prefix: --config default: '{"pdb_code" : "1aki"}'
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
* **outputs**: The **outputs section** of a **tool** contains a list of output parameters that should be returned after running the **tool**. Similarly to the inputs section, each parameter has an **id** for the name of parameter, and **type** describing what types of values are valid for that parameter. The **outputBi...
outputs: output_pdb_file: type: File format: edam:format_1476 outputBinding: glob: $(inputs.output_pdb_path)
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
For more information on CWL tools description, please refer to the [CWL User Guide](https://www.commonwl.org/user_guide/index.html) or the [CWL specifications](https://www.commonwl.org/v1.1/).*** Complete Pdb Building Block CWL description:Example of a **BioExcel building block CWL description** (pdb from biobb_io pack...
# Example of a BioExcel building block CWL description (pdb from biobb_io package) #!/usr/bin/env cwl-runner cwlVersion: v1.0 class: CommandLineTool baseCommand: pdb hints: DockerRequirement: dockerPull: quay.io/biocontainers/biobb_io:latest inputs: output_pdb_path: type: string inputBindi...
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
*** BioExcel building blocks WORKFLOWS CWL DescriptionsNow that we have seen the **BioExcel building blocks CWL descriptions**, we can use them to build our first **biomolecular workflow** as a demonstrator. All **CWL workflows** are divided in **two files**: the **CWL description** and the **YAML** or **JSON** files c...
# !/usr/bin/env cwl-runner cwlVersion: v1.0 class: Workflow label: Example CWL Header doc: | An example of how to create a CWl header. We have specified the version of CWL that we are using; the class, which is a 'workflow'. The label field should provide a short title or description of the workflow and the d...
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
Inputs:The **inputs section** describes the inputs for **each of the steps** of the workflow. The **BioExcel building blocks (biobb)** have three types of **input parameters**: **input**, **output**, and **properties**. The **properties** parameter, which contains all the input parameters that are neither **input** no...
# CWL workflow inputs section example inputs: step1_output_name: string step1_properties: string
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
Outputs:The **outputs:** section describes the set of **final outputs** from the **workflow**. These outputs can be a collection of outputs from **different steps of the workflow**. Each output is a `key: value` pair. The `key` should be a unique identifier, and the value should be a dictionary (consisting of `key: va...
outputs: pdb: #unique identifier label: Protein structure doc: | Step 1 of the workflow, download a 'protein structure' from the 'PDB database'. The *pdb* 'output' is a 'file' containing the 'protein structure' in 'PDB format', which is connected to the output parameter *output_pdb_f...
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
Steps:The **steps section** describes the actual steps of the workflow. Steps are **connected** one to the other through the **input parameters**.**Workflow steps** are not necessarily run in the order they are listed, instead **the order is determined by the dependencies between steps**. In addition, workflow steps w...
# CWL workflow steps section example step1_pdb: label: Fetch PDB Structure doc: | Download a protein structure from the PDB database run: biobb/biobb_adapters/cwl/biobb_io/mmb_api/pdb.cwl in: output_pdb_path: step1_pdb_name config: step1_pdb_config out: [output_pdb_file] step2...
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
Input of a run:As previously stated, all **CWL workflows** are divided in **two files**: the **CWL description** and the **YAML** or **JSON** files containing **all workflow inputs**. In this example, we are going to produce a **YAML** formatted object in a separate file describing the **inputs of our run**.**Example...
step1_output_name: 'tutorial_1aki.pdb' step1_properties: '{"pdb_code" : "1aki"}'
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
Complete workflow:Example of a short **CWL workflow** with **BioExcel building blocks**, which retrieves a **PDB file** for the **Lysozyme protein structure** from the RCSB PDB database (**step1: pdb.cwl**), and fixes the possible problems in the structure, adding **missing side chain atoms** if needed (**step2: fix_s...
# !/usr/bin/env cwl-runner cwlVersion: v1.0 class: Workflow label: Example of a short CWL workflow with BioExcel building blocks doc: | Example of a short 'CWL workflow' with 'BioExcel building blocks', which retrieves a 'PDB file' for the 'Lysozyme protein structure' from the RCSB PDB database ('step1: pdb.cwl'...
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
Running the CWL workflow:The final step of the process is **running the workflow described in CWL**. For that, the description presented in the previous cell should be written to a file (e.g. BioExcel-CWL-firstWorkflow.cwl), the **YAML** input should be written to a separate file (e.g. BioExcel-CWL-firstWorkflow-job.y...
# Run CWL workflow with CWL tool description reference implementation (cwltool). cwltool BioExcel-CWL-firstWorkflow.cwl BioExcel-CWL-firstWorkflow-job.yml
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
Cwltool workflow outputThe **execution of the workflow** will write information to the standard output such as the **step being performed**, the **way it is run** (command line, docker container, etc.), **inputs and outputs** used, and **state of each step** (success, failed). The next cell contains a **real output** ...
Resolved 'BioExcel-CWL-firstWorkflow.cwl' to 'file:///PATH/biobb_wf_md_setup/cwl/BioExcel-CWL-firstWorkflow.cwl' [workflow BioExcel-CWL-firstWorkflow.cwl] start [step step1_pdb] start [job step1_pdb] /private/tmp/docker_tmp1g8y0wu0$ docker \ run \ -i \ --volume=/private/tmp/docker_tmp1g8y0wu0:/private/var/s...
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
*** Protein MD-Setup CWL workflow with BioExcel building blocks The last step of this **tutorial** illustrates the building of a **complex CWL workflow**. The example used is the **Protein Gromacs MD Setup** [Jupyter Notebook tutorial](https://github.com/bioexcel/biobb_wf_md_setup). It is strongly recommended to take a...
step1_pdb: label: Fetch PDB Structure doc: | Download a protein structure from the PDB database run: biobb/biobb_adapters/cwl/biobb_io/mmb_api/pdb.cwl in: output_pdb_path: step1_pdb_name config: step1_pdb_config out: [output_pdb_file] step2_fixsidechain: label: Fix Protein ...
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
Inputs:All inputs for the **BioExcel building blocks** are defined as *strings*. Not all the steps in this particular example need **external inputs**, some of them just works using as input/s an output (or outputs) from **previous steps** (e.g. step2_fixsidechain). For the steps that need input, all of them will rece...
inputs: step1_pdb_name: string step1_pdb_config: string step4_editconf_config: string step6_gppion_config: string step7_genion_config: string step8_gppmin_config: string step10_energy_min_config: string step10_energy_min_name: string step11_gppnvt_config: string step13_energy_nvt_config: string st...
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
Outputs:The **outputs section** contains the set of **final outputs** from the **workflow**. In this case, **outputs** from **different steps** of the **workflow** are considered **final outputs**:* **Trajectories**: * **trr**: Raw trajectory from the *free* simulation step. * **trr_imaged_dry**: Post-processed...
outputs: trr: label: Trajectories - Raw trajectory doc: | Raw trajectory from the free simulation step type: File outputSource: step18_mdrun_md/output_trr_file trr_imaged_dry: label: Trajectories - Post-processed trajectory doc: | Post-processed trajectory, dehydrated, image...
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
Complete workflow:The complete **CWL described workflow** to run a **Molecular Dynamics Setup** on a protein structure can be found in the next cell. The **representation of the workflow** using the **CWL Viewer** web service can be found here: XXXXXX. The **full workflow** is a combination of the **inputs**, **output...
# Protein MD-Setup CWL workflow with BioExcel building blocks # https://github.com/bioexcel/biobb_wf_md_setup #!/usr/bin/env cwl-runner cwlVersion: v1.0 class: Workflow inputs: step1_pdb_name: string step1_pdb_config: string step4_editconf_config: string step6_gppion_config: string step7_genion_config: stri...
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
Input of the run:As previously stated, all **CWL workflows** are divided in **two files**: the **CWL description** and the **YAML** or **JSON** files containing **all workflow inputs**. The following cell presents the **YAML** file describing the **inputs of the run** for the **Protein Gromacs MD Setup** workflow.All...
# Protein MD-Setup CWL workflow with BioExcel building blocks - Input YAML configuration file # https://github.com/bioexcel/biobb_wf_md_setup step1_pdb_name: 'tutorial.pdb' step1_pdb_config: '{"pdb_code" : "1aki"}' step4_editconf_config: '{"box_type": "cubic","distance_to_molecule": 1.0}' step6_gppion_config: '{"mdp":...
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
Running the CWL workflow:The final step of the process is **running the workflow described in CWL**. For that, the complete **workflow description** should be written to a file (e.g. BioExcel-CWL-MDSetup.cwl), the **YAML** input should be written to a separate file (e.g. BioExcel-CWL-MDSetup-job.yml) and finally both ...
# Run CWL workflow with CWL tool description reference implementation (cwltool). cwltool BioExcel-CWL-MDSetup.cwl BioExcel-CWL-MDSetup-job.yml
_____no_output_____
Apache-2.0
biobb_wf_cwl_tutorial/notebooks/biobb_CWL_tutorial.ipynb
longr/biobb_wf_cwl_tutorial
Copy Task Plots
import matplotlib.pyplot as plt import numpy as np import pandas as pd from glob import glob import json import os import sys sys.path.append(os.path.abspath(os.getcwd() + "./../")) %matplotlib inline
_____no_output_____
BSD-3-Clause
notebooks/copy-task-plots.ipynb
arthurlemon/NTM
Load training historyTo generate the models and training history used in this notebook, run the following commands:```mkdir ./notebooks/copy./train.py --seed 1 --task copy --checkpoint-interval 500 --checkpoint-path ./notebooks/copy./train.py --seed 10 --task copy --checkpoint-interval 500 --checkpoint-path ./notebook...
batch_num = 40000 files = glob("./copy/*-{}.json".format(batch_num)) files # Read the metrics from the .json files history = [json.loads(open(fname, "rt").read()) for fname in files] training = np.array([(x['cost'], x['loss'], x['seq_lengths']) for x in history]) print("Training history (seed x metric x sequence) =", t...
_____no_output_____
BSD-3-Clause
notebooks/copy-task-plots.ipynb
arthurlemon/NTM
Evaluate
import torch from IPython.display import Image as IPythonImage from PIL import Image, ImageDraw, ImageFont import io from tasks.copytask import dataloader from train import evaluate from tasks.copytask import CopyTaskModelTraining model = CopyTaskModelTraining() model.net.load_state_dict(torch.load("./copy/copy-task-10...
_____no_output_____
BSD-3-Clause
notebooks/copy-task-plots.ipynb
arthurlemon/NTM
Create an animated GIFLets see how the prediction looks like in each checkpoint that we saved.
seq_len = 80 _, x, y = next(iter(dataloader(1, 1, 8, seq_len, seq_len))) frames = [] font = ImageFont.truetype("./fonts/PT_Sans-Web-Regular.ttf", 13) for batch_num in range(500, 10500, 500): model = CopyTaskModelTraining() model.net.load_state_dict(torch.load("./copy/copy-task-10-batch-{}.model".format(batch_n...
_____no_output_____
BSD-3-Clause
notebooks/copy-task-plots.ipynb
arthurlemon/NTM
Imports & Installations
!pip install pyforest !pip install plotnine !pip install transformers !pip install psycopg2-binary !pip uninstall -y tensorflow-datasets !pip install lit_nlp tfds-nightly transformers==4.1.1 # Automatic library importer (doesn't quite import everything yet) from pyforest import * # Expands Dataframe to view entire pan...
_____no_output_____
MIT
notebooks/labs38_notebooks/FrankenBERT_Training.ipynb
n8mcdunna/labs31_gp2
Reading in our Tweets
def get_df(db_url) -> pd.DataFrame: ''' Connects to our Blue Witness Data Labeler and retrieves manually labelled text before converting them all into a pandas dataframe. Parameters ---------- db_url: psycopg2 database Returns ------- df: pandas datafarme Contains thou...
_____no_output_____
MIT
notebooks/labs38_notebooks/FrankenBERT_Training.ipynb
n8mcdunna/labs31_gp2
Visualizations
%matplotlib inline (ggplot(force_ranks) # defining what dataframe to use + aes(x='labels') # defining what variable/column to use + geom_bar(size=20) # defining the type of plot to use and its size + labs(title='Number of Tweets Reporting Police Violence per Force Rank', x='Force Rank', y='Nu...
_____no_output_____
MIT
notebooks/labs38_notebooks/FrankenBERT_Training.ipynb
n8mcdunna/labs31_gp2
Preparing Data for BERTSplitting dataframe into training and testing sets before converting to parquet for later reference/resource.
def parquet_and_split(): ''' Splits our data into a format amicable to NLP modeling. Saves our original dataframe as well as the two split dataframes into parquet files for later reference/use. ----- Parameters ------ None Returns ------- df: pandas dataframes Contains two split dataframes r...
_____no_output_____
MIT
notebooks/labs38_notebooks/FrankenBERT_Training.ipynb
n8mcdunna/labs31_gp2
BERT Training our NLP Multi-Class Classification Model
def bert_trainer(df, output_dir: str, epochs: int): start = time() max_len = 280 if torch.cuda.is_available(): print("CUDA Active") device = torch.device("cuda") else: print("CPU Active") device = torch.device("cpu") sentences = df["tweets"].values labels = df["la...
CUDA Active
MIT
notebooks/labs38_notebooks/FrankenBERT_Training.ipynb
n8mcdunna/labs31_gp2
Making Predictions
class FrankenBert: """ Implements BertForSequenceClassification and BertTokenizer for binary classification from a saved model """ def __init__(self, path: str): """ If there's a GPU available, tell PyTorch to use the GPU. Loads model and tokenizer from saved model directory...
_____no_output_____
MIT
notebooks/labs38_notebooks/FrankenBERT_Training.ipynb
n8mcdunna/labs31_gp2
Saving Trained Model
from google.colab import drive drive.mount('/content/gdrive') #path that contains folder you want to copy %cd /content/gdrive/MyDrive/ColabNotebooks/Labs/saved_model # copy local folder to folder on Google Drive %cp -av /content/saved_model saved_model
/content/gdrive/MyDrive/ColabNotebooks/Labs/saved_model '/content/saved_model' -> 'saved_model' '/content/saved_model/.ipynb_checkpoints' -> 'saved_model/.ipynb_checkpoints' '/content/saved_model/config.json' -> 'saved_model/config.json' '/content/saved_model/pytorch_model.bin' -> 'saved_model/pytorch_model.bin' '/cont...
MIT
notebooks/labs38_notebooks/FrankenBERT_Training.ipynb
n8mcdunna/labs31_gp2
HW8: Topic Modeling
## ======================================================= ## IMPORTING ## ======================================================= import os def get_data_from_files(path): directory = os.listdir(path) results = [] for file in directory: f=open(path+file, encoding = "ISO-8859-1") results.app...
_____no_output_____
MIT
assets/all_html/2019_11_25_HW8_clean.ipynb
dskw1/dskw1.github.io
Image Tools> Tools for images.
# export class ImageOrientation(Enum): """ Image EXIF orientations. """ TOP = 1 TOP_FLIPPED = 2 BOTTOM = 3 BOTTOM_FLIPPED = 4 RIGHT_FLIPPED = 5 RIGHT = 6 LEFT_FLIPPED = 7 LEFT = 8 def __str__(self): return str(self.value) # export def get_image_scale(image_size, ...
Converted annotation-core.ipynb. Converted annotation-folder_category_adapter.ipynb. Converted annotation-multi_category_adapter.ipynb. Converted annotation-via_adapter.ipynb. Converted annotation-yolo_adapter.ipynb. Converted annotation_converter.ipynb. Converted annotation_viewer.ipynb. Converted category_tools.ipynb...
Apache-2.0
image-tools.ipynb
AI-Force/aiforce
pandas字符串操作很明显除了数值型,我们处理的数据还有很多字符类型的,而这部分数据显然也非常重要,因此这个部分我们提一提pandas的字符串处理。
%matplotlib inline %config ZMQInteractiveShell.ast_node_interactivity='all' import pandas as pd import matplotlib.pyplot as plt import numpy as np pd.set_option('display.mpl_style', 'default') plt.rcParams['figure.figsize'] = (15, 3) plt.rcParams['font.family'] = 'sans-serif'
/opt/anaconda3/envs/python27/lib/python2.7/site-packages/IPython/core/interactiveshell.py:2881: FutureWarning: mpl_style had been deprecated and will be removed in a future version. Use `matplotlib.pyplot.style.use` instead. exec(code_obj, self.user_global_ns, self.user_ns)
Apache-2.0
dataScience/02DataMining/02_Data-Computation-Analysis-Visualization/2-5_Pandas_String_Operations.ipynb
yangpanyang/DemoPractice
前面看到pandas在处理数值型的时候,各种如鱼得水,偷偷告诉你,pandas处理字符串也相当生猛。咱们来读一份天气数据。
weather_2012 = pd.read_csv('./data/weather_2012.csv', parse_dates=True, index_col='Date/Time') weather_2012[:5]
_____no_output_____
Apache-2.0
dataScience/02DataMining/02_Data-Computation-Analysis-Visualization/2-5_Pandas_String_Operations.ipynb
yangpanyang/DemoPractice
5.1字符串操作 从上面的数据里面可以看到,有 'Weather' 这一列。我们这里假定包含 "Snow" 的才是下雪天。pandas的str类型提供了一系列方便的函数,比如这里的contains,更多的例子可以查看 [这里](http://pandas.pydata.org/pandas-docs/stable/basics.htmlvectorized-string-methods)。
weather_description = weather_2012['Weather'] is_snowing = weather_description.str.contains('Snow')
_____no_output_____
Apache-2.0
dataScience/02DataMining/02_Data-Computation-Analysis-Visualization/2-5_Pandas_String_Operations.ipynb
yangpanyang/DemoPractice
你看我们contains返回的其实是布尔型的判定结果的dataframe。
# 返回bool型内容的dataframe is_snowing[:5]
_____no_output_____
Apache-2.0
dataScience/02DataMining/02_Data-Computation-Analysis-Visualization/2-5_Pandas_String_Operations.ipynb
yangpanyang/DemoPractice
你以为懒癌晚期的我会一个个去看吗!!图样图森破!!我一个函数就给你画出来了!!!
# 就是屌!!! is_snowing.plot()
_____no_output_____
Apache-2.0
dataScience/02DataMining/02_Data-Computation-Analysis-Visualization/2-5_Pandas_String_Operations.ipynb
yangpanyang/DemoPractice
6.2 平均气温 如果我们想知道每个月的温度值中位数,有一个很有用的函数可以调用哈,叫 `resample()`
weather_2012['Temp (C)'].resample('M', how=np.median).plot(kind='bar')
/opt/anaconda3/envs/python27/lib/python2.7/site-packages/ipykernel_launcher.py:1: FutureWarning: how in .resample() is deprecated the new syntax is .resample(...)..apply(<func>) """Entry point for launching an IPython kernel.
Apache-2.0
dataScience/02DataMining/02_Data-Computation-Analysis-Visualization/2-5_Pandas_String_Operations.ipynb
yangpanyang/DemoPractice
符合预期对吧,7月和8月是温度最高的 你要知道,布尔型的 `True` 和 `False`其实是不便于运算的,当然,其实他们就是0和1了,所以我们转成float型去做做运算可好?
is_snowing.astype(float)[:10]
_____no_output_____
Apache-2.0
dataScience/02DataMining/02_Data-Computation-Analysis-Visualization/2-5_Pandas_String_Operations.ipynb
yangpanyang/DemoPractice
然后我们很聪明地用 `resample` 去找到每个月下雪的比例状况(为嘛感觉在做很无聊的事情,其实哪个月下雪多我们知道的对么...)
is_snowing.astype(float).resample('M', how=np.mean) is_snowing.astype(float).resample('M', how=np.mean).plot(kind='bar')
/opt/anaconda3/envs/python27/lib/python2.7/site-packages/ipykernel_launcher.py:1: FutureWarning: how in .resample() is deprecated the new syntax is .resample(...)..apply(<func>) """Entry point for launching an IPython kernel.
Apache-2.0
dataScience/02DataMining/02_Data-Computation-Analysis-Visualization/2-5_Pandas_String_Operations.ipynb
yangpanyang/DemoPractice
So,你也看到了,加拿大的12月是下雪最多的月份。然后你还能观察到一些其他的端倪,比如你会发现,11月开始突然下雪,接着就雪期漫漫,虽然下雪的概率逐步减小,但是可能要到4月或者5月才会停止。 5.3 画一下温度和雪期 我们把温度和下雪概率放到一起,组成dataframe的2列,然后画个图
temperature = weather_2012['Temp (C)'].resample('M', how=np.median) is_snowing = weather_2012['Weather'].str.contains('Snow') snowiness = is_snowing.astype(float).resample('M', how=np.mean) # 给列取个名字 temperature.name = "Temperature" snowiness.name = "Snowiness"
/opt/anaconda3/envs/python27/lib/python2.7/site-packages/ipykernel_launcher.py:1: FutureWarning: how in .resample() is deprecated the new syntax is .resample(...)..apply(<func>) """Entry point for launching an IPython kernel. /opt/anaconda3/envs/python27/lib/python2.7/site-packages/ipykernel_launcher.py:3: FutureWarn...
Apache-2.0
dataScience/02DataMining/02_Data-Computation-Analysis-Visualization/2-5_Pandas_String_Operations.ipynb
yangpanyang/DemoPractice
我们用concat完成字符串的拼接 用 `concat` 把这两列拼接到一列中,组成一个新的dataframe
stats = pd.concat([temperature, snowiness], axis=1) stats stats.plot(kind='bar')
_____no_output_____
Apache-2.0
dataScience/02DataMining/02_Data-Computation-Analysis-Visualization/2-5_Pandas_String_Operations.ipynb
yangpanyang/DemoPractice
你发现,什么鬼!!!紫色的下雪概率呢!!!是的亲,你这2个维度的幅度是不一样的,所以要分开画哦。
stats.plot(kind='bar', subplots=True, figsize=(15, 10))
_____no_output_____
Apache-2.0
dataScience/02DataMining/02_Data-Computation-Analysis-Visualization/2-5_Pandas_String_Operations.ipynb
yangpanyang/DemoPractice
总结
%matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt # Make the graphs a bit prettier, and bigger pd.set_option('display.mpl_style', 'default') # matplotlib.style.use('ggplot') plt.rcParams['figure.figsize'] = (15, 5) plt.rcParams['font.family'] = 'sans-serif' # This is necessary...
/opt/anaconda3/envs/python27/lib/python2.7/site-packages/ipykernel_launcher.py:22: FutureWarning: how in .resample() is deprecated the new syntax is .resample(...)..apply(<func>) /opt/anaconda3/envs/python27/lib/python2.7/site-packages/ipykernel_launcher.py:24: FutureWarning: how in .resample() is deprecated the new sy...
Apache-2.0
dataScience/02DataMining/02_Data-Computation-Analysis-Visualization/2-5_Pandas_String_Operations.ipynb
yangpanyang/DemoPractice
Machine Learning - AA2AR **By Jakke Neiro & Andrei Roibu** 1. Importing All Required Dependencies This script imports all the required dependencies for running the different functions and the codes. Also, by using the _run_ command, the various notebooks are imprted into the main notebook.
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import interp import glob, os from sklearn.metrics import accuracy_score, roc_curve, roc_auc_score, auc, roc_auc_score, confusion_matrix, classification_report, log_loss from sklearn.model_selection import train_test_split from sklearn....
_____no_output_____
BSD-3-Clause
MAIN-AA2AR.ipynb
SABS-R3-projects/JA-ML