repo_name
stringlengths
6
77
path
stringlengths
8
215
license
stringclasses
15 values
content
stringlengths
335
154k
InsightLab/data-science-cookbook
2020/04-unsupervised-learning-clustering/Notebook_WhyNumpy.ipynb
mit
# import the libraries import time import random import numpy as np # Inicializar vetor com uma grande quantidade de dados aleátorios x = [random.randint(1,10) for i in range(50000)] np_x = np.array(x) # Selecionar valores k para a equação k = [4, 8, 30] """ Explanation: (Extra) Porque usar numpy? https://towardsda...
Chipe1/aima-python
mdp_apps.ipynb
mit
from mdp import * from notebook import psource, pseudocode """ Explanation: APPLICATIONS OF MARKOV DECISION PROCESSES In this notebook we will take a look at some indicative applications of markov decision processes. We will cover content from mdp.py, for Chapter 17 Making Complex Decisions of Stuart Russel's and Pe...
ES-DOC/esdoc-jupyterhub
notebooks/cams/cmip6/models/sandbox-3/atmoschem.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cams', 'sandbox-3', 'atmoschem') """ Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: CAMS Source ID: SANDBOX-3 Topic: Atmoschem Sub-Topics: Transport, Emissions ...
icrtiou/coursera-ML
ex1-linear regression/4- tensoflow batch gradient decent.ipynb
mit
%reload_ext autoreload %autoreload 2 %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import sys sys.path.append('..') from helper import linear_regression as lr # my own module from helper import general as general import tensorflow as tf """ Explanation: notes: tensorf...
datascience-practice/data-quest
python_introduction/intermediate/Classes.ipynb
mit
class Car(): def __init__(self): self.color = "black" self.make = "honda" self.model = "accord" black_honda_accord = Car() print(black_honda_accord.color) """ Explanation: 3: Class syntax Instructions Create a class called Team. Inside the class, create a name property. Assign the value "...
tensorflow/docs
site/en/guide/migrate/checkpoint_saver.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...
sanabasangare/data-visualization
Line_chart.ipynb
mit
import matplotlib.pyplot as plt from collections import Counter """ Explanation: Line Chart - Total Number of websites online End of explanation """ def line_graph(plt): years = [2000, 2002, 2005, 2007, 2010, 2012, 2014, 2015] websites = [17, 38, 64, 121, 206, 697, 968, 863] """ Explanation: create a line c...
dssg/diogenes
doc/notebooks/modify.ipynb
mit
import diogenes data = diogenes.read.open_csv_url('https://data.cityofchicago.org/api/views/mab8-y9h3/rows.csv?accessType=DOWNLOAD', parse_datetimes=['Creation Date', 'Completion Date']) """ Explanation: The Modify Module :mod:diogenes.modify provides tools for manipulating arrays a...
ondrejiayc/StatisticalMethods
examples/SDSScatalog/FirstLook.ipynb
gpl-2.0
%load_ext autoreload %autoreload 2 from __future__ import print_function import numpy as np import SDSS import pandas as pd import matplotlib %matplotlib inline objects = "SELECT top 10000 \ ra, \ dec, \ type, \ dered_u as u, \ dered_g as g, \ dered_r as r, \ dered_i as i, \ petroR50_i AS size \ FROM PhotoObjAll \ WH...
daleloogn/rp_extract
RP_extract_Tutorial.ipynb
gpl-3.0
# to install iPython notebook on your computer, use this in Terminal sudo pip install "ipython[notebook]" """ Explanation: <center><h1>Rhythm and Timbre Analysis from Music</h1></center> <center><h2>Rhythm Pattern Music Features</h2></center> <center><h2>Extraction and Application Tutorial</h2></center> <br> <center><...
julienchastang/unidata-python-workshop
notebooks/AWIPS/Map_Resources_and_Topography.ipynb
mit
from __future__ import print_function from awips.dataaccess import DataAccessLayer import matplotlib.pyplot as plt import cartopy.crs as ccrs import numpy as np from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER from cartopy.feature import ShapelyFeature,NaturalEarthFeature from shapely.geometry ...
kubeflow/pipelines
components/gcp/ml_engine/train/sample.ipynb
apache-2.0
%%capture --no-stderr !pip3 install kfp --upgrade """ Explanation: Name Submitting a Cloud Machine Learning Engine training job as a pipeline step Label GCP, Cloud ML Engine, Machine Learning, pipeline, component, Kubeflow, Kubeflow Pipeline Summary A Kubeflow Pipeline component to submit a Cloud ML Engine training j...
sarvex/tensorflow
tensorflow/lite/g3doc/performance/post_training_float16_quant.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...
cjcardinale/climlab
docs/source/courseware/Spectral_OLR_with_RRTMG.ipynb
mit
%matplotlib inline import numpy as np import matplotlib.pyplot as plt import climlab import xarray as xr import scipy.integrate as sp #Gives access to the ODE integration package """ Explanation: Spectrally-resolved Outgoing Longwave Radiation (OLR) with RRTMG_LW In this notebook we will demonstrate how to use climla...
tOverney/ADA-Project
preprocessing/process_csv.ipynb
apache-2.0
def strip_id(s): try: index = s.index(':') except ValueError: index = len(s) return s[:index] columns = [ 'agency_id', 'service_date_id', 'service_date_date', 'route_id', 'route_short_name', 'route_long_name', 'trip_id', 'trip_headsign', 'trip_short_name', 'stop_time_id...
mommermi/Introduction-to-Python-for-Scientists
notebooks/Lists_and_Control_Flow_20160916.ipynb
mit
l1 = [1, 2, 3, 4, 5, 6] # list of the same data type l2 = [1, 2.3, 'a'] # list of different data types l3 = [[1, 2, 3], [4, 5, 6]] # a nested (multidimensional) list l4 = range(3,10) # a neat way to generate a list of integers """ Explanation: Python Basics Content Lists Dictionaries Sets Cont...
AusCover/ml-biomass
ml-biomass.ipynb
apache-2.0
# Imports for this Python3 notebook import numpy import matplotlib.pyplot as plt from osgeo import gdal from osgeo import ogr from osgeo import osr from rios import rat from rios import ratapplier from tpot import TPOTRegressor """ Explanation: Biomass Estimation - Putting the RAT into TPOT <img src='http://www.au...
anonyXmous/CapstoneProject
Mini_Project_Logistic_Regression.ipynb
unlicense
%matplotlib inline import numpy as np import scipy as sp import matplotlib as mpl import matplotlib.cm as cm from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt import pandas as pd pd.set_option('display.width', 500) pd.set_option('display.max_columns', 100) pd.set_option('display.notebook_repr...
GoogleCloudPlatform/vertex-ai-samples
notebooks/community/ml_ops/stage6/get_started_with_fastapi.ipynb
apache-2.0
import os # The Vertex AI Workbench Notebook product has specific requirements IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME") IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists( "/opt/deeplearning/metadata/env_version" ) # Vertex AI Notebook requires dependencies to be installed with '--user' USER_FLAG = ...
jeroarenas/MLBigData
2_Classification/MLLib_classification-students.ipynb
mit
################################################# # TODO: Replace <FILL IN> with appropriate code ################################################# # You need to include mnist file in your working directory lines = sc.textFile("mnist") # Examine dataset format # 1. Number of lines n_lines = #FILL print 'Number of lin...
NEONScience/NEON-Data-Skills
tutorials/Python/Hyperspectral/indices/Plot_Spectral_Signature_Tiles_py/Plot_Spectral_Signature_Tiles_py.ipynb
agpl-3.0
import numpy as np import matplotlib.pyplot as plt %matplotlib inline import warnings warnings.filterwarnings('ignore') #don't display warnings """ Explanation: syncID: c91d556c8fad4570a33a1aaa550a561d title: "Plot a Spectral Signature in Python - Tiled Data" description: "Learn how to extract and plot a spectral pro...
liufuyang/deep_learning_tutorial
jizhi-pytorch-2/03_text_generation/Homework_3/Homeword_LSTM_Name_Generator-Copy1.ipynb
mit
# 第一步当然是引入PyTorch及相关包 import torch import torch.nn as nn import torch.optim from torch.autograd import Variable import numpy as np """ Explanation: 火炬上的深度学习(下)第三节:神经网络莫扎特 课后作业:使用 LSTM 编写一个国际姓氏生成模型 在火炬课程中,我们学习了使用 LSTM 来生成 MIDI 音乐。这节课我们使用类似的方法,再创建一个 LSTM 国际起名大师! 完成后的模型能够像下面这样使用,指定一个国家名,模型即生成几个属于这个国家的姓氏。 ``` python gene...
mne-tools/mne-tools.github.io
0.17/_downloads/ad203e57e0d21d6623eb90e7bd84fa3c/plot_morph_surface_stc.ipynb
bsd-3-clause
# Author: Tommy Clausner <tommy.clausner@gmail.com> # # License: BSD (3-clause) import os import mne from mne.datasets import sample print(__doc__) """ Explanation: Morph surface source estimate This example demonstrates how to morph an individual subject's :class:mne.SourceEstimate to a common reference space. We a...
sdpython/pyquickhelper
_unittests/ut_helpgen/notebooks2/custom_widget.ipynb
mit
from jyquickhelper import add_notebook_menu add_notebook_menu() """ Explanation: Custom widgets in a notebook The notebook explore a couple of ways to interact with the user and modifies the output based on these interactions. This is inspired from the examples from ipwidgets. End of explanation """ import ipywidget...
ireapps/cfj-2017
completed/20. Exercise - Web scraping.ipynb
mit
import csv import time import requests from bs4 import BeautifulSoup """ Explanation: Let's scrape some death row data Texas executes a lot of criminals, and it has a web page that keeps track of people on its death row. Using what you've learned so far, let's scrape this table into a CSV. Then we're going write a fu...
diegocavalca/Studies
programming/Python/tensorflow/exercises/Math_Part2.ipynb
cc0-1.0
from __future__ import print_function import tensorflow as tf import numpy as np from datetime import date date.today() author = "kyubyong. https://github.com/Kyubyong/tensorflow-exercises" tf.__version__ np.__version__ sess = tf.InteractiveSession() """ Explanation: Math Part 2 End of explanation """ _x = np.a...
rbiswas4/simlib
example/Demo_HealpixTree.ipynb
mit
from mpl_toolkits.basemap import Basemap import opsimsummary as oss oss.__VERSION__ from opsimsummary import HealpixTree, pixelsForAng, HealpixTiles import numpy as np %matplotlib inline import matplotlib.pyplot as plt import healpy as hp """ Explanation: Contents This notebook shows how to use the functionality...
anisfeld/MachineLearning
Building the Pipeline part 2 Write Up.ipynb
mit
first_grid = r.read_csv("small_loop_result.csv") fg = first_grid.sort_values(by="auc-roc") fg.head(10) #top 10 fg.tail(10).sort_values(by="auc-roc", ascending=False) """ Explanation: While I was working on improving my previous homework and determining a method for feature selection, I ran the small grid search of Ma...
rsnemmen/nmmn
docs/SEDs.ipynb
mit
%pylab inline import nmmn.sed as sed """ Explanation: Handling spectral energy distributions This notebook illustrates how to use the sed module of nmmn. This module is very convenient for dealing with spectral energy distributions (SEDs)—the distributions of luminosity $\nu L_\nu$ as a function of $\nu$. Often, we ...
ueapy/ueapy.github.io
content/notebooks/2020-09-10-github-scrape.ipynb
mit
import json import requests from collections import Counter import pandas as pd import numpy as np credentials = json.loads(open('credentials-secret.json').read()) #don't forget to add your creds here! username = credentials['username'] token = credentials['token'] """ Explanation: A meta-hackweek hack I put this no...
pinga-lab/magnetic-ellipsoid
code/demagnetizing_factors_Stoner1945.ipynb
bsd-3-clause
from __future__ import division %matplotlib inline import numpy as np import os from matplotlib import pyplot as plt from fatiando import utils import mesher import prolate_ellipsoid, oblate_ellipsoid, triaxial_ellipsoid # Set some plot parameters from matplotlib import rcParams rcParams['figure.dpi'] = 300. rcParams[...
analysiscenter/dataset
examples/tutorials/02_pipeline_operations.ipynb
apache-2.0
import sys import warnings warnings.filterwarnings("ignore") import PIL import numpy as np from matplotlib import pyplot as plt %matplotlib inline # the following line is not required if BatchFlow is installed as a python package. sys.path.append("../..") from batchflow import Dataset, DatasetIndex, R, P, V, C from b...
rflamary/POT
notebooks/plot_otda_classes.ipynb
mit
# Authors: Remi Flamary <remi.flamary@unice.fr> # Stanislas Chambon <stan.chambon@gmail.com> # # License: MIT License import matplotlib.pylab as pl import ot """ Explanation: OT for domain adaptation This example introduces a domain adaptation in a 2D setting and the 4 OTDA approaches currently supported in ...
fastai/fastai
nbs/31_text.data.ipynb
apache-2.0
#|export def reverse_text(x): return x.flip(0) t = tensor([0,1,2]) r = reverse_text(t) test_eq(r, tensor([2,1,0])) """ Explanation: Text data Functions and transforms to help gather text data in a Datasets Backwards Reversing the text can provide higher accuracy with an ensemble with a forward model. All that is ne...
neurohackweek/kids_rsfMRI_motion
kw_playingaround/Age_vs_Motion.ipynb
mit
import matplotlib.pylab as plt %matplotlib inline import numpy as np import os import pandas as pd import seaborn as sns sns.set_style('white') sns.set_context('notebook') from scipy.stats import kurtosis import sys %load_ext autoreload %autoreload 2 sys.path.append('../SCRIPTS/') import kidsmotion_stats as kms impo...
mattgiguere/doglodge
code/bf_qt_scraping.ipynb
mit
import sys from PyQt4.QtGui import * from PyQt4.QtCore import * from PyQt4.QtWebKit import * from lxml import html class Render(QWebPage): def __init__(self, url): self.app = QApplication(sys.argv) QWebPage.__init__(self) self.loadFinished.connect(self._loadFinished) ...
jalabort/templatetracker
notebooks/scrap/Correlation Filters.ipynb
bsd-3-clause
images = [] for i in mio.import_images('/Users/joan/PhD/DataBases/faces/lfpw/trainset/*', verbose=True, max_images=300): i.crop_to_landmarks_proportion_inplace(0.5) i = i.rescale_landmarks_to_diagonal_range(100) images.append(i) visualize_images(images) """ Explanation: Kerneli...
walkon302/CDIPS_Recommender
notebook_versions/Recommendor_Method_Nathans_v2.ipynb
apache-2.0
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style('white') %matplotlib inline """ Explanation: Recommendation Method 1: Most similar items to user's previous views Algorithm Offline: 1. For each item, calculate features on trained neural network $ f_j $ 2. For ...
UWashington-Astro300/Astro300-A16
08_Python_LaTeX.ipynb
mit
%matplotlib inline import sympy as sp import numpy as np import matplotlib.pyplot as plt """ Explanation: Python and $\LaTeX$ End of explanation """ plt.style.use('ggplot') x = np.linspace(0,2*np.pi,100) y = np.sin(5*x) * np.exp(-x) plt.plot(x,y) plt.title("The function $y\ =\ \sin(5x)\ e^{-x}$") plt.xlabel("This...
kit-cel/wt
ccgbc/ch2_Codes_Basic_Concepts/BiAWGN_Capacity_Finitelength.ipynb
gpl-2.0
import numpy as np import scipy.integrate as integrate from scipy.stats import norm import matplotlib import matplotlib.pyplot as plt # plotting options font = {'size' : 20} plt.rc('font', **font) plt.rc('text', usetex=matplotlib.checkdep_usetex(True)) matplotlib.rc('figure', figsize=(18, 6) ) """ Explanation: Fi...
muatik/my-coding-challenges
python/10daysOfStatistics/Day_5_Normal_Distribution_I.ipynb
mit
import math from matplotlib import pylab as plt %matplotlib inline def pdf(x, m, variance): sigma = math.sqrt(variance) """probability density function""" return 1 / (sigma * math.sqrt(2 * math.pi)) * math.e ** (-1 * ((x - m)**2 / (2 * variance ** 2))) pdf(20, 20, 4) """ Explanation: Day 5: Normal Distri...
poldrack/fmri-analysis-vm
analysis/efficiency/DesignEfficiency.ipynb
mit
import os import numpy %matplotlib inline import sys sys.path.insert(0,'../utils') from mkdesign import create_design_singlecondition import matplotlib.pyplot as plt #from spm_hrf import spm_hrf from nipy.modalities.fmri.hemodynamic_models import spm_hrf,compute_regressor tr=1.0 # the "blockiness" argument controls h...
jcmgray/quijy
docs/examples/ex_tn_train_circuit.ipynb
mit
V = circ.uni """ Explanation: We can extract just the unitary part of the circuit as a tensor network like so: End of explanation """ V.graph(color=['U3', gate2], show_inds=True) V.graph(color=[f'ROUND_{i}' for i in range(depth)], show_inds=True) V.graph(color=[f'I{i}' for i in range(n)], show_inds=True) # the ha...
Jackie789/JupyterNotebooks
3.1.3+KNN+RegressionWithJackiesModel.ipynb
gpl-3.0
from sklearn import neighbors # Build our model. knn = neighbors.KNeighborsRegressor(n_neighbors=10) X = pd.DataFrame(music.loudness) Y = music.bpm knn.fit(X, Y) # Set up our prediction line. T = np.arange(0, 50, 0.1)[:, np.newaxis] # Trailing underscores are a common convention for a prediction. Y_ = knn.predict(T)...
mne-tools/mne-tools.github.io
stable/_downloads/b2637a9801fb152d611a08a816cc5583/sensor_regression.ipynb
bsd-3-clause
# Authors: Tal Linzen <linzen@nyu.edu> # Denis A. Engemann <denis.engemann@gmail.com> # Jona Sassenhagen <jona.sassenhagen@gmail.com> # # License: BSD-3-Clause import pandas as pd import mne from mne.stats import linear_regression, fdr_correction from mne.viz import plot_compare_evokeds from mne.data...
tombstone/models
official/colab/nlp/nlp_modeling_library_intro.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...
gouthambs/karuth-source
content/extra/notebooks/american-option-models.ipynb
artistic-2.0
import QuantLib as ql import matplotlib.pyplot as plt %matplotlib inline ql.__version__ """ Explanation: American Option Pricing with QuantLib and Python Gouthaman Balaraman I wrote about pricing European options using QuantLib in an earlier post. Since then, I have received many questions from readers on how to exte...
ajdawson/python_for_climate_scientists
course_content/solutions/iris_exercise_2.ipynb
gpl-3.0
import iris soi = iris.load_cube(iris.sample_data_path('SOI_Darwin.nc')) print(soi) """ Explanation: A final exercise This exercise puts together many of the topics covered in this session. 1. Load the single cube from the file iris.sample_data_path('SOI_Darwin.nc'). This contains monthly values of the Southern Oscil...
DJCordhose/ai
notebooks/nlp/1b-glove-embedding.ipynb
mit
# Based on # https://github.com/fchollet/deep-learning-with-python-notebooks/blob/master/6.1-using-word-embeddings.ipynb # https://machinelearningmastery.com/develop-word-embeddings-python-gensim/ import warnings warnings.filterwarnings('ignore') %matplotlib inline %pylab inline import tensorflow as tf tf.logging.se...
saashimi/code_guild
wk0/notebooks/challenges/compress/.ipynb_checkpoints/compress_challenge-checkpoint.ipynb
mit
def compress_string(string): # TODO: Implement me string "!" pass """ Explanation: <small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small> Challenge Notebook Problem: Compress a string such that 'AAABCCDDDD' becomes 'A3B1C2D4'. Only compress the string if it...
landlab/landlab
notebooks/tutorials/flow_direction_and_accumulation/compare_FlowDirectors.ipynb
mit
%matplotlib inline # import plotting tools from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import matplotlib as mpl # import numpy import numpy as np # import necessary landlab components from landlab im...
matt-graham/auxiliary-pm-mcmc
experiment_notebooks/Auxiliary Pseudo-Marginal MCMC - E-SS u updates and RD-SS theta updates.ipynb
mit
data_dir = os.path.join(os.environ['DATA_DIR'], 'uci') exp_dir = os.path.join(os.environ['EXP_DIR'], 'apm_mcmc') """ Explanation: Construct data and experiments directorys from environment variables End of explanation """ data_set = 'pima' method = 'apm(ess+rdss)' n_chain = 10 chain_offset = 0 seeds = np.random.rand...
yashdeeph709/Algorithms
PythonBootCamp/Complete-Python-Bootcamp-master/Functions and Methods Homework - Solutions.ipynb
apache-2.0
def vol(rad): return (4.0/3)*(3.14)*(rad**3) """ Explanation: Functions and Methods Homework Solutions Write a function that computes the volume of a sphere given its radius. End of explanation """ def ran_check(num,low,high): #Check if num is between low and high (including low and high) if num in rang...
ThierryMondeel/FBA_python_tutorial
FBA_tutorials/5_biomarker_prediction_PKU.ipynb
mit
import cobra from utils import findBiomarkers import pandas as pd from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" M = cobra.io.load_json_model('models/recon_2_2_simple_medium.json') model = M.copy() # this way we can edit model but leave M unaltered """ Expl...
NYUDataBootcamp/Materials
Code/notebooks/bootcamp_indicators.ipynb
mit
# import packages import pandas as pd # data management import matplotlib.pyplot as plt # graphics import numpy as np # numerical calculations # IPython command, puts plots in notebook %matplotlib inline # check Python version import datetime as dt import sys print('To...
ES-DOC/esdoc-jupyterhub
notebooks/ec-earth-consortium/cmip6/models/ec-earth3-lr/atmos.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'ec-earth3-lr', 'atmos') """ Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: EC-EARTH-CONSORTIUM Source ID: EC-EARTH3-LR Topic: Atmos Sub-Topic...
GoogleCloudPlatform/asl-ml-immersion
notebooks/bigquery/labs/b_bqml.ipynb
apache-2.0
from google import api_core from google.cloud import bigquery PROJECT = !gcloud config get-value project PROJECT = PROJECT[0] %env PROJECT=$PROJECT """ Explanation: Big Query Machine Learning (BQML) Learning Objectives - Understand that it is possible to build ML models in Big Query - Understand when this is appropr...
adamsteer/nci-notebooks
pgpointcloud/PGpointlcloud tests.ipynb
apache-2.0
import os import psycopg2 as ppg import numpy as np import ast from osgeo import ogr import shapely as sp from shapely.geometry import Point,Polygon,asShape from shapely.wkt import loads as wkt_loads from shapely import speedups import cartopy as cp import cartopy.crs as ccrs import pandas as pd import pandas.io.s...
JuBra/cobrapy
documentation_builder/milp.ipynb
lgpl-2.1
cone_selling_price = 7. cone_production_cost = 3. popsicle_selling_price = 2. popsicle_production_cost = 1. starting_budget = 100. """ Explanation: Mixed-Integer Linear Programming Ice Cream This example was originally contributed by Joshua Lerman. An ice cream stand sells cones and popsicles. It wants to maximize its...
theandygross/TCGA_differential_expression
Notebooks/Imports.ipynb
mit
%matplotlib inline import matplotlib.pyplot as plt from matplotlib.pyplot import subplots """ Explanation: Global Imports End of explanation """ import os as os import pickle as pickle import pandas as pd """ Explanation: External Package Imports End of explanation """ from Stats.Scipy import * from Stats.Surviv...
yevheniyc/Python
1m_ML_Security/notebooks/answers/Worksheet 6 - DGA Detection ML Classification - Answers.ipynb
mit
df_final = pd.read_csv('../../data/dga_features_final_df.csv') print(df_final.isDGA.value_counts()) df_final.head() # Load dictionary of common english words from part 1 from six.moves import cPickle as pickle with open('../../data/d_common_en_words' + '.pickle', 'rb') as f: d = pickle.load(f) """ Explanation...
opensanca/trilha-python
04-python-prat/data_science/Python and Data Science _sem_spoilers.ipynb
mit
import pandas as pd import matplotlib %matplotlib inline """ Explanation: Trabalhando com o Jupyter Ferramenta que permite criação de código, visualização de resultados e documentação no mesmo documento (.ipynb) Modo de comando: esc para ativar, o cursor fica inativo Modo de edição: enter para ativar, modo de inserção...
befelix/Safe-RL-Benchmark
examples/SafeOpt.ipynb
mit
import GPy, safeopt from SafeRLBench.algo import SafeOptSwarm from SafeRLBench.envs import Quadrocopter, LinearCar from SafeRLBench.policy import NonLinearQuadrocopterController, LinearPolicy from SafeRLBench.measure import BestPerformance, SafetyMeasure from SafeRLBench import Bench # set up logging from SafeRLBen...
napsternxg/ControversialTweetAnalysis
Merge URLs and tweets.ipynb
apache-2.0
len(data) data[0].keys() data[0][u'source'] data[0][u'is_quote_status'] data[0][u'quoted_status']['text'] data[0]['text'] count_quoted = 0 has_coordinates = 0 count_replies = 0 language_ids = defaultdict(int) count_user_locs = 0 user_locs = Counter() count_verified = 0 for d in data: count_quoted += d.get('is...
mohsinhaider/pythonbootcampacm
Objects and Data Structures/Print Formatting.ipynb
mit
print("We are printing") """ Explanation: Print Formatting There are various ways to write print statements. In Python 3, to print to console you use print functions. In the following lecture we will cover: 1. "%" notation for Strings, Floats, and Integers 2. Use the .format() method 3. Other Print function uses Here...
mayanks43/auto-tag
k-means.ipynb
mit
def assign_points_to_clusters(centroids, points, k): # 1 list for each centroid (will contain indices of points) clusters = [[] for i in range(k)] for i in range(points.shape[0]): # find nearest centroid to this point best_centroid = 0 best_distance = euclidean(centroids[best_centroi...
HazyResearch/snorkel
tutorials/advanced/Hyperparameter_Search.ipynb
apache-2.0
from snorkel.learning import GenerativeModelWeights from snorkel.learning.structure import generate_label_matrix weights = GenerativeModelWeights(10) for i in range(10): weights.lf_accuracy[i] = 2.5 weights.dep_similar[0, 1] = 0.25 weights.dep_similar[2, 3] = 0.25 L_gold_train, L_train = generate_label_matrix(wei...
beangoben/HistoriaDatos_Higgs
Dia2/4_Datos_LHC.ipynb
gpl-2.0
import pandas as pd import numpy as np # modulo de computo numerico import matplotlib.pyplot as plt # modulo de graficas # esta linea hace que las graficas salgan en el notebook import seaborn as sns %matplotlib inline """ Explanation: A explorar los datos del LHC Hoy vamos a combinar dos conceptos que vimos ayer: A...
mne-tools/mne-tools.github.io
0.22/_downloads/0f6b60b574bc5e5c341b148b90d0f456/plot_evoked_whitening.ipynb
bsd-3-clause
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Denis A. Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import mne from mne import io from mne.datasets import sample from mne.cov import compute_covariance print(__doc__) """ Explanation: Whitening evoked data with a noise cova...
thunder-project/thunder-docs
tutorials/basics.ipynb
mit
import thunder as td series = td.series.fromexample('fish') """ Explanation: Basics Thunder provides data structures, read/write patterns, and simple processing of spatial and temporal data. All operations in Thunder are designed to scale to very large data sets through the distributed comptuing engine Spark, but als...
yashdeeph709/Algorithms
PythonBootCamp/Complete-Python-Bootcamp-master/Functions.ipynb
apache-2.0
def name_of_function(arg1,arg2): ''' This is where the function's Document String (doc-string) goes ''' # Do stuff here #return desired result """ Explanation: Functions Introduction to Functions This lecture will consist of explaining what a function is in Python and how to create one. Functions w...
suchit-upx/suchit-upx.github.io
Titanic_Decision_trees_and_Random_Forest.ipynb
mit
import pandas as pd from sklearn.preprocessing import Imputer from sklearn import tree from sklearn import metrics import numpy as np import matplotlib.pyplot as plt % matplotlib inline #train_df = pd.read_csv("titanic.csv") #test_df = pd.read_csv("titanic_test.csv") from google.colab import files import io uploaded ...
pbeens/ICS-Computer-Studies
Python/Class Demos/Introduction to Data Science using Python.ipynb
mit
import numpy as np """ Explanation: From http://www.codemag.com/article/1611081 <h1>NumPy Array Basics</h1> In NumPy, an array is of type ndarray (n-dimensional array). A NumPy array is an array of homogeneous values (all of the same type), and all items occupy a contiguous block of memory. To use NumPy, you first ne...
stellaxux/machine-learning-in-python
ch4/data_preprocessing.ipynb
mit
import pandas as pd from io import StringIO csv_data = '''A,B,C,D 1.0,2.0,3.0,4.0 5.0,6.0,,8.0 10.0,11.0,,''' data = pd.read_csv(StringIO(csv_data)) ## checking for missing data df.isnull().sum() # Another example of a dataframe with missing data # creating dataframe from dictionary; key is the colume name import n...
bmorris3/gsoc2015
presentation.ipynb
mit
# Altitude-azimuth frame: from astropy.coordinates import SkyCoord, EarthLocation, AltAz import astropy.units as u from astropy.time import Time # Specify location of Apache Point Observatory with astropy.coordinates.EarthLocation apache_point = EarthLocation.from_geodetic(-105.82*u.deg, 32.78*u.deg, 2798*u.m) # Spe...
xzturn/tensorflow
tensorflow/lite/g3doc/models/style_transfer/overview.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...
grehujt/SmallPythonProjects
jupyterNotebooks/ml_advice.ipynb
mit
import time import numpy as np np.random.seed(0) import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline # <!-- collapse=True --> # Modified from http://scikit-learn.org/stable/auto_examples/plot_learning_curve.html from sklearn.learning_curve import learning_curve def plot_learning_curve(estimator,...
jseabold/statsmodels
examples/notebooks/ols.ipynb
bsd-3-clause
%matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm from statsmodels.sandbox.regression.predstd import wls_prediction_std np.random.seed(9876789) """ Explanation: Ordinary Least Squares End of explanation """ nsample = 100 x = np.linspace(0, 10, 1...
eneskemalergin/Data_Mining_Spring2017
Final_Project/theAwesome_EnsModel.ipynb
mit
import pandas as pd import matplotlib.pyplot as plt # Read CSV data into df df = pd.read_csv('./theAwesome_EnsModel.csv') # delete id column no need df.drop('Id',axis=1,inplace=True) df.head() # Learn the unique values in diagnosis column print("Classification labels: ", df.Species.unique() ) # Mapping labels to num...
junhwanjang/DataSchool
Lecture/05. 기초 선형 대수 1 - 행렬의 정의와 연산/2) NumPy 배열 생성과 변형.ipynb
mit
x = np.array([1, 2, 3]) x.dtype """ Explanation: NumPy 배열 생성과 변형 NumPy의 자료형 NumPy의 ndarray클래스는 포함하는 모든 데이터가 같은 자료형(data type)이어야 한다. 또한 자료형 자체도 일반 파이썬에서 제공하는 것보다 훨씬 세분화되어 있다. NumPy의 자료형은 dtype 이라는 인수로 지정한다. dtype 인수로 지정할 값은 다음 표에 보인것과 같은 dtype 접두사로 시작하는 문자열이고 비트/바이트 수를 의미하는 숫자가 붙을 수도 있다. | dtype 접두사 | 설명 | 사용 예 | |-|-...
IEMLdev/ieml-api
notebooks/USL.ipynb
gpl-3.0
from ieml.usl.usl import usl u = usl("[E:.b.E:B:.- E:S:. (E:.-wa.-t.o.-' E:.-'wu.-S:.-'t.o.-',)(a.T:.-) > ! E:.l.- (E:.wo.- E:S:.-d.u.-')]") u.check() print(u) u1 = usl("[E:.b.E:B:.- E:S:. (E:.-'wu.-S:.-'t.o.-', E:.-wa.-t.o.-' )(a.T:.-) > ! E:.l.- (E:.wo.- E:S:.-d.u.-')]") u1.check() print(u1) assert u1 == u """ Expla...
PhonologicalCorpusTools/PolyglotDB
examples/tutorial/tutorial_2_enrichment.ipynb
mit
import os from polyglotdb import CorpusContext corpus_root = '/mnt/e/Data/pg_tutorial' """ Explanation: Tutorial 2: Adding extra information Note In general, enrichment can be performed in any order (i.e., speaker enrichment is independent of syllable encoding), so you can perform the major sections in any order and...
wittawatj/fsic-test
ipynb/nfsic_optimization.ipynb
mit
%load_ext autoreload %autoreload 2 %matplotlib inline #%config InlineBackend.figure_format = 'svg' #%config InlineBackend.figure_format = 'pdf' import matplotlib import matplotlib.pyplot as plt import numpy as np import fsic.util as util import fsic.data as data import fsic.kernel as kernel import fsic.indtest as it im...
open-forcefield-group/openforcefield
utilities/deprecated/convert_frosst/check_different_smirnoffs.ipynb
mit
# Imports from __future__ import print_function from convert_frcmod import * import openeye.oechem as oechem import openeye.oeiupac as oeiupac import openeye.oeomega as oeomega import openeye.oedepict as oedepict from IPython.display import display from openff.toolkit.typing.engines.smirnoff.forcefield import * from op...
ilogue/pyrsa
demos/example_dissimilarities.ipynb
lgpl-3.0
# relevant imports import numpy as np from scipy import io import matplotlib.pyplot as plt import pyrsa import pyrsa.data as rsd # abbreviation to deal with dataset import pyrsa.rdm as rsr # create a dataset object measurements = io.matlab.loadmat('92imageData/simTruePatterns.mat') measurements = measurements['simTrue...
obscode/bootcamp
MoreNotebooks/Skyfit.ipynb
mit
import pandas as pd data = pd.read_csv('data/skyfit.dat') """ Explanation: Putting it All Together This notebook is a case study in working with python and several 3rd-party modules. There are many ways to attack a problem such as this; this is simply one way. The point is to illustrate how you can get existing module...
mtasende/Machine-Learning-Nanodegree-Capstone
notebooks/prod/n08_simple_q_learner_fast_learner_11_actions.ipynb
mit
# Basic imports import os import pandas as pd import matplotlib.pyplot as plt import numpy as np import datetime as dt import scipy.optimize as spo import sys from time import time from sklearn.metrics import r2_score, median_absolute_error from multiprocessing import Pool %matplotlib inline %pylab inline pylab.rcPar...
NYUDataBootcamp/Projects
UG_S17/Sairam Sivaraj-Climate.ipynb
mit
# Packages needed including Advanced Plotly functions import pandas as pd # data package import datetime as dt # date and time module import numpy as np # foundation for Pandas #WB functions import wbdata from pandas_datareader import wb # worldbank data ...
Saytiras/StalkerML
Crawling Political Party Sites.ipynb
gpl-2.0
domain = 'http://www.die-linke.de' keyword = 'artikel' site = 'http://www.die-linke.de/nc/die-linke/nachrichten' pages = ['{}/browse/{}'.format(site, i) for i in range(1, 99)] pages.append(site) def get_data(): for page in pages: try: req = requests.get(page, timeout=10) soup = Bea...
gfabieno/SeisCL
docs/notebooks/ForwardModeling/1_SourcesReceivers.ipynb
gpl-3.0
import matplotlib.pyplot as plt import numpy as np from SeisCL import SeisCL seis = SeisCL() """ Explanation: Sources and receivers Defining the sources and receiver position is necessary for any seismic simulation or inversion problem. This notebook shows how to do so, and present the different functionalities allowe...
mdda/fossasia-2016_deep-learning
notebooks/5-RNN/6-RNN-Tagger-theano.ipynb
mit
import numpy as np import theano import lasagne import os import pickle import time SENTENCE_LENGTH_MAX = 32 EMBEDDING_DIM=50 """ Explanation: RNN Tagger This example trains a RNN to tag words from a corpus - The data used for training is from a Wikipedia download, which is the artificially annotated with parts of ...
astroumd/GradMap
notebooks/Haiti2016/python-basic.ipynb
gpl-3.0
# setting a variable a = 1.23 # although just writing the variable will show it's value, but this is not the recommended # way, because per cell only the last one will be printed and stored in the out[] # list that the notebook maintains a a+1 """ Explanation: Some very basic python Showing some very basic pytho...
FFIG/ffig
demos/LLVM-Cauldron.ipynb
mit
outputfile = "Shape.h" %%file $outputfile #include <stdexcept> #include <string> #ifdef __clang__ #define C_API __attribute__((annotate("GENERATE_C_API"))) #else #define C_API #endif #include <ffig/attributes.h> struct FFIG_EXPORT Shape { virtual ~Shape() = default; virtual double area() const = 0; virtua...
GoogleCloudPlatform/training-data-analyst
courses/machine_learning/deepdive2/launching_into_ml/solutions/explore_data.ipynb
apache-2.0
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst from google.cloud import bigquery import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import numpy as np """ Explanation: Explore and create ML datasets In this notebook, we will explore data corresponding to taxi rides in New Yo...
AutuanLiu/Python
nbs/func.ipynb
mit
%matplotlib inline # 多行结果输出支持 from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" """ Explanation: 函数 End of explanation """ # 可变参数 packing and unpacking def avg(first, *rest): return (first + sum(rest)) / (1 + len(rest)) # Sample use avg(1, 2) # 1.5 avg(1,...
decisionstats/pythonfordatascience
text+mining.ipynb
apache-2.0
import textmining tdm = textmining.TermDocumentMatrix() tdm.add_doc(raw) for row in tdm.rows(cutoff=1): print(row) """ Explanation: !pip install stemmer For Python 3 from https://stackoverflow.com/questions/15717752/python3-3-importerror-with-textmining-1-0 Converting the textmining code to python3 so...
ES-DOC/esdoc-jupyterhub
notebooks/test-institute-1/cmip6/models/sandbox-2/atmoschem.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'test-institute-1', 'sandbox-2', 'atmoschem') """ Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: TEST-INSTITUTE-1 Source ID: SANDBOX-2 Topic: Atmoschem Sub-Topic...
PMEAL/OpenPNM-Examples
Topology/various_cubic_networks.ipynb
mit
import openpnm as op wrk = op.Workspace() wrk.logelevel=50 pn = op.network.Cubic(shape=[10, 10, 10], spacing=1) """ Explanation: Generate Cubic Lattices of Various Shape, Sizes and Topologies The Cubic lattice network is easily the most commonly used pore network topology. When people first learn about pore network mo...
WNoxchi/Kaukasos
misc/KMeans_tutorial_1_sentdex.ipynb
mit
# the μ's centroids = kmeans.cluster_centers_ # these are the labels the KMeans Algo actually suplpies us labels = kmeans.labels_ print(centroids) print(labels) colors = ["g.","r."] # green/red dots # visualize dat points according to cluster for i in range(len(X)): print("coordinate:", X[i], "label:", labels...
iurilarosa/thesis
codici/Archiviati/numpy/Prove numpy.ipynb
gpl-3.0
unimatr = numpy.ones((10,10)) #unimatr duimatr = unimatr*2 #duimatr uniarray = numpy.ones((10,1)) #uniarray triarray = uniarray*3 scalarray = numpy.arange(10) scalarray = scalarray.reshape(10,1) #NB fare il reshape da orizzontale a verticale è come se aggiungesse #una dimensione all'array facendolo diventare un nda...