markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Print the properties of the modelThe fitted_model is a python object and you can read the different properties of the object. Test the fitted modelNow that the model is trained, split the data in the same way the data was split for training (The difference here is the data is being split locally) and then run the tes... | # convert the test data to dataframe
X_test_df = validation_data.drop_columns(columns=[label_column_name]).to_pandas_dataframe()
y_test_df = validation_data.keep_columns(columns=[label_column_name], validate=True).to_pandas_dataframe()
# call the predict functions on the model
y_pred = fitted_model.predict(X_test_df)
y... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb | tomasro27/MachineLearningNotebooks |
Calculate metrics for the predictionNow visualize the data on a scatter plot to show what our truth (actual) values are compared to the predicted values from the trained model that was returned. | from sklearn.metrics import confusion_matrix
import numpy as np
import itertools
cf =confusion_matrix(y_test_df.values,y_pred)
plt.imshow(cf,cmap=plt.cm.Blues,interpolation='nearest')
plt.colorbar()
plt.title('Confusion Matrix')
plt.xlabel('Predicted')
plt.ylabel('Actual')
class_labels = ['False','True']
tick_marks = ... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb | tomasro27/MachineLearningNotebooks |
Workflow registry authorization | # set the lifemonitor root
lifemonitor_root = "/mnt/data/projects/@crs4/EOSC-Life/Repositories/life_monitor_rachk8s"
%cd {lifemonitor_root}
# import requirements
import requests
import pprint
pp = pprint.PrettyPrinter(indent=2).pprint
# list registries
!docker-compose exec lm /bin/bash -c "flask registry show seek"
# ... | { 'name': 'seek',
'type': 'seek',
'uri': 'https://seek:3000',
'uuid': '1c40002b-8676-4f51-b529-9ff02ff78234'}
| MIT | examples/2_WorkflowRegistryAuthorize.ipynb | ilveroluca/life_monitor |
Submitted by Shailender Joseph and Ashish Kumar Sinha __Importing Libraries__ | import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, recall_score, roc_curve, auc
from sklearn import model_selection
from s... | _____no_output_____ | Apache-2.0 | dmml2/Shailender_Ashish_DMML_Assn_2.ipynb | AshishSinha5/mlAlgos |
Data Preprocessing | # Replacing the 'unknown' values wit the most frequent values
class DataFrameImputer(TransformerMixin):
def __init__(self):
"""Impute missing values.
Columns of dtype object are imputed with the most frequent value
in column.
Columns of other types are imputed with mean of column... | _____no_output_____ | Apache-2.0 | dmml2/Shailender_Ashish_DMML_Assn_2.ipynb | AshishSinha5/mlAlgos |
Function to output k-fold estimates of accuracy, recall, precision, f1, and roc_auc | def kfold_output(model, X, Y): #function for kfold output
start = timeit.default_timer()
begin = datetime.now()
scoring = ['accuracy', 'recall', 'precision', 'f1', 'roc_auc']
kfold = KFold(n_splits=10, random_state=100, shuffle = True)
results_kfold = model_selection.cross_validate(model, X, Y, sco... | _____no_output_____ | Apache-2.0 | dmml2/Shailender_Ashish_DMML_Assn_2.ipynb | AshishSinha5/mlAlgos |
Function to print roc curves for k-fold validation sets alongwith their AUC | def classifier_roc(classifier, X_train_res, y_train_res):
start = timeit.default_timer()
begin = datetime.now()
cv = KFold(n_splits=10, random_state=100, shuffle = True)
cv_split_filenames = []
tprs = []
aucs = []
mean_fpr = np.linspace(0, 1, 100)
plt.figure(figsize=(10,10))
i = 1
... | _____no_output_____ | Apache-2.0 | dmml2/Shailender_Ashish_DMML_Assn_2.ipynb | AshishSinha5/mlAlgos |
Function to plot roc curves using saved parameters | def plot_saved(directory,file_name, X_train_res,y_train_res):
start = timeit.default_timer()
begin = datetime.now()
cv = KFold(n_splits=10, random_state=100, shuffle = True)
tprs = []
aucs = []
mean_fpr = np.linspace(0, 1, 100)
plt.figure(figsize=(10,10))
i = 1
for train, test in cv.... | _____no_output_____ | Apache-2.0 | dmml2/Shailender_Ashish_DMML_Assn_2.ipynb | AshishSinha5/mlAlgos |
Building dataset for training | X_train_res = bank_final.drop(['y'], axis = 1)
y_train_res = bank_final['y'] | _____no_output_____ | Apache-2.0 | dmml2/Shailender_Ashish_DMML_Assn_2.ipynb | AshishSinha5/mlAlgos |
K-fold ouputs and ROC curve for Decision Tree classifier | dt_classifier = DecisionTreeClassifier(min_samples_split=60, min_samples_leaf=60, class_weight = 'balanced', random_state=20)
kfold_output(dt_classifier,X_train_res,y_train_res)
classifier_roc(dt_classifier, X_train_res, y_train_res) | _____no_output_____ | Apache-2.0 | dmml2/Shailender_Ashish_DMML_Assn_2.ipynb | AshishSinha5/mlAlgos |
ROC curve for Decision Tree classifier using saved parameters | plot_saved(DT_long, DT, X_train_res,y_train_res) | _____no_output_____ | Apache-2.0 | dmml2/Shailender_Ashish_DMML_Assn_2.ipynb | AshishSinha5/mlAlgos |
K-fold ouputs and ROC curve for Naive bayes classifier | nb_classifier = GaussianNB(priors = [0.11, 0.89])
kfold_output(nb_classifier,X_train_res,y_train_res)
classifier_roc(nb_classifier, X_train_res, y_train_res) | _____no_output_____ | Apache-2.0 | dmml2/Shailender_Ashish_DMML_Assn_2.ipynb | AshishSinha5/mlAlgos |
ROC curve for Naive Bayes classifier using saved parameters | plot_saved(GNB_long, GNB, X_train_res,y_train_res) | _____no_output_____ | Apache-2.0 | dmml2/Shailender_Ashish_DMML_Assn_2.ipynb | AshishSinha5/mlAlgos |
K-fold ouputs and ROC curve for SVM with plynomial kernel | svm_classifier = SVC(kernel = 'poly', random_state = 0, class_weight = 'balanced')
kfold_output(svm_classifier,X_train_res,y_train_res)
roc_svm_classifier = SVC(kernel = 'poly', probability = True, random_state = 0, class_weight = 'balanced')
classifier_roc(roc_svm_classifier, X_train_res, y_train_res) | _____no_output_____ | Apache-2.0 | dmml2/Shailender_Ashish_DMML_Assn_2.ipynb | AshishSinha5/mlAlgos |
ROC curve for SVM classifier using saved parameters | plot_saved(SVM_long, SVM, X_train_res,y_train_res) | _____no_output_____ | Apache-2.0 | dmml2/Shailender_Ashish_DMML_Assn_2.ipynb | AshishSinha5/mlAlgos |
This Jupyter Notebook contains the full code needed to write the ColumnTransformer blog Import Necessary Packages | import pandas as pd
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LinearRegression
from sklearn.pipeline impor... | _____no_output_____ | MIT | columntransformer_example.ipynb | allisonhonold/column_transformer_ferry_wait_blog |
Import Data and some pre-transformation data prep | # read the csvs with waits and weather
df = pd.read_csv('./data/dec2019.csv')
weather_df = pd.read_csv('./data/dec2019weather.csv')
# rename the columns
df.columns = ['date_hour', 'wait_hrs']
# cut the date_hours to the hour (no minutes/seconds) and convert to string for merging
df['date_hour'] = pd.to_datetime(df['da... | _____no_output_____ | MIT | columntransformer_example.ipynb | allisonhonold/column_transformer_ferry_wait_blog |
Simple Column Transformer Example | # a little cheating to extract the day of the week
# and hour of the day w/out using a transformer
# (see below for the "real" version)
df_simple = df_expanded.copy()
df_simple['weekday'] = [dt.weekday() for dt in df_simple['date_hour']]
df_simple['hour'] = [dt.hour for dt in df_simple['date_hour']]
df_simple.head()
... | SS col
['x0_0.0' 'x0_1.0' 'x0_2.0' 'x0_3.0' 'x0_4.0' 'x0_5.0' 'x0_6.0' 'x1_0.0'
'x1_5.0' 'x1_6.0' 'x1_7.0' 'x1_8.0' 'x1_9.0' 'x1_10.0' 'x1_11.0'
'x1_12.0' 'x1_13.0' 'x1_14.0' 'x1_15.0' 'x1_16.0' 'x1_17.0' 'x1_18.0'
'x1_19.0' 'x1_20.0' 'x1_21.0' 'x1_22.0' 'x1_23.0']
SS col
| MIT | columntransformer_example.ipynb | allisonhonold/column_transformer_ferry_wait_blog |
More complex column transformer example: imputing THEN standard scale/ohe | # define transformers
si_0 = SimpleImputer(strategy='constant', fill_value=0)
ss = StandardScaler()
ohe = OneHotEncoder()
# define column groups with same processing
cat_vars = ['weekday', 'hour']
num_vars = ['max_temp', 'avg_temp', 'min_temp']
# set up pipelines for each column group
categorical_pipe = Pipeline([
... | _____no_output_____ | MIT | columntransformer_example.ipynb | allisonhonold/column_transformer_ferry_wait_blog |
Create your own custom transformer | from sklearn.base import TransformerMixin, BaseEstimator
class DateTransformer(TransformerMixin, BaseEstimator):
"""Extracts features from datetime column
Returns:
hour: hour
day: Between 1 and the number of days in the given month of the given year.
month: Between 1 and 12 inclusive.
... | _____no_output_____ | MIT | columntransformer_example.ipynb | allisonhonold/column_transformer_ferry_wait_blog |
Rare features with ColumnTransformer | df = pd.DataFrame()
df['cat1'] = [0, 1, 1, 1, 1, 1, 1, 1, 1, 1]
df['cat2'] = [0, 0, 0, 0, 0, 2, 2, 2, 2, 2]
df['num1'] = [np.nan, 1, 1.1, .9, .8, np.nan, 2, 2.2, 1.5, np.nan]
df['num2'] = [1.1, 1.1, 1.1, 1.1, 1.1, 1.2, 1.2, 1.2, 1.2, 1.2]
target = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
X_train, X_test, y_train, y_test = tra... | _____no_output_____ | MIT | columntransformer_example.ipynb | allisonhonold/column_transformer_ferry_wait_blog |
Artist-themed Monopoly for Concert Prep DayJack L. '23 | #art fact function
def fact():
import random
x = random.randint(1,10)
if x == 1:
print("Bob Ross's 'Joy of Painting' TV series lasted for 31 seasons")
if x == 2:
print("In 1911 when the Mona Lisa was stolen from the Louvre, Pablo Picasso was one of the two primary suspects in the investi... | Welcome to Artist Monopoly!
This is just like regular monopoly but with some IMPORTANT twists:
To roll dice just ask siri to roll a pair of dice
*there are more spaces, and railroads have been replaced with more modern airlines
*there are auction spaces now. If you land on one you can buy any artist on the board but yo... | Apache-2.0 | Concert_Prep_artist_monopoly_JL.ipynb | athenian-ct-projects/Concert-Prep-Day-JL |
Python for Finance **Analyze Big Financial Data**O'Reilly (2014)Yves Hilpisch **Buy the book ** |O'Reilly |Amazon**All book codes & IPYNBs** |http://oreilly.quant-platform.com**The Python Quants GmbH** | http://tpq.io**Contact us** | pff@tpq.io Input-Output Operations | from pylab import plt
plt.style.use('ggplot')
import matplotlib as mpl
mpl.rcParams['font.family'] = 'serif' | _____no_output_____ | CNRI-Python | ipython3/07_Input_Output.ipynb | libaiw/PythonFinTechST |
Basic I/O with Python Writing Objects to Disk | path = './data/'
import numpy as np
from random import gauss
a = [gauss(1.5, 2) for i in range(1000000)]
# generation of normally distributed randoms
import pickle
pkl_file = open(path + 'data.pkl', 'wb')
# open file for writing
# Note: existing file might be overwritten
%time pickle.dump(a, pkl_file)
pkl_file
pk... | _____no_output_____ | CNRI-Python | ipython3/07_Input_Output.ipynb | libaiw/PythonFinTechST |
Reading and Writing Text Files | rows = 5000
a = np.random.standard_normal((rows, 5)) # dummy data
a.round(4)
import pandas as pd
t = pd.date_range(start='2014/1/1', periods=rows, freq='H')
# set of hourly datetime objects
t
csv_file = open(path + 'data.csv', 'w') # open file for writing
header = 'date,no1,no2,no3,no4,no5\n'
csv_file.write(heade... | _____no_output_____ | CNRI-Python | ipython3/07_Input_Output.ipynb | libaiw/PythonFinTechST |
SQL Databases | import sqlite3 as sq3
query = 'CREATE TABLE numbs (Date date, No1 real, No2 real)'
con = sq3.connect(path + 'numbs.db')
con.execute(query)
con.commit()
import datetime as dt
con.execute('INSERT INTO numbs VALUES(?, ?, ?)',
(dt.datetime.now(), 0.12, 7.3))
data = np.random.standard_normal((10000, 2)).round(5)... | _____no_output_____ | CNRI-Python | ipython3/07_Input_Output.ipynb | libaiw/PythonFinTechST |
Writing and Reading Numpy Arrays | import numpy as np
dtimes = np.arange('2015-01-01 10:00:00', '2021-12-31 22:00:00',
dtype='datetime64[m]') # minute intervals
len(dtimes)
dty = np.dtype([('Date', 'datetime64[m]'), ('No1', 'f'), ('No2', 'f')])
data = np.zeros(len(dtimes), dtype=dty)
data['Date'] = dtimes
a = np.random.standard_normal... | _____no_output_____ | CNRI-Python | ipython3/07_Input_Output.ipynb | libaiw/PythonFinTechST |
I/O with pandas | import numpy as np
import pandas as pd
data = np.random.standard_normal((1000000, 5)).round(5)
# sample data set
filename = path + 'numbs' | _____no_output_____ | CNRI-Python | ipython3/07_Input_Output.ipynb | libaiw/PythonFinTechST |
SQL Database | import sqlite3 as sq3
query = 'CREATE TABLE numbers (No1 real, No2 real,\
No3 real, No4 real, No5 real)'
con = sq3.Connection(filename + '.db')
con.execute(query)
%%time
con.executemany('INSERT INTO numbers VALUES (?, ?, ?, ?, ?)', data)
con.commit()
ll $path*
%%time
temp = con.execute('SELECT * FROM numbers').... | _____no_output_____ | CNRI-Python | ipython3/07_Input_Output.ipynb | libaiw/PythonFinTechST |
From SQL to pandas | import pandas.io.sql as pds
%time data = pds.read_sql('SELECT * FROM numbers', con)
data.head()
%time data[(data['No1'] > 0) & (data['No2'] < 0)].head()
%%time
res = data[['No1', 'No2']][((data['No1'] > 0.5) | (data['No1'] < -0.5))
& ((data['No2'] < -1) | (data['No2'] > 1))]
plt.plot(res.No1, res.N... | -rw-r--r--@ 1 yves staff 52633600 Jul 11 19:24 ./data/numbs.db
-rw-r--r--@ 1 yves staff 48007192 Jul 11 19:24 ./data/numbs.h5s
| CNRI-Python | ipython3/07_Input_Output.ipynb | libaiw/PythonFinTechST |
Data as CSV File | %time data.to_csv(filename + '.csv')
ls data/
%%time
pd.read_csv(filename + '.csv')[['No1', 'No2',
'No3', 'No4']].hist(bins=20)
# tag: data_hist_3
# title: Histogram of 4 data sets
# size: 60 | CPU times: user 1.25 s, sys: 151 ms, total: 1.41 s
Wall time: 1.41 s
| CNRI-Python | ipython3/07_Input_Output.ipynb | libaiw/PythonFinTechST |
Data as Excel File | %time data[:100000].to_excel(filename + '.xlsx')
%time pd.read_excel(filename + '.xlsx', 'Sheet1').cumsum().plot()
# tag: data_paths
# title: Paths of random data from Excel file
# size: 60
ll $path*
rm -f $path* | _____no_output_____ | CNRI-Python | ipython3/07_Input_Output.ipynb | libaiw/PythonFinTechST |
Fast I/O with PyTables | import numpy as np
import tables as tb
import datetime as dt
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | CNRI-Python | ipython3/07_Input_Output.ipynb | libaiw/PythonFinTechST |
Working with Tables | filename = path + 'tab.h5'
h5 = tb.open_file(filename, 'w')
rows = 2000000
row_des = {
'Date': tb.StringCol(26, pos=1),
'No1': tb.IntCol(pos=2),
'No2': tb.IntCol(pos=3),
'No3': tb.Float64Col(pos=4),
'No4': tb.Float64Col(pos=5)
}
filters = tb.Filters(complevel=0) # no compression
tab = h5.creat... | (1234, 9994)
(1234, 9997)
(1234, 9921)
(1234, 9902)
(1234, 9975)
(1234, 9970)
CPU times: user 28 ms, sys: 44.7 ms, total: 72.6 ms
Wall time: 51.7 ms
| CNRI-Python | ipython3/07_Input_Output.ipynb | libaiw/PythonFinTechST |
Working with Compressed Tables | filename = path + 'tab.h5c'
h5c = tb.open_file(filename, 'w')
filters = tb.Filters(complevel=4, complib='blosc')
tabc = h5c.create_table('/', 'ints_floats', sarray,
title='Integers and Floats',
expectedrows=rows, filters=filters)
%%time
res = np.array([(row['No3'], row['No... | _____no_output_____ | CNRI-Python | ipython3/07_Input_Output.ipynb | libaiw/PythonFinTechST |
Working with Arrays | %%time
arr_int = h5.create_array('/', 'integers', ran_int)
arr_flo = h5.create_array('/', 'floats', ran_flo)
h5
ll $path*
h5.close()
!rm -f $path* | _____no_output_____ | CNRI-Python | ipython3/07_Input_Output.ipynb | libaiw/PythonFinTechST |
Out-of-Memory Computations | filename = path + 'array.h5'
h5 = tb.open_file(filename, 'w')
n = 100
ear = h5.create_earray(h5.root, 'ear',
atom=tb.Float64Atom(),
shape=(0, n))
%%time
rand = np.random.standard_normal((n, n))
for i in range(750):
ear.append(rand)
ear.flush()
ear
ear.size_on_disk
out = ... | _____no_output_____ | CNRI-Python | ipython3/07_Input_Output.ipynb | libaiw/PythonFinTechST |
Copyright 2018 The TensorFlow Hub Authors.Licensed under the Apache License, Version 2.0 (the "License"); | # Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved.
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | _____no_output_____ | Apache-2.0 | tools/colab/keras_mnist_tpu.ipynb | eliabruni/tpu |
MNIST on TPU (Tensor Processing Unit)or GPU using tf.Keras and tf.data.Dataset OverviewThis sample trains an "MNIST" handwritten digit recognition model on a GPU or TPU backend using a Kerasmodel. Data are handled using the tf.data.Datset API. This isa very simple sample provided for educational purposes. Donot expect... | import os, re, time, json
import PIL.Image, PIL.ImageFont, PIL.ImageDraw
import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt
print("Tensorflow version " + tf.__version__)
#@title visualization utilities [RUN ME]
"""
This cell contains helper functions used for visualization
and downloads onl... | _____no_output_____ | Apache-2.0 | tools/colab/keras_mnist_tpu.ipynb | eliabruni/tpu |
*(you can double-click on collapsed cells to view the non-essential code inside)* Colab-only auth for this notebook and the TPU | IS_COLAB_BACKEND = 'COLAB_GPU' in os.environ # this is always set on Colab, the value is 0 or 1 depending on GPU presence
if IS_COLAB_BACKEND:
from google.colab import auth
# Authenticates the Colab machine and also the TPU using your
# credentials so that they can access your private GCS buckets.
auth.authent... | _____no_output_____ | Apache-2.0 | tools/colab/keras_mnist_tpu.ipynb | eliabruni/tpu |
TPU or GPU detection | # Detect hardware
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver() # TPU detection
except ValueError:
tpu = None
gpus = tf.config.experimental.list_logical_devices("GPU")
# Select appropriate distribution strategy
if tpu:
tf.tpu.experimental.initialize_tpu_system(tpu)
strategy = tf.distribu... | Running on TPU ['10.122.37.122:8470']
Number of accelerators: 8
| Apache-2.0 | tools/colab/keras_mnist_tpu.ipynb | eliabruni/tpu |
Parameters | BATCH_SIZE = 64 * strategy.num_replicas_in_sync # Gobal batch size.
# The global batch size will be automatically sharded across all
# replicas by the tf.data.Dataset API. A single TPU has 8 cores.
# The best practice is to scale the batch size by the number of
# replicas (cores). The learning rate should be increased ... | _____no_output_____ | Apache-2.0 | tools/colab/keras_mnist_tpu.ipynb | eliabruni/tpu |
tf.data.Dataset: parse files and prepare training and validation datasetsPlease read the [best practices for building](https://www.tensorflow.org/guide/performance/datasets) input pipelines with tf.data.Dataset | def read_label(tf_bytestring):
label = tf.io.decode_raw(tf_bytestring, tf.uint8)
label = tf.reshape(label, [])
label = tf.one_hot(label, 10)
return label
def read_image(tf_bytestring):
image = tf.io.decode_raw(tf_bytestring, tf.uint8)
image = tf.cast(image, tf.float32)/255.0
image = tf.re... | _____no_output_____ | Apache-2.0 | tools/colab/keras_mnist_tpu.ipynb | eliabruni/tpu |
Let's have a look at the data | N = 24
(training_digits, training_labels,
validation_digits, validation_labels) = dataset_to_numpy_util(training_dataset, validation_dataset, N)
display_digits(training_digits, training_labels, training_labels, "training digits and their labels", N)
display_digits(validation_digits[:N], validation_labels[:N], validati... | _____no_output_____ | Apache-2.0 | tools/colab/keras_mnist_tpu.ipynb | eliabruni/tpu |
Keras model: 3 convolutional layers, 2 dense layersIf you are not sure what cross-entropy, dropout, softmax or batch-normalization mean, head here for a crash-course: [Tensorflow and deep learning without a PhD](https://github.com/GoogleCloudPlatform/tensorflow-without-a-phd/featured-code-sample) | # This model trains to 99.4% accuracy in 10 epochs (with a batch size of 64)
def make_model():
model = tf.keras.Sequential(
[
tf.keras.layers.Reshape(input_shape=(28*28,), target_shape=(28, 28, 1), name="image"),
tf.keras.layers.Conv2D(filters=12, kernel_size=3, padding='same', use_bias=Fa... | W0805 18:33:32.316657 140549664556928 deprecation.py:506] From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializ... | Apache-2.0 | tools/colab/keras_mnist_tpu.ipynb | eliabruni/tpu |
Train and validate the model | EPOCHS = 10
steps_per_epoch = 60000//BATCH_SIZE # 60,000 items in this dataset
print("Steps per epoch: ", steps_per_epoch)
# Little wrinkle: in the present version of Tensorfow (1.14), switching a TPU
# between training and evaluation is slow (approx. 10 sec). For small models,
# it is recommeneded to run a single ... | Steps per epoch: 117
| Apache-2.0 | tools/colab/keras_mnist_tpu.ipynb | eliabruni/tpu |
Visualize predictions | # recognize digits from local fonts
probabilities = model.predict(font_digits, steps=1)
predicted_labels = np.argmax(probabilities, axis=1)
display_digits(font_digits, predicted_labels, font_labels, "predictions from local fonts (bad predictions in red)", N)
# recognize validation digits
probabilities = model.predict(... | _____no_output_____ | Apache-2.0 | tools/colab/keras_mnist_tpu.ipynb | eliabruni/tpu |
Deploy the trained model to AI Platform model servingPush your trained model to production on AI Platform for a serverless, autoscaled, REST API experience.You will need a GCS (Google Cloud Storage) bucket and a GCP project for this.Models deployed on AI Platform autoscale to zero if not used. There will be no AI Plat... | PROJECT = "" #@param {type:"string"}
BUCKET = "gs://" #@param {type:"string", default:"jddj"}
NEW_MODEL = True #@param {type:"boolean"}
MODEL_NAME = "mnist" #@param {type:"string"}
MODEL_VERSION = "v1" #@param {type:"string"}
assert PROJECT, 'For this part, you need a GCP project. Head to http://console.cloud.google.... | _____no_output_____ | Apache-2.0 | tools/colab/keras_mnist_tpu.ipynb | eliabruni/tpu |
Export the model for serving from AI Platform | # Wrap the model so that we can add a serving function
class ExportModel(tf.keras.Model):
def __init__(self, model):
super().__init__(self)
self.model = model
# The serving function performig data pre- and post-processing.
# Pre-processing: images are received in uint8 format converted
# ... | The given SavedModel contains the following tag-sets:
serve
The given SavedModel MetaGraphDef contains SignatureDefs with the following keys:
SignatureDef key: "__saved_model_init_op"
SignatureDef key: "serving_default"
The given SavedModel SignatureDef contains the following input(s):
inputs['images'] tensor_info:
... | Apache-2.0 | tools/colab/keras_mnist_tpu.ipynb | eliabruni/tpu |
Deploy the modelThis uses the command-line interface. You can do the same thing through the AI Platform UI at https://console.cloud.google.com/mlengine/models | # Create the model
if NEW_MODEL:
!gcloud ai-platform models create {MODEL_NAME} --project={PROJECT} --regions=us-central1
# Create a version of this model (you can add --async at the end of the line to make this call non blocking)
# Additional config flags are available: https://cloud.google.com/ml-engine/reference/r... | _____no_output_____ | Apache-2.0 | tools/colab/keras_mnist_tpu.ipynb | eliabruni/tpu |
Test the deployed modelYour model is now available as a REST API. Let us try to call it. The cells below use the "gcloud ml-engine"command line tool but any tool that can send a JSON payload to a REST endpoint will work. | # prepare digits to send to online prediction endpoint
digits_float32 = np.concatenate((font_digits, validation_digits[:100-N])) # pixel values in [0.0, 1.0] float range
digits_uint8 = np.round(digits_float32*255).astype(np.uint8) # pixel values in [0, 255] int range
labels = np.concatenate((font_labels, validation_lab... | ['DIGITS', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '7', '2', '1', '0', '4', '1', '4', '9', '5', '9', '0', '6', '9', '0', '1', '5', '9', '7', '3', '4', '9', '6', '6', '5', '4', '0', '7', '4', '0', '1', '3', '1', '3', '4', '7', '2', '7', '1',... | Apache-2.0 | tools/colab/keras_mnist_tpu.ipynb | eliabruni/tpu |
Writing an iterator to load data in chunks (1)Another way to read data too large to store in memory in chunks is to read the file in as DataFrames of a certain length, say, 100. For example, with the pandas package (imported as pd), you can do pd.read_csv(filename, chunksize=100). This creates an iterable reader objec... | # Import the pandas package
import pandas as pd
# Initialize reader object: df_reader
df_reader = pd.read_csv('world_ind_pop_data.csv' , chunksize= 10)
# Print two chunks
print(next(df_reader))
print(next(df_reader))
| CountryName CountryCode Year \
0 Arab World ARB 1960
1 Caribbean small states CSS 1960
2 Central Europe and the Baltics CEB 1960
3 East Asia & Pacific (all income levels) EAS... | MIT | Python Data Science Toolbox -Part 2/Bringing it all together/08. Writing an iterator to load data in chunks (1).ipynb | nazmusshakib121/Python-Programming |
第6章 スモール言語を作る | # !pip install pegtree
import pegtree as pg
from pegtree.colab import peg, pegtree, example
%%peg
Program = { // 開式非終端記号 Expression*
#Program
} EOF
EOF = !. // ファイル終端
Expression =
/ FuncDecl // 関数定義
/ VarDecl // 変数定義
/ IfExpr // if 式
/ Binary // 二項演算
| UsageError: Cell magic `%%peg` not found.
| MIT | pegbook_chap6.ipynb | kkuramitsu/pegbook2021 |
import pegtree as pgpeg = pg.grammar('chibi.pegtree') parser = pg.generate(peg) 6.2.5 パーザの生成 | import pegtree as pg
peg = pg.grammar('chibi.pegtree')
parser = pg.generate(peg) | _____no_output_____ | MIT | pegbook_chap6.ipynb | kkuramitsu/pegbook2021 |
トランスコンパイラ | class Visitor(object):
def visit(self, tree):
tag = tree.getTag()
name = f'accept{tag}'
if hasattr(self, name): # accept メソッドがあるか調べる
# メソッド名からメソッドを得る
acceptMethod = getattr(self, name)
return acceptMethod(tree)
print(f'TODO: accept{tag}')
... | TODO: acceptProgram
| MIT | pegbook_chap6.ipynb | kkuramitsu/pegbook2021 |
各ノードのコード変換 | BUILTIN_FUNCTIONS = {
'print': 'console.log'
}
class Compiler(Visitor): # Visitor クラスの継承
def __init__(self):
self.buffers = []
peg = pg.grammar('chibi.pegtree')
self.parser = pg.generate(peg)
def compile(self, source):
tree = self.parser(source) # 構文木に交換
self.buf... | Syntax Error ((unknown source):2:-1+0)
| MIT | pegbook_chap6.ipynb | kkuramitsu/pegbook2021 |
インタプリタ | class Interpreter(Visitor):
def __init__(self):
self.env = {} # 空の環境を用意する
peg = pg.grammar('chibi.pegtree')
self.parser = pg.generate(peg)
def eval(self, source):
tree = self.parser(source)
return self.visit(tree)
chibi = Interpreter()
source = input('>>> ')
whil... | TODO: accepterr
None
| MIT | pegbook_chap6.ipynb | kkuramitsu/pegbook2021 |
SQL in Python Packages - [Pandas.read_sql](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_sql.html) - [SQLite3](https://docs.python.org/3.6/library/sqlite3.html) Tutorials- https://www.tutorialspoint.com/sqlite/sqlite_python.htm- https://www.pythoncentral.io/introduction-to-sqlite-in-python/- ... | # Imports
import sqlite3 as sq3
import pandas.io.sql as pds
import pandas as pd | _____no_output_____ | MIT | SQL in Python.ipynb | jamwine/SQL-in-Python |
Database connectionsOur first step will be to create a connection to our SQL database. A few common SQL databases used with Python include: - Microsoft SQL Server - Postgres - MySQL - AWS Redshift - AWS Aurora - Oracle DB - Terradata - Db2 Family - Many, many others Each of these databases will require a slightly diff... | # Initialize path to SQLite database
path = 'databases/classic_rock.db'
con = sq3.Connection(path)
# We now have a live connection to our SQL database | _____no_output_____ | MIT | SQL in Python.ipynb | jamwine/SQL-in-Python |
Reading dataNow that we've got a connection to our database, we can perform queries, and load their results in as Pandas DataFrames | # Write the query
query = '''
SELECT *
FROM rock_songs;
'''
# Execute the query
observations = pds.read_sql(query, con)
observations.head()
# We can also run any supported SQL query
# Write the query
query = '''
SELECT Artist, Release_Year, COUNT(*) AS num_songs, AVG(PlayCount) AS avg_plays
FROM rock_songs
... | _____no_output_____ | MIT | SQL in Python.ipynb | jamwine/SQL-in-Python |
Common parametersThere are a number of common paramters that can be used to read in SQL data with formatting: - **coerce_float**: Attempt to force numbers into floats - **parse_dates**: List of columns to parse as dates - **chunksize**: Number of rows to include in each chunk | query='''
SELECT Artist, Release_Year, COUNT(*) AS num_songs, AVG(PlayCount) AS avg_plays
FROM rock_songs
GROUP BY Artist, Release_Year
ORDER BY num_songs desc;
'''
# Execute the query
observations_generator = pds.read_sql(query,
con,
coerce_float=T... | Observations index: 0
| MIT | SQL in Python.ipynb | jamwine/SQL-in-Python |
Baseball Database Example | # Create a variable, `path`, containing the path to the `baseball.db` contained in `resources/`
path = 'databases/baseball.db'
# Create a connection, `con`, that is connected to database at `path`
con = sq3.Connection(path)
# Create a variable, tables, which reads in all data from the table sqlite_master
all_tables = ... | _____no_output_____ | MIT | SQL in Python.ipynb | jamwine/SQL-in-Python |
Artists Database Example | conn = sq3.connect("databases/artists.sqlite")
# Displaying all tables in database
pd.read_sql("select name from sqlite_master where type = 'table';", conn)
query="SELECT * FROM artists"
music_reviews = pd.read_sql_query(query, conn)
music_reviews.tail()
query1="SELECT * FROM artists WHERE artist='kleenex'"
result=pd.... | _____no_output_____ | MIT | SQL in Python.ipynb | jamwine/SQL-in-Python |
Data Space Report Pittsburgh Bridges Data Set Andy Warhol Bridge - Pittsburgh.Report created by Student Francesco Maria Chiarlo s253666, for A.A 2019/2020.**Abstract**:The aim of this report is to evaluate the effectiveness of distinct, different statistical learning approaches, in particular focusing on their char... | from utils.all_imports import *;
%matplotlib inline
# Some global script variables
# --------------------------------------------------------------------------- #
dataset_path, dataset_name, column_names, TARGET_COL = \
get_dataset_location() # Info Data to be fetched
estimators_list, estimators_names = get_estimat... | Summary about Target Variable {target_col}
--------------------------------------------------
2 57
1 13
Name: T-OR-D, dtype: int64
shape features matrix X, after normalizing: (70, 11)
| MIT | pittsburgh-bridges-data-set-analysis/models-analyses/grid_search_analyses/Data Space Report (Official) - Sgd Classifier-v1.0.0.ipynb | franec94/Pittsburgh-Bridge-Dataset |
Pricipal Component Analysis | show_table_pc_analysis(X=rescaledX) | Cumulative varation explained(percentage) up to given number of pcs:
| MIT | pittsburgh-bridges-data-set-analysis/models-analyses/grid_search_analyses/Data Space Report (Official) - Sgd Classifier-v1.0.0.ipynb | franec94/Pittsburgh-Bridge-Dataset |
Major Pros & Cons of PCA Learning Models | # Parameters to be tested for Cross-Validation Approach
# -----------------------------------------------------
param_grids = []
parmas_logreg = {
'penalty': ('l1', 'l2', 'elastic', None),
'solver': ('newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'),
'fit_intercept': (True, False),
'tol': (1e-4, 1e-3, 1... | _____no_output_____ | MIT | pittsburgh-bridges-data-set-analysis/models-analyses/grid_search_analyses/Data Space Report (Official) - Sgd Classifier-v1.0.0.ipynb | franec94/Pittsburgh-Bridge-Dataset |
| Learning Technique | Type of Learner | Type of Learning | Classification | Regression | Clustering || --- | --- | --- | --- | --- | --- || *Stochastic Gradient Descent (SGD)* | *Linear Model* | *Supervised Learning*| *Supported* | *Supported* | *Not-Supported*| | n_components=9
learning_curves_by_kernels(
# learning_curves_by_components(
estimators_list[:], estimators_names[:],
rescaledX, y,
train_sizes=np.linspace(.1, 1.0, 10),
n_components=9,
pca_kernels_list=pca_kernels_list[0],
verbose=0,
by_pairs=True,
savefigs=True,
scoring='accuracy',
... | Kernel PCA: Linear | SGD
====================================================================================================
precision recall f1-score support
class 0 0.32 1.00 0.48 6
class 1 1.00 0.54 0.70 28
accuracy ... | MIT | pittsburgh-bridges-data-set-analysis/models-analyses/grid_search_analyses/Data Space Report (Official) - Sgd Classifier-v1.0.0.ipynb | franec94/Pittsburgh-Bridge-Dataset |
Looking at the results obtained running *Sgd Classifier* against our dataset splitted into training set and test set and adopting a different kernel trick applied to *kernel-Pca* unsupervised preprocessing method we can state generally speaking that looking at the weighted values of *Recall, Precision, and F1-Scores* w... | # create_widget_list_df([df_gs, df_auc_gs]) #print(df_gs); print(df_auc_gs)
show_table_summary_grid_search(df_gs, df_auc_gs, df_pvalue) | _____no_output_____ | MIT | pittsburgh-bridges-data-set-analysis/models-analyses/grid_search_analyses/Data Space Report (Official) - Sgd Classifier-v1.0.0.ipynb | franec94/Pittsburgh-Bridge-Dataset |
Looking at the table dispalyed just above that shows the details about the selected values for hyper-parameters specified during grid search, in the different situations accordingly to the fixed kernel-trick for kernel Pca unsupervised method we can state that, referring to the first two columns of *Train and Test Accu... | # show_histogram_first_sample(Xtrain_transformed, ytrain_, estimators_) | _____no_output_____ | MIT | pittsburgh-bridges-data-set-analysis/models-analyses/grid_search_analyses/Data Space Report (Official) - Sgd Classifier-v1.0.0.ipynb | franec94/Pittsburgh-Bridge-Dataset |
Datasethttps://data.wprdc.org/dataset/allegheny-county-restaurant-food-facility-inspection-violations/resource/112a3821-334d-4f3f-ab40-4de1220b1a0aThis data set is a set of all of the restaurants in Allegheny County with geographic locations including zip code, size, description of use, and a "status" ranging from 0 t... | import pandas as pd
restaurants_all = pd.read_csv("r.csv")
| _____no_output_____ | Unlicense | .ipynb_checkpoints/Teresa's Data-checkpoint.ipynb | GrayCleric4/Final-Project |
First, I remove the few restaurants that are outside of Pittsburgh and those with a value of 0 or 1 for their status, which indicates that they are closed. | query_mask = restaurants_all['status'] > 1
zip_mask_low = restaurants_all['zip'] > 14999.0
zip_mask_high = restaurants_all['zip'] < 16000.0
open_restaurants = restaurants_all[query_mask]
open_restaurants = open_restaurants[zip_mask_low]
open_restaurants = open_restaurants[zip_mask_high]
open_restaurants = open_restaura... | <ipython-input-3-b236f237d444>:5: UserWarning: Boolean Series key will be reindexed to match DataFrame index.
open_restaurants = open_restaurants[zip_mask_low]
<ipython-input-3-b236f237d444>:6: UserWarning: Boolean Series key will be reindexed to match DataFrame index.
open_restaurants = open_restaurants[zip_mask_h... | Unlicense | .ipynb_checkpoints/Teresa's Data-checkpoint.ipynb | GrayCleric4/Final-Project |
Then I count up the number of open restaurants within a certain zipcode by keeping track of the data in a dictionary, using the zipcode as a key and incrementing the value associated with it. | zipcode_counter = dict()
for row in open_restaurants.index:
zipc = open_restaurants.loc[row, "zip"]
if zipc not in zipcode_counter:
zipcode_counter[zipc] = 1
else:
zipcode_counter[zipc] = zipcode_counter[zipc] + 1
zipcode_counter
zip_sorted = dict(sorted(zipcode_counter.items(), key=l... | _____no_output_____ | Unlicense | .ipynb_checkpoints/Teresa's Data-checkpoint.ipynb | GrayCleric4/Final-Project |
Plotting this data, we find that there is a very wide range from 0 to 1041 and a mean of 124 restaurants per zipcode. | #all_values = zipcode_counter.values()
#max_value = max(all_values)
#print(max_value)
max_key = max(zipcode_counter, key=zipcode_counter.get)
print(max_key)
min_key = min(zipcode_counter, key=zipcode_counter.get)
print(min_key)
| 15222.0
15047.0
| Unlicense | .ipynb_checkpoints/Teresa's Data-checkpoint.ipynb | GrayCleric4/Final-Project |
The top ten zipcodes with the most restaurants and their corresponding neighborhoods are: * 15222.0: 1041 - Strip District* 15212.0: 694 - North Shore/North Side* 15213.0: 677 - Oakland* 15219.0: 639 - Hill District* 15237.0: 509 - Ross Township* 15146.0: 482 - Monroeville* 15205.0: 423 - Crafton* 15108.0: 408 - Coraop... | print(len(zip_sorted))
zipcode_points_restaurants = dict()
i = 1
for key in zip_sorted:
zipcode_points_restaurants[key] = i // 28 + 1
i = i + 1
zipcode_points_restaurants | 139
| Unlicense | .ipynb_checkpoints/Teresa's Data-checkpoint.ipynb | GrayCleric4/Final-Project |
Dimensionality Reduction ExampleUsing the IMDB data, feature matrix and apply dimensionality reduction to this matrix via PCA and SVD. | %matplotlib inline
import json
import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.sparse import lil_matrix
from sklearn.neighbors import DistanceMetric
from sklearn.metrics import jaccard_score
from sklearn.metrics import pairwise_distances
# Let's restrict ourselves jus... | Known Actors: 161996
| Apache-2.0 | Module03/04-Dimensionality.SVD.ipynb | tejatammali/umd.inst414 |
Generate Same DataFrame using Sparse MatricsThe above will break if you have too much data. We can get around that partially with sparse matrices, where we only store the non-zero elements of the feature matrix and their indices. | # With sparse matrix, initialize to size of Movies x Actors of 0s
matrix_sparse = lil_matrix((len(movie_actor_list), len(known_actors)), dtype=bool)
# Update the matrix, movie by movie, setting non-zero values for the appropriate actors
for row,movie in enumerate(movie_actor_list):
for actor_id in movie["actors... | _____no_output_____ | Apache-2.0 | Module03/04-Dimensionality.SVD.ipynb | tejatammali/umd.inst414 |
Apply SVD to Feature Matrix | # https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html
from sklearn.decomposition import TruncatedSVD
matrix_dense = reduced_df.to_numpy()
reduced_df
svd = TruncatedSVD(n_components=2)
svd.fit(matrix_dense)
matrix_reduced = svd.transform(matrix_dense)
np.mean(matrix_reduced, axis=0... | Movies in Component 2: 18069
Genres:
Drama 17274
Comedy 7327
Thriller 5586
Action 5152
Crime 3959
Romance 3727
Horror 3165
Mystery 2093
Adventure 2032
Sci-Fi 1190
Actors:
Joe Hammerstone 91
Tony Devon 85
Louis Koo 85
Brahmanandam 79
Nicolas Cage 69
James Franco 68
Prakash Raj 65
Samu... | Apache-2.0 | Module03/04-Dimensionality.SVD.ipynb | tejatammali/umd.inst414 |
Find Similar Movies in Reduced Dimensional Space | query_idx = [idx for idx,m in enumerate(reduced_df.index) if m == "The Lord of the Rings: The Fellowship of the Ring"][0]
# query_idx = [idx for idx,m in enumerate(reduced_df.index) if m == "Heavy Metal 2000"][0]
# query_idx = [idx for idx,m in enumerate(reduced_df.index) if m == "Casino Royale"][0]
# query_idx = [idx ... | 18 The Lord of the Rings: The Fellowship of the Ring 0.0
11487 Days and Nights 1.2209541406754873e-05
18457 The Tomorrow War 1.2776674116332596e-05
6383 My Own Love Song 1.3171993015743094e-05
10102 Best Man Down 1.639756956937894e-05
15541 Kingsglaive: Final Fantasy XV 1.8152531475848637e-05
11126 Mystery Road 2.18965... | Apache-2.0 | Module03/04-Dimensionality.SVD.ipynb | tejatammali/umd.inst414 |
SVD and Column Feature SpaceAbove, we focused on the *movies* in the reduced feature/"concept" space. Here, we will use SVD to map the *actors* into the reduced "concept" space. | # See that the shape of this matrix is *reduced space* X original features
svd.components_.shape | _____no_output_____ | Apache-2.0 | Module03/04-Dimensionality.SVD.ipynb | tejatammali/umd.inst414 |
We will use this reduced space to inspect the associations with a given actor and the concept set of concepts (i.e., the reduced space) | # query_actor = [idx for idx,name in actor_id_to_name_map.items() if name == "Ewan McGregor"][0]
# query_actor = [idx for idx,name in actor_id_to_name_map.items() if name == "Eric Roberts"][0]
# query_actor = [idx for idx,name in actor_id_to_name_map.items() if name == "Jason Statham"][0]
# query_actor = [idx for idx,n... | 397 George Clooney 0.0
854 Lalu Alex 2.1684959239110375e-05
552 Steve Carell 5.765535961270728e-05
950 Liam Neeson 8.58474608863118e-05
494 Tanikella Bharani 0.00011361512397967896
522 Gérard Depardieu 0.00014417276880813264
926 Siddique 0.0001534176616126892
888 Shawn Yue 0.00015625326486224262
584 Kunchacko Boban 0.0... | Apache-2.0 | Module03/04-Dimensionality.SVD.ipynb | tejatammali/umd.inst414 |
SVD is more scalable than PCA | from sklearn.decomposition import PCA
matrix_sparse.shape
# This will fail
pca = PCA(n_components=2)
pca.fit(matrix_sparse)
svd = TruncatedSVD(n_components=2)
svd.fit(matrix_sparse)
matrix_reduced = svd.transform(matrix_sparse)
print(np.mean(matrix_reduced, axis=0))
plt.scatter(matrix_reduced[:,0], matrix_reduced[:,1])... | _____no_output_____ | Apache-2.0 | Module03/04-Dimensionality.SVD.ipynb | tejatammali/umd.inst414 |
Let's look at some tweets | print('Loading previously "cleaned" tweets (could take a minute or so)...')
df = pd.read_csv(os.path.join(DATA_PATH, 'deduped_tweets.csv.gz'), index_col='id', compression='gzip',
quotechar='"', quoting=pd.io.common.csv.QUOTE_NONNUMERIC, low_memory=False)
print('Loaded {} tweets.'.format(len(df)))
df
te... |
#python never stop learning what you enjoy doing. https://t.co/IH5ZSKnU8K
Watching Boa vs. Python — https://t.co/Pivpk02s2A
Monty Python - The silly walk https://t.co/C0Ja8UHL4t via @YouTube
Senior Software Engineer Full Stack Python Django And Php Jobs #jobs #jobsearch https://t.co/EuO3Et4JIT
Architect Django Sol... | MIT | docs/notebooks/04 Data -- Natural Language.ipynb | orabhan/twip |
1. Workflow for building and deploying interactive dashboards **Let's say you want to make it easy to explore some dataset. That is, you want to:** * Make a visualization of the data* Maybe add some custom widgets to see the effects of some variables* Then deploy the result as a web app.**You can definitely do that in... | import holoviews as hv
import geoviews as gv
import param, paramnb, parambokeh
import dask.dataframe as dd
from colorcet import cm
from bokeh.models import WMTSTileSource
from holoviews.operation.datashader import datashade
from holoviews.operation import decimate
from holoviews.streams import RangeXY, PlotSize | _____no_output_____ | BSD-3-Clause | notebooks/01-workflow-introduction.ipynb | kasiarachuta-zz/jupytercon2017-holoviews-tutorial |
Step 1: Get some data* Here we'll use a subset of the often-studied NYC Taxi dataset* About 12 million points of GPS locations from taxis* Stored in the efficient Parquet format for easy access* Loaded into a Dask dataframe for multi-core(and if needed, out-of-core or distributed) computation Warning! If you are low... | %time df = dd.read_parquet('../data/nyc_taxi_hours.parq/').persist()
print(len(df))
df.head(2) | _____no_output_____ | BSD-3-Clause | notebooks/01-workflow-introduction.ipynb | kasiarachuta-zz/jupytercon2017-holoviews-tutorial |
Step 2: Prototype a plot in a notebook* A text-based representation isn't very useful for big datasets like this, so we need to build a plot* But we don't want to start a software project, so we use HoloViews: - Simple, declarative way to annotate your data for visualization - Large library of Elements with asso... | hv.extension('bokeh')
points = hv.Points(df, kdims=['pickup_x', 'pickup_y'])
decimate(points) | _____no_output_____ | BSD-3-Clause | notebooks/01-workflow-introduction.ipynb | kasiarachuta-zz/jupytercon2017-holoviews-tutorial |
Here ``Points`` declares an object wrapping `df` and visualized as a scatterplot, and `decimate` limits the number of points that will be sent to the browser to avoid crashing it.As you can see, HoloViews makes it very simple to pop up a visualization of your data, getting *something* on screen with only a few characte... | options = dict(width=700, height=600, xaxis=None, yaxis=None, bgcolor='black')
points = points.opts(plot=options)
decimate(points) | _____no_output_____ | BSD-3-Clause | notebooks/01-workflow-introduction.ipynb | kasiarachuta-zz/jupytercon2017-holoviews-tutorial |
That looks a bit better, but it's still decimating the data nearly beyond recognition, so let's try using Datashader to rasterize it into a fixed-size image to send to the browser: | taxi_trips = datashade(points, x_sampling=1, y_sampling=1, cmap=cm['fire']).opts(plot=options)
taxi_trips | _____no_output_____ | BSD-3-Clause | notebooks/01-workflow-introduction.ipynb | kasiarachuta-zz/jupytercon2017-holoviews-tutorial |
Ok, that looks good now; there's clearly lots to explore in this dataset. To put it in context, let's overlay that on a map: | taxi_trips = datashade(points, x_sampling=1, y_sampling=1, cmap=cm['fire']).opts(plot=options)
wmts = WMTSTileSource(url='https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg')
tiles = gv.WMTS(wmts)
tiles * taxi_trips | _____no_output_____ | BSD-3-Clause | notebooks/01-workflow-introduction.ipynb | kasiarachuta-zz/jupytercon2017-holoviews-tutorial |
We could add lots more visual elements (laying out additional plots left and right, overlaying annotations, etc.), but let's say that this is our basic visualization we'll want to share. To sum up what we've done so far, here are the complete 11 lines of code required to generate this geo-located interactive plot of mi... | class NYCTaxiExplorer(hv.streams.Stream):
alpha = param.Magnitude(default=0.75, doc="Alpha value for the map opacity")
plot = param.ObjectSelector(default="pickup", objects=["pickup","dropoff"])
colormap = param.ObjectSelector(default=cm["fire"], objects=cm.values())
passengers = param.... | _____no_output_____ | BSD-3-Clause | notebooks/01-workflow-introduction.ipynb | kasiarachuta-zz/jupytercon2017-holoviews-tutorial |
Each Parameter is a normal Python attribute, but with special checks and functions run automatically when getting or setting.Parameters capture your goals and your knowledge about your domain, declaratively. Class level parameters | NYCTaxiExplorer.alpha
NYCTaxiExplorer.alpha = 0.5
NYCTaxiExplorer.alpha | _____no_output_____ | BSD-3-Clause | notebooks/01-workflow-introduction.ipynb | kasiarachuta-zz/jupytercon2017-holoviews-tutorial |
Validation | try:
NYCTaxiExplorer.alpha = '0'
except Exception as e:
print(e) | _____no_output_____ | BSD-3-Clause | notebooks/01-workflow-introduction.ipynb | kasiarachuta-zz/jupytercon2017-holoviews-tutorial |
Instance parameters | explorer = NYCTaxiExplorer(alpha=0.6)
explorer.alpha
NYCTaxiExplorer.alpha | _____no_output_____ | BSD-3-Clause | notebooks/01-workflow-introduction.ipynb | kasiarachuta-zz/jupytercon2017-holoviews-tutorial |
Step 4: Get a widget-based UI for free* Parameters are purely declarative and independent of any widget toolkit, but contain all the information needed to build interactive widgets* ParamNB generates UIs in Jupyter from Parameters, using ipywidgets | paramnb.Widgets(NYCTaxiExplorer)
NYCTaxiExplorer.passengers | _____no_output_____ | BSD-3-Clause | notebooks/01-workflow-introduction.ipynb | kasiarachuta-zz/jupytercon2017-holoviews-tutorial |
* ipywidgets work with Jupyter Dashboards Server for deployment * Declaration of parameters is independent of the UI library used* ParamBokeh generates UIs from the same Parameters, using Bokeh widgets, either in Jupyter or in Bokeh Server | parambokeh.Widgets(NYCTaxiExplorer) | _____no_output_____ | BSD-3-Clause | notebooks/01-workflow-introduction.ipynb | kasiarachuta-zz/jupytercon2017-holoviews-tutorial |
Step 5: Link your domain model to your visualizationWe've now defined the space that's available for exploration, and the next step is to link up the parameter space with the code that specifies the plot: | class NYCTaxiExplorer(hv.streams.Stream):
alpha = param.Magnitude(default=0.75, doc="Alpha value for the map opacity")
colormap = param.ObjectSelector(default=cm["fire"], objects=cm.values())
plot = param.ObjectSelector(default="pickup", objects=["pickup","dropoff"])
passengers = para... | _____no_output_____ | BSD-3-Clause | notebooks/01-workflow-introduction.ipynb | kasiarachuta-zz/jupytercon2017-holoviews-tutorial |
Note that the `NYCTaxiExplorer` class is entirely declarative (no widgets), and can be used "by hand" to provide range-checked and type-checked plotting for values from the declared parameter space: | explorer = NYCTaxiExplorer(alpha=0.2, plot="dropoff")
explorer.make_view() | _____no_output_____ | BSD-3-Clause | notebooks/01-workflow-introduction.ipynb | kasiarachuta-zz/jupytercon2017-holoviews-tutorial |
Step 6: Widgets now control your interactive plotsBut in practice, why not pop up the widgets to make it fully interactive? | explorer = NYCTaxiExplorer()
paramnb.Widgets(explorer, callback=explorer.event)
hv.DynamicMap(explorer.make_view, streams=[explorer, RangeXY()])
explorer = NYCTaxiExplorer()
parambokeh.Widgets(explorer, callback=explorer.event)
hv.DynamicMap(explorer.make_view, streams=[explorer, RangeXY()]) | _____no_output_____ | BSD-3-Clause | notebooks/01-workflow-introduction.ipynb | kasiarachuta-zz/jupytercon2017-holoviews-tutorial |
Newbie BotScrape subreddits and use NLP to answer frequently asked questions. | import sys
import os
import numpy as np
import pandas as pd
import joblib
from joblib import dump, load
packages = [joblib, np, pandas]
print(f'python: {sys.version.spl}')
for package in packages:
print(f'{package.__name__}: {package.__version__}') | _____no_output_____ | MIT | Newbie Bot.ipynb | andrewmaurer/newbie-bot |
SKLearn Spacy Reddit Text Classification ExampleIn this example we will be buiding a text classifier using the reddit content moderation dataset.For this, we will be using SpaCy for the word tokenization and lemmatization. The classification will be done with a Logistic Regression binary classifier.The steps in this t... | # Let's first install any dependencies
!pip install -r requirements.txt
import pandas as pd
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from seldon_core.seldon_client import Seldo... | _____no_output_____ | Apache-2.0 | examples/models/sklearn_spacy_text/sklearn_spacy_text_classifier_example.ipynb | markusgay/seldon-core |
2) Build your containerized model | # This is the class we will use to deploy
!cat RedditClassifier.py
# test that our model works
from RedditClassifier import RedditClassifier
# With one sample
sample = x_test[0:1]
print(sample)
print(RedditClassifier().predict(sample, ["feature_name"])) | ['This is the study that the article is based on:\r\n\r\nhttps://www.nature.com/articles/nature25778.epdf']
[[0.82767095 0.17232905]]
| Apache-2.0 | examples/models/sklearn_spacy_text/sklearn_spacy_text_classifier_example.ipynb | markusgay/seldon-core |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.