text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
## Webscraping com `requests` e `BeautifulSoup` ### Código comentado de _webscraping_ simples A primeira biblioteca que precisamos é Requests. Ela gerencia a requisição HTTP. Significa que ela acessa e "copia" o código-fonte para nosso script. ``` import requests ``` Com a biblioteca carregada, vamos gerar a URL do...
github_jupyter
# Custom Estimator with Keras **Learning Objectives** - Learn how to create custom estimator using tf.keras ## Introduction Up until now we've been limited in our model architectures to premade estimators. But what if we want more control over the model? We can use the popular Keras API to create a custom model....
github_jupyter
``` # Copyright 2021 NVIDIA Corporation. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
github_jupyter
<a href="https://colab.research.google.com/github/TeachingTextMining/TextClassification/blob/main/01-SA-Pipeline/01-SA-Pipeline-Reviews.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ## Entrenamiento y ejecución de un pipeline de clasificación text...
github_jupyter
# Get average size of predicted instances ``` import numpy as np import os import matplotlib.pyplot as plt import matplotlib.pylab as pylab # this can be modified for better representation pylab.rcParams['figure.figsize'] = 10,7 ROOT = '/home/maxsen/DEEPL/data/training_data/test/' #ROOT = '/data/proj/smFISH/Students/M...
github_jupyter
Jeff's initial writeup -- 2019_01_21 ## Comparing molecule loading using RDKit and OpenEye It's really important that both RDKitToolkitWrapper and OpenEyeToolkitWrapper load the same file to equivalent OFFMol objects. If the ToolkitWrappers don't create the same OFFMol from a single file/external molecule representati...
github_jupyter
``` import os os.environ["OMP_NUM_THREADS"] = "4" import numpy as np import matplotlib.pyplot as plt import h5py import time from mpl_toolkits import mplot3d import matplotlib as mpl from matplotlib.gridspec import GridSpec import scipy.stats as stats mpl.rc('text', usetex = True) mpl.rc('font', family = 'serif') impo...
github_jupyter
``` # Dependencies and Setup import pandas as pd years = [2015,2016,2017,2018,2019] df={} # Looping through years list for year in years: # File to Load file = f"../Resources/{year}.csv" # Read each years File and store into Pandas data frame df[year] = pd.read_csv(file) # Assigning names to each item ...
github_jupyter
``` import os os.chdir("../") import pandas as pd import glob from scipy.stats import ttest_ind import matplotlib.pyplot as plt resultDir = 'results' problem = 'cauctions' # choices=['setcover', 'cauctions', 'facilities', 'indset'] sampling_Strategies = ['uniform5','depthK','depthK2'] # choices: uniform5, depthK,...
github_jupyter
# logging - 파이썬을 처음 배울 땐, 로그를 print문으로 남겼지만(이 당시에 이게 로그 개념인지도 몰랐음) 점점 서비스나 어플리케이션이 커지면 남기는 로그가 많아지고 관리도 어려워집니다 - 이를 위해 로그 관련 라이브러리들이 만들어졌습니다. 대표적으로 파이썬 내장 모듈인 logging이 있습니다 - 용도 - 현재 상태보기 - 버그 추적 - 로그 분석(빈도 확인) ## 로그 생성하기 ``` import logging import time logging.basicConfig(level=logging.DEBUG) logger = lo...
github_jupyter
# Time of Response and Practicing Effect --- ## 1. Introduction The main difference of responding the SDMT test on paper and responding on digital is thet the second one we have the precise moment every patient performs a task, so we might discover new features as time. We are interested on analyse the time of respo...
github_jupyter
# Anna KaRNNa In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book. This network is based off of Andrej Karpathy's [post on RNNs](http://karpathy.github.io/2015/05/21/rnn-effectiveness/) and [...
github_jupyter
``` !pip install mnist import numpy as np import cv2 import random import matplotlib.pyplot as plt from PIL import Image import mnist random.seed(1) np.random.seed(1) from __future__ import print_function import keras from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers...
github_jupyter
#### - Sobhan Moradian Daghigh #### - 12/3/2021 #### - PR - EX01 - Q6 - Part b. ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import griddata import lmfit ``` #### Reading data ``` dataset = pd.read_csv('./inputs/Q6/first_half_logs.csv', name...
github_jupyter
CT Reconstruction (ADMM Plug-and-Play Priors w/ BM3D, SVMBIR+CG) ================================================================ This example demonstrates the use of class [admm.ADMM](../_autosummary/scico.optimize.rst#scico.optimize.ADMM) to solve a tomographic reconstruction problem using the Plug-and-Play Priors f...
github_jupyter
# Image similarity estimation using a Siamese Network with a contrastive loss **Author:** Mehdi<br> **Date created:** 2021/05/06<br> **Last modified:** 2021/05/06<br> **ORIGINAL SOURCE:** https://github.com/keras-team/keras-io/blob/master/examples/vision/ipynb/siamese_contrastive.ipynb<br> **Description:** Similarity ...
github_jupyter
# Magnetics - Directional derivatives, ASA and ASA2-PVD filtering #### as part of worked filters in NFIS PROJECT - CPRM-UFPR #### CPRM Intern researcher: Luizemara S. A. Szameitat (luizemara@gmail.com) Notebook from https://github.com/lszam/cprm-nfis. Last modified: Dec/2021 ___ ○ References: Richard Blakely (1996). ...
github_jupyter
# Building your own algorithm container With Amazon SageMaker, you can package your own algorithms that can than be trained and deployed in the SageMaker environment. This notebook will guide you through an example that shows you how to build a Docker container for SageMaker and use it for training and inference. By ...
github_jupyter
``` import os os.chdir('../src/') print(os.getcwd()) from traffic_analysis.d05_evaluation.chunk_evaluator import ChunkEvaluator from traffic_analysis.d00_utils.load_confs import load_parameters from traffic_analysis.d06_visualisation.plot_frame_level_map import plot_map_over_time from traffic_analysis.d06_visualisatio...
github_jupyter
# Key Points for Review in this Section - Hyperlinks in Markdown - magic: ```!```, ```%%bash```, ```%%python``` and ```%%file``` - ```shift-tab``` to see help of function - ```zip()``` - ```dict.get(key, otherwise)``` - immutability and identity -- box and things inside - ```functions(*list)``` and ```func...
github_jupyter
<img style="float: left;" src="./images/cemsf.png" width="100"/><img style="float: right;" src="./images/icons.png" width="500"/> # Global ECMWF Fire Forecasting ## Harmonized danger classes According to EFFIS [documentation and user guidelines](https://effis.jrc.ec.europa.eu/about-effis/technical-background/fire-da...
github_jupyter
``` # Import libraries import os import sys import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt from scipy import stats # Here are my rc parameters for matplotlib mpl.rc('font', serif='Helvetica Neue') mpl.rcParams.update({'font.size': 12}) mpl.rcParams['figure.figsize'] = ...
github_jupyter
``` #hide from fastai.vision.all import * from utils import * matplotlib.rc('image', cmap='Greys') ``` # Under the Hood: Training a Digit Classifier ## Pixels: The Foundations of Computer Vision ## Sidebar: Tenacity and Deep Learning ## End sidebar ``` path = untar_data(URLs.MNIST_SAMPLE) #hide Path.BASE_PATH = p...
github_jupyter
``` import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn import metrics import matplotlib.pyplot as plt import seaborn as sns data = pd.read_pickle('../../data/processed/all_samples.pickle') data['datetime'] = pd.to_...
github_jupyter
# First BigQuery ML models for Taxifare Prediction In this notebook, we will use BigQuery ML to build our first models for taxifare prediction.BigQuery ML provides a fast way to build ML models on large structured and semi-structured datasets. ## Learning Objectives 1. Choose the correct BigQuery ML model type and sp...
github_jupyter
``` import pandas as pd fake_news_df = pd.DataFrame(dict(title=[], isFakeNews=[], src=[])) ``` ## COVID-19-rumor-dataset ``` covid_rumour_df = pd.read_csv('COVID-19-rumor-dataset/en_dup.csv') covid_rumour_df = covid_rumour_df[~(covid_rumour_df['label'] == 'U')] # Drop Unknown Label covid_rumour_df['label'] = covid_ru...
github_jupyter
# Sim-launcher This script show how to launch sims using Python ### 1. Package imports ``` import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from dotenv import load_dotenv from pathlib import Path # Python 3.6+ only import os import psycopg2 from psycopg2.extras import execute_values import r...
github_jupyter
# CNN with Bidirctional RNN - Char Classification Using TensorFlow ## TODO ``` ``` ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import math import tensorflow as tf import tensorflow.contrib.seq2seq as seq2seq import cv2 %matplotlib notebook # Increase size of plots plt.rcParams['figure...
github_jupyter
# FVCOM vertical slice along transect ``` %matplotlib inline import numpy as np import matplotlib.pyplot as plt import matplotlib.tri as mtri import cartopy.crs as ccrs from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER import iris import warnings import pyugrid import seawater as sw #url = 'ht...
github_jupyter
## SIMPLE CONVOLUTIONAL NEURAL NETWORK ``` import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data %matplotlib inline print ("PACKAGES LOADED") ``` # LOAD MNIST ``` mnist = input_data.read_data_sets('data/', one_hot=True) trainimg = mn...
github_jupyter
# Checklist * Make sure to have a clock visible * Check network connectivity * Displays mirrored * Slides up * This notebook * ~170% zoom * Ideally using 3.7-pre because it has better error messages: demo-env/bin/jupyter notebook pycon-notebook.ipynb * Full screened (F11) * Hide header and toolbar * Turn on ...
github_jupyter
# Estandarización, covarianza y correlación ``` import numpy as np import pandas as pd import scipy.stats import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline df = pd.read_csv('iris-data.csv', index_col=0) df.columns df.tipo_flor.value_counts() y = df['lar.petalo'] fig, axis = plt.subplots() axis...
github_jupyter
``` # look at tools/set_up_magics.ipynb yandex_metrica_allowed = True ; get_ipython().run_cell('# one_liner_str\n\nget_ipython().run_cell_magic(\'javascript\', \'\', \n \'// setup cpp code highlighting\\n\'\n \'IPython.CodeCell.options_default.highlight_modes["text/x-c++src"] = {\\\'reg\\\':[/^%%cpp/]} ;\'\n \...
github_jupyter
# Optimization with scipy.optimize When we want to optimize something, we do not ofcourse need to start everything from scratch. It is good to know how algorithms work, but if the development of new algorithms is not the main point, then one can just use packages and libraries that have been premade. In Python, there...
github_jupyter
![terrainbento logo](../../../../media/terrainbento_logo.png) # terrainbento model BasicRt steady-state solution This model shows example usage of the BasicRt model from the TerrainBento package. BasicRt modifies Basic by allowing for two lithologies: $\frac{\partial \eta}{\partial t} = - K(\eta,\eta_C) Q^{1/2}S + ...
github_jupyter
# 100 numpy exercises This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow and in the numpy documentation. The goal of this collection is to offer a quick reference for both old and new users but also to provide a set of exercises for those who teach. If you find an...
github_jupyter
# Lecture 1 - Introduction, Variables, and Print Statement *Monday, June 1st 2020* *Rahul Dani* In this lecture, we will cover many fundamental topics to get you started! ## Topic 1 : Variables Variables can be considered as an item that holds a value. You can put any value inside this item. Note that **Python i...
github_jupyter
# <img style="float: left; padding-right: 10px; width: 45px" src="https://raw.githubusercontent.com/Harvard-IACS/2018-CS109A/master/content/styles/iacs.png"> CS-109A Introduction to Data Science ## Lab 2: Linear Regression and k-NN **Harvard University**<br/> **Fall 2019**<br/> **Authors:** Rahul Dave, David Sondak, ...
github_jupyter
## Spatial Adaptive Graph Neural Network for POI Graph Learning In this tuorial, we will go through how to run the Spatial Adaptive Graph Neural Network (SA-GNN) to learn on the POI graph. If you are intersted in more details, please refer to the paper "Competitive analysis for points of interest". ``` import os impo...
github_jupyter
# Coding outside of Jupyter notebooks To be able to run Python on your own computer, I recommend installing [Anaconda](https://www.continuum.io/downloads) which contains basic packages for you to be up and running. While you are downloading things, also try the text editor [Atom](https://atom.io/). We have used Jupy...
github_jupyter
``` %cd .. import os os.environ['SEED'] = "42" import dataclasses from pathlib import Path import warnings import nlp import torch import numpy as np import torch.nn.functional as F from transformers import ( BertForSequenceClassification, DistilBertForSequenceClassification ) from torch.optim.lr_scheduler i...
github_jupyter
``` %matplotlib inline import gym import itertools import matplotlib import numpy as np import sys import tensorflow as tf import collections if "../" not in sys.path: sys.path.append("../") from lib.envs.cliff_walking import CliffWalkingEnv from lib import plotting matplotlib.style.use('ggplot') env = CliffWalki...
github_jupyter
# Example of physical analysis with IPython ``` %pylab inline import numpy import pandas import root_numpy folder = '/moosefs/notebook/datasets/Manchester_tutorial/' ``` ## Reading simulation data ``` def load_data(filenames, preselection=None): # not setting treename, it's detected automatically data = root...
github_jupyter
# FloPy ## MODFLOW 6 (MF6) Support The Flopy library contains classes for creating, saving, running, loading, and modifying MF6 simulations. The MF6 portion of the flopy library is located in: *flopy.mf6* While there are a number of classes in flopy.mf6, to get started you only need to use the main classes summar...
github_jupyter
# Seasonal Naive Approach Benchmark model that simply forecasts the same value from the previous seasonal period. ``` %matplotlib inline import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd matplotlib.rcParams['figure.figsize'] = (16, 9) pd.options.display.max_columns = 999 ``` ##...
github_jupyter
## Getting Started [`Magma`](https://github.com/phanrahan/magma) is a hardware construction language written in `Python 3`. The central abstraction in `Magma` is a `Circuit`, which is analagous to a verilog module. A circuit is a set of functional units that are wired together. `Magma` is designed to work with [`Mant...
github_jupyter
# Measuring monotonic relationships By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie with example algorithms by David Edwards Reference: DeFusco, Richard A. "Tests Concerning Correlation: The Spearman Rank Correlation Coefficient." Quantitative Investment Analysis. Hoboken, NJ: Wiley, 2007 Part of the ...
github_jupyter
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline df= pd.read_csv('911.csv') df.info() df df.head() #zipcodes for 911 calls df['zip'].value_counts() #Top zipcodes for 911 calls df['zip'].value_counts().head(5) #Townships for 911 calls df['twp'].value_...
github_jupyter
## Why automate your work flow, and how to approach the process **Questions for students to consider:** 1) What happens when you get a new dataset that you need to analyze in the same way you analyzed a previous data set? 2) What processes do you do often? How do you implement these? 3) Do you have a clear workfl...
github_jupyter
<h2> How to run this file </h2> To run code in each cell, use shift enter or tinker with cell part of the bar menu above You may come across run issues, look up online references or tinker and figure out, failure of the code is not a big deal as you can always delete a file and start afresh. <h2> About thi...
github_jupyter
``` import sys if "google.colab" in sys.modules: branch = "master" # change to the branch you want ! git clone --single-branch --branch $branch https://github.com/OpenMined/PySyft.git ! cd PySyft && ./scripts/colab.sh # fixes some colab python issues sys.path.append("/content/PySyft/src") # prev...
github_jupyter
# Reference: Implemented: https://towardsdatascience.com/detection-of-price-support-and-resistance-levels-in-python-baedc44c34c9 Alternative: https://medium.com/@judopro/using-machine-learning-to-programmatically-determine-stock-support-and-resistance-levels-9bb70777cf8e ``` import pandas as pd import numpy as np imp...
github_jupyter
``` import math import torch as t import torch.nn as nn import torch.nn.functional as F import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline # activation should be some kind function name as F.relu, F.tanh # this Layer may be realized directly by nn.Module class Layer(nn.Module): ...
github_jupyter
# Narrative ## GOALS - Provide a code narrative in this project including: - a map of the South King County region, - updated tables in comparison with the OY in the Road Map Project Region report, and - final vizualizations for the data. ## Detailed Steps Import the necessary packages. ``` %matplotlib ...
github_jupyter
``` import torch import torchvision import matplotlib.pyplot as plt # import torch.nn.functional as F import glob import scipy.io as sio import matplotlib.pyplot as plt from torchvision import datasets, transforms import torchvision.transforms as transforms from PIL import Image import vgg import glob import numpy as n...
github_jupyter
# 2018-10-02 - Scraping, récupérer une image depuis LeMonde Le notebook suivant récupère le contenu d'une page du journal [Le Monde](https://www.lemonde.f), extrait les urls d'images à l'aide d'une expression régulière puis télécharge les images pour les stocker dans un répertoire. Le notebook extrait les images d'une...
github_jupyter
# Parcels Tutorial Welcome to a quick tutorial on Parcels. This is meant to get you started with the code, and give you a flavour of some of the key features of Parcels. In this tutorial, we will first cover how to run a set of particles [from a very simple idealised field](#Running-particles-in-an-idealised-field). ...
github_jupyter
``` import pandas as pd import numpy as np import openml import os ``` # Download OpenML data ``` dataset_ids = [61] for dataset_id in dataset_ids: print ('Get dataset id', dataset_id) dataset = openml.datasets.get_dataset(dataset_id) X, y, categorical_indicator, attribute_names = dataset.get_data(dataset...
github_jupyter
IN DEVELOPMENT # Part 2: Training an RBM *with* a phase ## Getting Started The following imports are needed to run this tutorial. ``` from rbm_tutorial import RBM_Module, ComplexRBM import torch import cplx import unitary_library import numpy as np import csv ``` *rbm_tutorial.py* contains the child class **Comple...
github_jupyter
<!-- dom:TITLE: Demo - Working with Functions --> # Demo - Working with Functions <!-- dom:AUTHOR: Mikael Mortensen Email:mikaem@math.uio.no at Department of Mathematics, University of Oslo. --> <!-- Author: --> **Mikael Mortensen** (email: `mikaem@math.uio.no`), Department of Mathematics, University of Oslo. Date: ...
github_jupyter
[View in Colaboratory](https://colab.research.google.com/github/adowaconan/Deep_learning_fMRI/blob/master/3_1_some_concepts_of_CNN.ipynb) # Reference ## [How HBO’s Silicon Valley built “Not Hotdog” with mobile TensorFlow, Keras & React Native](https://medium.com/@timanglade/how-hbos-silicon-valley-built-not-hotdog-wit...
github_jupyter
# Bite Size Bayes Copyright 2020 Allen B. Downey License: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/) ## Review [In the previous notebook](https://colab.research.google.com/github/AllenDowney/BiteSizeBayes/blob/master/04_dice.ipynb) ...
github_jupyter
# Verify predictions ``` import pandas as pd import os s3_val_pred_ensemble_file_f1="s3://aegovan-data/pubmed_asbtract/predictions_valtest_ppimulticlass-bert-f1-2021-05-10-9_2021052215/val_multiclass.json.json" s3_test_pred_ensemble_file_f1="s3://aegovan-data/pubmed_asbtract/predictions_valtest_ppimulticlass-bert-f1-2...
github_jupyter
# Nutria In this Notebook we'll consider the population growth of the Nutria species. The data has been taken from .. . We'll begin importing the data and visualizing it. ``` import pandas as pd from pyfilter import __version__ print(__version__) data = pd.read_csv("nutria.txt", sep='\t').iloc[:, 0].rename("nutria")...
github_jupyter
``` import rasterio as rio import numpy as np import matplotlib.pyplot as plt from IPython import display from matplotlib_scalebar.scalebar import ScaleBar ``` # Sensitivity of ASO Snow cover mask to snow depth threshold David Shean May 2, 2020 _(modified by Tony Cannistra, Jan 30, 2021)_ **Purpose**: Examine the c...
github_jupyter
sbpy.data.Ephem Example Notebooks ================================= [Ephem](https://sbpy.readthedocs.io/en/latest/api/sbpy.data.Ephem.html#sbpy.data.Ephem) provides functionality to query, calculate, manipulate, and store ephemerides and observational information. Querying Asteroid Ephemerides from JPL Horizons -----...
github_jupyter
## Introduction This is a quick and dirty notebook to detect VDSL interference in amateur radio bands. The DSP very closly follows Dr Martin Sach's fantastic article on [VDSL2 Detection](http://rsgb.org/main/files/2018/10/VDSL-Radiation-and-its-Signal-Charecterisation.pdf). The purpose of this notebook is not to repla...
github_jupyter
#DV360 Report Create a DV360 report. #License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicab...
github_jupyter
# Collect NISMOD2 results for NIC resilience - demand scenarios - water demand - energy demand - transport OD matrix, trip distribution, energy consumption ``` import glob import os import re from datetime import datetime, timedelta import pandas import geopandas from pandas.api.types import CategoricalDtype from ...
github_jupyter
# Regression Week 4: Ridge Regression (gradient descent) In this notebook, you will implement ridge regression via gradient descent. You will: * Convert an SFrame into a Numpy array * Write a Numpy function to compute the derivative of the regression weights with respect to a single feature * Write gradient descent fu...
github_jupyter
## Testing different libraries for parallel processing in Python ``` import numpy as np # Different ways to speed up your computations using multiple cpu cores def slow_function(n=1000): total = 0.0 for i, _ in enumerate(range(n)): for j, _ in enumerate(range(1, n)): total += (i * j) r...
github_jupyter
# Poisson Distribution *** ## Definition >The Poisson distribution [...] [is a discrete probability distribution] that expresses the probability of a given number of events occurring in a fixed interval of time or space if these events occur with a known constant rate and independently of the time since the last event....
github_jupyter
### Demonstration of triangle slicing Here are some Python based functions for slicing sets of triangles given in an STL file relative to different tool shapes. A "barmesh" is an efficient way of encoding a continuous mesh of triangles using forward-right and back-left pointers from each edge that makes the tri...
github_jupyter
> **Tip**: Welcome to the Investigate a Dataset project! You will find tips in quoted sections like this to help organize your approach to your investigation. Before submitting your project, it will be a good idea to go back through your report and remove these sections to make the presentation of your work as tidy as ...
github_jupyter
# Data Preparation for 2D Medical Imaging ## Kidney Segmentation with PyTorch Lightning and OpenVINO™ - Part 1 This tutorial is part of a series on how to train, optimize, quantize and show live inference on a medical segmentation model. The goal is to accelerate inference on a kidney segmentation model. The [UNet](h...
github_jupyter
# Inheritance with the Gaussian Class To give another example of inheritance, take a look at the code in this Jupyter notebook. The Gaussian distribution code is refactored into a generic Distribution class and a Gaussian distribution class. Read through the code in this Jupyter notebook to see how the code works. Th...
github_jupyter
# Examples depicting the visualization and analysis of Retinal neuron data from mouse brain ## This notebook can be viewed with 3-d plots at [nbviewer](https://nbviewer.jupyter.org/github/natverse/nat.examples/blob/master/notebooks/helmstaedter2013_Mouse_RetinalConnectome.ipynb). ``` library('curl') library('R.matlab...
github_jupyter
``` import heapq import random from PIL import Image import numpy import nltk from IPython.display import display, Image as Img ``` # Minimum Spanning Trees: This tutorial will teach you the basics of Minimum spanning trees, Algorithms on how to make them, and some applications of minimum spanning trees. # Task Zero:...
github_jupyter
###### importing libraries : ``` import numpy as np import matplotlib.pyplot as plt import pandas as pd import os ``` ### Data Pre-processing Step : ###### Reading the Data: ``` dataset = pd.read_csv('Social_Network_Ads.csv') ``` ###### Visulaizing the Data: ``` dataset.shape dataset.head() ``` ###### Defining t...
github_jupyter
## Iterators and Generators In Python, anything which can be iterated over is called an iterable: ``` bowl = { "apple": 5, "banana": 3, "orange": 7 } for fruit in bowl: print(fruit.upper()) ``` Surprisingly often, we want to iterate over something that takes a moderately large amount of memory to st...
github_jupyter
# Introduction to Predictive Maintenance ## Fault Classification using Supervised learning #### Author Nagdev Amruthnath Date: 1/10/2019 ##### Citation Info If you are using this for your research, please use the following for citation. Amruthnath, Nagdev, and Tarun Gupta. "A research study on unsupervised machine ...
github_jupyter
<img align="right" style="max-width: 200px; height: auto" src="hsg_logo.png"> ### Lab 01 - "Introduction to the Lab Environment" Machine Learning (BBWL), University of St. Gallen, Spring Term 2021 The lab environment of the **"Machine Learning"** course is powered by Jupyter Notebooks (https://jupyter.org), which a...
github_jupyter
<center> <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/Logos/organization_logo/organization_logo.png" width="300" alt="cognitiveclass.ai logo" /> </center> <h1>Extracting and Visualizing Stock Data</h1> <h2>Description</h2> Extracting essential data from a dataset and...
github_jupyter
# Source layouts schematics ``` from IPython.display import display # noqa: F401 # ignore used but not imported from pathlib import Path import numpy as np import pandas as pd import verde as vd import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import boost_and_layouts from boost_and_layouts ...
github_jupyter
<a href="https://colab.research.google.com/github/GitMarco27/TMML/blob/main/Notebooks/009_Custom_Loss.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # 3 Minutes Machine Learning ## Episode 9: Custom Loss #### Marco Sanguineti, 2021 --- Welcome to ...
github_jupyter
``` # reload packages %load_ext autoreload %autoreload 2 ``` ### Choose GPU ``` %env CUDA_DEVICE_ORDER=PCI_BUS_ID %env CUDA_VISIBLE_DEVICES=3 import tensorflow as tf gpu_devices = tf.config.experimental.list_physical_devices('GPU') if len(gpu_devices)>0: tf.config.experimental.set_memory_growth(gpu_devices[0], Tr...
github_jupyter
# Create tables summarising contents of each dataset ``` import os from decimal import Decimal import numpy as np import pandas as pd pd.set_option('display.max_colwidth', -1) ``` ## Paths to directories ``` # Network dataset construction directory network_dir = os.path.join(os.path.curdir, os.path.pardir, '1_netw...
github_jupyter
``` import numpy as np import keras from keras import layers from keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D from keras.models import Model, load_model from keras.preprocessing import image from keras.utils im...
github_jupyter
## _*Using QISKit ACQUA for stableset problems*_ This QISKit ACQUA Optimization notebook demonstrates how to use the VQE algorithm to compute the maximum stable set of a given graph. The problem is defined as follows. Given a graph $G = (V,E)$, we want to compute $S \subseteq V$ such that there do not exist $i, j \...
github_jupyter
# How to contribute to jupyter notebooks ``` from fastai.gen_doc.nbdoc import * from fastai.gen_doc.gen_notebooks import * from fastai.gen_doc import * ``` The documentation is built from notebooks in `docs_src/`. Follow the steps below to build documentation. For more information about generating and authoring noteb...
github_jupyter
``` import numpy as np from utils_h5 import H5Loader from astroNN.apogee import aspcap_mask from astroNN.models import ApogeeBCNNCensored loader = H5Loader('__train') # continuum normalized dataset loader.load_err = True loader.target = ['teff', 'logg', 'C', 'C1', 'N', 'O', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'K', ...
github_jupyter
# SchNet S2EF training example The purpose of this notebook is to demonstrate some of the basics of the Open Catalyst Project's (OCP) codebase and data. In this example, we will train a schnet model for predicting the energy and forces of a given structure (S2EF task). First, ensure you have installed the OCP ocp repo...
github_jupyter
# Unstructured Data Wrangling ``` import os import chardet os.listdir()[3] import pandas as pd # dictionary to form the dataframe connection_dict = {'contact_name': [], 'position': [], 'timespan': [], 'timespan_type': [], 'tier_status': [], ...
github_jupyter
# Softmax exercise *Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see the [assignments page](http://vision.stanford.edu/teaching/cs231n/assignments.html) on the course website.* This exercise is ...
github_jupyter
SOP033 - azdata logout ====================== Use the azdata command line interface to logout of a Big Data Cluster. Steps ----- ### Common functions Define helper functions used in this notebook. ``` # Define `run` function for transient fault handling, hyperlinked suggestions, and scrolling updates on Windows im...
github_jupyter
``` # Visualization of the KO+ChIP Gold Standard from: # Miraldi et al. (2018) "Leveraging chromatin accessibility for transcriptional regulatory network inference in Th17 Cells" # TO START: In the menu above, choose "Cell" --> "Run All", and network + heatmap will load # NOTE: Default limits networks to TF-TF edges i...
github_jupyter
``` from PIL import Image, ImageOps, ImageMath, ImageEnhance #%pylab inline %matplotlib inline import numpy as np import matplotlib.pyplot as plt def add_transparency(bg_image): if (bg_image.mode is not "RGBA"): bg_image = bg_image.convert("RGBA") pixdata = bg_image.load() for y in xrange(bg_imag...
github_jupyter
# Image classification - training from scratch demo 1. [Introduction](#Introduction) 2. [Prerequisites and Preprocessing](#Prequisites-and-Preprocessing) 3. [Fine-tuning the Image classification model](#Fine-tuning-the-Image-classification-model) 4. [Set up hosting for the model](#Set-up-hosting-for-the-model) 1. [I...
github_jupyter
# Cloudwatch Metrics に学習過程のスコアを書き出す ## 概要 このノートブックでは,Amazon SageMaker 上で学習する際のスコアを,Cloudwatch Metrics に書き出して可視化するやり方について確認します. ## データセットのS3へのアップロード - keras.datasetsを利用してmnistのデータをダウンロードしてnpz形式で保存します。 - 保存したnpz形式のファイルを、SageMaker Python SDKを利用してS3にアップロードします。 ``` import os import keras import numpy as np from keras....
github_jupyter
``` import os import sys import itertools import copy import glob import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib as mpl from n2j import trainval_data import n2j.trainval_data.utils.raytracing_utils as ru import n2j.trainval_data.utils.halo_utils as hu import n2j.trainval_data.u...
github_jupyter