repo_name stringlengths 6 77 | path stringlengths 8 215 | license stringclasses 15
values | content stringlengths 335 154k |
|---|---|---|---|
feroda/lessons-python4beginners | .ipynb_checkpoints/P4B - Capitolo 1-checkpoint.ipynb | agpl-3.0 | # This is hello_who.py
def hello(who):
print("Hello {}!".format(who))
if __name__ == "__main__":
hello("mamma")
"""
Explanation: Python2 for beginners (P4B)
<p style="text-align: center;">Luca Ferroni <luca@befair.it></p>
<p style="text-align: center;">http://www.befair.it<br />**Software Libero per i terr... |
Upward-Spiral-Science/team1 | code/Assignment10_Akash.ipynb | apache-2.0 | import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import urllib2
import scipy.stats as stats
url = ('https://raw.githubusercontent.com/Upward-Spiral-Science/data/master/syn-density/output.csv')
data = urllib2.urlopen(url)
csv = np.genfromtxt(data, delimiter=",")[1:] # Remove lable row
# Clip data... |
cpcloud/ibis | docs/tutorial/03-Expressions-Lazy-Mode-Logging.ipynb | apache-2.0 | !curl -LsS -o $TEMPDIR/geography.db 'https://storage.googleapis.com/ibis-tutorial-data/geography.db'
import os
import tempfile
import ibis
connection = ibis.sqlite.connect(
os.path.join(tempfile.gettempdir(), 'geography.db')
)
countries = connection.table('countries')
"""
Explanation: Lazy Mode and Logging
So f... |
econ-ark/HARK | examples/ConsIndShockModel/PerfForesightConsumerType.ipynb | apache-2.0 | # Initial imports and notebook setup, click arrow to show
from copy import copy
import matplotlib.pyplot as plt
import numpy as np
from HARK.ConsumptionSaving.ConsIndShockModel import PerfForesightConsumerType
from HARK.utilities import plot_funcs
mystr = lambda number: "{:.4f}".format(number)
"""
Explanation: Per... |
rainyear/pytips | Tips/2016-04-30-Enum.ipynb | mit | WEEKDAY = {
'MON': 1,
'TUS': 2,
'WEN': 3,
'THU': 4,
'FRI': 5
}
class Color:
RED = 0
GREEN = 1
BLUE = 2
"""
Explanation: Python 中的枚举类型
枚举类型可以看作是一种标签或是一系列常量的集合,通常用于表示某些特定的有限集合,例如星期、月份、状态等。Python 的原生类型(Built-in types)里并没有专门的枚举类型,但是我们可以通过很多方法来实现它,例如字典、类等:
End of explanation
"""
WEEKDAY... |
tuanavu/coursera-university-of-washington | machine_learning/3_classification/assigment/week2/module-4-linear-classifier-regularization-assignment-blank-graphlab.ipynb | mit | from __future__ import division
import graphlab
"""
Explanation: Logistic Regression with L2 regularization
The goal of this second notebook is to implement your own logistic regression classifier with L2 regularization. You will do the following:
Extract features from Amazon product reviews.
Convert an SFrame into a... |
phoebe-project/phoebe2-docs | 2.3/tutorials/ORB.ipynb | gpl-3.0 | #!pip install -I "phoebe>=2.3,<2.4"
"""
Explanation: 'orb' Datasets and Options
Setup
Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab).
End of explanation
"""
import phoebe
from phoebe import u # units
logger = phoe... |
denstorti/Machine-learning-foundations-python | Study Sentiment Analysis - Babies Products.ipynb | mit | products = pd.read_csv('amazon_baby.csv')
products.head()
products.count()
products.shape
def cleanNaN(value):
if pd.isnull(value):
return ""
else:
return value
"""
Explanation: Loading the data
End of explanation
"""
products['review'] = products['review'].apply(cleanNaN)
products['name... |
TimothyHelton/k2datascience | notebooks/yelp.ipynb | bsd-3-clause | from k2datascience import yelp
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
%matplotlib inline
"""
Explanation: Yelp Dataset Challenge
Timothy Helton
Yelp is a website that allows patrons to review restaurants they have been to. The company runs a regular... |
oscarmore2/deep-learning-study | TFLearn_sentiment/TFLearn_Sentiment_Analysis.ipynb | mit | import pandas as pd
import numpy as np
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical
"""
Explanation: Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network w... |
vzg100/Post-Translational-Modification-Prediction | .ipynb_checkpoints/Phosphorylation Sequence Tests -MLP -dbptm+ELM-VectorAvr.-phos_stripped-checkpoint.ipynb | mit | from pred import Predictor
from pred import sequence_vector
from pred import chemical_vector
"""
Explanation: Template for test
End of explanation
"""
par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"]
for i in par:
print("y", i)
y = Predictor()
y.load_data(file="Data/Trainin... |
mne-tools/mne-tools.github.io | stable/_downloads/ed1a04dd775648ca869bfcffae26faca/30_mne_dspm_loreta.ipynb | bsd-3-clause | import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
"""
Explanation: Source localization with MNE, dSPM, sLORETA, and eLORETA
The aim of this tutorial is to teach you how to compute and apply a linear
minimum-n... |
guyk1971/deep-learning | transfer-learning/Transfer_Learning.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... |
martinjrobins/hobo | examples/optimisation/convenience.ipynb | bsd-3-clause | import pints
# Define a quadratic function f(x)
def f(x):
return 1 + (x[0] - 3) ** 2 + (x[1] + 5) ** 2
# Choose a starting point for the search
x0 = [1, 1]
# Find the arguments for which it is minimised
xopt, fopt = pints.fmin(f, x0, method=pints.XNES)
print(xopt)
print(fopt)
"""
Explanation: Convenience method... |
domschl/syncognite | doc/resilu-linearity.ipynb | mit | import copy
import numpy as np
import matplotlib.pyplot as plt
import math
import sympy
x=np.arange(-20,20,0.01)
def resilu(x):
return x/(1.0-np.exp(x*-1.0))
def relu(x):
y=copy.copy(x)
y[y<0]=0.0
return y
"""
Explanation: The resilu linearity / non-linearity
The function $resilu(x)=\frac{x}{1-... |
Kaggle/learntools | notebooks/nlp/raw/tut1.ipynb | apache-2.0 | import spacy
nlp = spacy.load('en_core_web_sm')
"""
Explanation: Intro
Data comes in many different forms: time stamps, sensor readings, images, categorical labels, and so much more. But text is still some of the most valuable data out there for those who know how to use it.
In this course about Natural Language Pro... |
ColeLab/informationtransfermapping | MasterScripts/Manuscript4_CompModel_GroupAnalysis.ipynb | gpl-3.0 | import numpy as np
import matplotlib.pyplot as plt
from scipy import sparse
% matplotlib inline
import scipy.stats as stats
import statsmodels.api as sm
import CompModel_v7 as cm
cm = reload(cm)
import multiprocessing as mp
import sklearn.preprocessing as preprocessing
import sklearn.svm as svm
import statsmodels.sandb... |
mtchem/Twitter-Politics | NLP-comparing-tweets-fed_docs.ipynb | mit | # general imports
import pandas as pd
import numpy as np
from datetime import datetime
from collections import defaultdict
import pickle
# imports for webscraping and text manipulation
import requests
import re
import io
import urllib
# imports to convert pdf to text
from pdfminer.pdfinterp import PDFResourceManager, P... |
hglanz/phys202-2015-work | assignments/assignment06/ProjectEuler17.ipynb | mit | import math as math
def ones_to_words(n):
onesdict = {0: "",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
}
... |
rencire/commoncs | algs/python/dp/partition_problem.ipynb | mit | # To better match the math equations above, collection starts at index 1 instead of 0
def partition(collection, n, k):
if n == 0:
return "No elements in collection to partition"
# initialize matrix
m = [[float('inf')] * k for _ in range(n+1)]
d = [[-1] * k for _ in range(n+1)]
... |
jrossyra/adaptivemd | examples/tutorial/2_example_run.ipynb | lgpl-2.1 | from __future__ import print_function
from adaptivemd import Project, Trajectory
"""
Explanation: Tutorial 2 - AdaptiveMD Trajectory and Modelling Tasks
adaptivemd relies on ansynchronous simulation execution and analysis. The objects introduced in Tutorial 1 provide the basic interface used to create and organize thi... |
yuhao0531/dmc | notebooks/week-5/02-using your own images.ipynb | apache-2.0 | %matplotlib inline
from matplotlib.pyplot import imshow
import matplotlib.pyplot as plt
import numpy as np
from scipy import misc
import os
import random
import pickle
"""
Explanation: Lab 5.2 - Using your own images
In the next part of the lab we will download another set of images from the web and format them for ... |
tdrussell/stocktwits_analysis | stocktwits_analysis.ipynb | mit | #!pip install pandas_datareader
import io, json, requests, time, os, os.path, math, urllib
from sys import stdout
from collections import Counter
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import svm
from sklearn import linear_model
from pandas_datar... |
prisae/blog-notebooks | MXCH.ipynb | cc0-1.0 | import shapefile
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
"""
Explanation: Plotting the outline of Mexico and Switzerland on top of each other
I wanted to plot Mexico and Switzerland on top of each other, with the same scale, to compare the size and relative distances... |
steinam/teacher | jup_notebooks/data-science-ipython-notebooks-master/misc/Algorithmia.ipynb | mit | pip install algorithmia==0.9.3
import Algorithmia
import pprint
pp = pprint.PrettyPrinter(indent=2)
"""
Explanation: This notebook was prepared by Algorithmia. Source and license info is on GitHub.
Algorithmia
Reference: Algorithmia Documentation
Table of Contents:
1. Installation
2. Authentication
3. Face Detection... |
jonathanmorgan/msu_phd_work | data/article_loading/proquest_hnp/proquest_hnp-article_loading.ipynb | lgpl-3.0 | debug_flag = False
"""
Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Introduction" data-toc-modified-id="Introduction-1"><span class="toc-item-num">1 </span>Introduction</a></span></li><li><span><a href="#Setup" data-toc-modifi... |
tjwei/HackNTU_Data_2017 | Week11/DIY_AI/Softmax-all-solutions.ipynb | mit | # Weight
W = Matrix([1,2],[3,4], [5,6])
W
# Bias
b = Vector(1,0,-1)
b
# 輸入
x = Vector(2,-1)
x
"""
Explanation: Supervised learning for classification
給一堆 $x$, 和他的分類,我們找出計算 x 的分類的方式
One hot encoding
如果我們有三類種類別, 我們可以來編碼這三個類別
* $(1,0,0)$
* $(0,1,0)$
* $(0,0,1)$
問題
為什麼不直接用 1,2,3 這樣的編碼呢?
Softmax Regression 的模型是這樣的
我們的輸... |
arve0/TFY4500 | matrices.ipynb | mit | import numpy as np
import scipy as sp
import scipy.linalg as linalg
"""
Explanation: matrices in python
End of explanation
"""
A = sp.matrix([[1,2,3],[3,1,2],[4,5,7]])
a = np.array([[1,2,3],[3,1,2],[4,5,7]])
A, a
"""
Explanation: ndarray vs matrix
ndarray is recommended
creating
End of explanation
"""
A.T, a.T
"... |
klavinslab/coral | docs/tutorial/seqio.ipynb | mit | import coral as cor
pKL278 = cor.seqio.read_dna('./files_for_tutorial/maps/pMODKan-HO-pACT1GEV.ape')
"""
Explanation: Sequence input/output and complex DNA sequences
More complex sequences (like plasmids) have many annotated pieces and benefit from other methods. sequence.DNA has many methods for accessing and modify... |
DawesLab/LabNotebooks | Superoperators.ipynb | mit | import numpy as np
from qutip import *
# prototype density matrix (i.e. nonsense)
rho = Qobj([[1,2],[3,4]])
rho
rho_v = operator_to_vector(rho)
rho_v
"""
Explanation: A study of superoperators in QuTiP
and some notes about computer implementations in general
Useful references:
- https://en.wikipedia.org/wiki/Super... |
aje/POT | docs/source/auto_examples/plot_otda_mapping_colors_images.ipynb | mit | # Authors: Remi Flamary <remi.flamary@unice.fr>
# Stanislas Chambon <stan.chambon@gmail.com>
#
# License: MIT License
import numpy as np
from scipy import ndimage
import matplotlib.pylab as pl
import ot
r = np.random.RandomState(42)
def im2mat(I):
"""Converts and image to matrix (one pixel per line)"""... |
steinam/teacher | jup_notebooks/data-science-ipython-notebooks-master/python-data/functions.ipynb | mit | %%file transform_util.py
import re
class TransformUtil:
@classmethod
def remove_punctuation(cls, value):
"""Removes !, #, and ?.
"""
return re.sub('[!#?]', '', value)
@classmethod
def clean_strings(cls, strings, ops):
"""General purpose method to clean strin... |
linglaiyao1314/maths-with-python | 03-loops-control-flow.ipynb | mit | from math import pi
def degrees_to_radians(theta_d):
"""
Convert an angle from degrees to radians.
Parameters
----------
theta_d : float
The angle in degrees.
Returns
-------
theta_r : float
The angle in radians.
"""
theta_r = pi / 180.0 *... |
ghvn7777/ghvn7777.github.io | content/fluent_python/11_abstract_class.ipynb | apache-2.0 | class Vector2d:
typecode = 'd'
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def __iter__(self):
return (i for i in (self.x, self.y))
"""
Explanation: 本章讨论的话题是接口,从鸭子类型代表特征动态协议,到使接口更明确,能验证是否符合规定的抽象基类(Abstract Base Class,ABC)
在 Python 中 上章所说的鸭子类型是接口的常规方式,... |
KUrushi/knocks | 05/係り受け解析.ipynb | mit | with open('neko_lattice.txt.cabocha', 'w') as f:
neko = "".join([i for i in open('neko.txt', 'r')])
tree = cabocha.parse(neko)
f.write(tree.toString(CaboCha.FORMAT_LATTICE))
"""
Explanation: 第5章: 係り受け解析
夏目漱石の小説『吾輩は猫である』の文章(neko.txt)をCaboChaを使って係り受け解析し,
その結果をneko.txt.cabochaというファイルに保存せよ.
このファイルを用いて,以下の問に対応す... |
henriquepgomide/caRtola | src/python/colabs/caRtola_como_ler_repositório_do_github_com_BeautifulSoup_e_Pandas.ipynb | mit | # Importar bibliotecas
import re # Expressão regulares
import requests # Acessar páginas da internet
from bs4 import BeautifulSoup # Raspar elementos de páginas da internet
import pandas as pd # Abrir e concatenar bancos de dados
"""
Explanation: <a href=... |
michaelaye/hapi | notebooks/absorption_Coeffs.ipynb | bsd-3-clause | nu, coeff_co2 = hapi.absorptionCoefficient_Voigt(SourceTables='CO2',
Environment={'p': 90,
'T': 700},
OmegaGrid=wavenos,
# ... |
spulido99/NetworksAnalysis | santiagoangee/Ejercicio1.1-Copy1.ipynb | mit | edges = set([(1, 2), (3, 1), (3, 2), (2, 4)])
edges = set([(1, 2), (3, 1), (3, 2), (2, 4)])
edges_list = [i[0] for i in edges] + [i[1] for i in edges]
nodes = set(edges_list)
edges_number = len(edges)
nodes_number = len(nodes)
print "Número de nodos: " + str(nodes_number)
print "Número de enlaces: " + str(edges_numb... |
radio-astro/radiopadre | notebooks/radiopadre-tutorial.ipynb | mit | from radiopadre import ls, settings
dd = ls() # calls radiopadre.ls() to get a directory listing, assigns this to dd
dd # standard notebook feature: the result of the last expression on the cell is rendered in HTML
dd.show()
print "Calling .show() on an object renders it in HTML anyway, same as ... |
shahariarrabby/Mail_Server | .ipynb_checkpoints/Send mail-checkpoint.ipynb | mit | # ! /usr/bin/python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
import getpass
"""
Explanation: Send email Clint
Importing all dependency
End of explanation
"""
def user():
# ORG_EMAIL = "@g... |
torgebo/deep_learning_workshop | 4-gan/2-gan-mnist.ipynb | mit | import numpy as np
from keras.datasets import mnist
import admin.tools as tools
# Load MNIST data
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_data = np.concatenate((X_train, X_test))
"""
Explanation: Generative Adversarial Networks 2
<div class="alert alert-warning">
This is a continuation of the pr... |
indranilsinharoy/PyZDDE | Examples/IPNotebooks/02 Simple fiber coupling analysis using Zemax's POP.ipynb | mit | import os
import numpy as np
import matplotlib.pyplot as plt
import pyzdde.zdde as pyz
%matplotlib inline
ln = pyz.createLink()
"""
Explanation: Simple fiber coupling analysis using Zemax's POP
<img src="https://raw.githubusercontent.com/indranilsinharoy/PyZDDE/master/Doc/Images/articleBanner_02_fibercoupling.png" he... |
buruzaemon/natto-py | notebooks/04_振り仮名変換.ipynb | bsd-2-clause | from natto import MeCab
text = "日本語です。これはカタカナです。ABC123 は全角英数字です。"
"""
Explanation: 振り仮名変換
natto-py を通して文にある漢字の読み方を出力することができます。
-F オプション
まず、 -F オプションを使用して ChaSen 読みの出力を指定します。
End of explanation
"""
katakana = (12449, 12532) # katakana code-points range
hiragana = (12353, 12436) # hiragana code-points range
ka... |
xgrg/thesaurus | doc/Thesaurus.ipynb | mit | j = {'ants_dwi_to_t1': u'ANTS 3 -m CC[ %s, %s, 1, 4] -r Gauss[0,3] -t Elast[1.5] -i 30x20x10 -o %s',
'warp_md_to_t1': u'WarpImageMultiTransform 3 %s %s -R %s %s %s'}
json.dump(j, open('/tmp/templates.json','w'))
"""
Explanation: Simplifying brain-twisting endless commands
and minimize the chance of typos between ... |
muatik/dm | linearRegression.ipynb | mit | # X = np.mat("[2 3;1 3;5 9; 12 21;15 27;20 35;22 40]")
# Y = np.mat("[4 3 8 17 27 35 40]")
# X, Y
df = pd.read_csv("data/cars.csv", sep=";")
def x_normalization(x):
return x - 1960
def y_normalization(x):
return x / 1000
X = x_normalization(np.matrix(df.Year[0:40]).T)
Y = y_normalization(np.matrix(df.Bus[0:4... |
twosigma/beaker-notebook | test/ipynb/python/OutputContainersTest.ipynb | apache-2.0 | # The defining of variable doesn't initiate output
x = "some string"
"""
Explanation: Output Containers and Layout Managers
Output containers are objects that hold a collection of other objects, and displays all its contents, even when they are complex interactive objects and MIME type.
By default the contents are jus... |
tpin3694/tpin3694.github.io | regex/match_us_phone_numbers.ipynb | mit | # Load regex package
import re
"""
Explanation: Title: Match US Phone Numbers
Slug: match_us_phone_numbers
Summary: Match US Phone Numbers
Date: 2016-05-01 12:00
Category: Regex
Tags: Basics
Authors: Chris Albon
Based on: Regular Expressions Cookbook
Preliminaries
End of explanation
"""
# Create a variable contain... |
TESScience/FPE_Test_Procedures | John Doty's Global Calibration of the Housekeeping Data Collection.ipynb | mit | from tessfpe.dhu.fpe import FPE
from tessfpe.dhu.unit_tests import check_house_keeping_voltages
fpe1 = FPE(1, debug=False, preload=False, FPE_Wrapper_version='6.1.1')
print fpe1.version
if check_house_keeping_voltages(fpe1):
print "Wrapper load complete. Interface voltages OK."
"""
Explanation: John Doty's Global ... |
sysid/nbs | lstm/LTSM_explained.ipynb | mit | import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers.embeddings import Embedding
from keras.preprocessing import sequence
N = 1200
N_train = 1000
X = np.zeros((1200, 20))
from numpy.random import choice
#one_indexes = choice(a=N, size=int... |
ES-DOC/esdoc-jupyterhub | notebooks/cams/cmip6/models/sandbox-3/atmos.ipynb | gpl-3.0 | # DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cams', 'sandbox-3', 'atmos')
"""
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: CAMS
Source ID: SANDBOX-3
Topic: Atmos
Sub-Topics: Dynamical Core, Radiation, Turbul... |
answerquest/answerquest.github.io | pandas-benchmark-bmtc-stoptimes.ipynb | gpl-3.0 | import pandas as pd
import time
stop_times = 'GTFSbmtc/test/stop_times.txt'
start = time.time()
df = pd.read_csv(stop_times, na_filter=False)
tripEntries = df.query("trip_id == '994_21_d'")
print(tripEntries)
end = time.time()
print("took {} seconds.".format(round(end-start,2)))
"""
Explanation: Testing Pandas changi... |
ccphillippi/predicting-boston-housing-prices | README.ipynb | mit | # import necessary libraries
import numpy as np
import pandas as pd
from sklearn.cross_validation import ShuffleSplit
%matplotlib inline
from pylab import rcParams
import seaborn as sns
sns.set_style('whitegrid')
rcParams['figure.figsize'] = 16, 13
"""
Explanation: Predicting Boston Housing Prices
I got the opportu... |
tensorflow/agents | docs/tutorials/bandits_tutorial.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... |
rastala/mmlspark | notebooks/samples/202 - Amazon Book Reviews - Word2Vec.ipynb | mit | import pandas as pd
import mmlspark
from pyspark.sql.types import IntegerType, StringType, StructType, StructField
dataFile = "BookReviewsFromAmazon10K.tsv"
textSchema = StructType([StructField("rating", IntegerType(), False),
StructField("text", StringType(), False)])
import os, urllib
if not... |
kit-cel/wt | nt2_ce2/vorlesung/ch_5_synchronization/parameter_offset.ipynb | gpl-2.0 | # importing
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib
# showing figures inline
%matplotlib inline
# plotting options
font = {'size' : 20}
plt.rc('font', **font)
plt.rc('text', usetex=True)
matplotlib.rc('figure', figsize=(18, 6) )
"""
Explanation: Content and O... |
ageron/tensorflow-safari-course | 09_organizing_code.ipynb | apache-2.0 | from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
tf.__version__
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("tmp/data/")
"""
Explanation: Try not to peek at the solutions when you go through the exercises. ;-)
... |
dwhswenson/openpathsampling | examples/alanine_dipeptide_tps/AD_tps_4_advanced.ipynb | mit | from __future__ import print_function
%matplotlib inline
import openpathsampling as paths
import numpy as np
import matplotlib.pyplot as plt
from tqdm.auto import tqdm
import os
import openpathsampling.visualize as ops_vis
from IPython.display import SVG
%%time
flexible = paths.Storage("ad_tps.nc")
%%time
fixed = pat... |
GoogleCloudPlatform/training-data-analyst | courses/machine_learning/deepdive2/introduction_to_tensorflow/labs/tfrecord-tf.example.ipynb | apache-2.0 | !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
#!pip install --upgrade tensorflow==2.5
import tensorflow as tf
import numpy as np
import IPython.display as display
print("TensorFlow version: ",tf.version.VERSION)
"""
Explanation: TFRecord and tf.Example
Learning Objectives
Understand the TFRec... |
vzg100/Post-Translational-Modification-Prediction | .ipynb_checkpoints/Phosphorylation Sequence Tests -svc-checkpoint.ipynb | mit | from pred import Predictor
from pred import sequence_vector
from pred import chemical_vector
"""
Explanation: Template for test
End of explanation
"""
par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"]
for i in par:
print("y", i)
y = Predictor()
y.load_data(file="Data/Trainin... |
joommf/tutorial | workshops/2017-04-05-IOPMagnetism2017/tutorial3_dynamics.ipynb | bsd-3-clause | import oommfc as oc
import discretisedfield as df
%matplotlib inline
# Define macro spin mesh (i.e. one discretisation cell).
p1 = (0, 0, 0) # first point of the mesh domain (m)
p2 = (1e-9, 1e-9, 1e-9) # second point of the mesh domain (m)
cell = (1e-9, 1e-9, 1e-9) # discretisation cell size (m)
mesh = oc.Mesh(p1=p... |
deepfield/ibis | docs/source/notebooks/tutorial/2-Basics-Aggregate-Filter-Limit.ipynb | apache-2.0 | import ibis
import os
hdfs_port = os.environ.get('IBIS_WEBHDFS_PORT', 50070)
hdfs = ibis.hdfs_connect(host='quickstart.cloudera', port=hdfs_port)
con = ibis.impala.connect(host='quickstart.cloudera', database='ibis_testing',
hdfs_client=hdfs)
"""
Explanation: Basics: Aggregation, filtering, l... |
awitney/2017 | hic_workshop_2017/WD/Single-cell_HiC_analysis.ipynb | gpl-3.0 | import os
from hiclib import mapping
from mirnylib import h5dict, genome
bowtie_path = '/opt/conda/bin/bowtie2'
enzyme = 'DpnII'
bowtie_index_path = '/home/jovyan/GENOMES/HG19_IND/hg19_chr1'
fasta_path = '/home/jovyan/GENOMES/HG19_FASTA/'
chrms = ['1']
genome_db = genome.Genome(fasta_pa... |
JaggedParadigm/pyplearnr | pyplearnr_test_code.ipynb | apache-2.0 | import pandas as pd
df = pd.read_pickle('trimmed_titanic_data.pkl')
df.info()
"""
Explanation: pyplearnr demo
Here I demonstrate pyplearnr, a wrapper for building/training/validating scikit learn pipelines using GridSearchCV or RandomizedSearchCV.
Quick keyword arguments give access to optional feature selection (e.... |
infilect/ml-course1 | ml-notebooks/recommendation.ipynb | mit | # Create two user-item matrices, one for training and another for testing
train_data_matrix = np.zeros((n_users, n_items))
for line in train_data.itertuples():
train_data_matrix[line[1]-1, line[2]-1] = line[3]
test_data_matrix = np.zeros((n_users, n_items))
for line in test_data.itertuples():
test_data_matrix[... |
Shatnerz/rhc | ping server.ipynb | mit | import sys
sys.path.append('/opt/rhc')
"""
Explanation: A simple REST service
Here is a rather useless ping server. It accepts GET /test/ping and responds with {"ping": "pong"}.
Start by making sure rhc is in python's path,
End of explanation
"""
import rhc.micro as micro
import rhc.async as async
"""
Explanation: ... |
fullmetalfelix/ML-CSC-tutorial | NeuralNetwork - AtomicCharges.ipynb | gpl-3.0 | # --- INITIAL DEFINITIONS ---
from sklearn.neural_network import MLPRegressor
import numpy, math, random
from scipy.sparse import load_npz
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from ase import Atoms
from visualise import view
"""
Explanation: Atomic Charge Prediction
Introduction
In t... |
Danghor/Formal-Languages | Python/Parse-Table.ipynb | gpl-2.0 | r1 = ('E', ('E', '+', 'P'))
r2 = ('E', ('E', '-', 'P'))
r3 = ('E', ('P'))
r4 = ('P', ('P', '*', 'F'))
r5 = ('P', ('P', '/', 'F'))
r6 = ('P', ('F'))
r7 = ('F', ('(', 'E', ')'))
r8 = ('F', ('NUMBER',))
"""
Explanation: A Parse Table for a Shift-Reduce Parser
This notebook contains the parse table that is needed for a ... |
asazo/CC2 | 5_PDE/schroedinger.ipynb | mit | import numpy as np
from scipy.constants import hbar, electron_mass as me, proton_mass as mp
from scipy.integrate import fixed_quad
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
%matplotlib notebook
"""
Explanation: Resolviendo una PDE: Ecuación de Schrödinger
La Ecua... |
PuPPy-Python/Scientific_Computing | HackNight_19Oct17/xarrayTutorial_SaiNudurupati/Intro_to_xarray.ipynb | mit | # Ignore warnings
import warnings; warnings.simplefilter('ignore')
%matplotlib inline
"""
Explanation: Hack Night - Xarray tutorial - Lvl: basic intro
Author: Sai Nudurupati 19Oct17
Material presented here is extensively mined (copied with permission) from the tutorial (https://github.com/geohackweek/tutorial_conten... |
ethen8181/machine-learning | big_data/spark_pca.ipynb | mit | # code for loading the format for the notebook
import os
# path : store the current path to convert back to it later
path = os.getcwd()
os.chdir(os.path.join('..', 'notebook_format'))
from formats import load_style
load_style(plot_style = False)
os.chdir(path)
# 1. magic for inline plot
# 2. magic to print version
#... |
tensorflow/docs-l10n | site/zh-cn/lattice/tutorials/keras_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... |
googlegenomics/gcp-variant-transforms | docs/sample_queries/gnomad/gnomad.ipynb | apache-2.0 | # Import libraries
import numpy as np
import os
# Imports for using and authenticating BigQuery
from google.colab import auth
"""
Explanation: Sample Notebook for exploring gnomAD in BigQuery
This notebook contains sample queries to explore the gnomAD dataset which is hosted through the Google Cloud Public Datasets P... |
sdpython/pyensae | _doc/notebooks/example_corrplot.ipynb | mit | %matplotlib inline
import pyensae
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import pandas
import numpy
letters = "ABCDEFGHIJKLM"[0:10]
df = pandas.DataFrame(dict(( (k, numpy.random.random(10)+ord(k)-65) for k in letters)))
df.head()
from pyensae.graphhelper import Corrplot
c = Corrplot(df)
c.plot(figs... |
tuanavu/python-cookbook-3rd | notebooks/ch01/11_naming_a_slice.ipynb | mit | ###### 0123456789012345678901234567890123456789012345678901234567890'
record = '....................100 .......513.25 ..........'
cost = int(record[20:32]) * float(record[40:48])
print(cost)
SHARES = slice(20,32)
PRICE = slice(40,48)
cost = int(record[SHARES]) * float(record[PRICE])
print(cost)
"""
E... |
kit-cel/wt | mloc/ch1_Preliminaries/MIMO_least_squares_detection.ipynb | gpl-2.0 | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
"""
Explanation: MIMO Least Squares Detection
This code is provided as supplementary material of the lecture Machine Learning and Optimization in Communications (MLOC).<br>
This code illustrates:
* Toy example of MIMO Detection with constrained lea... |
analysiscenter/dataset | examples/tutorials/research/02_advanced_usage_of_research.ipynb | apache-2.0 | import sys
import os
import shutil
import warnings
warnings.filterwarnings('ignore')
from tensorflow import logging
logging.set_verbosity(logging.ERROR)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import matplotlib
%matplotlib inline
sys.path.append('../../..')
from batchflow import Pipeline, B, C, V, D, L
from batch... |
kwant-project/kwant-tutorial-2016 | 2.2.scattering.ipynb | bsd-2-clause | import numpy as np
import kwant
%run matplotlib_setup.ipy
from matplotlib import pyplot
lat = kwant.lattice.square()
"""
Explanation: Scattering
Previously, we saw how to create finite systems. Now we will create quasi-1d translationally invariant systems and look at their band structures. As a second step, we will... |
anhaidgroup/py_stringsimjoin | notebooks/Joining two tables using Jaccard measure.ipynb | bsd-3-clause | # Import libraries
import py_stringsimjoin as ssj
import py_stringmatching as sm
import pandas as pd
import os, sys
print('python version: ' + sys.version)
print('py_stringsimjoin version: ' + ssj.__version__)
print('py_stringmatching version: ' + sm.__version__)
print('pandas version: ' + pd.__version__)
"""
Explana... |
empirical-org/WikipediaSentences | notebooks/Subordinate Clause Fragment Detection.ipynb | agpl-3.0 | import pandas as pd
import numpy as np
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical
import spacy
nlp = spacy.load('en')
import re
from nltk.util import ngrams, trigrams
import csv
"""
Explanation: TFLearn [Subordinate Clause] Fragment Detection
This notebook is based off the ori... |
mlperf/training_results_v0.5 | v0.5.0/google/cloud_v3.8/ssd-tpuv3-8/code/ssd/model/tpu/tools/colab/shakespeare_with_tpuestimator.ipynb | apache-2.0 | # !rm /content/adc.json
import json
import os
import pprint
import re
import time
import tensorflow as tf
use_tpu = True #@param {type:"boolean"}
bucket = '' #@param {type:"string"}
assert bucket, 'Must specify an existing GCS bucket name'
print('Using bucket: {}'.format(bucket))
if use_tpu:
assert 'COLAB_TPU_... |
hoburg/gpkit | docs/source/ipynb/Fuel/Fuel.ipynb | mit | import numpy as np
from gpkit.shortcuts import *
import gpkit.interactive
%matplotlib inline
"""
Explanation: <img src="fuellogo.svg" style="float:left; padding-right:1em;" width=150 />
AIRPLANE FUEL
Minimize fuel burn for a plane that can sprint and land quickly.
Set up the modelling environment
First we'll to import... |
phoebe-project/phoebe2-docs | 2.0/examples/legacy.ipynb | gpl-3.0 | !pip install -I "phoebe>=2.0,<2.1"
"""
Explanation: Comparing PHOEBE 2 vs PHOEBE Legacy
NOTE: PHOEBE 1.0 legacy is an alternate backend and is not installed with PHOEBE 2.0. In order to run this backend, you'll need to have PHOEBE 1.0 installed.
Setup
Let's first make sure we have the latest version of PHOEBE 2.0 ins... |
enchantner/python-zero | lesson_4/Slides.ipynb | mit | from collections import Counter
def checkio(arr):
counts = Counter(arr)
return [
w for w in arr if counts[w] > 1
]
"""
Explanation: Вопросы по прошлому занятию
* Почему файлы лучше всего открывать через with?
* Зачем нужен Git?
* Как переместить файл из папки "/some/folder" в папку "/another/dir"?... |
roebius/deeplearning_keras2 | nbs/lesson3.ipynb | apache-2.0 | from __future__ import division, print_function
%matplotlib inline
from importlib import reload # Python 3
import utils; reload(utils)
from utils import *
#path = "data/dogscats/sample/"
path = "data/dogscats/"
model_path = path + 'models/'
if not os.path.exists(model_path): os.mkdir(model_path)
#batch_size=1
batch_... |
GoogleCloudPlatform/asl-ml-immersion | notebooks/introduction_to_tensorflow/labs/what_if_mortgage.ipynb | apache-2.0 | import sys
python_version = sys.version_info[0]
print("Python Version: ", python_version)
!pip3 install witwidget
import numpy as np
import pandas as pd
import witwidget
from witwidget.notebook.visualization import WitConfigBuilder, WitWidget
"""
Explanation: LABXX: What-if Tool: Model Interpretability Using Mortga... |
tensorflow/docs-l10n | site/ja/tutorials/customization/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... |
lukechen526/deep-learning | sentiment-rnn/.ipynb_checkpoints/Sentiment RNN Solution-checkpoint.ipynb | mit | import numpy as np
import tensorflow as tf
with open('reviews.txt', 'r') as f:
reviews = f.read()
with open('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 network that performs sentiment analysis.... |
mesgarpour/T-CARER | TCARER_TensorFlow.ipynb | apache-2.0 | # Reload modules
# It is an optional step. It is useful to run when external Python modules are being modified
# It is reloading all modules (except those excluded by %aimport) every time before executing the Python code typed.
# Note: It may conflict with serialisation, when external modules are being modified
# %lo... |
kmorel/kmorel.github.io | images/better-plots/Bar_Basic.ipynb | mit | import pandas
import numpy
import toyplot
import toyplot.pdf
import toyplot.png
import toyplot.svg
print('Pandas version: ', pandas.__version__)
print('Numpy version: ', numpy.__version__)
print('Toyplot version: ', toyplot.__version__)
"""
Explanation: When analyzing data, I usually use the following three module... |
mne-tools/mne-tools.github.io | 0.17/_downloads/285b08fd9daa300c4b586365a3234831/plot_read_evoked.ipynb | bsd-3-clause | # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
from mne import read_evokeds
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
# Reading
condition = 'Left Auditory'
evoked = read_e... |
fivetentaylor/rpyca | RPCA_Testing-3d.ipynb | mit | %matplotlib inline
"""
Explanation: Robust PCA Example
Robust PCA is an awesome relatively new method for factoring a matrix into a low rank component and a sparse component. This enables really neat applications for outlier detection, or models that are robust to outliers.
End of explanation
"""
import matplotlib.... |
ssanderson/pydata-nyc-2015 | notebooks/Pipeline Demo.ipynb | cc0-1.0 | from zipline.pipeline.data import USEquityPricing as USEP
from zipline.pipeline.factors import SimpleMovingAverage
# sma30 and sma90 are Factors.
# Factors represent computations producing numerical-valued outputs.
sma30 = SimpleMovingAverage(inputs=[USEP.close], window_length=30)
sma90 = SimpleMovingAverage(inputs=[U... |
tensorflow/docs-l10n | site/zh-cn/guide/keras/transfer_learning.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... |
Echelle/AO_bonding_paper | notebooks/SiGaps_20_Thorlabs_filter_curve.ipynb | mit | %matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
"""
Explanation: This IPython Notebook is for integrating filter curves with the spectra to show the Si gap's effect size on tranmission in IR imaging.
Author: Michael Gully-Santiago, gully@astro.as.utexas.e... |
tensorflow/fairness-indicators | g3doc/tutorials/Fairness_Indicators_Example_Colab.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... |
sf-wind/caffe2 | caffe2/python/tutorials/experimental/Immediate.ipynb | apache-2.0 | %matplotlib inline
from caffe2.python import cnn, core, visualize, workspace, model_helper, brew
import numpy as np
import os
core.GlobalInit(['caffe2', '--caffe2_log_level=-1'])
"""
Explanation: Tutorial 4. Immediate mode
In this tutorial we will talk about a cute feature about Caffe2: immediate mode.
From the previo... |
aleph314/K2 | Foundations/Python CS/Activity 02.ipynb | gpl-3.0 | # Get input from user
score = float(input('What\'s your score? '))
if score < 0 or score > 100:
print('Score must be between 0 and 100')
elif score < 45:
print('Did you try?')
elif score < 66:
print('Need improvement')
elif score < 76.5:
print('Good')
elif score < 82:
print('Very good')
else:
p... |
rrbb014/data_science | fastcampus_dss/2016_05_17/2016_0517_행렬의 연산과 성질.ipynb | mit | A = (np.arange(9) - 4).reshape((3, 3))
A
np.linalg.norm(A)
"""
Explanation: 행렬의 연산과 성질
행렬에는 곱셈, 전치 이외에도 지수 함수 등의 다양한 연산을 정의할 수 있다. 각각의 정의와 성질을 알아보자.
행렬의 부호
행렬은 복수의 실수 값을 가지고 있으므로 행렬 전체의 부호는 정의할 수 없다. 하지만 행렬에서도 실수의 부호 정의와 유사한 기능을 가지는 정의가 존재한다. 바로 행렬의 양-한정(positive definite) 특성이다.
모든 실수 공간 $\mathbb{R}^n$ 의 0벡터가 아닌 벡터 $... |
ES-DOC/esdoc-jupyterhub | notebooks/bcc/cmip6/models/bcc-csm2-mr/atmos.ipynb | gpl-3.0 | # DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'bcc', 'bcc-csm2-mr', 'atmos')
"""
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: BCC
Source ID: BCC-CSM2-MR
Topic: Atmos
Sub-Topics: Dynamical Core, Radiation, Turb... |
joverbee/electromagnetism_course | multipole.ipynb | gpl-3.0 | import numpy as np
import matplotlib.pyplot as plt
"""
Explanation: Visualisation of a generic multipole
This notebook shows how to numerically calculate and visualise the fields around an electrostatic multipole.
Questions:
do you see local minima or maxima in the potential? (would a 3D generalisation be better?)
wh... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.