code
stringlengths
2.5k
150k
kind
stringclasses
1 value
## Some exploratory data analysis and the development of vegetation dependent angle model authors: Tuguldur Sukhbold ``` datapath = '../d/' import numpy as np import pandas as pd import matplotlib.pyplot as plt from itertools import product as iterp from math import sin, cos, radians, pi from sklearn.metrics impor...
github_jupyter
``` import time import numpy as np import random def write_table2sql(table, engine, sql=None): def select_col_agg(mask): """ select col agg pair :return: """ col_num = len(table['header']) sel_idx = np.argmax(np.random.rand(col_num) * mask) sel_type = table[...
github_jupyter
###### Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license. (c) Daniel Koehn based on Jupyter notebooks by Marc Spiegelman [Dynamical Systems APMA 4101](https://github.com/mspieg/dynamical-systems) and Kyle Mandli from his course [Introductio...
github_jupyter
<i>Copyright (c) Microsoft Corporation. All rights reserved.</i> <i>Licensed under the MIT License.</i> # Vowpal Wabbit Deep Dive <center> <img src="https://github.com/VowpalWabbit/vowpal_wabbit/blob/master/logo_assets/vowpal-wabbits-github-logo.png?raw=true" height="30%" width="30%" alt="Vowpal Wabbit"> </center> ...
github_jupyter
# Neural Network In this tutorial, we'll create a simple neural network classifier in TensorFlow. The key advantage of this model over the [Linear Classifier](https://github.com/easy-tensorflow/easy-tensorflow/blob/master/3_Neural_Network/Tutorials/1_Neural_Network.ipynb) trained in the previous tutorial is that it ca...
github_jupyter
``` import numpy as np from scipy.optimize import least_squares from scipy.optimize import basinhopping from pandas import Series, DataFrame import pandas as pd import matplotlib import matplotlib.pyplot as plt matplotlib.use('Qt5Agg') %matplotlib qt5 # # if pade.py is not in the current directory, set this path: # #im...
github_jupyter
# Peak Detection Feature detection, also referred to as peak detection, is the process by which local maxima that fulfill certain criteria (such as sufficient signal-to-noise ratio) are located in the signal acquired by a given analytical instrument. This process results in “features” associated with the analysis of ...
github_jupyter
# Homework 0 ### Due Tuesday, September 10 (but no submission is required) --- Welcome to CS109 / STAT121 / AC209 / E-109 (http://cs109.org/). In this class, we will be using a variety of tools that will require some initial configuration. To ensure everything goes smoothly moving forward, we will setup the majorit...
github_jupyter
``` import os import numpy as np from glob import glob from deformation_functions import * from menpo_functions import * from logging_functions import * from data_loading_functions import * from time import time from scipy.misc import imsave %matplotlib inline dataset='training' img_dir='/Users/arik/Dropbox/a_mac_thes...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import cython import timeit import math %load_ext cython ``` # Native code compilation We will see how to convert Python code to native compiled code. We will use the example of calculating the pairwise distance between a set of vectors, a $O(n^2)$ operation. F...
github_jupyter
# MSOA Mapping - England ``` import pandas as pd import geopandas as gpd import matplotlib.pyplot as plt import numpy as np from shapely.geometry import Point from sklearn.neighbors import KNeighborsRegressor import rasterio as rst from rasterstats import zonal_stats %matplotlib inline path = r"[CHANGE THIS PATH]\Eng...
github_jupyter
# Intro to Object Detection Colab Welcome to the object detection colab! This demo will take you through the steps of running an "out-of-the-box" detection model in SavedModel format on a collection of images. Imports ``` !pip install -U --pre tensorflow=="2.2.0" import os import pathlib # Clone the tensorflow mode...
github_jupyter
# Multi-Agent Reinforcement Learning ### Where do we see it? Multi agent reinforcement learning is a type of Reinforcement Learning which involves more than one agent interacting with an environment. There are many examples of Multi Agent systems around us Be it early morning with all the cars going to work <img src...
github_jupyter
``` %matplotlib notebook from matplotlib import style style.use('fivethirtyeight') import matplotlib.pyplot as plt import numpy as np import pandas as pd import datetime as dt ``` # Reflect Tables into SQLAlchemy ORM ``` # Python SQL toolkit and Object Relational Mapper import sqlalchemy from sqlalchemy.ext.automap i...
github_jupyter
<font size = "5"> **Chapter 4: [Spectroscopy](CH4-Spectroscopy.ipynb)** </font> <hr style="height:1px;border-top:4px solid #FF8200" /> # Analysis of Core-Loss Spectra <font size = "5"> **This notebook does not work in Google Colab** </font> [Download](https://raw.githubusercontent.com/gduscher/MSE672-Introduct...
github_jupyter
``` # Método para resolver las energías y eigenfunciones de un sistema cuántico numéricamente por Teoría de Pertubaciones # Modelado Molecular 2 # By: José Manuel Casillas Martín 22-oct-2017 import numpy as np from sympy import * from sympy.physics.qho_1d import E_n, psi_n from sympy.physics.hydrogen import E_nl, R...
github_jupyter
##### Copyright 2018 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
## Problem Given a sorted list of integers of length N, determine if an element x is in the list without performing any multiplication, division, or bit-shift operations. Do this in `O(log N)` time. ## Solution We can't use binary search to locate the element because involves dividing by two to get the middle elemen...
github_jupyter
# Feature processing with Spark, training with BlazingText and deploying as Inference Pipeline Typically a Machine Learning (ML) process consists of few steps: gathering data with various ETL jobs, pre-processing the data, featurizing the dataset by incorporating standard techniques or prior knowledge, and finally tra...
github_jupyter
# Polynomial Regression ``` import numpy as np import matplotlib.pyplot as plt plt.rcParams['axes.labelsize'] = 14 plt.rcParams['axes.titlesize'] = 14 plt.rcParams['legend.fontsize'] = 12 plt.rcParams['figure.figsize'] = (8, 5) %config InlineBackend.figure_format = 'retina' ``` ### Linear models $y = \beta_0 + \beta...
github_jupyter
# Exercise 4: Optimizing Redshift Table Design ``` %load_ext sql from time import time import configparser import matplotlib.pyplot as plt import pandas as pd config = configparser.ConfigParser() config.read_file(open('dwh.cfg')) KEY=config.get('AWS','key') SECRET= config.get('AWS','secret') DWH_DB= config.get("DWH",...
github_jupyter
# Naive Bayes on Abalone Dataset ``` # importing all necessary packages and functions import pandas as pd import numpy as np import math as m from sklearn.model_selection import train_test_split import warnings warnings.filterwarnings('ignore') # kernel option to see output of multiple code lines from IPython.core....
github_jupyter
``` import pandas as pd data = pd.read_csv('./data.csv') X,y = data.drop('target',axis=1),data['target'] from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.25) import torch import torch.nn as nn import numpy as np X_train = torch.from_numpy(np.array(X_t...
github_jupyter
# All Models Test Load the right file and rull all ``` import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression, BayesianRidge from sklearn.tree import DecisionTreeRegressor from sklearn...
github_jupyter
``` import pickle import pandas as pd import numpy as np import os, sys, gc from plotnine import * import plotnine from tqdm import tqdm_notebook import seaborn as sns import warnings import matplotlib.pyplot as plt import matplotlib.font_manager as fm import matplotlib as mpl from matplotlib import rc import re from...
github_jupyter
# Python Functions ``` import numpy as np ``` ## Custom functions ### Anatomy name, arguments, docstring, body, return statement ``` def func_name(arg1, arg2): """Docstring starts wtih a short description. May have more information here. arg1 = something arg2 = somehting Returns ...
github_jupyter
<a href="https://colab.research.google.com/github/dribnet/clipit/blob/master/demos/PixelDrawer.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> #Pixray PixelArt demo Using pixray to draw pixel art. ![beruit.png](data:image/png;base64,iVBORw0KGgoAAAA...
github_jupyter
``` # Require the packages require(ggplot2) library(repr) options(repr.plot.width=15, repr.plot.height=4.5) ladder_results_dir <- "../resources/results/ladder_results_sensem/140" bootstrap_results_dir <- "../resources/results/results_semisupervised_sensem_7k/140" lemma_data <- data.frame(iteration=integer(), sense=cha...
github_jupyter
<a href="https://colab.research.google.com/github/Tessellate-Imaging/monk_v1/blob/master/study_roadmaps/4_image_classification_zoo/Classifier%20-%20Weed%20Species%20Classification%20-%20Hyperparameter%20Tuning%20using%20Monk.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt...
github_jupyter
## $k$-means clustering: An example implementation in Python 3 with numpy and matplotlib. The [$k$-means](https://en.wikipedia.org/wiki/K-means_clustering) algorithm is an unsupervised learning method for identifying clusters within a dataset. The $k$ represents the number of clusters to be identified, which is specif...
github_jupyter
``` import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV from sklearn.preprocessing import StandardScaler, LabelEncoder, OrdinalEncoder from sklearn.pipeline import make_pipeline from category_en...
github_jupyter
# Biological question: Are there differences in the binding distance of the same TF-pair in different clusters? - PART2 This notebook can be used to analyse if there are differences in the binding distance of the same TF-pair in two different clusters. In "Outline of this notebook" the general steps in the notebook a...
github_jupyter
``` #!pwd import pandas as pd import os import string from nltk.corpus import stopwords from nltk import word_tokenize, WordNetLemmatizer from nltk import stem, pos_tag from nltk.corpus import wordnet as wn from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer import os import re cwd = os.getcwd(...
github_jupyter
# TV Script Generation In this project, you'll generate your own [Seinfeld](https://en.wikipedia.org/wiki/Seinfeld) TV scripts using RNNs. You'll be using part of the [Seinfeld dataset](https://www.kaggle.com/thec03u5/seinfeld-chronicles#scripts.csv) of scripts from 9 seasons. The Neural Network you'll build will ge...
github_jupyter
# Custom NER ``` # !pip install spacy import pandas as pd import plac import random import warnings from pathlib import Path import spacy from spacy.util import minibatch, compounding data = pd.read_csv('./label_text_product_attrs.csv', dtype=str) data.rename(columns={'sale_price': 'ppu', 'final_price': 'total_price'}...
github_jupyter
### Requirement ``` aliyun-python-sdk-core==2.13.25 aliyun-python-sdk-ocr==1.0.8 Flask==1.1.2 imutils==0.5.3 json5==0.9.5 Keras==2.4.3 Keras-Preprocessing==1.1.2 matplotlib==3.3.0 numpy==1.18.5 opencv-python==4.4.0.40 oss2==2.12.1 Pillow==7.0.0 sklearn==0.0 tensorflow==2.3.0 trdg==1.6.0 ``` ### Import Aliyun python S...
github_jupyter
# Multivariate Timeseries Classification In this project we have 205 samples of 89 rows each with 14 different features. The problem is similar to activity recognition and is solved using both traditional machine learning using feature engineering and also, using deep learning using LSTM, CNN1D-LSTM and CNN2D-LSTM. #...
github_jupyter
### This notebook contains some code for processing the atlas data: 1. Hole filling, masking to prostate, extract individual histology labels (Gleason grade) 2. Interpolate histology-derived data (5mm spacing vs. 2.5mm MRI axial slices) 3. Interpolate to isotropic voxel sizes (0.8 x 0.8 x 0.8 mm^3) 4. Write data to dis...
github_jupyter
``` %matplotlib inline %run utils.ipynb import matplotlib.pyplot as plt from matplotlib import colors, ticker # import cartopy.crs as ccrs import pandas as pd import numpy as np import scipy as sp from astropy.table import Table import astropy.units as u import astropy.coordinates as coord import arviz as az import se...
github_jupyter
``` import torch import torch.nn as nn import torchvision.transforms as transforms from torch.utils.data import DataLoader import torchvision from networks import * from advertorch.attacks import LinfPGDAttack, GradientSignAttack, LinfBasicIterativeAttack, CarliniWagnerL2Attack, MomentumIterativeAttack, SpatialTransfor...
github_jupyter
``` %matplotlib inline import numpy as np import pandas as pd import pymc3 as pm import matplotlib.pyplot as plt import seaborn as sns import arviz as az import warnings warnings.filterwarnings('ignore') ``` ## Archimedes procedure for porous material density determination Experimental procedure is as follow, fo...
github_jupyter
# Scaling up ML using Cloud AI Platform In this notebook, we take a previously developed TensorFlow model to predict taxifare rides and package it up so that it can be run in Cloud AI Platform. For now, we'll run this on a small dataset. The model that was developed is rather simplistic, and therefore, the accuracy of...
github_jupyter
# Riskfolio-Lib Tutorial: <br>__[Financionerioncios](https://financioneroncios.wordpress.com)__ <br>__[Orenji](https://www.orenj-i.net)__ <br>__[Riskfolio-Lib](https://riskfolio-lib.readthedocs.io/en/latest/)__ <br>__[Dany Cajas](https://www.linkedin.com/in/dany-cajas/)__ <a href='https://ko-fi.com/B0B833SXD' target='...
github_jupyter
``` import numpy as np from scipy import io img_list=[] image_names = io.loadmat('images.mat')['images'] image_attributes = io.loadmat('attributeLabels_continuous.mat')['labels_cv'] for i in range(image_names.shape[0]): img_list.append(image_names[i][0][0]) att_dict = dict(zip(img_list, image_attributes)) res101 = ...
github_jupyter
# Phase Kickback (фазовый откат?) В деталях об этом явлении можно почитать в [qiskit texbook](https://qiskit.org/textbook/ch-algorithms/grover.html). Для нас оно будет нужно, чтобы сконветировать "классическую функцию" (оракул) $f$ в функцию определённого вида. ## Фаза Для начала, напомним, что такое **фаза**. Сущес...
github_jupyter
# Language Translation In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset of English and French sentences that can translate new sentences from English to French. ## Get the Data Since translating the whole lan...
github_jupyter
## Quality control/Exploratory data analysis Notebook By: Megan Grout (groutm2020@alumni.ohsu.edu) Adapted from code written by Dr. Marilyne Labrie and Nick Kendsersky Last updated: 20200527 Import external libraries. ``` import os import random import re import subprocess import pandas as pd import numpy as np i...
github_jupyter
# KALEEM WAHEED 18L-1811 Project 2 ### Import Libraries ``` import os import cv2 import numpy as np import matplotlib.pyplot as plt import random import tensorflow as tf import keras from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D fro...
github_jupyter
# 多层感知机 :label:`sec_mlp` 在 :numref:`chap_linear`中, 我们介绍了softmax回归( :numref:`sec_softmax`), 然后我们从零开始实现softmax回归( :numref:`sec_softmax_scratch`), 接着使用高级API实现了算法( :numref:`sec_softmax_concise`), 并训练分类器从低分辨率图像中识别10类服装。 在这个过程中,我们学习了如何处理数据,如何将输出转换为有效的概率分布, 并应用适当的损失函数,根据模型参数最小化损失。 我们已经在简单的线性模型背景下掌握了这些知识, 现在我们可以开始对深度神经网络的探索,这...
github_jupyter
## Geocoding Tweets This script showcases how we geocoded (e.g. added coordinates) to tweets containing a placename in the Netherlands. For this, we made use of cbsodata and Nominatim from geopy, which uses the OSM database for geocoding strings. ``` # Import needed libraries import pandas as pd import numpy as np imp...
github_jupyter
# Numpy: Documentação : https://numpy.org/doc/stable/user/absolute_beginners.html#numpy-the-absolute-basics-for-beginners ## Instalação: Insira o código abaixo no Anaconda Prompt: <b>pip install numpy</b> https://numpy.org/install/ ## Importação: https://numpy.org/doc/stable/user/absolute_beginners.html#how-to-imp...
github_jupyter
``` import numpy as np from numpy import loadtxt import pylab as pl from IPython import display from RcTorchPrivate import * from matplotlib import pyplot as plt from scipy.integrate import odeint %matplotlib inline #this method will ensure that the notebook can use multiprocessing on jupyterhub or any other linux base...
github_jupyter
# Decision Tree Classification ``` # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Social_Network_Ads.csv') X = dataset.iloc[:, [2, 3]].values y = dataset.iloc[:, 4].values # Splitting the dataset into the Training set an...
github_jupyter
# Using TensorNet (Basic) This notebook will demonstrate some of the core functionalities of TensorNet: - Creating and setting up a dataset - Augmenting the dataset - Creating and configuring a model and viewing its summary - Defining an optimizer and a criterion - Setting up callbacks - Training and validating the m...
github_jupyter
``` # Code source: Sebastian Curi and Andreas Krause. # Python Notebook Commands %matplotlib inline %reload_ext autoreload %load_ext autoreload %autoreload 2 # Numerical Libraries import numpy as np import matplotlib.pyplot as plt from matplotlib import rcParams rcParams['figure.figsize'] = (10, 5) # Change this if ...
github_jupyter
``` #Install bert package for tensorflow v1 !pip install bert-tensorflow==1.0.1 import bert from bert import run_classifier from bert import optimization from bert import tokenization from datetime import datetime import keras from keras import layers from keras.callbacks import ReduceLROnPlateau import numpy as np im...
github_jupyter
``` import tensorflow as tf print(tf.__version__) ``` The Fashion MNIST data is available directly in the tf.keras datasets API. You load it like this: ``` mnist = tf.keras.datasets.fashion_mnist ``` Calling load_data on this object will give you two sets of two lists, these will be the training and testing values f...
github_jupyter
``` %load_ext autoreload %autoreload 2 # Add parent directory into system path import sys, os sys.path.insert(1, os.path.abspath(os.path.normpath('..'))) from utils.dataset_generator import generate_dataset, ImplicitDataset, TestDataset, SliceDataset import numpy as np from sdf import * import math @sdf3 def gyroid(w...
github_jupyter
# Exploring Datasets with Python In this short demo we will analyse a given dataset from 1978, which contains information about politicians having affairs. To analyse it, we will use a Jupyter Notebook, which is basically a REPL++ for Python. Entering a command with shift executes the line and prints the result. ```...
github_jupyter
# MSTICpy - Mordor data provider and browser ### Description This notebook provides a guided example of using the Mordor data provider and browser included with MSTICpy. For more information on the Mordor data sets see the [Open Threat Research Forge Mordor GitHub repo](https://github.com/OTRF/mordor) You must have ...
github_jupyter
``` import torch from transformers import MT5ForConditionalGeneration, MT5Config, MT5EncoderModel, MT5Tokenizer, Trainer, TrainingArguments from progeny_tokenizer import TAPETokenizer import numpy as np import math import random import scipy import time import pandas as pd from torch.utils.data import DataLoader, Rando...
github_jupyter
``` from util.MicFileTool import MicFile import util.Simulation as Gsim import util.RotRep as Rot import numpy as np import matplotlib.pyplot as plt from scipy import ndimage from scipy import optimize import json import os ``` # Extract the windows around the Bragg Peaks from a small grain ``` a=MicFile("AuxData/Ti...
github_jupyter
# Part 1 - 2D mesh tallies So far we have seen that neutron and photon interactions can be tallied on surfaces or cells, but what if we want to tally neutron behaviour throughout a geometry? (rather than the integrated neutron behaviour over a surface or cell). A mesh tally allows a visual inspection of the neutron b...
github_jupyter
# Tutorial: Computing with shapes of landmarks in Kendall shape spaces In this tutorial, we show how to use geomstats to perform a shape data analysis. Specifically, we aim to study the difference between two groups of data: - optical nerve heads that correspond to normal eyes, - optical nerve heads that correspond to...
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
<a href="https://cognitiveclass.ai/"> <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Ad/CCLog.png" width="200" align="center"> </a> <h1>String Operations</h1> <p><strong>Welcome!</strong> This notebook will teach you about the string operations in the Python Pr...
github_jupyter
``` from fastai.text import * from fastai.tabular import * path = Path('') data = pd.read_csv('good_small_dataset.csv', engine='python') data.head() df = data.dropna() df.to_csv('good_small_dataset_drop_missing.csv') data_lm = TextLMDataBunch.from_csv(path, 'good_small_dataset_drop_missing.csv', text_cols = 'content', ...
github_jupyter
``` import paths import yaml import os import copy import numpy as np import numpy.random as npr import scipy.optimize as spo import scipy.linalg as spl from matplotlib import pyplot as plt, collections as mc, patches as mpatches, cm, ticker from sdfs.geom_mrst import GeomMRST from sdfs.bc_mrst import BCMRST from sdfs....
github_jupyter
# Sentiment Classification & How To "Frame Problems" for a Neural Network by Andrew Trask - **Twitter**: @iamtrask - **Blog**: http://iamtrask.github.io ### What You Should Already Know - neural networks, forward and back-propagation - stochastic gradient descent - mean squared error - and train/test splits ### Wh...
github_jupyter
# **CSE 7324 Lab 3: Extending Logistic Regression** ### *Thomas Adams, Suleiman Hijazeen, Nancy Le and Andrew Whigham* ------ ### **1. Preparation and Overview** ------ #### 1.1 Business Understanding --- Austin Animal Center is the largest no-kill shelter in the United States and provides shelter to more than 16,00...
github_jupyter
``` import time import cv2 import numpy as np from random import * from keras.models import load_model model = load_model('keras_model.h5') cap = cv2.VideoCapture(0) data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) score = [a for a in range(2)] #2 scores in one variable score[1] = 0 playerScore = score[0] p...
github_jupyter
``` import os import numpy as np import itertools import matplotlib.pyplot as plt import pandas as pd from sklearn.utils import shuffle from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from tensorflow import keras from tensorflow.keras import layers from sklearn.metric...
github_jupyter
Taken from fastai NLP "8-translation-transformer" FastText embeddings: https://fasttext.cc/docs/en/crawl-vectors.html ``` from fastai2.text.all import * from fastai2.callback.all import * from fastai2.basics import * import seaborn as sns from einops import rearrange import gc import csv path = Path('../data/irish/c...
github_jupyter
# Met Office UKV high-resolution atmosphere model data :::{eval-rst} :opticon:`tag` :badge:`Urban,badge-primary` :badge:`Sensors,badge-secondary` ::: ## Context ### Purpose To load, plot, regrid and extract an urban region from the UKV gridded model data using the [Iris package](https://scitools-iris.readthedocs.io/e...
github_jupyter
ERROR: type should be string, got "https://www.kaggle.com/zhangyang/bldcv0708091?scriptVersionId=16901388\n\n# params\n\n```\ndbg = False\nif dbg:\n dbgsz = 500\n\nPRFX = 'CV070816' \np_o = f'../output/{PRFX}'\nSEED = 111\n\nBS = 128\nSZ = 224\nFP16 = False\n```\n\n# setup\n\n```\nimport fastai\nprint('fastai.__version__: ', fastai.__version__)\n\nimport random \nimport numpy as np\nimport torch\nimport os\n\ndef set_torch_seed(seed=SEED):\n os.environ['PYTHONHASHSEED'] = str(seed)\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n \n if torch.cuda.is_available(): \n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed) \n torch.backends.cudnn.deterministic = True \n torch.backends.cudnn.benchmark = False\n\nset_torch_seed()\n\nfrom fastai import *\nfrom fastai.vision import *\nfrom fastai.callbacks import *\n\nimport scipy as sp\nfrom sklearn.metrics import cohen_kappa_score\n\ndef quadratic_weighted_kappa(y1, y2):\n return cohen_kappa_score(y1, y2, weights='quadratic')\n```\n\n# preprocess\n\n```\nimg2grd = []\n\np = '../input/aptos2019-blindness-detection'\npp = Path(p)\ntrain = pd.read_csv(pp/'train.csv')\ntest = pd.read_csv(pp/'test.csv')\nlen_blnd = len(train)\nlen_blnd_test = len(test)\n\nimg2grd_blnd = [(f'{p}/train_images/{o[0]}.png',o[1]) for o in train.values]\n\nlen_blnd, len_blnd_test\nimg2grd += img2grd_blnd\ndisplay(len(img2grd))\ndisplay(Counter(o[1] for o in img2grd).most_common())\np = '../input/diabetic-retinopathy-detection'\npp = Path(p)\n\ntrain=pd.read_csv(pp/'trainLabels.csv')\nimg2grd_diab_train=[(f'../input/diabetic-retinopathy-detection/train_images/{o[0]}.jpeg',o[1]) for o in train.values]\nimg2grd += img2grd_diab_train\ndisplay(len(img2grd))\ndisplay(Counter(o[1] for o in img2grd).most_common())\n\n# test=pd.read_csv(pp/'retinopathy_solution.csv')\n# img2grd_diab_test=[(f'../input/diabetic-retinopathy-detection/test_images/{o[0]}.jpeg',o[1]) for o in test.values]\n# img2grd += img2grd_diab_test\n# display(len(img2grd))\n# display(Counter(o[1] for o in img2grd).most_common())\np = '../input/IDRID/B. Disease Grading'\npp = Path(p)\n\ntrain=pd.read_csv(pp/'2. Groundtruths/a. IDRiD_Disease Grading_Training Labels.csv')\nimg2grd_idrid_train=[(f'../input/IDRID/B. Disease Grading/1. Original Images/a. Training Set/{o[0]}.jpg',o[1]) for o in train.values]\nimg2grd += img2grd_idrid_train\ndisplay(len(img2grd))\ndisplay(Counter(o[1] for o in img2grd).most_common())\n\ntest=pd.read_csv(pp/'2. Groundtruths/b. IDRiD_Disease Grading_Testing Labels.csv')\nimg2grd_idrid_test=[(f'../input/IDRID/B. Disease Grading/1. Original Images/b. Testing Set/{o[0]}.jpg',o[1]) for o in test.values]\nimg2grd += img2grd_idrid_test\ndisplay(len(img2grd))\ndisplay(Counter(o[1] for o in img2grd).most_common())\nif not np.all([Path(o[0]).exists() for o in img2grd]): print('Some files are missing!!!')\ndf = pd.DataFrame(img2grd)\ndf.columns = ['fnm', 'target']\n\ndf.shape\nset_torch_seed()\nidx_blnd_train = np.where(df.fnm.str.contains('aptos2019-blindness-detection/train_images'))[0]\nidx_val = np.random.choice(idx_blnd_train, int(len_blnd*0.50), replace=False)\ndf['is_val']=False\ndf.loc[idx_val, 'is_val']=True\n\nif dbg:\n df=df.head(dbgsz)\n```\n\n# dataset\n\n```\n%%time\ntfms = get_transforms()\n\ndef get_data(sz, bs):\n src = (ImageList.from_df(df=df,path='./',cols='fnm') \n .split_from_df(col='is_val') \n .label_from_df(cols='target', \n label_cls=FloatList)\n )\n\n data= (src.transform(tfms, size=sz) #Data augmentation\n .databunch(bs=bs) #DataBunch\n .normalize(imagenet_stats) #Normalize \n )\n return data\n\nbs = BS \nsz = SZ\nset_torch_seed()\ndata = get_data(sz, bs)\n```\n\n# model\n\n```\n%%time\n# Downloading: \"https://download.pytorch.org/models/resnet50-19c8e357.pth\" to /tmp/.cache/torch/checkpoints/resnet50-19c8e357.pth\n\n# Making pretrained weights work without needing to find the default filename\nif not os.path.exists('/tmp/.cache/torch/checkpoints/'):\n os.makedirs('/tmp/.cache/torch/checkpoints/')\n!cp '../input/pytorch-vision-pretrained-models/resnet50-19c8e357.pth' '/tmp/.cache/torch/checkpoints/resnet50-19c8e357.pth'\nlearn = cnn_learner(data, \n base_arch = models.resnet50, \n path=p_o)\nlearn.loss = MSELossFlat\n\nif FP16: learn = learn.to_fp16()\nlearn.freeze()\nlen(learn.data.train_dl)\n%%time\nlearn.lr_find(start_lr=1e-4)\nlearn.recorder.plot(suggestion=True)\nset_torch_seed()\nlearn.fit_one_cycle(15, max_lr=5e-3, callbacks=[SaveModelCallback(learn, name='bestmodel_frozen')])\nlearn.recorder.plot_losses()\n# learn.recorder.plot_metrics()\nlearn.save('mdl-frozen')\n!nvidia-smi\nlearn.unfreeze()\n%%time\nlearn.lr_find()\nlearn.recorder.plot(suggestion=True)\nset_torch_seed()\nlearn.fit_one_cycle(10, max_lr=slice(5e-7,5e-5), callbacks=[SaveModelCallback(learn, name='bestmodel_finetune')])\nlearn.recorder.plot_losses()\n# learn.recorder.plot_metrics()\nlearn.save('mdl')\n!nvidia-smi\n```\n\n# validate and thresholding\n\n```\nlearn = learn.to_fp32()\n%%time\nset_torch_seed()\npreds_val, y_val = learn.get_preds(ds_type=DatasetType.Valid)\npreds_val = preds_val.numpy().squeeze()\ny_val= y_val.numpy()\nnp.save(f'{p_o}/preds_val.npy', preds_val)\nnp.save(f'{p_o}/y_val.npy', y_val)\n# https://www.kaggle.com/c/petfinder-adoption-prediction/discussion/88773#latest-515044\n# We used OptimizedRounder given by hocop1. https://www.kaggle.com/c/petfinder-adoption-prediction/discussion/76107#480970\n# put numerical value to one of bins\ndef to_bins(x, borders):\n for i in range(len(borders)):\n if x <= borders[i]:\n return i\n return len(borders)\n\nclass Hocop1OptimizedRounder(object):\n def __init__(self):\n self.coef_ = 0\n\n def _loss(self, coef, X, y, idx):\n X_p = np.array([to_bins(pred, coef) for pred in X])\n ll = -quadratic_weighted_kappa(y, X_p)\n return ll\n\n def fit(self, X, y):\n coef = [1.5, 2.0, 2.5, 3.0]\n golden1 = 0.618\n golden2 = 1 - golden1\n ab_start = [(1, 2), (1.5, 2.5), (2, 3), (2.5, 3.5)]\n for it1 in range(10):\n for idx in range(4):\n # golden section search\n a, b = ab_start[idx]\n # calc losses\n coef[idx] = a\n la = self._loss(coef, X, y, idx)\n coef[idx] = b\n lb = self._loss(coef, X, y, idx)\n for it in range(20):\n # choose value\n if la > lb:\n a = b - (b - a) * golden1\n coef[idx] = a\n la = self._loss(coef, X, y, idx)\n else:\n b = b - (b - a) * golden2\n coef[idx] = b\n lb = self._loss(coef, X, y, idx)\n self.coef_ = {'x': coef}\n\n def predict(self, X, coef):\n X_p = np.array([to_bins(pred, coef) for pred in X])\n return X_p\n\n def coefficients(self):\n return self.coef_['x']\n# https://www.kaggle.com/c/petfinder-adoption-prediction/discussion/76107#480970\nclass AbhishekOptimizedRounder(object):\n def __init__(self):\n self.coef_ = 0\n\n def _kappa_loss(self, coef, X, y):\n X_p = np.copy(X)\n for i, pred in enumerate(X_p):\n if pred < coef[0]:\n X_p[i] = 0\n elif pred >= coef[0] and pred < coef[1]:\n X_p[i] = 1\n elif pred >= coef[1] and pred < coef[2]:\n X_p[i] = 2\n elif pred >= coef[2] and pred < coef[3]:\n X_p[i] = 3\n else:\n X_p[i] = 4\n\n ll = quadratic_weighted_kappa(y, X_p)\n return -ll\n\n def fit(self, X, y):\n loss_partial = partial(self._kappa_loss, X=X, y=y)\n initial_coef = [0.5, 1.5, 2.5, 3.5]\n self.coef_ = sp.optimize.minimize(loss_partial, initial_coef, method='nelder-mead')\n\n def predict(self, X, coef):\n X_p = np.copy(X)\n for i, pred in enumerate(X_p):\n if pred < coef[0]:\n X_p[i] = 0\n elif pred >= coef[0] and pred < coef[1]:\n X_p[i] = 1\n elif pred >= coef[1] and pred < coef[2]:\n X_p[i] = 2\n elif pred >= coef[2] and pred < coef[3]:\n X_p[i] = 3\n else:\n X_p[i] = 4\n return X_p\n\n def coefficients(self):\n return self.coef_['x']\ndef bucket(preds_raw, coef = [0.5, 1.5, 2.5, 3.5]):\n preds = np.zeros(preds_raw.shape)\n for i, pred in enumerate(preds_raw):\n if pred < coef[0]:\n preds[i] = 0\n elif pred >= coef[0] and pred < coef[1]:\n preds[i] = 1\n elif pred >= coef[1] and pred < coef[2]:\n preds[i] = 2\n elif pred >= coef[2] and pred < coef[3]:\n preds[i] = 3\n else:\n preds[i] = 4\n return preds\noptnm2coefs = {'simple': [0.5, 1.5, 2.5, 3.5]}\n%%time\nset_torch_seed()\noptR = Hocop1OptimizedRounder()\noptR.fit(preds_val, y_val)\noptnm2coefs['hocop1'] = optR.coefficients()\n%%time\nset_torch_seed()\noptR = AbhishekOptimizedRounder()\noptR.fit(preds_val, y_val)\noptnm2coefs['abhishek'] = optR.coefficients()\noptnm2coefs\noptnm2preds_val_grd = {k: bucket(preds_val, coef) for k,coef in optnm2coefs.items()}\noptnm2qwk = {k: quadratic_weighted_kappa(y_val, preds) for k,preds in optnm2preds_val_grd.items()}\noptnm2qwk\nCounter(y_val).most_common()\npreds_val_grd = optnm2preds_val_grd['simple'].squeeze()\npreds_val_grd.mean()\nCounter(preds_val_grd).most_common()\nlist(zip(preds_val_grd, y_val))[:10]\n(preds_val_grd== y_val.squeeze()).mean()\npickle.dump(optnm2qwk, open(f'{p_o}/optnm2qwk.p', 'wb'))\npickle.dump(optnm2preds_val_grd, open(f'{p_o}/optnm2preds_val_grd.p', 'wb'))\npickle.dump(optnm2coefs, open(f'{p_o}/optnm2coefs.p', 'wb'))\n```\n\n# testing\n\n```\ndf_test = pd.read_csv('../input/aptos2019-blindness-detection/test.csv')\ndf_test.head()\nlearn.data.add_test(\n ImageList.from_df(df_test,\n '../input/aptos2019-blindness-detection',\n folder='test_images',\n suffix='.png'))\n%%time\nset_torch_seed()\npreds_tst, _ = learn.get_preds(ds_type=DatasetType.Test)\npreds_tst = preds_tst.numpy().squeeze()\nnp.save(f'{p_o}/preds_tst.npy', preds_tst)\ndef bucket(preds_raw, coef = [0.5, 1.5, 2.5, 3.5]):\n preds = np.zeros(preds_raw.shape)\n for i, pred in enumerate(preds_raw):\n if pred < coef[0]:\n preds[i] = 0\n elif pred >= coef[0] and pred < coef[1]:\n preds[i] = 1\n elif pred >= coef[1] and pred < coef[2]:\n preds[i] = 2\n elif pred >= coef[2] and pred < coef[3]:\n preds[i] = 3\n else:\n preds[i] = 4\n return preds\ncoef = optnm2coefs['simple']\npreds_tst_grd = bucket(preds_tst, coef)\npreds_tst_grd.squeeze()\nCounter(preds_tst_grd.squeeze()).most_common()\n```\n\n## submit\n\n```\nsubm = pd.read_csv(\"../input/aptos2019-blindness-detection/test.csv\")\nsubm['diagnosis'] = preds_tst_grd.squeeze().astype(int)\nsubm.head()\nsubm.diagnosis.value_counts()\nsubm.to_csv(f\"{p_o}/submission.csv\", index=False)\n```\n\n"
github_jupyter
# Deep Markov Model ## Introduction We're going to build a deep probabilistic model for sequential data: the deep markov model. The particular dataset we want to model is composed of snippets of polyphonic music. Each time slice in a sequence spans a quarter note and is represented by an 88-dimensional binary vector...
github_jupyter
``` %matplotlib inline import os # import wfdb as wf # le module n'est pas reconnu import numpy as np import pandas as pd # from pandas.compat import StringIO # pour pouvoir lire fichiers anotations mais ne fonctionne pas import seaborn as sns import matplotlib.pyplot as plt from sklearn import linear_model from sklear...
github_jupyter
``` !pip install --upgrade language-check import numpy as np import seaborn as sns import pandas as pd import matplotlib.pyplot as plt from sklearn.feature_extraction.text import CountVectorizer,_preprocess,TfidfVectorizer from sklearn.metrics.pairwise import linear_kernel,cosine_similarity from nltk.stem.snowball imp...
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
# Python Dictionary Python dictionary is a collection of key:value pairs. Each key:value pair maps the key to its associated value. A dictionary is a collection that is ordered, changeable, and does not allow duplicates. ``` # empty dictionary d = {} type(d) d2 = {'name':'John', 'last_name':'Doe', 'age':30} d2 d2[...
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
``` import os import numpy as np import pandas as pd import json import pickle from scipy import sparse import scipy.io dataset_name = 'dblp' data_path = os.path.join('../dataset/raw/{}'.format(dataset_name)) citations = [] incomming = {} for i in range(4): fn = os.path.join(data_path, 'dblp-ref-{}.json'.format(i...
github_jupyter
# Introduction to PyCaret - An open source low-code ML library ## This notebook consists 2 parts - Classification part using Titanic DataSet - Regression part using House Price Regression DataSet ![](https://pycaret.org/wp-content/uploads/2020/03/Divi93_43.png) You can reach pycaret website and documentation from ...
github_jupyter
# 2. Coding Style ## 2.1 Whitespace In Python, whitespace is used to structure code. Whitespace is important, so you have to be careful with how you use it. I'll be showing some examples, but don't worry about the code just yet. I just want you to know the use of whitespaces. We'll tackle more about the codes you'll...
github_jupyter
## Boxplot plots _______ tg: @misha_grol and anna.petrovskaia@skoltech.ru Boxplots for features based on DEM and NDVI ``` # Uncomment for Google colab # !pip install maxvolpy # !pip install clhs # !git clone https://github.com/EDSEL-skoltech/maxvol_sampling # %cd maxvol_sampling/ import csv import seaborn as ...
github_jupyter
Doc title: **Amazon Advertising Targeting Report** Article notes: Data came from 'Reports/Advertising Reports/Sponsored Products/Targeting Report' @Amazon Seller Central. 文章备注:亚马逊后台广告目标投放报告分析 Last modified date: 2019-12-05 16:33:04 ``` # 引入pandas数据分析模块 import pandas as pd # 数据范例:美国站,月度数据 workdf = pd.read_excel('da...
github_jupyter
``` from tensorflow.python.keras import backend as K from tensorflow.python.keras.applications.resnet50 import ResNet50, preprocess_input from tensorflow.python.keras.preprocessing import image from tensorflow.python.keras.layers import Conv2D, GlobalAveragePooling2D, Input, Dropout, Dense from tensorflow.python.keras....
github_jupyter
``` import csv import numpy as np import tensorflow as tf from sklearn.model_selection import train_test_split RANDOM_SEED = 42 ``` # 各パス指定 ``` dataset = 'model/point_history_classifier/point_history_allkeypoints.csv' model_save_path = 'model/point_history_classifier/point_history_classifier_allkeypoints.hdf5' ``` ...
github_jupyter
# Shor's algorithm, fully classical implementation ``` %matplotlib inline import random import math import itertools def period_finding_classical(a,N): # This is an inefficient classical algorithm to find the period of f(x)=a^x (mod N) # f(0) = a**0 (mod N) = 1, so we find the first x greater than 0 for which ...
github_jupyter
``` 16 import random import math import numpy as np import pandas as pd import matplotlib.pyplot as plt from timeit import Timer my_list = list(range(10**6)) my_array = np.array(my_list) def for_add(): return [item + 1 for item in my_list] def vec_add(): return my_array + 1 print("For loop addition :") print...
github_jupyter
## ELIZA Copyright (C) 2019 Szymon Jessa ### Kod Elizy Importujemy biblioteki: ``` import doctest import re ``` Tworzymy zmienną globalną, która będzie zapisywała wypowiedzi podczas konwersacji. ``` memstack = [] ``` Funkcja odpowiadająca za przetworzenie wypowiedzi użytkownika i zaproponowanie odpowiedzi. ``` ...
github_jupyter
<a href="https://www.bigdatauniversity.com"><img src="https://ibm.box.com/shared/static/cw2c7r3o20w9zn8gkecaeyjhgw3xdgbj.png" width="400" align="center"></a> <h1 align=center><font size="5"> SVM (Support Vector Machines)</font></h1> In this notebook, you will use SVM (Support Vector Machines) to build and train a mod...
github_jupyter
``` %reset ``` # Simulate particles translating through OAM beam Liz Strong 4/17/2020 ``` import sys sys.path.append('../slvel') import pandas as pd import numpy as np import matplotlib.pyplot as plt from calc_intensity import calculate_e_field_intensity from scattering_particle import Particle import scattering_...
github_jupyter
## Dependencies ``` from openvaccine_scripts import * import warnings, json from sklearn.model_selection import KFold, StratifiedKFold, GroupKFold import tensorflow.keras.layers as L import tensorflow.keras.backend as K from tensorflow.keras import optimizers, losses, Model from tensorflow.keras.callbacks import Early...
github_jupyter
# 02. Custom Dataset 만들어보기 - Dataset Generation! - 폴더별로 사진들이 모여있다면, 그 dataset을 우리가 원하는 형태로 바꿔봅시다! ``` import numpy as np import os from scipy.misc import imread, imresize import matplotlib.pyplot as plt %matplotlib inline print ("Package loaded") cwd = os.getcwd() print ("Current folder is %s" % (cwd) ) # 학습할 폴더 경로...
github_jupyter
<a href="https://colab.research.google.com/github/tiffanysn/general_learning/blob/dev/Quantium/Quantium_task_2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` from google.colab import drive drive.mount('/content/drive') ``` ## Load required lib...
github_jupyter
# 501R Lab1 ## Part 1 ## Program to generate random image ``` import cairo import numpy as np # Set the random seed seed = None # Populate for using specific value for consistency random = np.random.RandomState(seed) # Function to draw random integers in a range def randinteger(n, m=1): if m == 1: return...
github_jupyter
##### Copyright 2018 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
# Introduction In a sport like Football, each player contributes to the team's success. It's important to understand the player's overall performance. In this report we will look into various factors that impact the player's overall performance. ``` import pandas as pd import numpy as np #to replace values in column...
github_jupyter
**Principal Component Analysis (PCA)** is widely used in Machine Learning pipelines as a means to compress data or help visualization. This notebook aims to walk through the basic idea of the PCA and build the algorithm from scratch in Python. Before diving directly into the PCA, let's first talk about several import ...
github_jupyter