text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
``` #!pip3 install sklearn from sklearn.datasets import make_classification from sklearn.calibration import CalibratedClassifierCV from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score, brier_score_loss from sklearn.preprocessi...
github_jupyter
# RecipeClassification ## Identifying Which feature is best to classify Recipe Dataset ### Importing necessary libraries ###### The following code is written in Python 3.x. Libraries provide pre-written functionally to perform necessary tasks ``` import pandas as pd import numpy as np import matplotlib.pyplot as pl...
github_jupyter
# Model zoo ``` import torch import numpy as np import tensorflow as tf ``` ## Generate toy data ``` def generate_data(n=16, samples_per_class=1000): """ Generate some classification data Args: n (int): square root of the number of features. samples_per_class (int): number of samples...
github_jupyter
``` pip install ekphrasis pip install transformers import pandas as pd import os import numpy as np import torch import random import functools import operator import cv2 import seaborn as sns import matplotlib.pyplot as plt from torch import nn, optim from torch.utils.data import TensorDataset, DataLoader, Dataset, ...
github_jupyter
``` import numpy as np import numba import matplotlib.pyplot as plt import scipy.optimize as sopt from pysimu import ode2numba, ssa from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets %matplotlib notebook import freq2 syst = freq2.freq2_class() syst.struct[0].p_load = 0.1 s...
github_jupyter
# Running delay filter, followed by xrfi ``` %matplotlib inline import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors import os from hera_cal.delay_filter import DelayFilter from hera_cal.data import DATA_PATH from pyuvdata import UVData import shutil from hera_qm import xrfi from hera_...
github_jupyter
# 4. Indexing, slicing Each element of an array can be located by its position in each dimension. Numpy offers multiple ways to access single elements or groups of elements in very efficient ways. We will illustrate these concepts both with small simple matrices as well as a regular image, in order to illustrate them....
github_jupyter
So far, you have worked with datasets that we have provided for you. In this tutorial, you'll learn how to use your own datasets. Then, in the following exercise, you'll design and create your own data visualizations. You'll learn all about Kaggle Datasets, a tool that you can use to store your own datasets and quic...
github_jupyter
## Load necessary modules ``` # show images inline %matplotlib inline # automatically reload modules when they have changed %load_ext autoreload %autoreload 2 # import keras import keras # import keras_retinanet from keras_retinanet import models from keras_retinanet.utils.image import read_image_bgr, preprocess_im...
github_jupyter
## Background Information In a Stroop task, participants are presented with a list of words, with each word displayed in a color of ink. The participant’s task is to say out loud the color of the ink in which the word is printed. The task has two conditions: a congruent words condition, and an incongruent words conditi...
github_jupyter
# Read in the data ``` import pandas as pd import numpy import re data_files = [ "ap_2010.csv", "class_size.csv", "demographics.csv", "graduation.csv", "hs_directory.csv", "sat_results.csv" ] data = {} for f in data_files: d = pd.read_csv("schools/{0}".format(f)) data[f.replace(".csv...
github_jupyter
# Mémo concernant les images dans un Jupyter NoteBook : ![JupyterNoteBook.png](attachment:JupyterNoteBook.png) ## En Markdown : L'image ci-dessus correspont au code markdown : `![JupyterNoteBook.png](attachment:JupyterNoteBook.png)` ### Images intégrées : Il est possible d’insérer une image dans une cellule Markdo...
github_jupyter
Borrowed from [Rebecca Weiss](https://stanford.edu/~rjweiss/public_html/IRiSS2013/text2/notebooks/tfidf.html) ``` import numpy as np ``` ## Basic term frequencies First, let's review how to get a count of terms per document: a term frequency vector. ``` #examples taken from here: http://stackoverflow.com/a/1750187 ...
github_jupyter
``` import os, sys import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import sklearn as skl ``` ## Read data files ``` datasetA = [] features = None for file in os.listdir('../../sepsis_data/trainingA/'): # Read file with open('../../sepsis_data/trainingA/%s' % (fi...
github_jupyter
# Point Processes **Author: Serge Rey <sjsrey@gmail.com> and Wei Kang <weikang9009@gmail.com>** ## Introduction One philosophy of applying inferential statistics to spatial data is to think in terms of spatial processes and their possible realizations. In this view, an observed map pattern is one of the possible pat...
github_jupyter
## Programming Language : Python <img align='left' src='https://github.com/harveenchadha/Breast_Cancer_Prediction/blob/master/images/python.jpeg?raw=1' > ## Problem Statement Breast cancer (BC) is one of the most common cancers among women worldwide, representing the majority of new cancer cases and cancer-related d...
github_jupyter
# Cows supplychain network Table of Contents: 1. [Network analysis - Part1](#network-analysis---part1) - [Get network properties](#get-network-properties) - [Log-log Plot](#log-log-plot) - [Judge network](#judge-network) 2. [Network analysis - Part2](#network-analysis---part2) - [Network centrality proper...
github_jupyter
<table class="ee-notebook-buttons" align="left"> <td><a target="_parent" href="https://github.com/giswqs/geemap/tree/master/tutorials/ImageCollection/03_filtering_image_collection.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target...
github_jupyter
<a href="https://colab.research.google.com/github/raqueeb/TensorFlow2/blob/master/scratch_model_weight_changes_affect_accuracy.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import numpy as np # আমাদের প্রেডিকশন করার জন্য ডেটা পয়েন্ট, ছবির সাথ...
github_jupyter
``` from IPython.core.display import HTML HTML(open("custom.css", "r").read()) ``` <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#From-Transistors-to-ALUs-With-Skywater" data-toc-modified-id="From-Transistors-to-ALUs-With-Skywater-1">From Transistors t...
github_jupyter
# Setup ``` import os from google.colab import drive as gdrive # @markdown Setup output directory for the models OUTPUT_DIR = 'Colab/varname/' # @param {type:'string'} SAVE_ON_GDRIVE = False # @param {type:'boolean'} if SAVE_ON_GDRIVE: GDRIVE_ROOT = os.path.abspath('gdrive') GDRIVE_OUT = os.path.join(GDRIVE_ROO...
github_jupyter
``` %matplotlib inline import pandas as pd import geopandas as gpd import libpysal as lp import esda import numpy as np import matplotlib.pyplot as plt ``` # Case Study: *Gini in a bottle: Income Inequality and the Trump Vote* #### Read in the table and show the first three rows ``` # %load _solved/solutions/case-t...
github_jupyter
This notebook is part of the *orix* documentation https://orix.readthedocs.io. Links to the documentation won’t work from the notebook. # Visualizing Crystal Poles in the Pole Density Function This notebook demonstrates how to quantify the distribution of crystallographic poles, which is useful, for example, in textu...
github_jupyter
``` from qiskit.ml.datasets import * from qiskit import QuantumCircuit from qiskit.aqua.components.optimizers import COBYLA, ADAM, SPSA, SLSQP, POWELL, L_BFGS_B, TNC, AQGD from qiskit.circuit.library import ZZFeatureMap, RealAmplitudes from qiskit.quantum_info import Statevector import numpy as np import pandas as pd ...
github_jupyter
### Prerequisites You should have completed steps 1-3 of this tutorial before beginning this exercise. The files required for this notebook are generated by those previous steps. This notebook takes approximately 3 hours to run on an AWS `p3.8xlarge` instance. ``` # # Optional: you can set what GPU you want to use ...
github_jupyter
# Regular Expressions Regular expressions are text-matching patterns described with a formal syntax. You'll often hear regular expressions referred to as 'regex' or 'regexp' in conversation. Regular expressions can include a variety of rules, from finding repetition, to text-matching, and much more. As you advance in ...
github_jupyter
# Encoding of categorical variables In this notebook, we will present typical ways of dealing with **categorical variables** by encoding them, namely **ordinal encoding** and **one-hot encoding**. Let's first load the entire adult dataset containing both numerical and categorical data. ``` import pandas as pd adult...
github_jupyter
``` import matplotlib import numpy as np import matplotlib.pyplot as plt import sys, collections, os, argparse %matplotlib inline ``` # Download the 10x Dataset `1k Brain Cells from an E18 Mouse (v3 chemistry)` 10x datasets are available at https://support.10xgenomics.com/single-cell-gene-expression/datasets The pag...
github_jupyter
This is a technical description of banded ridge regression (see [Nunez-Elizalde, et al., 2019](https://doi.org/10.1016/j.neuroimage.2019.04.012)) ``` %matplotlib inline import matplotlib matplotlib.rcParams['figure.figsize'] = [7., 7.] matplotlib.rcParams['font.size'] = 15 import os import time import numpy as np np....
github_jupyter
![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true) <a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Science/HeatAndTemperature/heat-and-tem...
github_jupyter
# Loads the mechanical Turk data Run this script to load the data. Your job after loading the data is to make a 20 questions style game (see www.20q.net ) ## Read in the list of movies There were 250 movies in the list, but we only used the 149 movies that were made in 1980 or later ``` # Read in the list of 250 movi...
github_jupyter
# Conditional Statements ## If if "condition": > "do something" print() ``` num = int(input("Please enter a number: ")) if num < 0: num *= -1 #num = num*-1 print("Result: ", num) ``` # If-Else if "condition": > "do something" else: > "do something another" print() # If-Elif-Else if "cond...
github_jupyter
## Identifiability Test of Linear VAE on KittiMask Dataset ``` %load_ext autoreload %autoreload 2 import torch import torch.nn.functional as F from torch.utils.data import DataLoader, random_split import ltcl import numpy as np import scipy from ltcl.datasets.kitti import KittiMasks, KittiMasksTwoSample from ltcl.modu...
github_jupyter
___ <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> ___ # Part of Speech Basics The challenge of correctly identifying parts of speech is summed up nicely in the [spaCy docs](https://spacy.io/usage/linguistic-features): <div class="alert alert-info" style="margin: 20px">Processing raw...
github_jupyter
# Load data ``` %load_ext autoreload %autoreload 2 import numpy as np import matplotlib.pyplot as plt np.set_printoptions(precision=3, linewidth=120) import sys sys.path.append("..") from scem import ebm, stein, kernel, util, gen from scem.datasets import * import matplotlib.pyplot as plt from tqdm import notebook as ...
github_jupyter
<i>Copyright (c) Microsoft Corporation. All rights reserved.</i> <i>Licensed under the MIT License.</i> # Data transformation (collaborative filtering) It is usually observed in the real-world datasets that users may have different types of interactions with items. In addition, same types of interactions (e.g., clic...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import pandas as pd %matplotlib inline from sklearn.model_selection import train_test_split dataset = pd.read_csv('Churn_Modelling.csv') d_X = dataset.iloc[:, 3:13] d_y = dataset.iloc[:, 13] d_X = pd.get_dummies(d_X) d_X.drop(['Geography_France', 'Gender_Female'],...
github_jupyter
``` import heapq class Solution: def minEatingSpeed(self, piles, H: int) -> int: total_sum = sum(piles) left, right = 1, max(piles) + 1 min_speed = float('inf') while left < right: mid = left + (right - left) // 2 eat_sum = speed * H if eat_sum >=...
github_jupyter
``` # Cloning the github branch in the '/content/' directory. # installing the highway-env package. !pip install git+https://github.com/eleurent/highway-env.git --quiet # Cloning the github branch in the '/content/' directory. # installing the finite-mdp package. !pip install git+https://github.com/eleurent/finite-mdp...
github_jupyter
# Emission AI #### Microsoft AI for Earth Project AI Monitoring Coal-fired Power Plant Emission from Space #### Team Members Ziheng Sun, Ahmed Alnaim, Zack Chester, Daniel Tong #### Date 4/30/2020-10/30/2021 #### Abstract The goal is to build a reusable machine learning model to estimate the emission of coal-fired po...
github_jupyter
``` import tree.ctutils as ctu from tree import treeutils import numpy as np import pickle # Calculate merger event parameters def find_merger(atree, idx=None, aexp_min=0.0): """ find indices of merger event from a tree. (Full tree or main progenitor trunk) """ if idx == None: idx =...
github_jupyter
``` from google.colab import drive drive.mount('/content/drive') !pip install thop import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import torch.optim as optim import torch.backends.cudnn as cudnn import math import time import torch.nn.init as init import csv import shu...
github_jupyter
# CGC API Quickstart This Guide leads you through a simple RNA sequencing analysis which parallels the GUI Quickstart using the CGC API. We have written this example in Python, but the concepts can be adapted to your preferred programming language. We encourage you to try this analysis yourself ## Set project name, a...
github_jupyter
# Flow analysis This notebook reproduces plots that appear in Figs 6 and 8 of the paper: - Gilson M, Zamora-López G, Pallarés V, Adhikari MH, Senden M, Tauste Campo A, Mantini D, Corbetta M, Deco G, Insabato A (submitted) "Model-based whole-brain effective connectivity to study distributed cognition in health and dise...
github_jupyter
In this kernel, i will help you speed up your preprocessing at: 1. replace text in `question_text`: replace the text in the dict, e.g.: x = x.replace("?", " ? ") 2. load embeddings There is a quick report about the kernel. If you want to see the details, follow the codes :) | No | Category | Ty...
github_jupyter
# Get Data ``` # Get data from Github import numpy as np from math import sqrt from sklearn.metrics import mean_squared_error import pandas as pd url = 'https://raw.githubusercontent.com/raghav7203/covid19-raw-data/master/28AugCSVs/confirmed28Aug.csv?token=ALQ7JJRH3WVGQHDY3LCIWVK7KT2DO' confirmed = pd.read_csv(url, er...
github_jupyter
``` # Adds link to the scripts folder import sys import os sys.path.append("../../scripts/") import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import numpy as np from trajectory import Trajectory, load_trajectory_dict from hivevo.patients import Patient import filenames import copy from activity i...
github_jupyter
# Objects and Data Structures Assessment Test ## Test your knowledge. ** Answer the following questions ** Write a brief description of all the following Object Types and Data Structures we've learned about: **For the full answers, review the Jupyter notebook introductions of each topic!** [Numbers](http://nbview...
github_jupyter
# What is Quantum? ``` # This code is to create the interactive figure from bokeh.events import ButtonClick from bokeh.layouts import row, column from bokeh.models import ColumnDataSource, CustomJS, Button, Slider, DataRange1d, LabelSet, RadioButtonGroup, Div from bokeh.plotting import figure from bokeh.embed import f...
github_jupyter
# 1 - Predicting Salaries from Stack Overflow Surveys Stack Overflow has been conducting [annual user surveys](https://insights.stackoverflow.com/survey/?utm_source=so-owned&utm_medium=blog&utm_campaign=dev-survey-2017&utm_content=blog-link&utm_term=data) starting in 2011. Yes, this is the same survey that (re)started ...
github_jupyter
``` import pandas as pd import numpy as np from scipy import stats from statsmodels.stats.weightstats import ztest import matplotlib.pyplot as plt import seaborn as sns from IPython.display import display, Markdown df = pd.read_csv("../data/raw/train.csv") ``` ### Dataset inspection - Should we worry about computat...
github_jupyter
<a href="https://colab.research.google.com/github/Edudeiko/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling/blob/master/module3-make-explanatory-visualizations/Evgenii_Dudeiko_DSPT3_123_Make_Explanatory_Visualizations_Assignment.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.sv...
github_jupyter
## Torch Core This module contains all the basic functions we need in other modules of the fastai library (split with [`core`](/core.html#core) that contains the ones not requiring pytorch). Its documentation can easily be skipped at a first read, unless you want to know what a given function does. ``` from fastai.im...
github_jupyter
# Demonstration of basic image manipulation with SIRF/CIL This demonstration shows how to create image data objects for MR, CT and PET and how to work with them. This demo is a jupyter notebook, i.e. intended to be run step by step. Author: Kris Thielemans, Richard Brown, Christoph Kolbitsch First version: 8th of S...
github_jupyter
``` import gif import seaborn as sns; sns.set(); import numpy as np import matplotlib.pyplot as plt import pandas as pd import math from mpl_toolkits.mplot3d import Axes3D # Function to plot our input data for classification tasks. def plot_2D_input_datapoints(X_inp, y_inp): """Method to plot 2D datapoints for class...
github_jupyter
# 轨道旋转 MP2 方法 (OO-MP2) 简单理解 > 创建日期:2021-01-09 这篇文档会尝试简单介绍轨道旋转 MP2 方法 (Orbital-Optimized Second-Order Møller–Plesset Perturbation, OO-MP2 or OMP2) 的基础概念与 PySCF 上的程序实现和理解。 这篇文档的编写并没有翻阅很多文献,并作测评上的认识。为数不多的文献与参考资料是 > Sun, Chan, et al. [^Sun-Chan.JCP.2020] (PySCF 进展文章) > > PySCF 并没有一个完整或独立的 OO-MP2 模块。实现 OO-MP2 可以通过仿 C...
github_jupyter
# Output from another step * **Difficulty level**: intermediate * **Time need to lean**: 10 minutes or less * **Key points**: * Function `output_from(step)` refers to output from another `step` * `output_from(step)[name]` can be used to refer to named output from `step` ## Referring to named output from another s...
github_jupyter
## **GRIP - TSF | Data Science & Business Analytics Internship** ### **Task 2 : K-Means Clustering** ### Author : AYOUB EL AAMRI. # 1. Setup the environment PANDAS,NUMPY for data manuplation. Matplotlib,seaborn module for Data Visualisation. sklearn for modelling ``` import pandas as pd import numpy as np impo...
github_jupyter
``` from results import * import matplotlib.pyplot as plt import numpy as np import seaborn as sns import os from matplotlib.transforms import Affine2D sns.set(style='whitegrid') def extract_data(label, data_dict, denominator_dict, normalize): mean_list = list() std_list = list() if normalize: facto...
github_jupyter
### base : 넘버웍스의 질문 + 공부하면서 느낀 것 추가 #### 통계 - p-value를 고객에게는 뭐라고 설명하는게 이해하기 편할까요? - p-value는 요즘 시대에도 여전히 유효할까요? 언제 p-value가 실제를 호도하는 경향이 있을까요? - A/B Test 등 현상 분석 및 실험 설계 상 통계적으로 유의미함의 여부를 결정하기 위한 방법에는 어떤 것이 있을까요? - R square의 의미는 무엇인가요? 고객에게는 어떻게 설명하실 예정인가요? - 평균(mean)과 중앙값(median)중에 어떤 케이스에서 뭐를 써야할까요? - 중심극한정리는 ...
github_jupyter
``` import random from mesa import Agent, Model from mesa.time import RandomActivation from mesa.space import MultiGrid from mesa.datacollection import DataCollector def compute_gini(model): agent_wealths = [agent.wealth for agent in model.schedule.agents] x = sorted(agent_wealths) N = model.num_agents ...
github_jupyter
## 3. Sequence Pattern Minning ``` # ! pip install gsppy ``` ### a) ``` def _mystrip(x): return x[:-1].split(',') import pandas as pd df = pd.read_csv('Sequence.csv', sep='\n', header=None) contains = df[df[0].str.contains(",Bread,Sweet")] df[0]=df[0].apply(_mystrip) df.head() # trans = df.values.tolist() trans ...
github_jupyter
# Climate Data ``` import matplotlib.pyplot as plt import pydaymet as daymet from pynhd import NLDI ``` The Daymet database provides climatology data at 1-km resolution. First, we use [PyNHD](https://github.com/cheginit/pynhd) to get the contributing watershed geometry of a NWIS station with the ID of `USGS-01031500`...
github_jupyter
``` import numpy as np import tensorflow as tf from TextSum import helpers tf.reset_default_graph() sess = tf.InteractiveSession() PAD = 0 EOS = 1 vocab_size = 10 input_embedding_size = 20 encoder_hidden_units = 25 decoder_hidden_units = encoder_hidden_units # encoder_inputs:[max_time, batch_size] encoder_inputs = tf.p...
github_jupyter
![cover](Malawi-News-Class.jpg) ``` from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics import accuracy_score, classification_report, confusion_matrix from sklearn.model_selection import train_test_split from sklearn.linear_model import SGDClassifier from sklearn.preprocessing import Label...
github_jupyter
``` import matplotlib.pyplot as plt import numpy as np from qctrlvisualizer import get_qctrl_style, plot_controls from qctrl import Qctrl qctrl = Qctrl() # Define standard matrices. sigma_x = np.array([[0, 1], [1, 0]], dtype=complex) sigma_y = np.array([[0, -1j], [1j, 0]], dtype=complex) sigma_z = np.array([[1, 0], ...
github_jupyter
# House Prices: Advanced Regression Techniques ## Table of Contents - <b>Introduction</b> - <b>Data Processing</b> - Outliers - Target variable - <b>Feature engineering</b> - Missing data - <i>Exploration</i> - <i>Imputation</i> - Converting features - <b>Machine Learning</b> - Set ...
github_jupyter
# Getting started ## Install and import `sme` ``` !pip install -q sme import sme from matplotlib import pyplot as plt import numpy as np print("sme version:", sme.__version__) ``` ## Importing a model - to load an existing sme or xml file: `sme.open_file('model_filename.xml')` - to load a built-in example model: `s...
github_jupyter
# Mount Drive & Login to Wandb ``` from google.colab import drive from getpass import getpass import urllib import os # Mount drive drive.mount('/content/drive') !pip install wandb -qqq !wandb login ``` # Install dependencies ``` !rm -r pearl !git clone https://github.com/PAL-ML/PEARL_v1.git pearl %cd pearl !pip ...
github_jupyter
### Functions Functions represent reusable blocks of code that you can reference by name and pass informatin into to customize the exectuion of the function, and receive a response representing the outcome of the defined code in the function. *When would you want to define a function?* You should consider defining a f...
github_jupyter
Walk-through ============ This walk-through guides users through several key concepts for using the nervana graph. The corresponding jupyter notebook is found [here](https://github.com/NervanaSystems/ngraph-neon/blob/master/examples/walk_through/Graph_Introduction.ipynb). Let's begin with a very simple example: compu...
github_jupyter
# Geography as Feature ``` import pandas as pd import geopandas as gpd import libpysal as lp import matplotlib.pyplot as plt import rasterio as rio import numpy as np import contextily as ctx import shapely.geometry as geom %matplotlib inline ``` Today, we'll talk about representing spatial relationships in Python us...
github_jupyter
This lab on Polynomial Regression and Step Functions is a python adaptation of p. 288-292 of "Introduction to Statistical Learning with Applications in R" by Gareth James, Daniela Witten, Trevor Hastie and Robert Tibshirani. Original adaptation by J. Warmenhoven, updated by R. Jordan Crouser at Smith College for SDS293...
github_jupyter
# Data Balancing - Random undersampling class 0 and oversampling class 1 ``` from collections import Counter from imblearn.over_sampling import ADASYN from imblearn.under_sampling import RandomUnderSampler import numpy as np import pandas as pd ``` ## 1. Load the Data ``` starting_ratio = ''#'starting_ratio_05/' per...
github_jupyter
# ORF recognition by CNN Compare to 114. Make sure there is always a STOP codon but only sometimes in frame. ``` import time t = time.time() time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(t)) PC_SEQUENCES=4000 # how many protein-coding sequences NC_SEQUENCES=4000 # how many non-coding sequences PC_TESTS=10...
github_jupyter
<a href="https://colab.research.google.com/github/cohmathonc/biosci670/blob/master/IntroductionComputationalMethods/01_IntroPython.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # What is a 'Program' **A program is a sequence of instructions that ...
github_jupyter
``` # Configuration related preprocessing step before mounting the drive !apt-get install -y -qq software-properties-common python-software-properties module-init-tools !add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null !apt-get update -qq 2>&1 > /dev/null !apt-get -y install -qq google-drive-ocamlfuse f...
github_jupyter
# SVD Practice. 2018/2/12 - WNixalo Fastai Computational Linear Algebra (2017) §2: [Topic Modeling w NMF & SVD](https://github.com/fastai/numerical-linear-algebra/blob/master/nbs/2.%20Topic%20Modeling%20with%20NMF%20and%20SVD.ipynb) facebook research: [Fast Randomized SVD](https://research.fb.com/fast-randomized-svd...
github_jupyter
``` import numpy as np import pandas as pd from math import floor, ceil from numpy.linalg import cholesky, inv, solve from scipy.linalg import cho_solve from scipy.stats import wishart, invwishart, gamma #from lifetimes import BetaGeoFitter, GammaGammaFitter #from lifetimes.utils import calibration_and_holdout_data, s...
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
##### 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
## 4 Pillars of OOP ``` # Encapsulation # a simple class to explain Encapsulation class Human(): _name = None _age = 0 def __init__(self, name, age): self._name = name self._age = age def greet(self, name): print(f'Hello {name}. My name is {self._name}. Nice to meet you!') # T...
github_jupyter
# Quick start: Impacts of Falls Lake on streamflow... Recall from the Excel bootcamps session that the first step was to get the streamflow data into our working environment (Excel then, Python here) and tidy the data up. From there, we'd plot and summarize the data. The code snippets below hint at the power of Pytho...
github_jupyter
## CONVOLUTIONAL NEURAL NETWORK ``` import os import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data %matplotlib inline print ("CURRENT TF VERSION IS [%s]" % (tf.__version__)) print ("PACKAGES LOADED") ``` ## LOAD MNIST ``` mnist = inpu...
github_jupyter
# Analysis of schemes for the diffusion equation <div id="diffu:pde1:analysis"></div> The numerical experiments in the sections [diffu:pde1:FE:experiments](#diffu:pde1:FE:experiments) and [diffu:pde1:theta:experiments](#diffu:pde1:theta:experiments) reveal that there are some numerical problems with the Forward Euler...
github_jupyter
# License ``` # Copyright 2022 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...
github_jupyter
``` import numpy as np import pandas as pd import os import sys import pickle import time import datetime import matplotlib.pyplot as plt import seaborn as sns from importlib import reload %matplotlib inline from IPython.core.display import display, HTML, clear_output display(HTML("<style>.container { width:80% !import...
github_jupyter
``` ## Name: Chandni Patel ## ID: A20455322 ## CS 512 - Fall 2020 ## Extract Chessboard Features import numpy as np import cv2 class Extract_Features: #initialling the image processor def __init__(self, img): self.H=7 self.W=7 self.TITLE = 'Extract Features' self.su...
github_jupyter
<H1> Symbolic Computation: The Pitfalls </H1> This collection of notebooks is mostly numerical, with not a lot of exact or symbolic computation. Why not? And, for that matter, why is numerical computing (even with all the unexpected behaviour of floating-point arithmetic) so much more popular than symbolic or exact ...
github_jupyter
``` import os import random import catboost import numpy as np import pandas as pd import xarray from sklearn.metrics import roc_auc_score import warnings warnings.filterwarnings('ignore') SEED = 42 VAL_MONTHS = 6 ITERATIONS = 1000 DATA_PATH = '../data' MODELS_PATH = './' def reseed(seed=SEED): np.random.seed(...
github_jupyter
# Confined Aquifer Test **This test is taken from examples presented in MLU tutorial.** ``` %matplotlib inline import numpy as np import matplotlib.pyplot as plt import pandas as pd from ttim import * ``` The test is condected at a fully confined two-aquifer system. Both the pumping well and the observation piezomete...
github_jupyter
# Road Following - Live demo In this notebook, we will use model we trained to move jetBot smoothly on track. ### Load Trained Model We will assume that you have already downloaded ``best_steering_model_xy.pth`` to work station as instructed in "train_model.ipynb" notebook. Now, you should upload model file to JetBo...
github_jupyter
Copyright 2020 The dnn-predict-accuracy Authors. 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 w...
github_jupyter
<a href="https://colab.research.google.com/github/https-deeplearning-ai/GANs-Public/blob/master/C3W2_Pix2PixHD_(Optional).ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Pix2PixHD *Please note that this is an optional notebook, meant to introduce...
github_jupyter
# How to integrate Financial Data from Refinitiv Data Platform to Excel with Xlwings - Part 2 ## Overview This notebook is the second part of the series that demonstrate how to export financial data and report from Python/Jupyter application to Excel report file using xlwings CE and xlwings Pro libraries. The demo a...
github_jupyter
``` import numpy as np import casadi as cas class MPC: def __init__(self, dt): self.dt = dt self.k_total = 1.0 # the overall weighting of the total costs self.theta_iamb = np.pi/4 # my theta wrt to ambulance self.L = 4.5 self.W = 1.8 self.n_circles = 2 ## Sta...
github_jupyter
# Linking elements together As explained in the Data Structure chapter, `momepy` relies on links between different morphological elements. Each element needs ID, and each of the small-scale elements also needs to know the ID of the relevant higher-scale element. The case of block ID is explained in the previous chapte...
github_jupyter
# Working with Environments By now you've run many experiments in your Azure Machine Learning workspace, and in some cases you've had to specify the particular Python packages required in the environment where the experiment code is run. In this lab, you'll explore environments in a little more detail. ## Connect to ...
github_jupyter
# Analytical Modelling Often, a well testing problem can be efficiently investigated using analytical solutions but these may require a degree of sophistication that is cumbersome for hand or Excel calculation. The purpose of this notebook is to demonstrate a few Python techniques for well test modelling. ## 1. Impl...
github_jupyter
``` from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) ``` # Embedding CPLEX in a ML Spark Pipeline `Spark ML` provides a uniform set of high-level APIs that help users create and tune practical machine learning pipelines. In this notebook, we show how...
github_jupyter