repo_name
stringlengths
6
77
path
stringlengths
8
215
license
stringclasses
15 values
content
stringlengths
335
154k
DJMedhaug/code_guild
wk0/notebooks/challenges/primes/.ipynb_checkpoints/primes_challenge-checkpoint.ipynb
mit
def list_primes(n): # TODO: Implement me pass """ Explanation: <small><i>This notebook was prepared by Thunder Shiviah. Source and license info is on GitHub.</i></small> Challenge Notebook Problem: Implement list_primes(n), which returns a list of primes up to n (inclusive). Constraints Test Cases Algorithm C...
cfobel/colonists
colonists/notebooks/Colonists map data structures.ipynb
gpl-3.0
# ## Create hex grid ## hex_grid = HexGrid(8, 17, .165, 1.75) np.random.seed(2) # ## Set up board on grid ## # - Assign region (land, port, sea) and terrain type (clay, sheep, ore, wheat, wood, # desert, clay port, sheep port, ore port, wheat port, wood port, 3:1 port, sea) # to each hex. df_hexes = get_hexes(...
moagstar/puzzles
Array/Pascal's Triangle.ipynb
mit
import sys; sys.path.append('../..') from puzzles import leet_puzzle leet_puzzle('pascals-triangle') """ Explanation: Pascal's Triangle End of explanation """ def pascals_triangle(k): prev_row = None for r in xrange(k+1): row = [None] * r for c in xrange(r): if c == 0 or c == r-1:...
SylvainCorlay/bqplot
examples/Interactions/Mark Interactions.ipynb
apache-2.0
x_sc = LinearScale() y_sc = LinearScale() x_data = np.arange(20) y_data = np.random.randn(20) scatter_chart = Scatter(x=x_data, y=y_data, scales= {'x': x_sc, 'y': y_sc}, colors=['dodgerblue'], interactions={'click': 'select'}, selected_style={'opacity': 1.0, 'fill': 'Dar...
tbenthompson/tectosaur
examples/notebooks/fullspace_qd_run.ipynb
mit
import numpy as np import matplotlib.pyplot as plt import tectosaur.mesh.mesh_gen import tectosaur as tct import tectosaur.qd as qd qd.configure( gpu_idx = 0, # Which GPU to use if there are multiple. Best to leave as 0. fast_plot = True, # Let's make fast, inexpensive figures. Set to false for higher resolut...
tensorflow/tfx
docs/tutorials/model_analysis/tfma_basic.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...
samuelsinayoko/kaggle-housing-prices
prepare_data.ipynb
mit
from scipy.stats.mstats import mode import pandas as pd import numpy as np import time from sklearn.preprocessing import LabelEncoder """ Read Data """ train = pd.read_csv('data/train.csv') test = pd.read_csv('data/test.csv') target = train['SalePrice'] train = train.drop(['SalePrice'],axis=1) trainlen = train.shape[0...
rsignell-usgs/notebook
WMS/wms_sample.ipynb
mit
%matplotlib inline from owslib.wms import WebMapService #We just need a WMS url from one TDS dataset... serverurl ='http://thredds.ucar.edu/thredds/wms/grib/NCEP/NAM/CONUS_12km/best' wms = WebMapService( serverurl, version='1.1.1') """ Explanation: Exploring Web Map Service (WMS) WMS and OWSLib Getting some informati...
karlstroetmann/Formal-Languages
Python/Top-Down-Parser.ipynb
gpl-2.0
import re """ Explanation: A Recursive Parser for Arithmetic Expressions In this notebook we implement a simple recursive descend parser for arithmetic expressions. This parser will implement the following grammar: $$ \begin{eqnarray} \mathrm{expr} & \rightarrow & \mathrm{product}\;\;\mathrm{exprRest} ...
parkerzf/kaggle-expedia
notebooks/time_based_anlaysis.ipynb
bsd-3-clause
daily_stats[['count_click', 'count_booking_train', 'count_booking_test']].sum()/1000 print 'booking ratio for train set: ', daily_stats.count_booking_train.sum() * 1.0 \ / (daily_stats.count_click.sum() + daily_stats.count_booking_train.sum()) print 'daily booking in train set: ', daily_stats.count_booking_train.su...
xesscorp/myhdlpeek
examples/peeker_options.ipynb
mit
from myhdl import * from myhdlpeek import Peeker def adder_bit(a, b, c_in, sum_, c_out): '''Single bit adder.''' @always_comb def adder_logic(): sum_.next = a ^ b ^ c_in c_out.next = (a & b) | (a & c_in) | (b & c_in) # Add some peekers to monitor the inputs and outputs. Peeker(...
halflings/bio-data-workshop
notebook.ipynb
apache-2.0
# The dataset doesn't contain a header containing column names # so we generate them ourselves. feature_columns = ['feature_{}'.format(i) for i in range(1, 31)] columns = ['id', 'diagnosis'] + feature_columns # Reading data from a #DATA_PATH = 'https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-w...
santosjorge/cufflinks
Cufflinks Tutorial - Colors.ipynb
mit
import cufflinks as cf """ Explanation: Cufflinks Colors Cufflinks also provides a wide set of tools for color managements; including color conversion across multiple spectrums and color table generation. End of explanation """ # The colors module includes a pre-defined set of commonly used colors cf.colors.cnames ...
agussman/aws_name_similarity
aws_name_similarity.ipynb
mit
from itertools import combinations import jellyfish from scipy.cluster import hierarchy import numpy as np import matplotlib.pyplot as plt """ Explanation: Setup $ mkvirtualenv aws_name_similarity $ pip install --upgrade pip $ pip install jellyfish jupyter scipy matplotlib $ jupyter notebook End of explanation """ #...
nslatysheva/data_science_blogging
expanding_ML_toolkit/expanding_toolkit.ipynb
gpl-3.0
import wget import pandas as pd import numpy as np from sklearn.cross_validation import train_test_split # Import the dataset data_url = 'https://raw.githubusercontent.com/nslatysheva/data_science_blogging/master/datasets/wine/winequality-red.csv' dataset = wget.download(data_url) dataset = pd.read_csv(dataset, sep=";...
egentry/dwarf_photo-z
dwarfz/catalog_only_classifier/classifier_comparison.ipynb
mit
# give access to importing dwarfz import os, sys dwarfz_package_dir = os.getcwd().split("dwarfz")[0] if dwarfz_package_dir not in sys.path: sys.path.insert(0, dwarfz_package_dir) import dwarfz # back to regular import statements %matplotlib inline from matplotlib import pyplot as plt import seaborn as sns s...
nwfpug/python-primer
notebooks/05-looping.ipynb
gpl-3.0
for num in range(10,20): #to iterate between 10 to 20 for i in range(2,num): #to iterate on the factors of the number if num%i == 0: #to determine the first factor j=num/i #to calculate the second factor print '%d equals %d * %d' % (num,i,j) break ...
ini-python-course/ss15
notebooks/List Comprehensions.ipynb
mit
V = [2**i for i in range(13)] print V S = set([x**2 for x in range(10)]) print S M = set([x for x in S if x % 2 == 0]) print M """ Explanation: List comprehensions In Python there is a special way to initialize lists (and dictionaries) called list comprehensions. For many lists that we are going to create, list comp...
lknelson/text-analysis-2017
03-Pandas_and_DTM/01-DTM_DistinctiveWords.ipynb
bsd-3-clause
import pandas #create a dataframe called "df" df = pandas.read_csv("../Data/BDHSI2016_music_reviews.csv", sep = '\t', encoding = 'utf-8') #view the dataframe #The column "body" contains our text of interest. df #print the first review from the column 'body' df.loc[0,'body'] """ Explanation: The Document Term Matrix...
ihmeuw/dismod_mr
examples/cross_walks.ipynb
agpl-3.0
import numpy as np, pandas as pd, dismod_mr %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns # set a random seed to ensure reproducible simulation results np.random.seed(123456) # simulate data n = 20 data = dict(age=np.random.randint(0, 10, size=n)*10, year=np.random.randint(199...
lmcinnes/hdbscan
notebooks/How HDBSCAN Works.ipynb
bsd-3-clause
import numpy as np import matplotlib.pyplot as plt import seaborn as sns import sklearn.datasets as data %matplotlib inline sns.set_context('poster') sns.set_style('white') sns.set_color_codes() plot_kwds = {'alpha' : 0.5, 's' : 80, 'linewidths':0} """ Explanation: How HDBSCAN Works HDBSCAN is a clustering algorithm d...
antongrin/EasyMig
EasyMig_v3.ipynb
apache-2.0
# -*- coding: utf-8 -*- """ Created on Fri Feb 12 13:21:45 2016 @author: GrinevskiyAS """ from __future__ import division import numpy as np from numpy import sin,cos,tan,pi,sqrt import matplotlib as mpl import matplotlib.cm as cm import matplotlib.pyplot as plt %matplotlib inline font = {'family': 'Arial', 'weigh...
bert9bert/statsmodels
examples/notebooks/statespace_arma_0.ipynb
bsd-3-clause
%matplotlib inline from __future__ import print_function import numpy as np from scipy import stats import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm from statsmodels.graphics.api import qqplot """ Explanation: Autoregressive Moving Average (ARMA): Sunspots data This notebook replicat...
BrentDorsey/pipeline
gpu.ml/notebooks/03a_Train_Model_GPU.ipynb
apache-2.0
import tensorflow as tf from tensorflow.python.client import timeline import pylab import numpy as np import os %matplotlib inline %config InlineBackend.figure_format = 'retina' tf.logging.set_verbosity(tf.logging.INFO) """ Explanation: Train Model with GPU (and CPU*) CPU is still used to store variables that we are...
machinelearningnanodegree/stanford-cs231
solutions/vijendra/assignment1/knn.ipynb
mit
# Run some setup code for this notebook. import random import numpy as np from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt # This is a bit of magic to make matplotlib figures appear inline in the notebook # rather than in a new window. %matplotlib inline plt.rcParams['figure.figsize'] = (10....
bouhlelma/smt
tutorial/SMT_MixedInteger_application.ipynb
bsd-3-clause
%matplotlib inline from math import exp import numpy as np import matplotlib.pyplot as plt from matplotlib import colors from mpl_toolkits.mplot3d import Axes3D from scipy.stats import norm from scipy.optimize import minimize import scipy import six from smt.applications import EGO from smt.surrogate_models import K...
laurentperrinet/Khoei_2017_PLoSCB
notebooks/figure_3_FLE.ipynb
mit
%%writefile experiment_fle.py import MotionParticlesFLE as mp gen_dot = mp.generate_dot import numpy as np import os from default_param import * image = {} experiment = 'FLE' do_sim = False do_sim = True for stimulus_tag, im_arg in zip(stim_labels, stim_args): # generating the movie image[stimulus_tag] = {} ...
Sebbenbear/notebooks
Natural Language Processing.ipynb
apache-2.0
text6.concordance("swallow") text6.similar("Soldier") text6.common_contexts(["oh", "very"]) text6.dispersion_plot(["swallow", "European", "it", "oh", "very"]) len(text6) sorted(set(text6)) """ Explanation: Search text with context End of explanation """ len(set(text6)) / len(text6) text6.count("Allo") sentenc...
seg/2016-ml-contest
JLOWE/JLowe_NN.ipynb
apache-2.0
import numpy as np np.random.seed(1000) import warnings warnings.filterwarnings("ignore") import time as tm import pandas as pd from scipy.signal import medfilt from keras.models import Sequential from keras.constraints import maxnorm from keras.layers import Dense, Dropout from keras.utils import np_utils from skl...
surprisoh/crowdfunding_prediction
4. Before Funding.ipynb
mit
from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import RandomForestClassifier from sklearn.cross_validation import cross_val_score from sklearn.cross_validation import KFold from sklearn.cross_validation import StratifiedKFold from sklearn.neighbors im...
hungiyang/StatisticalMethods
examples/XrayImage/Modeling.ipynb
gpl-2.0
from __future__ import print_function import astropy.io.fits as pyfits import astropy.visualization as viz import matplotlib.pyplot as plt import numpy as np %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 10.0) """ Explanation: Forward Modeling the X-ray Image data In this notebook, we'll take a closer loo...
wenduowang/git_home
python/MSBA/intro/HW3/HW3_WenduoWang.ipynb
gpl-3.0
gold = pd.read_table("gold.txt", names=["url", "category"]).dropna() labels = pd.read_table("labels.txt", names=["turk", "url", "category"]).dropna() """ Explanation: Question 1: Read in data Read in the data from "gold.txt" and "labels.txt". Since there are no headers in the files, names parameter should be set expli...
adelavega/neurosynth-mfc
other/Create MFC mask.ipynb
mit
cortex = nib.load('cerbcort.nii.gz') # Binarize cortex = nib.Nifti1Image((cortex.get_data() > 0).astype('int'), cortex.get_header().get_best_affine()) niplt.plot_roi(cortex) """ Explanation: Here, I'm going to create the mask that defined MFC for further analysis. First, I load a cerebral cortex probabilty map, from ...
akseshina/dl_course
seminar_12/homework/homework.ipynb
gpl-3.0
import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets import matplotlib.pyplot as plt %matplotlib inline from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('fashion-mni...
TomTranter/OpenPNM
examples/percolation/Part B - Invasion Percolation.ipynb
mit
import sys import openpnm as op import numpy as np np.random.seed(10) import matplotlib.pyplot as plt import porespy as ps from ipywidgets import interact, IntSlider from openpnm.topotools import trim %matplotlib inline ws = op.Workspace() ws.settings["loglevel"] = 40 """ Explanation: Part B: Invasion Percolation The ...
CivicKnowledge/metatab-packages
census.gov/census.gov-pums-20165/notebooks/Extract.ipynb
mit
rac1p_map = { 1: 'white', 2: 'black', 3: 'amind', 4: 'alaskanat', 5: 'aian', 6: 'asian', 7: 'nhopi', 8: 'other', 9: 'many' } pop['race'] = pop.rac1p.astype('category') pop['race'] = pop.race.cat.rename_categories(rac1p_map) # The raceeth variable is the race varaiable, but with 'wh...
ALEXKIRNAS/DataScience
Coursera/Machine-learning-data-analysis/Course 2/Week_01/PA_linreg_stochastic_grad_descent.ipynb
mit
def write_answer_to_file(answer, filename): with open(filename, 'w') as f_out: f_out.write(str(round(answer, 3))) """ Explanation: Линейная регрессия и стохастический градиентный спуск Задание основано на материалах лекций по линейной регрессии и градиентному спуску. Вы будете прогнозировать выручку компан...
harsh6292/machine-learning-nd
projects/customer_segments/customer_segments.ipynb
mit
# Import libraries necessary for this project import numpy as np import pandas as pd import matplotlib.pyplot as plt 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 in...
arborh/tensorflow
tensorflow/lite/experimental/micro/examples/hello_world/create_sine_model.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...
csyhuang/hn2016_falwa
examples/nh2018_science/demo_script_for_nh2018.ipynb
mit
import numpy as np from numpy import dtype from math import pi from netCDF4 import Dataset import matplotlib.pyplot as plt import datetime as dt %matplotlib inline from hn2016_falwa.oopinterface import QGField import hn2016_falwa.utilities as utilities import datetime as dt """ Explanation: Last updated on Apr 9, 2020...
xiongzhenggang/xiongzhenggang.github.io
data-science/27-错误可视化.ipynb
gpl-3.0
%matplotlib inline import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') import numpy as np x = np.linspace(0, 10, 50) dy = 0.8 y = np.sin(x) + dy * np.random.randn(50) # yerr表示y的误差 plt.errorbar(x, y, yerr=dy, fmt='.k'); """ Explanation: 错误可视化 对于任何科学的度量,准确地计算错误几乎和准确报告数字本身一样重要,甚至更为重要。例如,假设我正在使用一些天体观测来估计哈...
Schiphol-Hub/schiphol-geo-notebooks
Creating_schiphol_map.ipynb
gpl-3.0
from arcgis.gis import * from arcgis.viz import MapView from IPython.display import display """ Explanation: Create a Schiphol map using Arcgis online and Jupyter notebook Documentation for the beta Esri Arcgis Python API can be found here: http://esri.github.io/arcgis-python-api/apidoc/html/index.html End of explana...
goyalsid/phageParser
demos/Spacer Length Analysis.ipynb
mit
%matplotlib inline #Import packages import requests import json import numpy as np import random import matplotlib.pyplot as plt from matplotlib import mlab import seaborn as sns import pandas as pd from scipy.stats import poisson sns.set_palette("husl") #Url of the phageParser API apiurl = 'https://phageparser.herok...
amueller/scipy-2017-sklearn
notebooks/10.Case_Study-Titanic_Survival.ipynb
cc0-1.0
from sklearn.datasets import load_iris iris = load_iris() print(iris.data.shape) """ Explanation: Case Study - Titanic Survival Feature Extraction Here we will talk about an important piece of machine learning: the extraction of quantitative features from data. By the end of this section you will Know how features...
TUW-GEO/pygeogrids
docs/examples/creating_and_working_with_grid_objects.ipynb
mit
import pygeogrids.grids as grids import numpy as np """ Explanation: Basics End of explanation """ # create the longitudes lons = np.arange(-180 + 5, 180, 10) print(lons) lats = np.arange(90 - 5, -90, -10) print(lats) """ Explanation: Let's create a simple regular 10x10 degree grid with grid points at the center of...
amcdawes/QMlabs
Lab 3 - Operators.ipynb
mit
import matplotlib.pyplot as plt from numpy import sqrt,cos,sin,arange,pi from qutip import * %matplotlib inline H = Qobj([[1],[0]]) V = Qobj([[0],[1]]) P45 = Qobj([[1/sqrt(2)],[1/sqrt(2)]]) M45 = Qobj([[1/sqrt(2)],[-1/sqrt(2)]]) R = Qobj([[1/sqrt(2)],[-1j/sqrt(2)]]) L = Qobj([[1/sqrt(2)],[1j/sqrt(2)]]) """ Explanatio...
ray-project/ray
doc/source/tune/examples/tune-wandb.ipynb
apache-2.0
import numpy as np import wandb from ray import tune from ray.tune import Trainable from ray.tune.integration.wandb import ( WandbLoggerCallback, WandbTrainableMixin, wandb_mixin, ) """ Explanation: Using Weights & Biases with Tune (tune-wandb-ref)= Weights & Biases (Wandb) is a tool for experiment tracki...
tensorflow/docs-l10n
site/zh-cn/hub/tutorials/text_classification_with_tf_hub.ipynb
apache-2.0
# Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
gprakhar/janCC
Janacare_User-Segmentation_dataset_Aug2014-Apr2016.ipynb
bsd-3-clause
# This to clear all variable values %reset # Import the required modules import pandas as pd import numpy as np #import scipy as sp # simple function to read in the user data file. # the argument parse_dates takes in a list of colums, which are to be parsed as date format user_data_raw = pd.read_csv("janacare_user-en...
wikistat/Ateliers-Big-Data
CatsVSDogs/Atelier-keras-CatsVSDogs.ipynb
mit
# Utils import sys import os import shutil import time import pickle import numpy as np # Deep Learning Librairies import tensorflow as tf import keras.preprocessing.image as kpi import keras.layers as kl import keras.optimizers as ko import keras.backend as k import keras.models as km import keras.applications as ka ...
eblur/AstroHackWeek2015
day3-machine-learning/09.1 - Linear models.ipynb
gpl-2.0
from sklearn.datasets import make_regression from sklearn.cross_validation import train_test_split X, y, true_coefficient = make_regression(n_samples=80, n_features=30, n_informative=10, noise=100, coef=True, random_state=5) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=5) print(X_train.shape)...
tedunderwood/horizon
chapter3/notebooks/chapter3table3.ipynb
mit
# some standard modules import csv, os, sys from collections import Counter import numpy as np from scipy.stats import pearsonr # now a module that I wrote myself, located # a few directories up, in the software # library for this repository sys.path.append('../../lib') import FileCabinet as filecab """ Explanatio...
landmanbester/fundamentals_of_interferometry
7_Observing_Systems/7_8_rfi.ipynb
gpl-2.0
import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML HTML('../style/course.css') #apply general CSS """ Explanation: Outline Glossary 7. Observing Systems Previous: 7.7 Propagation Effects Next: 7.x Further Reading and References Import standard modules: End of ...
shngli/Data-Mining-Python
Mining massive datasets/association.ipynb
gpl-3.0
from __future__ import division import itertools import operator from sys import argv support = 99 mappings = [] itemCounts = [] transactions = 0 """ Explanation: Association Rules Use the online browsing behavior dataset "browsing.txt". Each line represents a browsing session of a customer. On each line, each s...
datascience-course/datascience-course.github.io
2016/assets/slides/03-hypothesis-testing-1.ipynb
mit
import scipy as sc from scipy.stats import bernoulli from scipy.stats import binom from scipy.stats import norm import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (10, 6) """ Explanation: Introduction to Data Science, CS 5963 / Math 3900 Lecture 3: Hypothesis Testing I In this lectur...
maigimenez/trolls
Notebooks/0. Gather data.ipynb
mit
config = ConfigParser() config.read(join(pardir,'src','credentials.ini')) APP_KEY = config['twitter']['app_key'] APP_SECRET = config['twitter']['app_secret'] OAUTH_TOKEN = config['twitter']['oauth_token'] OAUTH_TOKEN_SECRET = config['twitter']['oauth_token_secret'] from twitter import oauth, Twitter, TwitterHTTPErr...
kaka0525/Process-Bike-Share-data-with-Pandas
bikeshare.ipynb
mit
import pandas as pd import numpy as np weather = pd.read_table("daily_weather.tsv") usage = pd.read_table("usage_2012.tsv") station = pd.read_table("stations.tsv") """ Explanation: <strong>Process Bike-Share data with Pandas</strong> End of explanation """ weather mean = weather.groupby('season_desc')['temp'].m...
NLeSC/noodles
notebooks/An interactive introduction.ipynb
apache-2.0
from noodles import schedule @schedule def add(x, y): return x + y @schedule def mul(x,y): return x * y """ Explanation: An interactive introduction to Noodles: translating Poetry Noodles is there to make your life easier, in parallel! The reason why Noodles can be easy and do parallel Python at the same tim...
dsacademybr/PythonFundamentos
Cap07/DesafioDSA/Missao2/missao2.ipynb
gpl-3.0
# Versão da Linguagem Python from platform import python_version print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version()) """ Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 7</font> Download: http://github.com/dsacademybr End of explanation """ import ...
YuriyGuts/kaggle-quora-question-pairs
notebooks/preproc-extract-unique-questions.ipynb
mit
from pygoose import * import nltk """ Explanation: Preprocessing: Unique Question Corpus Based on the training and test sets, extract a list of unique documents. Imports This utility package imports numpy, pandas, matplotlib and a helper kg module into the root namespace. End of explanation """ project = kg.Project...
phoebe-project/phoebe2-docs
2.3/tutorials/meshes.ipynb
gpl-3.0
#!pip install -I "phoebe>=2.3,<2.4" import phoebe logger = phoebe.logger() b = phoebe.default_binary() """ Explanation: Advanced: Accessing and Plotting Meshes Setup Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab)....
tclaudioe/Scientific-Computing
SC1/10_GMRes.ipynb
bsd-3-clause
import numpy as np import scipy as sp from scipy import linalg as la import matplotlib.pyplot as plt import scipy.sparse.linalg %matplotlib inline #%load_ext memory_profiler import matplotlib as mpl mpl.rcParams['font.size'] = 14 mpl.rcParams['axes.labelsize'] = 20 mpl.rcParams['xtick.labelsize'] = 14 mpl.rcParams['yti...
megbedell/wobble
notebooks/espresso.ipynb
mit
data = wobble.Data() filenames = glob.glob('/Users/mbedell/python/wobble/data/toi/TOI-*_CCF_A.fits') for filename in tqdm(filenames): try: sp = wobble.Spectrum() sp.from_ESPRESSO(filename, process=True) data.append(sp) except Exception as e: print("File {0} failed; error: {1}".f...
spectralDNS/shenfun
binder/stokes.ipynb
bsd-2-clause
import os import sys import numpy as np from sympy import symbols, sin, cos from shenfun import * """ Explanation: <!-- dom:TITLE: Demo - Stokes equations --> Demo - Stokes equations <!-- dom:AUTHOR: Mikael Mortensen Email:mikaem@math.uio.no at Department of Mathematics, University of Oslo. --> <!-- Author: --> Mikael...
pcm-ca/pcm-ca.github.io
pages/informatication/extra-files/codes/notebooks/Ajustes.ipynb
mit
%matplotlib inline import matplotlib.pyplot as plt import numpy as np medidas = np.random.normal(0, 1, size=100) plt.figure() plt.plot(medidas, '.') plt.axhline(y=0, ls='--', c='k') plt.show() medidas = np.random.normal(0, 0.1, size=100) plt.figure() plt.plot(medidas, '.') plt.axhline(y=0, ls='--', c='k') plt.show(...
mne-tools/mne-tools.github.io
0.16/_downloads/plot_label_from_stc.ipynb
bsd-3-clause
# Author: Luke Bloy <luke.bloy@gmail.com> # Alex Gramfort <alexandre.gramfort@telecom-paristech.fr> # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne.minimum_norm import read_inverse_operator, apply_inverse from mne.datasets import sample print(__doc__) data_pa...
atulsingh0/MachineLearning
HandsOnML/code/10_introduction_to_artificial_neural_networks.ipynb
gpl-3.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 def reset_graph(seed=42): tf.reset_default_graph() tf.set_random_seed(seed) np.random.seed(seed) # To...
jGaboardi/Facility_Location
Gurobi_v_Cplex__Set_Cover.ipynb
lgpl-3.0
import pysal as ps import numpy as np import networkx as nx import shapefile as shp import gurobipy as gbp import cplex as cp import datetime as dt import time from collections import OrderedDict import IPython.display as IPd %pylab inline from mpl_toolkits.basemap import Basemap """ Explanation: <font size='5' face='...
kdmurray91/kwip-experiments
writeups/coalescent/50reps_2016-05-18/sqrt-dist.ipynb
mit
expts = list(map(lambda fp: path.basename(fp.rstrip('/')), glob('data/*/'))) print("Number of replicate experiments:", len(expts)) def process_expt(expt): expt_results = [] def extract_info(filename): return re.search(r'kwip/(\d\.?\d*)x-(0\.\d+)-(wip|ip).dist', filename).groups() def r_sqrt(tr...
mne-tools/mne-tools.github.io
0.22/_downloads/243172b1ef6a2d804d3245b8c0a927ef/plot_60_maxwell_filtering_sss.ipynb
bsd-3-clause
import os import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np import mne from mne.preprocessing import find_bad_channels_maxwell sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', ...
boffi/boffi.github.io
dati_2016/08/Subspace2.ipynb
mit
def redeigh(K, M, phi): """Solves the reduced eigenproblem in subspace iteration method. Input: phi, a 2-d array containing the current subspace; output: 1. 1-d array of eigenvalues estimates; 2. 2-d array of eigenvector estimates in Ritz coordinates.""" # compute the reduced matrices ...
AjinkyaBhave/CarND_P1_FindLanes
P1.ipynb
agpl-3.0
#importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 import os import math from scipy import misc %matplotlib inline # Import everything needed to edit/save/watch video clips from moviepy.editor import VideoFileClip from IPython.display import H...
ernestyalumni/MLgrabbag
sklearn_ML.ipynb
mit
%matplotlib inline import matplotlib.pyplot as plt import sklearn from sklearn import datasets import os, sys os.getcwd() os.listdir( os.getcwd() ) ; import numpy as np import scipy import pandas as pd """ Explanation: Using sci-kit learn, i.e. sklearn for Machine Learning (ML); in combination with numpy,scipy, an...
CentreForResearchInAppliedLinguistics/clic
docs/notebooks/Cheshire/.ipynb_checkpoints/Cheshire objects and methods-checkpoint.ipynb
mit
# coding: utf-8 import os from cheshire3.baseObjects import Session from cheshire3.document import StringDocument from cheshire3.internal import cheshire3Root from cheshire3.server import SimpleServer session = Session() session.database = 'db_dickens' serv = SimpleServer(session, os.path.join(cheshire3Root, 'con...
meta-mind/workspace
kaggle/Titanic: Machine Learning from Disaster/scripts/Titanic Machine Learning from Disaster.ipynb
mit
import pandas as pd """ Explanation: Titanic: Machine Learning from Disaster Get the Data with Pandas Import the Pandas library End of explanation """ train_url = "http://s3.amazonaws.com/assets.datacamp.com/course/Kaggle/train.csv" train = pd.read_csv(train_url) test_url = "http://s3.amazonaws.com/assets.datacamp....
jinntrance/MOOC
coursera/ml-foundations/week5/Song recommender.ipynb
cc0-1.0
import graphlab """ Explanation: Building a song recommender Fire up GraphLab Create End of explanation """ song_data = graphlab.SFrame('song_data.gl/') """ Explanation: Load music data End of explanation """ song_data.head() """ Explanation: Explore data Music data shows how many times a user listened to a song...
tangsttw/python_tips_and_notes
pandas/pandas.ipynb
mit
import pandas as pd import numpy as np """ Explanation: pandas THis notebook records some tips for the pandas module End of explanation """ df = pd.DataFrame(np.random.randint(0,100,size=(10, 4)), columns=list('ABCD')) df """ Explanation: Create dataframe Create a dataframe of random integers End of explanation ...
prasants/pyds
11.Introduction_to_Numpy.ipynb
mit
import numpy as np # Create an array with the statement np.array a = np.array([1,2,3,4]) print('a is of type:', type(a)) print('dimension of a:', a.ndim) # To find the dimension of 'a' arr1 = np.array([1,2,3,4]) arr1.ndim arr2 = np.array([[1,2],[2,3],[3,4],[4,5]]) arr2.ndim # Doesn't make a difference to a computer...
dryadb11781/machine-learning-python
Classification/ipython_notebook/EX2.ipynb
bsd-3-clause
%matplotlib inline from __future__ import division import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_blobs from sklearn.discriminant_analysis import LinearDiscriminantAnalysis n_train = 20 # samples for training n_test = 200 # samples for testing n_averages = 50 # how often to re...
GoogleCloudPlatform/mlops-on-gcp
model_serving/caip-load-testing/02-perf-testing.ipynb
apache-2.0
%pip install -q -U locust google-cloud-monitoring google-cloud-logging google-cloud-monitoring-dashboards # Automatically restart kernel after installs import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True) """ Explanation: AI Platform Prediction Load Testing using Locust This Notebook dem...
LaubachLab/Spikes-and-Fields
Working with NEx files using oct2py.ipynb
gpl-3.0
import numpy as np from scipy.io import loadmat %load_ext oct2py.ipython %cd ~/Desktop/Spikes-and-Fields/NEx-demo """ Explanation: This post demonstrates how oct2py can be used to run legacy Matlab/Octave code to load data saved in NeuroExplorer files into Python. As will be illustrated in a forthcoming post, this sa...
xiongzhenggang/xiongzhenggang.github.io
AI/ML/week4反向传播实现.ipynb
gpl-3.0
import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib from scipy.io import loadmat from sklearn.preprocessing import OneHotEncoder data = loadmat('../data/andrew_ml_ex33507/ex3data1.mat') data X = data['X'] y = data['y'] X.shape, y.shape#看下维度 # 目前考虑输入是图片的像素值,20*20像素的图片有400个输入层单元,...
quantumlib/OpenFermion-FQE
docs/tutorials/hamiltonian_time_evolution_and_expectation_estimation.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...
kubeflow/pipelines
components/gcp/dataproc/create_cluster/sample.ipynb
apache-2.0
%%capture --no-stderr !pip3 install kfp --upgrade """ Explanation: Name Data processing by creating a cluster in Cloud Dataproc Label Cloud Dataproc, cluster, GCP, Cloud Storage, KubeFlow, Pipeline Summary A Kubeflow Pipeline component to create a cluster in Cloud Dataproc. Details Intended use Use this component at ...
rajul/tvb-library
tvb/simulator/demos/display_region_connectivity.ipynb
gpl-2.0
from tvb.simulator.lab import * """ Explanation: Plot regions and connection edges. Xmas balls scaled is in the range [0 - 1], representing the cumulative input to each region. End of explanation """ white_matter = connectivity.Connectivity(load_default=True) #Compute cumulative input for each region node_data = wh...
JAmarel/LiquidCrystals
ElectroOptics/CurveFitAttempt.ipynb
mit
import numpy as np from scipy.integrate import quad, dblquad %matplotlib inline import matplotlib.pyplot as plt import scipy.optimize as opt """ Explanation: TO DO: Need to be able to scatter plot measured values of Psi on top of the current Psi plot. Alpha and rho LaTeX not working in plots. Legend needs to be move i...
qinwf-nuan/keras-js
notebooks/layers/convolutional/ZeroPadding1D.ipynb
mit
data_in_shape = (3, 5) L = ZeroPadding1D(padding=1) layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(240) data_in = 2 * np.random.random(data_in_shape) - 1 result = model.predict(np.array([dat...
tensorflow/docs-l10n
site/en-snapshot/probability/examples/TFP_Release_Notebook_0_12_1.ipynb
apache-2.0
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # 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, sof...
mne-tools/mne-tools.github.io
0.12/_downloads/plot_clickable_image.ipynb
bsd-3-clause
# Authors: Christopher Holdgraf <choldgraf@berkeley.edu> # # License: BSD (3-clause) from scipy.ndimage import imread import numpy as np from matplotlib import pyplot as plt from os import path as op import mne from mne.viz import ClickableImage, add_background_image # noqa from mne.channels import generate_2d_layout ...
ktmud/deep-learning
first-neural-network/Your_first_neural_network.solution.ipynb
mit
%matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt """ Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code...
cokelaer/colormap
notebooks/colormap package demonstration.ipynb
bsd-3-clause
%pylab inline from colormap import Colormap c = Colormap() cmap = c.cmap('cool') # let us see what it looks like c.test_colormap(cmap) #Would be nice to plot a bunch of colormap to pick up one interesting c.plot_colormap('diverging') c.plot_colormap(c.misc) c.plot_colormap(c.qualitative) c.plot_colormap(c.sequen...
kimkipyo/dss_git_kkp
통계, 머신러닝 복습/160502월_1일차_분석 환경, 소개/16.Pandas 데이터 입출력.ipynb
mit
%cd /home/dockeruser/data/pydata-book-master/ """ Explanation: Pandas 데이터 입출력 이 노트북의 예제를 실행하기 위해서는 datascienceschool/rpython 도커 이미지의 다음 디렉토리로 이동해야 한다. End of explanation """ !cat ../../pydata-book-master/ch06/ex1.csv !cat ch06/ex1.csv df = pd.read_csv('../../pydata-book-master/ch06/ex1.csv') df """ Explanation: p...
piyushbhattacharya/machine-learning
python/Carvan script.ipynb
gpl-3.0
ld_train, ld_test = train_test_split(cd_train, test_size=0.2, random_state=2) x80_train = ld_train.drop(['V86'],1) y80_train = ld_train['V86'] x20_test = ld_test.drop(['V86'],1) y20_test = ld_test['V86'] """ Explanation: Optimizing model... Run train_test splits on the train data End of explanation """ model_logr1...
tonyfast/tidy-harness
README.ipynb
bsd-3-clause
import harness from harness import Harness from pandas import Categorical from sklearn import datasets, discriminant_analysis iris = datasets.load_iris() # Harness is just a dataframe df = Harness( data=iris['data'], index=Categorical(iris['target']), estimator=discriminant_analysis.LinearDiscriminantAnalysis...
massie/notebooks
Physio.ipynb
apache-2.0
from math import log # RT/F = 26.73 at room temperature rt_div_f = 26.73 nernst = lambda xO, xI, z: rt_div_f/z * log(1.0 * xO / xI) Na_Eq = nernst(145, 15, 1) K_Eq = nernst(4.5, 120, 1) Cl_Eq = nernst(116, 20, -1) print "Na+ equilibrium potential is %.2f mV" % (Na_Eq) print "K+ equilibrium potential is %.2f mV" % (K...
GoogleCloudPlatform/training-data-analyst
courses/machine_learning/deepdive2/art_and_science_of_ml/labs/neural_network.ipynb
apache-2.0
import os, json, math import numpy as np import shutil import tensorflow as tf print("TensorFlow version: ",tf.version.VERSION) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # SET TF ERROR LOG VERBOSITY """ Explanation: Build a DNN using the Keras Functional API Learning objectives Review how to read in CSV file data usi...
tsarouch/python_minutes
core/Hypothesis_Testing.ipynb
gpl-2.0
import random import pandas as pd import numpy as np import matplotlib.pyplot as plt """ Explanation: Common Use Cases when dealing with Hypothesis Testing End of explanation """ # se have: n_h = 140 n_t = 110 observations = (n_h, n_t) n_observations = n_h + n_t print observations, n_observations, # We define the ...
materialsvirtuallab/matgenb
notebooks/2021-5-12-Explanation of Corrections.ipynb
bsd-3-clause
from pymatgen.entries.computed_entries import ComputedEntry from pymatgen.entries.compatibility import MaterialsProjectCompatibility, \ MaterialsProject2020Compatibility from pymatgen.ext.matproj import MPRester """ Explanation: Demonstration of Materials Project Energy Corre...
simulkade/peteng
python/.ipynb_checkpoints/two_phase_1D_fipy-checkpoint.ipynb
mit
from fipy import * # relperm parameters swc = 0.1 sor = 0.1 krw0 = 0.3 kro0 = 1.0 nw = 2.0 no = 2.0 # domain and boundaries k = 1e-12 # m^2 phi = 0.4 u = 1.e-5 p0 = 100e5 # Pa Lx = 100. Ly = 10. nx = 100 ny = 10 dx = Lx/nx dy = Ly/ny # fluid properties muo = 0.002 muw = 0.001 # define the fractional flow functions ...
nadvamir/deep-learning
image-classification/dlnd_image_classification.ipynb
mit
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' # Use Floyd's cifar-10 dataset if present floyd_cifar10...