repo_name stringlengths 6 77 | path stringlengths 8 215 | license stringclasses 15
values | content stringlengths 335 154k |
|---|---|---|---|
garth-wells/notebooks-3M1 | 03-IterativeMethods.ipynb | bsd-2-clause | import numpy as np
"""
Explanation: Iterative methods
We explore in this notebook some iterative techniques for linear algebra problems. The implementations are written to expose how the methods work and are not optimised. Production-level implementations typically involve some specialised optimisations.
This notebook... |
msampathkumar/datadriven_pumpit | blood_donation/blood_donation_predicitons.ipynb | apache-2.0 | import warnings
import itertools
warnings.filterwarnings('ignore')
from functools import lru_cache
# standard tools
import numpy as np
import pandas as pd
# %load_ext autoreload
seed = 7 * 9
np.random.seed(seed)
import xgboost
import sklearn.ensemble
from sklearn.model_selection import train_test_split
from sklearn... |
weleen/mxnet | example/notebooks/moved-from-mxnet/cnn-text-classification.ipynb | apache-2.0 | import urllib2
import numpy as np
import re
import itertools
from collections import Counter
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
"""
string = re.sub(r"[^A-Za-... |
bjshaw/phys202-project | galaxy_project/D) Initial_velocities.ipynb | mit | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
gamma = 4.4983169634398596e-06
"""
Explanation: Initial Velocities
End of explanation
"""
def velocities_m(M,x,y):
"""Computes the velocities in the x and y direction of a star, m
Parameters
-------------
M : central mass of ... |
koverholt/notebooks | dask/run-calculation.ipynb | bsd-3-clause | import coiled
clusters = coiled.list_clusters()
clusters
"""
Explanation: Connect to existing Dask cluster
First, we get the list of Dask clusters running on Coiled:
End of explanation
"""
cluster_name = list(clusters.keys())[0]
cluster = coiled.Cluster(
name=cluster_name,
)
"""
Explanation: Now we can connect ... |
silburt/rebound2 | ipython_examples/EscapingParticles.ipynb | gpl-3.0 | import rebound
import numpy as np
def setupSimulation():
sim = rebound.Simulation()
sim.integrator = "ias15" # IAS15 is the default integrator, so we don't need this line
sim.add(m=1., id=0)
sim.add(m=1e-3,x=1.,vx=2., id=1)
sim.add(m=1e-3,a=1.25,M=np.pi/2, id=2)
sim.move_to_com()
return sim
... |
undercertainty/ou_nlp | 05_support_vector_machines.ipynb | apache-2.0 | # To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
np.random.seed(42)
# To plot pretty figures
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
... |
knowledgeanyhow/notebooks | noaa/etl/noaa_hdta_etl.ipynb | mit | # Import special helper functions for the IBM Knowledge Anyhow Workbench.
import kawb
"""
Explanation: Historical Daily Temperature Analysis
Objective
If there is scientific evidence of extreme fluctuations in our weather patterns due to human impact to the environment then we should be able to identify factual examp... |
jseabold/statsmodels | examples/notebooks/tsa_filters.ipynb | bsd-3-clause | %matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
dta = sm.datasets.macrodata.load_pandas().data
index = pd.Index(sm.tsa.datetools.dates_from_range('1959Q1', '2009Q3'))
print(index)
dta.index = index
del dta['year']
del dta['quarter']
print(sm.datasets.macrodata.N... |
cdawei/flickr-photo | src/trajectory_construction.ipynb | gpl-2.0 | %matplotlib inline
import os
import matplotlib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
import generate_tables
# data files
data_dir = '../data/'
table0 = 'Melb_photos_bigbox.csv'
table1 = 'trajectory_photos.csv'
table2 = 'trajectory_stats.csv'
raw_table = o... |
oliverlee/pydy | examples/mass_spring_damper/mass_spring_damper.ipynb | bsd-3-clause | from IPython.display import SVG
SVG(filename='mass_spring_damper.svg')
"""
Explanation: Defining the Problem
Here we will derive the equations of motion for the classic mass-spring-damper system under the influence of gravity. The following figure gives a pictorial description of the problem.
End of explanation
"""
... |
InsightLab/data-science-cookbook | 2019/12-spark/14-spark-mllib-classification/LogisticRegressionClassifier.ipynb | mit | from pyspark.ml.classification import LogisticRegression
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml import Pipeline
from pyspark.mllib.regression import LabeledPoint
from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import StringIndexer
from pyspark.mllib.evaluation import Multicl... |
JackDi/phys202-2015-work | assignments/assignment08/InterpolationEx02.ipynb | mit | %matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set_style('white')
from scipy.interpolate import griddata
"""
Explanation: Interpolation Exercise 2
End of explanation
"""
# YOUR CODE HERE
five_1=np.ones(11)*-5
four_1=np.ones(2)*-4
three_1=np.ones(2)*-3
two_1=np.ones... |
mholtrop/Phys605 | Python/FFT/FFT+example1.ipynb | gpl-3.0 | %matplotlib inline
"""
Explanation: Fast Fourier Transforms With Python
This Jupyter interactive notebook show you how you can make Fast Fourier Transforms (FFT) using Python and SciPy.
This is just a quick example tutorial, the real documentation is at: https://docs.scipy.org/doc/scipy-0.18.1/reference/tutorial/fftp... |
VictorQuintana91/Thesis | notebooks/004_grouping_domain_synonyms.ipynb | mit | # For monitoring duration of pandas processes
from tqdm import tqdm, tqdm_pandas
# To avoid RuntimeError: Set changed size during iteration
tqdm.monitor_interval = 0
# Register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm`
# (can use `tqdm_gui`, `tqdm_notebook`, optional kwargs, etc.)
tqdm.pandas(... |
4dsolutions/Python5 | Using SymPy.ipynb | mit | import sympy as sym
x = sym.symbols('x')
sym.init_printing()
sym.Integral(sym.sin(x), (x, 0, sym.pi))
sym.Integral(sym.sin(x), (x, 0, sym.pi)).doit()
"""
Explanation: SciPy / Havana
In case I get to go to SciPy / Havana, I'm boning up on SymPy, an important component within the SciPy Ecosystem.
Here's the kind of t... |
daneschi/berkeleytutorial | tutorial/03_multiResolutionChaos/multiResolutionChaos.ipynb | mit | # Imports
import sys,math
sys.path.insert(0, '..') # path to ../common.py
import numpy as np
import matplotlib.pyplot as plt
from common import *
"""
Explanation: Multiresolution regression of a function with non-continuous derivative
Author: Daniele E. Schiavazzi
Date: June 28th, 2017
References
- Schiavazzi D., Doos... |
LorenzoBi/courses | TSAADS/tutorial 9/9_LORENZO_BIASI_JULIUS_VERNIE.ipynb | mit | import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import fsolve
%matplotlib inline
def sigmoid(x):
return 1. / (1 + np.exp(-x))
def df(x, w=0, theta=0):
return w * sigmoid(x) * (1 - sigmoid(x))
def f(x, w=0, theta=0):
return w * sigmoid(x) + theta
def g(x, w, theta):
return f(x,... |
oditorium/blog | iPyTools/XL-PasteImport.ipynb | agpl-3.0 | data_string = """
1 2 3 4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
51 52 53 54
"""
data_string = data_string.strip()
data = [line.split('\t') for line in data_string.split('\n')]
data
data_f = [list(map(float,line.split('\t'))) for line in data_string.split('\n')]
data_f
data_i = [list(map(int,line.split('\t'... |
computational-class/cjc2016 | code/03.graphlab.ipynb | mit | ! python --version
"""
Explanation: Graphlab 安装与使用
王成军
wangchengjun@nju.edu.cn
计算传播网 http://computational-communication.com
Problem
只有低版本的anaconda才可以安装,强行安装还会破坏掉anaconda的jupyter notebook中的kernel,排除使用anaconda运行graphlab的方案。
Register for Academic Use of GraphLab Create
https://turi.com/download/academic.html
查邮件
https:... |
vub-ai-lab/MAL-seminar | notebooks/Deep Policy Gradient.ipynb | mit | def create_mlp(inputs, n_out):
net = nn.input_data(placeholder=inputs)
net = nn.fully_connected(net, 25, activation='relu', weight_decay=0.0001)
net = nn.dropout(net, 0.3)
net = nn.fully_connected(net, 25, activation='relu', weight_decay=0.0001)
net = nn.dropout(net, 0.3)
#softmax to normalize t... |
has2k1/plydata | doc/tutorials/dealing-with-nan-values.ipynb | bsd-3-clause | import pandas as pd
import numpy as np
from plydata import call
df = pd.DataFrame({
'w': [1, 2, np.nan, 4, 5],
'x': [np.nan, 2, np.nan, 4, 5],
'y': [np.nan] * 4 + [5],
'z': [np.nan] * 5
})
df
"""
Explanation: Dealing with NaN values
End of explanation
"""
df >> call(pd.DataFrame.dropna)
# You can c... |
elvd/elec3360 | ELEC3360_week6.ipynb | mit | import math # get access to most mathematical functions
l = 100 # length converted to cm
rho_copper = 1.7e-6
r_wire = 0.05 # radius converted to cm
R = (rho_copper * l) / (math.pi * r_wire**2)
print("Copper wire resistance at DC is {:.3f} Ohms".format(R))
"""
Explanation: ELEC 3360 RF & Microwave Engineering <br><b... |
mne-tools/mne-tools.github.io | 0.24/_downloads/524b9a6067f1a7bd3b66aa385465b921/20_source_alignment.ipynb | bsd-3-clause | import os.path as op
import numpy as np
import nibabel as nib
from scipy import linalg
import mne
from mne.io.constants import FIFF
data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
trans_fname = op.join(... |
aakashm301/Workshop | Refactored_Py_DS_ML_Bootcamp-master/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb | gpl-3.0 | import pandas as pd
"""
Explanation: <a href='http://www.pieriandata.com'> <img src='../../Pierian_Data_Logo.png' /></a>
SF Salaries Exercise - Solutions
Welcome to a quick exercise for you to practice your pandas skills! We will be using the SF Salaries Dataset from Kaggle! Just follow along and complete the tasks o... |
BDannowitz/polymath-progression-blog | running-weight-plot/Running-Weight-Data-Cleaning.ipynb | gpl-2.0 | %matplotlib inline
import pandas as pd
import numpy as np
"""
Explanation: Running and Weight Data Cleaning
Four disparate sources
Each have different features and formats, units, etc.
Work through to figure out requisite steps for processing and combining
Once done, wrap all steps up into concise functions for futu... |
jerkos/cobrapy | documentation_builder/pymatbridge.ipynb | lgpl-2.1 | %load_ext pymatbridge
import cobra.test
m = cobra.test.create_test_model("textbook")
"""
Explanation: Using the COBRA toolbox with cobrapy
This example demonstrates using COBRA toolbox commands in MATLAB from python through pymatbridge.
End of explanation
"""
from cobra.io.mat import model_to_pymatbridge
model_to_p... |
ottogroup/dstoolbox | notebooks/Examples_models.ipynb | apache-2.0 | import numpy as np
from dstoolbox.models import W2VClassifier
"""
Explanation: Using dstoolbox models
Table of contents
Text
W2VClassifier
Imports
End of explanation
"""
word2idx = {'herren': 0, 'damen': 1, 'stiefel': 2, 'rock': 3}
word_embeddings = np.array([
[0.1, 0.1, 0.1],
[10.0, 10.0, 10.1],
[-... |
luctrudeau/Teaching | IntroductionIOAsync/IntroductionIOAsync.ipynb | lgpl-3.0 | from IPython.display import Image
from IPython.display import display
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("etsmtl.ca" , 80))
"""
Explanation: Introduction à l'I/O Asynchrone
Le Socket de Berkeley
Il est difficile d'imaginer le nombre d'instanciations d'objets de type ... |
quasars100/Resonance_testing_scripts | python_tutorials/Exceptions.ipynb | gpl-3.0 | import rebound
import numpy as np
def setupSimulation():
rebound.reset()
rebound.integrator = "ias15" # IAS15 is the default integrator, so we don't need this line
rebound.add(m=1.)
rebound.add(m=1e-3,a=1.)
rebound.add(m=1e-3,a=1.25)
rebound.move_to_com()
"""
Explanation: Catching close encount... |
empirical-org/WikipediaSentences | notebooks/BERT-3 Experiments with Passage.ipynb | agpl-3.0 | import torch
from pytorch_transformers.tokenization_bert import BertTokenizer
from pytorch_transformers.modeling_bert import BertForSequenceClassification
BERT_MODEL = 'bert-base-uncased'
tokenizer = BertTokenizer.from_pretrained(BERT_MODEL)
"""
Explanation: BERT Experiments with passage
In this notebook we repeat ... |
fonnesbeck/ngcm_pandas_2016 | notebooks/1.1 Introduction to NumPy and Pandas.ipynb | cc0-1.0 | import numpy as np
"""
Explanation: Introduction to NumPy and Pandas
Introduction to NumPy
most fundamental third-party package for scientific computing in Python
multidimensional array data structures
associated functions and methods to manipulate them.
Other third-party packages, including pandas, use NumPy array... |
BeatHubmann/17F-U-DLND | autoencoder/Convolutional_Autoencoder_Solution.ipynb | mit | %matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
img = mnist.train.images[2]
plt.imshow(img.reshape((28, 28)), cmap='Greys_r')
"""
Explanation: C... |
hannorein/rebound | ipython_examples/EccentricComets.ipynb | gpl-3.0 | import rebound
import numpy as np
"""
Explanation: Integrating eccentric Comets with MERCURIUS
In this example, we study highly eccentric comets which interact with a Neptune mass planet.
MERCURIUS is a hybrid integration scheme which combines the WHFAST and IAS15 algorithms. It smoothly transitions between the two in... |
weinbe58/QuSpin | examples/notebooks/SSH.ipynb | bsd-3-clause | from quspin.operators import hamiltonian # Hamiltonians and operators
from quspin.basis import spinless_fermion_basis_1d # Hilbert space fermion basis
from quspin.tools.block_tools import block_diag_hamiltonian # block diagonalisation
import numpy as np # generic math functions
#
##### define model parameters #####
L=6... |
junhwanjang/DataSchool | Lecture/15. 과최적화와 정규화/1) 다항 회귀와 과최적화.ipynb | mit | np.random.seed(0)
n_samples = 30
X = np.sort(np.random.rand(n_samples))
y = np.cos(1.5 * np.pi * X) + np.random.randn(n_samples) * 0.1
dfX = pd.DataFrame(X, columns=["x"])
dfX = sm.add_constant(dfX)
dfy = pd.DataFrame(y, columns=["y"])
df = pd.concat([dfX, dfy], axis=1)
print(sm.OLS.from_formula("y ~ x", data=df).fit... |
tensorflow/docs-l10n | site/zh-cn/tutorials/generative/style_transfer.ipynb | apache-2.0 | #@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 agreed to in writing, software
# distributed under... |
JamesSample/icpw | check_trend_signif.ipynb | mit | # Read RESA2 export, calculate annual medians and plot
# Input file
in_xlsx = (r'C:\Data\James_Work\Staff\Heleen_d_W\ICP_Waters\TOC_Trends_Analysis_2015'
r'\Data\TOC_Little_Woodford_Partridge.xlsx')
df = pd.read_excel(in_xlsx, sheetname='DATA')
# Pivot
df = df.pivot(index='Date', columns='Station name', va... |
tpin3694/tpin3694.github.io | machine-learning/variance_thresholding_binary_features.ipynb | mit | from sklearn.feature_selection import VarianceThreshold
"""
Explanation: Title: Variance Thresholding Binary Features
Slug: variance_thresholding_binary_features
Summary: How to select the best binary features for machine learning using variance thresholding in Python.
Date: 2017-09-14 12:00
Category: Machine Learni... |
adamkovics/atmosphere | notebooks/Introduction.ipynb | gpl-2.0 | import os
os.environ['RTDATAPATH'] = '/Users/mate/g/rt/data/refdata_demo/'
import atmosphere as atm
atm.refdata.setup_directory()
"""
Explanation: Radiative transfer model of Titan in Near-IR
mate@berkeley.edu
Introduction
This is a pac... |
vravishankar/Jupyter-Books | pandas/04.Pandas - Tidying Data.ipynb | mit | # import pandas, numpy and datetime
import numpy as np
import pandas as pd
import datetime
# set some pandas options for controlling output
pd.set_option('display.notebook_repr_html', False)
pd.set_option('display.max_columns',10)
pd.set_option('display.max_rows',10)
"""
Explanation: Tidying Data
Tidying of data is r... |
SheffieldML/notebook | theano_day/variational_MRF.ipynb | bsd-3-clause | # Import Theano
import theano
# Tensor is the most useful module to import for our purposes. Let's make a shorthand
from theano import tensor as T
# Let's import other useful libraries
import numpy as np
import scipy as sp
import Image
import pylab as pb
%pylab inline
pb.ion()
"""
Explanation: 08/05/15 Example of v... |
ocefpaf/system-test | content/downloads/notebooks/2015-12-07-NGDC_CSW_QueryForIOOSRAs_UUID.ipynb | unlicense | from owslib.csw import CatalogueServiceWeb
endpoint = 'http://www.ngdc.noaa.gov/geoportal/csw'
csw = CatalogueServiceWeb(endpoint, timeout=30)
"""
Explanation: In the previous example we investigated if it was possible to query the NGDC CSW Catalog to extract records matching an IOOS RA acronym.
However, we could not... |
fastai/fastai | nbs/examples/migrating_catalyst.ipynb | apache-2.0 | from migrating_catalyst import *
"""
Explanation: Tutorial - Migrating from Catalyst
Incrementally adding fastai goodness to your Catalyst training
Catalyst code
We're going to use the MNIST training code from Catalyst's README (as at August 2020), converted to a module.
Note: The source script for migrating_cataly... |
Flaviolib/dx | 07_dx_portfolio_risk.ipynb | agpl-3.0 | import dx
import datetime as dt
import time
import numpy as np
"""
Explanation: <img src="http://hilpisch.com/tpq_logo.png" alt="The Python Quants" width="45%" align="right" border="4">
Derivatives Portfolio Risk Statistics
From a risk management perspective it is important to know how sensitive derivatives portfolios... |
cjam/deep-onc | notebooks/tf-mnist-ml-beginners.ipynb | mit | from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("data/MNIST",one_hot=True)
"""
Explanation: MNIST ML Beginner tutorial
This notebook is based on the tutorial found here
Get the MNIST dataset
End of explanation
"""
import tensorflow as tf
# Setup our Input placeholder
x ... |
cyliustack/sofa | validation/auto-caption-algorithm.ipynb | apache-2.0 | # system
import os
import sys
# 3rd party lib
import pandas as pd
from sklearn.cluster import KMeans
from fuzzywuzzy import fuzz # stirng matching
print('Python verison: {}'.format(sys.version))
print('\n############################')
print('Pandas verison: {}'.format(pd.show_versions()))
"""
Explanation: Auto-captio... |
atlury/deep-opencl | DL0110EN/5.1.2.He_Initialization.ipynb | lgpl-3.0 | import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as dsets
import torch.nn.functional as F
import matplotlib.pylab as plt
import numpy as np
torch.manual_seed(0)
"""
Explanation: <div class="alert alert-block alert-info" style="margin-top: 20px">
<a href="htt... |
MegaShow/college-programming | Homework/Principles of Artificial Neural Networks/Week 14 Training Issues 2/TrainingIssues.ipynb | mit | %load_ext autoreload
%autoreload 2
"""
Explanation: Week 14. Training Issues 2 (Review)
In this part, we would spend time revising common skills used in training model.
In short version, easy but useful.
In long version, we would introduce content in Outline step by step.
We mainly reference from sklearn and Pytorch
... |
landlab/landlab | notebooks/tutorials/reading_dem_into_landlab/reading_dem_into_landlab.ipynb | mit | from landlab.io import read_esri_ascii
"""
Explanation: <a href="http://landlab.github.io"><img style="float: left" src="../../landlab_header.png"></a>
How to read a DEM as a Landlab grid
This tutorial demonstrates how to create and initialize a Landlab grid using a Digital Elevation Model (DEM). The DEM is in ESRI's ... |
sdpython/ensae_teaching_cs | _doc/notebooks/td1a_home/2020_suffix.ipynb | mit | from jyquickhelper import add_notebook_menu
add_notebook_menu()
"""
Explanation: Algo - jeux de dictionnaires, plus grand suffixe commun
Les dictionnaires sont très utilisés pour associer des choses entre elles, surtout quand ces choses ne sont pas entières. Le notebook montre l'intérêt de perdre un peu de temps pour ... |
astroNN/astroNN | notebooks/1_notmnist_solutions.ipynb | mit | label_map = list('abcdefghij')
fig,axes = pl.subplots(3,3,figsize=(5,5),sharex=True,sharey=True)
with h5py.File(cache_file, 'r') as f:
for i in range(9):
ax = axes.flat[i]
idx = np.random.randint(f['test']['images'].shape[0])
ax.imshow(f['test']['images'][idx],
cm... |
appleby/fastai-courses | deeplearning1/nbs/lesson1.ipynb | apache-2.0 | %matplotlib inline
"""
Explanation: Using Convolutional Neural Networks
Welcome to the first week of the first deep learning certificate! We're going to use convolutional neural networks (CNNs) to allow our computer to see - something that is only possible thanks to deep learning.
Introduction to this week's task: 'Do... |
opengeostat/pygslib | doc/source/Ipython_templates/bigaus_raw.ipynb | mit | #general imports
import matplotlib.pyplot as plt
import pygslib
import numpy as np
import pandas as pd
#make the plots inline
%matplotlib inline
#get the data in gslib format into a pandas Dataframe
mydata= pygslib.gslib.read_gslib_file('../datasets/cluster.dat')
# This is a 2D file, in thi... |
himanshuy/titanic_survivals | titanic_survival_exploration.ipynb | gpl-3.0 | # Import libraries necessary for this project
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames
# Import supplementary visualizations code visuals.py
import visuals as vs
# Pretty display for notebooks
%matplotlib inline
# Load the dataset
in_file... |
ioos/notebooks_demos | notebooks/2017-01-18-siphon-explore-thredds.ipynb | mit | from siphon.catalog import TDSCatalog
catalog = TDSCatalog("https://thredds.cencoos.org/thredds/catalog.xml")
info = """
Catalog information
-------------------
Base THREDDS URL: {}
Catalog name: {}
Catalog URL: {}
Metadata: {}
""".format(
catalog.base_tds_url, catalog.catalog_name, catalog.catalog_url, catalog... |
JuBra/cobrapy | documentation_builder/io.ipynb | lgpl-2.1 | import cobra.test
import os
from os.path import join
data_dir = cobra.test.data_directory
print("mini test files: ")
print(", ".join(i for i in os.listdir(data_dir)
if i.startswith("mini")))
textbook_model = cobra.test.create_test_model("textbook")
ecoli_model = cobra.test.create_test_model("ecoli"... |
Danghor/Formal-Languages | Python/NFA-2-DFA.ipynb | gpl-2.0 | def epsClosure(s, delta):
Result = { s }
while True:
NewStates = { p for q in Result
for p in delta.get((q, ''), set())
}
if NewStates <= Result:
return frozenset(Result)
Result |= NewStates
"""
Explanation: Converting a Non-Deter... |
williamgilpin/pypdb | demos/demos.ipynb | mit | %pylab inline
from IPython.display import HTML
# Import from local directory
# import sys
# sys.path.insert(0, '../pypdb')
# from pypdb import *
# Import from installed package
from pypdb import *
%load_ext autoreload
%autoreload 2
"""
Explanation: pypdb demos
This is a set of basic examples of the usage and output... |
aslihandincer/coursera-machinelearning-python | ex5/ml-ex5.ipynb | mit | import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize
import scipy.io
%matplotlib inline
"""
Explanation: Exercise 5 | Regularized Linear Regression and Bias-Variance
End of explanation
"""
ex5data1 = scipy.io.loadmat('ex5data1.mat')
X = ex5data1['X']
y = ex5data1['y'][:,0]
Xtest = ex5data1['Xtes... |
ES-DOC/esdoc-jupyterhub | notebooks/inpe/cmip6/models/sandbox-3/landice.ipynb | gpl-3.0 | # DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'inpe', 'sandbox-3', 'landice')
"""
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: INPE
Source ID: SANDBOX-3
Topic: Landice
Sub-Topics: Glaciers, Ice.
Properties:... |
jonathf/chaospy | docs/user_guide/advanced_topics/advanced_regression_method.ipynb | mit | import sklearn
"""
Explanation: Advanced regression method
The library scikit-learn is a great machine-learning toolkit that provides a large collection of regression methods.
By default, chaospy only support traditional least-square regression, but is also designed to work together with the various regression functio... |
tomkraljevic/gtc2017-labs | L7126/Classification.ipynb | apache-2.0 | #import modules we plan to use
#-*- coding: utf-8 -*-
%matplotlib inline
import csv
from PIL import Image
import numpy as np
import tensorflow as tf
import skimage.io as io
import matplotlib.pyplot as plt
import scipy.ndimage
!nvidia-smi
#Read a text file with a list of the training and validation images
TRAIN_LIST=[]... |
Hackerfarm/awarenode | notebook/Workshop - 04 - Cleaning up data (WIP).ipynb | agpl-3.0 | %matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from pprint import pprint
"""
Explanation: Ok, let's get serious
First, let's import a few libs we will use to make the graphs:
End of explanation
"""
f = open("awanode-farmlab-2017-08-14.txt")
data=[]
times = list()
prevt=0
li... |
simpleoier/2016FallSpeechProj | .ipynb_checkpoints/1. Analysis-checkpoint.ipynb | apache-2.0 | import numpy as np
import os
from sklearn.manifold import TSNE
from common import Data
lld=Data('lld')
lld.load_training_data()
print 'training feature shape: ', lld.feature.shape
print 'training label shape: ', lld.label.shape
#lld.load_test_data()
#print 'test feature shape: ',lld.feature_test.shape
#print 'test l... |
google/jax | docs/notebooks/How_JAX_primitives_work.ipynb | apache-2.0 | from jax import lax
from jax._src import api
def multiply_add_lax(x, y, z):
"""Implementation of multiply-add using the jax.lax primitives."""
return lax.add(lax.mul(x, y), z)
def square_add_lax(a, b):
"""A square-add function using the newly defined multiply-add."""
return multiply_add_lax(a, a, b)
print("... |
eggie5/UCSD-MAS-DSE230 | hmwk5/2.Higgs.ipynb | mit | #define feature names
feature_text='lepton pT, lepton eta, lepton phi, missing energy magnitude, missing energy phi, jet 1 pt, jet 1 eta, jet 1 phi, jet 1 b-tag, jet 2 pt, jet 2 eta, jet 2 phi, jet 2 b-tag, jet 3 pt, jet 3 eta, jet 3 phi, jet 3 b-tag, jet 4 pt, jet 4 eta, jet 4 phi, jet 4 b-tag, m_jj, m_jjj, m_lv, m_jl... |
cmshobe/landlab | notebooks/tutorials/network_sediment_transporter/network_plotting_examples.ipynb | mit | import warnings
warnings.filterwarnings('ignore')
import os
import pathlib
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
from landlab import ExampleData
from landlab.components import FlowDirectorSteepest, NetworkSedimentTransporter
from landlab.data_record import DataRecord
fr... |
oditorium/blog | iPython/SubindexingListsFunctionalStyle.ipynb | agpl-3.0 | import random
"""
Explanation: Subindexing list, functional style
End of explanation
"""
mylist = [(random.randint(1,3),random.randint(1,100)) for x in range(20)]
mylist.sort()
mylist
"""
Explanation: The issue is the following: we have a list where one item is a category, and another one is a sortable value. We ca... |
mldbai/mldb | container_files/tutorials/Selecting Columns Programmatically Using Column Expressions Tutorial.ipynb | apache-2.0 | from pymldb import Connection
mldb = Connection()
"""
Explanation: Selecting Columns Programmatically Using Column Expressions Tutorial
MLDB provides a complete implementation of the SQL SELECT statement. Most of the functions you are accustomed to using are available in your queries.
MLDB is different from tradition... |
MIT-LCP/mimic-code-sharing | notebooks/crrt-notebook.ipynb | mit | # Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import psycopg2
from IPython.display import display, HTML # used to print out pretty pandas dataframes
import matplotlib.dates as dates
import matplotlib.lines as mlines
%matplotlib inline
plt.style.use('ggplot')
# specify user... |
google/qkeras | notebook/CodebookQuantization.ipynb | apache-2.0 | from tensorflow.keras.regularizers import *
from tensorflow.keras.layers import *
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import *
from tensorflow.keras.datasets import *
from tensorflow.keras.utils import to_categorical
from qkeras import *
from qkeras.codebook import *
def get_da... |
ES-DOC/esdoc-jupyterhub | notebooks/hammoz-consortium/cmip6/models/mpiesm-1-2-ham/ocnbgchem.ipynb | gpl-3.0 | # DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'hammoz-consortium', 'mpiesm-1-2-ham', 'ocnbgchem')
"""
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: HAMMOZ-CONSORTIUM
Source ID: MPIESM-1-2-HAM
Topic: Ocnbgch... |
Benedicto/ML-Learning | Linear_Regression_5_lasso_regression_assignment_1.ipynb | gpl-3.0 | import graphlab
import numpy as np
"""
Explanation: Regression Week 5: Feature Selection and LASSO (Interpretation)
In this notebook, you will use LASSO to select features, building on a pre-implemented solver for LASSO (using GraphLab Create, though you can use other solvers). You will:
* Run LASSO with different L1... |
watsonyanghx/CS231n | assignment2/Dropout.ipynb | mit | # As usual, a bit of setup
import time
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.fc_net import *
from cs231n.data_utils import get_CIFAR10_data
from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
from cs231n.solver import Solver
%matplotlib inline
... |
PyladiesMx/Pyladies_ifc | 3. Functions/.ipynb_checkpoints/Functions-checkpoint.ipynb | mit | animales = ['perro', 'gato', 'perico']
len(animales)
animales[1]
x = 4
type(int('43'))
"""
Explanation: Bienvenid@s a otra reunión de Pyladies!!
En esta sesión aprenderemos a crear nuestras propias funciones en python.Pero primero que son funciones?
Una función en python es un bloque de código organizado y reusabl... |
sebsch/WT-2_Such-_und_Texttechnologien | Decision-Tree_Learning.ipynb | gpl-3.0 | def entropy(S):
outcomes = pd.unique(S[final])
ent = lambda p: 0 if p == 0 else p * log2(p)
return -sum([ ent( S[S[final] == o].size / S.size ) for o in outcomes ])
"""
Explanation: Decision-Tree Learning
Decision tree learning uses a decision tree as a predictive model observations ab... |
mrcinv/matpy | oma/kolokviji/OMA, 2. kolokvij 2012_2013.ipynb | gpl-2.0 | %%tikz s 400,400 -sc 1.2 -f png
\draw [domain=0:180] plot ({cos(\x)}, {sin(\x)});
\draw (-1,0) -- (1, 0);
\draw [color=red] (-0.5, 0) -- node[below, color=black] {2a} ++ (1, 0);
\draw [color=red] (-0.5, 0.8660254037844386) -- (0.5, 0.8660254037844386);
\draw [color=red] (-0.5, 0) -- node[left, color=black] {b} ++ (0, 0... |
OpenDSA/Analysis | Yusuf/Count_Questions.ipynb | mit | # This file is used for both, nutshell (Coarse-grained) and detailed (Fine-grained) creation of the questions and their numbers
import json
import os
from math import comb
from scipy import stats
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
%matplotlib ... |
whitead/numerical_stats | unit_9/hw_2017/problem_set_1.ipynb | gpl-3.0 | import numpy as np
m = np.zeros( (10,10) )
m[:,1] = 3
m[np.diag_indices(10)] = 4
print(m)
"""
Explanation: Problem 1 Instructions
Create the following matrices without explicitly initializing them. Instead create a matrix of ones or zeros and use slicing to create the requested pattern. Print the matrix after creatin... |
NLP-Deeplearning-Club/Classic-ML-Methods-Algo | ipynbs/appendix/cross_validation.ipynb | mit | import numpy as np
from sklearn import datasets
from sklearn import svm
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_val_predict
from sklearn import metrics
iris = datasets.load_iris()
clf = svm.SVC(kernel='linear', C=1)
scores = cross_val_score(clf, iris.data, iris.ta... |
tensorflow/docs-l10n | site/en-snapshot/model_optimization/guide/pruning/pruning_for_on_device_inference.ipynb | apache-2.0 | #@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 agreed to in writing, software
# distributed under... |
bobmyhill/burnman | tutorial/tutorial_03_layers_and_planets.ipynb | gpl-2.0 | import numpy as np
import matplotlib.pyplot as plt
import burnman
from burnman import Mineral, PerplexMaterial, Composite, Layer, Planet
from burnman import minerals
depths = np.linspace(2890e3, 670e3, 20)
rock = Composite([minerals.SLB_2011.mg_bridgmanite(),
minerals.SLB_2011.periclase()],
... |
jrrembert/cybernetic-organism | dato/classification/.ipynb_checkpoints/Analyzing product sentiment-checkpoint.ipynb | gpl-2.0 | import graphlab
"""
Explanation: Predicting sentiment from product reviews
Fire up GraphLab Create
End of explanation
"""
products = graphlab.SFrame('amazon_baby.gl/')
"""
Explanation: Read some product review data
Loading reviews for a set of baby products.
End of explanation
"""
products.head()
"""
Explanation... |
bretthandrews/marvin | docs/sphinx/jupyter/saving_and_restoring.ipynb | bsd-3-clause | # let's grab the H-alpha emission line flux map
from marvin.tools.maps import Maps
mapfile = '/Users/Brian/Work/Manga/analysis/v2_0_1/2.0.2/SPX-GAU-MILESHC/8485/1901/manga-8485-1901-MAPS-SPX-GAU-MILESHC.fits.gz'
maps = Maps(filename=mapfile)
haflux = maps.getMap('emline_gflux', channel='ha_6564')
print(haflux)
"""
Exp... |
mmathioudakis/moderndb | 2016/mongodb.tutorial.ipynb | mit | # start a client
client = pm.MongoClient()
# connect to a database
db = client.moderndb
# get a collection
coll = db.test_collection
"""
Explanation: MongoDB Tutorial - Monday 22 February 2016
Introduction
In what follows, we assume that you have installed MongoDB according to the instructions online and started th... |
gibiansky/blog | posts/nram-2/post.ipynb | gpl-2.0 | import theano
from theano import tensor
import numpy as np
from collections import namedtuple
"""
Explanation: In the previous post, we discussed a simplified neural random-access memory machine (NRAM). We dubbed this simplified machine a neural register machine, since it lacks random-access memory but has a fixed se... |
sellensr/Juice-Box-Viscometer | JuiceBox.ipynb | mit | import numpy as np
import math
from IPython.display import HTML
HTML('<iframe width="853" height="480" \
src="https://www.youtube.com/embed/ktuVw9C_KNA" \
frameborder="0" allowfullscreen></iframe>')
"""
Explanation: Measuring Viscosity with a Juice Box
Choose Cell/Run All from the menu to get started and loa... |
ES-DOC/esdoc-jupyterhub | notebooks/cccma/cmip6/models/sandbox-2/ocean.ipynb | gpl-3.0 | # DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cccma', 'sandbox-2', 'ocean')
"""
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: CCCMA
Source ID: SANDBOX-2
Topic: Ocean
Sub-Topics: Timestepping Framework, Advecti... |
karlstroetmann/Algorithms | Python/Chapter-06/Calculator-Frame.ipynb | gpl-2.0 | class Stack:
def __init__(self):
self.mStackElements = []
def push(self, e):
self.mStackElements.append(e)
def pop(self):
assert len(self.mStackElements) > 0, "popping empty stack"
self.mStackElements = self.mStackElements[:-1]
def top(self):
assert len(self.mS... |
chicagopython/CodingWorkshops | problems/data_science/Introduction_to_Text_Analysis_with_sklearn.ipynb | gpl-3.0 | !pip install -r requirements.txt
"""
Explanation: Introduction to pandas and sklearn
Recommendation System
We live in a world surrounded by recommendation systems - our shopping habbits, our reading habits, political opinions are heavily influenced by recommendation algorithms. So lets take a closer look at how to bui... |
kimkipyo/dss_git_kkp | 통계, 머신러닝 복습/160613월_14일차_정규화(Regularization), 로지스틱 회귀 분석(Logistic Regression)/3.정규화 선형 회귀.ipynb | mit | np.random.seed(0)
n_samples = 30
X = np.sort(np.random.rand(n_samples))
y = np.cos(1.5 * np.pi * X) + np.random.randn(n_samples) * 0.1
dfX = pd.DataFrame(X, columns=["x"])
dfX = sm.add_constant(dfX)
dfy = pd.DataFrame(y, columns=["y"])
df = pd.concat([dfX, dfy], axis=1)
model = sm.OLS.from_formula("y ~ x + I(x**2) + ... |
ercius/openNCEM | ncempy/notebooks/3D_slicer.ipynb | gpl-3.0 | # Set the data location
dirName = r'c:\users\linol\data'
fName = '10_series_1.ser'
# Load needed modules
%matplotlib widget
from pathlib import Path
import matplotlib.pyplot as plt
import ncempy.io as nio
import ipywidgets as widgets
from ipywidgets import interact, interactive
"""
Explanation: NCEMPY's 3D slicer... |
tclaudioe/Scientific-Computing | SC4/Chapter 8 - Markov processes.ipynb | bsd-3-clause | import numpy as np
import scipy.sparse.linalg as sp
import sympy as sym
from scipy.linalg import toeplitz
import ipywidgets as widgets
from ipywidgets import IntSlider
import matplotlib.pyplot as plt
%matplotlib inline
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
plt.styl... |
GoogleCloudPlatform/bigquery-notebooks | notebooks/community/analytics-componetized-patterns/retail/recommendation-system/bqml-scann/00_prep_bq_procedures.ipynb | apache-2.0 | !pip install -q -U google-cloud-bigquery pyarrow
"""
Explanation: Create BigQuery stored procedures
This notebook is the second of two notebooks that guide you through completing the prerequisites for running the Real-time Item-to-item Recommendation with BigQuery ML Matrix Factorization and ScaNN solution.
Use this n... |
ktaneishi/deepchem | examples/notebooks/protein_ligand_complex_notebook.ipynb | mit | %load_ext autoreload
%autoreload 2
%pdb off
# set DISPLAY = True when running tutorial
DISPLAY = False
# set PARALLELIZE to true if you want to use ipyparallel
PARALLELIZE = False
import warnings
warnings.filterwarnings('ignore')
import deepchem as dc
from deepchem.utils import download_url
import os
data_dir = dc.u... |
tensorflow/quantum | docs/tutorials/gradients.ipynb | apache-2.0 | #@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 agreed to in writing, software
# distributed under... |
GoogleCloudPlatform/training-data-analyst | courses/machine_learning/deepdive2/production_ml/solutions/post_training_quant.ipynb | apache-2.0 | # Importing necessary modules
import logging
logging.getLogger("tensorflow").setLevel(logging.DEBUG)
import tensorflow as tf
from tensorflow import keras
import numpy as np
import pathlib
"""
Explanation: Post-training dynamic range quantization
Learning Objectives
1. We will learn how to train a TensorFlow model.
... |
bqtc/lessons | src/lessons/Python intro.ipynb | gpl-3.0 | # Prints Hello, world!
print('Hello, world!')
"""
Explanation: Throughout this tutorial, feel free to change the code and play around with it to see what will break it.
Data Types & Expressions
End of explanation
"""
def hello():
'''Function that prints Hello, world!
'''
print('Hello, world!')
hello()
... |
apryor6/apryor6.github.io | visualizations/seaborn/notebooks/.ipynb_checkpoints/jointplot-checkpoint.ipynb | mit | %matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
plt.rcParams['figure.figsize'] = (20.0, 10.0)
plt.rcParams['font.family'] = "serif"
"""
Explanation: seaborn.jointplot
Seaborn's jointplot displays a relationship between 2 variables (bivariate) as well as ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.