text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
# Introduction to Mathematical Optimization Modeling ## Objective and prerequisites The goal of this modeling example is to introduce the key components in the formulation of mixed integer programming (MIP) problems. For each component of a MIP problem formulation, we provide a description, the associated Python cod...
github_jupyter
# Comments In the previous lecture we learnt how to print "hello world". Lets try to do that again. Click on the cell below and hit the 'run' button. Go on, I'll wait for you... ``` # print("Hello World) ``` Woah !? Nothing happened!? Why is that? The reason “hello world” did not get printed to the console in thi...
github_jupyter
# Lost Luggage Distribution Problem ## Objective and Prerequisites In this example, you’ll learn how to use mathematical optimization to solve a vehicle routing problem with time windows, which involves helping a company figure out the minimum number of vans required to deliver pieces of lost or delayed baggage to t...
github_jupyter
``` #-*- coding: utf-8 -*- import re from wxpy import * import jieba import numpy import pandas as pd import matplotlib.pyplot as plt from scipy.misc import imread from wordcloud import WordCloud, ImageColorGenerator def write_txt_file(path, txt): ''' 写入txt文本 ''' with open(path, 'a', encoding='gb18030'...
github_jupyter
``` model_name= 'Burns_CNNBiLSTM' %load_ext autoreload %autoreload 2 import sys sys.path.append('../') import os import tensorflow import numpy as np import random seed_value = 123123 seed_value = None environment_name = sys.executable.split('/')[-3] print('Environment:', environment_name) os.environ[environment_na...
github_jupyter
``` import os import numpy as np import pandas as pd import statistics as st from scipy import signal import matplotlib.pyplot as plt import keras from keras.utils import to_categorical from sklearn.metrics import confusion_matrix from sklearn.metrics import confusion_matrix,classification_report data1n = [] data2n = [...
github_jupyter
Actually this is not PCA, but PCA-related questions in CS357. ``` import numpy as np import numpy.linalg as la def center_data(A): ''' Given a matrix A, we want every column to shift by their column mean ''' B = np.copy(A).astype(float) for i in range(B.shape[1]): B[:,i] -= np.mean(B[:,i]) ...
github_jupyter
# Transient Fickian Diffusion The package `OpenPNM` allows for the simulation of many transport phenomena in porous media such as Stokes flow, Fickian diffusion, advection-diffusion, transport of charged species, etc. Transient and steady-state simulations are both supported. An example of a transient Fickian diffusion...
github_jupyter
``` epochs = 50 ``` # পর্ব 7 - ফেডারেটড্যাটাসেটের সাথে ফেডারেট লার্নিং এখানে আমরা ফেডারেটেড ডেটাসেট ব্যবহারের জন্য একটি নতুন সরঞ্জাম প্রবর্তন করি। আমরা একটি "ফেডারেটড্যাটাসেট` ক্লাস তৈরি করেছি যা পাইটর্চ ডেটাসেট ক্লাসের মতো ব্যবহার করার উদ্দেশ্যে এবং এটি একটি ফেডারেশনযুক্ত ডেটা লোডার - ফেডারেটডাটাডোলোডারকে দেওয়া হয়...
github_jupyter
# records ``` import vectorbt as vbt import numpy as np import pandas as pd from numba import njit from collections import namedtuple from datetime import datetime # Disable caching for performance testing # NOTE: Expect waterfall of executions, since some attributes depend on other attributes # that have to be calcu...
github_jupyter
# Rendimiento vs. Riesgo. ¿Cómo medirlos? <img style="float: left; margin: 15px 15px 15px 15px;" src="http://www.creative-commons-images.com/clipboard/images/return-on-investment.jpg" width="300" height="100" /> <img style="float: right; margin: 15px 15px 15px 15px;" src="https://upload.wikimedia.org/wikipedia/commons...
github_jupyter
# Computational Thinking *Lesson Developer: Aaron Weeden aweeden@shodor.org* ``` # This code cell starts the necessary setup for Hour of CI lesson notebooks. # First, it enables users to hide and unhide code by producing a 'Toggle raw code' button below. # Second, it imports the hourofci package, which is necessary fo...
github_jupyter
# Developing an AI application Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall appli...
github_jupyter
``` %load_ext watermark %watermark -d -u -a 'Andreas Mueller, Kyle Kastner, Sebastian Raschka' -v -p numpy,scipy,matplotlib,scikit-learn %matplotlib inline import matplotlib.pyplot as plt import numpy as np ``` # 无监督学习(Unsupervised Learning) Part 2 -- 聚类(Clustering) 聚类是将样本组织到具有相似分组的任务,本节中,将探讨一个基本的聚类任务,针对一些合成的和真实世界的数...
github_jupyter
#Transformer ``` from google.colab import drive drive.mount('/content/drive') # informer, ARIMA, Prophet, LSTMa와는 다른 형식의 CSV를 사용한다.(Version2) !pip install pandas import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline df = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/Data/...
github_jupyter
``` %load_ext autoreload import os import sys import glob import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error, r2_score import torch import torch.nn as nn module_path = os.path....
github_jupyter
This is a collection of scratch work that i use to organize the tests for coddiwomple ``` from simtk import openmm from openmmtools.testsystems import HarmonicOscillator from coddiwomple.tests.utils import get_harmonic_testsystem from coddiwomple.tests.utils import HarmonicAlchemicalState from simtk import unit import...
github_jupyter
# ElasticNet with MinMaxScaler & Polynomial Features This Code template is for Regression tasks using a ElasticNet based on the Regression linear model Technique with MinMaxScaler and feature transformation technique Polynomial Features in a pipeline. ### Required Packages ``` import warnings as wr import numpy as n...
github_jupyter
# RadiusNeighborsClassifier with Power Transformer This Code template is for the Classification task using a simple Radius Neighbor Classifier with pipeline and PowerTransformer Feature Transformation. It implements learning based on the number of neighbors within a fixed radius r of each training point, where r is a ...
github_jupyter
## 10.1 添加程序源代码 很多时候,在技术文档中添加程序源代码具有一定的必要性,这源于: - 在很多文档(如实验报告)中,程序源代码往往作为重要组成部分,必须作为辅助材料放在文档末尾的附录中。 - 程序源代码既可以直接展现计算机编程的实现过程和细节,又可以评估实验的真实性,同时也能供读者学习和使用。 事实上,使用LaTeX制作文档时,添加程序源代码是一件看似简单、但又比较考验技巧的事,因为在文档中添加程序源代码并不能通过简单的“复制+粘贴”来实现。我们需要保持代码在原来程序语言中的格式,包括代码所采用的高亮颜色和等宽字体,目的都是为了让代码本来的面貌得以完美展现。 在LaTeX中,有很多宏包可供制作文档时添加程序源代码...
github_jupyter
# EASY pilot study downloads This notebook can be used to download the data associated with the "EASY Study - 75 Image, full featureset" study on the ISIC archive available here: https://isic-archive.com/api/v1/#!/study/study_find And from there we can see that this study has the (mongodb Object) ID "58d9189ad8311337...
github_jupyter
<a href="https://githubtocolab.com/giswqs/geemap/blob/master/examples/notebooks/28_voila.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab"/></a> Uncomment the following line to install [geemap](https://geemap.org) if needed. ``` # !pip install geemap ``` ...
github_jupyter
# **Classification of iris varieties within the same species** ## Introduction The aim of this Notebook is to use AI TRAINING product to train a simple model, on the Iris dataset, with the PyTorch library. It is an exemple of neural network for data classification ## Code The neural network will be set up in differ...
github_jupyter
``` # Copyright 2021 Google LLC # Use of this source code is governed by an MIT-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/MIT. # Notebook authors: Kevin P. Murphy (murphyk@gmail.com) # and Mahmoud Soliman (mjs@aucegypt.edu) # This notebook reproduces figures for chap...
github_jupyter
# Parametric Dynamic Mode Decomposition In this tutorial we explore the usage of the class `pydmd.ParametricDMD`, which is implemented following the work presented in [arXiv:2110.09155](https://arxiv.org/pdf/2110.09155.pdf) (Andreuzzi, Demo, Rozza. _A dynamic mode decomposition extension for the forecasting of paramet...
github_jupyter
# LogisticRegression with StandardScaler & Polynomial Features This Code template is for the Classification task using the LogisticRegression with StandardScaler feature scaling technique and PolynomialFeatures as Feature Transformation Technique in a pipeline. ### Required Packages ``` !pip install imblearn --q imp...
github_jupyter
The objective of this experiment is to learn words with similar or different meanings are equally apart in BoW and semantics or Meaning of the word is preserved in W2V In this experiment we will be using a huge dataset named as 20 news classification dataset. This data set consists of 20000 messages taken from 20 news...
github_jupyter
## Computer vision data ``` %matplotlib inline from fastai.gen_doc.nbdoc import * from fastai.vision import * ``` This module contains the classes that define datasets handling [`Image`](/vision.image.html#Image) objects and their transformations. As usual, we'll start with a quick overview, before we get in to the d...
github_jupyter
``` %matplotlib inline ``` ============================= Model Surface Output ============================= Plot an surface map with mean sea level pressure (MSLP), 2m Temperature (F), and Wind Barbs (kt). Imports ``` from datetime import datetime import cartopy.crs as ccrs import cartopy.feature as cfeature impor...
github_jupyter
Collect stock and option data, price with BSM, compare accuracy ``` import pandas as pd from math import sqrt import numpy as np from scipy.stats import norm import seaborn as sns from datetime import datetime, timezone, timedelta # initial parameters ticker = 'GOOG' risk_free_rate = 0.08 option_type = 'put' # 2 ...
github_jupyter
<img src='./img/LogoWekeo_Copernicus_RGB_0.png' alt='Logo EU Copernicus EUMETSAT' align='right' width='20%'></img> <br> <a href="./00_index.ipynb"><< Index</a><br> <a href="./10_sentinel5p_L2_retrieve.ipynb"><< 10 - Sentinel-5P Carbon Monoxide - Retrieve</a><span style="float:right;"><a href="./20_sentinel3_OLCI_L1_r...
github_jupyter
### SVD Estimation For this example a square matrix of size 2 operates on a dense set of unit vectors distributed uniformly around a unit circle. The resulting set of vectors is searched for maximum and minimum lengths to find an estimate of the singular values of the matrix. ####Note This example is also available in...
github_jupyter
``` import sys import os from IPython.display import Image os.getcwd() sys.path.append('Your path to Snowmodel') # insert path to Snowmodel import numpy as np from model import * sys.path ``` #### Initialize model geometry In set_up_model_geometry you can choose several intial geometries via *geom* that are described ...
github_jupyter
# Large, three-generation CEPH families reveal post-zygotic mosaicism and variability in germline mutation accumulation ### Thomas A. Sasani, Brent S. Pedersen, Ziyue Gao, Lisa M. Baird, Molly Przeworski, Lynn B. Jorde, Aaron R. Quinlan ### Read in files containing DNMs identified in the second and third generations,...
github_jupyter
<a href="https://colab.research.google.com/github/diogojorgebasso/bootcamp-python-igti/blob/main/modulo1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Anotações preciosas do Módulo I - curso IGTI. Fundamentos do Python Import files in Google Co...
github_jupyter
# 2A.eco - Mise en pratique des séances 1 et 2 - Utilisation de pandas et visualisation - correction Correction d'un exercice sur la manipulation des données. ``` from jyquickhelper import add_notebook_menu add_notebook_menu() from pyensae.datasource import download_data files = download_data("td2a_eco_exercices_de_m...
github_jupyter
# Visualizing COVID-19 Data at the State and County Levels in Python ## Part I: Downloading and Organizing Data From casual observation, I surmise that the widespread stay-at-home orders initiated in March 2020 have left data scientists with a bit of extra time as, with each passing week, I find new sources for COVID-...
github_jupyter
``` # LSTM for international airline passengers problem with window regression framing import numpy import keras import matplotlib.pyplot as plt from pandas import read_csv import math from keras.models import Sequential from keras.layers import Dense,Dropout from keras.layers import LSTM from sklearn.preprocessing imp...
github_jupyter
# Map Benign Mutations to 3D Structure This notebook maps a dataset of 63,197 missense mutations with allele frequencies >=1% and <25% extracted from the ExAC database to 3D structures in the Protein Data Bank. The dataset is described in: [1] Niroula A, Vihinen M (2019) How good are pathogenicity predictors in d...
github_jupyter
## NumPy for Performance ### NumPy constructors We saw previously that NumPy's core type is the `ndarray`, or N-Dimensional Array: ``` import numpy as np np.zeros([3, 4, 2, 5])[2, :, :, 1] ``` The real magic of numpy arrays is that most python operations are applied, quickly, on an elementwise basis: ``` x = np.ar...
github_jupyter
``` pip install BeautifulSoup4 pip install selenium pip install pandas_datareader pip install pandas pip install webdriver_manager !apt install chromium-chromedriver import os # declare a directory name dir_name= os.getcwd()+'/sentiment-data/' import pandas as pd hkex_files=os.path.join(dir_name,'stock_ticker_data...
github_jupyter
``` import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd %matplotlib inline from matplotlib import rc, font_manager ticks_font = font_manager.FontProperties(family='serif', style='normal', size=24, weight='normal', stretch='normal') imp...
github_jupyter
# Landscape Expansion Index More details on the wiki - https://github.com/worldbank/GOST_Urban/wiki/Landscape-Expansion-Index ``` import os, sys, logging, importlib import geojson, rasterio import rasterio.features import geopandas as gpd import pandas as pd import numpy as np from shapely.geometry import shape, G...
github_jupyter
# This is an even easier demo This demo is designed only just for showing how to use the pretrained model, nothing else. ``` import torch import torchvision from torchvision import transforms transform = transforms.Compose([ transforms.Resize(( 224,224)), transforms.ToTensor() ] ) class CarMakeMo...
github_jupyter
# Hello, TensorFlow ## A beginner-level, getting started, basic introduction to TensorFlow TensorFlow is a general-purpose system for graph-based computation. A typical use is machine learning. In this notebook, we'll introduce the basic concepts of TensorFlow using some simple examples. TensorFlow gets its name from...
github_jupyter
``` from __future__ import division import os import urllib, cStringIO import pymongo as pm import numpy as np import scipy.stats as stats import pandas as pd import json import re from PIL import Image import base64 import sys import matplotlib from matplotlib import pylab, mlab, pyplot %matplotlib inline from IP...
github_jupyter
## UCI Adult Data Set ### Dataset URL: https://archive.ics.uci.edu/ml/datasets/adult Predict whether income exceeds $50K/yr based on census data. Also known as "Census Income" dataset. ``` import shutil import math from datetime import datetime import multiprocessing import pandas as pd import numpy as np import te...
github_jupyter
``` import pandas as pd from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score, confusion_matrix data_dir = '../data/' out_dir = '../data/output/' annotated_out_dir = '../data/output/annotated_output/' output_validation_data = pd.read_excel(data_dir + 'DrugVisData - All Annotations V2.xlsx...
github_jupyter
``` import sys, os, glob, warnings, logging import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt import seaborn as sns from scipy import stats from sw_plotting import change_bar_width, plotCountBar from sw_utilities import tukeyTest # logging.basicConfig(stream=sys.stdout, format='%...
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import numpy as np from scipy.spatial import distance from sklearn.tree import DecisionTreeClassifier d_tree = DecisionTre...
github_jupyter
# Chernoff Faces, Deep Learning In this notebook, we use convolutional neural networks (CNNs) to classify the Chernoff faces generated from [chernoff-faces.ipynb](chernoff-faces.ipynb). We want to see if framing a numerical problem as an image problem and using CNNs to classify the data (images) would be a promising a...
github_jupyter
<a href="https://colab.research.google.com/github/njaramillov07/MDigital/blob/main/Clase2%2005_08_21.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> **Operadores Aritmeticos** --- Los operadores permiten realizar diferentes procesos de calculo e...
github_jupyter
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import random import math import json from torch.autograd import Variable from torch.distributions import Categorical from utils.qf_data import normal...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import scipy.interpolate ``` # Интерполяция многочленами Допустим мы знаем значения $f_k=f(x_k)$ некоторой функции $f(x)$ только на некотором множестве аргументов $x_k\in\mathbb R$, $k=1..K$. Мы хотим вычислять $f$ в точках $x$ лежащих между узлами интерполяции $...
github_jupyter
# <p style="text-align: center;">Clusterização e algoritmo K-means</p> Organizar dados em agrupamentos é um dos modos mais fundamentais de compreensão e aprendizado. Como por exemplo, os organismos em um sistema biologico são classificados em domínio, reino, filo, classe, etc. A análise de agrupamento é o estudo form...
github_jupyter
## Regression Inference and OLS Asymptotics In this notebook, we are going to study and demonstrate the use of *Python* to perform **statistical inference** to test our regression models. We are also going to explore the **Asymptotic Theory** and understand how it allows us to relax some assumptions needed to derive t...
github_jupyter
# Benchmarking cell2location pyro model using softplus/exp for scales using 5x larger data ``` import sys, ast, os import scanpy as sc import anndata import pandas as pd import numpy as np import os import matplotlib.pyplot as plt import matplotlib as mpl data_type='float32' import cell2location_model from matplot...
github_jupyter
### Introduction to K-Nearest Neighbors (KNN) The K-Nearest Neighbors (KNN) algorithm is very simple and very effective.The k-Nearest Neighbors (kNN) algorithm is arguably the simplest machine learning algorithm. Building the model only consists of storing the training dataset. #### Making Predictions with KNN KNN m...
github_jupyter
# Bis438 Final Project Problem 2 ## Import Python Libraries ``` import numpy as np import deepchem as dc from MPP.model import GCN, MLP from MPP.utils import process_prediction, make_feature, split_data ``` ## Build GraphConv Model ``` batch_size = 50 gcn_model = GCN(batch_size=batch_size) # build model ``` ## Tr...
github_jupyter
``` import numpy as np from tensorflow import keras import matplotlib.pyplot as plt import os import cv2 import random import sklearn.model_selection as model_selection import datetime from model import createModel from contextlib import redirect_stdout from tensorflow.keras import layers import tensorflow as tf polic...
github_jupyter
``` # default_exp utils.clusterization ! pip install pyclustering ``` ## clusterization ``` #export import logging import sentencepiece as sp from pyclustering.cluster.kmedoids import kmedoids from pyclustering.utils.metric import euclidean_distance_square, euclidean_distance from pyclustering.cluster.silhouette i...
github_jupyter
``` // #r ".\binaries2\bossspad.dll" // #r ".\binaries2\XNSEC.dll" // #r "C:\BoSSS_Binaries\bossspad.dll" // #r "C:\BoSSS_Binaries\XNSEC.dll" #r "C:\BoSSS\experimental\public\src\L4-application\BoSSSpad\bin\Release\net5.0\bossspad.dll" #r "C:\BoSSS\experimental\public\src\L4-application\BoSSSpad\bin\Release\net5.0...
github_jupyter
# Ames Housing Prices - Step 4: Modeling We are now ready to begin building our regression model to predict prices. This notebook demonstrates how to use the previous work (cleaning, feature prep) to quickly build up the engineered features we need to train our ML model. ``` # Basic setup %run config.ipynb # Connect ...
github_jupyter
``` import SimPEG as simpeg import simpegMT as simpegmt import numpy as np, os import matplotlib.pyplot as plt ## Setup the modelling # Setting up 1D mesh and conductivity models to forward model data. # Frequency nFreq = 31 freqs = np.logspace(3,-3,nFreq) # Set mesh parameters ct = 20 air = simpeg.Utils.meshTensor([(...
github_jupyter
# Receiver Operating Characteristic (ROC) with cross validation on Iris In this notebook we find an example of Receiver Operating Characteristic (ROC) Curves. An ROC curve represents the discriminative ability of a binary classification in a graphical plot. In an ROC curve the true positive rate of the binary classif...
github_jupyter
# Neural networks with PyTorch Deep learning networks tend to be massive with dozens or hundreds of layers, that's where the term "deep" comes from. You can build one of these deep networks using only weight matrices as we did in the previous notebook, but in general it's very cumbersome and difficult to implement. Py...
github_jupyter
<a href="https://colab.research.google.com/github/dcshapiro/AI-Feynman/blob/master/AI_Feynman_2_0.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # AI Feynman 2.0: Learning Regression Equations From Data ### Clone repository and install dependencie...
github_jupyter
## AI for Medicine Course 1 Week 1 lecture exercises # Data Exploration In the first assignment of this course, you will work with chest x-ray images taken from the public [ChestX-ray8 dataset](https://arxiv.org/abs/1705.02315). In this notebook, you'll get a chance to explore this dataset and familiarize yourself wit...
github_jupyter
``` !nvidia-smi ``` # **Intro to Generative Adversarial Networks (GANs)** Generative adversarial networks (GANs) are algorithmic architectures that use two neural networks, compitting one against the other (thus the “adversarial”) in order to generate new, synthetic instances of data that can pass for real data. They...
github_jupyter
# Iris Training and Prediction with Sagemaker Scikit-learn ### Modified Version of AWS Example: https://github.com/awslabs/amazon-sagemaker-examples/blob/master/sagemaker-python-sdk/scikit_learn_iris/Scikit-learn%20Estimator%20Example%20With%20Batch%20Transform.ipynb Following modifications were made: 1. Incorpora...
github_jupyter
``` %matplotlib inline from pyvista import set_plot_theme set_plot_theme('document') pyvista._wrappers['vtkPolyData'] = pyvista.PolyData ``` Load data using a Reader {#reader_example} ======================== To have more control over reading data files, use a class based reader. This class allows for more fine-grain...
github_jupyter
# Quantum State Tomography (Unsupervised Learning) Quantum state tomography (QST) is a machine learning task which aims to reconstruct the full quantum state from measurement results. __Aim__: Given a variational ansatz $\Psi(\lbrace \boldsymbol{\beta} \rbrace)$ and a set of measurement results, we want to find the p...
github_jupyter
# Visualization We use dpi=300 to genrate the plots in the paper. But for an easy viewing purpose here, we use dpi = 50. ``` DPI = 50 ``` ## Figure 1(b)-(f): Data Statisctics ``` import os import numpy as np import random import pandas as pd from sklearn import metrics from operator import itemgetter import json i...
github_jupyter
## Result Visualizations with Comparison Analysis ### CHAPTER 02 - *Model Explainability Methods* From **Applied Machine Learning Explainability Techniques** by [**Aditya Bhattacharya**](https://www.linkedin.com/in/aditya-bhattacharya-b59155b6/), published by **Packt** ### Objective In this notebook, we will try to ...
github_jupyter
# TSG013 - Show file list in Storage Pool (HDFS) ## Steps ### Parameters ``` path = "/" ``` ### Common functions Define helper functions used in this notebook. ``` # Define `run` function for transient fault handling, suggestions on error, and scrolling updates on Windows import sys import os import re import pla...
github_jupyter
# Novel Fraud Analysis We show that hybrid model with exploration detects novel frauds better (e.g., trades from new HS6 and new import ID) ``` import numpy as np import pandas as pd import glob import csv import traceback import datetime import os pd.options.display.max_columns=50 ``` ### Basic statistics and Novel...
github_jupyter
# Huggingface Sagemaker-sdk - Spot instances example ### Binary Classification with `Trainer` and `imdb` dataset 1. [Introduction](#Introduction) 2. [Development Environment and Permissions](#Development-Environment-and-Permissions) 1. [Installation](#Installation) 2. [Development environment](#Development...
github_jupyter
# Example: CanvasXpress nonlinearfit Chart No. 1 This example page demonstrates how to, using the Python package, create a chart that matches the CanvasXpress online example located at: https://www.canvasxpress.org/examples/nonlinearfit-1.html This example is generated using the reproducible JSON obtained from the a...
github_jupyter
#**SVM** ``` import numpy as np import matplotlib.pyplot as plt import random from numpy import linalg as LA ``` --- **Generating Random linearly separable data** --- ``` data = [[np.random.rand(), np.random.rand()] for i in range(10)] for i, point in enumerate(data): x, y = point if 0.5*x - y + 0.25 > 0:...
github_jupyter
# GPs with boundary conditions In the paper entitled '' (https://export.arxiv.org/pdf/2002.00818), the author claims that a GP can be constrained to match boundary conditions. Consider a GP prior with covariance kernel $$k_F(x,y) = \exp\left(-\frac{1}{2}(x-y)^2\right)$$ Try and match the boundary conditions: $$f(0) =...
github_jupyter
# Import Dataset, Split X,Y ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import pickle trainDF = pd.read_csv('E:/Sem5/ML-Final-Project/Dataset/train.csv', low_memory=False) valDF = pd.read_csv('E:/Sem5/ML-Final-Project/Dataset/val.csv', low_memory=False) testDF = pd.read_csv('E:/Sem5/ML-F...
github_jupyter
``` import os import itertools import pathlib import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from torch.utils.data import ConcatDataset PROJECT_DIR = os.path.dirname(os.getcwd()) if PROJECT_DIR not in sys.path: sys.path.insert(0, PROJECT_DIR) from chord_re...
github_jupyter
# Лабораторная работа 1. Алгоритмы на графах. ``` import networkx as nx import pylab import matplotlib.pyplot as plt ``` Пусть задан граф множеством смежности: ``` pos = {0: {1, 2}, 1: {3, 4}, 2: {1, 4}, 3: {4}, 4: {1, 3, 5}, 5: {0, 2}} ``` Создадим соответствующий [направленный г...
github_jupyter
# Knapsack With Integer Weights問題 各々重さ$(w_\alpha \geq 0)$と価値$(c_\alpha \geq 0)$の決まったN個のアイテムがあり、そのうちのいくつかをナップサックに入れるとき、総重量$ \displaystyle W(= \sum _ {\alpha = 1} ^ {N} w_{\alpha}x_{\alpha})$をある決められた値$W_{limit}$以下に抑えながら、価値の合計$ \displaystyle C(= \sum _ {\alpha = 1} ^ {N} c_{\alpha}x_{\alpha})$を最大化するような入れ方を探す問題をナップサック問題とい...
github_jupyter
# Import Libraries and Dataset ``` # Importing Libraries import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split, GridSearchCV from sk...
github_jupyter
# Lesson 2 Exercise 2: Creating Denormalized Tables <img src="images/postgresSQLlogo.png" width="250" height="250"> ## Walk through the basics of modeling data from normalized from to denormalized form. We will create tables in PostgreSQL, insert rows of data, and do simple JOIN SQL queries to show how these multiple...
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
``` import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics.pairwise import cosine_similarity df = pd.read_csv("complete_course_data.csv") df.head() df features = ["course_title","platform","level"] def combine_features(row): return row['course_title']...
github_jupyter
# Importing the libraries ``` %matplotlib inline import IPython.display as ipd import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix, roc_curve, auc from sklearn.model_selection import train_test_split, ...
github_jupyter
# Chapter 4 ## 4.2.1 均方誤差 (Mean Squared Error) ``` # 均方根函數 import numpy as np # y為預測輸出,t為正確答案 def mean_squared_error(y, t): return 0.5 * np.sum((y-t)**2) # 假設正確答案為"2" t = [0,0,1,0,0,0,0,0,0,0] # 例一:"2"的機率為最高時(0.6) y = [0.1,0.05,0.6,0.0,0.05,0.1,0.0,0.1,0.0,0.0] print('Example 1 - MSE: ', mean_squared_error(np....
github_jupyter
# Image loading and generation notebook ## Notebook setup ``` # noqa import os COLAB = 'DATALAB_DEBUG' in os.environ if COLAB: !apt-get update !apt-get install git !git clone https://gist.github.com/oskopek/e27ca34cb2b813cae614520e8374e741 bstrap import bstrap.bootstrap as bootstrap else: wd = %%...
github_jupyter
# Learning Rate and Convergence of stochastic gradient descent algorihtm (SGD) for a simple linear model This exercise is based on the tensorflow [playground](https://playground.tensorflow.org) program (developed by google to teach machine learning principles). You'll experiment with learning rate by performing two ta...
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
# Train faster, more flexible models with Amazon SageMaker Linear Learner Today Amazon SageMaker is launching several additional features to the built-in linear learner algorithm. Amazon SageMaker algorithms are designed to scale effortlessly to massive datasets and take advantage of the latest hardware optimizations...
github_jupyter
<a href="https://colab.research.google.com/github/Shantanu9326/Banking-Marketing-Campaign-with-Spark/blob/master/Banking_Marketing_Campaign_with_pySpark.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # SIT742: Modern Data Science **(Assessment Tas...
github_jupyter
``` import re import os import random import itertools import numpy as np import pandas as pd import seaborn as sns import tensorflow as tf from sklearn import metrics from tensorflow import keras from sklearn.ensemble import RandomForestClassifier from tensorflow.keras import backend as K import matplotlib.pyplot as p...
github_jupyter
# Getting Started with SYMPAIS [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ethanluoyc/sympais/blob/master/notebooks/getting_started.ipynb) ## Setup ``` try: import google.colab IN_COLAB = True except: IN_COLAB = False ``` ### Install SYM...
github_jupyter
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. ### Agent Testing - Single Job Set In this notebook we test the performance of the agent trained with a single job set. We can then compare its performance to the random and shortest-job-first agents in the exploration noteboo...
github_jupyter
# Create a Learner for inference ``` from fastai.gen_doc.nbdoc import * ``` In this tutorial, we'll see how the same API allows you to create an empty [`DataBunch`](/basic_data.html#DataBunch) for a [`Learner`](/basic_train.html#Learner) at inference time (once you have trained your model) and how to call the `predic...
github_jupyter
``` import numpy as np import numpy.random as npr from sklearn.linear_model import LinearRegression, Ridge from sklearn.decomposition import PCA import statsmodels.api as sm from numpy.linalg import cond N=2000 D=5 # number of features mean = np.zeros(D) corr = 0.9 y_noise = 0.1 # designate the core feature num_coref...
github_jupyter