code
stringlengths
2.5k
150k
kind
stringclasses
1 value
# Uncertainty Sampling on the Radio Galaxy Zoo ``` import sys import h5py, numpy, sklearn.neighbors from astropy.coordinates import SkyCoord import matplotlib.pyplot as plt sys.path.insert(1, '..') import crowdastro.train, crowdastro.test TRAINING_H5_PATH = '../training.h5' CROWDASTRO_H5_PATH = '../crowdastro.h5' N...
github_jupyter
<a href="https://colab.research.google.com/github/lasyaistla/Ai.fellowship/blob/main/Copy_of_Style_Transfer_PyTorch.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Please complete the missing parts in the code below. Moreover, please correct the m...
github_jupyter
# Assignment 1: Numpy RNN Implement a RNN and run BPTT ``` from typing import Dict, Tuple import numpy as np class RNN(object): """Numpy implementation of sequence-to-one recurrent neural network for regression tasks.""" def __init__(self, input_size: int, hidden_size: int, output_size: int): """I...
github_jupyter
<a href="https://colab.research.google.com/github/marixko/Supervised_Learning_Tutorial/blob/master/The_Basics_of_Supervised_Learning_For_Astronomers.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ###**About Google's Colaboratory: ** This is a fre...
github_jupyter
``` import numpy as np import pandas as pd import xarray as xr import xesmf as xe import json import matplotlib.pyplot as plt import cartopy.crs as ccrs def make_regridder(ds, ds_base, variable, algorithm='bilinear'): if 'latitude' in ds[variable].dims: ds = ds.rename({'latitude': 'lat', 'longitude': 'lon...
github_jupyter
# Peform statistical analyses of GNSS station locations and tropospheric zenith delays **Author**: Simran Sangha, David Bekaert - Jet Propulsion Laboratory This notebook provides an overview of the functionality included in the **`raiderStats.py`** program. Specifically, we outline examples on how to perform basic st...
github_jupyter
<a href="https://colab.research.google.com/github/probml/probml-notebooks/blob/main/notebooks/smc_logreg_tempering.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> #SMC for logistic regression We compare data tempering (IBIS) with temperature temper...
github_jupyter
* basic roberta ft: 0.6589791487657798 (thr 0.3) * basic roberta ft (head first): 0.6768011808573329 (thr 0.42) * fine tune roberta on weird clf, then only head on spans, then whole: 0.6853127403287083 (thr 0.32) * ``` from transformers import RobertaTokenizer, RobertaForTokenClassification from transformers import Be...
github_jupyter
# Predicting Credit Card Default with Neural Networks ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import os %matplotlib inline ``` ### Back with the credit card default dataset ``` # Loading the dataset DATA_DIR = '../data' FILE_NAME = 'credit_card_default.csv' da...
github_jupyter
``` import pandas as pd # Let us just create a dictioinary to understand about the DataFrame. people = { "First": ["Me", "Myself", "I"], "Last" : ["He", 'She', "It"], "Email" : ["mehe@email.com", "myselfshe@email.com", "iit@email.com"] } # In this dict We can visualise the keys as the column's descripton...
github_jupyter
``` ## Basic stuff %load_ext autoreload %autoreload from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) display(HTML("""<style>div.output_area{max-height:10000px;overflow:scroll;}</style>""")) #IPython.Cell.options_default.cm_config.lineNumbers = true; ...
github_jupyter
# WELL NOTEBOOK ## Well logs visualization &amp; petrophysics Install the the repository reservoirpy from github and import the required packages ``` import os path = os.path.join('/home/santiago/Documents/dev/reservoirpy') import sys sys.path.insert(0,path) import pandas as pd import geopandas as gpd import numpy as...
github_jupyter
``` import paddle from paddle.nn import Linear import paddle.nn.functional as F import numpy as np import os import random def load_data(): # 从文件导入数据 datafile = 'external-libraries/housing.data' data = np.fromfile(datafile, sep=' ', dtype=np.float32) # 每条数据包括14项,其中前面13项是影响因素,第14项是相应的房屋价格中位数 ...
github_jupyter
# **<div align="center"> Dolby.io Developer Days Media APIs 101 - Getting Started </div>** ### **<div align="center"> Notebook #1: Getting Started</div>** ### Starting with a Raw Audio File We can run code blocks like this in Binder by pressing "Control+Enter". Try it now after clicking the below code block! ``` im...
github_jupyter
# Import ``` import matplotlib.pyplot as plt import numpy as np import pandas as pd import matplotlib matplotlib.__version__ np.__version__, pd.__version__ ``` # Dataset: ``` from sklearn.datasets import california_housing data = california_housing.fetch_california_housing() X = data['data'] y = data['target'] col...
github_jupyter
``` %load_ext autoreload %autoreload 2 import sys sys.path.append('../docs') from gen_doc.nbdoc import show_doc as sd #export from nb_001b import * import sys, PIL, matplotlib.pyplot as plt, itertools, math, random, collections, torch import scipy.stats, scipy.special from enum import Enum, IntEnum from torch import ...
github_jupyter
<a href="https://colab.research.google.com/github/JimKing100/nfl-test/blob/master/predictions/Prediction_Offense_Final.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` # Installs !pip install pmdarima # Imports import numpy as np import pandas as...
github_jupyter
![DSA log](dsalogo.png) ### Instructions 1. Make sure you are using a version of notebook greater than v.3. If you installed Anaconda with python 3 - this is likely to be fine. The next piece of code will check if you have the right version. 2. The notebook has both some open test cases that you can use to test the f...
github_jupyter
``` # Itertools # product --> Returns the Cartesian product of iterables such as lists from itertools import product lst_a=[2,4] lst_b=[3,6] print('List a -->',lst_a) print('List b -->',lst_b) ab=product(lst_a,lst_b) print('Returns a product object -->',type(ab)) lst_ab=list(ab) print('Returns a list -->',type(lst_ab...
github_jupyter
### As before, let's find the set of compounds for which both simulations and experimental measurements exist Matt Robinson posted a `moonshot_initial_activity_data.csv` file of the initial activity data: ``` import numpy as np import pandas as pd df_activity = pd.read_csv('../data-release-2020-05-10/moonshot_initia...
github_jupyter
## Model one policy variables This notebook extracts the selected policy variables in the `indicator_list` from IMF and World Bank (wb) data sources, and writes them to a csv file. ``` import warnings import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline warn...
github_jupyter
``` from opentrons import simulate ctx = simulate.get_protocol_api('2.1') NUM_SAMPLES = 48 VOLUME_MMIX = 20 ELUTION_LABWARE = '2ml tubes' PREPARE_MASTERMIX = True MM_TYPE = 'MM1' EL_LW_DICT = { 'large strips': 'opentrons_96_aluminumblock_generic_pcr_strip_200ul', 'short strips': 'opentrons_96_aluminumblock_ge...
github_jupyter
<a href="https://colab.research.google.com/github/wearlianbaguio/OOP-1-1/blob/main/OOP_Concepts_2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ##Application 1 1. Create a Python program that displays the name of the students (Student 1, Student 2...
github_jupyter
# ETL Pipeline Preparation Follow the instructions below to help you create your ETL pipeline. ### 1. Import libraries and load datasets. - Import Python libraries - Load `messages.csv` into a dataframe and inspect the first few lines. - Load `categories.csv` into a dataframe and inspect the first few lines. ``` # imp...
github_jupyter
# Assignment 1 This assignment is to test your understanding of Python basics. Answer the questions and complete the tasks outlined below; use the specific method described, if applicable. In order to get complete points on your homework assigment you have to a) complete this notebook, b) based on your results answer...
github_jupyter
# Sklearn ## sklearn.model_selection документация: http://scikit-learn.org/stable/modules/cross_validation.html ``` from sklearn import model_selection, datasets import numpy as np ``` ### Разовое разбиение данных на обучение и тест с помощью train_test_split ``` iris = datasets.load_iris() train_data, test_data,...
github_jupyter
# Black Litterman with Investor Views Optimization: Oldest Country ETFs # Charts ## 1. Data Fetching ### 1.1 Model configuration ``` import os import sys import datetime as dt import logging import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from hmmlearn import hmm import c...
github_jupyter
<a href="https://colab.research.google.com/github/Conscious-Mind/TensorFlow-Course-DeepLearning.AI/blob/main/C1/W2/ungraded_labs/C1_W2_Lab_1_beyond_hello_world_completed.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Ungraded Lab: Beyond Hello Wo...
github_jupyter
# <strong>Road networks and robustness to flooding on US Atlantic and Gulf barrier islands</strong> ## <strong>- Download elevations for the US Atlantic and Gulf barrier islands -</strong> ### The purpose of this notebook is to download CUDEM tiles from https://coast.noaa.gov/htdata/raster2/elevation/NCEI_ninth_Topo...
github_jupyter
``` """ Training script to train a model on MultiNLI and, optionally, on SNLI data as well. The "alpha" hyperparamaters set in paramaters.py determines if SNLI data is used in training. If alpha = 0, no SNLI data is used in training. If alpha > 0, then down-sampled SNLI data is used in training. """ %tb import tens...
github_jupyter
``` import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.data import DataLoader from torch.utils.data import Dataset from torch.utils.tensorboard import SummaryWriter import numpy as np import pandas as p...
github_jupyter
# Testing `TFNoiseAwareModel` We'll start by testing the `textRNN` model on a categorical problem from `tutorials/crowdsourcing`. In particular we'll test for (a) basic performance and (b) proper construction / re-construction of the TF computation graph both after (i) repeated notebook calls, and (ii) with `GridSear...
github_jupyter
# Analyze population data from https://covidtracking.com **Note:** This is a Jupyter notebook which is also available as its executable export as a Python 3 script (therefore with automatically generated comments). ### Sept 29,2021: Obsolete data Our source https://covidtracking.com/data/api says: - `As of March 7, ...
github_jupyter
``` from scripts.setup_libs import * ``` # [CatBoost](https://github.com/catboost/catboost) Бустинг от Яндекса для категориальных фичей и много чего еще. Для начала настоятельно рекомендуется посмотреть видео. Там идет основная теория по CatBoost ``` from IPython.display import YouTubeVideo YouTubeVideo('UYDwhuyWYS...
github_jupyter
### Evaluación 1. Parte Computacional (60 puntos) #### (Elementos de Probabilidad y Estadística: 3008450) Se tiene información acerca de 694 propiedades ubicadas en el valle de aburra. La base de datos fue recolectada en el año 2015, e incluye las siguientes variables: 1. valor comercial de la propiedad en millones ...
github_jupyter
# Sorting Madonna Songs This project will randomly order the entire backlog of Madonna's songs. This was motivated following a colleague's offhand remark about one's favourite song being *Material Girl* by Madge, which triggered another colleague to provide the challenge of ranking all of Madonna's songs. In particu...
github_jupyter
# Homework (16 pts) - Hypothesis Testing ``` import numpy as np import scipy.stats as st import matplotlib.pyplot as plt ``` 1. You measure the duration of high frequency bursts of action potentials under two different experimental conditions (call them conditions A and B). Based on your measured data below, determin...
github_jupyter
### TDD for data with pytest TDD is great for software engineering, but did you know TDD can add a lot of speed and quality to Data Science projects too? We'll learn how we can use TDD to save you time - and quickly improve functions which extract and process data. # About me **Chris Brousseau** *Surface Owl - F...
github_jupyter
# Information Flow In this chapter, we detail how to track information flows in python by tainting input strings, and tracking the taint across string operations. Some material on `eval` exploitation is adapted from the excellent [blog post](https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) by Ned ...
github_jupyter
## Face and Facial Keypoint detection After you've trained a neural network to detect facial keypoints, you can then apply this network to *any* image that includes faces. The neural network expects a Tensor of a certain size as input and, so, to detect any face, you'll first have to do some pre-processing. 1. Detect...
github_jupyter
## Reinforcement Learning Tutorial -1: Q Learning #### MD Muhaimin Rahman sezan92[at]gmail[dot]com Q learning , can be said one of the most famous -and kind of intuitive- of all Reinforcement learning algorithms. In fact ,the recent all algorithms using Deep learning , are based on the Q learning algorithms. So, to w...
github_jupyter
``` import sys; sys.path.insert(0, '..') import spot spot.setup() import buddy from spot.jupyter import display_inline from decimal import Decimal import decimal from fimdp.core import ConsMDP from fimdp.energy_solvers import BasicES from fimdp.labeled import LabeledConsMDP from fimdp.objectives import BUCHI ``` # P...
github_jupyter
``` """ The concept of the creation of the test data in order to evaluate the similarities, a synthethic data creation is introduced. The idea is as follows: 1. Outlier Instances. These are the users who deviate from the other in the data. Identifying them would of interest to understand how they behave against most o...
github_jupyter
<a href="https://colab.research.google.com/github/michelmunoz99/daa_2021_1/blob/master/20enero.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` class NodoArbol: def __init__(self, value, left=None, right=None): self.data=value self.left=left...
github_jupyter
# Marginalized Gaussian Mixture Model Author: [Austin Rochford](http://austinrochford.com) ``` %matplotlib inline from matplotlib import pyplot as plt import numpy as np import pymc3 as pm import seaborn as sns SEED = 383561 np.random.seed(SEED) # from random.org, for reproducibility ``` Gaussian mixtures are a fle...
github_jupyter
<img align="left" src="https://lever-client-logos.s3.amazonaws.com/864372b1-534c-480e-acd5-9711f850815c-1524247202159.png" width=200> <br></br> <br></br> # Major Neural Network Architectures Challenge ## *Data Science Unit 4 Sprint 3 Challenge* In this sprint challenge, you'll explore some of the cutting edge of Data...
github_jupyter
# The Data to see where we got the data go here: https://www.ndbc.noaa.gov/station_history.php?station=42040 ``` import pandas as pd import numpy as np import datetime ``` This is the first set of data from 1995 ``` from utils import read_file, build_median_df df1995 = read_file('data/42040/buoy_data_1995.txt') #all...
github_jupyter
Lambda School Data Science *Unit 1, Sprint 2, Module 1* --- _Lambda School Data Science_ # Join and Reshape datasets Objectives - concatenate data with pandas - merge data with pandas - understand tidy data formatting - melt and pivot data with pandas Links - [Pandas Cheat Sheet](https://github.com/pandas-dev/p...
github_jupyter
## Model training In this notebook we'll first define a baseline model and then train a couple of ML models to try to better that performance. The dataset is quite small and the features are few, so I'm going to keep it simple in terms of algotrithms. We'll see how a logistic regression model and a random forest model...
github_jupyter
``` library(magrittr) treatment_df = readr::read_tsv('../summary/indications.tsv') %>% dplyr::filter(rel_type == 'TREATS_CtD') %>% dplyr::select(compound_id, disease_id) %>% dplyr::mutate(status = 1) degree_prior_df = readr::read_tsv('data/degree-prior.tsv') %>% dplyr::mutate(Empiric = n_treatments / n_possibl...
github_jupyter
``` import pandas as pd train_data_file = 'data/zhengqi_train.txt' test_data_file = 'data/zhengqi_test.txt' train_data = pd.read_csv(train_data_file, sep = '\t', encoding = 'utf-8') test_data = pd.read_csv(test_data_file, sep = '\t', encoding = 'utf_8') ``` ## 定义特征构造方法 ``` eps = 1e-5 # 交叉特征方式 func_dict = { 'a...
github_jupyter
# 基于注意力的神经机器翻译 此笔记本训练一个将波斯语翻译为英语的序列到序列(sequence to sequence,简写为 seq2seq)模型。此例子难度较高,需要对序列到序列模型的知识有一定了解。 训练完此笔记本中的模型后,你将能够输入一个波斯语句子,例如 *"من می دانم."*,并返回其英语翻译 *"I know."* 对于一个简单的例子来说,翻译质量令人满意。但是更有趣的可能是生成的注意力图:它显示在翻译过程中,输入句子的哪些部分受到了模型的注意。 <img src="https://tensorflow.google.cn/images/spanish-english.png" alt="spanish...
github_jupyter
This is from a "Getting Started" competition from Kaggle [Titanic competition](https://www.kaggle.com/c/titanic) to showcase how we can use Auto-ML along with datmo and docker, in order to track our work and make machine learning workflow reprocible and usable. Some part of data analysis is inspired from this [kernel]...
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import numpy as np import os from scipy.optimize import curve_fit os.getcwd() data = pd.read_csv('data/CA_Fc_GC_MeCN_0V-1.2V_P-06-14/data.csv', sep=',') data data.plot('t', 'iw', xlim=(0,2)) index_max = data['iw'].idxmax() time_max = data.loc[in...
github_jupyter
# Extract from JSON and XML You'll now get practice extracting data from JSON and XML. You'll extract the same population data from the previous exercise, except the data will be in a different format. Both JSON and XML are common formats for storing data. XML was established before JSON, and JSON has become more pop...
github_jupyter
# Main Code ``` import os import time import numpy as np import redis from IPython.display import clear_output from PIL import Image from io import BytesIO import base64 import json import matplotlib.pyplot as plt from face_detection import get_face from utils import img_to_txt, decode_img, log_error ###############...
github_jupyter
``` from mxnet import nd from mxnet.contrib import text glove_vec = text.embedding.get_pretrained_file_names("glove") print(glove_vec) glove_6b50d = text.embedding.create('glove', pretrained_file_name="glove.6B.50d.txt") word_size = len(glove_6b50d) print(word_size) #词的索引 index = glove_6b50d.token_to_idx['happy'] print...
github_jupyter
# Dictionaries ### # Dictionary in Python is an unordered collection of data values. ### # Dictionary holds key:value pair. ### # Each key-value pair in a Dictionary is separated by a colon whereas each key is separated by a ‘comma’. ### # Keys of a Dictionary must be unique. ``` Dictionary = {1:'Nokia',2:'EDP'...
github_jupyter
# Tutorial 01: Running Sumo Simulations This tutorial walks through the process of running non-RL traffic simulations in Flow. Simulations of this form act as non-autonomous baselines and depict the behavior of human dynamics on a network. Similar simulations may also be used to evaluate the performance of hand-design...
github_jupyter
# Quick start guide ## Installation ### Stable Fri can be installed via the Python Package Index (PyPI). If you have `pip` installed just execute the command pip install fri to get the newest stable version. The dependencies should be installed and checked automatically. If you have problems installing plea...
github_jupyter
# Amortized Neural Variational Inference for a toy probabilistic model Consider a certain number of sensors placed at known locations, $\mathbf{s}_1,\mathbf{s}_2,\ldots,\mathbf{s}_L$. There is a target at an unknown position $\mathbf{z}\in\mathbb{R}^2$ that is emitting a certain signal that is received at the $i$-th...
github_jupyter
``` %matplotlib inline from pyvista import set_plot_theme set_plot_theme('document') ``` Colormap Choices {#colormap_example} ================ Use a Matplotlib, Colorcet, cmocean, or custom colormap when plotting scalar values. ``` from pyvista import examples import pyvista as pv import matplotlib.pyplot as plt fro...
github_jupyter
``` # Originally made by Katherine Crowson (https://github.com/crowsonkb, https://twitter.com/RiversHaveWings) # The original BigGAN+CLIP method was by https://twitter.com/advadnoun import math import random # from email.policy import default from urllib.request import urlopen from tqdm import tqdm import sys import o...
github_jupyter
## Homework: Multilingual Embedding-based Machine Translation (7 points) **In this homework** **<font color='red'>YOU</font>** will make machine translation system without using parallel corpora, alignment, attention, 100500 depth super-cool recurrent neural network and all that kind superstuff. But even without para...
github_jupyter
# Matplotlib and NumPy crash course You may install numpy, matplotlib, sklearn and many other usefull package e.g. via Anaconda distribution. ``` import numpy as np ``` ## NumPy basics ### Array creation ``` np.array(range(10)) np.ndarray(shape=(5, 4)) np.linspace(0, 1, num=20) np.arange(0, 20) np.zeros(shape=(5, ...
github_jupyter
<a href="https://colab.research.google.com/github/piyushsharma1812/recurrent-neural-networks/blob/master/NER_LSTM.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` # Required Libraries import numpy as np import pandas as pd from keras.preprocessi...
github_jupyter
# 虚谷号WebGPIO应用(客户端Python版) 虚谷号和手机(App inventor)如何互动控制? 虚谷号和掌控板如何互动控制? 为了让虚谷号和其他开源硬件、编程语言快速互动,虚谷号的WebGPIO应运而生。简单的说,只要在虚谷号上运行一个python文件,就可以用WebAPI的形式来与虚谷号互动,可以获取虚谷号板载Arduino的所有引脚的电平,也可以控制所有引脚。 ## 1.接口介绍 要在虚谷号上运行“webgpio.py”。也可以将“webgpio.py”文件更名为“main.py”,复制到vvBoard的Python目录,只要一开机,虚谷号就会执行。 下载地址:https://github.com/vv...
github_jupyter
# Toy Environment ![toy-mdp](../pictures/toy-mdp.png) In this exercise we will learn how to implement a simple Toy environment using Python. The environment is illustrated in figure. It is composed of 3 states and 2 actions. The initial state is state 1. The goal of this exercise is to implement a class Environment w...
github_jupyter
The second example shows how to set up a power-law spectral source, as well as how to add two sets of photons together. This example will also briefly show how to set up a mock dataset "in memory" using yt. For more details on how to do this, check out [the yt docs on in-memory datasets](http://yt-project.org/doc/exam...
github_jupyter
``` # extract features of region of an image from mask-rcnn by Detectron2 import detectron2 from detectron2.utils.logger import setup_logger setup_logger() # import some common libraries import numpy as np import cv2 import random import io import torch # import some common detectron2 utilities from detectron2 impo...
github_jupyter
``` from helpers.utilities import * %run helpers/notebook_setup.ipynb ``` While attempting to compare limma's results for log-transformed an non-transformed data, it was noticed (and brought up by Dr Tim) That the values of logFC produced by limma for non-transformed data are of wrong order of magnitude. I have inves...
github_jupyter
### AVGN Tutorial This tutorial walks you through getting started with AVGN on a sample dataset, so you can figure out how to use it on your own data. If you're not too familiar with Python, make sure you've first familiarized yourself with Jupyter notebooks and installing pyhton packages. Then come back and try the ...
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
# Plotting Here you can explore the different possibilities that the hep_spt package offers for plotting. ``` %matplotlib inline import hep_spt hep_spt.set_style() import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.axes_grid1 import make_axes_locatable from scipy.stats import norm ``` ## Plotting a ...
github_jupyter
``` Copyright 2021 IBM Corporation 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 applicable law or agreed to in writing, softwa...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt from collections import defaultdict from scipy.optimize import minimize import networkx as nx from networkx.generators.random_graphs import erdos_renyi_graph from IPython.display import Image from qiskit import QuantumCircuit, execute, Aer from qiskit.tools.visu...
github_jupyter
##### Detection and Location Chain **Abstract**: This hackathon project represents our effort to combine our existing machine learning and photogrametry efforts and further combine those efforts with both Cloud and Edge based solutions based upon Xilinx FPGA acceleration. The Trimble team decided that the Xilinx hac...
github_jupyter
# 6 - Pivot Table In this sixth step I'll show you how to reshape your data using a pivot table. This will provide a nice condensed version. We'll reshape the data so that we can see how much each customer spent in each category. ``` import pandas as pd import numpy as np df = pd.read_json("customer_data.json", c...
github_jupyter
``` #export from fastai.basics import * from fastai.callback.progress import * from fastai.text.data import TensorText from fastai.tabular.all import TabularDataLoaders, Tabular from fastai.callback.hook import total_params #hide from nbdev.showdoc import * #default_exp callback.wandb ``` # Wandb > Integration with [...
github_jupyter
# Detecting Payment Card Fraud In this section, we'll look at a credit card fraud detection dataset, and build a binary classification model that can identify transactions as either fraudulent or valid, based on provided, *historical* data. In a [2016 study](https://nilsonreport.com/upload/content_promo/The_Nilson_Rep...
github_jupyter
*** *** # 11. 튜플과 집합 *** *** *** ## 1 튜플 활용법 *** - 튜플(Tuples): 순서있는 임의의 객체 모음 (시퀀스형) - 튜플은 변경 불가능(Immutable) - 시퀀스형이 가지는 다음 연산 모두 지원 - 인덱싱, 슬라이싱, 연결, 반복, 멤버쉽 테스트 ### 1-1 튜플 연산 ``` t1 = () # 비어있는 튜플 t2 = (1,2,3) # 괄호 사용 t3 = 1,2,3 # 괄호가 없어도 튜플이 됨 print(type(t1), type(t2), type(t3)) # <type 'tuple'> <type ...
github_jupyter
``` %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from rmgpy.kinetics import * # Set global plot styles plt.style.use('seaborn-paper') plt.rcParams['axes.labelsize'] = 16 plt.rcParams['xtick.labelsize'] = 12 plt.rcParams['ytick.labelsize'] = 12 # Set temperature range a...
github_jupyter
## Test Riksdagen SFS dokument * Denna [Jupyter Notebook](https://github.com/salgo60/open-data-examples/blob/master/Riksdagens%20dokument%20SFS.ipynb) * [KU anmälningar](https://github.com/salgo60/open-data-examples/blob/master/Riksdagens%20dokument%20KU-anm%C3%A4lningar.ipynb) * [Motioner](https://github.com/sa...
github_jupyter
``` import os import numpy as np from mnucosmomap import util as UT from mnucosmomap import catalogs as mNuCats %load_ext line_profiler fullbox = mNuCats.mNuICs(1, sim='paco') x, y, z = fullbox['Position'].T vx, vy, vz = fullbox['Velocity'].T nside = 8 L_subbox = 1000./float(nside) # L_subbox L_res = 1000./512. L_hal...
github_jupyter
<h1>Lists in Python</h1> <p><strong>Welcome!</strong> This notebook will teach you about the lists in the Python Programming Language. By the end of this lab, you'll know the basics list operations in Python, including indexing, list operations and copy/clone list.</p> <h2>Table of Contents</h2> <div class="alert ale...
github_jupyter
``` ! wget http://corpora.linguistik.uni-erlangen.de/someweta/german_web_social_media_2018-12-21.model -P /mnt/data2/ptf from someweta import ASPTagger model = "/mnt/data2/ptf/german_web_social_media_2018-12-21.model" # future versions will have sensible default values asptagger = ASPTagger(beam_size=5, iterations=1...
github_jupyter
``` import sys import tensorflow as tf from sklearn.datasets import load_boston import pandas as pd import matplotlib.pyplot as plt plt.style.use('dark_background') boston = load_boston() ''' THIS is how you print the name of a function from within the function print(sys._getframe().f_code.co_name) '''#print([x fo...
github_jupyter
# Import the data ``` import pandas as pd import numpy as np import networkx as nx import statsmodels import statsmodels.api as sm import scipy.stats as stats import matplotlib.pyplot as plt # import the csv file with JUST the politicians post comDB = pd.read_csv(r"/Users/tassan-mazzoccoarthur/Desktop/NETWORK SCI...
github_jupyter
``` import glob import warnings import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.discriminant_analysis...
github_jupyter
## Make your own heatmap based on Strava activities This notebook shows you how to create your own heatmap based on your Strava activities. You need to create a Strava API application in order to use their API. Follow the instructions on this page to create your app: <https://medium.com/@annthurium/getting-started-wit...
github_jupyter
# <p style="text-align: center;"> Part Two: Scaling & Normalization </p> ``` from IPython.display import HTML from IPython.display import Image Image(url= "https://miro.medium.com/max/3316/1*yR54MSI1jjnf2QeGtt57PA.png") HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide();...
github_jupyter
# Implementing a Route Planner In this project you will use A\* search to implement a "Google-maps" style route planning algorithm. ## The Map ``` # Run this cell first! from helpers import Map, load_map_10, load_map_40, show_map import math %load_ext autoreload %autoreload 2 ``` ### Map Basics ``` map_10 = load_...
github_jupyter
# Structured and time series data This notebook contains an implementation of the third place result in the Rossman Kaggle competition as detailed in Guo/Berkhahn's [Entity Embeddings of Categorical Variables](https://arxiv.org/abs/1604.06737). The motivation behind exploring this architecture is it's relevance to re...
github_jupyter
# Classifying Images with a NN and DNN Model ## Introduction In this notebook, you learn how to build a neural network to classify the tf-flowers dataset using a Deep Neural Network Model. ## Learning Objectives * Define Helper Functions. * Train and evaluate a Neural Network (NN) model. * Train and evaluate a Deep...
github_jupyter
``` import sys sys.path.append('../Scripts') from capstone_functions import * ``` ## Gradient Descent exploration ### This notebook has many example of running gradient descent with different hyper parameters ### Epoch Choice This calls our main pipeline function that loads raw data performs all adjustments and crea...
github_jupyter
# Naive Bayes from scratch ``` import pandas as pd import numpy as np def get_accuracy(x: pd.DataFrame, y: pd.Series, y_hat: pd.Series): correct = y_hat == y acc = np.sum(correct) / len(y) cond = y == 1 y1 = len(y[cond]) y0 = len(y[~cond]) print(f'Class 0: tested {y0}, correctly classified {co...
github_jupyter
# Create simple CNN network Import all important libraries ``` import tensorflow as tf from tensorflow import keras import matplotlib as plt import pandas as pd # Import stuff fof preprocessing from tensorflow.keras.preprocessing.image import ImageDataGenerator ``` Now load the IDmap ``` IDmap = {} # id: hand gest...
github_jupyter
## Import dependencies ``` import numpy as np import sys import pandas as pd import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import inset_axes import seaborn as sn import scipy as sp from tqdm import tqdm import glob from fair import * from fair.scripts.data_retrieval impo...
github_jupyter
``` %reload_ext autoreload %autoreload 2 %matplotlib inline ``` ### Image Generation from Audio ``` from pathlib import Path from IPython.display import Audio import librosa import librosa.display import matplotlib.pyplot as plt import numpy as np from utils import read_file, transform_path DATA = Path('data') # the...
github_jupyter
``` import os import pandas as pd from pandas_profiling import ProfileReport from pandas_profiling.utils.cache import cache_file from collections import Counter import seaborn as sn import random import statistics import statsmodels.api as sm import numpy as np box_file_dir = os.path.join(os.getcwd(), "..", "..", "...
github_jupyter