repo_name
stringlengths
6
77
path
stringlengths
8
215
license
stringclasses
15 values
content
stringlengths
335
154k
Atomahawk/flagging-suspicious-blockchain-transactions
lab_notebooks/spark-play.ipynb
mit
# from pyspark import SparkContext from pyspark.mllib.clustering import KMeans, KMeansModel # http://spark.apache.org/docs/2.0.0/api/python/pyspark.mllib.html#pyspark.mllib.classification.NaiveBayesModel from pyspark.mllib.classification import NaiveBayesModel # http://spark.apache.org/docs/2.0.0/api/python/pyspark.m...
karlstroetmann/Artificial-Intelligence
Python/1 Search/A-Star-Search-Slim.ipynb
gpl-2.0
import heapq """ Explanation: Improved A$^*$ First Search The module heapq provides priority queues that are implemented as heaps. Technically, these heaps are just lists. In order to use them as priority queues, the entries of these lists will be pairs of the form $(p, o)$, where $p$ is the priority of the object ...
mohanprasath/Course-Work
coursera/python_for_data_science/2.1_Tuples.ipynb
gpl-3.0
tuple1=("disco",10,1.2 ) tuple1 """ Explanation: <a href="http://cocl.us/topNotebooksPython101Coursera"><img src = "https://ibm.box.com/shared/static/yfe6h4az47ktg2mm9h05wby2n7e8kei3.png" width = 750, align = "center"></a> <a href="https://www.bigdatauniversity.com"><img src = "https://ibm.box.com/shared/static/ugcqz6...
NYUDataBootcamp/Projects
UG_S17/Booth_Praveen_Final_Project.ipynb
mit
import pandas as pd # data package import matplotlib.pyplot as plt # graphics import datetime as dt # date tools, used to note current date import requests from bs4 import BeautifulSoup import urllib.request from matplotlib.offsetbox import OffsetImage %matplotlib inline #per game statistics...
thehackerwithin/berkeley
code_examples/python_matplotlib/Matplotlib_THW_tutorial.ipynb
bsd-3-clause
import matplotlib as mpl mpl # I normally prototype my code in an editor + ipy terminal. # In those cases I import pyplot and numpy via import matplotlib.pyplot as plt import numpy as np # In Jupy notebooks we've got magic functions and pylab gives you pyplot as plt and numpy as np # %pylab # Additionally, inline ...
amueller/nyu_ml_lectures
First Steps.ipynb
bsd-2-clause
from sklearn.datasets import load_digits digits = load_digits() from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target) X_train.shape """ Explanation: Get some data to play with End of ex...
sysid/nbs
LP/Introduction-to-linear-programming/LaTeX_formatted_ipynb_files/Introduction to Linear Programming with Python - Part 4.ipynb
mit
import pulp # Instantiate our problem class model = pulp.LpProblem("Cost minimising blending problem", pulp.LpMinimize) """ Explanation: Introduction to Linear Programming with Python - Part 4 Real world examples - Blending Problem We're going to make some sausages! We have the following ingredients available to us: ...
quantumlib/Cirq
docs/gatezoo.ipynb
apache-2.0
try: import cirq except ImportError: print("installing cirq...") !pip install --quiet --pre cirq print("installed cirq.") import IPython.display as ipd import cirq import inspect def display_gates(*gates): for gate_name in gates: ipd.display(ipd.Markdown("---")) gate = getattr(...
miykael/nipype_tutorial
notebooks/basic_mapnodes.ipynb
bsd-3-clause
from nipype import Function def square_func(x): return x ** 2 square = Function(["x"], ["f_x"], square_func) """ Explanation: MapNode If you want to iterate over a list of inputs, but need to feed all iterated outputs afterward as one input (an array) to the next node, you need to use a MapNode. A MapNode is quite...
giacomov/3ML
docs/notebooks/Quickstart.ipynb
bsd-3-clause
from threeML import * # Let's generate some data with y = Powerlaw(x) gen_function = Powerlaw() # Generate a dataset using the power law, and a # constant 30% error x = np.logspace(0, 2, 50) xyl_generator = XYLike.from_function("sim_data", function = gen_function, x = x, ...
jakevdp/sklearn_tutorial
notebooks/04.2-Clustering-KMeans.ipynb
bsd-3-clause
%matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy import stats plt.style.use('seaborn') """ Explanation: <small><i>This notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small> Clustering: K-Means In-Depth Here we'll explore K Means Clustering, whi...
GSimas/EEL7045
.ipynb_checkpoints/Aula 10 - Circuitos RL-checkpoint.ipynb
mit
print("Exemplo 7.3") import numpy as np from sympy import * I0 = 10 L = 0.5 R1 = 2 R2 = 4 t = symbols('t') #Determinar Req = Rth #Io hipotético = 1 A #Analise de Malhas #4i2 + 2(i2 - i0) = -3i0 #6i2 = 5 #i2 = 5/6 #ix' = i2 - i1 = 5/6 - 1 = -1/6 #Vr1 = ix' * R1 = -1/6 * 2 = -1/3 #Rth =...
armandosrz/UdacityNanoMachine
titanic-survival-exploration/titanic_survival_exploration/Titanic_Survival_Exploration.ipynb
apache-2.0
import numpy as np import pandas as pd # RMS Titanic data visualization code from titanic_visualizations import survival_stats from IPython.display import display %matplotlib inline # Load the dataset in_file = 'titanic_data.csv' full_data = pd.read_csv(in_file) # Print the first few entries of the RMS Titanic data...
scotthuang1989/Python-3-Module-of-the-Week
BeautifulSoup/Improving Performance by Parsing Only Part of the Document.ipynb
apache-2.0
from bs4 import BeautifulSoup,SoupStrainer import re doc = '''Bob reports <a href="http://www.bob.com/">success</a> with his plasma breeding <a href="http://www.bob.com/plasma">experiments</a>. <i>Don't get any on us, Bob!</i> <br><br>Ever hear of annular fusion? The folks at <a href="http://www.boogabooga.net/">Boog...
citxx/sis-python
crash-course/slices.ipynb
mit
lst = [1, 2, 3, 4, 5, 6, 7, 8] print(lst[::]) """ Explanation: <h1>Содержание<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Получение-среза" data-toc-modified-id="Получение-среза-1">Получение среза</a></span><ul class="toc-item"><li><span><a href="#Без-параметров" data-toc...
phoebe-project/phoebe2-docs
2.3/examples/legacy_spots.ipynb
gpl-3.0
#!pip install -I "phoebe>=2.3,<2.4" """ Explanation: Comparing Spots in PHOEBE 2 vs PHOEBE Legacy 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 # un...
shareactorIO/pipeline
source.ml/jupyterhub.ml/notebooks/zz_old/TensorFlow/HvassLabsTutorials/05_Ensemble_Learning.ipynb
apache-2.0
from IPython.display import Image Image('images/02_network_flowchart.png') """ Explanation: TensorFlow Tutorial #05 Ensemble Learning by Magnus Erik Hvass Pedersen / GitHub / Videos on YouTube Introduction This tutorial shows how to use a so-called ensemble of convolutional neural networks. Instead of using a single n...
agentzh2m/muic_class_freq
class_freq.ipynb
mit
df = pd.read_csv('t2_2016.csv') df = df[df['Type'] == 'master'] df.head() #format [Day, start_time, end_time] def time_extract(s): s = str(s).strip().split(" "*16) def helper(s): try: temp = s.strip().split(" ")[1:] comb = temp[:2] + temp[3:] comb[0] = comb[0][1:] ...
faneshion/MatchZoo
tutorials/data_handling.ipynb
apache-2.0
data_pack = mz.datasets.toy.load_data() data_pack.left.head() data_pack.right.head() data_pack.relation.head() """ Explanation: DataPack Structure matchzoo.DataPack is a MatchZoo native data structure that most MatchZoo data handling processes build upon. A matchzoo.DataPack consists of three parts: left, right and...
GoogleCloudPlatform/training-data-analyst
courses/machine_learning/deepdive2/launching_into_ml/labs/intro_logistic_regression.ipynb
apache-2.0
import os import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline """ Explanation: Introduction to Logistic Regression Learning Objectives Create Seaborn plots for Exploratory Data Analysis Train a Logistic Regression Model using Scikit-Learn Introduction This...
sindrerb/VecDiSCS
notebooks/Generate.ipynb
gpl-3.0
lattice = np.array([[ 3.2871687359128612, 0.0000000000000000, 0.0000000000000000], [-1.6435843679564306, 2.8467716318265182, 0.0000000000000000], [ 0.0000000000000000, 0.0000000000000000, 5.3045771064003047]]) positions = [[0.3333333333333357, 0.6666666666666643, 0.99968143309...
fcollonval/coursera_data_visualization
Analysis_Variance.ipynb
mit
# Magic command to insert the graph directly in the notebook %matplotlib inline # Load a useful Python libraries for handling data import pandas as pd import numpy as np import statsmodels.formula.api as smf import seaborn as sns import matplotlib.pyplot as plt from IPython.display import Markdown, display # Read the ...
ManyBodyPhysics/NuclearForces
doc/exercises/Variable_Phase_Approach.ipynb
cc0-1.0
# I know you're not supposed to do this to avoid namespace issues, but whatever from numpy import * from matplotlib.pyplot import * # Global variables for this notebook mu=1. R=1. hbar=1. """ Explanation: Preliminaries In this notebook, we compute the phase shifts of the potential with $V = -V0$ for $r < R$ and $V=0$...
GoogleCloudPlatform/practical-ml-vision-book
07_training/07c_export.ipynb
apache-2.0
import tensorflow as tf print('TensorFlow version' + tf.version.VERSION) print('Built with GPU support? ' + ('Yes!' if tf.test.is_built_with_cuda() else 'Noooo!')) print('There are {} GPUs'.format(len(tf.config.experimental.list_physical_devices("GPU")))) device_name = tf.test.gpu_device_name() if device_name != '/devi...
mbeyeler/opencv-machine-learning
notebooks/06.01-Implementing-Your-First-Support-Vector-Machine.ipynb
mit
from sklearn import datasets X, y = datasets.make_classification(n_samples=100, n_features=2, n_redundant=0, n_classes=2, random_state=7816) """ Explanation: <!--BOOK_INFORMATION--> <a href="https://www.packtpub.com/big-data-and-business-intellige...
vicente-gonzalez-ruiz/YAPT
scientific_computation/about_accuracy.ipynb
cc0-1.0
x = 7**273 print(x) print(type(x)) """ Explanation: About arithmetic accuracy in Python <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Integers" data-toc-modified-id="Integers-1"><span class="toc-item-num">1&nbsp;&nbsp;</span><a href="https://docs.pyth...
dashee87/blogScripts
Jupyter/2017-12-19-charting-the-rise-of-song-collaborations-with-scrapy-and-pandas.ipynb
mit
import scrapy import re # for text parsing import logging class ChartSpider(scrapy.Spider): name = 'ukChartSpider' # page to scrape start_urls = ['http://www.officialcharts.com/charts/'] # if you want to impose a delay between sucessive scrapes # download_delay = 0.5 def parse(self, response): ...
mne-tools/mne-tools.github.io
dev/_downloads/d418deb5d74ab4363c42409de6a8e6df/label_source_activations.ipynb
bsd-3-clause
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Eric Larson <larson.eric.d@gmail.com> # # License: BSD-3-Clause import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects import mne from mne.datasets import sample from mne.minimum_norm import read_inverse_operator, apply_inve...
smorton2/think-stats
code/chap03soln.ipynb
gpl-3.0
from __future__ import print_function, division %matplotlib inline import numpy as np import nsfg import first import thinkstats2 import thinkplot """ Explanation: Examples and Exercises from Think Stats, 2nd Edition http://thinkstats2.com Copyright 2016 Allen B. Downey MIT License: https://opensource.org/licenses/...
spacy-io/thinc
examples/04_parallel_training_ray.ipynb
mit
# To let ray install its own version in Colab !pip uninstall -y pyarrow # You might need to restart the Colab runtime !pip install --upgrade "thinc>=8.0.0a0" "ml_datasets>=0.2.0a0" ray psutil setproctitle """ Explanation: Parallel training with Thinc and Ray This notebook is based off one of Ray's tutorials and shows...
bramacchino/numberSense
Plotly-Mesh3d.ipynb.ipynb
mit
from IPython.display import HTML HTML('<iframe src=https://plot.ly/~empet/13475/ width=850 height=350></iframe>') """ Explanation: Generating and Visualizing Alpha Shapes with Python Plotly Notebook available at https://plot.ly/~notebook_demo/125/generating-and-visualizing-alpha-shapes/ Starting with a finite set of...
tensorflow/tfx-addons
tfx_addons/schema_curation/example/taxi_example_colab.ipynb
apache-2.0
!pip install -U tfx x = !pwd if 'schemacomponent' not in str(x): !git clone https://github.com/rcrowe-google/schemacomponent %cd schemacomponent/example """ Explanation: <a href="https://colab.research.google.com/github/rcrowe-google/schemacomponent/blob/Nirzari%2Ffeature%2Fexample/example/taxi_example_colab.ipy...
sassoftware/sas-viya-programming
communities/Getting a CASTable Object from an Existing CAS Table.ipynb
apache-2.0
import swat conn = swat.CAS(host, port, username, password) """ Explanation: Getting a Python CASTable Object from an Existing CAS Table Many of the examples in the Python series of articles here use a CASTable object to invoke actions or apply DataFrame-like syntax to CAS tables. In those examples, the CASTable obj...
csiu/100daysofcode
misc/day85.ipynb
mit
url = "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json" """ Explanation: I want to look into stock data. Yahoo Finance API According to stackoverflow ("alternative to google finance api"), financial information can be obtained through the Yahoo Finance API. For instance, you can generate...
AtmaMani/pyChakras
python_crash_course/seaborn_cheat_sheet_2.ipynb
mit
import seaborn as sns %matplotlib inline tips = sns.load_dataset('tips') tips.head() """ Explanation: Seaborn - categorical plotting End of explanation """ sns.barplot(x='sex', y='total_bill', data=tips) """ Explanation: ToC - Barplot - Countplot - Boxplot - Violin plot - Strip plot - Swarm plot Barplot Barpl...
deepcharles/ruptures
docs/examples/text-segmentation.ipynb
bsd-2-clause
from pathlib import Path import nltk import numpy as np import ruptures as rpt # our package from nltk.corpus import stopwords from nltk.stem import PorterStemmer from nltk.tokenize import regexp_tokenize from ruptures.base import BaseCost from sklearn.feature_extraction.text import CountVectorizer from sklearn.metri...
jorisvandenbossche/DS-python-data-analysis
_solved/00-jupyter_introduction.ipynb
bsd-3-clause
from IPython.display import Image Image(url='http://python.org/images/python-logo.gif') """ Explanation: <p><font size="6"><b>Jupyter notebook INTRODUCTION </b></font></p> © 2021, Joris Van den Bossche and Stijn Van Hoey (&#106;&#111;&#114;&#105;&#115;&#118;&#97;&#110;&#100;&#101;&#110;&#98;&#111;&#115;&#115;&#99;&...
t-davidson/hate-speech-and-offensive-language
src/Automated Hate Speech Detection and the Problem of Offensive Language Python 3.6.ipynb
mit
import pandas as pd import numpy as np import pickle import sys from sklearn.feature_extraction.text import TfidfVectorizer import nltk from nltk.stem.porter import * import string import re from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer as VS from textstat.textstat import * from sklearn.linear_mo...
zenoss/pywbem
docs/notebooks/subscriptionmanager.ipynb
lgpl-2.1
from __future__ import print_function import pywbem # The WBEM server that should emit the indications server = 'http://myserver' username = 'user' password = 'password' # The URL of the WBEM listener listener_url = 'http://mylistener' conn = pywbem.WBEMConnection(server, (username, password), ...
sallai/mbuild
docs/tutorials/tutorial_simple_LJ.ipynb
mit
import mbuild as mb class MonoLJ(mb.Compound): def __init__(self): super(MonoLJ, self).__init__() lj_particle1 = mb.Particle(name='LJ', pos=[0, 0, 0]) self.add(lj_particle1) lj_particle2 = mb.Particle(name='LJ', pos=[1, 0, 0]) self.add(lj_particle2) lj_particle3 = ...
Alex-Ian-Hamilton/solarbextrapolation
docs/auto_examples/plot_define_and_run_trivial_analytical_model.ipynb
mit
# Module imports from solarbextrapolation.map3dclasses import Map3D from solarbextrapolation.analyticalmodels import AnalyticalModel from solarbextrapolation.visualisation_functions import visualise """ Explanation: Defining and Run a Custom Analytical Model Here you will be creating trivial analytical model following...
giacomov/astromodels
examples/Point_source_tutorial.ipynb
bsd-3-clause
from astromodels import * # Using J2000 R.A. and Dec (ICRS), which is the default coordinate system: simple_source_icrs = PointSource('simple_source', ra=123.2, dec=-13.2, spectral_shape=powerlaw()) """ Explanation: Point sources In astromodels a point source is described by its position in the sky and its spectral ...
astroumd/GradMap
notebooks/Lectures2018/Lecture4/Lecture4-2BodyProblem-Student.ipynb
gpl-3.0
#Physical Constants (SI units) G=6.67e-11 AU=1.5e11 #meters. Distance between sun and earth. daysec=24.0*60*60 #seconds in a day """ Explanation: Welcome to your first numerical simulation! The 2 Body Problem Many problems in statistical physics and astrophysics requiring solving problems consisting of many particles ...
jupyter-widgets/ipywidgets
docs/source/examples/Widget Styling.ipynb
bsd-3-clause
from ipywidgets import Button, Layout b = Button(description='(50% width, 80px height) button', layout=Layout(width='50%', height='80px')) b """ Explanation: Layout and Styling of Jupyter widgets This notebook presents how to layout and style Jupyter interactive widgets to build rich and reactive widget-ba...
lwahedi/CurrentPresentation
talks/MDI2/Scraping+Lecture.ipynb
mit
import pandas as pd import numpy as np import pickle import statsmodels.api as sm from sklearn import cluster import matplotlib.pyplot as plt %matplotlib inline from bs4 import BeautifulSoup as bs import requests import time # from ggplot import * """ Explanation: Collecting and Using Data in Python Laila A. Wahedi Ma...
vikashvverma/machine-learning
mlfoundation/istat/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 read_csv(filename): with open(filename, 'rb') as f: r...
GoogleCloudPlatform/training-data-analyst
quests/sparktobq/02_gcs.ipynb
apache-2.0
# Catch up cell. Run if you did not do previous notebooks of this sequence !wget http://kdd.ics.uci.edu/databases/kddcup99/kddcup.data_10_percent.gz """ Explanation: Migrating from Spark to BigQuery via Dataproc -- Part 2 Part 1: The original Spark code, now running on Dataproc (lift-and-shift). Part 2: Replace HDFS ...
dougkelly/SmartMeterResearch
SmartMeterResearch_Phase2.ipynb
apache-2.0
s3 = boto3.client('s3') s3.list_buckets() def create_s3_bucket(bucketname): """Quick method to create bucket with exception handling""" s3 = boto3.resource('s3') exists = True bucket = s3.Bucket(bucketname) try: s3.meta.client.head_bucket(Bucket=bucketname) except botocore.exceptions.C...
LSSTC-DSFP/LSSTC-DSFP-Sessions
Sessions/Session07/Day0/TooBriefVisualization.ipynb
mit
import numpy as np import matplotlib.pyplot as plt %matplotlib inline """ Explanation: Introduction to Visualization: Density Estimation and Data Exploration Version 0.1 There are many flavors of data analysis that fall under the "visualization" umbrella in astronomy. Today, by way of example, we will focus on 2 basic...
antoniomezzacapo/qiskit-tutorial
community/terra/qis_adv/topological_quantum_walk.ipynb
apache-2.0
#initialization import sys import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing QISKit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import Aer, IBMQ, execute from qiskit.wrapper.jupyter import * from qiskit.backends.ibmq import least_busy from qiskit....
sertansenturk/tomato
demos/score_analysis_demo.ipynb
agpl-3.0
score_data = scoreAnalyzer.analyze(txt_filename, mu2_filename, symbtr_name=symbtr_name) # pretty print the metadata pprint(score_data['metadata']) """ Explanation: You can use the single line call "analyze," which does all the available analysis simultaneously End of explanation """ from tomato.metadata.symbtr im...
rastala/mmlspark
notebooks/samples/102 - Regression Example with Flight Delay Dataset.ipynb
mit
import numpy as np import pandas as pd import mmlspark """ Explanation: 102 - Training Regression Algorithms with the L-BFGS Solver In this example, we run a linear regression on the Flight Delay dataset to predict the delay times. We demonstrate how to use the TrainRegressor and the ComputePerInstanceStatistics APIs....
4dsolutions/Python5
STEM Mathematics.ipynb
mit
from itertools import accumulate, islice def cubocta(): """ Classic Generator: Cuboctahedral / Icosahedral #s https://oeis.org/A005901 """ yield 1 # nuclear ball f = 1 while True: elem = 10 * f * f + 2 # f for frequency yield elem # <--- pause / resume here f +...
castanan/w2v
ml-scripts/Word2Vec with Tweets.ipynb
mit
t0 = time.time() datapath = '/Users/jorgecastanon/Documents/github/w2v/data/tweets.gz' tweets = sqlContext.read.json(datapath) tweets.registerTempTable("tweets") twr = tweets.count() print "Number of tweets read: ", twr # this line add ~7 seconds (from ~24.5 seconds to ~31.5 seconds) # Number of tweets read: 239082 p...
kit-cel/wt
sigNT/signals_transforms/rect_sinc.ipynb
gpl-2.0
import numpy as np import matplotlib import matplotlib.pyplot as plt %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 Objective Show different aspects when dealing with FFT Using ...
farr/emcee
docs/_static/notebooks/autocorr.ipynb
mit
import numpy as np import matplotlib.pyplot as plt np.random.seed(1234) # Build the celerite model: import celerite from celerite import terms kernel = terms.RealTerm(log_a=0.0, log_c=-6.0) kernel += terms.RealTerm(log_a=0.0, log_c=-2.0) # The true autocorrelation time can be calculated analytically: true_tau = sum(...
pagutierrez/tutorial-sklearn
notebooks-spanish/20-clustering_jerarquico_y_basado_densidades.ipynb
cc0-1.0
from sklearn import datasets iris = datasets.load_iris() X = iris.data[:, [2, 3]] y = iris.target n_samples, n_features = X.shape plt.scatter(X[:, 0], X[:, 1], c=y); """ Explanation: Aprendizaje no supervisado: algoritmos de clustering jerárquicos y basados en densidades En el cuaderno número 8, introdujimos uno de ...
mavillan/SciProg
01_intro/01_intro.ipynb
gpl-3.0
%matplotlib inline import numpy as np import matplotlib.pyplot as plt import scipy as sp """ Explanation: <h1 align="center">Scientific Programming in Python</h1> <h2 align="center">Topic 1: Introduction and basic tools </h2> Notebook created by Martín Villanueva - martin.villanueva@usm.cl - DI UTFSM - April 2017. En...
cochoa0x1/integer-programming-with-python
04-packing-and-allocation/knapsack_problem.ipynb
mit
from pulp import * import numpy as np """ Explanation: Knapsack Problem Bin packing tried to minimize the number of bins needed for a fixed number of items, if we instead fix the number of bins and assign some way to value objects, then the knapsack problem tells us which objects to take to maximize our total item val...
GoogleCloudPlatform/training-data-analyst
courses/unstructured/ML-Tests-Solution.ipynb
apache-2.0
from googleapiclient.discovery import build import subprocess images = subprocess.check_output(["gsutil", "ls", "gs://{}/unstructured/photos".format(BUCKET)]) images = list(filter(None,images.split('\n'))) print(images) """ Explanation: <h2> Finding specific text in a corpus of scanned documents </h2> End of explanat...
ocefpaf/secoora
notebooks/timeSeries/ssh/01-skill_score.ipynb
mit
import os try: import cPickle as pickle except ImportError: import pickle run_name = '2014-07-07' fname = os.path.join(run_name, 'config.pkl') with open(fname, 'rb') as f: config = pickle.load(f) import numpy as np from pandas import DataFrame, read_csv from utilities import (load_secoora_ncs, to_html, ...
ES-DOC/esdoc-jupyterhub
notebooks/hammoz-consortium/cmip6/models/sandbox-2/aerosol.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'hammoz-consortium', 'sandbox-2', 'aerosol') """ Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: HAMMOZ-CONSORTIUM Source ID: SANDBOX-2 Topic: Aerosol Sub-Topics: T...
HrantDavtyan/Data_Scraping
Week 5/Working_with_XML_docs.ipynb
apache-2.0
data = ''' <xml_data> <person> <id>01</id> <name> <first>Hrant</first> <last>Davtyan</last> </name> <status organization="AUA">Instructor</status> </person> <person> <id>02</id> <name> <first>Jack</first> <last>N...
Startupsci/data-science-notebooks
.ipynb_checkpoints/titanic-kaggle-old-checkpoint.ipynb
mit
df['Gender'] = df['Sex'].map( {'female': 0, 'male': 1} ).astype(int) df.head() """ Explanation: Convert Sex feature to numeric End of explanation """ df['Age'].dropna().hist(bins=16, range=(0,80), alpha = .5) P.show() median_ages = np.zeros((2,3)) median_ages for i in range(0, 2): for j in range(0, 3): ...
satishkt/ML-Foundations-Coursera
Week3-Classification/.ipynb_checkpoints/Analyzing product sentiment-checkpoint.ipynb
bsd-2-clause
import graphlab """ Explanation: Predicting sentiment from product reviews Fire up GraphLab Create End of explanation """ products = graphlab.SFrame('amazon_baby.gl/') """ Explanation: Read some product review data Loading reviews for a set of baby products. End of explanation """ products.head() """ Explanation...
grokkaine/biopycourse
day1/.ipynb_checkpoints/tutorial-checkpoint.ipynb
cc0-1.0
# This is a line comment. """ A multi-line comment. """ a = None #Just declared an empty object print(a) a = 1 print(a) a = 'abc' print(a) b = 3 c = [1, 2, 3] a = [a, 2, b, 1., 1.2e-5, True] #This is a list. print(a) ## Python is a dynamic language a = 1 print(type(a)) print(a) a = "spam" print(type(a)) print(a) a = ...
jorisvandenbossche/DS-python-data-analysis
notebooks/pandas_03a_selecting_data.ipynb
bsd-3-clause
import pandas as pd # redefining the example DataFrame data = {'country': ['Belgium', 'France', 'Germany', 'Netherlands', 'United Kingdom'], 'population': [11.3, 64.3, 81.3, 16.9, 64.9], 'area': [30510, 671308, 357050, 41526, 244820], 'capital': ['Brussels', 'Paris', 'Berlin', 'Amsterdam', 'Lo...
slundberg/shap
notebooks/benchmark/text/Abstractive Summarization Benchmark Demo.ipynb
mit
import numpy as np from transformers import AutoTokenizer, AutoModelForSeq2SeqLM import torch import nlp import shap import shap.benchmark as benchmark """ Explanation: Text Data Explanation Benchmarking: Abstractive Summarization This notebook demonstrates how to use the benchmark utility to benchmark the performance...
Kaggle/learntools
notebooks/machine_learning/raw/tut_automl.ipynb
apache-2.0
#$HIDE_INPUT$ # Save CSV file with first 2 million rows only import pandas as pd train_df = pd.read_csv("../input/new-york-city-taxi-fare-prediction/train.csv", nrows = 2_000_000) train_df.to_csv("train_small.csv", index=False) PROJECT_ID = 'kaggle-playground-170215' BUCKET_NAME = 'automl-tutorial-alexis' DATASET_DIS...
QuantScientist/Deep-Learning-Boot-Camp
day03/Advanced_Keras_Tutorial/1.0 Multi-Modal Networks.ipynb
mit
!pip install keras==2.0.8 from keras.datasets import mnist from keras.layers import * from keras.layers import Dense, Input, Flatten from keras.models import Model from keras.layers.merge import concatenate from keras.utils import np_utils img_rows, img_cols = 28, 28 if K.image_data_format() == 'channels_first': ...
tolaoniyangi/dmc
notebooks/week-3/01-basic ann.ipynb
apache-2.0
%matplotlib inline import random import numpy as np import matplotlib.pyplot as plt import seaborn as sns; sns.set(style="ticks", color_codes=True) from sklearn.preprocessing import OneHotEncoder from sklearn.utils import shuffle """ Explanation: Lab 3 - Basic Artificial Neural Network In this lab we will build a very...
CosmoJG/neural-heatmap
cable-properties/cable-length-calculator.ipynb
gpl-3.0
# Imports import sys # Required for system access (below) import os # Required for os access (below) sys.path.append(os.path.join(os.path.dirname(os.getcwd()), 'dependencies')) from neuron_readExportedGeometry import * # Required to interpret hoc files """ Explanation: Cable Length Calculator This program reads a neur...
planetlabs/notebooks
jupyter-notebooks/analytics/change_detection_heatmap.ipynb
apache-2.0
!pip install cython !pip install https://github.com/SciTools/cartopy/archive/v0.18.0.zip """ Explanation: Creating a Heatmap of Vector Results In this notebook, you'll learn how to use Planet's Analytics API to display a heatmap of vector analytic results, specifically buildng change detections. This can be used to i...
GSimas/EEL7045
Aula 9.3 - Circuitos RC.ipynb
mit
print("Exemplo 7.1") import numpy as np from sympy import * C = 0.1 v0 = 15 t = symbols('t') Req1 = 8 + 12 Req2 = Req1*5/(Req1 + 5) tau = C*Req2 vc = v0*exp(-t/tau) vx = vc*12/(12 + 8) ix = vx/12 print("Tensão Vc:",vc,"V") print("Tensão Vx:",vx,"V") print("Corrente ix:",ix,"A") """ Explanation: Circuitos Lineares...
qinwf-nuan/keras-js
notebooks/layers/pooling/GlobalMaxPooling3D.ipynb
mit
data_in_shape = (6, 6, 3, 4) L = GlobalMaxPooling3D(data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(270) data_in = 2 * np.random.random(data_in_shape) - 1 result ...
njtwomey/ADS
03_data_transformation_and_integration/01_wrangling_casas.ipynb
mit
## from __future__ import print_function # uncomment if using python 2 from os.path import join import pandas as pd import numpy as np from datetime import datetime %matplotlib inline """ Explanation: Applied Data Science Data Wrangling Niall Twomey To contact, please email &lt;firstname&gt;.&lt;lastname&gt;@brist...
snth/ctdeep
MNIST Tutorial.ipynb
mit
from __future__ import absolute_import from __future__ import print_function from ipywidgets import interact, interactive, widgets import numpy as np np.random.seed(1337) # for reproducibility """ Explanation: Deep Neural Networks Theano Python library that provides efficient (low-level) tools for working with Neura...
hankcs/HanLP
plugins/hanlp_demo/hanlp_demo/zh/ner_stl.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/ner_mtl.ipynb" target="_blank"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Ope...
Chipe1/aima-python
games.ipynb
mit
from games import * from notebook import psource, pseudocode """ Explanation: GAMES OR ADVERSARIAL SEARCH This notebook serves as supporting material for topics covered in Chapter 5 - Adversarial Search in the book Artificial Intelligence: A Modern Approach. This notebook uses implementations from games.py module. Let...
mrmeswani/Robotics
RoboND-Rover-Project/src/.ipynb_checkpoints/Rover_Project_Test_Notebook-checkpoint.ipynb
gpl-3.0
%%HTML <style> code {background-color : orange !important;} </style> %matplotlib inline #%matplotlib qt # Choose %matplotlib qt to plot to an interactive window (note it may show up behind your browser) # Make some of the relevant imports import cv2 # OpenCV for perspective transform import numpy as np import matplotl...
Diyago/Machine-Learning-scripts
DEEP LEARNING/fastai kaggle rossman - tabular regression.ipynb
apache-2.0
%matplotlib inline %reload_ext autoreload %autoreload 2 from fastai.structured import * from fastai.column_data import * np.set_printoptions(threshold=50, edgeitems=20) PATH='data/rossmann/' """ Explanation: Structured and time series data This notebook contains an implementation of the third place result in the Ros...
tensorflow/federated
docs/tutorials/custom_federated_algorithms_2.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...
ThyrixYang/LearningNotes
MOOC/stanford_cnn_cs231n/assignment2/ConvolutionalNetworks.ipynb
gpl-3.0
# As usual, a bit of setup from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.cnn import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient_array, eval_numerical_gradient from cs231n.layers import * fro...
wisner23/serenata-de-amor
develop/2016-08-08-irio-translate-dataset.ipynb
mit
import pandas as pd data = pd.read_csv('../data/2016-08-08-AnoAtual.csv') data.shape data.head() data.iloc[0] """ Explanation: Translate dataset The main language of the project is English: works well mixed in programming languages like Python and provides a low barrier for non-Brazilian contributors. Today, the da...
adit-chandra/tensorflow
tensorflow/lite/examples/experimental_new_converter/keras_lstm.ipynb
apache-2.0
!pip install tf-nightly --upgrade """ Explanation: Overview This CodeLab demonstrates how to build a LSTM model for MNIST recognition using Keras, and how to convert it to TensorFlow Lite. The CodeLab is very similar to the tf.lite.experimental.nn.TFLiteLSTMCell CodeLab. However, with the control flow support in the e...
lukasmerten/CRPropa3
doc/pages/example_notebooks/secondaries/photons.v4.ipynb
gpl-3.0
from crpropa import * obs = Observer() obs.add(ObserverPoint()) obs.add(ObserverInactiveVeto()) t = TextOutput("photon_electron_output.txt", Output.Event1D) obs.onDetection(t) sim = ModuleList() sim.add(SimplePropagation()) sim.add(Redshift()) sim.add(EMPairProduction(CMB(),True)) sim.add(EMPairProduction(IRB_Gilmore...
anachlas/w210_vendor_recommendor
Collaborative Filtering on Spark.ipynb
gpl-3.0
import os import sys spark_home = os.environ['SPARK_HOME'] = '/Users/ozimmer/GoogleDrive/berkeley/w261/spark-2.0.0-bin-hadoop2.6' if not spark_home: raise ValueError('SPARK_HOME enviroment variable is not set') sys.path.insert(0,os.path.join(spark_home,'python')) sys.path.insert(0,os.path.join(spark_home,'python/li...
francisc0garcia/autonomous_bicycle
docs/python_notebooks/EKF_Design.ipynb
apache-2.0
# Import dependencies from __future__ import division, print_function %matplotlib inline import scipy from BicycleTrajectory2D import * from BicycleUtils import * from FormatUtils import * from PlotUtils import * """ Explanation: Extended Kalman Filter design for bicycle's kinematic motion model End of explanation "...
cgnorthcutt/rankpruning
tutorial_and_testing/tutorial.ipynb
mit
# Choose mislabeling noise rates. frac_pos2neg = 0.8 # rh1, P(s=0|y=1) in literature frac_neg2pos = 0.15 # rh0, P(s=1|y=0) in literature # Combine data into training examples and labels data = neg.append(pos) X = data[["x1","x2"]].values y = data["label"].values # Noisy P̃Ñ learning: instead of target y, we have s co...
xebia-france/luigi-airflow
Luigi_airflow_003.ipynb
apache-2.0
raw_dataset = pd.read_csv(source_path + "Speed_Dating_Data.csv") """ Explanation: Import data End of explanation """ raw_dataset.head(3) raw_dataset_copy = raw_dataset check1 = raw_dataset_copy[raw_dataset_copy["iid"] == 1] check1_sel = check1[["iid", "pid", "match","gender","date","go_out","sports","tvsports","ex...
jgoppert/pymola
test/notebooks/XML.ipynb
bsd-3-clause
m1_xml = os.path.join( '..', 'models', 'bouncing-ball.xml') m1_ca = parse_xml.parse_file(m1_xml) m1_ca m1_ode = m1_ca.to_ode() m1_ode m1_ode.prop['x']['start'] = 1 data1 = sim_scipy.sim(m1_ode, {'dt': 0.01, 'tf': 3.5, 'integrator': 'dopri5'}) plt.figure(figsize=(15, 10)) analysis.plot(data1, marker='.', linewidth...
ptpro3/ptpro3.github.io
Projects/Challenges/Challenge09/challenge_set_9ii_prashant.ipynb
mit
from sqlalchemy import create_engine import pandas as pd cnx = create_engine('postgresql://prashant:ptpro3@52.14.144.23:5432/prashant') #port ~ 5432 pd.read_sql_query('''SELECT * FROM allstarfull LIMIT 5''',cnx) pd.read_sql_query('''SELECT * FROM schools LIMIT 5''',cnx) pd.read_sql_query('''SELECT * FROM salaries LI...
skkandrach/foundations-homework
Homework_5_Soma_graded.ipynb
mit
# !pip3 install requests import requests response = requests.get('https://api.spotify.com/v1/search?query=Lil+&offset=0&limit=50&type=artist&market=US') data = response.json() data.keys() artist_data = data['artists']['items'] for artist in artist_data: print(artist['name'], artist['popularity'], artist['genres']) ...
Boussau/Notebooks
Notebooks/computeConsensusChronogram.ipynb
gpl-2.0
import sys from ete3 import Tree, TreeStyle, NodeStyle import numpy as np import pandas as pd import matplotlib.pyplot as plt import math fileT = "100.trees" try: f=open(fileT, 'r') except IOError: print ("Unknown file: " + fileT) sys.exit() allTrees = list() for l in f: allTrees.append( Tree( l.stri...
jdnz/qml-rg
Meeting 6/aps_with_classifiers.ipynb
gpl-3.0
import numpy as np import os from skimage.transform import resize from sklearn.ensemble import RandomForestClassifier from sklearn import svm import image_loader as im from matplotlib import pyplot as plt %matplotlib inline path=os.getcwd()+'/' # finds the path of the folder in which the notebook is path_train=path+'i...
csadorf/signac
doc/signac_202_Integration_with_pandas.ipynb
bsd-3-clause
import signac import pandas as pd project = signac.get_project(root='projects/tutorial') """ Explanation: 2.2 Integration with pandas data frames As was shown earlier, we can use indexes to search for specific data points. One way to operate on the data is using pandas data frames. Please note: The following steps re...
wasit7/tutorials
flask/tu/notebook/.ipynb_checkpoints/Somkiats-Basic-Python-checkpoint.ipynb
mit
x=1 print x type(x) x.conjugate() type(1+2j) z=1+2j print z (1,2) t=(1,2,"text") t t def foo(): return (1,2) x,y=foo() print x print y def swap(x,y): return (y,x) x=1;y=2 print "{0:d} {1:d}".format(x,y) x,y=swap(x,y) print "{:f} {:f}".format(x,y) dir(1) x=[] x.append("text") x x.append(1) x.p...
SaTa999/pyPanair
examples/tutorial2/tutorial2.ipynb
mit
%matplotlib notebook import matplotlib.pyplot as plt from pyPanair.preprocess import wgs_creator for eta in ("0000", "0126", "0400", "0700", "1000"): af = wgs_creator.read_airfoil("eta{}.csv".format(eta)) plt.plot(af[:,0], af[:,2], "k-", lw=1.) plt.plot((0.5049,), (0,), "ro", label="Center of rotation") plt.le...
austinjalexander/sandbox
python/py/nanodegree/intro_ds/final_project/IntroDS-ProjectOne-Section2.ipynb
mit
import numpy as np import pandas as pd import scipy as sp import scipy.stats as st import statsmodels.api as sm import scipy.optimize as op from sklearn.cross_validation import train_test_split import matplotlib.pyplot as plt %matplotlib inline filename = '/Users/excalibur/py/nanodegree/intro_ds/final_project/improve...
ML4DS/ML4all
R_lab1_ML_Bay_Regresion/old/Pract_regression_student.ipynb
mit
# Import some libraries that will be necessary for working with data and displaying plots # To visualize plots in the notebook %matplotlib inline import matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np import scipy.io # To read matlab files from scipy import spatial imp...