repo_name stringlengths 6 77 | path stringlengths 8 215 | license stringclasses 15
values | content stringlengths 335 154k |
|---|---|---|---|
suriyan/ethnicolr | ethnicolr/examples/ethnicolr_app_contrib2010.ipynb | mit | import pandas as pd
df = pd.read_csv('/opt/names/fec_contrib/contribDB_2010.csv.zip', nrows=100)
df.columns
"""
Explanation: Application: Illustrating the use of the package by imputing the race of the campaign contributors recorded by FEC for the years 2000 and 2010
a) what proportion of contributors were black, whi... |
omoju/udacityUd120Lessons | Text Learning.ipynb | gpl-3.0 | from_sara = open('../text_learning/from_sara.txt', "r")
from_chris = open('../text_learning/from_chris.txt', "r")
from_data = []
word_data = []
from nltk.stem.snowball import SnowballStemmer
import string
filePath = '/Users/omojumiller/mycode/hiphopathy/HipHopDataExploration/JayZ/'
f = open(filePath+"JayZ_America... |
camillescott/boink | notebooks/LabeledLinearAssembler_review.ipynb | mit | K = 21
graph = khmer.Countgraph(K, 1e6, 4)
labeller = khmer._GraphLabels(graph)
graph.consume(contig)
bubble = mutate_position(contig, 100)
reads = list(itertools.chain(reads_from_sequence(contig), reads_from_sequence(bubble)))
random.shuffle(reads)
for n, read in enumerate(reads):
graph.consume(read)
hdns ... |
jrg365/gpytorch | examples/03_Multitask_Exact_GPs/Multitask_GP_Regression.ipynb | mit | import math
import torch
import gpytorch
from matplotlib import pyplot as plt
%matplotlib inline
%load_ext autoreload
%autoreload 2
"""
Explanation: Multitask GP Regression
Introduction
Multitask regression, introduced in this paper learns similarities in the outputs simultaneously. It's useful when you are performin... |
meli-lewis/pygotham2015 | jupyter_panda.ipynb | mit | from __future__ import division
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import rpy2
from IPython.display import display, Image, YouTubeVideo
%matplotlib inline
"""
Explanation: Introduction to data munging with Jupyter and pandas
PyGotham... |
royalosyin/Python-Practical-Application-on-Climate-Variability-Studies | ex04-Read nino3 SSTA series in npz format, plot and save the image.ipynb | mit | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt # to generate plots
"""
Explanation: Read nino3 SSTA time series, Plot and Save the image
In this noteboo, we will finish the following operations
* read time series data produced bya previous notebook
* have a quick plot
* decorate plots
*... |
arnoldlu/lisa | ipynb/examples/devlib/cgroups_example.ipynb | apache-2.0 | import logging
from conf import LisaLogging
LisaLogging.setup()
import os
import json
import operator
import devlib
import trappy
import bart
from bart.sched.SchedMultiAssert import SchedMultiAssert
from wlgen import RTA, Periodic
"""
Explanation: Cgroups
cgroups (abbreviated from control groups) is a Linux kernel ... |
HaFl/ufldl-tutorial-python | Gradient_Checking.ipynb | mit | data_original = np.loadtxt('stanford_dl_ex/ex1/housing.data')
data = np.insert(data_original, 0, 1, axis=1)
np.random.shuffle(data)
train_X = data[:400, :-1]
train_y = data[:400, -1]
m, n = train_X.shape
theta = np.random.rand(n)
"""
Explanation: Preparation (Based on Linear Regression)
Prepare train and test data.
E... |
GoogleCloudPlatform/asl-ml-immersion | notebooks/bigquery/solutions/c_extract_and_benchmark.ipynb | apache-2.0 | import pandas as pd
from google.cloud import bigquery
PROJECT = !gcloud config get-value project
PROJECT = PROJECT[0]
%env PROJECT=$PROJECT
"""
Explanation: Extract Datasets and Establish Benchmark
Learning Objectives
- Divide into Train, Evaluation and Test datasets
- Understand why we need each
- Pull data out of ... |
f-guitart/data_mining | notes/96 - Summary - Indexing and Apllying Functions.ipynb | gpl-3.0 | import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(8, 4), columns=['A', 'B', 'C', 'D'])
df["A"] #indexing
df.A #attribute
type(df.A)
df.A[0]
df[["A","B"]]
type(df[["A","B"]])
"""
Explanation: Series/Dataframes slicing and function application
Slicing
(from panda docs: https://pandas.pydata... |
alorenzo175/pvlib-python | docs/tutorials/pvsystem.ipynb | bsd-3-clause | # built-in python modules
import os
import inspect
import datetime
# scientific python add-ons
import numpy as np
import pandas as pd
# plotting stuff
# first line makes the plots appear in the notebook
%matplotlib inline
import matplotlib.pyplot as plt
# seaborn makes your plots look better
try:
import seaborn ... |
sdpython/ensae_teaching_cs | _doc/notebooks/td1a_home/2020_tsp.ipynb | mit | from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline
"""
Explanation: Algo - TSP - Traveling Salesman Problem
TSP, Traveling Salesman Problem ou Problème du Voyageur de Commerce est un problème classique. Il s'agit de trouver le plus court chemin passant par des villes en supposant qu'il... |
taylort7147/udacity-projects | titanic_survival_exploration/Titanic_Survival_Exploration.ipynb | mit | import numpy as np
import pandas as pd
# RMS Titanic data visualization code
from titanic_visualizations import survival_stats
from IPython.display import display
%matplotlib inline
# Load the dataset
in_file = 'titanic_data.csv'
full_data = pd.read_csv(in_file)
# Print the first few entries of the RMS Titanic data... |
Kaggle/learntools | notebooks/intro_to_programming/raw/tut3.ipynb | apache-2.0 | x = 14
print(x)
print(type(x))
"""
Explanation: Introduction
Whenever you create a variable in Python, it has a value with a corresponding data type. There are many different data types, such as integers, floats, booleans, and strings, all of which we'll cover in this lesson. (This is just a small subset of the avai... |
NAU-CFL/Python_Learning_Source | reference_notebooks/Notes-05.ipynb | mit | bruce = 5
print(bruce)
bruce = 7
print(bruce)
"""
Explanation: Iteration
Multiple Assignments
It's legal to assign a new value to an existing variable. A new assignment makes an existing variable refer to a new value (and stop referring to the old value).
End of explanation
"""
a = 5
print("a is: ", a)
b = a # a and... |
google/starthinker | colabs/mapping.ipynb | apache-2.0 | !pip install git+https://github.com/google/starthinker
"""
Explanation: Column Mapping
Use sheet to define keyword to column mappings.
License
Copyright 2020 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 co... |
mne-tools/mne-tools.github.io | dev/_downloads/775a4c9edcb81275d5a07fdad54343dc/channel_epochs_image.ipynb | bsd-3-clause | # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD-3-Clause
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
"""
Explanation: Visualize channel over epochs as an image
This will p... |
bmorris3/salter | stats_vis.ipynb | mit | [n for n in table.colnames if n.startswith('ks')]
p = table['ttest:out_of_transit&before_midtransit-vs-out_of_transit&after_midtransit']
poorly_normalized_oot_threshold = -1
mask_poorly_normalized_oot = np.log(p) > poorly_normalized_oot_threshold
plt.hist(np.log(p[~np.isnan(p)]))
plt.axvline(poorly_normalized_oot_... |
jstac/quantecon_nyu_2016 | lecture7/Intro_to_pymc.ipynb | bsd-3-clause | %matplotlib inline
import numpy as np
import scipy as sp
import pymc as pm
import seaborn as sb
import matplotlib.pyplot as plt
"""
Explanation: Intorduction to PyMC2
Balint Szoke
Installation:
>> conda install pymc
End of explanation
"""
def sample_path(rho, sigma, T, y0=None):
'''
Simulates the sam... |
tensorflow/docs-l10n | site/zh-cn/quantum/tutorials/qcnn.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... |
dewitt-li/deep-learning | first-neural-network/Your_first_neural_network.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... |
diegocavalca/Studies | deep-learnining-specialization/2. improving deep neural networks/resources/Regularization.ipynb | cc0-1.0 | # import packages
import numpy as np
import matplotlib.pyplot as plt
from reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_dec
from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters
import sklearn
import sklearn.da... |
ES-DOC/esdoc-jupyterhub | notebooks/bcc/cmip6/models/bcc-csm2-hr/ocean.ipynb | gpl-3.0 | # DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'bcc', 'bcc-csm2-hr', 'ocean')
"""
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: BCC
Source ID: BCC-CSM2-HR
Topic: Ocean
Sub-Topics: Timestepping Framework, Advecti... |
nick-youngblut/SIPSim | ipynb/bac_genome/n1210/qSIP/qSIP_dev.ipynb | mit | supInfoFile = '/home/nick/notebook/SIPSim/dev/qSIP/PeerJ_qSIP_preprint/PeerJ_Supplemental_Information.pdf'
"""
Explanation: Developing a simulation methodology for the qSIP method
Method:
qPCR simulation
mean quantifications derived from the absolute count data
variance derived from qSIP paper
values will be multipli... |
pysg/pyther | Modelo de impregnacion/modelo1/Actividad 8 Simulación de impregnación de LDPE.ipynb | mit | import numpy as np
import pandas as pd
import math
import cmath
from scipy.optimize import root
import matplotlib.pyplot as plt
%matplotlib inline
"""
Explanation: Simulación de impregnación de LDPE
Introduction
Ce programme nous permet de modéliser la concentration (c2) pour différents food simulant. Cela nous permet... |
NYUDataBootcamp/Projects | MBA_S17/Sasidharan.ipynb | mit | import pandas as pd # Importing necessary data package
import matplotlib.pyplot as plt # pyplot module
import numpy as np
"""
Explanation: Python Real Estate Analysis Project
May 2017
Written by Divya Sasidharan at NYU Stern
Contact: ds5151@nyu.edu
Overview
Real estate is an active area in b... |
statsmodels/statsmodels.github.io | v0.12.2/examples/notebooks/generated/contrasts.ipynb | bsd-3-clause | import numpy as np
import statsmodels.api as sm
"""
Explanation: Contrasts Overview
End of explanation
"""
import pandas as pd
url = 'https://stats.idre.ucla.edu/stat/data/hsb2.csv'
hsb2 = pd.read_table(url, delimiter=",")
hsb2.head(10)
"""
Explanation: This document is based heavily on this excellent resource fro... |
bjshaw/phys202-2015-work | assignments/assignment08/InterpolationEx01.ipynb | mit | %matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from scipy.interpolate import interp1d
"""
Explanation: Interpolation Exercise 1
End of explanation
"""
f = open('trajectory.npz','r')
r = np.load('trajectory.npz')
t = r['t']
y = r['y']
x = r['x']
f.close()
assert isinsta... |
Caranarq/01_Dmine | Datasets/LEED/LEED.ipynb | gpl-3.0 | # Librerias utilizadas
import pandas as pd
import sys
import os
import csv
from lxml import html
import requests
import time
# Configuracion del sistema
print('Python {} on {}'.format(sys.version, sys.platform))
print('Pandas version: {}'.format(pd.__version__))
import platform; print('Running on {} {}'.format(platfor... |
LucaCanali/Miscellaneous | Impala_SQL_Jupyter/Impala_Basic.ipynb | apache-2.0 | from impala.dbapi import connect
conn = connect(host='impalasrv-test', port=21050)
"""
Explanation: IPython/Jupyter notebooks for Apache Impala
1. Connect to the target database (requires Cloudera impyla package)
End of explanation
"""
cur = conn.cursor()
cur.execute('select * from test2.emp limit 2')
cur.fetchall... |
jeffzhengye/pylearn | tensorflow_learning/tf2/notebooks/transfer_learning.ipynb | unlicense | import numpy as np
import tensorflow as tf
from tensorflow import keras
"""
Explanation: Transfer learning & fine-tuning
Author: fchollet<br>
Date created: 2020/04/15<br>
Last modified: 2020/05/12<br>
Description: Complete guide to transfer learning & fine-tuning in Keras.
Setup
End of explanation
"""
layer = keras.... |
NlGG/MachineLearning | NeuralNetwork/auto_encorder_and_rnn.ipynb | mit | %matplotlib inline
import numpy as np
import pylab as pl
import math
from sympy import *
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
from nn import NN
"""
Explanation: 今回のレポートでは、①オートエンコーダの作成、②再帰型ニューラルネットワークの作成を試みた。
①コブダクラス型生産関数を再現できるオートエンコーダの作成が目標... |
GuidoBR/python-for-finance | python-for-finance-investment-fundamentals-data-analytics/1 - Calculating and Comparing Rates of Return in Python/Rate of Return.ipynb | mit | BRK['simple_return'] = (BRK['Close'] / BRK['Close'].shift(1)) - 1
print(BRK['simple_return'])
BRK['simple_return'].plot(figsize=(8,5))
plt.show()
avg_returns_d = BRK['simple_return'].mean()
avg_returns_d
avg_returns_a = avg_returns_d * 250 # multiply by the average number of business days per year
print(str(round(av... |
jotterbach/Data-Exploration-and-Numerical-Experimentation | Numerical-Experimentation/Series of N equals in coin tosses.ipynb | cc0-1.0 | import random as rd
import numpy as np
from numpy.random import choice
import matplotlib.pyplot as plt
import matplotlib
%matplotlib inline
matplotlib.style.use('ggplot')
matplotlib.rc_params_from_file("../styles/matplotlibrc" ).update()
"""
Explanation: Series of N equals in coin tosses
For a fair coin, the question... |
graphistry/pygraphistry | demos/more_examples/graphistry_features/encodings-colors.ipynb | bsd-3-clause | # ! pip install --user graphistry
import graphistry
# To specify Graphistry account & server, use:
# graphistry.register(api=3, username='...', password='...', protocol='https', server='hub.graphistry.com')
# For more options, see https://github.com/graphistry/pygraphistry#configure
graphistry.__version__
import dat... |
vascotenner/holoviews | doc/Tutorials/Elements.ipynb | bsd-3-clause | import holoviews as hv
hv.notebook_extension()
hv.Element(None, group='Value', label='Label')
"""
Explanation: Elements are the basic building blocks for any HoloViews visualization. These are the objects that can be composed together using the various Container types.
Here in this overview, we show an example of how... |
mercye/foundations-homework | 11/Homework_11_Emelike.ipynb | mit | # checks data type of each value in series Plate ID by printing if type does not equal string
# all values are strings
for x in df['Plate ID']:
if type(x) != str:
print(type(x))
"""
Explanation: 1. I want to make sure my Plate ID is a string. Can't lose the leading zeroes!
End of explanation
"""
df['Veh... |
calico/basenji | tutorials/sat_mut.ipynb | apache-2.0 | if not os.path.isfile('data/hg19.ml.fa'):
subprocess.call('curl -o data/hg19.ml.fa https://storage.googleapis.com/basenji_tutorial_data/hg19.ml.fa', shell=True)
subprocess.call('curl -o data/hg19.ml.fa.fai https://storage.googleapis.com/basenji_tutorial_data/hg19.ml.fa.fai', shell=True)
if not ... |
AllenDowney/ModSimPy | notebooks/chap12.ipynb | mit | # Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import functions from the modsim.py module
from modsim import *
"""
Explanation: Modeling and Simulati... |
DJCordhose/ai | notebooks/rl/berater-v11-lower.ipynb | mit | !pip install git+https://github.com/openai/baselines >/dev/null
!pip install gym >/dev/null
"""
Explanation: <a href="https://colab.research.google.com/github/DJCordhose/ai/blob/master/notebooks/rl/berater-v11-lower.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open I... |
Linlinzhao/linlinzhao.github.io | _drafts/.ipynb_checkpoints/understanding backward() in Pytorch-checkpoint.ipynb | mit | import torch as T
import torch.autograd
from torch.autograd import Variable
import numpy as np
"""
Explanation: Having heard about the announcement about Theano from Bengio lab , as a Theano user, I am happy and sad to see the fading of the old hero, caused by many raising stars. Sad to see it is too old to compete wi... |
tensorflow/docs-l10n | site/ko/r1/tutorials/eager/custom_layers.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... |
phobson/pygridtools | docs/tutorial/04_InteractiveWidgets.ipynb | bsd-3-clause | from IPython.display import Audio,Image, YouTubeVideo
YouTubeVideo('S5SG9km2f_A', height=450, width=900)
"""
Explanation: Grid Generation with Interactive Widgets
This notebook demostrates how to use the interative widgets.
See a version of it in action:
End of explanation
"""
%matplotlib inline
import warnings
war... |
tkas/osmose-backend | doc/3_0-SQL-minimal.ipynb | gpl-3.0 | sql10 = """
SELECT
nodes.id,
ST_AsText(nodes.geom) AS geom
FROM
nodes
JOIN ways ON
ways.tags != ''::hstore AND
ways.tags?'building' AND ways.tags->'building' != 'no' AND
ways.is_polygon AND
ST_Intersects(ST_MakePolygon(ways.linestring), nodes.geom)
WHERE
nodes.tags !=... |
bollwyvl/ipytangle | notebooks/examples/Tangling up interact.ipynb | bsd-3-clause | from IPython.html.widgets import interact
from math import (sin, cos, tan)
from ipytangle import tangle
"""
Explanation: Tangling up interact
IPython's interact can do some things that are awkward with straight widgets, such as generating plots. It will magically make built-in widgets from some simple settings objects... |
mkuron/espresso | doc/tutorials/08-visualization/08-visualization.ipynb | gpl-3.0 | from matplotlib import pyplot
import espressomd
import numpy
espressomd.assert_features("LENNARD_JONES")
# system parameters (10000 particles)
box_l = 10.7437
density = 0.7
# interaction parameters (repulsive Lennard-Jones)
lj_eps = 1.0
lj_sig = 1.0
lj_cut = 1.12246
lj_cap = 20
# integration parameters
system = esp... |
FordyceLab/AcqPack | examples/imaging_and_gui.ipynb | mit | # test image stack
arr = []
for i in range(50):
b = np.random.rand(500,500)
b= (b*(2**16-1)).astype('uint16')
arr.append(b)
# snap (MPL)
button = widgets.Button(description='Snap')
display.display(button)
def on_button_clicked(b):
img=arr.pop()
plt.imshow(img, cmap='gray')
display.clear_ou... |
gronnbeck/udacity-deep-learning | language-translation/dlnd_language_translation.ipynb | mit | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
"""
Explanation: Language Translation
In this project, you’re going... |
dipanjank/ml | algorithms/0_1_knapsack.ipynb | gpl-3.0 | import pandas as pd
import numpy as np
# Solve the problem for this toy example
weights = [5, 4, 6, 3]
values = [10, 50, 30, 50]
W = 10
# Handy data structure to refer to values and weights easily
items_df = pd.DataFrame(
index=range(1, len(weights)+1),
data=list(zip(weights, values)),
columns=['weights'... |
datascience-practice/data-quest | python_introduction/beginner/booleans-and-if-statements.ipynb | mit | cat = True
dog = False
print(type(cat))
"""
Explanation: 1: Booleans
Instructions
Assign the value True to the variable cat and the value False to the variable dog. Then use the print() function and the type() function to display the type for cat.
Answer
End of explanation
"""
from cities import cities
print(citie... |
lukassnoek/ICON2017 | tutorial/ICON2017_tutorial_answers.ipynb | mit | # First, we need to import some Python packages
import numpy as np
import pandas as pd
import os.path as op
import warnings
import matplotlib.pyplot as plt
plt.style.use('classic')
warnings.filterwarnings("ignore")
%matplotlib inline
# The onset times are loaded as pandas dataframe with three columns:
# onset times (... |
dwhswenson/openpathsampling | examples/misc/move_strategies_and_schemes.ipynb | mit | %matplotlib inline
import openpathsampling as paths
from openpathsampling.visualize import PathTreeBuilder, PathTreeBuilder
from IPython.display import SVG, HTML
import openpathsampling.high_level.move_strategy as strategies # TODO: handle this better
# real fast setup of a small network
cvA = paths.FunctionCV(name="... |
nicoguaro/notebooks_examples | elasticity_fdm.ipynb | mit | from sympy import *
from continuum_mechanics.vector import lap, sym_grad
from continuum_mechanics.solids import navier_cauchy, strain_stress
init_printing()
x, y = symbols("x y")
lamda, mu, h = symbols("lamda mu h")
def construct_poly(pts, terms, var="u"):
npts = len(pts)
u = symbols("{}:{}".format(var, npts... |
pytransitions/transitions | examples/Playground.ipynb | mit | from transitions import Machine
import random
class NarcolepticSuperhero(object):
# Define some states. Most of the time, narcoleptic superheroes are just like
# everyone else. Except for...
states = ['asleep', 'hanging out', 'hungry', 'sweaty', 'saving the world']
# A more compact version of the quic... |
AllenDowney/ModSimPy | notebooks/chap22.ipynb | mit | # Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import functions from the modsim.py module
from modsim import *
"""
Explanation: Modeling and Simulati... |
aleph314/K2 | Data Preprocessing/Preprocessing_exercise.ipynb | gpl-3.0 | import pandas as pd
import numpy as np
"""
Explanation: Data Preprocessing
Imputation
You will often find yourself in a situation where you will be dealing with an incomplete dataset. There are many reasons why data may be missing: survey responses may have been optional, there may have been some sort of data recordi... |
Britefury/deep-learning-tutorial-pydata2016 | TUTORIAL 05 - Dogs vs cats with transfer learning.ipynb | mit | %matplotlib inline
"""
Explanation: Dogs vs Cats with Transfer Learning
In this Notebook we're going to use transfer learning to attempt to crack the Dogs vs Cats Kaggle competition.
We are going to downsample the images to 64x64; that's pretty small, but should be enough (I hope). Furthermore, large images means long... |
shagunsodhani/PyDelhiConf2017 | notebook/Demo.ipynb | mit | def mul(a, b):
return a*b
mul(2, 3)
mul = lambda a, b: a*b
mul(2, 3)
"""
Explanation: Functional Programming in Python <center>
<p>
<p>
Shagun Sodhani
# Functions as first class citizens
End of explanation
"""
mul(mul(2, 3), 3)
def transform_and_add(func, a, b):
return func(a) + func(b)
transform_and_a... |
GoogleCloudPlatform/asl-ml-immersion | notebooks/recommendation_systems/solutions/2_als_bqml.ipynb | apache-2.0 | PROJECT = !(gcloud config get-value core/project)
PROJECT = PROJECT[0]
%env PROJECT=$PROJECT
%%bash
rm -r bqml_data
mkdir bqml_data
cd bqml_data
curl -O 'http://files.grouplens.org/datasets/movielens/ml-20m.zip'
unzip ml-20m.zip
yes | bq rm -r $PROJECT:movielens
bq --location=US mk --dataset \
--description 'Movi... |
cuemacro/finmarketpy | finmarketpy_examples/finmarketpy_notebooks/market_data_example.ipynb | apache-2.0 | import datetime
from chartpy import Chart, Style
from findatapy.market import Market, MarketDataGenerator, MarketDataRequest
# So we don't see deprecated warnings... when you're coding it's usually good to leave these!
import warnings
warnings.filterwarnings('ignore')
# Disable logging messages, to make output tidie... |
abonaca/streakline | example/orbit.ipynb | mit | from __future__ import print_function, division
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import astropy.units as u
from astropy.constants import G
import streakline
%matplotlib inline
mpl.rcParams['figure.figsize'] = (8,8)
mpl.rcParams['font.size'] = 18
"""
Explanation: Orbit in ... |
maojrs/riemann_book | Acoustics_heterogeneous.ipynb | bsd-3-clause | %matplotlib inline
%config InlineBackend.figure_format = 'svg'
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import widgets, interact
from exact_solvers import acoustics_heterogeneous, acoustics_heterogeneous_demos
from utils import riemann_tools
import seaborn as sns
sns.set_style('white',{'legen... |
turbomanage/training-data-analyst | quests/rl/dqn/dqns_on_gcp.ipynb | apache-2.0 | %%bash
BUCKET=<your-bucket-here> # Change to your bucket name
JOB_NAME=dqn_on_gcp_$(date -u +%y%m%d_%H%M%S)
REGION='us-central1' # Change to your bucket region
IMAGE_URI=gcr.io/qwiklabs-resources/rl-qwikstart/dqn_on_gcp@sha256:326427527d07f30a0486ee05377d120cac1b9be8850b05f138fc9b53ac1dd2dc
gcloud ai-platform jobs sub... |
sonyahanson/assaytools | examples/ipynbs/data-analysis/hsa/analyzing_FLU_hsa_lig2_20150922.ipynb | lgpl-2.1 | import numpy as np
import matplotlib.pyplot as plt
from lxml import etree
import pandas as pd
import os
import matplotlib.cm as cm
import seaborn as sns
%pylab inline
# Get read and position data of each fluorescence reading section
def get_wells_from_section(path):
reads = path.xpath("*/Well")
wellIDs = [rea... |
retnuh/deep-learning | sentiment-rnn/Sentiment_RNN.ipynb | mit | import numpy as np
import tensorflow as tf
with open('../sentiment_network/reviews.txt', 'r') as f:
reviews = f.read()
with open('../sentiment_network/labels.txt', 'r') as f:
labels = f.read()
reviews[:2000]
"""
Explanation: Sentiment Analysis with an RNN
In this notebook, you'll implement a recurrent neura... |
Paradigm4/wearable_prototypes | sleep_python3.ipynb | agpl-3.0 | import scidbpy
import getpass
import requests
import warnings
warnings.filterwarnings("ignore")
#requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
db = scidbpy.connect(scidb_url="http://localhost:8080")
"""
Explanation: SciDB and Machine Learning on Wearable Data
T... |
mne-tools/mne-tools.github.io | 0.15/_downloads/plot_3d_to_2d.ipynb | bsd-3-clause | # Authors: Christopher Holdgraf <choldgraf@berkeley.edu>
#
# License: BSD (3-clause)
from scipy.io import loadmat
import numpy as np
from mayavi import mlab
from matplotlib import pyplot as plt
from os import path as op
import mne
from mne.viz import ClickableImage # noqa
from mne.viz import plot_alignment, snapshot_... |
davicsilva/dsintensive | notebooks/WorldUniversityRankings.ipynb | apache-2.0 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
## CWUR 2016 dataset
datacwur2016 = 'data/cwur2016.csv'
cwur2016 = pd.read_csv(datacwur2016)
"""
Explanation: World University Rankings
We can find, at least, three global university rankings with different methodologies to clas... |
RuthAngus/LSST-max | code/LSST_inject_and_recover.ipynb | mit | import numpy as np
import matplotlib.pyplot as plt
from gatspy.periodic import LombScargle
import sys
%matplotlib inline
from toy_simulator import simulate_LSST
from trilegal_models import random_stars
import simple_gyro as sg
import pandas as pd
"""
Explanation: Recovering rotation periods in simulated LSST data
End ... |
maxkleiner/maXbox4 | ARIMA_Predictor21.ipynb | gpl-3.0 | #sign:max: MAXBOX8: 03/02/2021 18:34:41
# optimal moving average OMA for market index signals ARIMA study- Max Kleiner
# v2 shell argument forecast days - 4 lines compare - ^GDAXI for DAX
# pip install pandas-datareader
# C:\maXbox\mX46210\DataScience\princeton\AB_NYC_2019.csv AB_NYC_2019.csv
#https://medium.co... |
ES-DOC/esdoc-jupyterhub | notebooks/cas/cmip6/models/sandbox-3/land.ipynb | gpl-3.0 | # DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cas', 'sandbox-3', 'land')
"""
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: CAS
Source ID: SANDBOX-3
Topic: Land
Sub-Topics: Soil, Snow, Vegetation, Energy Balance... |
coolharsh55/advent-of-code | 2016/python3/Day19.ipynb | mit | no_elves = 5
elves = [elf for elf in range(1, no_elves + 1)]
print(elves)
"""
Explanation: Day 19: An Elephant Named Joseph
author: Harshvardhan Pandit
license: MIT
link to problem statement
The Elves contact you over a highly secure emergency channel. Back at the North Pole, the Elves are busy misunderstanding White ... |
hannorein/reboundx | ipython_examples/Migration.ipynb | gpl-3.0 | import rebound
import reboundx
import numpy as np
sim = rebound.Simulation()
ainner = 1.
aouter = 10.
e0 = 0.1
inc0 = 0.1
sim.add(m=1.)
sim.add(m=1e-6,a=ainner,e=e0, inc=inc0)
sim.add(m=1e-6,a=aouter,e=e0, inc=inc0)
sim.move_to_com() # Moves to the center of momentum frame
ps = sim.particles
"""
Explanation: Migratio... |
bearing/dosenet-analysis | calibration/Untitled.ipynb | mit | import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#plt.plot([1,2,3,4])
#plt.show()
csv = np.genfromtxt('k40_cal_2019-02-11_D3S.csv', delimiter= ",")
plt.plot(csv.T)
plt.show()
np.max(csv.T)
summed = np.sum(csv.T, axis=1)
plt.plot(summed)
plt.show()
summed[-1]
"""
Explanation: ... |
kaka0525/Process-Bike-Share-data-with-Pandas | bike_plot.ipynb | mit | weather = pd.read_table("daily_weather.tsv")
usage = pd.read_table("usage_2012.tsv")
station = pd.read_table("stations.tsv")
weather.loc[weather['season_code'] == 1, 'season_desc'] = 'winter'
weather.loc[weather['season_code'] == 2, 'season_desc'] = 'spring'
weather.loc[weather['season_code'] == 3, 'season_desc'] ... |
AmberJBlue/aima-python | agents.ipynb | mit | from agents import *
class BlindDog(Agent):
def eat(self, thing):
print("Dog: Ate food at {}.".format(self.location))
def drink(self, thing):
print("Dog: Drank water at {}.".format( self.location))
dog = BlindDog()
"""
Explanation: AGENT
An agent, as defined in 2.1 is anything th... |
mne-tools/mne-tools.github.io | 0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb | bsd-3-clause | import numpy as np
from scipy import signal, fftpack
import matplotlib.pyplot as plt
from mne.time_frequency.tfr import morlet
from mne.viz import plot_filter, plot_ideal_filter
import mne
sfreq = 1000.
f_p = 40.
flim = (1., sfreq / 2.) # limits for plotting
"""
Explanation: Background information on filtering
Her... |
AstroHackWeek/AstroHackWeek2016 | breakouts/gaussian_process/GaussianProcessTasteTest.ipynb | mit | %matplotlib inline
import numpy as np
from matplotlib import pyplot as plt
plt.style.use('seaborn-whitegrid')
"""
Explanation: Gaussian Process Taste-test
The scikit-learn package has a nice Gaussian Process example - but what is it doing? In this notebook, we review the mathematics of Gaussian Processes, and then 1) ... |
QuantEcon/QuantEcon.notebooks | permanent_income.ipynb | bsd-3-clause | import quantecon as qe
import numpy as np
import scipy.linalg as la
import matplotlib.pyplot as plt
%matplotlib inline
np.set_printoptions(suppress=True, precision=4)
"""
Explanation: Permanent Income Model
Chase Coleman and Thomas Sargent
This notebook maps instances of the linear-quadratic-Gaussian permanent income... |
pbstark/DKDHondt14 | danmark14EU.ipynb | mit | from __future__ import division
from __future__ import print_function
import math
import numpy as np
def dHondt(partyTotals, seats, divisors):
'''
allocate <seats> seats to parties according to <partyTotals> votes,
using D'Hondt proportional allocation with <weights> divisors
Input:
party... |
chengsoonong/crowdastro | notebooks/106-passive.ipynb | mit | import astropy.io.ascii as asc, numpy, h5py, sklearn.linear_model, crowdastro.crowd.util, pickle, scipy.spatial
import matplotlib.pyplot as plt
%matplotlib inline
with open('/Users/alger/data/Crowdastro/sets_atlas.pkl', 'rb') as f:
atlas_sets = pickle.load(f)
atlas_sets_compact = atlas_sets['RGZ & compact']
... |
cgpotts/cs224u | finetuning.ipynb | apache-2.0 | __author__ = "Christopher Potts"
__version__ = "CS224u, Stanford, Spring 2022"
"""
Explanation: Bringing contextual word representations into your models
End of explanation
"""
import os
from sklearn.metrics import classification_report
import torch
import torch.nn as nn
import transformers
from transformers import ... |
statsmodels/statsmodels.github.io | v0.13.1/examples/notebooks/generated/statespace_cycles.ipynb | bsd-3-clause | %matplotlib inline
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
from pandas_datareader.data import DataReader
endog = DataReader('UNRATE', 'fred', start='1954-01-01')
endog.index.freq = endog.index.inferred_freq
"""
Explanation: Trends and cycles in unemployment... |
greenelab/GCB535 | 29_ML-II/ML2_svms_and_overfitting.ipynb | bsd-3-clause | import numpy as np
from sklearn import svm
from sklearn import preprocessing
# Define a useful helper function to read in our PCL files and store the gene names,
# matrix of values, and sample names
# We'll use this function later, but we don't need to dig into how it works here.
def read_dataset(filename):
data... |
Kaggle/learntools | notebooks/feature_engineering/raw/tut4.ipynb | apache-2.0 | #$HIDE_INPUT$
%matplotlib inline
import itertools
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import lightgbm as lgb
from sklearn.preprocessing import LabelEncoder
from sklearn import metrics
ks = pd.read_csv('../input/kickstarter-projects/ks-projects-201801.csv',
parse_dat... |
mayank-johri/LearnSeleniumUsingPython | Section 1 - Core Python/Chapter 02 - Basics/2.2. Python Identifiers.ipynb | gpl-3.0 | current_month = "MAY"
print(current_month)
"""
Explanation: Python Identifiers aka Variables
In Python, variable names are kind of tags/pointers to the memory location which hosts the data. We can also think of it as a labeled container that can store a single value. That single value can be of practically any data t... |
sdpython/ensae_teaching_cs | _doc/notebooks/td1a_home/2020_ordonnancement.ipynb | mit | from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline
"""
Explanation: Algo - Problème d'ordonnancement
Un problème d'ordonnancement est un problème dans lequel il faut déterminer le meilleur moment de démarrer un travail, une tâche alors que celles-ci ont des durées bien précises et dépe... |
dwhswenson/openmm-mmst | examples/tully_model_1.ipynb | lgpl-2.1 | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import simtk.openmm as mm
import simtk.openmm.app as app
import simtk.unit as unit
sys11 = mm.openmm.System()
sys12 = mm.openmm.System()
sys22 = mm.openmm.System()
sys00 = mm.openmm.System()
for sys in [sys11, sys12, sys22, sys00]:
mass = 1980... |
zingale/pyreaclib | modify-example.ipynb | bsd-3-clause | import pynucastro as pyna
reaclib_library = pyna.ReacLibLibrary()
"""
Explanation: Modifying Rates
Sometimes we want to change the nuclei involved in rates to simplify our network. Currently,
pynucastro supports changing the products. Here's an example.
End of explanation
"""
filter = pyna.RateFilter(reactants=["... |
ohadravid/ml-tutorial | notebooks/402-ClusteringTextFromWiki2.ipynb | mit | df = pd.read_csv('../data/wiki/wiki.csv.gz', encoding='utf8', index_col=None)
df['text'] = df.text.str[:3000]
totalvocab_stemmed = []
totalvocab_tokenized = []
for doc_text in df.text:
allwords_stemmed = tokenize_and_stem(doc_text) #for each item in 'synopses', tokenize/stem
totalvocab_stemmed.extend(allwords... |
google/CFU-Playground | proj/fccm_tutorial/Amaranth_for_CFUs.ipynb | apache-2.0 | # Install Amaranth
!pip install --upgrade 'amaranth[builtin-yosys]'
# CFU-Playground library
!git clone https://github.com/google/CFU-Playground.git
import sys
sys.path.append('CFU-Playground/python')
# Imports
from amaranth import *
from amaranth.back import verilog
from amaranth.sim import Delay, Simulator, Tick
f... |
ananswam/bioscrape | inference examples/Multiple trajectories.ipynb | mit | %matplotlib inline
%config InlineBackend.figure_format = "retina"
from matplotlib import rcParams
rcParams["savefig.dpi"] = 100
rcParams["figure.dpi"] = 100
rcParams["font.size"] = 20
%matplotlib inline
import bioscrape as bs
from bioscrape.types import Model
from bioscrape.simulator import py_simulate_model
import ... |
molgor/spystats | notebooks/global_variogram.ipynb | bsd-2-clause | # Load Biospytial modules and etc.
%matplotlib inline
import sys
sys.path.append('/apps')
import django
django.setup()
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
## Use the ggplot style
plt.style.use('ggplot')
from external_plugins.spystats import tools
%run ../testvariogram.py
%time vg = ... |
dtamayo/MachineLearning | Day1/06_cross_validation.ipynb | gpl-3.0 | from sklearn.datasets import load_iris
from sklearn.cross_validation import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
# read in the iris data
iris = load_iris()
# create X (features) and y (response)
X = iris.data
y = iris.target
# use train/test split with diffe... |
KrisCheng/ML-Learning | archive/MOOC/Deeplearning_AI/ImprovingDeepNeuralNetworks/SettingupyourMachineLearningApplication/Gradient+Checking.ipynb | mit | # Packages
import numpy as np
from testCases import *
from gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector
"""
Explanation: Gradient Checking
Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking.
You are ... |
brianspiering/word2vec-talk | word2vec_demo.ipynb | apache-2.0 | reset -fs
import collections
import math
import os
from pprint import pprint
import random
import urllib.request
import zipfile
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from sklearn.manifold import TSNE
%matplotlib inline
"""
Explanation: Apply word2vec to dataset
Overview:
Dow... |
luctrudeau/Teaching | AsyncIOisAwesome/AsyncIOisAwesome.ipynb | lgpl-3.0 | import matplotlib.pyplot as plt
%matplotlib inline
"""
Explanation: Asynchronous IO is Awesome
End of explanation
"""
interupts1 = [4898, 4708, 4698, 4730, 4614, 4679, 4686, 4739, 4690, 4743, 3250, 4217]
interuptsN = [3299, 4328, 4498, 4346, 4412, 4417, 4321, 4493, 4514, 4432, 4366, 4519]
interuptsT = [3373, 4287, 4... |
pombredanne/gensim | docs/notebooks/doc2vec-lee.ipynb | lgpl-2.1 | import gensim
import os
import collections
import random
"""
Explanation: Doc2Vec Tutorial on the Lee Dataset
End of explanation
"""
# Set file names for train and test data
test_data_dir = '{}'.format(os.sep).join([gensim.__path__[0], 'test', 'test_data'])
lee_train_file = test_data_dir + os.sep + 'lee_background.c... |
Upward-Spiral-Science/spect-team | Code/Assignment-5/Classification.ipynb | apache-2.0 | import pandas as pd
import numpy as np
# Our data is cleaned by cleaning utility code
df = pd.read_csv('Clean_Data_Adults_1.csv')
# Separate labels and Features
df_labels = df['Depressed']
df_feats = df.drop(['Depressed', 'Unnamed: 0'], axis=1, inplace=False)
X = df_feats.get_values() # features
y = df_labels.get_v... |
materialsvirtuallab/nano106 | lectures/lecture_4_point_group_symmetry/Symmetry Computations on m-3m (O_h) Point Group.ipynb | bsd-3-clause | import numpy as np
from sympy import symbols, Mod
from symmetry.groups import PointGroup
#Create the point group.
oh = PointGroup("m-3m")
print "The generators for this point group are:"
for m in oh.generators:
print m
print "The order of the point group is %d." % len(oh.symmetry_ops)
"""
Explanation: NANO106 - ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.