repo_name stringlengths 6 77 | path stringlengths 8 215 | license stringclasses 15
values | content stringlengths 335 154k |
|---|---|---|---|
mne-tools/mne-tools.github.io | 0.18/_downloads/d71abe904faddac1a89e44f2986e07fa/plot_mne_inverse_label_connectivity.ipynb | bsd-3-clause | # Authors: Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Nicolas P. Rougier (graph code borrowed from his matplotlib gallery)
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets imp... |
maestrotf/pymepps | docs/examples/example_plot_stationnc.ipynb | gpl-3.0 | import pymepps
import matplotlib.pyplot as plt
"""
Explanation: Load station data based on NetCDF files
In this example we show how to load station data based on NetCDF files.
The data is loaded with the pymepps package. Thanks to Ingo Lange we
could use original data from the Wettermast for this example. In the
follo... |
mne-tools/mne-tools.github.io | 0.22/_downloads/2567f25ca4c6b483c12d38184d7fe9d7/plot_decoding_xdawn_eeg.ipynb | bsd-3-clause | # Authors: Alexandre Barachant <alexandre.barachant@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import c... |
frib-high-level-controls/FLAME | examples/flame_demo.ipynb | mit | ### import flame module
from flame import Machine
### specify lattice file location
lat_file = "LS1FS1_lattice.lat"
### read lattice file in
with open(lat_file, 'rb') as inf:
# create lattice data object M
M = Machine(inf)
### Initialize simulation parameters
# states
S = M.allocState({})
### run fl... |
DominikDitoIvosevic/Uni | STRUCE/SU-2019-LAB00-Python.ipynb | mit | xs = [5, 6, 2, 3]
xs
xs[0]
xs[-1]
xs[2] = 10
xs
xs[0] = "a book"
xs
xs[1] = [3, 4]
xs
xs += [99, 100]
xs
xs.extend([22, 33])
xs
xs[-1]
xs.pop()
xs
len(xs)
xs[0:2]
xs[2:]
xs[:3]
xs[:-2]
for el in xs:
print(el)
for idx, el in enumerate(xs):
print(idx, el)
for idx in range(len(xs)):
print(idx... |
Dharamsitejas/E4571-Personalisation-Theory-Project | Part1/analysis/CF-Data.ipynb | mit | ratings = pd.read_csv('../raw-data/BX-Book-Ratings.csv', encoding='iso-8859-1', sep = ';')
ratings.columns = ['user_id', 'isbn', 'book_rating']
print(ratings.dtypes)
print()
print(ratings.head())
print()
print("Data Points :", ratings.shape[0])
"""
Explanation: Loading the Book Ratings Dataset
End of explanation
"""
... |
ray-project/ray | doc/source/_templates/template.ipynb | apache-2.0 | import ray
import ray.rllib.agents.ppo as ppo
from ray import serve
def train_ppo_model():
trainer = ppo.PPOTrainer(
config={"framework": "torch", "num_workers": 0},
env="CartPole-v0",
)
# Train for one iteration
trainer.train()
trainer.save("/tmp/rllib_checkpoint")
return "/tmp... |
legacysurvey/pipeline | doc/nb/overview-paper-gallery.ipynb | gpl-2.0 | import os, sys
import shutil, time, warnings
from contextlib import redirect_stdout
import numpy as np
import matplotlib.pyplot as plt
from astropy.table import Table, vstack
from PIL import Image, ImageDraw, ImageFont
import multiprocessing
nproc = multiprocessing.cpu_count() // 2
%matplotlib inline
"""
Explanatio... |
cfcdavidchan/Deep-Learning-Foundation-Nanodegree | dcgan-svhn/DCGAN_Exercises.ipynb | mit | %matplotlib inline
import pickle as pkl
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import loadmat
import tensorflow as tf
!mkdir data
"""
Explanation: Deep Convolutional GANs
In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called a De... |
raschuetz/foundations-homework | 12/311 time series homework.ipynb | mit | df = pd.read_csv('311-2015.csv', dtype = str)
df.head()
import datetime
def created_date_to_datetime(date_str):
return datetime.datetime.strptime(date_str, '%m/%d/%Y %I:%M:%S %p')
df['created_datetime'] = df['Created Date'].apply(created_date_to_datetime)
df = df.set_index('created_datetime')
"""
Explanation:... |
root-mirror/training | NCPSchool2021/Examples/GraphDrawPython.ipynb | gpl-2.0 | import ROOT
c = ROOT.TCanvas()
"""
Explanation: Interactively Draw a Graph
End of explanation
"""
g = ROOT.TGraph()
for i in range(5): g.SetPoint(i,i,i*i)
g.Draw("APL")
c.Draw()
"""
Explanation: The simple graph
End of explanation
"""
%jsroot on
g.SetMarkerStyle(ROOT.kFullTriangleUp)
g.SetMarkerSize(3)
g.SetMark... |
luofan18/deep-learning | tensorboard/Anna_KaRNNa_Name_Scoped.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... |
astrojhgu/mcupy | example/estimate_eff/README.ipynb | bsd-3-clause | import sys
from mcupy.graph import *
from mcupy.nodes import *
from mcupy.utils import *
from mcupy.core import ensemble_type
try:
import pydot
except(ImportError):
import pydot_ng as pydot
"""
Explanation: Example
Check .<br/>
This is an example given in thie book section 8.2.
First let's import necessary pa... |
david-hoffman/pyOTF | notebooks/Microscope Imaging Models/Epi with Camera.ipynb | apache-2.0 | # We'll use a 1.27 NA water dipping objective imaging in water
psf_params = dict(
na=1.27,
ni=1.33,
wl=0.585,
size=64,
vec_corr="none",
zrange=[0]
)
# Set the Nyquist sampling rate
nyquist_sampling = psf_params["wl"] / psf_params["na"] / 4
# our oversampling factor
oversample_factor = 8
# we ... |
quantopian/research_public | notebooks/tutorials/1_getting_started_lesson4/notebook.ipynb | apache-2.0 | # Import Pipeline class and datasets
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data import EquityPricing
from quantopian.pipeline.domain import US_EQUITIES
from quantopian.pipeline.data.sentdex import sentiment
# Import built-in moving average calculation
from quantopian.pipeline.factors import... |
bspalding/research_public | lectures/beta_hedging/How To - Beta Hedging.ipynb | apache-2.0 | # Import libraries
import numpy as np
from statsmodels import regression
import statsmodels.api as sm
import matplotlib.pyplot as plt
import math
# Get data for the specified period and stocks
start = '2014-01-01'
end = '2015-01-01'
asset = get_pricing('TSLA', fields='price', start_date=start, end_date=end)
benchmark ... |
captain-proton/aise | documentation/source/nia/jupyter_nb/exercise_1.ipynb | gpl-3.0 | import matplotlib.pyplot as plt
import numpy as np
plt.style.use('ggplot')
import subprocess
hosts = ('uni-due.de', 'whitehouse.gov', 'oceania.pool.ntp.org')
log = []
for host in hosts:
process = subprocess.Popen(['ping', '-c', "50", host], stdout=subprocess.PIPE)
for line in process.stdout:
# die ze... |
dolittle007/dolittle007.github.io | notebooks/Euler-Maruyama and SDEs.ipynb | gpl-3.0 | %pylab inline
import pymc3 as pm
import theano.tensor as tt
import scipy
from pymc3.distributions.timeseries import EulerMaruyama
"""
Explanation: Inferring parameters of SDEs using a Euler-Maruyama scheme
This notebook is derived from a presentation prepared for the Theoretical Neuroscience Group, Institute of Syste... |
YosefLab/scVI | tests/notebooks/autotune_advanced_notebook.ipynb | bsd-3-clause | import sys
sys.path.append("../../")
sys.path.append("../")
%matplotlib inline
import logging
import os
import pickle
import scanpy
import anndata
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
from hyperopt import hp
import scvi
from scvi.data import cortex, pbmc_dataset, brai... |
tensorflow/model-optimization | tensorflow_model_optimization/g3doc/guide/quantization/training_comprehensive_guide.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... |
YuriyGuts/kaggle-quora-question-pairs | notebooks/feature-phrase-embedding.ipynb | mit | from pygoose import *
from gensim.models.wrappers.fasttext import FastText
from scipy.spatial.distance import cosine, euclidean, cityblock
"""
Explanation: Feature: Phrase Embedding Distances
Based on the pre-trained word embeddings, we'll calculate the mean embedding vector of each question (as well as the unit-len... |
vbarua/PythonWorkshop | Code/An Interlude on Input and Output/1 - Reading and Writing Data.ipynb | mit | f = open("basicOutput.txt", 'w') # Open/create the basicOutput.txt file for writing ('w')
f.write("Hello World\n") # Write the string to the basicOutput.txt file.
f.write("Goodbye World\n")
f.close() # Close the string to the file.
"""
Explanation: Reading and Writing Data
Basic I/O
Reading and writing to files is ref... |
trangel/Data-Science | reinforcement_learning/dqn_atari.ipynb | gpl-3.0 | #XVFB will be launched if you run on a server
import os
if type(os.environ.get("DISPLAY")) is not str or len(os.environ.get("DISPLAY")) == 0:
!bash ../xvfb start
os.environ['DISPLAY'] = ':1'
"""
Explanation: Deep Q-Network implementation
This notebook shamelessly demands you to implement a DQN - an approximate... |
mohsinhaider/pythonbootcampacm | Objects and Data Structures/.ipynb_checkpoints/List Comprehensions-checkpoint.ipynb | mit | # Store even numbers from 0 to 20
even_lst = [num for num in range(21) if num % 2 == 0]
print(even_lst)
"""
Explanation: List Comprehensions and Generators
Python comes with more than just a programming language, it also includes a way to write elegant code. Pythonic code is syntax that wishes to emulate natural const... |
Unidata/unidata-python-workshop | notebooks/Siphon/Siphon Overview.ipynb | mit | from datetime import datetime, timedelta
from siphon.catalog import TDSCatalog
date = datetime.utcnow() - timedelta(days=1)
cat = TDSCatalog('http://thredds.ucar.edu/thredds/catalog/nexrad/level3/'
f'N0Q/LRX/{date:%Y%m%d}/catalog.xml')
"""
Explanation: <a name="top"></a>
<div style="width:1000 px">
<... |
yedivanseven/bestPy | examples/06.1_BenchmarkSplitData.ipynb | gpl-3.0 | import sys
sys.path.append('../..')
"""
Explanation: CHAPTER 6
6.1 Benchmark: Split Data into Training and Test Sets
Now that we have a convenient way to make recommendations, we still need to make an informed choice as to which of bestPy's algorithms we should pick and how we should set its parameters to achieve the ... |
Benedicto/ML-Learning | document-retrieval.ipynb | gpl-3.0 | import graphlab
"""
Explanation: Document retrieval from wikipedia data
Fire up GraphLab Create
End of explanation
"""
people = graphlab.SFrame('people_wiki.gl/')
"""
Explanation: Load some text data - from wikipedia, pages on people
End of explanation
"""
people.head()
len(people)
"""
Explanation: Data contain... |
RTHMaK/RPGOne | scipy-2017-sklearn-master/notebooks/15 Pipelining Estimators.ipynb | apache-2.0 | import os
with open(os.path.join("datasets", "smsspam", "SMSSpamCollection")) as f:
lines = [line.strip().split("\t") for line in f.readlines()]
text = [x[1] for x in lines]
y = [x[0] == "ham" for x in lines]
from sklearn.model_selection import train_test_split
text_train, text_test, y_train, y_test = train_test... |
AtmaMani/pyChakras | udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb | mit | import pandas as pd
"""
Explanation: <a href='http://www.pieriandata.com'> <img src='../../Pierian_Data_Logo.png' /></a>
SF Salaries Exercise - Solutions
Welcome to a quick exercise for you to practice your pandas skills! We will be using the SF Salaries Dataset from Kaggle! Just follow along and complete the tasks o... |
twosigma/beakerx | doc/python/KernelMagics.ipynb | apache-2.0 | %%groovy
println("stdout works")
f = {it + " work"}
f("results")
%%groovy
new Plot(title:"plots work", initHeight: 200)
%%groovy
[a:"tables", b:"work"]
%%groovy
"errors work"/1
%%groovy
HTML("<h1>HTML works</h1>")
%%groovy
def p = new Plot(title : 'Plots Work', xLabel: 'Horizontal', yLabel: 'Vertical');
p << new L... |
kettlewell/pipeline | Input/notebooks/kafkaSendDataPy.ipynb | mit | import os
os.environ['PYSPARK_SUBMIT_ARGS'] = '--conf spark.ui.port=4041 --packages org.apache.kafka:kafka_2.11:0.10.0.0,org.apache.kafka:kafka-clients:0.10.0.0 pyspark-shell'
"""
Explanation: kafkaSendDataPy
This notebook sends data to Kafka on the topic 'test'. A message that gives the current time is sent every se... |
nansencenter/nansat-lectures | notebooks/15 Django-Geo-SPaaS.ipynb | gpl-3.0 | import os, sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'geospaas_project.settings'
sys.path.insert(0, '/vagrant/shared/course_vm/geospaas_project/')
import django
django.setup()
from django.conf import settings
"""
Explanation: Django-Geo-SPaaS - GeoDjango framework for Satellite Data Management
First of all we need ... |
bakanchevn/DBCourseMirea2017 | Неделя 2/Задание в классе/Лекция-2-1.ipynb | gpl-3.0 | a = 'Pop'
%sql select * from genres where Name = :a
"""
Explanation: Передача переменных python в sql
Можно передать переменную из python в sql
End of explanation
"""
a = %sql select * from genres
type(a)
print(a)
"""
Explanation: Можно присвоить результат запроса в переменную
End of explanation
"""
import sql... |
google/jax-md | notebooks/customizing_potentials_cookbook.ipynb | apache-2.0 | #@title Imports & Utils
!pip install -q git+https://www.github.com/google/jax-md
import numpy as onp
import jax.numpy as np
from jax import random
from jax import jit, grad, vmap, value_and_grad
from jax import lax
from jax import ops
from jax.config import config
config.update("jax_enable_x64", True)
from jax_md ... |
vanheck/blog-notes | SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb | mit | SQUARE = 128
SQUARE_MULTIPLIER = 1.5
# how many
BARS_BACK_TO_REFERENCE = np.int(np.ceil(SQUARE * SQUARE_MULTIPLIER))
# set higher timeframe for getting SquareMathLevels
MINUTES = 30 # range 0-59
PD_RESAMPLE_RULE = f'{MINUTES}Min'
# set the period of PD_RESAMPLE_RULE will be started. E.g. PD_RESAMPLE_RULE == '30min'... |
BjornFJohansson/pydna-examples | notebooks/simple_examples/Dseqrecord.ipynb | bsd-3-clause | from pydna.dseqrecord import Dseqrecord
"""
Explanation: Demonstration of the Dseqrecord object
End of explanation
"""
mysequence = Dseqrecord("GGATCCAAA")
"""
Explanation: A small Dseqrecord object can be created directly. The Dseqrecord class is a double stranded version of the Biopython SeqRecord class.
End of e... |
open-forcefield-group/openforcefield | examples/deprecated/chemicalEnvironments/create_move_types_and_weights.ipynb | mit | # generic scientific/ipython header
from __future__ import print_function
from __future__ import division
import os, sys
import copy
import numpy as np
"""
Explanation: Creating Weighted Moves
This notebook was created in August 2016 during exploration in how to bias different types of moves in chemical space for the ... |
jorisroovers/machinelearning-playground | machine-learning/keras/simple.ipynb | apache-2.0 | # Imports
import numpy
import pandas
def generate_data():
# Generate Random Data
cluster_size = 1000 # number of data points in a cluster
dimensions = 2
# Cluster A random numbers
cA_offset = (5,5)
cA = pandas.DataFrame(numpy.random.rand(cluster_size, dimensions) + cA_offset, columns=["x", "y... |
zoltanctoth/bigdata-training | spark/Logistic Regression Example - without output.ipynb | gpl-2.0 | training = sqlContext.read.parquet("data/training.parquet")
test = sqlContext.read.parquet("data/test.parquet")
test.printSchema()
test.first()
"""
Explanation: Spark ML
Read training and test data. In this case test data is labeled as well (we will generate our label based on the arrdelay field)
End of explanation... |
mne-tools/mne-tools.github.io | dev/_downloads/ca1574468d033ed7a4e04f129164b25b/20_cluster_1samp_spatiotemporal.ipynb | bsd-3-clause | # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Eric Larson <larson.eric.d@gmail.com>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD-3-Clause
import numpy as np
from numpy.random import randn
from scipy import stats as stats
import mne
from mne.epochs import equaliz... |
keras-team/keras-io | examples/vision/ipynb/nnclr.ipynb | apache-2.0 | !pip install tensorflow-datasets
"""
Explanation: Self-supervised contrastive learning with NNCLR
Author: Rishit Dagli<br>
Date created: 2021/09/13<br>
Last modified: 2021/09/13<br>
Description: Implementation of NNCLR, a self-supervised learning method for computer vision.
Introduction
Self-supervised learning
Self-s... |
peterwittek/qml-rg | Archiv_Session_Spring_2017/Exercises/10_CIFAR with sklearn.ipynb | gpl-3.0 | import math
import os
from matplotlib import pyplot as plt
import numpy as np
from six.moves import cPickle
import matplotlib.pyplot as plt
from sklearn import manifold
from tools import CifarLoader
# General parameters for classification
n_neighbors = 30
n_components = 2
"""
Explanation: CIFAR embedding through skl... |
ShinjiKatoA16/UCSY-sw-eng | Python-7 Input and Output.ipynb | mit | fd = open('README.md', 'r')
print(fd.readline(), end='') # \n is included in input string
for s in fd: # file object(descriptor) is iterable, and can be used in for loop
print(s.strip()) # strip() removes extra space and \n
# print(s.split()) # convert string to List
"""
Explanation: I/O
File I... |
sisnkemp/deep-learning | intro-to-rnns/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... |
Naereen/notebooks | A_short_study_of_Renyi_entropy.ipynb | mit | !pip install watermark matplotlib numpy
%load_ext watermark
%watermark -v -m -a "Lilian Besson" -g -p matplotlib,numpy
import numpy as np
import matplotlib.pyplot as plt
"""
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#A-short-study-of-Rényi-entropy" data-toc-modified-id="A-short-study-of-R... |
ES-DOC/esdoc-jupyterhub | notebooks/inm/cmip6/models/inm-cm5-0/aerosol.ipynb | gpl-3.0 | # DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'inm', 'inm-cm5-0', 'aerosol')
"""
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: INM
Source ID: INM-CM5-0
Topic: Aerosol
Sub-Topics: Transport, Emissions, Concent... |
billzhao1990/CS231n-Spring-2017 | assignment2/Dropout.ipynb | mit | # As usual, a bit of setup
from __future__ import print_function
import time
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.fc_net import *
from cs231n.data_utils import get_CIFAR10_data
from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
from cs231n.solv... |
GoogleCloudPlatform/dialogflow-email-agent-demo | Training_Data_for_Signature_Extraction.ipynb | apache-2.0 | ! pip install bs4 lxml
from bs4 import BeautifulSoup
import lxml
import html
import pandas as pd
import random
import re
import json
"""
Explanation: This Colab uses the BC3: British Columbia Conversation Corpora to generate a training dataset for Google Cloud Vertex AI Entity Extraction to train an email signature e... |
karlstroetmann/Algorithms | Python/Chapter-08/Heapsort-Performance.ipynb | gpl-2.0 | def swap(A, i, j):
A[i], A[j] = A[j], A[i]
"""
Explanation: This notebook implements an array-based version of Heapsort.
Heapsort
The function call swap(A, i, j) takes an array A and two indexes i and j and exchanges the elements at these indexes.
End of explanation
"""
def sink(A, k, n):
while 2 * k + 1 <=... |
ewulczyn/ewulczyn.github.io | ipython/ab_testing_with_multinomial_data/ab_testing_with_multinomial_data.ipynb | mit | def plot_donation_amounts(counts):
keys = list(counts.keys())
values = list(counts.values())
fig = plt.figure(figsize=(15, 6))
ind = 1.5*np.arange(len(keys)) # the x locations for the groups
a_rects = plt.bar(ind, values, align='center', facecolor ='yellow', edgecolor='gr... |
statsmodels/statsmodels.github.io | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | bsd-3-clause | %matplotlib inline
from statsmodels.compat import lmap
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import statsmodels.api as sm
"""
Explanation: M-Estimators for Robust Linear Modeling
End of explanation
"""
norms = sm.robust.norms
def plot_weights(support, weights_func, xlabels, xt... |
google/rba | Standard Regression (BQML).ipynb | apache-2.0 | ###########################################################################
#
# Copyright 2021 Google Inc.
#
# 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/... |
vitojph/kschool-nlp | notebooks-py2/pos-tagger-es.ipynb | gpl-3.0 | import nltk
from nltk.corpus import cess_esp
cess_esp = cess_esp.tagged_sents()
print(cess_esp[0])
"""
Explanation: PoS tagging en Español
En este primer ejercicio vamos a jugar con uno de los corpus en español que está disponible desde NLTK: CESS_ESP, un treebank anotado a partir de una colección de noticias en esp... |
RaspberryJamBe/ipython-notebooks | notebooks/nl-be/Communicatie - Mail verzenden.ipynb | cc0-1.0 | MAIL_SERVER = "mail.****.com"
FROM_ADDRESS = "noreply@****.com"
TO_ADDRESS = "my_friend@****.com"
"""
Explanation: Vereiste:
Voor het verzenden van Mail heb je een uitgaande mailserver nodig (die in het geval van dit script ook niet geauthenticeerde uitgaande communicatie moet toelaten). Vul de vereiste gegevens in in... |
jmhsi/justin_tinker | data_science/courses/deeplearning2/DCGAN.ipynb | apache-2.0 | %matplotlib inline
import importlib
import utils2; importlib.reload(utils2)
from utils2 import *
from tqdm import tqdm
"""
Explanation: Generative Adversarial Networks in Keras
End of explanation
"""
from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train.shape
n = len(X_t... |
kcyu1993/ML_course_kyu | labs/ex03/template/ex03.ipynb | mit | def compute_cost_MSE(y, tx, beta):
"""compute the loss by mse."""
e = y - tx.dot(beta)
mse = e.dot(e) / (2 * len(e))
return mse
def compute_cost_MAE(y, tx, w):
y = np.array(y)
return np.sum(abs(y - np.dot(tx, w))) / y.shape[0]
def least_squares(y, tx):
"""calculate the least squares solutio... |
analysiscenter/dataset | examples/experiments/augmentation/augmentation.ipynb | apache-2.0 | import sys
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm_notebook as tqn
%matplotlib inline
sys.path.append('../../..')
sys.path.append('../../utils')
import utils
from secondbatch import MnistBatch
from simple_conv_model import ConvModel
from batchflow import V, B
from batchflow.opensets ... |
egillanton/Udacity-SDCND | 1. Computer Vision and Deep Learning/L2 LeNet Lab/LeNet-Lab.ipynb | mit | from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", reshape=False)
X_train, y_train = mnist.train.images, mnist.train.labels
X_validation, y_validation = mnist.validation.images, mnist.validation.labels
X_test, y_test = mnist.test.images, mn... |
fabriziocosta/pyMotif | glam2_example.ipynb | mit | #printing motives as lists
for motif in glam2.motives_list:
for m in motif:
print m
print
"""
Explanation: <h3>Print motives as list</h3>
End of explanation
"""
glam2.display_logo(do_alignment=False)
glam2.display_logo(motif_num=1)
"""
Explanation: <h3>Display Sequence logo of unaligned motives</h3... |
patelparth30j/yelp-sentiment-analysis | yelp_03bagOfWords.ipynb | mit | read_filename = os.path.join(yelp_utils.YELP_DATA_CSV_DIR, 'business_review_user' + data_subset + '.csv')
df_data = pd.read_csv(read_filename, engine='c', encoding='utf-8')
"""
Explanation: Read the csv file generated in yelp_datacleaning
End of explanation
"""
df_data_preprocessed_review = df_data.copy();
%time df_... |
amitkaps/hackermath | Module_1d_linear_regression_gradient.ipynb | mit | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('fivethirtyeight')
plt.rcParams['figure.figsize'] = (9, 6)
pop = pd.read_csv('data/cars_small.csv')
pop.head()
"""
Explanation: Linear Regression (Gradient Descent)
So far we have looked at direct matrix method fo... |
bbfamily/abu | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | gpl-3.0 | # 基础库导入
from __future__ import print_function
from __future__ import division
import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import ipywidgets
%matplotlib inline
import os
import sys
# 使用insert 0即只使用github,避免交叉... |
seanjh/DSRecommendationSystems | task2.ipynb | apache-2.0 | global_mean = ratings_train.map(lambda r: (r[2])).mean()
global_mean
"""
Explanation: Calculate the general mean u for all ratings
End of explanation
"""
#convert training data to dataframe with attribute
df = sqlContext.createDataFrame(ratings_train, ['userId', 'movieId', 'ratings'])
#sort the data by movie
df_or... |
jaredleekatzman/DeepSurv | notebooks/DeepSurv Example.ipynb | mit | train_dataset_fp = './example_data.csv'
train_df = pd.read_csv(train_dataset_fp)
train_df.head()
"""
Explanation: Read in dataset
First, I read in the dataset and print the first five elements to get a sense of what the dataset looks like
End of explanation
"""
# event_col is the header in the df that represents the... |
fggp/ctcsound | cookbook/drafts/plot_audio_file.ipynb | lgpl-2.1 | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import soundfile as sf
"""
Explanation: Plotting an Audio File
For the transformation of the audio data to a numpy array the soundfile library is used. It is based on libsndfile which is also used by Csound. Other Python modules like wave have probl... |
jayme-anchante/cv-bio | interview_tests/Teste BI em Python.ipynb | mit | # Links para as bases de dados do R:
mtcars_link = 'https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/datasets/mtcars.csv'
quakes_link = 'https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/datasets/quakes.csv'
cars_link = 'https://raw.github.com/vincentarelbundock/Rdatasets/master/c... |
fastai/course-v3 | nbs/dl2/11_train_imagenette.ipynb | apache-2.0 | path = datasets.untar_data(datasets.URLs.IMAGENETTE_160)
size = 128
tfms = [make_rgb, RandomResizedCrop(size, scale=(0.35,1)), np_to_float, PilRandomFlip()]
bs = 64
il = ImageList.from_files(path, tfms=tfms)
sd = SplitData.split_by_func(il, partial(grandparent_splitter, valid_name='val'))
ll = label_by_func(sd, pare... |
planet-os/notebooks | nasa-opennex/OpenNEX DCP30 Analysis Using Pandas.ipynb | mit | %matplotlib inline
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
# set default figure size
from pylab import rcParams
rcParams['figure.figsize'] = 16, 8
import pandas as pd
import urllib2
"""
Explanation: OpenNEX DCP30 Analysis Using Pandas
This notebook illustrates how to analyze ... |
0x4a50/udacity-0x4a50-deep-learning-nanodegree | intro-to-rnns/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... |
JoseGuzman/myIPythonNotebooks | genetics/PrimerDesign.ipynb | gpl-2.0 | %pylab inline
from itertools import product, permutations
from math import pow
"""
Explanation: <H1>PrimerDesign</H1>
We need to define a sequence of 17 bases with the following requirements:
<ul>
<li>Total GC content: 40-60%</li>
<li>GC Clamp: < 3 in the last 5 bases at the 3' end of the primer.</li>
</ul>
... |
hunterherrin/phys202-2015-work | assignments/assignment09/IntegrationEx02.ipynb | mit | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy import integrate
"""
Explanation: Integration Exercise 2
Imports
End of explanation
"""
def integrand(x, a):
return 1.0/(x**2 + a**2)
def integral_approx(a):
# Use the args keyword argument to feed extra a... |
arcyfelix/Courses | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/11-Advanced-Quantopian-Topics/00-Pipeline-Example-Walkthrough.ipynb | apache-2.0 | from quantopian.pipeline import Pipeline
from quantopian.research import run_pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
"""
Explanation: Pipeline Example
End of explanation
"""
from quantopian.pipeline.filters import Q1500US
"""
Explanation: Getting the Securities we want.
The Q500US and ... |
tcmoore3/mdtraj | examples/rmsd-drift.ipynb | lgpl-2.1 | import mdtraj.testing
crystal_fn = mdtraj.testing.get_fn('native.pdb')
trajectory_fn = mdtraj.testing.get_fn('frame0.xtc')
crystal = md.load(crystal_fn)
trajectory = md.load(trajectory_fn, top=crystal) # load the xtc. the crystal structure defines the topology
trajectory
"""
Explanation: Find two files that are dist... |
wmfschneider/CHE30324 | Homework/HW8-soln.ipynb | gpl-3.0 | import numpy as np
import matplotlib.pyplot as plt
r = np.linspace(0,12,100) # r=R/a0
P = (1+r+1/3*r**2)*np.exp(-r)
plt.plot(r,P)
plt.xlim(0)
plt.ylim(0)
plt.xlabel('Internuclear Distance $R/a0$')
plt.ylabel('Overlap S')
plt.title('The Overlap Between Two 1s Orbitals')
plt.show()
"""
Explanation: Chem 30324, Spring ... |
wikistat/Apprentissage | GRC-carte_Visa/Apprent-Python-Visa.ipynb | gpl-3.0 | # Importation des librairies.
import numpy as np
import pandas as pd
import random as rd
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
# Lecture d'un data frame
vispremv = pd.read_table('vispremv.dat', delimiter=... |
thehackerwithin/berkeley | code_examples/data_tidying_python_r/Data Tidying and Transformation in Python.ipynb | bsd-3-clause | from __future__ import print_function # For the python2 people
import pandas as pd # This is typically how pandas is loaded
"""
Explanation: Data Tidying and Transformation in Python
by David DeTomaso, Diya Das, and Andrey Indukaev
The goal
Data tidying is a necessary first step for data analysis - it's the process of... |
kit-cel/wt | qc/quantization/Uniform_Quantization_Sine.ipynb | gpl-2.0 | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import librosa
import librosa.display
import IPython.display as ipd
"""
Explanation: Illustration of Uniform Quantization
This code is provided as supplementary material of the lecture Quellencodierung.
This code illustrates
* Uniform scalar quantiz... |
intel-analytics/BigDL | docs/docs/ClusterServingGuide/OtherFrameworkUsers/keras-to-cluster-serving-example.ipynb | apache-2.0 | import tensorflow as tf
import os
import PIL
tf.__version__
# Obtain data from url:"https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip"
zip_file = tf.keras.utils.get_file(origin="https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip",
fname="... |
nmih/ssbio | docs/notebooks/GEM-PRO - Genes & Sequences.ipynb | mit | import sys
import logging
# Import the GEM-PRO class
from ssbio.pipeline.gempro import GEMPRO
# Printing multiple outputs per cell
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
"""
Explanation: GEM-PRO - Genes & Sequences
This notebook gives an example of ... |
RNAer/Calour | doc/source/notebooks/microbiome_diff_abundance.ipynb | bsd-3-clause | import calour as ca
ca.set_log_level(11)
%matplotlib notebook
import numpy as np
np.random.seed(2018)
"""
Explanation: Microbiome differential abundance tutorial
This is a jupyter notebook example of how to identify bacteria different between two conditions
Setup
End of explanation
"""
cfs=ca.read_amplicon('data/chr... |
linhbngo/cpsc-4770_6770 | 03-cloudlab-genilib.ipynb | gpl-3.0 | !unzip codes/cloudlab/emulab-0.9.zip -d codes/cloudlab
!cd codes/cloudlab/emulab-geni-lib-1baf79cf12cb/;\
source activate python2;\
python setup.py install --user
!ls /home/lngo/.local/lib/python2.7/site-packages/
!rm -Rf codes/cloudlab/emulab-geni-lib-1baf79cf12cb/
"""
Explanation: Important
This notebook ... |
AlJohri/DAT-DC-12 | notebooks/exercise_nba.ipynb | mit | # read the data into a DataFrame
import pandas as pd
url = 'https://raw.githubusercontent.com/kjones8812/DAT4-students/master/kerry/Final/NBA_players_2015.csv'
nba = pd.read_csv(url, index_col=0)
nba.head()
# examine the columns
# examine the positions
"""
Explanation: KNN exercise with NBA player data
Introduction
... |
rubensfernando/mba-analytics-big-data | Python/2016-08-01/aula5-parte3-json.ipynb | mit | import simplejson as json
json_string = '{"pnome": "Dino", "unome":"Magri"}'
arq_json = json.loads(json_string)
print(arq_json['pnome'])
json_lista = ['foo', {'bar': ('baz', None, 1.0, 2)}]
print(json.dumps(json_lista))
json_dic = {"c": 0, "b": 0, "a": 0}
print(json.dumps(json_dic, sort_keys=True))
"""
Explanat... |
aleph314/K2 | Data Mining/Recommender Systems/solution/Recommender-Engine_solution.ipynb | gpl-3.0 | # Importing the data
import pandas as pd
import numpy as np
header = ['user_id', 'item_id', 'rating', 'timestamp']
data_movie_raw = pd.read_csv('../data/ml-100k/u.data', sep='\t', names=header)
data_movie_raw.head()
"""
Explanation: Recommender Engine
Perhaps the most famous example of a recommender engine in the D... |
sdpython/pyquickhelper | _doc/notebooks/example_about_files.ipynb | mit | from pyquickhelper.filehelper import download, gzip_files, zip7_files, zip_files
download("https://docs.python.org/3.4/library/urllib.request.html")
gzip_files("request.html.gz", ["urllib.request.html"])
import os
os.listdir(".")
ipy = [ _ for _ in os.listdir(".") if ".ipynb" in _ ]
if os.path.exists("request.html.... |
NGSchool2016/ngschool2016-materials | jupyter/agyorkei/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb | gpl-3.0 | %pylab inline
"""
Explanation: Set the matplotlib magic to notebook enable inline plots
End of explanation
"""
import subprocess
import matplotlib.pyplot as plt
import random
import numpy as np
"""
Explanation: Calculate the Nonredundant Read Fraction (NRF)
SAM format example:
SRR585264.8766235 0 1 ... |
OpenWeavers/openanalysis | doc/OpenAnalysis/05 - Data Structures.ipynb | gpl-3.0 | from openanalysis.data_structures import DataStructureBase, DataStructureVisualization
import gi.repository.Gtk as gtk # for displaying GUI dialogs
"""
Explanation: Data Structures
Data structures are a concrete implementation of the specification provided by one or more particular abstract data types (ADT), which s... |
daniel-severo/dask-ml | docs/source/examples/dask-glm.ipynb | bsd-3-clause | import os
import s3fs
import pandas as pd
import dask.array as da
import dask.dataframe as dd
from distributed import Client
from dask import persist, compute
from dask_glm.estimators import LogisticRegression
"""
Explanation: Dask GLM
dask-glm is a library for fitting generalized linear models on large datasets.
The... |
davidthomas5412/PanglossNotebooks | MassLuminosityProject/SummerResearch/ValidatingLikelihoodVarianceAndSingleLikelihoodWeightDistribution_20170627.ipynb | mit | %matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib import rc
rc('text', usetex=True)
!head -n 5 likelihoodvariancetest.txt
multi = np.loadtxt('likelihoodvariancetest.txt')
multi1000 = np.loadtxt('likelihoodvariancetest1000samples.txt')
multi10000 = np.loadtxt('l... |
arcyfelix/Courses | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/02-NumPy/Numpy Exercises - Solved.ipynb | apache-2.0 | import numpy as np
"""
Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
<center>Copyright Pierian Data 2017</center>
<center>For more information, visit us at www.pieriandata.com</center>
NumPy Exercises
Now that we've learned about NumPy let's test your knowledge. We'll s... |
samuelsinayoko/kaggle-housing-prices | xgboost/xgboost-feature-selection.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('train.csv')
test = pd.read_csv('test.csv')
target = train['SalePrice']
train = train.drop(['SalePrice'],axis=1)
trainlen = train.shape[0]
"""
Exp... |
benhoyle/udacity-tensorflow | 2_fullyconnected.ipynb | mit | # These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range
"""
Explanation: Deep Learning
Assignment 2
Previously in 1_n... |
chrismcginlay/crazy-koala | jupyter/03_processing_data.ipynb | gpl-3.0 | boys = int(input('How many boys are in the class: '))
girls = int(input('How many girls are in the class:'))
pupils = boys + girls
print('There are', pupils,'in the class altogether')
"""
Explanation: Processing Data
Working With Numbers
Let's get some integer (aka whole number) variables going and learn how to add, d... |
ebellm/ztf_summerschool_2015 | notebooks/Machine_Learning_Light_Curve_Classification.ipynb | bsd-3-clause | shelf_file = " " # complete the path to the appropriate shelf file here
shelf = shelve.open(shelf_file)
shelf.keys()
"""
Explanation: <span style='color:red'>An essential note in preparation for this exercise.</span> We will use scikit-learn to provide classifications of the PTF sources that we developed on the first... |
AI-Innovation/cs231n_ass1 | 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.... |
GoogleCloudPlatform/mlops-on-gcp | immersion/kubeflow_pipelines/cicd/labs/lab-03_vertex.ipynb | apache-2.0 | PROJECT_ID = !(gcloud config get-value project)
PROJECT_ID = PROJECT_ID[0]
REGION = 'us-central1'
ARTIFACT_STORE = f'gs://{PROJECT_ID}-vertex'
"""
Explanation: CI/CD for a Kubeflow pipeline on Vertex AI
Learning Objectives:
1. Learn how to create a custom Cloud Build builder to pilote Vertex AI Pipelines
1. Learn how ... |
mjabri/holoviews | doc/Tutorials/Pandas_Conversion.ipynb | bsd-3-clause | import numpy as np
import pandas as pd
import holoviews as hv
from IPython.display import HTML
%reload_ext holoviews.ipython
%output holomap='widgets'
"""
Explanation: Pandas is one of the most popular Python libraries providing high-performance, easy-to-use data structures and data analysis tools. Additionally it p... |
rogerallen/kaggle | ncfish/roger.ipynb | apache-2.0 | #Verify we are in the lesson1 directory
%pwd
%matplotlib inline
import os, sys
sys.path.insert(1, os.path.join(sys.path[0], '../utils'))
from utils import *
from vgg16 import Vgg16
from PIL import Image
from keras.preprocessing import image
from sklearn.metrics import confusion_matrix
"""
Explanation: Based on fast.... |
CUBoulder-ASTR2600/lectures | lecture_12_differentiation.ipynb | isc | %matplotlib inline
import numpy as np
import matplotlib.pyplot as pl
"""
Explanation: Numerical Differentiation
End of explanation
"""
from IPython.display import Image
Image(url='http://wordlesstech.com/wp-content/uploads/2011/11/New-Map-of-the-Moon-2.jpg')
"""
Explanation: Applications:
Derivative difficult to... |
misken/hillmaker-examples | notebooks/basic_usage_shortstay_unit_multicats.ipynb | apache-2.0 | import pandas as pd
import hillmaker as hm
"""
Explanation: Using hillmaker (v0.2.0)
In this notebook we'll focus on basic use of hillmaker for analyzing occupancy in a typical hospital setting. The data is fictitious data from a hospital short stay unit (SSU). Patients flow through a SSU for a variety of procedures, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.