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 |
|---|---|---|---|---|---|
Creating a Function to Test for Stationarity | def test_stationarity(timeseries):
rolmean = pd.Series(timeseries).rolling(12).mean()
rolstd = pd.Series(timeseries).rolling(12).mean()
fig = plt.figure(figsize = (12, 8))
orig = plt.plot(timeseries, color = 'blue', label = 'Original')
mean = plt.plot(rolmean, color = 'red', label = 'Rolling Average... | _____no_output_____ | MIT | MSFT Time Series Analysis.ipynb | maxrzhang/Microsoft-Stock-Time-Series-Analysis |
Now let us examine the stock price's Autocorrelation and Partial Autocorrelation plots | fig = plt.figure(figsize = (12, 8))
ax1 = fig.add_subplot(211)
fig = sm.graphics.tsa.plot_acf(stock.Price, lags = 200, ax = ax1)
ax2 = fig.add_subplot(212)
fig = sm.graphics.tsa.plot_pacf(stock.Price, lags = 200, ax = ax2)
plt.show() | _____no_output_____ | MIT | MSFT Time Series Analysis.ipynb | maxrzhang/Microsoft-Stock-Time-Series-Analysis |
We can see that the Autocorrelation of the Microsoft stock prices is weak, perhaps suggesting that the autocorrelation is not statistically significant within the 95% confidence interval. Observing the Partial Autocorrelation graph, however, while we also do not see clear significant indication of partial autocorrelati... | optimal = auto_arima(stock.Price, start_p = 0, start_q = 0, test = 'adf', seasonal = True)
optimal.summary()
model = sm.tsa.statespace.SARIMAX(stock.Price, trend = 'n', order = (3, 1, 0))
results = model.fit()
results.summary()
stock['Forecast'] = results.predict(dynamic = False)
stock[['Price', 'Forecast']].plot(figsi... | _____no_output_____ | MIT | MSFT Time Series Analysis.ipynb | maxrzhang/Microsoft-Stock-Time-Series-Analysis |
The above function simulates trading using our SARIMAX predictions, and we assume a $5 transaction fee. | stock['Target'] = stock.Price.shift(-1)
stock.tail()
stock['Forecast'] = results.predict(dynamic = False)
stock['Predicted Growth'] = stock[['Forecast', 'Price']].apply(lambda x: 1 if x[0] - x[1] >= 0 else 0, axis = 1)
stock['Actual Growth'] = stock[['Target', 'Price']].apply(lambda x: 1 if x[0] - x[1] >= 0 else 0, axi... | _____no_output_____ | MIT | MSFT Time Series Analysis.ipynb | maxrzhang/Microsoft-Stock-Time-Series-Analysis |
Building the ARMA Model | model = ARMA(stock.Price, (3, 1)).fit()
model.summary()
stock['Forecast'] = model.predict()
stock['Target'] = stock.Price.shift(-1)
stock.head()
plt.scatter(stock.iloc[1: -1].Target, stock.iloc[1: -1].Forecast)
plt.xlabel('True Values')
plt.ylabel('Predictions')
print('Score: ', metrics.r2_score(stock.iloc[1: -1].Targe... | /Users/maxzhang/opt/anaconda3/lib/python3.7/site-packages/statsmodels/tsa/base/tsa_model.py:218: ValueWarning: A date index has been provided, but it has no associated frequency information and so will be ignored when e.g. forecasting.
' ignored when e.g. forecasting.', ValueWarning)
/Users/maxzhang/opt/anaconda3/lib... | MIT | MSFT Time Series Analysis.ipynb | maxrzhang/Microsoft-Stock-Time-Series-Analysis |
The visualization used for this homework is based on Alexandr Verinov's code. Generative models In this homework we will try several criterions for learning an implicit model. Almost everything is written for you, and you only need to implement the objective for the game and play around with the model. **0)** Read t... | """
Please, implement everything in one notebook, using if statements to switch between the tasks
"""
TASK = 1 # 2, 3, 4, 5 | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | Tobichimaru/Practical_DL |
Imports | import numpy as np
import time
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(12345)
lims=(-5, 5) | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | Tobichimaru/Practical_DL |
Define sampler from real data and Z | from scipy.stats import rv_discrete
MEANS = np.array(
[[-1,-3],
[1,3],
[-2,0],
])
COVS = np.array(
[[[1,0.8],[0.8,1]],
[[1,-0.5],[-0.5,1]],
[[1,0],[0,1]],
])
PROBS = np.array([
0.2,
0.5,
0.3
])
assert len(MEANS) == len(CO... | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | Tobichimaru/Practical_DL |
Visualization functions | def vis_data(data):
"""
Visualizes data as histogram
"""
hist = np.histogram2d(data[:, 1], data[:, 0], bins=100, range=[lims, lims])
plt.pcolormesh(hist[1], hist[2], hist[0], alpha=0.5)
fixed_noise = sample_noise(1000)
def vis_g():
"""
Visualizes generator's samples as circles
"... | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | Tobichimaru/Practical_DL |
Define architectures After you've passed task 1 you can play with architectures. Generator | class Generator(nn.Module):
def __init__(self, noise_dim, out_dim, hidden_dim=100):
super(Generator, self).__init__()
self.fc1 = nn.Linear(noise_dim, hidden_dim)
nn.init.xavier_normal(self.fc1.weight)
nn.init.constant(self.fc1.bias, 0.0)
self.fc2 = nn.Linear... | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | Tobichimaru/Practical_DL |
Discriminator | class Discriminator(nn.Module):
def __init__(self, in_dim, hidden_dim=100):
super(Discriminator, self).__init__()
self.fc1 = nn.Linear(in_dim, hidden_dim)
nn.init.xavier_normal(self.fc1.weight)
nn.init.constant(self.fc1.bias, 0.0)
self.fc2 = nn.Linear(hidden... | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | Tobichimaru/Practical_DL |
Define updates and losses | generator = Generator(NOISE_DIM, out_dim = 2)
discriminator = Discriminator(in_dim = 2)
lr = 0.001
g_optimizer = optim.Adam(generator.parameters(), lr=lr, betas=(0.5, 0.999))
d_optimizer = optim.Adam(discriminator.parameters(), lr=lr, betas=(0.5, 0.999)) | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | Tobichimaru/Practical_DL |
Notice we are using ADAM optimizer with `beta1=0.5` for both discriminator and discriminator. This is a common practice and works well. Motivation: models should be flexible and adapt itself rapidly to the distributions. You can try different optimizers and parameters. | ################################
# IMPLEMENT HERE
# Define the g_loss and d_loss here
# these are the only lines of code you need to change to implement GAN game
def g_loss():
# if TASK == 1:
# do something
return # TODO
def d_loss():
# if TASK == 1:
# do something
return # TODO... | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | Tobichimaru/Practical_DL |
Get real data | data = sample_true(100000)
def iterate_minibatches(X, batchsize, y=None):
perm = np.random.permutation(X.shape[0])
for start in range(0, X.shape[0], batchsize):
end = min(start + batchsize, X.shape[0])
if y is None:
yield X[perm[start:end]]
else:
yield X[perm... | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | Tobichimaru/Practical_DL |
**Legend**:- Blue dots are generated samples. - Colored histogram at the back shows density of real data. - And with arrows we show gradients of the discriminator -- they are the directions that discriminator pushes generator's samples. Train the model | from IPython import display
plt.xlim(lims)
plt.ylim(lims)
num_epochs = 100
batch_size = 64
# ===========================
# IMPORTANT PARAMETER:
# Number of D updates per G update
# ===========================
k_d, k_g = 4, 1
accs = []
try:
for epoch in range(num_epochs):
for input_data in iterate_minib... | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | Tobichimaru/Practical_DL |
BYÖYO 2018Yapay Öğrenmeye Giriş IAli Taylan Cemgil2 Temmuz 2018 Parametrik Regresyon, Parametrik Fonksyon Oturtma Problemi (Parametric Regression, Function Fitting)Verilen girdi ve çıktı ikilileri $x, y$ için parametrik bir fonksyon $f$ oturtma problemi. Parametre $w$ değerlerini öyle bir seçelim ki $$y \approx f(x; w... | import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
from __future__ import print_function
from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets
import matplotlib.pylab as plt
from IPython.display import clear_output, display, HTML
x = np.array([8.0 , 6.1 , 11., 7., 9., ... | _____no_output_____ | MIT | byoyo2018-giris-1.ipynb | ardakdemir/notes |
Gerçek veri: Türkiyedeki araç sayıları | %matplotlib inline
import scipy as sc
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pylab as plt
df_arac = pd.read_csv(u'data/arac.csv',sep=';')
df_arac[['Year','Car']]
#df_arac
BaseYear = 1995
x = np.matrix(df_arac.Year[0:]).T-BaseYear
y = np.matrix(df_arac.Car[0:]).T/1000000.
pl... | _____no_output_____ | MIT | byoyo2018-giris-1.ipynb | ardakdemir/notes |
Örnek 1, devam: Modeli Öğrenmek* Öğrenmek: parametre kestirimi $w = [w_0, w_1]$* Genelde model veriyi hatasız açıklayamayacağı için her veri noktası için bir hata tanımlıyoruz:$$e_i = y_i - f(x_i; w)$$* Toplam kare hata $$E(w) = \frac{1}{2} \sum_i (y_i - f(x_i; w))^2 = \frac{1}{2} \sum_i e_i^2$$* Toplam kare hatayı $w... | from itertools import product
BaseYear = 1995
x = np.matrix(df_arac.Year[0:]).T-BaseYear
y = np.matrix(df_arac.Car[0:]).T/1000000.
# Setup the vandermonde matrix
N = len(x)
A = np.hstack((np.ones((N,1)), x))
left = -5
right = 15
bottom = -4
top = 6
step = 0.05
W0 = np.arange(left,right, step)
W1 = np.arange(bottom,t... | _____no_output_____ | MIT | byoyo2018-giris-1.ipynb | ardakdemir/notes |
Modeli Nasıl Kestirebiliriz? Fikir: En küçük kare hata (Gauss 1795, Legendre 1805)* Toplam hatanın $w_0$ ve $w_1$'e göre türevini hesapla, sıfıra eşitle ve çıkan denklemleri çöz\begin{eqnarray}\left(\begin{array}{c}y_0 \\ y_1 \\ \vdots \\ y_{N-1} \end{array}\right)\approx\left(\begin{array}{cc}1 & x_0 \\ 1 & x_1 \\ \v... | # Solving the Normal Equations
# Setup the Design matrix
N = len(x)
A = np.hstack((np.ones((N,1)), x))
#plt.imshow(A, interpolation='nearest')
# Solve the least squares problem
w_ls,E,rank,sigma = np.linalg.lstsq(A, y)
print('Parametreler: \nw0 = ', w_ls[0],'\nw1 = ', w_ls[1] )
print('Toplam Kare Hata:', E/2)
f = n... | Parametreler:
w0 = [[ 4.13258253]]
w1 = [[ 0.20987778]]
Toplam Kare Hata: [[ 37.19722385]]
| MIT | byoyo2018-giris-1.ipynb | ardakdemir/notes |
Polinomlar Parabol\begin{eqnarray}\left(\begin{array}{c}y_0 \\ y_1 \\ \vdots \\ y_{N-1} \end{array}\right)\approx\left(\begin{array}{ccc}1 & x_0 & x_0^2 \\ 1 & x_1 & x_1^2 \\ \vdots \\ 1 & x_{N-1} & x_{N-1}^2 \end{array}\right) \left(\begin{array}{c} w_0 \\ w_1 \\ w_2\end{array}\right)\end{eqnarray} $K$ derecesind... | x = np.array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5])
N = len(x)
x = x.reshape((N,1))
y = np.array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]).reshape((N,1))
#y = np.array([9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74]).reshape((N,1))
#y = np.array([7.46, 6.77, 12.74, 7.11, 7... | _____no_output_____ | MIT | byoyo2018-giris-1.ipynb | ardakdemir/notes |
get data set by id | saved_id = 'b3d66173-5608-41b4-b4d4-4b7bd188a2ee'
Dataset.get_by_id(workspace=ws, id=saved_id) | _____no_output_____ | MIT | batch/xx_misc.ipynb | mutazag/cv |
enumerate datastores and datasets | print('>>>>> datastores')
for i,ds in enumerate(ws.datastores):
print(i, ds)
print('>>>>> datasets using datasets collection')
for i, dataset in enumerate(ws.datasets):
print(i, dataset)
print('>>>>> datasets using get_all')
for i, dataset in enumerate(Dataset.get_all(workspace=ws)):
print(i, dataset)... | _____no_output_____ | MIT | batch/xx_misc.ipynb | mutazag/cv |
pipelines | exp = Experiment(workspace=ws, name='MAG-batch-paramdataset')
exp.runs | _____no_output_____ | MIT | batch/xx_misc.ipynb | mutazag/cv |
!pip install -Uqq fastbook --quiet
!pip install pyfolio --quiet
import fastbook
import os
import re
import random
import numpy as np
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
import pandas as pd
from pyl... | _____no_output_____ | MIT | lgb__model_training.ipynb | African-Quant/WQU_MScFE_Capstone_Grp9 | |
Using *Light Gradient Boosting* method to Predict Market Direction. | lgb_results_valid, lgb_results_test = lgb_results()
lgb_results_valid
lgb_results_test | _____no_output_____ | MIT | lgb__model_training.ipynb | African-Quant/WQU_MScFE_Capstone_Grp9 |
Introduction to the Pipelines SDK The [Kubeflow Pipelines SDK](https://github.com/kubeflow/pipelines/tree/master/sdk) provides a set of Python packages that you can use to specify and run your machine learning (ML) workflows. A pipeline is a description of an ML workflow, including all of the components that make up t... | !pip install kfp --upgrade --user | _____no_output_____ | Apache-2.0 | notebooks/05_Kubeflow_Pipeline/05_01_Pipeline_SDK.ipynb | PatrickXYS/eks-kubeflow-workshop |
After successful installation, the command `dsl-compile` should be available. You can use this command to verify it | !which dsl-compile | _____no_output_____ | Apache-2.0 | notebooks/05_Kubeflow_Pipeline/05_01_Pipeline_SDK.ipynb | PatrickXYS/eks-kubeflow-workshop |
> Note: Please check official documentation to understand Pipline concetps before your move forward. [Introduction to Pipelines SDK](https://www.kubeflow.org/docs/pipelines/sdk/sdk-overview/) Build simple components and pipelines In this example, we want to calculate sum of three numbers. 1. Let's assume we have a p... | import kfp
from kfp import dsl
def add_two_numbers(a, b):
return dsl.ContainerOp(
name='calculate_sum',
image='python:3.6.8',
command=['python', '-c'],
arguments=['with open("/tmp/results.txt", "a") as file: file.write(str({} + {}))'.format(a, b)],
file_outputs={
... | _____no_output_____ | Apache-2.0 | notebooks/05_Kubeflow_Pipeline/05_01_Pipeline_SDK.ipynb | PatrickXYS/eks-kubeflow-workshop |
3. Define your pipeline as a Python functionDescribe each pipeline as a Python function. | @dsl.pipeline(
name='Calcualte sum pipeline',
description='Calculate sum of numbers and prints the result.'
)
def calculate_sum(
a=7,
b=10,
c=4,
d=7
):
"""A four-step pipeline with first two running in parallel."""
sum1 = add_two_numbers(a, b)
sum2 = add_two_numbers(c, d)
sum = add_... | _____no_output_____ | Apache-2.0 | notebooks/05_Kubeflow_Pipeline/05_01_Pipeline_SDK.ipynb | PatrickXYS/eks-kubeflow-workshop |
4. Compile the pipelineCompile the pipeline to generate a compressed YAML definition of the pipeline. The Kubeflow Pipelines service converts the static configuration into a set of Kubernetes resources for execution.There are two ways to compile the pipeline. Either use python lib `kfp.compiler.Compiler.compile ` or u... | kfp.compiler.Compiler().compile(calculate_sum, 'calculate-sum-pipeline.zip')
# If you have a python file, you can also try build pipeline using `dsl-compile` command.
# dsl-compile --py [path/to/python/file] --output my-pipeline.zip | _____no_output_____ | Apache-2.0 | notebooks/05_Kubeflow_Pipeline/05_01_Pipeline_SDK.ipynb | PatrickXYS/eks-kubeflow-workshop |
5. Deploy pipelineThere're two ways to deploy the pipeline. Either upload the generate `.tar.gz` file through the `Kubeflow Pipelines UI`, or use `Kubeflow Pipeline SDK` to deploy it.We will only show sdk usage here. | client = kfp.Client()
aws_experiment = client.create_experiment(name='aws')
my_run = client.run_pipeline(aws_experiment.id, 'calculate-sum-pipeline',
'calculate-sum-pipeline.zip') | _____no_output_____ | Apache-2.0 | notebooks/05_Kubeflow_Pipeline/05_01_Pipeline_SDK.ipynb | PatrickXYS/eks-kubeflow-workshop |
Table of Contents1 Load Data2 Compare dimensionalities3 Find "single-gene" iModulons4 Plot Components | from pymodulon.core import IcaData
import os
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
import numpy as np
from tqdm.notebook import tqdm
# Directory containing ICA outputs
DATA_DIR = '../data/interim/ica_runs' | _____no_output_____ | MIT | notebooks/4_ica_dimensionality.ipynb | SBRG/modulome_ppu |
Load Data | def load_M(dim):
return pd.read_csv(os.path.join(DATA_DIR,str(dim),'S.csv'),index_col=0)
def load_A(dim):
return pd.read_csv(os.path.join(DATA_DIR,str(dim),'A.csv'),index_col=0)
dims = sorted([int(x) for x in os.listdir(DATA_DIR)])
M_data = [load_M(dim) for dim in dims]
A_data = [load_A(dim) for dim in dims]
n... | _____no_output_____ | MIT | notebooks/4_ica_dimensionality.ipynb | SBRG/modulome_ppu |
Compare dimensionalities | final_m = M_data[-1]
thresh = 0.7
n_final_mods = []
for m in tqdm(M_data):
corrs = pd.DataFrame(index=final_m.columns,columns=m.columns)
for col1 in final_m.columns:
for col2 in m.columns:
corrs.loc[col1,col2] = abs(stats.pearsonr(final_m[col1],m[col2])[0])
n_final_mods.append(len(np.wh... | _____no_output_____ | MIT | notebooks/4_ica_dimensionality.ipynb | SBRG/modulome_ppu |
Find "single-gene" iModulonsAt a high enough dimensionality, some iModulons track the expression trajectory of a single iModulon | n_single_genes = []
for m in tqdm(M_data):
counter = 0
for col in m.columns:
sorted_genes = abs(m[col]).sort_values(ascending=False)
if sorted_genes.iloc[0] > 2 * sorted_genes.iloc[1]:
counter += 1
n_single_genes.append(counter) | _____no_output_____ | MIT | notebooks/4_ica_dimensionality.ipynb | SBRG/modulome_ppu |
Plot Components | non_single_components = np.array(n_components) - np.array(n_single_genes)
DF_stats = pd.DataFrame([n_components,n_final_mods,non_single_components,n_single_genes],
index=['Robust Components','Final Components','Multi-gene Components',
'Single Gene Components'],
... | _____no_output_____ | MIT | notebooks/4_ica_dimensionality.ipynb | SBRG/modulome_ppu |
Exercise 1.04: Continuing Verification of Data Integrity | import pandas as pd
df = pd.read_excel(
'../../Data/default_of_credit_card_clients__courseware_version_1_21_19.xls')
id_counts = df['ID'].value_counts()
id_counts.head()
dupe_mask = id_counts == 2
dupe_mask[0:5]
id_counts.index[0:5]
dupe_ids = id_counts.index[dupe_mask]
dupe_ids = list(dupe_ids)
len(dupe_ids)
dupe_... | _____no_output_____ | MIT | Chapter01/Exercise04/Exercise04.ipynb | MaheshPackt/Data-Science-Projects-2nd |
We can see some duplicates here, and it looks like every duplicate ID has one row with data, and another row with all zeros. Is this the case for every duplicate ID? Let's check. | df.shape
df_zero_mask = df == 0
feature_zero_mask = df_zero_mask.iloc[:,1:].all(axis=1)
sum(feature_zero_mask) | _____no_output_____ | MIT | Chapter01/Exercise04/Exercise04.ipynb | MaheshPackt/Data-Science-Projects-2nd |
It looks like there are at least as many "zero rows" as there are duplicate IDs. Let's remove all the rows with all zero features and response, and see if that gets rid of the duplicate IDs. | df_clean_1 = df.loc[~feature_zero_mask,:].copy()
df_clean_1.shape
df_clean_1['ID'].nunique() | _____no_output_____ | MIT | Chapter01/Exercise04/Exercise04.ipynb | MaheshPackt/Data-Science-Projects-2nd |
Looks like this worked. Save progress for next exercise. | df_clean_1.to_csv('../../Data/df_clean_1.csv', index=False) | _____no_output_____ | MIT | Chapter01/Exercise04/Exercise04.ipynb | MaheshPackt/Data-Science-Projects-2nd |
Image ClassificationThe *Computer Vision* cognitive service provides useful pre-built models for working with images, but you'll often need to train your own model for computer vision. For example, suppose the Northwind Traders retail company wants to create an automated checkout system that identifies the grocery ite... | project_id = 'YOUR_PROJECT_ID'
cv_key = 'YOUR_KEY'
cv_endpoint = 'YOUR_ENDPOINT'
model_name = 'groceries' # this must match the model name you set when publishing your model iteration (it's case-sensitive)!
print('Ready to predict using model {} in project {}'.format(model_name, project_id)) | _____no_output_____ | MIT | 01b - Image Classification.ipynb | jonnalakarthik/ai-fundamentals |
Client applications can use the details above to connect to and your custom vision classification model.Run the following code cell to classifiy a selection of test images using your published model.> **Note**: Don't worry too much about the details of the code. It uses the Computer Vision SDK for Python to get a class... | from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient
import matplotlib.pyplot as plt
from PIL import Image
import os
%matplotlib inline
# Get the test images from the data/vision/test folder
test_folder = os.path.join('data', 'image-classification', 'test-fruit')
test_images ... | _____no_output_____ | MIT | 01b - Image Classification.ipynb | jonnalakarthik/ai-fundamentals |
Deploy a simple S3 dispersed storage archive solution RequirementsIn order to be able to deploy this example deployment you will have to have the following components activated- the 3Bot SDK, in the form of a local container with the SDK, or a grid based SDK container. Getting started instuctions are [here](https://gi... | from Jumpscale import j
import time
j.clients.explorer.default_addr_set('explorer.grid.tf')
# Which identities are available in you SDK
j.tools.threebot.me
# Make sure I have an identity (set default one for mainnet of testnet)
me = j.tools.threebot.me.default
# Load the zero-os sal and reate empty reservation meth... | _____no_output_____ | Apache-2.0 | jupyter_notebooks/s3_server/s3_storage.ipynb | threefoldfoundation/info_gridmanual |
Setup your overlay network (skip this step if you have a network setup and available)An overlay network creates a private peer2peer network over selected nodes. In this notebook it is assumend you have created one by following this [notebook](https://github.com/Threefoldfoundation/info_projectX/blob/development/code/j... | # load the zero-os sal
zos = j.sal.zosv2
day=24*60*60
hour=60*60
# Node: 5 ID: 9kcLeTuseybGHGWw2YXvdu4kk2jZzyZCaCHV9t6Axqqx IPv4 address: 172.20.15.0/24
minio_node_id = '9kcLeTuseybGHGWw2YXvdu4kk2jZzyZCaCHV9t6Axqqx'
minio_node_ip = '172.20.15.16'
# ---------------------------------------------------------------------... | _____no_output_____ | Apache-2.0 | jupyter_notebooks/s3_server/s3_storage.ipynb | threefoldfoundation/info_gridmanual |
Prepare and deploy the S3 software containerThe nodes that will run the storage solution needs some persistent storage. This will create a reservation for a volume on the same node as the software runs and attached this as a volume to the container that will run the storage software. For the reservation duration pleas... | # Storage solution reservation time
nr_of_hours=24
# ----------------------------------------------------------------------------------
# Attach persistant storage to container - for storing metadata
# ----------------------------------------------------------------------------------
volume = zos.volume.create(reserv... | _____no_output_____ | Apache-2.0 | jupyter_notebooks/s3_server/s3_storage.ipynb | threefoldfoundation/info_gridmanual |
With the low level zero-DB reservations done and stored the `results` variable (these storage managers will get an IPv4 address assigned from the local `/24` node network. We need to store those addresses in `namespace_config` to pass it to the container running the storage software. | # ----------------------------------------------------------------------------------
# Read the IP address of the 0-DB namespaces after they are deployed
# we will need these IPs when creating the minio container
# ----------------------------------------------------------------------------------
namespace_config = []
... | _____no_output_____ | Apache-2.0 | jupyter_notebooks/s3_server/s3_storage.ipynb | threefoldfoundation/info_gridmanual |
```['9012-4:supersecret@[2a04:7700:1003:1:54f0:edff:fe87:2c48]:9900', '9012-1:supersecret@[2a02:16a8:1000:0:5c2f:ddff:fe5a:1a70]:9900', '9012-2:supersecret@[2a02:16a8:1000:0:1083:59ff:fe38:ce71]:9900', '9012-7:supersecret@[2003:d6:2f32:8500:dc78:d6ff:fe04:7368]:9900', '9012-3:supersecret@[2a02:16a8:1000:0:fc7c:4aff:fec... | # ----------------------------------------------------------------------------------
# With the low level disk managers done and the IP adresses discovered we could now build
# the reservation for the min.io S3 interface.
# ----------------------------------------------------------------------------------
reservation_m... | _____no_output_____ | Apache-2.0 | jupyter_notebooks/s3_server/s3_storage.ipynb | threefoldfoundation/info_gridmanual |
With the definition of the S3 container done we now need to attached persistent storage on a volume to store metadata. | # ----------------------------------------------------------------------------------
# Attach persistant storage to container - for storing metadata
# ----------------------------------------------------------------------------------
zos.volume.attach_existing(
container=minio_container,
volume_id=f'{volume_rid}-{... | _____no_output_____ | Apache-2.0 | jupyter_notebooks/s3_server/s3_storage.ipynb | threefoldfoundation/info_gridmanual |
Last but not least, execute the resevation for the storage manager. | # ----------------------------------------------------------------------------------
# Write reservation for min.io container in BCDB - end user interface
# ----------------------------------------------------------------------------------
expiration = j.data.time.epoch + (nr_of_hours*hour)
# register the reservatio... | _____no_output_____ | Apache-2.0 | jupyter_notebooks/s3_server/s3_storage.ipynb | threefoldfoundation/info_gridmanual |
pedestrian detector https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html | pip install git+https://github.com/gautamchitnis/cocoapi.git@cocodataset-master#subdirectory=PythonAPI
from google.colab import drive
drive.mount('/content/drive')
import zipfile
with zipfile.ZipFile("/content/drive/MyDrive/PennFudanPed.zip", 'r') as zip_ref:
zip_ref.extractall()
import sys
sys.path.insert(1, '/con... | _____no_output_____ | Apache-2.0 | _notebooks/2021-05-09-Pedestrian_detector.ipynb | anders447/sample-ds-blog-anders |
Fitting and predicting | ndim = 3
fit_intercept = True
ndata = 100
p_true = [2, 0, -2, 0]
np.random.seed(42)
X = np.random.uniform(low=-1, high=1, size=ndim*ndata).reshape(ndata, ndim)
p = scipy.stats.logistic.cdf(np.dot(np.concatenate((X, np.ones((X.shape[0],1), dtype=float)), axis=1), p_true))
y = (p > np.random.uniform(size=ndata)).astype(... | _____no_output_____ | MIT | notebooks/example.ipynb | faab5/errortools |
Create report (2 ways) | features = ['x1', 'x2', 'x3', 'bias']
with PdfPages('Report.pdf') as pdf:
errortools.errortools.report_correlation_matrix(model, features, pdf)
errortools.errortools.report_parameter_error(model, features, pdf)
errortools.errortools.report_loss_versus_approximation(model, X, y, 0, 0, features, pdf)
erro... | _____no_output_____ | MIT | notebooks/example.ipynb | faab5/errortools |
Probabilistic Variables | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from volumetricspy import ProbVar, MonteCarlo | _____no_output_____ | MIT | docs/examples/2-Montecarlo/1-ProbVar.ipynb | scuervo91/volumetricspy |
Constant Values | x = ProbVar(name='test1',constant=5.)
x.get_sample()
y = ProbVar(
name = 'test',
dist = 'lognorm',
kw = {'s':0.42, 'scale':500})
sns.histplot(y.get_sample(size=100))
def ooip(a,h,bo,phi,sw):
return 7758*a*h*phi*(1-sw)*(1/bo)*(1/1000000)
a = ProbVar(name = 'area',dist='norm',kw={'loc':1000,'scale':200}... | _____no_output_____ | MIT | docs/examples/2-Montecarlo/1-ProbVar.ipynb | scuervo91/volumetricspy |
Predicting Boston Housing Prices Updating a model using SageMaker_Deep Learning Nanodegree Program | Deployment_---In this notebook, we will continue working with the [Boston Housing Dataset](https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html). Our goal in this notebook will be to train two different mode... | %matplotlib inline
import os
import numpy as np
import pandas as pd
from pprint import pprint
import matplotlib.pyplot as plt
from time import gmtime, strftime
from sklearn.datasets import load_boston
import sklearn.model_selection | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
In addition to the modules above, we need to import the various bits of SageMaker that we will be using. | import sagemaker
from sagemaker import get_execution_role
from sagemaker.amazon.amazon_estimator import get_image_uri
from sagemaker.predictor import csv_serializer
# This is an object that represents the SageMaker session that we are currently operating in. This
# object contains some useful information that we will ... | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Step 1: Downloading the dataFortunately, this dataset can be retrieved using sklearn and so this step is relatively straightforward. | boston = load_boston() | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Step 2: Preparing and splitting the dataGiven that this is clean tabular data, we don't need to do any processing. However, we do need to split the rows in the dataset up into train, test and validation sets. | # First we package up the input data and the target variable (the median value) as pandas dataframes. This
# will make saving the data to a file a little easier later on.
X_bos_pd = pd.DataFrame(boston.data, columns=boston.feature_names)
Y_bos_pd = pd.DataFrame(boston.target)
# We split the dataset into 2/3 training ... | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Step 3: Uploading the training and validation files to S3When a training job is constructed using SageMaker, a container is executed which performs the training operation. This container is given access to data that is stored in S3. This means that we need to upload the data we want to use for training to S3. We can u... | # This is our local data directory. We need to make sure that it exists.
data_dir = '../data/boston'
if not os.path.exists(data_dir):
os.makedirs(data_dir)
# We use pandas to save our train and validation data to csv files. Note that we make sure not to include header
# information or an index as this is required b... | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Upload to S3Since we are currently running inside of a SageMaker session, we can use the object which represents this session to upload our data to the 'default' S3 bucket. Note that it is good practice to provide a custom prefix (essentially an S3 folder) to make sure that you don't accidentally interfere with data u... | prefix = 'boston-update-endpoints'
val_location = session.upload_data(os.path.join(data_dir, 'validation.csv'), key_prefix=prefix)
train_location = session.upload_data(os.path.join(data_dir, 'train.csv'), key_prefix=prefix) | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Step 4 (A): Train the XGBoost modelNow that we have the training and validation data uploaded to S3, we can construct our XGBoost model and train it. We will be making use of the high level SageMaker API to do this which will make the resulting code a little easier to read at the cost of some flexibility.To construct ... | # As stated above, we use this utility method to construct the image name for the training container.
xgb_container = get_image_uri(session.boto_region_name, 'xgboost')
# Now that we know which container to use, we can construct the estimator object.
xgb = sagemaker.estimator.Estimator(xgb_container, # The name of the... | 'get_image_uri' method will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.
There is a more up to date SageMaker XGBoost image. To use the newer image, please set 'repo_version'='1.0-1'. For example:
get_image_uri(region, 'xgboost', '1.0-1').
Parameter image_name will be renamed to image... | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Before asking SageMaker to begin the training job, we should probably set any model specific hyperparameters. There are quite a few that can be set when using the XGBoost algorithm, below are just a few of them. If you would like to change the hyperparameters below or modify additional ones you can find additional info... | xgb.set_hyperparameters(max_depth=5,
eta=0.2,
gamma=4,
min_child_weight=6,
subsample=0.8,
objective='reg:linear',
early_stopping_rounds=10,
num_round=20... | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Now that we have our estimator object completely set up, it is time to train it. To do this we make sure that SageMaker knows our input data is in csv format and then execute the `fit` method. | # This is a wrapper around the location of our train and validation data, to make sure that SageMaker
# knows our data is in csv format.
s3_input_train = sagemaker.s3_input(s3_data=train_location, content_type='text/csv')
s3_input_validation = sagemaker.s3_input(s3_data=val_location, content_type='text/csv')
xgb.fit({... | 's3_input' class will be renamed to 'TrainingInput' in SageMaker Python SDK v2.
's3_input' class will be renamed to 'TrainingInput' in SageMaker Python SDK v2.
| MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Step 5: Test the trained modelWe will be skipping this step for now. Step 6 (A): Deploy the trained modelEven though we used the high level approach to construct and train the XGBoost model, we will be using the lower level approach to deploy it. One of the reasons for this is so that we have additional control over h... | # Remember that a model needs to have a unique name
xgb_model_name = "boston-update-xgboost-model" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
# We also need to tell SageMaker which container should be used for inference and where it should
# retrieve the model artifacts from. In our case, the xgboost container that we ... | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Create the endpoint configurationOnce we have a model we can start putting together the endpoint. Recall that to do this we need to first create an endpoint configuration, essentially the blueprint that SageMaker will use to build the endpoint itself. | # As before, we need to give our endpoint configuration a name which should be unique
xgb_endpoint_config_name = "boston-update-xgboost-endpoint-config-" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
# And then we ask SageMaker to construct the endpoint configuration
xgb_endpoint_config_info = session.sagemaker_client.cre... | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Deploy the endpointNow that the endpoint configuration has been created, we can ask SageMaker to build our endpoint.**Note:** This is a friendly (repeated) reminder that you are about to deploy an endpoint. Make sure that you shut it down once you've finished with it! | # Again, we need a unique name for our endpoint
endpoint_name = "boston-update-endpoint-" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
# And then we can deploy our endpoint
endpoint_info = session.sagemaker_client.create_endpoint(
EndpointName = endpoint_name,
EndpointConfigName = ... | -------------! | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Step 7 (A): Use the modelNow that our model is trained and deployed we can send some test data to it and evaluate the results. | response = session.sagemaker_runtime_client.invoke_endpoint(
EndpointName = endpoint_name,
ContentType = 'text/csv',
Body = ','.join(map(str, X_test.values[0])))
pprint(respons... | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Shut down the endpointNow that we know that the XGBoost endpoint works, we can shut it down. We will make use of it again later. | session.sagemaker_client.delete_endpoint(EndpointName = endpoint_name) | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Step 4 (B): Train the Linear modelSuppose we are working in an environment where the XGBoost model that we trained earlier is becoming too costly. Perhaps the number of calls to our endpoint has increased and the length of time it takes to perform inference with the XGBoost model is becoming problematic.A possible sol... | # Similar to the XGBoost model, we will use the utility method to construct the image name for the training container.
linear_container = get_image_uri(session.boto_region_name, 'linear-learner')
# Now that we know which container to use, we can construct the estimator object.
linear = sagemaker.estimator.Estimator(li... | 'get_image_uri' method will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.
Parameter image_name will be renamed to image_uri in SageMaker Python SDK v2.
| MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Before asking SageMaker to train our model, we need to set some hyperparameters. In this case we will be using a linear model so the number of hyperparameters we need to set is much fewer. For more details see the [Linear model hyperparameter page](https://docs.aws.amazon.com/sagemaker/latest/dg/ll_hyperparameters.html... | linear.set_hyperparameters(feature_dim=13, # Our data has 13 feature columns
predictor_type='regressor', # We wish to create a regression model
mini_batch_size=200) # Here we set how many samples to look at in each iteration | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Now that the hyperparameters have been set, we can ask SageMaker to fit the linear model to our data. | linear.fit({'train': s3_input_train, 'validation': s3_input_validation}) | 2020-08-05 14:00:32 Starting - Starting the training job...
2020-08-05 14:00:34 Starting - Launching requested ML instances......
2020-08-05 14:01:37 Starting - Preparing the instances for training......
2020-08-05 14:02:40 Downloading - Downloading input data...
2020-08-05 14:03:16 Training - Downloading the training ... | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Step 6 (B): Deploy the trained modelSimilar to the XGBoost model, now that we've fit the model we need to deploy it. Also like the XGBoost model, we will use the lower level approach so that we have more control over the endpoint that gets created. Build the modelOf course, before we can deploy the model, we need to f... | # First, we create a unique model name
linear_model_name = "boston-update-linear-model" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
# We also need to tell SageMaker which container should be used for inference and where it should
# retrieve the model artifacts from. In our case, the linear-learner container that we used... | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Create the endpoint configurationOnce we have the model we can start putting together the endpoint by creating an endpoint configuration. | # As before, we need to give our endpoint configuration a name which should be unique
linear_endpoint_config_name = "boston-linear-endpoint-config-" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
# And then we ask SageMaker to construct the endpoint configuration
linear_endpoint_config_info = session.sagemaker_client.creat... | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Deploy the endpointNow that the endpoint configuration has been created, we can ask SageMaker to build our endpoint.**Note:** This is a friendly (repeated) reminder that you are about to deploy an endpoint. Make sure that you shut it down once you've finished with it! | # Again, we need a unique name for our endpoint
endpoint_name = "boston-update-endpoint-" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
# And then we can deploy our endpoint
endpoint_info = session.sagemaker_client.create_endpoint(
EndpointName = endpoint_name,
EndpointConfigName = ... | ---------------! | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Step 7 (B): Use the modelJust like with the XGBoost model, we will send some data to our endpoint to make sure that it is working properly. An important note is that the output format for the linear model is different from the XGBoost model. | response = session.sagemaker_runtime_client.invoke_endpoint(
EndpointName = endpoint_name,
ContentType = 'text/csv',
Body = ','.join(map(str, X_test.values[0])))
pprint(respons... | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Shut down the endpointNow that we know that the Linear model's endpoint works, we can shut it down. | session.sagemaker_client.delete_endpoint(EndpointName = endpoint_name) | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Step 6 (C): Deploy a combined modelSo far we've constructed two separate models which we could deploy and use. Before we talk about how we can change a deployed endpoint from one configuration to another, let's consider a slightly different situation. Suppose that before we switch from using only the XGBoost model to ... | # As before, we need to give our endpoint configuration a name which should be unique
combined_endpoint_config_name = "boston-combined-endpoint-config-" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
# And then we ask SageMaker to construct the endpoint configuration
combined_endpoint_config_info = session.sagemaker_client... | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Now that we've created the endpoint configuration, we can ask SageMaker to construct the endpoint.**Note:** This is a friendly (repeated) reminder that you are about to deploy an endpoint. Make sure that you shut it down once you've finished with it! | # Again, we need a unique name for our endpoint
endpoint_name = "boston-update-endpoint-" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
# And then we can deploy our endpoint
endpoint_info = session.sagemaker_client.create_endpoint(
EndpointName = endpoint_name,
EndpointConfigName = ... | ---------------! | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Step 7 (C): Use the modelNow that we've constructed an endpoint which sends data to both the XGBoost model and the linear model we can send some data to the endpoint and see what sort of results we get back. | response = session.sagemaker_runtime_client.invoke_endpoint(
EndpointName = endpoint_name,
ContentType = 'text/csv',
Body = ','.join(map(str, X_test.values[0])))
pprint(respons... | {'Body': <botocore.response.StreamingBody object at 0x7ffa3ad9f2b0>,
'ContentType': 'application/json',
'InvokedProductionVariant': 'Linear-Model',
'ResponseMetadata': {'HTTPHeaders': {'content-length': '48',
'content-type': 'application/json',
... | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Since looking at a single response doesn't give us a clear look at what is happening, we can instead take a look at a few different responses to our endpoint | for rec in range(10):
response = session.sagemaker_runtime_client.invoke_endpoint(
EndpointName = endpoint_name,
ContentType = 'text/csv',
Body = ','.join(map(str, X_test.v... | {'Body': <botocore.response.StreamingBody object at 0x7ffa3ad9fb00>,
'ContentType': 'application/json',
'InvokedProductionVariant': 'Linear-Model',
'ResponseMetadata': {'HTTPHeaders': {'content-length': '48',
'content-type': 'application/json',
... | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
If at some point we aren't sure about the properties of a deployed endpoint, we can use the `describe_endpoint` function to get SageMaker to return a description of the deployed endpoint. | pprint(session.sagemaker_client.describe_endpoint(EndpointName=endpoint_name)) | {'CreationTime': datetime.datetime(2020, 8, 5, 14, 33, 48, 662000, tzinfo=tzlocal()),
'EndpointArn': 'arn:aws:sagemaker:eu-west-2:519526115051:endpoint/boston-update-endpoint-2020-08-05-14-33-48',
'EndpointConfigName': 'boston-combined-endpoint-config-2020-08-05-14-33-08',
'EndpointName': 'boston-update-endpoint-202... | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Updating an EndpointNow suppose that we've done our A-B test and the new linear model is working well enough. What we'd like to do now is to switch our endpoint from sending data to both the XGBoost model and the linear model to sending data only to the linear model.Of course, we don't really want to shut down the end... | session.sagemaker_client.update_endpoint(EndpointName=endpoint_name, EndpointConfigName=linear_endpoint_config_name) | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
To get a glimpse at what is going on, we can ask SageMaker to describe our in-use endpoint now, before the update process has completed. When we do so, we can see that the in-use endpoint still has the same characteristics it had before. | pprint(session.sagemaker_client.describe_endpoint(EndpointName=endpoint_name)) | {'CreationTime': datetime.datetime(2020, 8, 5, 14, 33, 48, 662000, tzinfo=tzlocal()),
'EndpointArn': 'arn:aws:sagemaker:eu-west-2:519526115051:endpoint/boston-update-endpoint-2020-08-05-14-33-48',
'EndpointConfigName': 'boston-combined-endpoint-config-2020-08-05-14-33-08',
'EndpointName': 'boston-update-endpoint-202... | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
If we now wait for the update process to complete, and then ask SageMaker to describe the endpoint, it will return the characteristics of the new endpoint configuration. | endpoint_dec = session.wait_for_endpoint(endpoint_name)
pprint(session.sagemaker_client.describe_endpoint(EndpointName=endpoint_name)) | {'CreationTime': datetime.datetime(2020, 8, 5, 14, 33, 48, 662000, tzinfo=tzlocal()),
'EndpointArn': 'arn:aws:sagemaker:eu-west-2:519526115051:endpoint/boston-update-endpoint-2020-08-05-14-33-48',
'EndpointConfigName': 'boston-linear-endpoint-config-2020-08-05-14-06-51',
'EndpointName': 'boston-update-endpoint-2020-... | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Shut down the endpointNow that we've finished, we need to make sure to shut down the endpoint. | session.sagemaker_client.delete_endpoint(EndpointName = endpoint_name) | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Optional: Clean upThe default notebook instance on SageMaker doesn't have a lot of excess disk space available. As you continue to complete and execute notebooks you will eventually fill up this disk space, leading to errors which can be difficult to diagnose. Once you are completely finished using a notebook it is a ... | # First we will remove all of the files contained in the data_dir directory
!rm $data_dir/*
# And then we delete the directory itself
!rmdir $data_dir | _____no_output_____ | MIT | sagemaker-deployment/Tutorials/Boston Housing - Updating an Endpoint.ipynb | dilayercelik/MLND-learning |
Sales by Rate Schedule Request 2:* **p304 L8(b)** TOTAL RESIDENTIAL - MWh Sold (difficult b/c rate schedules change)* **p304 L8(c)** TOTAL RESIDENTIAL - Revenue (difficult b/c rate schedules change)* **p304 L8(d)** TOTAL RESIDENTIAL - Avg Number of Customers (difficult b/c rate schedules change)* **p304 L24(b)** TOTA... | sales_by_sched = (
pd.read_sql("f1_sales_by_sched", ferc1_engine).
pipe(pudl.transform.ferc1.unpack_table,
table_name="f1_sales_by_sched",
data_cols=[
"mwh_sold",
"revenue",
"avg_num_cstmr"
],
data_rows=[
"total"
])... | _____no_output_____ | MIT | notebooks/rbinz_heco.ipynb | catalyst-cooperative/rbinz-heco |
O&M Expenses Request 2:* **p320 L5(b)** (Steam) Fuel (501)* **p320 L25(b)** (Nuclear) Fuel (518)* **p320 L63(b)** (Other) Fuel (547)* **p321 L76(b)** Purchased Power (555) | elec_oandm = (
pd.read_sql("f1_elc_op_mnt_expn", ferc1_engine)
.pipe(
pudl.transform.ferc1.unpack_table,
table_name="f1_elc_op_mnt_expn",
data_cols=[
"crnt_yr_amt"
],
data_rows=[
"production_steam_ops_acct501_fuel",
"production_nuclear_... | _____no_output_____ | MIT | notebooks/rbinz_heco.ipynb | catalyst-cooperative/rbinz-heco |
Operating Revenues Request 2:* **p300 L10(b,d,f)** TOTAL Sales to Ultimate Consumers (revenues, MWh, avg customers)* **p300 L11(b,d,f)** Sales for Resale (447) (revenues, MWh, avg customers)* **p300 L12(b,d,f)** TOTAL Sales of Electricity (revenues, MWh, avg customers) Additional Data in lieu of `f1_sales_by_sched`* ... | sales_hierarchical = (
pd.read_sql("f1_elctrc_oper_rev", ferc1_engine)
.pipe(
pudl.transform.ferc1.unpack_table,
table_name="f1_elctrc_oper_rev",
data_cols=[
"rev_amt_crnt_yr",
"mwh_sold_crnt_yr",
"avg_cstmr_crntyr"
],
data_rows=[
... | _____no_output_____ | MIT | notebooks/rbinz_heco.ipynb | catalyst-cooperative/rbinz-heco |
Income Statements Request 1* **p115 L2(g+h)** Electric Operating Revenues Current+Prior Year* **p115 L?(g+h)** Electric Operating Expenses Current+Prior Year* **p115 L26(g+h)** Electric Net Util Oper Inc Current Year Current+Prior Year Request 2* **p114 L6(g)** Depreciation Expense (403)* **p114 L7(g)** Depreciation ... | elec_income = (
pd.read_sql("f1_income_stmnt", ferc1_engine)
.pipe(
pudl.transform.ferc1.unpack_table,
table_name="f1_income_stmnt",
data_cols = [
"cy_elctrc_total",
],
data_rows = [
"operating_revenues_acct400",
"depreciation_expenses_... | _____no_output_____ | MIT | notebooks/rbinz_heco.ipynb | catalyst-cooperative/rbinz-heco |
Depreciation Request 1:* **P336 L12(f)** Electric Depreciation Expense | elec_depreciation = (
pd.read_sql("f1_dacs_epda", ferc1_engine)
.pipe(
pudl.transform.ferc1.unpack_table,
table_name="f1_dacs_epda",
data_cols=['total'],
data_rows=["total_electric_plant"]
)
.dropna(how="all")
.query("report_prd==12")
.droplevel(0, axis="columns")... | _____no_output_____ | MIT | notebooks/rbinz_heco.ipynb | catalyst-cooperative/rbinz-heco |
Plant in Service Request 1:* **P206 L104(b)** TOTAL Electric Plant in Service Bal Beginning of Year* **P206 L104(g)** TOTAL Electric Plant in Service Bal End of Year | elec_plant_in_service = (
pd.read_sql("f1_plant_in_srvce", ferc1_engine)
.pipe(
pudl.transform.ferc1.unpack_table,
table_name="f1_plant_in_srvce",
data_cols=["begin_yr_bal", "yr_end_bal"],
data_rows=["electric_plant_in_service_total"]
)
.dropna(how="all")
.query("repo... | _____no_output_____ | MIT | notebooks/rbinz_heco.ipynb | catalyst-cooperative/rbinz-heco |
EIA 861 Sales by Customer Class Request 2:**Pull:** * Annual revenues (USD) * Annual sales (MWh) * Annual customers counts**For each of:** * Residential customers * Commercial customers * Industrial customers * All Customers (even though are others like Transportation sales in there?) | import pudl.extract.eia861
eia861_years = range(1999,2019)
eia861_extractor = pudl.extract.eia861.ExtractorExcel(
dataset_name="eia861",
years=eia861_years,
pudl_settings=pudl_settings
)
eia861_dfs = eia861_extractor.create_dfs(years=eia861_years)
sales_eia861 = eia861_dfs["sales_eia861_states"]
cols = [
... | _____no_output_____ | MIT | notebooks/rbinz_heco.ipynb | catalyst-cooperative/rbinz-heco |
Check Data Quality Spot check dataframes | elec_plant_in_service.columns
elec_depreciation.columns
print(elec_plant_in_service.count())
df = pd.merge(elec_plant_in_service, elec_depreciation, left_index=True, right_index=True)
sns.scatterplot(x="total_electric_plant", y="ending_balance", data=df)
elec_income.columns
elec_income.sample(10)
df = elec_income.reset... | _____no_output_____ | MIT | notebooks/rbinz_heco.ipynb | catalyst-cooperative/rbinz-heco |
Prepare Data for Output Select requested utilities* Use Binz' target list to select a subset of the tables/columns.* Add missing & unmapped `utility_id_ferc1` values to the (FERC) target list: - **`eia 22500`** : `ferc1 191, 276` (Westar Energy) - **`eia 13780`** : `ferc1 121` (Northern States Power Company - W... | # Grab the EIA/FERC Utility IDs & Names:
utilities_eia = pd.read_sql("utilities_eia", pudl_engine)
utilities_ferc1 = pd.read_sql("utilities_ferc1", pudl_engine)
# Get Binz' list of utilities based on EIA IDs:
rbinz_eia_utils = pd.read_csv("rbinz_instructions.csv", index_col="utility_id_eia")
# Infer FERC 1 Utility ID... | _____no_output_____ | MIT | notebooks/rbinz_heco.ipynb | catalyst-cooperative/rbinz-heco |
Stemming* Stemming is the process of removing suffix from word to obtain base or root word i.e., to reduce inflectional form of word to base word.* Stemming will chop-off ‘s’, ‘es’, ‘ed’, ‘ing’, ‘ly’ etc from the end of the words and sometimes the conversion is not desirable. But nonetheless, stemming helps us in stan... | import nltk
from nltk.stem import PorterStemmer, SnowballStemmer, LancasterStemmer
from nltk.tokenize import word_tokenize
nltk.download('punkt') | [nltk_data] Downloading package punkt to /root/nltk_data...
[nltk_data] Package punkt is already up-to-date!
| MIT | Data-Preprocessing/Stemming.ipynb | guru9573/NLP |
Porter StemmerThis is one of the most common and gentle stemmer. It is very fast but not precise enough. | porter_stemmer = PorterStemmer()
def stem_words_porter(text):
words = word_tokenize(text)
stem_words = [stemmer.stem(word) for word in words]
return stem_words
input_text = "SpaceX is an American aerospace manufacturer, space transportation services and communications company headquartered in Hawthorne, Califor... | _____no_output_____ | MIT | Data-Preprocessing/Stemming.ipynb | guru9573/NLP |
Snowball Stemmer* There were some improvements done on Porter Stemmer which made it more precise over large datasets* One feature of Snowball Stemmer is that it will ignore stemming of Stopwords | snowball_stemmer = SnowballStemmer(language="english")
def stem_words_snowball(text):
words = word_tokenize(text)
stem_words = [snowball_stemmer.stem(word) for word in words]
return stem_words
stem_words_snowball(input_text) | _____no_output_____ | MIT | Data-Preprocessing/Stemming.ipynb | guru9573/NLP |
You can see "was" is handled well by Snowball Stemmer compared to PorterStemmer. Lancaster Stemmer* This very aggressive Stemmer and will hugely trim down the vocabulary* It is fast but not quite advisable as the base word will not be much accurate | lancaster = LancasterStemmer()
def stem_words_lancaster(text):
words = word_tokenize(text)
stem_words = [lancaster.stem(word) for word in words]
return stem_words
stem_words_lancaster(input_text) | _____no_output_____ | MIT | Data-Preprocessing/Stemming.ipynb | guru9573/NLP |
Deploy a Trained MXNet ModelIn this notebook, we walk through the process of deploying a trained model to a SageMaker endpoint. If you recently ran [the notebook for training](get_started_mnist_deploy.ipynb) with %store% magic, the `model_data` can be restored. Otherwise, we retrieve the model artifact from a public S... | # setups
import os
import json
import boto3
import sagemaker
from sagemaker.mxnet import MXNetModel
from sagemaker import get_execution_role, Session
sess = Session()
role = get_execution_role()
%store -r mx_mnist_model_data
try:
mx_mnist_model_data
except NameError:
import json
# copy a pretrained m... | _____no_output_____ | Apache-2.0 | frameworks/mxnet/get_started_mnist_deploy.ipynb | Amirosimani/amazon-sagemaker-examples |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.