text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
## Facial Filters Using your trained facial keypoint detector, you can now do things like add filters to a person's face, automatically. In this optional notebook, you can play around with adding sunglasses to detected face's in an image by using the keypoints detected around a person's eyes. Checkout the `images/` di...
github_jupyter
# Building a Supervised Machine Learning Model The objective of this hands-on activity is to create and evaluate a Real-Bogus classifier using ZTF alert data. We will use the same data from the Day 2 clustering exercise (see [that notebook](https://github.com/LSSTC-DSFP/LSSTC-DSFP-Sessions/blob/master/Session7/Day2/C...
github_jupyter
``` import numpy as np from gridworld import GridworldEnv env = GridworldEnv() def policy_eval(policy, env, discount_factor=1.0, theta=0.00001): """ Evaluate a policy given an environment and a full description of the environment's dynamics. Args: policy: [S, A] shaped matrix representing the p...
github_jupyter
# IoT Microdemos ## Indexing Strategy A proper indexing strategy is key for efficient querying of data. The first index is mandatory for efficient time series queries in historical data. The second one is needed for efficient retreival of the current, i.e. open, bucket for each device. If all device types have the s...
github_jupyter
<p style="font-family: Arial; font-size:3.75em;color:purple; font-style:bold"><br> Introduction to numpy: </p><br> <p style="font-family: Arial; font-size:1.25em;color:#2462C0; font-style:bold"><br> Package for scientific computing with Python </p><br> Numerical Python, or "Numpy" for short, is a foundational package...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline import os import cv2 data_dir= r'C:\Users\Benyamin\Downloads\DATASET\four-shapes\shapes' cat=['circle','square','star','triangle'] for category in cat: path=os.path.join(data_dir,category) for img in os.listdir(path):...
github_jupyter
# Explaining Tree Models with Interventional Feature Perturbation Tree SHAP <div class="alert alert-info"> To enable SHAP support, you may need to run ```bash pip install alibi[shap] ``` </div> ## Introduction This example shows how to apply interventional Tree SHAP to compute shap values exactly for an `xgboo...
github_jupyter
``` import torch import torch.nn.functional as F import torchsde from torchvision import datasets, transforms import math import numpy as np import pandas as pd from tqdm import tqdm import scipy.io import os from torchvision.transforms import ToTensor from torch.utils.data import DataLoader, TensorDataset import fu...
github_jupyter
``` # 0110101 # 1011111 # suma=0; # for(int i = 0; i < n; i++) { # if(i % 3 == 0) { # suma+=i; # } # } # primitivne funkcije: +,-,* # terminali: celi brojevi [-20, 20] # X=5000 # (a.b).(c.d) # izraz: (2+3)*(4-1) # code: ['*' '+' '-' 2 3 4 1] eval('2+3*4') 0 1 2 3 4 5 6 ['*' '+' '-' 2 3 4 1] -> ...
github_jupyter
# Learning to compute a product Unlike the communication channel and the element-wise square, the product is a nonlinear function on multiple inputs. This represents a difficult case for learning rules that aim to generalize a function given many input-output example pairs. However, using the same type of network stru...
github_jupyter
``` from google.colab import drive drive.mount('/content/drive', force_remount = True) %tensorflow_version 2.x !pip install tiffile !pip install gputools !pip install imagecodecs !pip install vollseg %cd '/content/drive/My Drive/VollSeg/' import os import glob import sys import numpy as np from tqdm import tqdm from...
github_jupyter
# Python modeling of the impact of social distancing and early termination of lockdown ### Dr. Tirthajyoti Sarkar, Fremont, CA 94536 --- ## What is this demo about? The greatest [global crisis since World War II](https://www.bloomberg.com/opinion/articles/2020-03-24/coronavirus-recession-it-will-be-a-lot-like-world-wa...
github_jupyter
# Evaluate Modified Algorithms - part 1 ## BalancedBaggingClassifier ``` from imblearn.ensemble import BalancedBaggingClassifier from sklearn.ensemble import BaggingClassifier from sklearn.datasets import make_classification from imblearn.under_sampling import RandomUnderSampler from sklearn.model_selection import St...
github_jupyter
# Kalman-Stan ``` rm(list = ls()) library(rstan) library(reshape2) library(ggplot2) rstan_options(auto_write = TRUE) options(mc.cores = parallel::detectCores()) ``` In many settings, the permanent and transitory component of an aggregate time series (like labour income) is estimated by writing up a state space repres...
github_jupyter
``` import astropy.units as u from astroduet.duet_telescope import load_telescope_parameters from astroduet.duet_sensitivity import src_rate, bgd_sky_qe_rate, bgd_electronics, calc_exposure from astroduet.duet_neff import get_neff from astroduet.bbmag import bb_abmag_fluence import numpy as np from matplotlib import py...
github_jupyter
# Exercise 7 The result will be evaluated from a report in Jupyter, which must be found in a public GitHub repository. The project must be carried out in the groups assigned in class. Use clear and rigorous procedures. Due date: July 20, 2021, 11:59 pm, through Bloque Neón + (Upload repository link) # Part 1 - DT ##...
github_jupyter
# Burn Wound Classification by Transfer Learning by Carsten Isert, Nov. 2017 This notebook is originally based on the dog-breed classification notebook from the Udacity AI Nanodegree. ## Motivation The goal of this first step is to classify the burn degree on a given image. There are two stages that will be covere...
github_jupyter
# Data description & Problem statement: The dataset is related to red vinho verde wine samples, from the north of Portugal. The goal is to model wine quality based on physicochemical tests. For more details, please check: https://archive.ics.uci.edu/ml/datasets/wine+quality * Dataset is imbalanced. The data has 4898 r...
github_jupyter
# Working with Images stored on the OMERO server using Cell Profiler This notebook demonstrates how to retrieve Images stored in OMERO and process them using [CellProfiler](http://cellprofiler.org/). The output is saved back to OMERO as CSV attachments. For this example, we use the pipeline [FruitFlyCells](http://cell...
github_jupyter
# Logistic Regression with a Neural Network mindset Welcome to your first (required) programming assignment! You will build a logistic regression classifier to recognize cats. This assignment will step you through how to do this with a Neural Network mindset, and so will also hone your intuitions about deep learning....
github_jupyter
``` %matplotlib inline ``` How to post-process simulation data ================================================== In this example we compute the scattering through an orifice plate in a circular duct with flow. The data is extracted from two Comsol Multiphysics simulations with a similar setup as in `this study <htt...
github_jupyter
# Assignment 3 Ungraded Sections - Part 1: BERT Loss Model Welcome to the part 1 of testing the models for this week's assignment. We will perform decoding using the BERT Loss model. In this notebook we'll use an input, mask (hide) random word(s) in it and see how well we get the "Target" answer(s). ## Colab Since...
github_jupyter
``` import pandas as pd import numpy as np df_us_counties = pd.read_csv('data/us-counties.csv') df_us_counties df_us_states = pd.read_csv('data/us-states.csv') df_us_states df_us_states = df_us_states.sort_values(["state", "date"]).reset_index() df_us_states # loop to reverse cumulative death count and get daily number...
github_jupyter
# Image features 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.* We have see...
github_jupyter
``` import numpy as np import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.models import Model from tensorflow.keras import applications from tensorflow.keras.layers import BatchNormalization, Conv2D, AveragePooling2D, TimeDistributed, Dense, Dropout, Activa...
github_jupyter
<a href="http://landlab.github.io"><img style="float: left" src="https://raw.githubusercontent.com/landlab/tutorials/release/landlab_header.png"></a> # Animate Landlab output <hr> <p><small>More Landlab tutorials: <a href="https://landlab.readthedocs.io/en/latest/user_guide/tutorials.html">https://landlab.readthedocs...
github_jupyter
# Multivariate Time Series Forecasting Multivariate time series forecasting works similarly to univariate time series forecasting (covered [here](0_ForecastIntro.ipynb) and [here](1_ForecastFeatures.ipynb)). The main difference is that you must specify the index of a target univariate to forecast, e.g. for a 5-variabl...
github_jupyter
``` # This cell is added by sphinx-gallery !pip install mrsimulator --quiet %matplotlib inline import mrsimulator print(f'You are using mrsimulator v{mrsimulator.__version__}') ``` # ⁸⁷Rb 2D 3QMAS NMR of RbNO₃ The following is a 3QMAS fitting example for $\text{RbNO}_3$. The dataset was acquired and shared by Bre...
github_jupyter
# Project 2: Inference and Capital Punishment Welcome to Project 2! You will investigate the relationship between murder and capital punishment (the death penalty) in the United States. By the end of the project, you should know how to: 1. Test whether observed data appears to be a random sample from a distribution...
github_jupyter
# Diagrams Overview One piece generate document workflows allow for the creation of materials containing a wide variety of simple diagrams produced from simple text descriptions contained within the body of the document. Making changes to the diagram simply requires a change to the original text description of it. Wh...
github_jupyter
``` #Function to generate a 3-panel plot for input arrays def plot_array(dem, clim=None, titles=None, cmap='inferno', label=None, overlay=None, fn=None, close_fig=True): fig, ax = plt.subplots(1,1, sharex=True, sharey=True, figsize=(10,5)) alpha = 1.0 #Gray background ax.set_facecolor('0.5') #Force ...
github_jupyter
# TTstar benchmarks First, let's get formalities out of the way. ``` library(ggplot2) library(reshape2) library(repr) library(dplyr) options(repr.plot.width=4, repr.plot.height=3) # load measured data #xs <- read.csv('benchmark-1490607733.csv') #xs <- read.csv('benchmark-1491380156.csv') #xs <- read.csv('benchmark-1...
github_jupyter
![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true) <a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=SocialStudies/BubonicPlague/bubonic-pla...
github_jupyter
### Attacks Our implementation inludes three black-box patch attacks: Texture-based Patch Attack (TPA), MonoChrome Patch Attack (MPA) in our [paper](https://arxiv.org/abs/2004.05682); Metropolis-Hastings Attack (HPA) originally proposed in [paper](http://www.bmva.org/bmvc/2016/papers/paper137/index.html). Besides, we ...
github_jupyter
# test note * jupyterはコンテナ起動すること * テストベッド一式起動済みであること ``` from pathlib import Path # settings cell # mounted dir ait_dir = Path('/workdir/root') ait_name='eval_bdd100k_aicc_tf2.3' ait_full_name='eval_bdd100k_aicc_tf2.3_0.1' # (dockerホスト側の)インベントリ登録用アセット格納ルートフォルダ #invenotory_root_dir=r'F:\qai-testbed\dev\qai-testbe...
github_jupyter
# TensorFlow 자습서 #03-B # Layers API 원저자 [Magnus Erik Hvass Pedersen](http://www.hvass-labs.org/) / [GitHub](https://github.com/Hvass-Labs/TensorFlow-Tutorials) / [Videos on YouTube](https://www.youtube.com/playlist?list=PL9Hr9sNUjfsmEu1ZniY0XpHSzl5uihcXZ) / 번역 곽병권 ## 개요 TensorFlow에서 신경망을 만들 때 빌더 API를 사용하는 것이 중요합니다. ...
github_jupyter
This work implement the paper of "Preference fusion for community detection in social networks" F.Elarbi, T.Bouadi, A.Martin, B. Ben Yaghlane Coded by Yiru Zhang <yiru.zhang@irisa.fr> ``` import numpy as np import csv import networkx as nx import matplotlib.pyplot as plt #define the class for belief fuction of one p...
github_jupyter
### Dependencies ``` import os import cv2 import math import random import shutil import warnings import numpy as np import pandas as pd import seaborn as sns import multiprocessing as mp import albumentations as albu import matplotlib.pyplot as plt from tensorflow import set_random_seed from sklearn.model_selection i...
github_jupyter
<a href="https://colab.research.google.com/github/mateusjunges/music-gender-detection/blob/master/music-gender-detection.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` # Imports import cv2 import numpy as np import pandas as pd import re import...
github_jupyter
<h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#RNN-(Recurrent-Neural-Network)" data-toc-modified-id="RNN-(Recurrent-Neural-Network)-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>RNN (Recurrent Neural Network)</a></span><ul class="toc-item"><li><span...
github_jupyter
##### Copyright 2020 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); ``` #@title License # 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.or...
github_jupyter
``` %matplotlib inline ``` # Demo Agg Filter ``` import matplotlib.cm as cm import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms from matplotlib.colors import LightSource from matplotlib.artist import Artist import numpy as np def smooth1d(x, window_len): # copied from http://www.scipy.o...
github_jupyter
.. _nb_subset_selection: ## Subset Selection Problem A genetic algorithm can be used to approach subset selection problems by defining custom operators. In general a metaheuristic algorithm might not be the ultimate goal to implement in a real-world scenario, however, it might be useful to investigate patterns or cha...
github_jupyter
``` # importing prerequisites import sys import requests import cv2 import random import tarfile import json import numpy as np import pdf2image from os import path from PIL import Image from PIL import ImageFont, ImageDraw from glob import glob from matplotlib import pyplot as plt from pdf2image import convert_from_pa...
github_jupyter
``` from src.dataset_wrapper import * from src.networks import * import torch from tqdm import tqdm import numpy as np import matplotlib.pyplot as plt import matplotlib import pickle device = 'cuda:0' net_params = { "relation_dim": 23, "object_dim": 8, "hidden_dim": 256, } dataset_params = { "d...
github_jupyter
# Numerical solution to the 1-dimensional Time Independent Schroedinger Equation Based on the paper "Matrix Numerov method for solving Schroedinger's equation" by Mohandas Pillai, Joshua Goglio, and Thad G. Walker, _American Journal of Physics_ **80** (11), 1017 (2012). [doi:10.1119/1.4748813](http://dx.doi.org/10.111...
github_jupyter
``` try: from openmdao.utils.notebook_utils import notebook_mode except ImportError: !python -m pip install openmdao[notebooks] ``` # ExplicitComponent Explicit variables are those that are computed as an explicit function of other variables. For instance, $z$ would be an explicit variable, given $z=sin(y)$, ...
github_jupyter
[![AnalyticsDojo](https://github.com/rpi-techfundamentals/spring2019-materials/blob/master/fig/final-logo.png?raw=1)](http://rpi.analyticsdojo.com) <center><h1>Introduction to Feature Creation & Dummy Variables</h1></center> <center><h3><a href = 'http://rpi.analyticsdojo.com'>rpi.analyticsdojo.com</a></h3></center> ...
github_jupyter
# Q-Learning * value learning : state + action * learn to find a max Q(s, a) (Q function calculates the max discounted future value, Q value) * Q value: the expected long-term rewards $$Q^*(s_t, a_t) = max_\pi{E[\sum^T_{i=t}\gamma^ir^i]}$$ * the chicken-and-egg conundrum ## Bellman Function * redefine Q-value as...
github_jupyter
# Building a Controller The following documents the development of a new controller. In this case we are going to implement an arbitrary controllable storage unit. This may be a battery, an electrically powered car or some sort of reservoir storage. ## Modelling a Battery In order to simulate a storage system we use...
github_jupyter
Note: The evals here have been run on GPU so they may not exactly match the results reported in the paper which were run on TPUs, however the difference in accuracy should not be more than 0.1%. # Setup ``` import tensorflow as tf import tensorflow_datasets as tfds CROP_PROPORTION = 0.875 # Standard for ImageNet. HE...
github_jupyter
``` # reload packages %load_ext autoreload %autoreload 2 ``` ### Choose GPU (this may not be needed on your computer) ``` %env CUDA_DEVICE_ORDER=PCI_BUS_ID %env CUDA_VISIBLE_DEVICES=0 import tensorflow as tf gpu_devices = tf.config.experimental.list_physical_devices('GPU') tf.config.experimental.set_memory_growth(gpu...
github_jupyter
# Notebook showing how to correctly calculate CPUE for CCFRP data ``` # Imports import numpy as np import pandas as pd # Load data occ = pd.read_csv('CCFRP_grid-level_occurrence.csv') mof = pd.read_csv('CCFRP_grid-level_mof.csv', sep=',') ``` **Note** that I've now included an `organismQuantity` column in occ that ...
github_jupyter
# Windowed-Sinc Filters Windowed-sinc filters are used to separate one band of frequencies from another. They are very stable, produce few surprises, and can be pushed to incredible performance levels. These exceptional frequency domain characteristics are obtained at the expense of poor performance in the time domain,...
github_jupyter
# pandas, linear regression * регрессия - линию провести * классификация - конечное чило ответов или бинарная калссификация * много классовая классификация - от 1 до К классов * классификация с пересекающими классами - (какая тема в статье? математика, биология, экономика) * ранжирования - набор документов $d_1, ......
github_jupyter
<center> <h2> DS 3000 - Fall 2021</h2> </center> <center> <h3> DS Report </h3> </center> <center> <h3>E-Commerce Trends</h3> </center> <center><h4>Armaan Pruthi, Angel Gong, Aritra Saharay</h4></center> <hr style="height:2px; border:none; color:black; background-color:black;"> #### Executive Summary: The e-commerce...
github_jupyter
## Amazon SageMaker Processing jobs *이 노트북은 [Amazon SageMaker Processing jobs (영문 원본)](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/sagemaker_processing/scikit_learn_data_processing_and_model_evaluation/scikit_learn_data_processing_and_model_evaluation.ipynb) 의 한국어 번역입니다.* Amazon SageMaker Process...
github_jupyter
##### Copyright 2019 The TensorFlow Authors. ``` #@title 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 applicable law or ...
github_jupyter
# Exporting BioCantor data models BioCantor data models can be exported to any of: 1. GenBank 2. GFF3 3. JSON 4. BED (TranscriptInterval and FeatureInterval only). The JSON representation can be read directly by the `marshmallow` data structures that build the data model. ``` from inscripta.biocantor.io.gff3.parser...
github_jupyter
<a href="https://colab.research.google.com/github/raoyongming/DynamicViT/blob/master/colab_demo.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` !git clone https://github.com/raoyongming/DynamicViT.git ``` ``` !pip install timm import os os.ch...
github_jupyter
# Assignment 2: Naive Bayes Welcome to week two of this specialization. You will learn about Naive Bayes. Concretely, you will be using Naive Bayes for sentiment analysis on tweets. Given a tweet, you will decide if it has a positive sentiment or a negative one. Specifically you will: * Train a naive bayes model on a...
github_jupyter
<i>Copyright (c) Microsoft Corporation. All rights reserved.</i> <i>Licensed under the MIT License.</i> # Standard Variational Autoencoders for Collaborative Filtering on MovieLens dataset. This notebook accompanies the paper "*A Hybrid Variational Autoencoder for Collaborative Filtering*" by Kilol Gupta, Mukund Y. ...
github_jupyter
# Character level language model - Dinosaurus land Welcome to Dinosaurus Island! 65 million years ago, dinosaurs existed, and in this assignment they are back. You are in charge of a special task. Leading biology researchers are creating new breeds of dinosaurs and bringing them to life on earth, and your job is to gi...
github_jupyter
``` from medpy.io import load image_data, image_header = load('training/HGG/brats_tcia_pat447_0313/VSD.Brain.XX.O.MR_T1.41130.mha') image_data.shape image_data image_header.get_voxel_spacing() image_header.get_offset() from medpy.filter import otsu threshold = otsu(image_data) output_data = image_data > threshold thres...
github_jupyter
# Plot.ly Charts ``` import pickle from collections import Counter, OrderedDict # load the pickled files from previous notebook meat_potatoes_sent = pickle.load(open("aws_backup/meat_potatoes_sentiment.pkl", "rb")) meat_potatoes_dict = pickle.load(open("aws_backup/meat_potatoes_dict.pkl", "rb")) primanti_sent = pickl...
github_jupyter
``` import keras keras.__version__ ``` # Predicting house prices: a regression example This notebook contains the code samples found in Chapter 3, Section 6 of [Deep Learning with Python](https://www.manning.com/books/deep-learning-with-python?a_aid=keras&a_bid=76564dff). Note that the original text features far more...
github_jupyter
# Week 2 - Classical ML Models ## 2. Introduction to Scikit-learn Started as a Google Summer of Code project in 2007, **scikit-learn** is one of the most popular machine learning libraries today. It provides efficient implementations of the ML models we will be taking a look at this week, as well as various other uti...
github_jupyter
# Implementing the Gradient Descent Algorithm In this lab, we'll implement the basic functions of the Gradient Descent algorithm to find the boundary in a small dataset. First, we'll start with some functions that will help us plot and visualize the data. ``` import matplotlib.pyplot as plt import numpy as np import ...
github_jupyter
# 빅데이터 분석 기말고사 - toc:true - branch: master - badges: false - comments: false - author: 최서연 - categories: [Big Data Analysis] ## `#1`. 체인룰과 역전파기법 주어진 자료가 아래와 같다고 하자. - ${\bf X} = \begin{bmatrix} 1 & 2.1 \\ 1 & 3.0 \end{bmatrix}$ - ${\bf y} = \begin{bmatrix} 3.0 \\ 5.0 \end{bmatrix}$ 손실함수의 정의가 아래와 같다고 하자. $$lo...
github_jupyter
``` from quchem.Hamiltonian_Generator_Functions import * from quchem.Graph import * ### HAMILTONIAN start Molecule = 'H2' geometry = [('H', (0., 0., 0.)), ('H', (0., 0., 0.74))] basis = 'sto-3g' ### Get Hamiltonian Hamilt = Hamiltonian_PySCF(Molecule, run_scf=1, run_mp2=1, run_cisd=1, run_ccsd=1,...
github_jupyter
``` import os import tensorflow as tf import tensorflow.python.platform from tensorflow.python.platform import gfile import numpy as np import glob classes = np.array(['ayam_bakar', 'ayam_crispy', 'bakso', 'gado2', 'ikan_bakar', 'mie_goreng', 'nasi_goreng', 'pecel_lele', 'pizza', 'rendang', 'sate', 'soto', 'sushi']) n...
github_jupyter
# K Nearest Neighbors Project Welcome to the KNN Project! This will be a simple project very similar to the lecture, except you'll be given another data set. Go ahead and just follow the directions below. ## Import Libraries **Import pandas,seaborn, and the usual libraries.** ``` import pandas as pd import numpy as ...
github_jupyter
# Publications markdown generator for academicpages Takes a set of bibtex of publications and converts them for use with [academicpages.github.io](academicpages.github.io). This is an interactive Jupyter notebook ([see more info here](http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/what_is_jupyter.html...
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
<h1> OpenSees Examples Manual Examples for OpenSeesPy</h1> <h2>OpenSees Example 1a. 2D Elastic Cantilever Column -- Earthquake Ground Motion</h2> <p> You can find the original Examples:<br> https://opensees.berkeley.edu/wiki/index.php/Examples_Manual<br> Original Examples by By Silvia Mazzoni & Frank McKenna, 2006, i...
github_jupyter
# NumPy ``` # importação do pacote abaixo com abreviação import numpy as np ``` # NumPy - criação de matrizes ``` # Matriz de uma dimensão np.array([1,2,3]) # Matriz bidimensional np.array([[1, 2], [3, 4]]) # Array 1D de comprimento 3 todos os valores 0 np.zeros(3) # Matriz 3x4 com todos os valores em 1 np.ones((...
github_jupyter
### AnADAMA2 Example: A workflow to download files in parallel [AnADAMA2](http://huttenhower.sph.harvard.edu/anadama2) is the next generation of AnADAMA (Another Automated Data Analysis Management Application). AnADAMA is a tool to create reproducible workflows and execute them efficiently. Tasks can be run locally or...
github_jupyter
``` import glob import pandas as pd import numpy as np import networkx as nx import seaborn as sns print(nx.__version__) from matplotlib import pyplot as plt import sys sys.path.append('../.') from comap.mapper import CoMap from comap.graph_utils import (compute_graph_deltas) from comap.helper_utils import (get_red...
github_jupyter
#1. Install Dependencies First install the libraries needed to execute recipes, this only needs to be done once, then click play. ``` !pip install git+https://github.com/google/starthinker ``` #2. Get Cloud Project ID To run this recipe [requires a Google Cloud Project](https://github.com/google/starthinker/blob/mast...
github_jupyter
``` # Import Libraries import numpy as np import pandas as pd import os from torchsummary import summary import sys import torch from time import time import torch.nn as nn import torch.optim as optim from torch.utils import data from torch.autograd import Variable import transformers import random import pickle from...
github_jupyter
Azure ML & Azure Databricks notebooks by Parashar Shah. Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. We support installing AML SDK as library from GUI. When attaching a library follow this https://docs.databricks.com/user-guide/libraries.html and add the below string as y...
github_jupyter
# Week 1 - Exercises ## Working with Numbers ``` ## create a variable called num equal to 30 billion in scientific notation ## print it as "This number is $30,000,000,000.00" using f-string literal (2 decimal places) ## create a variable called num2 equal to 30 billion in scientific notation ## Print it like you did ...
github_jupyter
# Сглаживание как способ быстрого решения негладких задач $$ \min_x f(x) $$ Основано на статье [Smooth minimization of non-smooth functions](https://www.math.ucdavis.edu/~sqma/MAT258A_Files/Nesterov-2005.pdf) by Y. Nesterov ## Текущие достижения для выпуклых функций - Функция $f$ негладкая $$ \epsilon \sim O\left...
github_jupyter
``` # MODIFY! # use Robust! model_name = 'poi-baseline-no' import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv('./data/d-no-ns.csv') # df.columns # df.head() df.shape # df.info() X = df.drop('throughput',axis=1) X.shape y = df['throughput'] y.shape # Split the...
github_jupyter
# RGI11 (Central Europe) F. Roura-Adseiras & Fabien Maussion Goal: - Alps: updates of the Paul 2003 dataset - Pytrenees: new inventory by Izagirre ``` import pandas as pd import geopandas as gpd import subprocess import matplotlib.pyplot as plt import matplotlib.patches as mpatches import seaborn as sns import numpy...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import accuracy_score from keras.datasets import cifar10 from keras.models import Model, Sequential from keras.layers import Input, Dense, Concatenate, Reshape, Dropout, Conv...
github_jupyter
The main package used in this notebook is **CasADi**. It has automatic differentiacion capabilities, focuses in optimal control. Its following integration are used: - IDAS, for diferential algebraic equations - IPOPT for non linear optimization ``` %matplotlib inline from casadi import SX,DM,solve,substitute,kr...
github_jupyter
``` #!pip install torch==1.0.1 ## uploading files and put it in the right folder #!mkdir data #!mkdir checkpoint #!mkdir models #!mv abstract.py data #!mv common.py data #!mv iCIFAR.py data #!mv idadataloader.py data #!mv cifar_order.npy data from torch import tensor import torch import torch.nn as nn import torch.opti...
github_jupyter
# Realization of Recursive Filters *This jupyter notebook is part of a [collection of notebooks](../index.ipynb) on various topics of Digital Signal Processing. Please direct questions and suggestions to [Sascha.Spors@uni-rostock.de](mailto:Sascha.Spors@uni-rostock.de).* ## Cascaded Structures The realization of rec...
github_jupyter
``` import pickle import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt import datetime font = {'family': 'sans-serif', # Helvetica 'size' : 12} matplotlib.rc('font', **font) text = {'usetex': False} matplotlib.rc('text', **text) monospace_font = {'fontname':'monospace'} ...
github_jupyter
# Profiling and Optimizing * * * By C Hummels (Caltech) ``` import random import numpy as np from matplotlib import pyplot as plt ``` It can be hard to guess which code is going to operate faster just by looking at it because the interactions between software and computers can be extremely complex. The best way ...
github_jupyter
# Convolution :label:`ch_conv_cpu` In this section, we will optimize the convolution operator defined in :numref:`ch_conv` on CPUs. Specifically, this is a 2-D convolution operator. ## Setup ``` def set_env(num, current_path='.'): import sys from pathlib import Path ROOT = Path(current_path).resolve().p...
github_jupyter
``` %load_ext autoreload %autoreload 2 %aimport utils_1_1 import pandas as pd import numpy as np import altair as alt from altair_saver import save import datetime import dateutil.parser from os.path import join from constants_1_1 import SITE_FILE_TYPES from utils_1_1 import ( get_site_file_paths, get_site_fi...
github_jupyter
# Introduction: Using Watt Time to Find Energy Sources The purpose of this notebook is to explore the Watt Time API to find what kind of electricity we are currently using. The Watt Time API allows us to see a breakdown of the energy generation for a given location. ``` # Standard Data Science Helpers import numpy as...
github_jupyter
``` import pandas as pd from pandas import ExcelWriter from pandas import ExcelFile import datetime as dt from datetime import datetime, timedelta import numpy as np import xarray as xr import matplotlib.pyplot as plt from copy import copy from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import ...
github_jupyter
# Simple RNN In ths notebook, we're going to train a simple RNN to do **time-series prediction**. Given some set of input data, it should be able to generate a prediction for the next time step! ![image.png](attachment:image.png)<img src='assets/time_prediction.png' width=40% /> > * First, we'll create our data * The...
github_jupyter
``` # !wget https://f000.backblazeb2.com/file/malay-dataset/keyphrase/keyphrase-twitter-no-calon.json # !wget https://raw.githubusercontent.com/huseinzol05/Malay-Dataset/master/keyphrase/twitter-bahasa/topics.json import os os.environ['CUDA_VISIBLE_DEVICES'] = '1' import json with open('topics.json') as fopen: top...
github_jupyter
# Python avançado - Parte 1 ## Dados em cores - [Sistemas de Cor PANTONE](www.pantone.com/color-systems/pantone-color-systems-explained) - PANTONE MATCHING SYSTEM (PMS): adequado para impressão, artes gráficas e trabalhos digitais; - FASHION, HOME + INTERIORS (FHI) SYSTEM: adequado para vestuário, tecidos, ma...
github_jupyter
# Table of Contents <p><div class="lev1 toc-item"><a href="#TP-6---Programmation-pour-la-préparation-à-l'agrégation-maths-option-info" data-toc-modified-id="TP-6---Programmation-pour-la-préparation-à-l'agrégation-maths-option-info-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>TP 6 - Programmation pour la préparati...
github_jupyter
# Detecting active ranges Here we examine, how a modestly deep network of dense layers is able to recognize the fact that a single feature influences the prediction only when it is within a certain range. ``` %matplotlib inline import random import numpy as np import pandas as pd import matplotlib.pyplot as plt impor...
github_jupyter