code stringlengths 2.5k 150k | kind stringclasses 1
value |
|---|---|
# DATASET 2 - GPU Runtime
```
import pandas as pd
import numpy as np
import seaborn as sns #visualisation
import matplotlib.pyplot as plt #visualisation
%matplotlib inline
import pandas as pd
import numpy as np
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier,export_graphviz
from sklearn.model... | github_jupyter |
# Horovod
## Introduction
This recipe shows how to run [Horovod](https://github.com/uber/horovod) distributed training framework using Batch AI.
Currently Batch AI has no native support for Horovod framework, but it's easy to run it using customtoolkit and job preparation command line.
## Details
- Standard Horov... | github_jupyter |
To aid autoassociative recall (sparse recall using partial pattern), we need to two components -
1. each pattern remembers a soft mask of the contribution of each
element in activating it. For example, if an element varies a lot at high activation levels, that element should be masked out when determining activation. ... | github_jupyter |
Original samples in https://fslab.org/FSharp.Charting/FurtherSamples.html
```
#load "FSharp.Charting.Paket.fsx"
#load "FSharp.Charting.fsx"
```
## Sample data
```
open FSharp.Charting
open System
open System.Drawing
let data = [ for x in 0 .. 99 -> (x,x*x) ]
let data2 = [ for x in 0 .. 99 -> (x,sin(float x / 10.0))... | github_jupyter |
<a href="https://colab.research.google.com/github/c-w-m/btap/blob/master/ch02/API_Data_Extraction.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
Original source: [**Blueprints for Text Analysis Using Python**](https://github.com/blueprints-for-text... | github_jupyter |
# Examples for Bounded Innovation Propagation (BIP) MM ARMA parameter estimation
```
import numpy as np
import scipy.signal as sps
import robustsp as rsp
import matplotlib.pyplot as plt
import matplotlib
# Fix random number generator for reproducibility
np.random.seed(1)
```
## Example 1: AR(1) with 30 percent isola... | github_jupyter |
# Perceptron
### TODO
- **[ok]** Ajouter dans le code la fonction d'évaluation du réseau
- **[ok]** Plot de $\sum |E|$ par itération (i.e. num updates par itération)
- Critere d'arrêt + générale
- Lire l'article de rérérence
- Ajouter la preuve de convergence
- Ajouter notations et explications
- Tester l'autre versi... | github_jupyter |
## Load Weight
```
import torch
import numpy as np
path = './output/0210/Zero/checkpoint_400.pth'
import os
assert(os.path.isfile(path))
weight = torch.load(path)
input_dim = weight['input_dim']
branchNum = weight['branchNum']
IOScale = weight['IOScale']
state_dict = weight['state_dict']... | github_jupyter |
# OneHotEncoder
Performs One Hot Encoding.
The encoder can select how many different labels per variable to encode into binaries. When top_categories is set to None, all the categories will be transformed in binary variables.
However, when top_categories is set to an integer, for example 10, then only the 10 most po... | github_jupyter |
```
from eva_cttv_pipeline.clinvar_xml_utils import *
from consequence_prediction.repeat_expansion_variants.clinvar_identifier_parsing import parse_variant_identifier
import os
import sys
import urllib
import requests
import xml.etree.ElementTree as ElementTree
from collections import Counter
import hgvs.parser
from ... | github_jupyter |
# GPU
```
gpu_info = !nvidia-smi
gpu_info = '\n'.join(gpu_info)
print(gpu_info)
```
# CFG
```
CONFIG_NAME = 'config41.yml'
debug = False
from google.colab import drive, auth
# ドライブのマウント
drive.mount('/content/drive')
# Google Cloudの権限設定
auth.authenticate_user()
def get_github_secret():
import json
... | github_jupyter |
# Transfer Learning Template
```
%load_ext autoreload
%autoreload 2
%matplotlib inline
import os, json, sys, time, random
import numpy as np
import torch
from torch.optim import Adam
from easydict import EasyDict
import matplotlib.pyplot as plt
from steves_models.steves_ptn import Steves_Prototypical_Network
... | github_jupyter |
# Cat Dog Classification
## 1. 下载数据
我们将使用包含猫与狗图片的数据集。它是Kaggle.com在2013年底计算机视觉竞赛提供的数据集的一部分,当时卷积神经网络还不是主流。可以在以下位置下载原始数据集: `https://www.kaggle.com/c/dogs-vs-cats/data`。
图片是中等分辨率的彩色JPEG。看起来像这样:

不出所料,2013年的猫狗大战的Kaggle比赛是由使用卷... | github_jupyter |
# Titanic: Machine Learning from Disaster
## [Kaggle Challenge](https://www.kaggle.com/c/titanic#tutorials)
**In this challenge, we ask you to complete the analysis of what sorts of people were likely to survive. In particular, we ask you to apply the tools of machine learning to predict which passengers survived the ... | github_jupyter |
# CNN for Classification
---
In this notebook, we define **and train** an CNN to classify images from the [Fashion-MNIST database](https://github.com/zalandoresearch/fashion-mnist).
### Load the [data](http://pytorch.org/docs/master/torchvision/datasets.html)
In this cell, we load in both **training and test** datase... | github_jupyter |
```
import os
os.environ['KERAS_BACKEND'] = 'theano'
from keras.models import Sequential
from keras.layers import Input, Dense, Convolution2D, MaxPooling2D, UpSampling2D, Dropout, Flatten
from keras import optimizers
from keras.models import Model
from keras import backend as K
import numpy
# train
def classifier(n):... | github_jupyter |
# Titanic: Machine Learning from Disaster
---
```
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.model_selection import train_test_split, learning_curve, GridSearchCV, cross_validate
from sklearn.metrics import f1_score, accuracy_score, make_scorer
from sklearn.linear_model import LogisticRe... | github_jupyter |
# Widget Events
In this lecture we will discuss widget events, such as button clicks!
## Special events
The `Button` is not used to represent a data type. Instead the button widget is used to handle mouse clicks. The `on_click` method of the `Button` can be used to register a function to be called when the button is... | github_jupyter |
# Broadcast Variables
We already saw so called *broadcast joins* which is a specific impementation of a join suitable for small lookup tables. The term *broadcast* is also used in a different context in Spark, there are also *broadcast variables*.
### Origin of Broadcast Variables
Broadcast variables where introduce... | github_jupyter |
# Sudoku
This tutorial includes everything you need to set up decision optimization engines, build constraint programming models.
When you finish this tutorial, you'll have a foundational knowledge of _Prescriptive Analytics_.
>This notebook is part of the **[Prescriptive Analytics for Python](https://rawgit.com/IB... | github_jupyter |
# RadarCOVID-Report
## Data Extraction
```
import datetime
import json
import logging
import os
import shutil
import tempfile
import textwrap
import uuid
import matplotlib.pyplot as plt
import matplotlib.ticker
import numpy as np
import pandas as pd
import pycountry
import retry
import seaborn as sns
%matplotlib in... | github_jupyter |
# Karatsuba Multiplication
Order is O(n^1.59) as opposed to O(n^2) asin the case of normal multiplication.<br>
This is a recursive technique performed with the divide and conquer technique.
## By retaining the numbers in the same base
```
def addition(m, n, r) :
res = 0
a = m
b = n
po = 0
c = 0
... | 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 |
## Dragon Real Estate - Price Predictor
```
import pandas as pd
housing = pd.read_csv("data.csv")
housing.head()
housing.info()
housing['CHAS'].value_counts()
housing.describe()
%matplotlib inline
# # For plotting histogram
# import matplotlib.pyplot as plt
# housing.hist(bins=50, figsize=(20, 15))
```
## Train-Test ... | github_jupyter |
```
import numpy as np
from sklearn import datasets
from scipy.optimize import minimize
from matplotlib import pyplot as plt
from sklearn.metrics.pairwise import euclidean_distances
import warnings
warnings.simplefilter("ignore")
n = 200
np.random.seed(1111)
X, y = datasets.make_blobs(n_samples=n, shuffle=True, random_... | github_jupyter |
# Replacing scalar values I
In this exercise, we will replace a list of values in our dataset by using the .replace() method with another list of desired values.
We will apply the functions in the poker_hands DataFrame. Remember that in the poker_hands DataFrame, each row of columns R1 to R5 represents the rank of eac... | github_jupyter |
```
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
def plot_series(time, series, format="-", start=0, end=None):
plt.plot(time[start:end], series[start:end], format)
plt.xlabel("Time")
plt.ylabel("Value")
plt.grid(True)
!wget --no-check-certificate \
https://raw.g... | github_jupyter |
### Exercícios do capítulo 24
```
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
%matplotlib inline
def trap(f,a,b):
return (b-a)*(f[0]+f[1])/2
def simpson13(f,a,b):
s = f[0] + 4*f[1] + f[2]
s *= (b-a)/6
#print("pontos usados:")
#print("a")
... | github_jupyter |
```
import sys,tweepy,csv,re
from textblob import TextBlob
import matplotlib.pyplot as plt
class SentimentAnalysis:
def __init__(self):
self.tweets = []
self.tweetText = []
def DownloadData(self):
# authenticating
consumerKey = '59oDfXxmBBm22p2j3Gowy4lEE'
consumerSecr... | github_jupyter |
## <font color='blue'>数据清洗案例
### 1. 导入相关包
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#jupyter notebook一定运行这一行代码,在cell中显示图形
```
### 2.导入数据集
```
df=pd.read_csv('qunar_freetrip.csv',index_col=0)
df.head(2)
```
### 3. 初步探索数据
```
#查看数据形状
df.shape
#快速了解数据的结构
df.info()... | github_jupyter |
<a href="https://colab.research.google.com/github/christianadriano/PCA_AquacultureSystem/blob/master/PCA_KMeans_All_Piscicultura.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
import pandas as pd #tables for data wrangling
import numpy as np #b... | github_jupyter |
# TensorFlowOnSpark with InputMode.TENSORFLOW
This notebook demonstrates TensorFlowOnSpark using `InputMode.TENSORFLOW`, which launches a distributed TensorFlow cluster on the Spark executors, where each TensorFlow process reads directly from disk.
### Start a Spark Standalone Cluster
First, in a terminal/shell wind... | github_jupyter |
# Determine the 2D Basis of a Plane
The first step in simulating interfaces is the determination of the two-dimensional periodicity (i.e. the basis vectors) of the plane. The interfaces are two-dimensional sections of the underlying three-dimensional lattice, and hence, the interface will exhibit the periodicity of th... | github_jupyter |
# Large scale text analysis with deep learning (3 points)
Today we're gonna apply the newly learned tools for the task of predicting job salary.
<img src="https://storage.googleapis.com/kaggle-competitions/kaggle/3342/media/salary%20prediction%20engine%20v2.png" width=400px>
_Special thanks to [Oleg Vasilev](https:/... | github_jupyter |
```
from osgeo import gdal
import numpy as np
import cv2
import matplotlib.pyplot as plt
import os
import datetime
import random
import xlwt
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, BatchNormalization, Conv2D, MaxPooling2D, Dropout, concatenate, UpSam... | github_jupyter |
```
try:
import openmdao.api as om
except ImportError:
!python -m pip install openmdao[notebooks]
import openmdao.api as om
```
# Warning Control
OpenMDAO has several classes of warnings that may be raised during operation.
In general, these warnings are useful and the user should pay attention to them.
S... | github_jupyter |
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Linear-Algebra" data-toc-modified-id="Linear-Algebra-1"><span class="toc-item-num">1 </span>Linear Algebra</a></span><ul class="toc-item"><li><span><a href="#Dot-Products" data-toc-modified-id="D... | github_jupyter |
<h2>What is the purpose of Data Wrangling?</h2>
Data Wrangling is the process of converting data from the initial format to a format that may be better for analysis.
<h3>What is the fuel consumption (L/100k) rate for the diesel car?</h3>
<h3>Import data</h3>
<p>
You can find the "Automobile Data Set" from the follow... | github_jupyter |
```
import numpy as np
import pickle
import gzip
import glob
import json
import csv
import sys
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
import imageio
import cv2
sns.set()
%matplotlib inline
```
Specify the experiment directory: pass this in as a command line argument.
... | github_jupyter |
# Operations on word vectors
Welcome to your first assignment of this week!
Because word embeddings are very computationally expensive to train, most ML practitioners will load a pre-trained set of embeddings.
**After this assignment you will be able to:**
- Load pre-trained word vectors, and measure similarity u... | github_jupyter |
## 15 Used cars dataset
A short tour through some used car data
* https://data.world/data-society/used-cars-data
This is a real-world data set with couple of flaws: wrong or missing data, outliers.
In the process we:
* inspect the data
* dig into the strange (ugly) parts and clean bad rows
* run a few aggregations... | github_jupyter |
```
import torch as t
import torchvision as tv
import numpy as np
import time
```
# 不是逻辑回归
```
# 超参数
EPOCH = 5
BATCH_SIZE = 100
DOWNLOAD_MNIST = True # 下过数据的话, 就可以设置成 False
N_TEST_IMG = 10 # 到时候显示 5张图片看效果, 如上图一
class DNN(t.nn.Module):
def __init__(self):
super(DNN, self).__init__()
... | github_jupyter |
```
import numpy as np
import time
import pickle
## I import sys to kill the program if an option is not correct.
import sys
import os
import csv
from RhoAndBeta import CalcRhoAndBetaVectors
from UtilitiesOptimization import SubgrAlgSavPrimDualObjInd, \
SubgrAlgSavPrimDualObjFn_L2Ind
from SimulationCode import Exp... | github_jupyter |
# Meanshift and Camshift
_You can view [IPython Nootebook](README.ipynb) report._
----
## Contents
- [GOAL](#GOAL)
- [Meanshift](#Meanshift)
- [Meanshift in OpenCV](#Meanshift-in-OpenCV)
- [Camshift](#Camshift)
- [Camshift in OpenCV](#Camshift-in-OpenCV)
- [Additional Resources](#Additional-Resources)
- [Exerc... | github_jupyter |
<a href="https://colab.research.google.com/github/skywalker0803r/c620/blob/main/notebook/Modeling_C620.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
import pandas as pd
import numpy as np
import joblib
!pip install autorch > log.txt
c = joblib... | github_jupyter |
# Denoising Autoencoder
Sticking with the MNIST dataset, let's add noise to our data and see if we can define and train an autoencoder to _de_-noise the images.
<img src='notebook_ims/autoencoder_denoise.png' width=70%/>
Let's get started by importing our libraries and getting the dataset.
```
import torch
import n... | github_jupyter |
```
import os
import time
import datetime as dt
import xarray as xr
from datetime import datetime
import pandas
import matplotlib.pyplot as plt
import numpy as np
import math
import geopy.distance
from math import sin, pi
from scipy import interpolate
from scipy import stats
#functions for running storm data
import sy... | github_jupyter |
## Dependencies
```
import os
import sys
import cv2
import shutil
import random
import warnings
import numpy as np
import pandas as pd
import seaborn as sns
import multiprocessing as mp
import matplotlib.pyplot as plt
from tensorflow import set_random_seed
from sklearn.utils import class_weight
from sklearn.model_sele... | github_jupyter |
```
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from tqdm import tqdm
%matplotlib inline
from torch.utils.data import Dataset, DataLoader
import torch
import torchvision
import torch.nn as nn
import torch.optim as optim
from torch.nn import functional as F
device = torch.device("cuda" i... | github_jupyter |
<a href="https://colab.research.google.com/github/AliaksandrSiarohin/first-order-model/blob/master/demo.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Demo for paper "First Order Motion Model for Image Animation"
To try the demo, press the 2 play... | github_jupyter |
<a href="https://colab.research.google.com/github/Jun-629/20MA573/blob/master/src/bsm_price_change.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
**Consider** an european option with
- call type
- strike = 110
- maturity = T
underlying a Gbm stock ... | github_jupyter |
# Uploading a Qiskit runtime program
<div class="alert alert-block alert-info">
<b>Note:</b> Qiskit Runtime allows authorized users to upload runtime programs. Access to the Qiskit Runtime service may not mean you have access to upload a runtime program.
</div>
Here we provide an overview on how to construct and uplo... | github_jupyter |
# Installing Tensorflow
We will creat an environment for tensorflow that will activate every time we use th package
### NOTE: it will take some time!
```
%pip install --upgrade pip
%pip install tensorflow==2.5.0
```
#### If you see the message below, restart the kernel please from the panel above (Kernels>restart)!... | github_jupyter |
# Classifying Fashion-MNIST
Now it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 9... | github_jupyter |
# Classification and Prediction in GenePattern Notebook
This notebook will show you how to use k-Nearest Neighbors (kNN) to build a predictor, use it to classify leukemia subtypes, and assess its accuracy in cross-validation.
### K-nearest-neighbors (KNN)
KNN classifies an unknown sample by assigning it the phenotype... | github_jupyter |
# Time Series Analysis 1
In the first lecture, we are mainly concerned with how to manipulate and smooth time series data.
```
%matplotlib inline
import matplotlib.pyplot as plt
import os
import time
import numpy as np
import pandas as pd
! python3 -m pip install --quiet gmaps
import gmaps
import gmaps.datasets
```
... | github_jupyter |
Your name here.
Your Woskshop section here.
# Homework 3: Arrays, File I/O and Plotting
**Submit this notebook to bCourses to receive a grade for this Workshop.**
Please complete homework activities in code cells in this iPython notebook. Be sure to comment your code well so that anyone who reads it can follow it... | github_jupyter |
# Pandas Cheat Sheet
## Inspect
**df.info( )** - tells you the type of object you have eg object, int, float AND the amount of memory your DataFrame is using up!
**df.describe( )** - gives you a series of information about your DataFrame - mean, stdev, count, max, min values...
**df.shape** - gives you a tuple of t... | github_jupyter |
## BERT model for MITMovies Dataset
I was going to make this repository a package with setup.py and everything but because of my deadlines and responsibilities at my current workplace I haven't got the time to do that so I shared the structure of the project in README.md file.
```
# If any issues open the one that giv... | github_jupyter |
```
# Import common packages and create database connection
import pandas as pd
import sqlite3 as db
conn = db.connect('Db-IMDB.db')
```
1.List all the directors who directed a 'Comedy' movie in a leap year. (You need to check that the genre is 'Comedy’ and year is a leap year) Your query should return director name,... | github_jupyter |
```
!pip install torchvision==0.2.2
!pip install https://download.pytorch.org/whl/cu100/torch-1.1.0-cp36-cp36m-linux_x86_64.whl
!pip install typing
!pip install opencv-python
!pip install slackweb
!pip list | grep torchvision
!pip list | grep torch
# import cv2
import audioread
import logging
import os
import random
im... | github_jupyter |
Python programmers will often suggest that there many ways the language can be used to solve a particular
problem. But that some are more appropriate than others. The best solutions are celebrated as Idiomatic
Python and there are lots of great examples of this on StackOverflow and other websites.
A sort of sub-langu... | github_jupyter |
# 讀取字典
```
import pandas as pd
import numpy as np
import os
filepath = '/Volumes/backup_128G/z_repository/Yumin_data/玉敏_俄羅斯課本的研究'
file_dic = '華語八千詞(內含注音字型檔)/Chinese_8000W_20190515_v1.xlsx'
book_file = '實用漢語教科書2010_生詞表.xlsx'
to_file = 'processed/chinese_8000Words_results.xlsx'
# write_level_doc = '{0}/{1}'.format(fil... | github_jupyter |
# The Great Pyramid
This is an estimate of the number of people needed to raise stones to the top of the [great pyramid](https://en.wikipedia.org/wiki/Great_Pyramid_of_Giza) using basic physics, such as force, energy, and power. It relies solely on reasonable estimates of known dimensions of the great pyramid and typi... | github_jupyter |
# Aeff toy MC
```
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams['text.usetex'] = False
```
define the function for the selection efficiency, as a function of log10(E):
```
def Eeff(logE):
x0=2.7
y=1-1./(np.exp((logE-x0)/0.5)+1)
return y
```
<img src="plotEff.png" alt="effi... | github_jupyter |
# Importing from the COVID Tracking Project
This script pulls data from the API provided by the [COVID Tracking Project](https://covidtracking.com/). They're collecting data from 50 US states, the District of Columbia, and five U.S. territories to provide the most comprehensive testing data. They attempt to include po... | github_jupyter |
# Time series analysis and visualization
```
# Hide all warnings
import warnings
warnings.simplefilter('ignore')
import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import statsmodels as sm
import statsmodels.api
from tqdm import tqdm
from pylab import rcParams # Run-Control (... | github_jupyter |
<center>
<img src="../../img/ods_stickers.jpg">
## Открытый курс по машинному обучению
<center>Автор материала: Ефремова Дина (@ldinka).
# <center>Исследование возможностей BigARTM</center>
## <center>Тематическое моделирование с помощью BigARTM</center>
#### Интро
BigARTM — библиотека, предназначенная для тематиче... | 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>
## *Data Science Unit 4 Sprint 3 Assignment 2*
# Convolutional Neural Networks (CNNs)
# Assignment
Load a pretrained network from Keras, [ResNet50](https://tfhub.d... | github_jupyter |
# Question 2
You're an aspiring computational biologist, working with some alveolar (lung) cells to study some of the cellular machinery involved in disease progression. You've tagged the proteins you're interested in, run your experiment, and collected your data from the confocal microscope in your advisor's lab.
Un... | github_jupyter |
# SIR-X
This notebook exemplifies how Open-SIR can be used to fit the SIR-X model by [Maier and Dirk (2020)](https://science.sciencemag.org/content/early/2020/04/07/science.abb4557.full) to existing data and make predictions. The SIR-X model is a standard generalization of the Susceptible-Infectious-Removed (SIR) mode... | github_jupyter |
**Chapter 3 – Classification**
_This notebook contains all the sample code and solutions to the exercises in chapter 3._
# Setup
First, let's make sure this notebook works well in both python 2 and 3, import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the figures:
```... | github_jupyter |
```
import os
import numpy as np
import yaml
from astropy.io import ascii as asc
from astropy.time import Time
import astropy.units as u
import astropy.constants as c
from astropy.modeling import models, fitting
from matplotlib import pyplot as plt
%matplotlib inline
import supernova
TEST_FILE_DIR = '../data/line_in... | github_jupyter |
# Huggingface SageMaker-SDK - BERT Japanese QA example
1. [Introduction](#Introduction)
2. [Development Environment and Permissions](#Development-Environment-and-Permissions)
1. [Installation](#Installation)
2. [Permissions](#Permissions)
3. [Uploading data to sagemaker_session_bucket](#Uploading-data-... | github_jupyter |
```
from idf_analysis.idf_class import IntensityDurationFrequencyAnalyse
from idf_analysis.definitions import *
import pandas as pd
%matplotlib inline
```
# Intensity Duration Frequency Analyse
## Parameter
**series_kind**:
`PARTIAL` = Partielle Serie (partial duration series, PDS) (peak over threshold, POT)
`ANNU... | github_jupyter |
```
# Compute overlap proportion between:
# 1) clustering of individuals based on similar FCI responses
# 2) FCI question clusters results and their behavioral interpretations
# Author: Jessica Bartley
# Last edited: 11/6/17
%matplotlib inline
# libraries
import numpy as np
from __future__ import division
import mat... | github_jupyter |
## DreliaCalc LOC Report
```
import arrow
dateformat='DD.MM.YYYY - HH:mm'
print(arrow.now('Europe/Vienna').format(dateformat))
%cd /opt/notebooks/dmyplant2
!git pull --rebase
%cd ../dReliaCalc
import dmyplant2
import pandas as pd
import numpy as np
from pprint import pprint as pp
dval = pd.read_csv("input.csv",sep=';'... | github_jupyter |
```
from google.colab import drive
drive.mount('gdrive')
%cd /content/gdrive/My\ Drive/colab
from __future__ import print_function
import json
import keras
import pickle
import os.path
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from ke... | github_jupyter |
```
# -*- coding: utf-8 -*-
# This work is part of the Core Imaging Library (CIL) developed by CCPi
# (Collaborative Computational Project in Tomographic Imaging), with
# substantial contributions by UKRI-STFC and University of Manchester.
# Licensed under the Apache License, Version 2.0 (the "License");
# ... | github_jupyter |
# Isolated skyrmion in confined helimagnetic nanostructure
**Authors**: Marijan Beg, Marc-Antonio Bisotti, Weiwei Wang, Ryan Pepper, David Cortes-Ortuno
**Date**: 26 June 2016 (Updated 24 Jan 2019)
This notebook can be downloaded from the github repository, found [here](https://github.com/computationalmodelling/fidi... | github_jupyter |
```
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
```
## 1. 加载并可视化数据
```
path = 'LogiReg_data.txt'
pdData = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted'])
pdData.head()
pdData.shape
positive = pdData[pdData['Admitted'] == 1]
negative = p... | github_jupyter |
##### Copyright 2020 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 |
# 重定义森林火灾模拟
在前面的例子中,我们定义了一个 `BurnableForest`,实现了一个循序渐进的生长和燃烧过程。
假设我们现在想要定义一个立即燃烧的过程(每次着火之后燃烧到不能燃烧为止,之后再生长,而不是每次只燃烧周围的一圈树木),由于燃烧过程不同,我们需要从 `BurnableForest` 中派生出两个新的子类 `SlowBurnForest`(原来的燃烧过程) 和 `InsantBurnForest`,为此
- 将 `BurnableForest` 中的 `burn_trees()` 方法改写,不做任何操作,直接 `pass`(因为在 `advance_one_step()` 中调用了它,所以不能直接去掉)... | github_jupyter |
# VIME: Self/Semi Supervised Learning for Tabular Data
# Setup
```
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import tensorflow as tf
import umap
from sklearn.metrics import (average_precision_score, mean_squared_error,
roc_auc_score)
from... | github_jupyter |
```
from google.colab import drive
drive.mount('/content/gdrive')
%cd gdrive/My\ Drive/Colab\ Notebooks/neural\ project\ new/
# import functions
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import os
import pickle
i... | github_jupyter |
```
JSON_PATH = 'by-article-train_attn-data.json'
from json import JSONDecoder
data = JSONDecoder().decode(open(JSON_PATH).read())
word = 'Sponsored'
hyper_count = dict()
main_count = dict()
for i, article in enumerate(data):
if word in article['normalizedText'][-1]:
energies = [e for w, e in article['acti... | github_jupyter |
```
import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()
import numpy as np
import random
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer
from detectron2.data import MetadataCatalog
from detectron2.m... | github_jupyter |
# setup
importing stuff and such
```
import spotipy
import matplotlib
import numpy as np
%matplotlib notebook
from matplotlib import pylab as plt
from matplotlib import mlab
sp = spotipy.Spotify()
```
# fetch all the playlist details that have 'punk' in the name
(note that this doesn't get the track lists, we'll do... | github_jupyter |
# Machine learning for medicine
## Linear measures of non-linear things
## Overview
In this notebook we're going to address a major limitation of correlations and linear regressions in data analysis.
## Code Setup
```
import numpy as np
import scipy
import matplotlib.pyplot as plt
from ipywidgets import interact, in... | github_jupyter |
```
from anomaly import io, tmm, adm
from sklearn.metrics import f1_score
import scipy
import pandas as pd
import numpy as np
import anomaly.utils.modelselect_utils as mu
import anomaly.utils.statsutils as su
import matplotlib.pyplot as plt
import seaborn as sns
```
## The pipeline
We demonstrate below how the anoma... | github_jupyter |
# Transpose of a Matrix
In this set of exercises, you will work with the transpose of a matrix.
Your first task is to write a function that takes the transpose of a matrix. Think about how to use nested for loops efficiently.
The second task will be to write a new matrix multiplication function that takes advantage ... | github_jupyter |
# Introducing `git` version control system
* A [version control](https://en.wikipedia.org/wiki/Version_control) system helps keeping track of changes in software source code.
* With a version control system, trying and testing possibly risky attempts can be easier.
* Currently in the late 2010s, [`git`](https://en.wik... | github_jupyter |
# Amazon SageMaker로 다중 노드들 간 분산 RL을 이용해 Roboschool 에이전트 훈련
---
이 노트북은 `rl_roboschool_ray.ipynb` 의 확장으로, Ray와 TensorFlow를 사용한 강화 학습의 수평(horizontal) 스케일링을 보여줍니다.
## 해결해야 할 Roboschool 문제 선택
Roboschool은 가상 로봇 시스템에 대한 RL 정책을 훈련시키는 데 주로 사용되는 [오픈 소스](https://github.com/openai/roboschool/tree/master/roboschool) 물리 시뮬레이터입니다. ... | github_jupyter |
```
import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import turbofats
```
## Create a lightcurve
```
n_samples = 400
n_days = 100
n_components = 7
period = 7.4
std = 0.5
time = np.random.rand(n_samples) * n_days
time.sort()
time = time.reshape(-1, 1)
cosine_components = np.ran... | 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: Add two numbers whose digits are stored in a linked list in reverse order.
* [Constraints](#Constraints)
* [Test... | github_jupyter |
```
import pickle
import os
import numpy as np
from tqdm.notebook import tqdm
from quchem_ibm.exp_analysis import *
def dict_of_M_to_list(M_dict, PauliOP):
P_Qubit_list, _ = zip(*(list(*PauliOP.terms.keys())))
list_of_M_bitstrings=None
for bit_string, N_obtained in M_dict.items():
... | github_jupyter |
L'obiettivo di questa esercitazione è quello di arrivare ad implementare un sistema completo di classificazione dei sopravvissuti al disastro del Titanic. Per farlo, partiremo dall'omonimo dataset, faremo un'analisi completa dello stesso, e cercheremo di raggiungere il miglior risultato possibile in termini di accuracy... | github_jupyter |
##### Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License");
```
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at... | github_jupyter |
# Exponential Model
This model is not working! It attempts to fit an exponential curve to the data in order to predict the number of new cases. The example used here just takes in one feature and needs to be able to take an `*args` value and unpack it to be able to expand the function to take more arguments. Might be e... | github_jupyter |
在本练习中,您将实现正则化的线性回归,并使用它来研究具有不同偏差-方差属性的模型
## 1 Regularized Linear Regression 正则线性回归
在前半部分的练习中,你将实现正则化线性回归,以预测水库中的水位变化,从而预测大坝流出的水量。在下半部分中,您将通过一些调试学习算法的诊断,并检查偏差 v.s. 方差的影响。
### 1.1 Visualizing the dataset
我们将从可视化数据集开始,其中包含水位变化的历史记录,x,以及从大坝流出的水量,y。
这个数据集分为了三个部分:
- training set 训练集:训练模型
- cross validation set 交叉验证集:选择正... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.