code
stringlengths
2.5k
150k
kind
stringclasses
1 value
# CatBoostRegressor with RobustScaler This Code template is for regression analysis using CatBoostRegressor and Robust Scaler Feature Scaling technique. CatBoost is an algorithm for gradient boosting on decision trees. <img src="https://cdn.blobcity.com/assets/gpu_recommended.png" height="25" style="margin-bottom:-1...
github_jupyter
<pre><h1>E1-313 TIPR Assignment 2 Code base & Report</h1> <h2>Neural Network Implementation in Python3</h2> <h3><i> - Achint Chaudhary</i></h3> <h3>15879, M.Tech (CSA)</h3> <h5>Note:</h5> Please Scroll Down for Report section, or search "Part 1" <img src="Images/dnn_architecture.png"/> <pre> <h3>Standard Library Impo...
github_jupyter
### 함수 - 반복되는 코드를 묶음으로 효율적인 코드를 작성하도록 해주는 기능 - 기본 함수 - 파라미터와 아규먼트 - 리턴 - `*args`, `**kwargw` - docstring - scope - inner function - lambda function - Map, filter, Reduce - Decorlator #### 1. 기본 함수 - 선언과 호출 ``` point=88 if point >= 90: print("A") elif point>= 80: print("B") else: print("C") # 함수 선언 (식별자 스...
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
<a href="https://colab.research.google.com/github/andretocci/notebooks/blob/master/Post_blog_Attribution(MAM).ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ## Demostração Blog DP6 Importando pacotes necessários: ``` import pandas as pd import nu...
github_jupyter
``` from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf from tensorflow import keras from os import listdir, path import numpy as np from collections import defaultdict import datetime import random random.seed(42) # Keep the order stable everytime shuffling the f...
github_jupyter
## Best Practise 1 → Using enumerate() - Fetch elements from list ``` # List Variable example = ['use','enumerate','instead','of','iteration'] # Ideal Way for i in range(len(example)): print(f"# {i + 1}: {example[i]}") # Pythonic way - enumerate for i, value in enumerate(example, 1): print(f"# {i}:...
github_jupyter
# Müller Brown II ## Previously on Müller Brown I ``` import numpy as np from taps.paths import Paths from taps.models import MullerBrown from taps.coords import Cartesian from taps.visualize import view N = 300 x = np.linspace(-0.55822365, 0.6234994, N) y = np.linspace(1.44172582, 0.02803776, N) coords = Cartesia...
github_jupyter
<h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Introduction" data-toc-modified-id="Introduction-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Introduction</a></span><ul class="toc-item"><li><span><a href="#Example-01:-Extract-text" data-toc-modified...
github_jupyter
# **Neural machine translation with attention** Today we will train a sequence to sequence (seq2seq) model for Spanish to English translation. This is an advanced example that assumes some knowledge of sequence to sequence models. After training the model in this notebook, you will be able to input a Spanish sentence...
github_jupyter
# Predict google map review dataset ## model - kcbert - fine-tuned with naver shopping review dataset (200,000개) - train 5 epochs - 0.97 accuracy ## dataset - google map review of tourist places in Daejeon, Korea ``` import torch from torch import nn, Tensor from torch.optim import Optimizer from torch.utils.data im...
github_jupyter
### Testing for Interactive use case ``` import mlflow from azureml.core import Workspace, Experiment, Environment, Datastore, Dataset, ScriptRunConfig from azureml.core.runconfig import PyTorchConfiguration # from azureml.widgets import RunDetails from azureml.core.compute import ComputeTarget, AmlCompute from azurem...
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 (htt...
github_jupyter
*** # COVID-19 Vaccination Progress - Modelling **** ``` #common imports: import numpy as np import pandas as pd from datetime import datetime import os from itertools import permutations #import for visualization import matplotlib.pyplot as plt %matplotlib inline import matplotlib.colors import seaborn as sns impor...
github_jupyter
<a href="https://colab.research.google.com/github/Tessellate-Imaging/monk_v1/blob/master/study_roadmaps/2_transfer_learning_roadmap/5_exploring_model_families/2_vgg/1.1)%20Intro%20to%20vgg%20network%20-%20mxnet%20backend.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Op...
github_jupyter
# Use PMML to predict iris species with `ibm-watson-machine-learning` This notebook contains steps from storing sample PMML model to starting scoring new data. Some familiarity with python is helpful. This notebook uses Python 3. You will use a **Iris** data set, which details measurements of iris perianth. Use the...
github_jupyter
# Metadata preprocessing tutorial Melusine **prepare_data.metadata_engineering subpackage** provides classes to preprocess the metadata : - **MetaExtension :** a transformer which creates an 'extension' feature extracted from regex in metadata. It extracts the extensions of mail adresses. - **MetaDate :** a transforme...
github_jupyter
<p><img alt="DataOwl" width=150 src="http://gwsolutions.cl/Images/dataowl.png", align="left", hspace=0, vspace=5></p> <h1 align="center">Aplicación de la derivada</h1> <h4 align="center">Ecuaciones de una variable y Optimización</h4> <pre><div align="center"> La idea de este notebook es que sirva para iniciarse en co...
github_jupyter
# Results summary | Logistic Regression | LightGBM Classifier | Logistic Regression + ATgfe | |-------------------------------------------------------------------------|--------...
github_jupyter
``` # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in import numpy as np # linear algebra import pandas as pd # data processing, CSV file...
github_jupyter
# WeatherPy ---- #### Note * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. ``` !pip install citipy # Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests impo...
github_jupyter
# Performance - example ``` import matplotlib.pyplot as plt import networkx as nx import numpy as np import networkx as nx import numpy as np G = nx.DiGraph() G.add_node(1, capacity = 1) G.add_node(2, capacity = 1) G.add_node(3, capacity = 1) G.add_node(4, capacity = 1) G.add_node(5, capacity = 1) G.add_edge(1, 2, c...
github_jupyter
**Данный ноутбук проводит анализ текста с использование Google Cloud Nature Library** **Расценки на использование данного API:** Использование вами естественного языка рассчитывается в виде **«единиц»**, где каждый документ, отправляемый в API для анализа, представляет собой **как минимум одну единицу**. Документы, с...
github_jupyter
``` import h2o h2o.init(max_mem_size = 2) #uses all cores by default h2o.remove_all() %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd from h2o.estimators.deeplearning import H2ODeepLearningEstimator higgs = h2o.import_file('higgs_boston_train.csv') higgs.head() higgs...
github_jupyter
# Residual Networks Welcome to the first assignment of this week! You'll be building a very deep convolutional network, 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.](https://ar...
github_jupyter
# Sentiment Analysis ``` from keras.datasets import imdb # import the built-in imdb dataset in Keras # Set the vocabulary size vocabulary_size = 5000 # Load in training and test data (note the difference in convention compared to scikit-learn) (X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=vocabula...
github_jupyter
# Objective * 20181225: * Predict stock price in next day using XGBoost * Given prices and other features for the last N days, we do prediction for day N+1 * Here we split 3 years of data into train(60%), dev(20%) and test(20%) * 20190110 - Diff from StockPricePrediction_v1_xgboost.ipynb: * Here we sca...
github_jupyter
## In this notebook: - Using a pre-trained convnet to do feature extraction - Use ConvBase only for feature extraction, and use a separate machine learning classifier - Adding ```Dense``` layers to top of a frozen ConvBase, allowing us to leverage data augmentation - Fine-tuning a pre-trained convnet (Skipped,...
github_jupyter
# Gradient Descent Optimizations Mini-batch and stochastic gradient descent is widely used in deep learning, where the large number of parameters and limited memory make the use of more sophisticated optimization methods impractical. Many methods have been proposed to accelerate gradient descent in this context, and ...
github_jupyter
# The Stick and Ball Geometry The ``SpheresAndCylinders`` class contains an assortment of pore-scale models that generate geometrical information assuming the pores are spherical and throats are cylindrical. The ``SpheresAndCylinders`` is a perfect starting point for generating your own custom geometry. In fact, it...
github_jupyter
``` import os os.chdir('D:/IIM/Competitions/Resolvr') # changing working directory to required file location os.getcwd() # Importing libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns pal = ['#009786','#7CCC4E', '#1E2A39'] sns.set(style="white", color_codes=True) sns....
github_jupyter
# Welcome to Exkaldi In this section, we will train a n-grams language model and query it. Althrough __Srilm__ is avaliable in exkaldi, we recommend __Kenlm__ toolkit. ``` import exkaldi import os dataDir = "librispeech_dummy" ``` Firstly, prepare the lexicons. We have generated and saved a __LexiconBank__ object ...
github_jupyter
``` require(cowplot) require(data.table) require(ggplot2) require(ggpubr) require(pbapply) pboptions(type="timer") nthreads=10 x_breaks = c(0, .01, .02, .03, .05, .07, .1, .2, .3, .5, .7, 1, 2, 3, 5, 7, 10, 20, 30, 50) ``` # Read spot data ``` thresholds = c(seq(0, .1, by=.01), seq(.2, 1, by=.1), seq(2, 50)) dw__root...
github_jupyter
<h1 style="text-align:center">Chapter 2</h1> --- ###### Words --- Take a look at this sentence : 'The quick brown fox jumps over the lazy fox, and took his meal.' * The sentence has 13 _Words_ if you don't count punctuations, and 15 if you count punctions. * To count punctuation as a word or not depends on th...
github_jupyter
``` import torch import torch.nn.functional as F import torchsde from torchvision import datasets, transforms import math import numpy as np import pandas as pd from tqdm import tqdm from torchvision.transforms import ToTensor from torch.utils.data import DataLoader import functorch import matplotlib.pyplot as plt ...
github_jupyter
# Assignment 2 - Q-Learning and Expected Sarsa Welcome to Course 2 Programming Assignment 2. In this notebook, you will: - Implement Q-Learning with $\epsilon$-greedy action selection - Implement Expected Sarsa with $\epsilon$-greedy action selection - Investigate how these two algorithms behave on Cliff World (descr...
github_jupyter
# CTEs Products Lab ### Introduction In this lesson, we'll practice working with CTEs. As we know CTEs allow to break our queries into multiple steps by creating a temporary table. And we perform our CTEs with the following syntax: ```SQL WITH table_name AS ( SELECT ... ) SELECT ... FROM table_name; ``` Ok, l...
github_jupyter
# 2. Imperative Programming Languages 우선 2.5까지 나오는 내용 중에서 빼고 살펴보는데, 지난번에 `CMa01.ipynb`에 작성했던 컴파일러 코드에서 문제점을 수정해 보자. --- 컴파일 타겟이 되는 VM의 단순화된 버전을 하스켈로 구현 ``` -- {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE Flex...
github_jupyter
## Hi, i was having a hard time trying to load this huge data set as a pandas data frame on my pc, so i searched for alternative ways of doing this as i don't want to pay for cloud services and don't have access to better machines. ### actually the solution was pretty simple, so i'm sharing what i ended up with, maybe ...
github_jupyter
# Self-Driving Car Engineer Nanodegree ## Deep Learning ### Project: Build a Traffic Sign Recognition Classifier --- ### Step 0: Imports ``` # imported pacakges which are being used in project import pickle import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from tensorflow.contrib.la...
github_jupyter
# European Soccer Database for data analysis Using SQLite, - In this report, I will analyse the Europeon Soccer Dataset to answer some questions. This dataset comes from Kaggle and is well suited for data analysis and machine learning. It contains data for 25k+ soccer matches, 10k+ players, and teams from several Europ...
github_jupyter
# Train XGboost Model With Hyper-Params Using Serverless Functions ``` # nuclio: ignore import nuclio ``` ### Define function dependencies ``` %%nuclio cmd pip install sklearn pip install xgboost pip install matplotlib pip install mlrun %nuclio config spec.build.baseImage = "python:3.6-jessie" ``` ### Function cod...
github_jupyter
# KNN - Accuracy estimation ``` import numpy as np import pandas as pd import csv from sklearn.model_selection import GridSearchCV, KFold from sklearn.neighbors import KNeighborsClassifier from sklearn.preprocessing import MinMaxScaler from sklearn import metrics pd.options.mode.chained_assignment = None # Load dat...
github_jupyter
# [ NLP DAY 2 ] : ``` import nltk #natural language tool kit ``` 1. Preprocessing: a. segmentation b. tokenization c. POS tagging (parts of speech) 2. Word level processing: a. wordnet b. lemmatization c. stemming d. NGrams 3. Utilities: a. Tree ...
github_jupyter
# Randomized Benchmarking ## Contents 1. [Introduction](#intro) 2. [The Randomized Benchmarking Protocol](#protocol) 3. [The Intuition Behind RB](#intuition) 4. [Simultaneous Randomized Benchmarking](#simultaneousrb) 5. [Predicted Gate Fidelity](#predicted-gate-fidelity) 6. [References](#refe...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt ``` ## R50-FPN-3x ``` test_results = {'AP': 30.183924421787978, 'AP-Bathtub': 53.39773724295068, 'AP-Bed': 52.754509322305175, 'AP-Billiard table': 67.45412317841321, 'AP-Ceiling fan'...
github_jupyter
``` # default_exp datasets #export from fastai.text import * from tse.preprocessing import * from tse.tokenizers import * ``` ### Prepare Data Inputs for Q/A Following for each input for training is needed: `input_ids`, `attention_mask`, `token_type_ids`, `offsets`, `answer_text`, `start_tok_idx`, `end_tok_idx` Pr...
github_jupyter
#### Copyright 2017 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 writin...
github_jupyter
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. # Automated Machine Learning _**Prepare Data using `azureml.dataprep` for Local Execution**_ ## Contents 1. [Introduction](#Introduction) 1. [Setup](#Setup) 1. [Data](#Data) 1. [Train](#Train) 1. [Results](#Results) 1. [Test](#...
github_jupyter
# Introduction to AlTar/Pyre applications ### 1. Introduction An AlTar application is based on the [pyre](https://github.com/pyre/pyre) framework. Compared with traditional Python programming, the `pyre` framework provides enhanced features for developing high performance scientific applications, including - It int...
github_jupyter
``` import os import random ``` # get speech reps for all utts in lj ``` fp = "/home/s1785140/fairseq/examples/speech_audio_corrector/lj_speech_quantized.txt" # load file contents with open(fp, 'r') as f: lines = f.readlines() # return dict mapping from id to speech rep codes ids2speechreps = {} for l in line...
github_jupyter
# Hacking Into FasterRcnn in Pytorch - toc: true - badges: true - comments: true - categories: [jupyter] - image: images/chart-preview.png # Brief Intro In the post I will show how to tweak some of the internals of FaterRcnn in Pytorch. I am assuming the reader is someone who already have trained an object detection...
github_jupyter
<!-- dom:TITLE: PHY321: Harmonic Oscillations, Damping, Resonances and time-dependent Forces --> # PHY321: Harmonic Oscillations, Damping, Resonances and time-dependent Forces <!-- dom:AUTHOR: [Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/) at Department of Physics and Astronomy and Facility for Rare Ion ...
github_jupyter
# Adding AI to Your App There are multiple approaches one can use to leverage AI and ML in their business idea. 1. Building your own proprietary model 2. Using a pre-trained model within your application 3. Leverage Cloud providers to support AI functions in your application These different approaches have pros and ...
github_jupyter
# **Pseudotimes and cell fates** --------------------------- **Motivation:** While clustering is an useful type of analysis to try giving a structure to the development of cells towards their final stage (spermatozoa), it does not give an understanding of how the development "stretches" from start to end. For exampl...
github_jupyter
# Data Processing The project has five steps: - delet irregular (too large or small (no data)) and non-image data - remove duplicate image - remove irrelevant image - split dataset: create classes.txt, train.txt, test.txt - rename images ### Deleting irragular images ``` import os import sys import imghdr class Ima...
github_jupyter
``` import pymc3 as pm import matplotlib.pyplot as plt import pandas as pd import numpy as np import theano.tensor as tt import theano %load_ext autoreload %autoreload 2 %matplotlib inline %config InlineBackend.figure_format = 'retina' df = pd.read_csv('../datasets/bikes/hour.csv') df feature_cols = ['workingday', 'h...
github_jupyter
##### Copyright 2019 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
github_jupyter
Parametric non Parametric inference =================== Suppose you have a physical model of an output variable, which takes the form of a parametric model. You now want to model the random effects of the data by a non-parametric (better: infinite parametric) model, such as a Gaussian Process as described in [Bayesian...
github_jupyter
``` import numpy as np import pandas as pd import pickle import os import time from sklearn.metrics import r2_score, accuracy_score, confusion_matrix from sklearn.model_selection import train_test_split from IPython.display import Image import tensorflow as tf from keras.layers import Conv2D, MaxPooling2D, Flatten fr...
github_jupyter
# CST PTM Data Overview The PTM data from CST has a significant amount of missing data and requires special consideration when normalizing. The starting data is ratio-level-data - where log2 ratios have been calculated from the cancerous cell lines compared to the non-cancerous 'Normal Pool' data from within the 'plex...
github_jupyter
``` # Load the TensorBoard notebook extension %load_ext tensorboard import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense, Dropout, Bidirectional from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard from sklearn import preprocessing from sk...
github_jupyter
# Sublime Text ## Getting set up ### Laptop install Sublime Text (Done once per laptop) 1. Step one is to download and install [Sublime Text](https://www.sublimetext.com/3). Sidenote: You don't need to purchase a license, you can use it forever with all features in evaluate mode. If you purchase a license it follows...
github_jupyter
<a href="https://colab.research.google.com/github/leehanchung/cs224w/blob/main/notebooks/XCS224W_Colab3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # **CS224W - Colab 3** In Colab 2 we constructed GNN models by using PyTorch Geometric's built i...
github_jupyter
``` !python3 -m pip freeze | grep xlrd !python3 -m pip freeze | grep openpy ``` # Использование библиотеки pandas для анализа описаний уязвимостей из банка данных ФСТЭК В статье демонстрируются возможности использования библиотеки pandas для работы с информацией из банка данных ФСТЭК (bdu.fstec.ru) об угрозах (thrlis...
github_jupyter
<i>Copyright (c) Microsoft Corporation. All rights reserved.</i> <i>Licensed under the MIT License.</i> # LightGBM: A Highly Efficient Gradient Boosting Decision Tree This notebook will give you an example of how to train a LightGBM model to estimate click-through rates on an e-commerce advertisement. We will train a...
github_jupyter
``` import os datadir = "/Users/michielk/oxdata/P01/EM/Myrf_01/SET-B/B-NT-S10-2f_ROI_00/zws" # pred_file = os.path.join(datadir, 'B-NT-S10-2f_ROI_00ds7_probs1_eed2_main.h5') # dataset: 'main' pred_file = os.path.join(datadir, 'B-NT-S10-2f_ROI_00ds7_probs_main_vol00.h5') # dataset: 'main' aff_file = os.path.join(data...
github_jupyter
## sigMF STFT on GPU and CPU ``` import os import itertools from sklearn.utils import shuffle import torch, torchvision import torch.nn as nn import torch.nn.functional as d import torch.optim as optim import torch.nn.functional as F import torch.nn.modules as mod import torch.utils.data import torch.utils.data as dat...
github_jupyter
``` import re from typing import List import pandas as pd import numpy as np from tqdm.notebook import tqdm import optuna from sklearn.metrics import roc_auc_score from sklearn.preprocessing import OneHotEncoder, StandardScaler, MinMaxScaler, PolynomialFeatures from sklearn.linear_model import LogisticRegression, SGD...
github_jupyter
# Heat transfer for pipes ``` """ importing the necessary libraries, do not modify """ %matplotlib inline from IPython.display import clear_output import schemdraw as schem import schemdraw.elements as e import matplotlib.pyplot as plt import numpy as np import math import scipy.constants as sc import sympy as s...
github_jupyter
### Dataset Lets Load the dataset. We shall use the following datasets: Features are in: "sido0_train.mat" Labels are in: "sido0_train.targets" ``` from scipy.io import loadmat import numpy as np X = loadmat(r"/Users/rkiyer/Desktop/teaching/CS6301/jupyter/data/sido0_matlab/sido0_train.mat") y = np.loadtxt(r"/Users/rk...
github_jupyter
# Singleton Networks ``` import qualreas as qr import os import copy qr_path = os.path.join(os.getenv('PYPROJ'), 'qualreas') alg_dir = os.path.join(qr_path, "Algebras") ``` ## Make a Test Network ``` test1_net_dict = { 'name': 'Network Copy Test #1', 'algebra': 'Extended_Linear_Interval_Algebra', 'descri...
github_jupyter
``` import pandas import numpy as np import sklearn from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import RandomForestRegressor from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split import glob ``` # San Francisco State University ## Software ...
github_jupyter
# Estadísticos principales - Esperanzas, varianza y ley débil de los grandes números - Variables aleatorias especiales ## Esperanza La esperanza o valor esperado de una v.a. $X$ se denota $E[X]$ y se calcula como: $\begin{array}{ll} E[X] = \left\{\begin{array}{ll} \sum_i x_i P(X=x_i) & si\,X\, discreta\\ ...
github_jupyter
``` import os import pickle import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt from matplotlib.offsetbox import OffsetImage, AnnotationBbox import seaborn as sns import numpy as np import pandas as pd plt.style.use("dark_background") %matplotlib inline DATA_PATH = "/nethome/san37/Workspace/semit/da...
github_jupyter
Date: 2/09/2018 Version: 1.0 Environment: Python 3.6.1 and Jupyter notebook Libraries used: Main libraries used for assignment: * re (for regular expression, included in Anaconda Python 3.6) * sys (to display system version, included in Anaconda Python 3.6) * nltk (for text processing, included in Anaconda Python ...
github_jupyter
# Linear Algebra with Python and NumPy ``` # First, we need to import the package NumPy, which is the library enabling all the fun with algebraic structures. from numpy import * ``` ## Complex Numbers A complex number is a number of the form $z = x + jy$, where $x$ and $y$ are real numbers and $j$ is the **_imaginar...
github_jupyter
# Two Market Makers - via Pontryagin This notebook corresponds to section 4 (**Agent based models**) of "Market Based Mechanisms for Incentivising Exchange Liquidity Provision" available [here](https://vega.xyz/papers/liquidity.pdf). It models two market makers and solves the resulting game by an iterative scheme base...
github_jupyter
``` import sys import os sys.path.insert(0, os.path.abspath('../src/')) ``` # Plotting ``` from pathlib import Path import SimplePreprocessor as sp DATASETPATH = Path("../dataset/") pr = sp.SimplePreprocessor(deltas=True, discretize=False, flevel="MAGIK") netdata = pr.load_path(DATASETPATH) netdata["_date"] = netda...
github_jupyter
<a href="https://colab.research.google.com/github/cedeerwe/brutalna-akademia/blob/master/notebooks/zaverecny_test.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Inštrukcie Test pozostáva zo 7 príkladov, dokopy za 50 bodov. Na test máš 3 hodiny č...
github_jupyter
# Data types & Structures ### A great advatage of `Python` is the type of data it can handle & combine Python has been widely used to handle internet related operations, which means lots and lots of text and numbers. combined! *** ## Let's start with the basic types! ### Like other programing languages, `Python` dat...
github_jupyter
# Masakhane - Machine Translation for African Languages (Using JoeyNMT) ## Note before beginning: ### - The idea is that you should be able to make minimal changes to this in order to get SOME result for your own translation corpus. ### - The tl;dr: Go to the **"TODO"** comments which will tell you what to update to...
github_jupyter
# Evaluate the Performance of MPNN models Get all of the models, regardless how we trained them and evaluate their performance ``` %matplotlib inline from matplotlib import pyplot as plt from datetime import datetime from sklearn import metrics from tqdm import tqdm from glob import glob import pandas as pd import num...
github_jupyter
# Multi-center analysis ### Imports ``` import sys sys.path.append('../') from PAINTeR import connectivity # in-house lib used for the RPN-signature from PAINTeR import plot # in-house lib used for the RPN-signature from PAINTeR import model # in-house lib used for the RPN-signature import num...
github_jupyter
(tune-mnist-keras)= # Using Keras & TensorFlow with Tune ```{image} /images/tf_keras_logo.jpeg :align: center :alt: Keras & TensorFlow Logo :height: 120px :target: https://www.keras.io ``` ```{contents} :backlinks: none :local: true ``` ## Example ``` import argparse import os from filelock import FileLock from t...
github_jupyter
An example showing how different online solvers perform on the hand-written digits dataset. #### New to Plotly? Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the client and [reading the primer](https://plot.ly/python/getting-started/). <br>You ca...
github_jupyter
## Text Data Preprocessing In any machine learning task, cleaning or preprocessing the data is as important as model building if not more. And when it comes to unstructured data like text, this process is even more important. Objective of this notebook is to understand the various text preprocessing steps with code e...
github_jupyter
``` from google.colab import drive drive.mount('/content/drive/') import tensorflow as tf import matplotlib.pyplot as plt from keras.layers import Conv2D, Activation, GlobalAvgPool2D, MaxPooling2D, Dense, Flatten, Dropout from keras.models import Sequential file1='/content/drive/MyDrive/archive (1)/Train' file2=...
github_jupyter
``` # Useful for debugging %load_ext autoreload %autoreload 2 # Nicer plotting import matplotlib import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_format = 'retina' matplotlib.rcParams['figure.figsize'] = (8,4) ``` # Disgten example Similar to the simple example, but generating particles...
github_jupyter
<small><i>This notebook was prepared by Marco Guajardo. Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).</i></small> # Challenge Notebook ## Problem: Implement a binary search tree with insert, delete, different traversals & max/min node values * [Constraints](#Con...
github_jupyter
``` #https://pytorch.org/tutorials/beginner/pytorch_with_examples.html ``` # MNIST Dataset ### http://yann.lecun.com/exdb/mnist/ ### The MNIST database of handwritten digits, available from this page, has a training set of 60,000 examples, and a test set of 10,000 examples. It is a subset of a larger set available fro...
github_jupyter
# List, Set, and Dictionary Comprehensions In our prior session we discussed a variety of loop patterns. One of the most common patterns that we encounter in practice is the need to iterate through a list of values, transform the elements of the list using some operations, filter out the results, and return back a n...
github_jupyter
# *Circuitos Elétricos I - Semana 10* ### Problema 1 (Problema 7.19 - Nilsson) Para o circuito abaixo, pede-se: <img src="./figures/J13C1.png" width="400"> a) Determine a tensão $v_0(t)$ sobre o indutor de $48\;mH$ para $t\geq0$.\ b) Determine a corrente $i_0(t)$ sobre o indutor de $48\;mH$ para $t\geq0$.\ c) Det...
github_jupyter
___ <a href='http://www.pieriandata.com'> <img src='../../Pierian_Data_Logo.png' /></a> ___ # SF Salaries Exercise Welcome to a quick exercise for you to practice your pandas skills! We will be using the [SF Salaries Dataset](https://www.kaggle.com/kaggle/sf-salaries) from Kaggle! Just follow along and complete the...
github_jupyter
``` from __future__ import absolute_import, division, print_function, unicode_literals from IPython import display from matplotlib import pyplot as plt from scipy.ndimage.filters import gaussian_filter1d import pandas as pd import numpy as np import datetime import tensorflow as tf !rm -rf ./logs/ # Load the Tens...
github_jupyter
``` import pandas as pd df = pd.read_csv('data/small_corpus.csv') df['reviews']= df['reviews'].astype(str) from transformers import pipeline classifier = pipeline('sentiment-analysis') def classify(item): output = classifier(item)[0] label = output['label'] score = output['score'] return ','.join([label...
github_jupyter
<h1 align=center>The Cobweb Model</h1> Presentation follows <a href="http://www.parisschoolofeconomics.eu/docs/guesnerie-roger/hommes94.pdf">Hommes, <em>JEBO 1994</em></a>. Let $p_t$ denote the <em>observed price</em> of goods and $p_t^e$ the <em>expected price</em> of goods in period $t$. Similarly, let $q_t^d$ deno...
github_jupyter
# Efficient Interpolation & Exploration with STONED SELFIES ### By: AkshatKumar Nigam, Robert Pollice, Mario Krenn, Gabriel dos Passos Gomes, and Alan Aspuru-Guzik Paper Link: https://doi.org/10.26434/chemrxiv.13383266.v2 \ Paper Github: https://github.com/aspuru-guzik-group/stoned-selfies <img src="https://github...
github_jupyter
``` import pandas as pd import numpy as np log = pd.read_csv('../data/log.xls', header=None, names=['user_id', 'time', 'bet', 'win']) log.time =log.time.str.replace('[', '') log.time = pd.to_datetime(log.time) log.head() users = pd.read_csv('../data/users.xls', encoding="koi8-r", sep='\t', names=['user_id', 'email', 'g...
github_jupyter
# Band Ratios Conflations This notebook steps through how band ratio measures are underdetermined. By 'underdetermined', we mean that the same value, or same change in value between measures, can arise from different underlying causes. This shows that band ratios are a non-specific measure. As an example case, w...
github_jupyter