code stringlengths 2.5k 150k | kind stringclasses 1
value |
|---|---|
# Getting Started with ctapipe
This hands-on was presented at the Paris CTA Consoritum meeting (K. Kosack)
## Part 1: load and loop over data
```
from ctapipe.io import event_source
from ctapipe import utils
from matplotlib import pyplot as plt
%matplotlib inline
path = utils.get_dataset_path("gamma_test_large.simte... | github_jupyter |
<a href="https://colab.research.google.com/github/daveshap/QuestionDetector/blob/main/QuestionDetector.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Compile Training Data
Note: Generate the raw data with [this notebook](https://github.com/davesh... | github_jupyter |
# Preliminaries
The `pandas` library allows the user several data structures for different data manipulation tasks:
1. Data storage through its `Series` and `DataFrame` data structures.
2. Data filtering using multiple methods from the package.
3. Reading data from many different file formats such as `csv`, `txt`, `xl... | github_jupyter |
This is a demo illustrating an application of the OS2D method on one image.
Demo assumes the OS2D code is [installed](./INSTALL.md).
```
import os
import argparse
import matplotlib.pyplot as plt
import torch
import torchvision.transforms as transforms
from os2d.modeling.model import build_os2d_from_config
from os2d.... | github_jupyter |
# RadiusNeighborsClassifier with MinMaxScaler
This Code template is for the Classification task using a simple Radius Neighbor Classifier, with data being scaled by MinMaxScaler. It implements learning based on the number of neighbors within a fixed radius r of each training point, where r is a floating-point value sp... | github_jupyter |
# SIMULATE THE SYSTEM
```
import simtk.openmm as mm # Main OpenMM functionality
import simtk.openmm.app as app # Application layer (handy interface)
import simtk.unit as unit # Unit/quantity handling
import mdtraj
import matplotlib as mpl
import matplotlib.pyplot as plt
import os
cwd = cwd = os.getcwd()
... | github_jupyter |
# 03 - Stats Review: The Most Dangerous Equation
In his famous article of 2007, Howard Wainer writes about very dangerous equations:
"Some equations are dangerous if you know them, and others are dangerous if you do not. The first category may pose danger because the secrets within its bounds open doors beh... | github_jupyter |
# Gender Prediction, using Pre-trained Keras Model
Deep Neural Networks can be used to extract features in the input and derive higher level abstractions. This technique is used regularly in vision, speech and text analysis. In this exercise, we use a pre-trained model deep learning model that would identify low level... | github_jupyter |
# Carving Unit Tests
So far, we have always generated _system input_, i.e. data that the program as a whole obtains via its input channels. If we are interested in testing only a small set of functions, having to go through the system can be very inefficient. This chapter introduces a technique known as _carving_, w... | github_jupyter |
```
# Import Module
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import h5py
# Read data, which has a size of N * 784 and N * 1
MNIST = h5py.File("..\MNISTdata.hdf5",'r')
x_train = np.float32(MNIST['x_train'][:])
x_test = np.float32(MNIST['x_test'][:])
y_train = np.int32(MNIST['y_train'][:,0])... | github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib
%matplotlib inline
matplotlib.rcParams['figure.figsize'] = (12, 8) # set default figure size, 8in by 6in
```
This week, you will be learning about the support vector machine (SVM) algorithm. SVMs are considered by many to be t... | github_jupyter |
# INFO 3350/6350
## Lecture 07: Vectorization, distance metrics, and regression
## To do
* Read HDA ch. 5 and Grimmer and Stewart for Monday (a lot of reading)
* HW3 (gender and sentiment; dictionary methods) due by Thursday night at 11:59.
* Extra credit for good, consistent answers on Ed
* Study groups are great f... | github_jupyter |
## Algorithm - II
### Clustering, Link Analysis, Node Classification, Link Prediction
```
import matplotlib.pyplot as plt
import networkx as nx
import seaborn as sns
sns.set()
%matplotlib inline
import warnings
import matplotlib.cbook
warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation)
G = nx.k... | github_jupyter |
# **[HW2] Training Neural Network**
1. Prerequisite
2. Activation
3. Optimizer
4. Regularization
5. FC vs Conv
6. Do it by yourself
이번 실습에서는 지난 시간에 배웠던 MLP-layer의 component들을 하나씩 바꿔가며 activation, optimizer, regularization, convolution layer등의 중요성을 하나씩 익혀가는 시간을 갖도록 하겠습니다.
# 1. Prerequisite
본격적인 실습을 진행하기 이전, 지난 [HW1.2... | github_jupyter |
# Attention Basics
In this notebook, we look at how attention is implemented. We will focus on implementing attention in isolation from a larger model. That's because when implementing attention in a real-world model, a lot of the focus goes into piping the data and juggling the various vectors rather than the concepts... | github_jupyter |
# Introduction to Pandas
Complete the following set of exercises to solidify your knowledge of Pandas fundamentals.
#### 1. Import Numpy and Pandas and alias them to `np` and `pd` respectively.
```
# your code here
import numpy as np
import pandas as pd
```
#### 2. Create a Pandas Series containing the elements of... | github_jupyter |
# Seasonal Accuracy Assessment of Water Observations from Space (WOfS) Product in Africa<img align="right" src="../Supplementary_data/DE_Africa_Logo_Stacked_RGB_small.jpg">
## Description
Now that we have run WOfS classification for each AEZs in Africa, its time to conduct seasonal accuracy assessment for each AEZ in ... | github_jupyter |
## Principal Component Analysis
```
# Import numpy
import numpy as np
# Import linear algebra module
from scipy import linalg as la
# Create dataset
data=np.array([[7., 4., 3.],
[4., 1., 8.],
[6., 3., 5.],
[8., 6., 1.],
[8., 5., 7.],
[7., 2... | github_jupyter |
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#定义系统参数" data-toc-modified-id="定义系统参数-1"><span class="toc-item-num">1 </span>定义系统参数</a></span></li><li><span><a href="#Q表的创建函数,初始化为0" data-toc-modified-id="Q表的创建函数,初始化为0-2"><span class="toc-item-n... | github_jupyter |
**Copyright 2021 The TensorFlow Hub Authors.**
Licensed under the Apache License, Version 2.0 (the "License");
```
# Copyright 2021 The TensorFlow Hub Authors. 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.
# ... | github_jupyter |
```
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing
# Try to find value for W and b to compute y_data = x_data * W + b
# Define dimensions
d = 2 # Size of the parameter space
N = 50 # Number of data sample
# Model parameters
W = tf.Variable(tf.zero... | github_jupyter |
# Residual Networks
Welcome to the second assignment of this week! You will learn how to build very deep convolutional networks, using Residual Networks (ResNets). In theory, very deep networks can represent very complex functions; but in practice, they are hard to train. Residual Networks, introduced by [He et al.](h... | github_jupyter |
# Nu-Support Vector Regression with StandardScaler & Quantile Transformer
This Code template is for regression analysis using a Nu-Support Vector Regressor(NuSVR) based on the Support Vector Machine algorithm with Quantile Transformer as Feature Transformation Technique and StandardScaler for Feature Scaling in a pip... | github_jupyter |
```
import gym
import numpy as np
import matplotlib.pyplot as plt
import sys
env = gym.make('MountainCar-v0')
LEARNING_RATE = 0.1
NUM_EPISODES = 500
DISCOUNT_FACTOR = 0.95
DISCRETE_OS_SIZE = [20] * len(env.observation_space.high)
discrete_os_win_size = (env.observation_space.high-env.observation_space.low)/DISCRETE_OS_... | github_jupyter |
## Exercício 01
### Linguagens e Paradigmas de Programação
Janaina Emilia
<br /> <b>RA</b> 816114781
1- Faça um Programa que peça o raio de um círculo, calcule e
mostre sua área.
```
import math
raio = float(input("Digite o valor do raio:"))
area = math.pi * (raio ** 2)
print("A área do circulo é: ", area)
```
2-... | github_jupyter |
# Siamese Neural Network with Triplet Loss trained on MNIST
## Cameron Trotter
### c.trotter2@ncl.ac.uk
This notebook builds an SNN to determine similarity scores between MNIST digits using a triplet loss function. The use of class prototypes at inference time is also explored.
This notebook is based heavily on the ... | github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as image
import os
import cv2
capture = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier('./haarcascade_frontalface_alt.xml')
#Iterate to save data for each face
face_data = []
face_name = input("Enter face name :")
face_cascade = c... | github_jupyter |
# Gateway Exploration
In this final segment you can take what you have learned and try it yourself. This segment is displayed in "Notebook Mode" rather than "Presentation Mode." So you will need to scroll down as you explore more content. Notebook mode will allow you to see more content at once. It also allows you to ... | github_jupyter |
# Welcome to Python!
There are many excellent Python and Jupyter/IPython tutorials out there. This Notebook contains a few snippets of code from here and there, but we suggest you go over some in-depth tutorials, especially if you are not familiar with Python.
Here we borrow some material from:
- [A Crash Course in... | github_jupyter |
# Multi-class Classification and Neural Networks
## 1. Multi-class Classification
In this exercise, we will use logistic regression and neural networks to recognize handwritten digits (from 0 to 9).
### 1.1 Dataset
The dataset ex3data1.mat contains 5000 training examples of handwritten digits. Each training example ... | github_jupyter |
```
import construction as cs
import matplotlib.pyplot as plt
### read font
from matplotlib import font_manager
font_dirs = ['Barlow/']
font_files = font_manager.findSystemFonts(fontpaths=font_dirs)
for font_file in font_files:
font_manager.fontManager.addfont(font_file)
# set font
plt.rcParams['font.family'] =... | github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import *
from sklearn.linear_model import *
from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_predict
### UTILITY FUNCTION FOR DATA GENERATION ###
def gen_sinusoidal(timesteps, amp, freq, noise... | github_jupyter |
**Question1**
<br>Create a function that takes three integer arguments (a, b, c) and returns the amount of
integers which are of equal value.
<br>Examples
<br>equal(3, 4, 3) ➞ 2
<br>equal(1, 1, 1) ➞ 3
<br>equal(3, 4, 1) ➞ 0
<br>
<br>Notes
<br>Your function must return 0, 2 or 3.
**Answer:**
```
def equal(a, b, c):
... | github_jupyter |
# PCA (Principal Component Analysis)
---
<img src="https://selecao.letscode.com.br/favicon.png" width="40px" style="position: absolute; top: 15px; right: 40px; border-radius: 5px;" />
## Introdução
São cada vez mais comuns a elevada quantidade de variáveis explicativas, porém quanto maior a quantidade de variáveis, ... | github_jupyter |
<a href="https://colab.research.google.com/github/Estampille/Cognitive-Services-Vision-Solution-Templates/blob/master/googlesentiments.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
!pip install --upgrade google-api-python-client
!pip install... | github_jupyter |
# Plotting Categorical Data
In this section, we will:
- Plot distributions of data across categorical variables
- Plot aggregate/summary statistics across categorical variables
## Plotting Distributions Across Categories
We have seen how to plot distributions of data. Often, the distributions reveal new information... | github_jupyter |
<img src="https://maltem.com/wp-content/uploads/2020/04/LOGO_MALTEM.png" style="float: left; margin: 20px; height: 55px">
<br>
<br>
<br>
<br>
# Random Forests and ExtraTrees
_Authors: Matt Brems (DC), Riley Dallas (AUS)_
---
## Random Forests
---
With bagged decision trees, we generate many different trees on ... | github_jupyter |
# H2O Model
* Wrap a H2O model for use as a prediction microservice in seldon-core
* Run locally on Docker to test
* Deploy on seldon-core running on minikube
## Dependencies
* [Helm](https://github.com/kubernetes/helm)
* [Minikube](https://github.com/kubernetes/minikube)
* [S2I](https://github.com/opensh... | github_jupyter |
# Model management with MLflow
Model management can be done using both MLflow and Azure ML SDK/CLI v2. If you are familiar with MLflow and the capabilities it exposes, we support the entire model lifecycle using the MLFlow client. If you rather use Azure ML specific features or do model management using the CLI, in th... | github_jupyter |
# AWS Elastic Kubernetes Service (EKS) Deep MNIST
In this example we will deploy a tensorflow MNIST model in Amazon Web Services' Elastic Kubernetes Service (EKS).
This tutorial will break down in the following sections:
1) Train a tensorflow model to predict mnist locally
2) Containerise the tensorflow model with o... | github_jupyter |
```
#importing libraries
import cv2
from matplotlib import pyplot as plt
import numpy as np
import imutils
import easyocr
from datetime import datetime
import mysql.connector
from csv import writer
#importing image and converting into grayscale
img = cv2.imread('image3.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)... | github_jupyter |
# Matrizes, Arrays, Tensores
## Referências
- Documentação oficial de Tensores do PyTorch
http://pytorch.org/docs/master/tensors.html
- PyTorch para usuários NumPy:
https://github.com/torch/torch7/wiki/Torch-for-Numpy-users
## NumPy array
```
import numpy as np
a = np.array([[2., 8., 3.],
[0.,... | github_jupyter |
```
import sys
sys.path.append('../transformers/')
import tensorflow as tf
import tensorflow_datasets as tfds
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import pickle
from tqdm import tqdm
from path_explain import utils
from plot.text import text_plot, matrix_interaction_plot, bar_inte... | github_jupyter |
```
# import packages
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import re
import nltk
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test... | github_jupyter |
```
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import math
import seaborn as sns
from datetime import datetime
from functools import reduce
from collections import Counter
import functions
from scipy.stats import ks_2samp
from scipy.stats import pearsonr
import statsmodels.api as sm
import s... | github_jupyter |
# explore_data_gov_sg_api
## Purpose:
Explore the weather-related APIs at https://developers.data.gov.sg.
## History:
- 2017-05 - Benjamin S. Grandey
- 2017-05-29 - Moving from atmos-scripts repository to access-data-gov-sg repository, and renaming from data_gov_sg_explore.ipynb to explore_data_gov_sg_api.ipynb.
```... | github_jupyter |
Before you turn this problem in, make sure everything runs as expected. First, **restart the kernel** (in the menubar, select Kernel$\rightarrow$Restart) and then **run all cells** (in the menubar, select Cell$\rightarrow$Run All).
Make sure you fill in any place that says `YOUR CODE HERE` or "YOUR ANSWER HERE", as we... | github_jupyter |
This model will cluster a set of data, first with KMeans and then with MiniBatchKMeans, and plot the results. It will also plot the points that are labelled differently between the two algorithms.
```
import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import MiniBatchKMeans, KMeans
f... | github_jupyter |
This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# Solution Notebook
## Problem: Given an array of n integers, find an int not in the input. Use a minimal amount of memory.
* [Constrain... | github_jupyter |
Lambda School Data Science
*Unit 2, Sprint 2, Module 4*
---
# Classification Metrics
## Assignment
- [ ] If you haven't yet, [review requirements for your portfolio project](https://lambdaschool.github.io/ds/unit2), then submit your dataset.
- [ ] Plot a confusion matrix for your Tanzania Waterpumps model.
- [ ] Co... | github_jupyter |
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-59152712-8"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-59152712-8');
</script>
# `GiRaFFE_NRPy`: Source Terms
## Author: Patrick Nelson
... | github_jupyter |
# Find Descriptors (Matching)
Similar to classification, VDMS supports feature vector search based on similariy matching as part of its API.
In this example, where we have a pre-load set of feature vectors and labels associated,
we can search for similar feature vectors, and query information related to it.
We will... | github_jupyter |
<a href="https://colab.research.google.com/github/Vinit-source/CSL7382-Medical-image-clustering-assignment.py/blob/main/problem_code.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Problem
Implement the **k-means**, **SLIC**, and **Ratio Cut** al... | github_jupyter |
```
!sudo nvidia-persistenced
!sudo nvidia-smi -ac 877,1530
from IPython.core.display import display, HTML
display(HTML("<style>.container {width:95% !important;}</style>"))
from core import *
from torch_backend import *
colors = ColorMap()
draw = lambda graph: display(DotGraph({p: ({'fillcolor': colors[type(v)], 'to... | github_jupyter |
# Radius and mean slip of rock patches failing in micro-seismic events
When stresses in a rock surpass its shear strength, the affected rock volume will fail to shearing.
Assume that we observe a circular patch with radius $r$ on, e.g. a fault, and that this patch is affected by a slip with an average slip distance ... | github_jupyter |
# Autonomous driving - Car detection
Welcome to your week 3 programming assignment. You will learn about object detection using the very powerful YOLO model. Many of the ideas in this notebook are described in the two YOLO papers: [Redmon et al., 2016](https://arxiv.org/abs/1506.02640) and [Redmon and Farhadi, 2016](h... | github_jupyter |
# Exercice 2
Ce deuxième exercice va se produire dans une partie `code` où vous devez écrire quelques lignes de Python! Mais pas de soucis, on va y aller progressivement.
En-dessous de ce block de texte vous trouverez trois blocks pour les trois niveaux de l'exercice.
On va se pencher sur la *Differential Privacy* et... | github_jupyter |
```
import pandas as pd
fh = '../files/tickets-gen-all.csv'
df = pd.read_csv(fh, index_col=0, parse_dates=['created', 'opened_at', 'updated_on', 'resolved'])
df.shape
df.columns
```
##### cataloging active tickets only
```
cadf = df[((df['category'] == 'Cataloging') | (df['assignment_group'] == 'BKOPS CAT')) & ((df['... | github_jupyter |
# Color extraction from images with Lithops4Ray
In this tutorial we explain how to use Lithops4Ray to extract colors and [HSV](https://en.wikipedia.org/wiki/HSL_and_HSV) color range from the images persisted in the IBM Cloud Oject Storage. To experiment with this tutorial, you can use any public image dataset and uplo... | github_jupyter |
# Introduction to Deep Learning with PyTorch
In this notebook, you'll get introduced to [PyTorch](http://pytorch.org/), a framework for building and training neural networks. PyTorch in a lot of ways behaves like the arrays you love from Numpy. These Numpy arrays, after all, are just tensors. PyTorch takes these tenso... | github_jupyter |
<h1><center>CS 455/595a: Ensemble Methods - bagging and random forests</center></h1>
<center>Richard S. Stansbury</center>
This notebook applies the bagging and random forest ensemble classification and regression concepts concepts covered in [1] with the [Titanic](https://www.kaggle.com/c/titanic/) and [Boston Housin... | github_jupyter |
<img style="float: left; margin: 30px 15px 15px 15px;" src="https://pngimage.net/wp-content/uploads/2018/06/logo-iteso-png-5.png" width="300" height="500" />
### <font color='navy'> Simulación de procesos financieros.
**Nombres:** Ana Esmeralda Rodriguez Rodriguez, Antonio de Santiago Rosas Saldaña.
**Fec... | github_jupyter |
```
import dask.dataframe as dask
dask_df = dask.read_csv("*.csv")
dask_df
dask_df.head()
# Elnino Melendez sounds like she has some real wholesome, family-friendly content on her channel
dask_df.count().compute()
dask_df.columns
len(dask_df)
# Looks like 1956 instances (rows) and 5 features (columns)
dask_df['CLASS'].... | github_jupyter |
```
import nltk
import re
import operator
from collections import defaultdict
import numpy as np
import matplotlib.pyplot as plt
```
The idea is generate more common sentences according to their word tagging. So the sentences will have the real structure written by lovecraft and composed by a list of most common word... | github_jupyter |
# Tutorial - Evaluate DNBs additional Rules
This notebook contains a tutorial for the evaluation of DNBs additional Rules for the following Solvency II reports:
- Annual Reporting Solo (ARS); and
- Quarterly Reporting Solo (QRS)
Besides the necessary preparation, the tutorial consists of 6 steps:
1. Read possible dat... | github_jupyter |
```
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
def normalize(fold_data,icount_data): #creating function for normalizing folded pulse data
norm_data = np.zeros_like(fold_data) #initializing array for normalized data
for i in range(len(fold_data[:,:,:])): #looping over how eve... | github_jupyter |
# SST-2
# Simple Baselines using ``mean`` and ``last`` pooling
## Librairies
```
# !pip install transformers==4.8.2
# !pip install datasets==1.7.0
# !pip install ax-platform==0.1.20
import os
import sys
sys.path.insert(0, os.path.abspath("../..")) # comment this if library is pip installed
import io
import re
import ... | github_jupyter |
- https://www.kaggle.com/tanlikesmath/intro-aptos-diabetic-retinopathy-eda-starter
- https://medium.com/@btahir/a-quick-guide-to-using-regression-with-image-data-in-fastai-117304c0af90
- add diabetic-retinopathy-detection training data (cropped)
# params
```
PRFX = 'CvCropDiabtrn070314'
p_prp = '../output/Prep0703'
p... | github_jupyter |
```
# from https://www.kaggle.com/carlbeckerling/kaggle-titanic-tutorial
import pandas as pd
test = pd.read_csv('./test.csv')
train = pd.read_csv('./train.csv')
test.shape,train.shape
test.info()
train.info()
import matplotlib.pyplot as plt
sex_pivot = train.pivot_table(index='Sex', values='Survived')
sex_pivot.plot.... | github_jupyter |
<small><i>This notebook was put together by [Jake Vanderplas](http://www.vanderplas.com). Source and license info is on [GitHub](https://github.com/jakevdp/sklearn_tutorial/).</i></small>
# Clustering: K-Means In-Depth
Here we'll explore **K Means Clustering**, which is an unsupervised clustering technique.
We'll st... | github_jupyter |
```
%run ./dlt
%run ./dlt_workflow_refactored
from pyspark.sql import Row
import unittest
from pyspark.sql.functions import lit
import datetime
timestamp = datetime.datetime.fromisoformat("2000-01-01T00:00:00")
def timestamp_provider():
return lit(timestamp)
from pyspark.sql.functions import when, col
from pyspar... | github_jupyter |
```
import numpy as np
from matplotlib import pyplot as plt
from joblib import Parallel, delayed
import multiprocessing
import time
from tqdm import tqdm
from VolcGases.functions import solve_gases
import warnings
warnings.filterwarnings('ignore')
# The total H and C mass fractions
mCO2tot=1000e-6
mH2Otot=1000e-6
# s... | github_jupyter |
# T1056.004 - Input Capture: Credential API Hooking
Adversaries may hook into Windows application programming interface (API) functions to collect user credentials. Malicious hooking mechanisms may capture API calls that include parameters that reveal user authentication credentials.(Citation: Microsoft TrojanSpy:Win32... | github_jupyter |
```
#from lab2.utils import get_random_number_generator
class BoxWindow:
"""[summary]"""
def __init__(self, args):
"""initialize the box window with the bounding points
Args:
args (np.array([integer])): array of the bounding points of the box
"""
self.bounds = arg... | github_jupyter |
# Monte calro localization
Monte calro localizationのサンプルです。
## ライブラリのインポート
```
%matplotlib inline
import math, random # 計算用、乱数の生成用ライブラリ
import matplotlib.pyplot as plt # 描画用ライブラリ
```
## ランドマーククラス
下のグラフに表示されている星たちです。
ロボットはこの星を目印にして自分の位置を知ります。
今回は星の位置もロボットが覚えている設定です。
ロボットがどんな風に星を見ているのかは、観測モデ... | github_jupyter |
# Introduction to Data Science
## From correlation to supervised segmentation and tree-structured models
Spring 2018 - Profs. Foster Provost and Josh Attenberg
Teaching Assistant: Apostolos Filippas
***
### Some general imports
```
import os
import numpy as np
import pandas as pd
import math
import matplotlib.pyl... | github_jupyter |
# Syft Duet for Federated Learning - Central Aggregator
## Setup
First we need to install syft 0.3.0 because for every other syft project in this repo we have used syft 0.2.9. However, a recent update has removed a lot of the old features and replaced them with this new 'Duet' function. To do this go into your termin... | github_jupyter |
This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# Challenge Notebook
## Problem: Find the kth to last element of a linked list.
* [Constraints](#Constraints)
* [Test Cases](#Test-Cases)
* [Algo... | github_jupyter |
```
# import data science libraries
import numpy as np
import pandas as pd
import re
import os.path
from os import path
from datetime import datetime
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from sklearn.preprocessing import MinMaxScaler, StandardScaler, Pow... | github_jupyter |
## Observations and Insights
```
# Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import scipy.stats as st
import numpy as np
from scipy.stats import linregress
# Study data files
mouse_metadata_path = "data/Mouse_metadata.csv"
study_results_path = "data/Study_results.csv"
# Read the mouse... | github_jupyter |
```
# importing the packages
import pandas as pd
import numpy as np
# reading the csv files
orders = pd.read_csv('orders_test (2).csv')
stores = pd.read_csv('store_test (2).csv')
customers = pd.read_csv('customer_test (2).csv')
```
1. Create a CSV containing an aggregate table showing the total orders and revenue
each... | github_jupyter |
```
#!/bin/python
import numpy as np
import pandas as pd
import os
import pickle
import sys
import scipy
from pathlib import Path
from collections import Counter
import random
import copy
# Machine Learning libraries
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from s... | github_jupyter |
## Distinction of solid liquid atoms and clustering
In this example, we will take one snapshot from a molecular dynamics simulation which has a solid cluster in liquid. The task is to identify solid atoms and cluster them. More details about the method can be found [here](https://pyscal.readthedocs.io/en/latest/solidl... | github_jupyter |
## Download the Fashion-MNIST dataset
```
import os
import numpy as np
from tensorflow.keras.datasets import fashion_mnist
(x_train, y_train), (x_val, y_val) = fashion_mnist.load_data()
os.makedirs("./data", exist_ok = True)
np.savez('./data/training', image=x_train, label=y_train)
np.savez('./data/validation', imag... | github_jupyter |
```
import mackinac
import cobra
import pandas as pd
import json
import os
import numpy as np
# load ID's for each organisms genome
id_table = pd.read_table('../data/study_strain_subset_w_patric.tsv',sep='\t',dtype=str)
id_table = id_table.replace(np.nan, '', regex=True)
species_to_id = dict(zip(id_table["designation i... | github_jupyter |
This script loads behavioral mice data (from `biasedChoiceWorld` protocol and, separately, the last three sessions of training) only from mice that pass a given (stricter) training criterion. For the `biasedChoiceWorld` protocol, only sessions achieving the `trained_1b` and `ready4ephysrig` training status are collecte... | github_jupyter |
# Distance Matrix
```
# imports
# The sklearn library contains a lot of efficient tools for machine learning and statistical modeling including
# classification, regression, clustering and dimensionality reduction
from sklearn import datasets
# used to perform a wide variety of mathematical operations on arrays. ... | github_jupyter |
# Publications markdown generator for academicpages
Takes a TSV of publications with metadata 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.... | github_jupyter |
```
#!pip install jupyterthemes
#!jt -t chesterish
#!pip install autopep8
import numpy as np
import matplotlib.pyplot as plt
import tkinter as tk
class Planet():
def __init__(self, a, M, e, T, r, n, soi):
self.G = 6.67e-11
self.semimajor_axis = a
self.mass = M
self.eccentricity = e
... | github_jupyter |
<h1>CI Midterm<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Q1-Simple-Linear-Regression" data-toc-modified-id="Q1-Simple-Linear-Regression-1">Q1 Simple Linear Regression</a></span></li><li><span><a href="#Q2-Fuzzy-Linear-Regression" data-toc-modified-id="Q2-Fuzzy-Linear-Re... | github_jupyter |
```
# fetching data online
import os
import tarfile
from six.moves import urllib
DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml2/master/"
HOUSING_PATH = os.path.join("datasets", "housing")
HOUSING_URL = DOWNLOAD_ROOT + "datasets/housing/housing.tgz"
def fetch_housing_data(housing_url=HOUSING_URL,... | github_jupyter |
# 2016 Olympics medal count acquisition
In this notebook, we acquire the current medal count from the web.
# 1. List of sports
```
from bs4 import BeautifulSoup
import urllib
r = urllib.urlopen('http://www.bbc.com/sport/olympics/rio-2016/medals/sports').read()
soup = BeautifulSoup(r,"lxml")
sports_span = soup.findA... | github_jupyter |
# Self-Driving Car Engineer Nanodegree
## Project: **Finding Lane Lines on the Road**
***
In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really j... | github_jupyter |
```
import os
import sys
import pandas as pd
import re
# pd.set_option('display.max_colwidth', -1)
```
Read data and Spilit into texts and Labels
```
BASE_DIR = ''
GLOVE_DIR = os.path.join(BASE_DIR, 'glove.6B')
TEXT_DATA_DIR = os.path.join(BASE_DIR, '20_newsgroups')
# This code from http#s://www.kaggle.com/mansijhari... | github_jupyter |
```
import torch
from torch.nn import functional as F
from torch import nn
from pytorch_lightning.core.lightning import LightningModule
import pytorch_lightning as pl
import torch.optim as optim
import torchvision
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data... | github_jupyter |
**Chapter 7 – Ensemble Learning and Random Forests**
_This notebook contains all the sample code and solutions to the exercises in chapter 7._
<table align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/ageron/handson-ml2/blob/master/07_ensemble_learning_and_random_forests.ipynb"... | github_jupyter |
## Exercise 1.1
In this exercise we will use the Amazon sentiment analysis data (Blitzer et al., 2007), where the goal is toclassify text documents as expressing apositiveornegativesentiment (i.e., a classification problem with two classes).We are going to focus on book reviews. To load the data, type:
```
import lxml... | github_jupyter |
## API tutorial
### Expression building
(note: may have old API in some cases)
```
import dynet as dy
## ==== Create a new computation graph
# (it is a singleton, we have one at each stage.
# dy.renew_cg() clears the current one and starts anew)
dy.renew_cg()
## ==== Creating Expressions from user input / constant... | github_jupyter |
# Using [vtreat](https://github.com/WinVector/pyvtreat) with Classification Problems
Nina Zumel and John Mount
November 2019
Note: this is a description of the [`Python` version of `vtreat`](https://github.com/WinVector/pyvtreat), the same example for the [`R` version of `vtreat`](https://github.com/WinVector/vtreat)... | github_jupyter |
```
# Copyright 2019 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 applicable law or agreed to in writi... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.