repo_name stringlengths 6 77 | path stringlengths 8 215 | license stringclasses 15
values | content stringlengths 335 154k |
|---|---|---|---|
mortada/notebooks | blog/traveling_tesla_salesman.ipynb | apache-2.0 | import math
math.factorial(200)
"""
Explanation: Traveling Salesman Problem
The Traveling Salesman Problem (TSP) is quite an interesting math problem. It simply asks: Given a list of cities and the distances between them, what is the shortest possible path that visits each city exactly once and returns to the origin c... |
jayoshih/ricecooker | docs/examples/languages.ipynb | mit | from le_utils.constants import languages
# can lookup language using language code
language_obj = languages.getlang('en')
language_obj
# can lookup language using language name (the new le_utils version has not shipped yet)
language_obj = languages.getlang_by_name('English')
language_obj
# all `language` attributed... |
tritemio/multispot_paper | out_notebooks/usALEX-5samples-PR-raw-out-Dex-7d.ipynb | mit | ph_sel_name = "Dex"
data_id = "7d"
# ph_sel_name = "all-ph"
# data_id = "7d"
"""
Explanation: Executed: Mon Mar 27 11:35:39 2017
Duration: 7 seconds.
usALEX-5samples - Template
This notebook is executed through 8-spots paper analysis.
For a direct execution, uncomment the cell below.
End of explanation
"""
from f... |
spectralDNS/shenfun | docs/source/functions.ipynb | bsd-2-clause | from shenfun import *
N = 8
T = FunctionSpace(N, 'Chebyshev', domain=(-1, 1))
"""
Explanation: <!-- File automatically generated using DocOnce (https://github.com/doconce/doconce/):
doconce format ipynb functions.do.txt -->
Demo - Working with Functions
Mikael Mortensen (email: mikaem@math.uio.no), Department of Mat... |
aw3s/PT3S | .ipynb_checkpoints/PT3S-checkpoint.ipynb | mit | import doctest
"""
>>> from platform import python_version
>>> print(python_version())
3.8.8
"""
doctest.testmod()
"""
Explanation: PT3S
Use SIR 3S Modeldata and SIR 3S Results in pure Python.
With pandas, matplotlib and others.
For documentation, test, verification, analysis, reporting, prototyping, play.
Install Pyt... |
wasit7/algae2 | shrimp/numpy.ipynb | gpl-2.0 | print x
type(x)
y=np.ones((2,3))
print y
"""
Explanation: 1D called vector
2D called matrix
3D nad so on tensor
End of explanation
"""
z=np.arange(2,8,1)
alpha=np.reshape(z,(3,2))
print alpha
beta= np.random.randn(3,4)
print beta
gamma=beta*2.0
print gamma
a=[3,4,5]
a=np.array(a)
type(a)
"""
Explanation: I ne... |
Upward-Spiral-Science/the-fat-boys | docs/Team Fatboys 5 Updates Report Part 2.ipynb | apache-2.0 | filter = (abs(synapsin1 - synapsin2) < 5) & (synapsin1 > 15) & (synapsin2 > 15)
synapsin1_sub = synapsin1[filter]
synapsin2_sub = synapsin2[filter]
sub_sample = np.random.permutation(len(synapsin1_sub))[1:100]
plt.scatter(synapsin1_sub[sub_sample], synapsin2_sub[sub_sample], alpha=0.5)
plt.xlabel("Score on Synapsin... |
mcocdawc/chemcoord | Tutorial/Zmat.ipynb | lgpl-3.0 | import chemcoord as cc
import time
water = cc.Cartesian.read_xyz('water_dimer.xyz', start_index=1).get_zmat()
small = cc.Cartesian.read_xyz('MIL53_small.xyz', start_index=1).get_zmat()
"""
Explanation: Zmatrices
End of explanation
"""
water
"""
Explanation: Let's have a look at it:
End of explanation
"""
water['... |
sdpython/ensae_teaching_cs | _doc/notebooks/td1a_home/2021_random_graph.ipynb | mit | from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline
"""
Explanation: Algo - graphes aléatoires
Comment générer un graphe aléatoire... Générer une séquence de nombres aléatoires indépendants est un problème connu et plutôt bien résolu. Générer une structure aléatoire comme une graphe est... |
nishantsbi/pattern_classification | machine_learning/webapp/webapp.ipynb | gpl-3.0 | import numpy as np
from nltk.stem.porter import PorterStemmer
import re
from nltk.corpus import stopwords
stop = stopwords.words('english')
porter = PorterStemmer()
def tokenizer(text):
text = re.sub('<[^>]*>', '', text)
emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)', text.lower())
text = re.sub('[... |
ealogar/curso-python | basic/3_Booleans_Flow_Control_and_Comprehension.ipynb | apache-2.0 | # Let's declare some bools
spam = True
print spam
print type(spam)
eggs = False
print eggs
print type(eggs)
"""
Explanation: Booleans
End of explanation
"""
# Let's try boolean operations
print True or True
print True or False
print False or True # Boolean or. Short-circuited, so it only evaluates the second... |
ecell/ecell4-notebooks | en/examples/example12.ipynb | gpl-2.0 | %matplotlib inline
from ecell4.prelude import *
"""
Explanation: How to Use the Unit System
Important: The unit system is a feature under development. The following section might not work properly yet.
Here, we show some examples using the unit system in ecell4. This feature requires Python library, pint. Install pint... |
bgroveben/python3_machine_learning_projects | prepare_text_data/prepare_text_data.ipynb | mit | from sklearn.feature_extraction.text import CountVectorizer
# Create a list of text documents:
text = ["The quick brown fox jumped over the lazy dog."]
# Create the transform:
vectorizer = CountVectorizer()
# Tokenize and build vocabulary:
vectorizer.fit(text)
# Summarize:
print("vectorizer.vocabulary: {}".format(vect... |
dmolina/es_intro_python | 12-Generators.ipynb | gpl-3.0 | [n ** 2 for n in range(12)]
"""
Explanation: <!--BOOK_INFORMATION-->
<img align="left" style="padding-right:10px;" src="fig/cover-small.jpg">
This notebook contains an excerpt from the Whirlwind Tour of Python by Jake VanderPlas; the content is available on GitHub.
The text and code are released under the CC0 license;... |
xianjunzhengbackup/code | data science/find_underprice_apartment.ipynb | mit | df.fillna('n/a',inplace=True)
su=df[df['type_of_property'].str.contains('Apartment')]
mu=df[df['type_of_property'].str.contains('Apartments')]
print(len(mu))
print(len(su))
su['propertyinfo_value']
len(su[~(su['propertyinfo_value'].str.contains('bd') | su['propertyinfo_value'].str.contains('Studio'))])
"""
Explanat... |
xpharry/Udacity-DLFoudation | tutorials/transfer-learning/Transfer_Learning_Solution.ipynb | mit | from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
vgg_dir = 'tensorflow_vgg/'
# Make sure vgg exists
if not isdir(vgg_dir):
raise Exception("VGG directory doesn't exist!")
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=1, total_s... |
google/eng-edu | ml/fe/exercises/intro_to_modeling.ipynb | apache-2.0 | # 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 the L... |
royalosyin/Python-Practical-Application-on-Climate-Variability-Studies | ex25-Heatmap of Global Temperature Anomaly.ipynb | mit | import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
import calendar
%matplotlib inline
"""
Explanation: Heatmap of Global Temperature Anomaly
Global temperature anomaly (GTA, $^oC$) was downloaded from NCDC. The data come from the Global Historical Climatology Network-Monthly (GHCN-M) data ... |
nitin-cherian/LifeLongLearning | Python/Python Morsels/3.compact/better_solution/.ipynb_checkpoints/compact-checkpoint.ipynb | mit | def compact(items):
"""Return new iterable with adjacent duplicate values removed."""
for item, prev in zip(items, [object(), *items]):
if item != prev:
yield item
"""
Explanation: Key Takeaways
object() - This will give an unique object, which can used instead of None
... |
ldhagen/docker-jupyter | OpenCV.ipynb | mit | ! wget --no-check-certificate http://www.hobieco.com/linked_images/H18-Magnum.jpg
%matplotlib inline
import cv2
from matplotlib import pyplot as plt
import numpy as np
import time as t
print "OpenCV Version : %s " % cv2.__version__
image = cv2.imread("H18-Magnum.jpg")
fig, ax = plt.subplots()
fig.set_size_inches(3, 3... |
HeardLibrary/workshops | Jupyter/Introduction to Jupyter Notebook.ipynb | gpl-3.0 | !conda list
"""
Explanation: Jupyter Notebook
Jupyter Notebook that evolved out of iPython and is aimed at providing a platform for easy sharing, interaction, and development of open-source software, standards and services. Althought primarily and originally used for phyton interactions, you can interact with multip... |
cdawei/digbeta | dchen/music/aotm2011_subset_repr.ipynb | gpl-3.0 | %matplotlib inline
%load_ext autoreload
%autoreload 2
import os, sys
import gzip
import pickle as pkl
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_fscore_support, roc_auc_score, average_precision_score
from scipy.sparse import ... |
wtbarnes/loops-workshop-2017-talk | notebooks/time_average_em.ipynb | mit | import os
import io
import copy
import glob
import urllib
import numpy as np
import h5py
import matplotlib.pyplot as plt
import matplotlib.colors
import seaborn as sns
import astropy.units as u
import astropy.constants as const
from scipy.ndimage import gaussian_filter
from sunpy.map import Map,GenericMap
import synt... |
Santana9937/Regression_ML_Specialization | Week_5_Lasso/assign_1_week-5-lasso.ipynb | mit | import os
import zipfile
from math import log, sqrt
import numpy as np
import pandas as pd
from sklearn import linear_model
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('darkgrid')
%matplotlib inline
"""
Explanation: Regression Week 5: Feature Selection and LASSO (Interp... |
ES-DOC/esdoc-jupyterhub | notebooks/nims-kma/cmip6/models/sandbox-1/atmos.ipynb | gpl-3.0 | # DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'nims-kma', 'sandbox-1', 'atmos')
"""
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: NIMS-KMA
Source ID: SANDBOX-1
Topic: Atmos
Sub-Topics: Dynamical Core, Radiation... |
mne-tools/mne-tools.github.io | 0.21/_downloads/2b710ad55cbf958235c0d74bf0b0d4ae/plot_evoked_ers_source_power.ipynb | bsd-3-clause | # Authors: Luke Bloy <luke.bloy@gmail.com>
# Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
import mne
from mne.cov import compute_covariance
from mne.datasets import somato
from mne.time_frequency import csd_morlet
from mne.beamformer import (make_di... |
darshanbagul/ComputerVision | RegionMerging-BoundaryMelting/RegionMergingByBoundaryMelting.ipynb | gpl-3.0 | % matplotlib inline
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import convolve2d
import scipy.ndimage as ndi
import math
"""
Explanation: Region Merging Segmentation
Problem Statement.
Region merging is an effective scheme for region growing based segmentation. Region growing may b... |
geektoni/shogun | doc/ipython-notebooks/logdet/logdet.ipynb | bsd-3-clause | %matplotlib inline
from scipy.sparse import eye
from scipy.io import mmread
import numpy as np
from matplotlib import pyplot as plt
import os
import shogun as sg
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
matFile=os.path.join(SHOGUN_DATA_DIR, 'logdet/apache2.mtx.gz')
M = mmread(matFile)
rows = M.sha... |
idekerlab/cyrest-examples | notebooks/cookbook/Python-cookbook/Import.ipynb | mit | # import
from py2cytoscape.data.cyrest_client import CyRestClient
# Create REST client for Cytoscape
cy = CyRestClient()
# Reset current session for fresh start
cy.session.delete()
# Empty network
empty1 = cy.network.create()
# With name
empty2 = cy.network.create(name='Created in Jupyter Notebook')
# With name an... |
mne-tools/mne-tools.github.io | 0.13/_downloads/plot_sensor_permutation_test.ipynb | bsd-3-clause | # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne import io
from mne.stats import permutation_t_test
from mne.datasets import sample
print(__doc__)
"""
Explanation: Permutation T-test on sensor data
One tests if the signal sign... |
paris-saclay-cds/python-workshop | Day_2_Software_engineering_best_practices/solutions/02_docstring.ipynb | bsd-3-clause | def read_spectra(path_csv):
"""Read and parse data in pandas DataFrames.
Parameters
----------
path_csv : str
Path to the CSV file to read.
Returns
-------
s : pandas DataFrame, shape (n_spectra, n_freq_point)
DataFrame containing all Raman spectra.
... |
lionell/university-labs | eco_systems/lab1.ipynb | mit | data = pd.read_csv('lab1v1.csv')
P, D, S = data['Price'].values, data['Demand'].values, data['Supply'].values
data
def plot(*args, x='Quantity', y='Price', **kw):
plt.figure(figsize=(15, 10))
plt.plot(*args)
plt.xlabel(x)
plt.ylabel(y)
plt.legend(kw['legend'])
plt.title(kw['title'])
plt.sho... |
BlancaCC/cultutrilla | python_aprendizaje/curiosidades_pitonicas.ipynb | gpl-3.0 | cuadrado = lambda a: a*a
cuadrado(2)
"""
Explanation: Funciones lambda, listas por compresión, decoradores y otras curiosidades pitónicas
Python es un lenguaje precioso, o por lo menos así me lo parece a mí, por tanto procedo a contarte aspectos, funciones y otras cosilla que a mí me llaman la función.
Funciones lambd... |
Dima806/udacity-mlnd-capstone | capstone-step1-sensitivity-check-run1.ipynb | apache-2.0 | # Select test_size and random_state for splitting a subset
test_size=0.1
random_state=0
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import time
import gzip
import shutil
import seaborn as sns
from collections import Counter
from sklearn.mixture ... |
cathalmccabe/PYNQ | boards/Pynq-Z2/logictools/notebooks/wavedrom_tutorial.ipynb | bsd-3-clause | from pynq.lib.logictools.waveform import draw_wavedrom
"""
Explanation: logictools WaveDrom Tutorial
WaveDrom is a tool for rendering digital timing waveforms. The waveforms are defined in a simple textual format.
This notebook will show how to render digital waveforms using the pynq library.
The logictools overlay u... |
hongsups/insightfl_shin | project/clean_biz_pattern_census.ipynb | mit | import requests
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
import csv
import seaborn as sns
font = {'family' : 'Arial',
'weight' : 'bold',
'size' : 25}
matplotlib.rc('font', **font)
from census import Census
from us import states
import ... |
tensorflow/neural-structured-learning | neural_structured_learning/examples/notebooks/graph_keras_cnn_flowers.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... |
mne-tools/mne-tools.github.io | 0.17/_downloads/3ade035c928216ab770a554e9a0c0cef/plot_stats_cluster_spatio_temporal.ipynb | bsd-3-clause | # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Eric Larson <larson.eric.d@gmail.com>
# License: BSD (3-clause)
import os.path as op
import numpy as np
from numpy.random import randn
from scipy import stats as stats
import mne
from mne.epochs import equalize_epoch_counts
from mne.... |
chrismcginlay/crazy-koala | jupyter/09_print_formatting_decimal_places.ipynb | gpl-3.0 | answer = 4/7
print(answer)
"""
Explanation: Pretty Printing - Decimal Places
Python will print real numbers to many decimal places, usually more than is necessary.
Run this code to see well over 10 decimal places
End of explanation
"""
answer = 4/7
answer_2dp = format(answer, '0.2f')
print(answer_2dp)
"""
Explanati... |
KMFleischer/PyEarthScience | Tutorial/02_Numpy_basics.ipynb | mit | import numpy as np
"""
Explanation: 2. Numpy basics
Numpy is a python module for scientific computing (linear algebra, Fourier transform, random number capabilities), and efficient handling of N-dimensional arrays. Have a closer look at https://numpy.org/.
2.1 Import numpy
First, we have to import the numpy module to ... |
drpngx/tensorflow | tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb | apache-2.0 | from __future__ import absolute_import, division, print_function
# Import TensorFlow >= 1.9 and enable eager execution
import tensorflow as tf
tf.enable_eager_execution()
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import unicodedata
import re
import numpy as np
import os
im... |
texib/spark_tutorial | 4.AnalysisArticle_Content.ipynb | gpl-2.0 | def parseRaw(json_map):
url = json_map['url']
content = json_map['html']
return (url,content)
"""
Explanation: Parse Json
End of explanation
"""
import json
import pprint
pp = pprint.PrettyPrinter(indent=2)
path = "./pixnet.txt"
all_content = sc.textFile(path).map(json.loads).map(parseRaw)
"""
Explanati... |
daniestevez/jupyter_notebooks | Linrad resampler.ipynb | gpl-3.0 | samp_rate = 48000
pulse_on = samp_rate//100
pulse_off = samp_rate//10 - pulse_on
duration = 600 # seconds
n_pulses = duration * 10
amplitude = 0.01
pulse = np.array([1]*pulse_on + [0]*pulse_off, dtype='float32')
i = amplitude*np.tile(pulse, n_pulses)
iq = np.zeros((len(i),2), dtype='float32')
iq[:,0] = i
wavfile.wri... |
rainyear/pytips | Tips/2016-04-07-Thread-vs-Coroutine-ii.ipynb | mit | def jump_range(upper):
index = 0
while index < upper:
jump = yield index
if jump is None:
jump = 1
index += jump
jump = jump_range(5)
print(jump)
print(jump.send(None))
print(jump.send(3))
print(jump.send(None))
"""
Explanation: Python 线程与协程(2)
我之前翻译了Python 3.5 协程原理这篇文章之后尝试用... |
belavenir/Udacity_P1_Lane_Detetion | find_lane.ipynb | gpl-3.0 | #importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
#reading in an image
image = mpimg.imread('test_images/solidWhiteRight.jpg')
#printing out some stats and plotting
print('This image is:', type(image), 'with dimesions:', im... |
dsquareindia/gensim | docs/notebooks/doc2vec-IMDB.ipynb | lgpl-2.1 | import locale
import glob
import os.path
import requests
import tarfile
dirname = 'aclImdb'
filename = 'aclImdb_v1.tar.gz'
locale.setlocale(locale.LC_ALL, 'C')
# Convert text to lower-case and strip punctuation/symbols from words
def normalize_text(text):
norm_text = text.lower()
# Replace breaks with space... |
mediagit2016/workcamp-maschinelles-lernen-grundlagen | 18-05-14-ml-workcamp/sensor-daten-10/Projekt-Sensordaten-Daten Skalieren-Workcamp-ML.ipynb | gpl-3.0 | # Laden der entsprechenden Module (kann etwas dauern !)
# Wir laden die Module offen, damit man einmal sieht, was da alles benötigt wird
# Allerdings aufpassen, dann werden die Module anderst angesprochen wie beim Standard
# zum Beispiel pyplot und nicht plt
from matplotlib import pyplot
pyplot.rcParams["figure.figsize... |
atcemgil/notes | Sampling1.ipynb | mit | import numpy as np
x_1 = np.random.rand()
print(x_1)
"""
Explanation: Basic Distributions
A. Taylan Cemgil
Boğaziçi University, Dept. of Computer Engineering
Notebook Summary
We review the notation and parametrization of densities of some basic distributions that are often encountered
We show how random numbers are... |
tensorflow/tfx-addons | tfx_addons/feature_selection/example/Pima_Indians_Diabetes_example_colab.ipynb | apache-2.0 | !pip install -U tfx
# getting the code directly from the repo
x = !pwd
if 'feature_selection' not in str(x):
!git clone -b main https://github.com/deutranium/tfx-addons.git
%cd tfx-addons/tfx_addons/feature_selection
"""
Explanation: <a href="https://colab.research.google.com/github/deutranium/tfx-addons/blob/m... |
martinjrobins/hobo | examples/toy/model-goodwin-oscillator.ipynb | bsd-3-clause | import pints
import pints.plot
import pints.toy
import matplotlib.pyplot as plt
import numpy as np
model = pints.toy.GoodwinOscillatorModel()
"""
Explanation: Goodwin's oscillator toy model
This example shows how the Goodwin's Oscillator toy model can be used.
Our version of this model has five parameters and three o... |
RaoUmer/lightning-example-notebooks | plots/graph.ipynb | mit | import os
from lightning import Lightning
from numpy import random, asarray, argmin
from colorsys import hsv_to_rgb
import networkx as nx
"""
Explanation: <img style='float: left' src="http://lightning-viz.github.io/images/logo.png"> <br> <br> Graph plots in <a href='http://lightning-viz... |
probml/pyprobml | notebooks/book1/14/resnet_jax.ipynb | mit | import jax
import jax.numpy as jnp # JAX NumPy
from jax import lax
import matplotlib.pyplot as plt
import math
from IPython import display
try:
from flax import linen as nn # The Linen API
except ModuleNotFoundError:
%pip install -qq flax
from flax import linen as nn # The Linen API
from flax.training i... |
UCSBarchlab/PyRTL | ipynb-examples/example7-synth-timing.ipynb | bsd-3-clause | import pyrtl
"""
Explanation: Example 7: Reduction and Speed Analysis
After building a circuit, one might want to do some stuff to reduce the
hardware into simpler nets as well as analyze various metrics of the
hardware. This functionality is provided in the Passes part of PyRTL
and will demonstrated here.
End of expl... |
swirlingsand/deep-learning-foundations | reinforcement/.ipynb_checkpoints/Q-learning-cart-checkpoint.ipynb | mit | import gym
import tensorflow as tf
import numpy as np
"""
Explanation: Deep Q-learning
In this notebook, we'll build a neural network that can learn to play games through reinforcement learning. More specifically, we'll use Q-learning to train an agent to play a game called Cart-Pole. In this game, a freely swinging p... |
tensorflow/docs | site/en/guide/migrate/evaluator.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... |
erdewit/ib_insync | notebooks/market_depth.ipynb | bsd-2-clause | from ib_insync import *
util.startLoop()
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=16)
"""
Explanation: Market depth (order book)
End of explanation
"""
l = ib.reqMktDepthExchanges()
l[:5]
"""
Explanation: To get a list of all exchanges that support market depth data and display the first five:
End of expla... |
deo1/deo1 | Legacy/Udacity/Intro to Data Analysis/L1_Starter_Code.ipynb | mit | import unicodecsv
## Longer version of code (replaced with shorter, equivalent version below)
# enrollments = []
# f = open('enrollments.csv', 'rb')
# reader = unicodecsv.DictReader(f)
# for row in reader:
# enrollments.append(row)
# f.close()
def csv_to_list_of_dict(filename):
with open(filename, 'rb') as f... |
fastai/fastai | nbs/30_text.core.ipynb | apache-2.0 | #|export
import html
"""
Explanation: Text core
Basic function to preprocess text before assembling it in a DataLoaders.
End of explanation
"""
#|export
#special tokens
UNK, PAD, BOS, EOS, FLD, TK_REP, TK_WREP, TK_UP, TK_MAJ = "xxunk xxpad xxbos xxeos xxfld xxrep xxwrep xxup xxmaj".split()
#|export
_all_ = ["UNK"... |
SnShine/aima-python | csp.ipynb | mit | from csp import *
from notebook import psource, pseudocode
# Needed to hide warnings in the matplotlib sections
import warnings
warnings.filterwarnings("ignore")
"""
Explanation: CONSTRAINT SATISFACTION PROBLEMS
This IPy notebook acts as supporting material for topics covered in Chapter 6 Constraint Satisfaction Prob... |
Mashimo/datascience | 02-Classification/svm.ipynb | apache-2.0 | import pandas as pd
# The Dataset comes from:
# https://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits
# Load up the data.
with open('../Datasets/optdigits.tes', 'r') as f: testing = pd.read_csv(f)
with open('../Datasets/optdigits.tra', 'r') as f: training = pd.read_csv(f)
# The nu... |
khalido/deep-learning | tensorboard/Anna KaRNNa.ipynb | mit | import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
"""
Explanation: Anna KaRNNa
In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.
This network is base... |
cdawei/digbeta | dchen/music/aotm2011_MLC_genre.ipynb | gpl-3.0 | %matplotlib inline
%load_ext autoreload
%autoreload 2
import os, sys, time
import pickle as pkl
import numpy as np
import pandas as pd
import sklearn as sk
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
from sklearn.metrics import classification_report, f1_score,... |
uber/pyro | tutorial/source/tensor_shapes.ipynb | apache-2.0 | import os
import torch
import pyro
from torch.distributions import constraints
from pyro.distributions import Bernoulli, Categorical, MultivariateNormal, Normal
from pyro.distributions.util import broadcast_shape
from pyro.infer import Trace_ELBO, TraceEnum_ELBO, config_enumerate
import pyro.poutine as poutine
from pyr... |
google/prog-edu-assistant | exercises/dataframe-pre3-master.ipynb | apache-2.0 | # データをCVSファイルから読み込みます。 Read the data from CSV file.
df = pd.read_csv('data/15-July-2019-Tokyo-hourly.csv')
print("データフレームの行数は %d" % len(df))
print(df.dtypes)
df.head()
"""
Explanation: Data frames 3: 簡単なデータの変換 (Simple data manipulation)
```
ASSIGNMENT METADATA
assignment_id: "DataFrame3"
```
lang:en
In this unit, we ... |
BDannowitz/polymath-progression-blog | distribution-fitting/Distribution-Fitting.ipynb | gpl-2.0 | import pandas as pd
data_df = pd.read_csv('raw-data.csv', index_col='eventID')
data_df.head()
"""
Explanation: Distribution Fitting
Goals:
Load up raw data from previous post
Inspect distribution for a feature
Postulate a fit function
Use scipy.stats to fit function to the distribution
1. Load the Raw Data
End of e... |
GoogleCloudPlatform/training-data-analyst | courses/machine_learning/deepdive2/computer_vision_fun/labs/classifying_images_with_pre-built_tf_container_on_vertex_ai.ipynb | apache-2.0 | from datetime import datetime
import os
REGION = 'us-central1'
PROJECT = !(gcloud config get-value core/project)
PROJECT = PROJECT[0]
BUCKET = PROJECT
MODEL_TYPE = "cnn" # "linear", "dnn", "dnn_dropout", or "cnn"
# Do not change these
os.environ["PROJECT"] = PROJECT
os.environ["BUCKET"] = BUCKET
os.environ["REGION"... |
dorairajsanjay/w209finalproject | Getting simple demo data.ipynb | apache-2.0 | import pandas as pd
data_dir = "/Users/seddont/Dropbox/Tom/MIDS/W209_work/Tom_project/"
"""
Explanation: Processing the open food databse to extract a small number of representative items to use as demonstration for the visualization.
End of explanation
"""
# Get sample of the full database to understand what colum... |
kubeflow/community | scripts/company_stats.ipynb | apache-2.0 | # NOTE: The RuntimeWarnings (if any) are harmless. See ContinuumIO/anaconda-issues#6678.
from pandas.io import gbq
import pandas as pd
import getpass
import subprocess
# Configuration Variables. Modify as desired.
PROJECT = subprocess.check_output(["gcloud", "config", "get-value", "project"]).strip().decode()
"""
Ex... |
aqreed/PyVLM | issues/issue_CD_convergence.ipynb | mit | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import MaxNLocator
from pyvlm.vlm import PyVLM
"""
Explanation: As the mesh density increases, CD does not converge (unlike CL).
Import of the needed libraries:
End of explanation
"""
C = np.array([0, 1... |
csaladenes/aviation | code/airport_parser-Copy1.ipynb | mit | L=json.loads(file('../json/L.json','r').read())
M=json.loads(file('../json/M.json','r').read())
N=json.loads(file('../json/N.json','r').read())
import requests
AP={}
for c in M:
if c not in AP:AP[c]={}
for i in range(len(L[c])):
AP[c][N[c][i]]=L[c][i]
sch={}
"""
Explanation: Load airports of each co... |
oemof/feedinlib | examples/load_era5_weather_data.ipynb | mit | from feedinlib import era5
"""
Explanation: Example for ERA5 weather data download
This example shows you how to download ERA5 weather data from the Climate Data Store (CDS) and store it locally. Furthermore, it shows how to convert the weather data to the format needed by the pvlib and windpowerlib.
In order to downl... |
sbussmann/sensor-fusion | Code/Resample Sensor Data to 10 Hz Sampling Rate.ipynb | mit | import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
# load the raw data
df = pd.read_csv('../Data/shaneiphone_exp2.csv')
"""
Explanation: Goal: resample XYZ signals to 10 Hz sampling rate
Experiment: I drove my car from home to Censio and back. My phone rested on my seat facing ... |
feststelltaste/software-analytics | prototypes/Reading a Git repo's commit history with Pandas efficiently (Word counts edition).ipynb | gpl-3.0 | import git
import pandas as pd
GIT_REPO_PATH = r'../../spring-petclinic/'
repo = git.Repo(GIT_REPO_PATH)
git_bin = repo.git
git_log = git_bin.execute('git log --pretty=format:"%h\t%at\t%aN\t%s"')
commits = pd.read_csv(StringIO(git_log),
sep="\t",
header=None,
names=['sha', 'timestamp', 'aut... |
andreyf/machine-learning-examples | linear_models/peer_review_linreg_height_weight.ipynb | gpl-3.0 | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
"""
Explanation: Линейная регрессия и основные библиотеки Python для анализа данных и научных вычислений
Это задание посвящено линейной регрессии. На примере прогнозирования роста человека по его весу Вы уви... |
nproctor/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 = np.load("trajectory.npz")
t = f['t']
x = f['x']
y = f['y']
assert isinstance(x, np.ndarray) and len(x)==40
assert i... |
dmolina/es_intro_python | 07-Control-Flow-Statements.ipynb | gpl-3.0 | x = -15
if x == 0:
print(x, "is zero")
elif x > 0:
print(x, "is positive")
elif x < 0:
print(x, "is negative")
else:
print(x, "is unlike anything I've ever seen...")
"""
Explanation: <!--BOOK_INFORMATION-->
<img align="left" style="padding-right:10px;" src="fig/cover-small.jpg">
This notebook contains... |
mathnathan/notebooks | mpfi/Probability of an Image.ipynb | mit | x1 = np.random.uniform(size=500)
x2 = np.random.uniform(size=500)
fig = plt.figure();
ax = fig.add_subplot(1,1,1);
ax.scatter(x1,x2, edgecolor='black', s=80);
ax.grid();
ax.set_axisbelow(True);
ax.set_xlim(-0.25,1.25); ax.set_ylim(-0.25,1.25)
ax.set_xlabel('Pixel 2'); ax.set_ylabel('Pixel 1'); plt.savefig('images_in_2d... |
SlipknotTN/udacity-deeplearning-nanodegree | 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 neural... |
ComputationalModeling/spring-2017-danielak | past-semesters/fall_2016/day-by-day/day19-kinematics-terminal-velocity-of-a-skydiver/Day_19_pre_class_notebook.ipynb | agpl-3.0 | from IPython.display import YouTubeVideo
# WATCH THE VIDEO IN FULL-SCREEN MODE
YouTubeVideo("JXJQYpgFAyc",width=640,height=360) # Numerical integration
"""
Explanation: Day 19 Pre-class assignment
Goals for today's pre-class assignment
In this pre-class assignment, you are going to learn how to:
Numerically integ... |
morningc/pyladies-interactive-planetary | notebooks/HELLO WORLD | matplotlib + seaborn + ipywidgets.ipynb | mit | %pylab inline
"""
Explanation: python libs for all vis things
End of explanation
"""
t = arange(0.0, 1.0, 0.01)
y1 = sin(2*pi*t)
y2 = sin(2*2*pi*t)
import pandas as pd
df = pd.DataFrame({'t': t, 'y1': y1, 'y2': y2})
df.head(10)
fig = figure(1, figsize = (10,10))
ax1 = fig.add_subplot(211)
ax1.plot(t, y1)
ax1.gr... |
intel-analytics/analytics-zoo | pyzoo/zoo/chronos/use-case/fsi/stock_prediction.ipynb | apache-2.0 | import numpy as np
import pandas as pd
import os
# S&P 500
FILE_NAME = 'all_stocks_5yr.csv'
SOURCE_URL = 'https://github.com/CNuge/kaggle-code/raw/master/stock_data/'
filepath = './data/'+ FILE_NAME
filepath = os.path.join('data', FILE_NAME)
print(filepath)
# download data
!if ! [ -d "data" ]; then mkdir data;... |
FedericoMuciaccia/SistemiComplessi | src/Fede.ipynb | mit | # import math
def euclideanDistace(x,y):
return numpy.sqrt(numpy.square(x) + numpy.square(y))
import geopy # TODO AttributeError: 'module' object has no attribute 'distance'
from geopy import distance, geocoders
# distanze in km
# geopy.distance.vincenty(A, B) # su sferoide oblato
# geopy.distance.great_circle(A... |
bollwyvl/yamlmagic | README.ipynb | bsd-3-clause | %reload_ext yamlmagic
"""
Explanation: yamlmagic
an IPython magic for capturing data in YAML into a running IPython kernel.
Install
From the command line (or with ! in a notebook cell):
bash
pip install yamlmagic
Enable
Ad-hoc
In the notebook, you can use the %load_ext or %reload_ext line magic.
End of explanation... |
DJCordhose/ai | notebooks/2019_tf/time_series.ipynb | mit | # univariate data preparation
import numpy as np
# split a univariate sequence into samples
def split_sequence(sequence, n_steps):
X, y = list(), list()
for i in range(len(sequence)):
# find the end of this pattern
end_ix = i + n_steps
# check if we are beyond the sequence
if end_ix > len(sequence)-1:
bre... |
CalPolyPat/Python-Workshop | Python Workshop/MatPlotLib.ipynb | mit | import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
#^^^This line tells Jupyter to render the plots inside the notebook^^^
"""
Explanation: MatPlotLib
MatPlotLib is another add on library. It allows us to plot anything we desire. But first, as with NumPy, we need to import it.
End of explanation
"""... |
tensorflow/datasets | docs/determinism.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... |
kkai/perception-aware | 4.visualization/Plotting Basics.ipynb | mit | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%pylab inline
#use a nicer plotting style
plt.style.use(u'seaborn-notebook')
print(plt.style.available)
"""
Explanation: Plotting Basics
Let's start with importing some plotting functions (don't care about the warning ... we should use something e... |
akseshina/dl_course | seminar_1/homework_task1.ipynb | gpl-3.0 | def task_1a_np(x, y):
return np.where(x > y, x + y, x - y)
X = tf.placeholder(tf.float64)
Y = tf.placeholder(tf.float64)
out = tf.cond(tf.greater(X, Y), lambda: tf.add(X, Y), lambda: tf.subtract(X, Y))
with tf.Session() as sess:
for xx, yy in np.random.uniform(size=(50, 2)):
actual = sess.run(out, fee... |
astroai/starnet | Quantifying+Persistence-v2.ipynb | bsd-2-clause | f = '/home/spiffical/data/stars/apStar_visits_quantifypersist_med.txt'
persist_vals_med1=[]
persist_vals_med2=[]
fibers_med = []
snr_combined_med = []
starflags_indiv_med = []
loc_ids_med = []
ap_ids_med = []
fi = open(f)
for j, line in enumerate(fi):
# Get values
line = line.split()
persist1 = float(l... |
Summer-MIND/mind_2017 | Tutorials/hyperalignment/hyperalignment_tutorial.ipynb | mit | %matplotlib inline
import numpy as np
from scipy.spatial.distance import pdist, cdist
from mvpa2.datasets.base import Dataset
from mvpa2.mappers.zscore import zscore
from mvpa2.misc.surfing.queryengine import SurfaceQueryEngine
from mvpa2.algorithms.searchlight_hyperalignment import SearchlightHyperalignment
from mvpa2... |
hankcs/HanLP | plugins/hanlp_demo/hanlp_demo/zh/con_mtl.ipynb | apache-2.0 | !pip install hanlp -U
"""
Explanation: <h2 align="center">点击下列图标在线运行HanLP</h2>
<div align="center">
<a href="https://colab.research.google.com/github/hankcs/HanLP/blob/doc-zh/plugins/hanlp_demo/hanlp_demo/zh/con_mtl.ipynb" target="_blank"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Ope... |
kristianperkins/nbrequests | example_nbrequests.ipynb | apache-2.0 | # autoreload for development
%load_ext autoreload
%autoreload 1
%aimport nbrequests
import requests
from nbrequests import display_request
"""
Explanation: Example nbrequests
Pretty printing requests/responses from the python requests library in Jupyter notebook.
End of explanation
"""
r = requests.get('http://http... |
matthijsvk/multimodalSR | code/Experiments/Tutorials/EbenOlsen_TheanoLasagne/1 - Theano Basics/.ipynb_checkpoints/Exercises-checkpoint.ipynb | mit | # Uncomment and run this cell for one solution
load ./spoilers/logistic.py
"""
Explanation: Exercises
1. Logistic function
Create an expression for the logistic function $s(x) = \frac{1}{1+exp(-x)}$. Plot the function and its derivative, and verify that $\frac{ds}{dx} = s(x)(1-s(x))$.
End of explanation
"""
# Uncomm... |
jegibbs/phys202-2015-work | assignments/assignment05/InteractEx04.ipynb | mit | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
"""
Explanation: Interact Exercise 4
Imports
End of explanation
"""
def random_line(m, b, sigma, size=10):
"""Create a line y = m*x + b + N(0,si... |
google/spectral-density | tf/mnist_spectral_density.ipynb | apache-2.0 | import os
import sys
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import experiment_utils
import lanczos_experiment
import tensorflow_datasets as tfds
sys.path.insert(0, os.path.abspath("./../jax"))
import density
COLAB_PATH = '/tmp/spectral-density'
TRAIN_PATH = os.path.join(COLAB_PA... |
nick-youngblut/SIPSim | ipynb/bac_genome/priming_exp/.ipynb_checkpoints/CD-HIT-checkpoint.ipynb | mit | baseDir = '/home/nick/notebook/SIPSim/dev/priming_exp/'
workDir = os.path.join(baseDir, 'CD-HIT')
rnammerDir = '/home/nick/notebook/SIPSim/dev/bac_genome1210/rnammer/'
otuRepFile = '/var/seq_data/priming_exp/otusn.pick.fasta'
otuTaxFile = '/var/seq_data/priming_exp/otusn_tax/otusn_tax_assignments.txt'
genomeDir = '/ho... |
geoscixyz/computation | docs/case-studies/PF/Kevitsa_Grav_Inv.ipynb | mit | # The usual, we need to load some libraries
from SimPEG import Mesh, Utils, Maps, PF
from SimPEG import mkvc, Regularization, DataMisfit, Optimization, InvProblem, Directives,Inversion
from SimPEG.Utils import mkvc
from SimPEG.Utils.io_utils import download
import numpy as np
import scipy as sp
import os
%pylab inline
... |
UWSEDS/LectureNotes | PreFall2018/Unit-Tests/unit-tests-completed.ipynb | bsd-2-clause | import numpy as np
# Code Under Test
def entropy(ps):
if not np.isclose(np.sum(ps), 1.0):
raise ValueError("Probability is not 1.")
items = ps * np.log(ps)
return -np.sum(items)
# Smoke test
probs = [
[0.1, 0.8, 0.1],
[0.1, 0.9],
[0.5, 0.5],
[1.0]
]
for prob in probs:
try:
... |
mne-tools/mne-tools.github.io | 0.23/_downloads/70e603ce6ceb1fd2cb094ccee99a1920/resolution_metrics_eegmeg.ipynb | bsd-3-clause | # Author: Olaf Hauk <olaf.hauk@mrc-cbu.cam.ac.uk>
#
# License: BSD (3-clause)
import mne
from mne.datasets import sample
from mne.minimum_norm.resolution_matrix import make_inverse_resolution_matrix
from mne.minimum_norm.spatial_resolution import resolution_metrics
print(__doc__)
data_path = sample.data_path()
subje... |
sudov/numpy_pandas_learning | ipython_notebook_tutorial.ipynb | mit | # Hit shift + enter or use the run button to run this cell and see the results
print 'hello world'
# The last line of every code cell will be displayed by default,
# even if you don't print it. Run this cell to see how this works.
2 + 2 # The result of this line will not be displayed
3 + 3 # The result of this line... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.