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 |
|---|---|---|---|---|---|
- `*` 0,28,28,0 부분을 0,27,27,0으로 바꾸심. 이유는 잘 모르겠음 2d part의 (1,16,12,12) 와 Linear transform인 (16,1)의 연산이 이해되지 않음 tensor 계산 연습 | _mat1 = torch.tensor([[[1,2,3,4], [5,6,7,8], [9,10,11,12]],[[-1,2,-3,4], [-5,6,-7,8], [-9,10,-11,12]]])
_mat2 = torch.tensor([10 for i in range(2)])
_mat2.shape, _mat1.shape | _____no_output_____ | Apache-2.0 | _notebooks/2021-10-26,28-{fastai_CNN}.ipynb | chchin33/violet |
-- | net1(x).squeeze().shape
net2[2].weight.squeeze().shape # net2[2]는 두 cell 위의 net2결과에서 (2): Linear부분을 뜻한다. | _____no_output_____ | Apache-2.0 | _notebooks/2021-10-26,28-{fastai_CNN}.ipynb | chchin33/violet |
`-` camimg = torch.einsum("i, ijk -> jk", net2[2].weight.squeeze(), net1(x).squeeze())를 참고하여 -- | torch.einsum("i, ijk -> jk", _mat2, _mat1) # 각각의 jk에 대해 i인덱스별 합, | _____no_output_____ | Apache-2.0 | _notebooks/2021-10-26,28-{fastai_CNN}.ipynb | chchin33/violet |
각각의 jk에 대해 i인덱스별 합, $ \sum_i{mat1_i}{mat2_ijk}$ -> ijk를 [i][j][k]로 인덱싱하면 각각의 j,k별로 _mat1[0][0][0]*_mat2[0] + _mat1[1][0][0]*_mat2[1] /// _mat1[0][0][1]*_mat2[0] + _mat1[1][0][1]*_mat2[1] /// $\dots$ ///_mat1[0][2][3]*_mat2[0] + _mat1[1][2][3]*_mat2[1] 과 같이 계산된다. | for i in range(3):
for j in range(4):
print(_mat1[0][i][j]*_mat2[0] + _mat1[1][i][j]*_mat2[1])
_mat1[0][0][0]*_mat2[0] + _mat1[1][0][0]*_mat2[1] | _____no_output_____ | Apache-2.0 | _notebooks/2021-10-26,28-{fastai_CNN}.ipynb | chchin33/violet |
`-` 알아낸 einsum의 원리를 바탕으로 2d part output 과 1d part의 linear transform의 연산결과를 해석해보면, -> 2d part output은 torch.Size([16, 12, 12]) 이고 1d part는 16개의 가중치를 가진다.torch.Size([16, 12, 12]) -> 16은 channel(혹은 16장의 이미지) 즉, [이미지 지정 인덱스][지정된 인덱스 이미지 pixel row][지정된 인덱스 이미지 pixel col] 에서 지정 위치의 픽셀 [row][col]에 대한 16장 이미지의 해당 픽셀들에 가중치를 곱해... | x = X[7000]
x.shape
x = X[7000]
x = x.squeeze()
plt.imshow(x)
x = x.reshape(1,1,28,28)
camimg = torch.einsum("i, ijk -> jk", net2[2].weight.squeeze(), net1(x).squeeze())
plt.imshow(x.squeeze(), cmap='gray',alpha=0.5)
plt.imshow(camimg.data, alpha = 0.5, extent = (0,27,27,0), interpolation = 'bilinear', cmap='magma') | _____no_output_____ | Apache-2.0 | _notebooks/2021-10-26,28-{fastai_CNN}.ipynb | chchin33/violet |
**LabML03a**Purpose: Identify clusters of Gira docking station1 import libraries needed:numpy, sklearn, matplotlib and pandas2 generate a sample of blobs and convert it into a dataframe called df13 Verify datatype4 Plot the blobs5 calculete WCSS6 plot the new chart with centroids7 identify to what group does each item ... | import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans
file='https://github.com/masterfloss/data/blob/main/giras201030.csv?raw=true'
dfGiras=pd.read_csv(file,sep=';')
dfGiras.head()
dfGiras.loc[0,'position'].split()[1].replace('[','').replace(',','')
for i in rang... | _____no_output_____ | MIT | training_modules/LabML03a.ipynb | jorgealexandreb/Covid-19-ML-Project- |
Game Music dataset: data cleaning and explorationThe goal with this notebook is cleaning the dataset to make it usable as well as providing a descriptive analysis of the dataset features. Data loading and cleaning | import warnings
warnings.filterwarnings('ignore')
import pandas as pd
import numpy as np
from ast import literal_eval
import os
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
df = pd.read_csv('midi_dataframe.csv', parse_dates=[11])
num_midis_before = len(df)
print('There is %d midi files, fro... | There is 31685 midi files, from 3388 games, with 31249 midis matched with tgdb
| BSD-3-Clause | dataset/Data Exploration.ipynb | cedricviaccoz/musicology |
We keep only files matched with tgdb and check that every midi file is only present once, if not we drop the rows. | num_dup = df.duplicated(subset='file_name').sum()
df.drop_duplicates(subset='file_name', inplace=True)
print('There was %d duplicated midi files, %d midis left'%(num_dup, len(df))) | There was 2 duplicated midi files, 31683 midis left
| BSD-3-Clause | dataset/Data Exploration.ipynb | cedricviaccoz/musicology |
Since we are interested in the genre, we only keep midis that have one. | num_genres_na = df.tgdb_genres.isnull().sum()
df.dropna(subset=['tgdb_genres'], inplace=True)
print("We removed %d midis, %d midis left"%(num_genres_na, len(df))) | We removed 436 midis, 31247 midis left
| BSD-3-Clause | dataset/Data Exploration.ipynb | cedricviaccoz/musicology |
Then, there are some categories, such as Medleys or Piano only that are not interesting.There is also a big "remix" scene on vgmusic, so we also remove those. | categories_filter = df.console.isin(['Medleys', 'Piano Only'])
remix_filter = df.title.str.contains('[Rr]emix')
df = df[~categories_filter & ~remix_filter]
print('We removed %d midis from Medleys and Piano categories'%categories_filter.sum())
print('We removed %d midis containing "remix" in their title'%remix_filter.s... | We removed 872 midis from Medleys and Piano categories
We removed 1860 midis containing "remix" in their title
28537 midis left
| BSD-3-Clause | dataset/Data Exploration.ipynb | cedricviaccoz/musicology |
There often exists several versions of the same midi file, most of the time denoted by 'title (1)', 'title (2)', etc.We also consider removing those, but keeping only the one with the highest value, or if there are several with the same title, we randomly keep one. | num_midis_before = len(df)
df_stripped = df.copy()
df_stripped.title = df.title.str.replace('\(\d+\)', '').str.rstrip()
df_stripped['rank'] = df.title.str.extract('\((\d+)\)', expand=False)
df = df_stripped.sort_values(by='rank', ascending=False).groupby(['brand', 'console', 'game', 'title']).first().reset_index()
pri... | We removed 6358 midis, 22179 midis left
| BSD-3-Clause | dataset/Data Exploration.ipynb | cedricviaccoz/musicology |
We also check if the midis files are valid by using mido and trying to load them. | from mido import MidiFile
bad_midis = []
for file in df['file_name']:
try:
midi = MidiFile("full/" + file)
except:
bad_midis.append(file)
df = df.loc[df.file_name.apply(lambda x: x not in bad_midis)]
print("We removed %d midis, %d midis left"%(len(bad_midis), len(df))) | We removed 117 midis, 22062 midis left
| BSD-3-Clause | dataset/Data Exploration.ipynb | cedricviaccoz/musicology |
The final numbers after preliminary data cleaning are: | num_games = len(df.groupby(['tgdb_platform', 'tgdb_gametitle']))
print('There is %d midi files, from %d games, with %d midis matched with tgdb'
%(len(df),
num_games,
(df.tgdb_gametitle.notnull().sum()))) | There is 22062 midi files, from 3237 games, with 22062 midis matched with tgdb
| BSD-3-Clause | dataset/Data Exploration.ipynb | cedricviaccoz/musicology |
Data Exploration General statisticsWe first begin by some general statistics about the dataset. The number of gaming platforms is computed. | print('There is %d platforms'%df.tgdb_platform.nunique()) | There is 62 platforms
| BSD-3-Clause | dataset/Data Exploration.ipynb | cedricviaccoz/musicology |
Then, statistics concerning the number of games per platform are computed and plotted. | df.drop_duplicates(subset=['tgdb_platform', 'tgdb_gametitle']).groupby('tgdb_platform').size().to_frame().describe()
size= (10, 5)
fig, ax = plt.subplots(figsize=size)
ax = sns.distplot(df.drop_duplicates(subset=['tgdb_platform', 'tgdb_gametitle']).groupby('tgdb_platform').size().to_frame(), ax = ax)
ax.set_xlabel("num... | _____no_output_____ | BSD-3-Clause | dataset/Data Exploration.ipynb | cedricviaccoz/musicology |
It can be noted that the majority of platforms seem to have around 10 games, which is a sufficient sample size. Following this, statistics concerning the number of midis per platform are computed and plotted. | df.groupby('tgdb_platform').size().to_frame().describe()
fig, ax = plt.subplots(figsize=size)
ax = sns.distplot(df.groupby('tgdb_platform').size().to_frame())
ax.set_xlabel("number of midi per platform")
ax.set_ylabel("density")
ax.set_title("Density of the number of midis per platform")
ax.set_xticks(np.arange(0, 1000... | _____no_output_____ | BSD-3-Clause | dataset/Data Exploration.ipynb | cedricviaccoz/musicology |
It can be noted that the majority of platform have around 50 midis, which is again judged to be a sufficient sample for analysis. Finally, statistics concerning the number of midi per game are computed and plotted. | df.groupby(['tgdb_platform', 'tgdb_gametitle']).size().to_frame().describe()
fig, ax = plt.subplots(figsize=size)
ax = sns.distplot(df.groupby(['tgdb_platform', 'tgdb_gametitle']).size().to_frame())
ax.set_xlabel("number of midi per game")
ax.set_ylabel("density")
ax.set_title("Density of the number of midi per game")
... | _____no_output_____ | BSD-3-Clause | dataset/Data Exploration.ipynb | cedricviaccoz/musicology |
It can be noted that the peak of density is at 2 midi per game. This does not matter much as we are not trying to classify music per game, but by genres. As a general remark, it can be noticed that most of the data we have follow power laws. Genres analysisWe currently had list of genres, for more convenience, we rewo... | genres = df.tgdb_genres.map(literal_eval, 'ignore').apply(pd.Series).stack().reset_index(level=1, drop=True)
genres.name = 'tgdb_genres'
genres_df = df.drop('tgdb_genres', axis=1).join(genres)
print("There is %d different genres"%genres_df.tgdb_genres.nunique())
genres_df.to_csv("midi_dataframe_cleaned.csv") | _____no_output_____ | BSD-3-Clause | dataset/Data Exploration.ipynb | cedricviaccoz/musicology |
Here follows the percentage of games belonging to each genre and of midis for each genres. | genres_df.drop_duplicates(subset=['tgdb_platform', 'tgdb_gametitle'])\
.groupby(['tgdb_genres']).size().to_frame()\
.sort_values(0, ascending = False)/num_games*100 | _____no_output_____ | BSD-3-Clause | dataset/Data Exploration.ipynb | cedricviaccoz/musicology |
Convolutional Neural Network in Keras Bulding a Convolutional Neural Network to classify Fashion-MNIST. Set seed for reproducibility | import numpy as np
np.random.seed(42) | _____no_output_____ | MIT | notebooks/keras/3_conv-net-in-keras.ipynb | ekholabs/workshop |
Load dependencies | import os
from tensorflow.keras.datasets import fashion_mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Layer, Activation, Dense, Dropout, Conv2D, MaxPooling2D, Flatten, LeakyReLU, BatchNormalization
from tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStop... | _____no_output_____ | MIT | notebooks/keras/3_conv-net-in-keras.ipynb | ekholabs/workshop |
Load data | (X_train, y_train), (X_test, y_test) = fashion_mnist.load_data() | _____no_output_____ | MIT | notebooks/keras/3_conv-net-in-keras.ipynb | ekholabs/workshop |
Preprocess dataFlatten and normalise input data. | X_train = X_train.reshape(-1, 28, 28, 1)
X_test = X_test.reshape(-1, 28, 28, 1)
X_train = X_train.astype("float32")/255.
X_test = X_test.astype("float32")/255.
# One-hot encoded categories
n_classes = 10
y_train = to_categorical(y_train, n_classes)
y_test = to_categorical(y_test, n_classes) | _____no_output_____ | MIT | notebooks/keras/3_conv-net-in-keras.ipynb | ekholabs/workshop |
Design Neural Network architecture | model = Sequential()
model.add(Conv2D(32, 7, padding = 'same', input_shape = (28, 28, 1)))
# model.add(LeakyReLU(alpha=0.01))
model.add(Activation('relu'))
model.add(Conv2D(32, 7, padding = 'same'))
# model.add(LeakyReLU(alpha=0.01))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(... | Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 28, 28, 32) 1600
____________________________________... | MIT | notebooks/keras/3_conv-net-in-keras.ipynb | ekholabs/workshop |
Callbacks | modelCheckpoint = ModelCheckpoint(monitor='val_accuracy', filepath='model_output/weights-cnn-fashion-mnist.hdf5',
save_best_only=True, mode='max')
earlyStopping = EarlyStopping(monitor='val_accuracy', mode='max', patience=5)
if not os.path.exists('model_output'):
os.... | _____no_output_____ | MIT | notebooks/keras/3_conv-net-in-keras.ipynb | ekholabs/workshop |
Configure model | model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy']) | _____no_output_____ | MIT | notebooks/keras/3_conv-net-in-keras.ipynb | ekholabs/workshop |
Train! | history = model.fit(X_train, y_train, batch_size = 128, epochs = 20, verbose = 1,
validation_split = 0.1, callbacks=[modelCheckpoint, earlyStopping, tensorboard]) | Train on 54000 samples, validate on 6000 samples
Epoch 1/20
54000/54000 [==============================] - 109s 2ms/sample - loss: 0.6916 - accuracy: 0.7466 - val_loss: 0.3887 - val_accuracy: 0.8520
Epoch 2/20
54000/54000 [==============================] - 117s 2ms/sample - loss: 0.3989 - accuracy: 0.8529 - val_loss: 0... | MIT | notebooks/keras/3_conv-net-in-keras.ipynb | ekholabs/workshop |
Test Predictions | saved_model = load_model('model_output/weights-cnn-fashion-mnist.hdf5')
predictions = saved_model.predict_classes(X_test, verbose = 2)
print(predictions)
# np.std(history.history['loss']) | 10000/1 - 9s
[9 2 1 ... 8 1 5]
| MIT | notebooks/keras/3_conv-net-in-keras.ipynb | ekholabs/workshop |
Test Final Accuracy | final_loss, final_acc = saved_model.evaluate(X_test, y_test, verbose = 2)
print("Final loss: {0:.4f}, final accuracy: {1:.4f}".format(final_loss, final_acc))
image = X_test[0].reshape(1, 28, 28, 1)
predictions = model.predict_classes(image, verbose = 2)
print(predictions)
plt.imshow(X_test[0].reshape((28, 28)), cmap='g... | _____no_output_____ | MIT | notebooks/keras/3_conv-net-in-keras.ipynb | ekholabs/workshop |
7.1 Breakoutを実行してみるWindowsでbreakout-v0を実行するために、事前に以下のコマンドを実行してください。pip install --no-index -f https://github.com/Kojoley/atari-py/releases atari_pypip install opencv-python | # パッケージのimport
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import gym
# ゲームの開始
ENV = 'Breakout-v0' # 使用する課題名
env = gym.make(ENV) # 実行する課題を設定
# ゲームの状態と行動を把握
# 状態
print(env.observation_space)
# Box(210, 160, 3)
# 行動
print(env.action_space)
print(env.unwrapped.get_action_meanings())
# Discr... | _____no_output_____ | MIT | program/7_1_Breakout_try.ipynb | keito1029/Deep-Reinforcement-Learning-Book |
Given a dictionary, print the key for nth highest value present in the dict. dic ={'a':242,'b':10,'c':500} k= 2 RETURN VALUE op = 242 | def nth_highest(dic,k):
dic ={'a':4,'d':6,'c':9,'b':9}
return sorted(dic.values())[-k]
dic ={'a':4,'d':6,'c':9,'b':9}
print(nth_highest(dic,2)) | 9
| MIT | array_strings/ipynb/kth_highest_dict.ipynb | PRkudupu/Algo-python |
Given a dictionary, print the key for nth highest value present in the dict. dic ={'a':242,'b':10,'c':500} k= 2 op = a RETURN KEY | # return Keys not values. In the above example we are returning keys
def nth_highest(dic,k):
kth_value=sorted(dic.values())[-k]
for k,v in dic.items():
if v==kth_value:
return k
dic ={'a':4,'d':6,'c':9,'b':9}
print(nth_highest(dic,1)) | c
| MIT | array_strings/ipynb/kth_highest_dict.ipynb | PRkudupu/Algo-python |
Given a dictionary, print the key for nth highest value present in the dict. If there are more than 1 record present for nth highest value then sort the key and print the first one. {'a':500,'b':10,'c':500,'d':500} k= 1 op = a RETURN KEY | def nth_highest(dic,k):
kth_value=sorted(dic.values())[-k]
for k,v in dic.items():
if v==kth_value:
return k
dic ={'a':4,'d':6,'c':9,'b':9}
print(nth_highest(dic,1)) | c
| MIT | array_strings/ipynb/kth_highest_dict.ipynb | PRkudupu/Algo-python |
Another approach | dict = {'a':4,'d':6,'c':9,'b':9}
def nth_highest(n):
a = sorted(dict.items(),key= lambda x :x[1],reverse =True)
print(a[n-1][0])
x = nth_highest(1) | c
| MIT | array_strings/ipynb/kth_highest_dict.ipynb | PRkudupu/Algo-python |
Parallel GST using MPIThe purpose of this tutorial is to demonstrate how to compute GST estimates in parallel (using multiple CPUs or "processors"). The core PyGSTi computational routines are written to take advantage of multiple processors via the MPI communication framework, and so one must have a version of MPI an... | #Import pyGSTi and the "stardard 1-qubit quantities for a model with X(pi/2), Y(pi/2), and idle gates"
import pygsti
from pygsti.modelpacks import smq1Q_XYI
#Create experiment design
exp_design = smq1Q_XYI.get_gst_experiment_design(max_max_length=32)
pygsti.io.write_empty_protocol_data(exp_design, "example_files/mpi_g... | _____no_output_____ | Apache-2.0 | jupyter_notebooks/Examples/MPI-RunningGST.ipynb | lnmaurer/pyGSTi |
Next, we'll write a Python script that will load in the just-created `DataSet`, run GST on it, and write the output to a file. The only major difference between the contents of this script and previous examples is that the script imports `mpi4py` and passes a MPI comm object (`comm`) to the `do_long_sequence_gst` func... | mpiScript = """
import time
import pygsti
#get MPI comm
from mpi4py import MPI
comm = MPI.COMM_WORLD
print("Rank %d started" % comm.Get_rank())
#load in data
data = pygsti.io.load_data_from_dir("example_files/mpi_gst_example")
#Specify a per-core memory limit (useful for larger GST calculations)
memLim = 2.1*(1024)... | _____no_output_____ | Apache-2.0 | jupyter_notebooks/Examples/MPI-RunningGST.ipynb | lnmaurer/pyGSTi |
Next, we run the script with 3 processors using `mpiexec`. The `mpiexec` executable should have been installed with your MPI distribution -- if it doesn't exist, try replacing `mpiexec` with `mpirun`. | ! mpiexec -n 3 python3 "example_files/mpi_example_script.py" | Rank 1 started
Rank 0 started
Rank 2 started
-- Std Practice: Iter 1 of 1 (TP) --:
--- Iterative MLGST: [##################################################] 100.0% 784 operation sequences ---
Iterative MLGST Total Time: 6.8s
Rank 2 finished in 7.4s
/Users/enielse/pyGSTi/pygsti/algorithms/gaugeopt.py:389: UserWa... | Apache-2.0 | jupyter_notebooks/Examples/MPI-RunningGST.ipynb | lnmaurer/pyGSTi |
Notice in the above that output within `StandardGST.run` is not duplicated (only the first processor outputs to stdout) so that the output looks identical to running on a single processor. Finally, we just need to read the saved `ModelEstimateResults` object from file and proceed with any post-processing analysis. In... | results = pygsti.io.load_results_from_dir("example_files/mpi_gst_example", name="StandardGST")
pygsti.report.construct_standard_report(
results, title="MPI Example Report", verbosity=2
).write_html('example_files/mpi_example_brief', auto_open=True) | Running idle tomography
Computing switchable properties
Found standard clifford compilation from smq1Q_XYI
| Apache-2.0 | jupyter_notebooks/Examples/MPI-RunningGST.ipynb | lnmaurer/pyGSTi |
Copyright (c) Microsoft Corporation. All rights reserved.Licensed under the MIT License.  Automated Machine... | import azureml.core
import pandas as pd
import numpy as np
import logging
from azureml.core import Workspace, Experiment, Dataset
from azureml.train.automl import AutoMLConfig
from datetime import datetime | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
This sample notebook may use features that are not available in previous versions of the Azure ML SDK. | print("This notebook was created using version 1.17.0 of the Azure ML SDK")
print("You are currently using version", azureml.core.VERSION, "of the Azure ML SDK") | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
As part of the setup you have already created a Workspace. To run AutoML, you also need to create an Experiment. An Experiment corresponds to a prediction problem you are trying to solve, while a Run corresponds to a specific approach to the problem. | ws = Workspace.from_config()
# choose a name for the run history container in the workspace
experiment_name = 'automl-bikeshareforecasting'
experiment = Experiment(ws, experiment_name)
output = {}
output['Subscription ID'] = ws.subscription_id
output['Workspace'] = ws.name
output['SKU'] = ws.sku
output['Resource Gro... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
ComputeYou will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targetsamlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource. Creation of AmlCompute takes approximately 5 minutes. If the AmlCom... | from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
# Choose a name for your cluster.
amlcompute_cluster_name = "bike-cluster"
# Verify that cluster does not exist already
try:
compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluste... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
DataThe [Machine Learning service workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-workspace) is paired with the storage account, which contains the default data store. We will use it to upload the bike share data and create [tabular dataset](https://docs.microsoft.com/en-us/python/ap... | datastore = ws.get_default_datastore()
datastore.upload_files(files = ['./bike-no.csv'], target_path = 'dataset/', overwrite = True,show_progress = True) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
Let's set up what we know about the dataset. **Target column** is what we want to forecast.**Time column** is the time axis along which to predict. | target_column_name = 'cnt'
time_column_name = 'date'
dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, 'dataset/bike-no.csv')]).with_timestamp_columns(fine_grain_timestamp=time_column_name)
dataset.take(5).to_pandas_dataframe().reset_index(drop=True) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
Split the dataThe first split we make is into train and test sets. Note we are splitting on time. Data before 9/1 will be used for training, and data after and including 9/1 will be used for testing. | # select data that occurs before a specified date
train = dataset.time_before(datetime(2012, 8, 31), include_boundary=True)
train.to_pandas_dataframe().tail(5).reset_index(drop=True)
test = dataset.time_after(datetime(2012, 9, 1), include_boundary=True)
test.to_pandas_dataframe().head(5).reset_index(drop=True) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
Forecasting ParametersTo define forecasting parameters for your experiment training, you can leverage the ForecastingParameters class. The table below details the forecasting parameter we will be passing into our experiment.|Property|Description||-|-||**time_column_name**|The name of your time column.||**forecast_hori... | forecast_horizon = 14 | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
Config AutoML | from azureml.automl.core.forecasting_parameters import ForecastingParameters
forecasting_parameters = ForecastingParameters(
time_column_name=time_column_name,
forecast_horizon=forecast_horizon,
country_or_region_for_holidays='US', # set country_or_region will trigger holiday featurizer
target_lags='aut... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
We will now run the experiment, you can go to Azure ML portal to view the run details. | remote_run = experiment.submit(automl_config, show_output=False)
remote_run
remote_run.wait_for_completion() | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
Retrieve the Best ModelBelow we select the best model from all the training iterations using get_output method. | best_run, fitted_model = remote_run.get_output()
fitted_model.steps | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
FeaturizationYou can access the engineered feature names generated in time-series featurization. Note that a number of named holiday periods are represented. We recommend that you have at least one year of data when using this feature to ensure that all yearly holidays are captured in the training featurization. | fitted_model.named_steps['timeseriestransformer'].get_engineered_feature_names() | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
View the featurization summaryYou can also see what featurization steps were performed on different raw features in the user data. For each raw feature in the user data, the following information is displayed:- Raw feature name- Number of engineered features formed out of this raw feature- Type detected- If feature wa... | # Get the featurization summary as a list of JSON
featurization_summary = fitted_model.named_steps['timeseriestransformer'].get_featurization_summary()
# View the featurization summary as a pandas dataframe
pd.DataFrame.from_records(featurization_summary) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
Evaluate We now use the best fitted model from the AutoML Run to make forecasts for the test set. We will do batch scoring on the test dataset which should have the same schema as training dataset.The scoring will run on a remote compute. In this example, it will reuse the training compute. | test_experiment = Experiment(ws, experiment_name + "_test") | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
Retrieving forecasts from the modelTo run the forecast on the remote compute we will use a helper script: forecasting_script. This script contains the utility methods which will be used by the remote estimator. We copy the script to the project folder to upload it to remote compute. | import os
import shutil
script_folder = os.path.join(os.getcwd(), 'forecast')
os.makedirs(script_folder, exist_ok=True)
shutil.copy('forecasting_script.py', script_folder) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
For brevity, we have created a function called run_forecast that submits the test data to the best model determined during the training run and retrieves forecasts. The test set is longer than the forecast horizon specified at train time, so the forecasting script uses a so-called rolling evaluation to generate predict... | from run_forecast import run_rolling_forecast
remote_run = run_rolling_forecast(test_experiment, compute_target, best_run, test, target_column_name)
remote_run
remote_run.wait_for_completion(show_output=False) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
Download the prediction result for metrics calcuationThe test data with predictions are saved in artifact outputs/predictions.csv. You can download it and calculation some error metrics for the forecasts and vizualize the predictions vs. the actuals. | remote_run.download_file('outputs/predictions.csv', 'predictions.csv')
df_all = pd.read_csv('predictions.csv')
from azureml.automl.core.shared import constants
from azureml.automl.runtime.shared.score import scoring
from sklearn.metrics import mean_absolute_error, mean_squared_error
from matplotlib import pyplot as plt... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
Since we did a rolling evaluation on the test set, we can analyze the predictions by their forecast horizon relative to the rolling origin. The model was initially trained at a forecast horizon of 14, so each prediction from the model is associated with a horizon value from 1 to 14. The horizon values are in a column n... | from metrics_helper import MAPE, APE
df_all.groupby('horizon_origin').apply(
lambda df: pd.Series({'MAPE': MAPE(df[target_column_name], df['predicted']),
'RMSE': np.sqrt(mean_squared_error(df[target_column_name], df['predicted'])),
'MAE': mean_absolute_error(df[ta... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
To drill down more, we can look at the distributions of APE (absolute percentage error) by horizon. From the chart, it is clear that the overall MAPE is being skewed by one particular point where the actual value is of small absolute value. | df_all_APE = df_all.assign(APE=APE(df_all[target_column_name], df_all['predicted']))
APEs = [df_all_APE[df_all['horizon_origin'] == h].APE.values for h in range(1, forecast_horizon + 1)]
%matplotlib inline
plt.boxplot(APEs)
plt.yscale('log')
plt.xlabel('horizon')
plt.ylabel('APE (%)')
plt.title('Absolute Percentage Er... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb | sebastiangonzalezv/MachineLearningNotebooks |
Plot General/Specific results Functions | %run -i 'arena.py'
%matplotlib inline
%matplotlib notebook
import matplotlib
from matplotlib import pyplot as plt
def plotDataFromFile(file, saveDir, style, label, color, fullRuns, linewidth, ax):
x = [i for i in range(9)]
if fullRuns:
data = load_obj(saveDir, file)
data = convertFullToMeanErro... | _____no_output_____ | Apache-2.0 | mainCode/TL-PLOT.ipynb | dreamspy/Endnet |
Parameters | ############################### parameters
saveDir = 'bengioResults'
######## Misc parm
xSize = 7
ySize = 7
fontSize = 12
linewidth = 1
startAt = 1
######### colors
### blue red colors
c3n4p = '#ff9999'
c3n4 = '#ff0000'
c4n4p = '#9999ff'
c4n4 = '#0000ff'
c3n4pref = '#ff9999'
c3n4ref = '#ff... | _____no_output_____ | Apache-2.0 | mainCode/TL-PLOT.ipynb | dreamspy/Endnet |
Plot Tensorboard logs |
### prepare plot (has to be in same cell as the plot functions)
fig = plt.figure(figsize=(xSize,ySize))
ax = fig.add_subplot(111)
### parameters
ymin = None
ymax = None
xmin = None
xmax = None
# ymin = 0.95
ymax = 0.1
# xmin = 1
# xmax = 8
file = "./logsArchiveGood/052-4pc-RND-184KPM-Training 4pc with transfer ... | _____no_output_____ | Apache-2.0 | mainCode/TL-PLOT.ipynb | dreamspy/Endnet |
Run arrays | ######### Plot plots using plot function plot
run001 = [
#3n4+
['3n4+-10runAverage', 'bengioResults/1.savedResults/001', '-', '3n4+ 001', c3n4p, False],
#3n4
['3n4-10runAverage', 'bengioResults/1.savedResults/001', '-', '3n4 001', c3n4, False],
... | _____no_output_____ | Apache-2.0 | mainCode/TL-PLOT.ipynb | dreamspy/Endnet |
Draw Plots | ### prepare plot (has to be in same cell as the plot functions)
fig = plt.figure(figsize=(xSize,ySize))
ax = fig.add_subplot(111)
### plot plots
# ruined
# plotIt(run001)
# ruined
# plotIt(run002)
# one run average for comp with 001 and 002
# plotIt(run003)
### prepare plot (has to be in same cell as the plot functi... | _____no_output_____ | Apache-2.0 | mainCode/TL-PLOT.ipynb | dreamspy/Endnet |
Calc confidence interval | ### MOVED TO ARENA.PY
def calcStats(measurements):
μ = np.mean(measurements)
σ = np.std(measurements, ddof=1)
max = np.max(measurements)
min = np.min(measurements)
print('max-min', max-min)
print('σ',σ*100)
n = len(measurements)
ste = σ/np.sqrt(n-1)
error = 1.96 * ste
print('erro... | _____no_output_____ | Apache-2.0 | mainCode/TL-PLOT.ipynb | dreamspy/Endnet |
Calculate some shit... not sure what, probably transfer learning comparision | from3 = [0.977
,0.98
,0.978
,0.977
,0.976
]
rnd = [ 0.982,
0.984,
0.985,
0.983,
0.982]
print(rnd)
rndStats = calcStats(rnd)
from3Stats = calcStats(from3)
print(rndStats)
print(from3Stats)
print()
print(rndStats[0] + rndStats[1])
print(rndStats[0] - rndStats[1])
print()
print(from3Stats[0] + from3St... | [0.9832000000000001, 0.0012777636714197203]
[0.9776, 0.0014862435870341053]
0.9844777636714198
0.9819222363285803
0.9790862435870341
0.9761137564129659
| Apache-2.0 | mainCode/TL-PLOT.ipynb | dreamspy/Endnet |
Calculating accuracty of phi_4 after 10 epochs, taken from logs 773-861, approximately (Adam skipped) | phi_4 = [
0.9673,
0.9676,
0.9659,
0.9680,
0.9694,
0.9724,
0.9695,
0.9694
]
phi_4_Stats = calcStats(phi_4)
print(phi_4_Stats) | max-min 0.006500000000000061
σ 0.19569929556775342
error 0.14497606699038412
[0.9686875, 0.0014497606699038412]
| Apache-2.0 | mainCode/TL-PLOT.ipynb | dreamspy/Endnet |
Plot tensorboard in Matplotlib example code | #this doesn't work
import numpy as np
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
# from tensorflow.python.summary.event_accumulator import EventAccumulator
import matplotlib as mpl
import matplotlib.pyplot as plt
def plot_tensorflow_log(path):
# Loading too much data is s... | {'acc': (array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, ... | Apache-2.0 | mainCode/TL-PLOT.ipynb | dreamspy/Endnet |
Converge 3 to 4 5 average train 3 every time Calculate means and shit | d3 = load_obj('.','d3')
d4 = load_obj('.','d4')
print('33333333333333')
for key, value in d3.items():
print(key,value)
print()
print('4444444444444')
for key, value in d4.items():
print(key,value)
print('\naverage....')
print('33333333333333')
for key, value in d3.items():
print(key,np.mean(value))
print()
... | _____no_output_____ | Apache-2.0 | mainCode/TL-PLOT.ipynb | dreamspy/Endnet |
Let's have a look at the stats of Population (*ApplicantIncome*). | # mean
mean_pop=income_pop.mean()
mean_pop
# std dev.
std_pop=income_pop.std()
std_pop
median_pop = income_pop.median()
median_pop
sns.histplot(income_pop, kde=True)
plt.show() | _____no_output_____ | MIT | Deep Dive into CLT(Section 2)/Video 2.3(Better Practice of CLT)/Final CLT (1).ipynb | codered-by-ec-council/Applied-Statistics-with-Python |
Here we can see that the distribution is not normal and mean = 5403.45, std. dev = 6109.04. Central Limit TheormThe central limit theorem states that if you have a population with mean μ and standard deviation σ and take sufficiently large random samples from the population with replacement , then the distribution of ... | sample_means_list = []
n_best=0
n_list= [25, 50, 100, 150, 200]
skew= []
kurt= []
for n in n_list:
sample_means_trial=[]
for sample in range(0, 300):
sample_values = np.random.choice(income_pop, size=n)
sample_mean = np.mean(sample_values)
sample_means_trial.append(sample_mean)
sns.kdeplot(sample_me... | _____no_output_____ | MIT | Deep Dive into CLT(Section 2)/Video 2.3(Better Practice of CLT)/Final CLT (1).ipynb | codered-by-ec-council/Applied-Statistics-with-Python |
So, here we have 5 sample means list. And as per CLT if we choose an appropriate sample size then the sample means approximate a normal distribution.So, here we have the skewness and kurtosis of the *sample means* and we will go with that smaple_mean that has low skew and kurt. | # let's have a look at the skew list and kurt list
print('skew:',skew)
print('kurt:',kurt) | skew: [1.648218482445727, 1.1582465547989451, 0.38582932493973066, 0.5901312383613396, 0.6577926097285884]
kurt: [4.792232199483437, 2.308726578120716, -0.17635207701170597, 0.44427136934656186, 0.7513447585314599]
| MIT | Deep Dive into CLT(Section 2)/Video 2.3(Better Practice of CLT)/Final CLT (1).ipynb | codered-by-ec-council/Applied-Statistics-with-Python |
So, the 4th sample_means list with n=150 resembles a normal distribution best with lowest skew and kurt. | means_list_index= (np.abs(skew)+np.abs(kurt)).argmin()
means_list_index
sample_means= sample_means_list[means_list_index]
n= n_list[means_list_index]
len(sample_means)
sns.distplot(sample_means) | /usr/local/lib/python3.6/dist-packages/seaborn/distributions.py:2557: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).
war... | MIT | Deep Dive into CLT(Section 2)/Video 2.3(Better Practice of CLT)/Final CLT (1).ipynb | codered-by-ec-council/Applied-Statistics-with-Python |
Hence we can see the proof of CLT here, i.e. we have taken samples from the Population (Income) and their sample mean form approximately a normal distribution (with proper sample size).The curve is fairly symmetrical around the central value and the median is roughly equivalent to the mean lets check it. | # median of sample_mean
median_of_sample_means = np.median(sample_means)
median_of_sample_means
# std of sample_mean
std_sample_mean=np.std(sample_means)
std_sample_mean
# mean of a sample_mean
mean_of_sample_mean = np.mean(sample_means)
mean_of_sample_mean | _____no_output_____ | MIT | Deep Dive into CLT(Section 2)/Video 2.3(Better Practice of CLT)/Final CLT (1).ipynb | codered-by-ec-council/Applied-Statistics-with-Python |
Here we can see, the mean and median values of the sample_mean nearly equal.let's compare mean of this and a population now | print(mean_of_sample_mean, mean_pop) | 5370.229466666666 5403.459283387622
| MIT | Deep Dive into CLT(Section 2)/Video 2.3(Better Practice of CLT)/Final CLT (1).ipynb | codered-by-ec-council/Applied-Statistics-with-Python |
This mean_of_sample_means value is roughly equivalent to our population mean value assigned to the variable mean_pop. Based on the central limit theorem, this will always be the case! Equation for Calculating the standard error sampling distribution The standard deviation of sample means is more commonly called the s... | standard_error = std_pop/np.sqrt(n)
standard_error | _____no_output_____ | MIT | Deep Dive into CLT(Section 2)/Video 2.3(Better Practice of CLT)/Final CLT (1).ipynb | codered-by-ec-council/Applied-Statistics-with-Python |
Here we can see, it is nearly same as the *std_sample_mean* we obtained above.-------------*So, we can say that the **sample_means** of the total population (with a proper sample size) is an approximate and normal representation of the whole population.*----------------------------------Now let's see, the sample_means ... | sample_means_25= sample_means_list[0]
# median of sample_mean
median_of_sample_means_25 = np.median(sample_means_25)
median_of_sample_means_25
# std of sample_mean
std_sample_mean_25=np.std(sample_means_25)
std_sample_mean_25
# mean of a sample_mean
mean_of_sample_mean_25 = np.mean(sample_means_25)
mean_of_sample_mean_... | _____no_output_____ | MIT | Deep Dive into CLT(Section 2)/Video 2.3(Better Practice of CLT)/Final CLT (1).ipynb | codered-by-ec-council/Applied-Statistics-with-Python |
**Conclusion**:The standard error increases if *sample size* is decreased i.e. the distribution of *sample_means* spreads out more. Sample size = 200 | sample_means_200= sample_means_list[4]
# median of sample_mean
median_of_sample_means_200 = np.median(sample_means_200)
median_of_sample_means_200
# std of sample_mean
std_sample_mean_200=np.std(sample_means_200)
std_sample_mean_200
# mean of a sample_mean
mean_of_sample_mean_200 = np.mean(sample_means_200)
mean_of_sam... | _____no_output_____ | MIT | Deep Dive into CLT(Section 2)/Video 2.3(Better Practice of CLT)/Final CLT (1).ipynb | codered-by-ec-council/Applied-Statistics-with-Python |
Getting Started with BentoML[BentoML](http://bentoml.ai) is an open-source framework for machine learning **model serving**, aiming to **bridge the gap between Data Science and DevOps**.Data Scientists can easily package their models trained with any ML framework using BentoMl and reproduce the model for serving in pr... | # Install PyPI packages required in this guide, including BentoML
!pip install -q bentoml
!pip install -q 'scikit-learn>=0.23.2' 'pandas>=1.1.1' | _____no_output_____ | Apache-2.0 | guides/quick-start/bentoml-quick-start-guide.ipynb | andy51002000/BentoML |
Before started, let's discuss how BentoML's project structure would look like. For most use-cases, users can follow this minimal scaffoldfor deploying with BentoML to avoid any potential errors (example project structure can be found under [guides/quick-start](https://github.com/bentoml/BentoML/tree/master/guides/quick... | from sklearn import svm
from sklearn import datasets
# Load training data
iris = datasets.load_iris()
X, y = iris.data, iris.target
# Model Training
clf = svm.SVC(gamma='scale')
clf.fit(X, y) | _____no_output_____ | Apache-2.0 | guides/quick-start/bentoml-quick-start-guide.ipynb | andy51002000/BentoML |
Create a Prediction Service with BentoMLModel serving with BentoML comes after a model is trained. The first step is creating aprediction service class, which defines the models required and the inference APIs whichcontains the serving logic. Here is a minimal prediction service created for servingthe iris classifier ... | %%writefile bento_service.py
import pandas as pd
from bentoml import env, artifacts, api, BentoService
from bentoml.adapters import DataframeInput
from bentoml.frameworks.sklearn import SklearnModelArtifact
@env(infer_pip_packages=True)
@artifacts([SklearnModelArtifact('model')])
class IrisClassifier(BentoService):
... | Overwriting iris_classifier.py
| Apache-2.0 | guides/quick-start/bentoml-quick-start-guide.ipynb | andy51002000/BentoML |
This code defines a prediction service that packages a scikit-learn model and providesan inference API that expects a `pandas.Dataframe` object as its input. BentoML also supports other API input data types including `JsonInput`, `ImageInput`, `FileInput` and [more](https://docs.bentoml.org/en/latest/api/adapters.html)... | # import the IrisClassifier class defined above
from bento_service import IrisClassifier
# Create a iris classifier service instance
iris_classifier_service = IrisClassifier()
# Pack the newly trained model artifact
iris_classifier_service.pack('model', clf)
# Prepare input data for testing the prediction service
imp... | [2021-03-19 02:36:06,764] INFO - BentoService bundle 'IrisClassifier:20210319023551_84AAF6' saved to: /Users/chaoyu/bentoml/repository/IrisClassifier/20210319023551_84AAF6
| Apache-2.0 | guides/quick-start/bentoml-quick-start-guide.ipynb | andy51002000/BentoML |
BentoML stores all packaged model files under the`~/bentoml/{service_name}/{service_version}` directory by default.The BentoML file format contains all the code, files, and configs required to deploy the model for serving. REST API Model ServingTo start a REST API model server with the `IrisClassifier` saved above, us... | !bentoml serve IrisClassifier:latest | [2021-03-19 02:37:09,964] INFO - Getting latest version IrisClassifier:20210319023551_84AAF6
[2021-03-19 02:37:09,965] INFO - Starting BentoML API server in development mode..
* Serving Flask app "IrisClassifier" (lazy loading)
* Environment: production
[31m WARNING: This is a development server. Do not use it in ... | Apache-2.0 | guides/quick-start/bentoml-quick-start-guide.ipynb | andy51002000/BentoML |
If you are running this notebook from Google Colab, you can start the dev server with `--run-with-ngrok` option, to gain acccess to the API endpoint via a public endpoint managed by [ngrok](https://ngrok.com/): | !bentoml serve IrisClassifier:latest --run-with-ngrok | _____no_output_____ | Apache-2.0 | guides/quick-start/bentoml-quick-start-guide.ipynb | andy51002000/BentoML |
The `IrisClassifier` model is now served at `localhost:5000`. Use `curl` command to senda prediction request:```bashcurl -i \--header "Content-Type: application/json" \--request POST \--data '[[5.1, 3.5, 1.4, 0.2]]' \localhost:5000/predict```Or with `python` and [request library](https://requests.readthedocs.io/):```py... | !bentoml containerize IrisClassifier:latest -t iris-classifier:v1 | [2021-03-19 02:37:37,423] INFO - Getting latest version IrisClassifier:20210319023551_84AAF6
[39mFound Bento: /Users/chaoyu/bentoml/repository/IrisClassifier/20210319023551_84AAF6[0m
Containerizing IrisClassifier:20210319023551_84AAF6 with local YataiService and docker daemon from local environment-[32mBuild contain... | Apache-2.0 | guides/quick-start/bentoml-quick-start-guide.ipynb | andy51002000/BentoML |
Start a container with the docker image built in the previous step: | !docker run -p 5000:5000 iris-classifier:v1 --workers=2 | [2021-03-19 09:37:42,276] INFO - Starting BentoML API server in production mode..
[2021-03-19 09:37:42 +0000] [1] [INFO] Starting gunicorn 20.0.4
[2021-03-19 09:37:42 +0000] [1] [INFO] Listening at: http://0.0.0.0:5000 (1)
[2021-03-19 09:37:42 +0000] [1] [INFO] Using worker: sync
[2021-03-19 09:37:42 +0000] [12] [INFO]... | Apache-2.0 | guides/quick-start/bentoml-quick-start-guide.ipynb | andy51002000/BentoML |
This made it possible to deploy BentoML bundled ML models with platforms such as[Kubeflow](https://www.kubeflow.org/docs/components/serving/bentoml/),[Knative](https://knative.dev/community/samples/serving/machinelearning-python-bentoml/),[Kubernetes](https://docs.bentoml.org/en/latest/deployment/kubernetes.html), whic... | import bentoml
import pandas as pd
bento_svc = bentoml.load(saved_path)
# Test loaded bentoml service:
bento_svc.predict(test_input_df) | [2021-03-19 02:38:54,032] WARNING - Module `iris_classifier` already loaded, using existing imported module.
[2021-03-19 02:38:54,071] WARNING - pip package requirement pandas already exist
[2021-03-19 02:38:54,072] WARNING - pip package requirement scikit-learn already exist
| Apache-2.0 | guides/quick-start/bentoml-quick-start-guide.ipynb | andy51002000/BentoML |
The BentoML format is pip-installable and can be directly distributed as aPyPI package for using in python applications: | !pip install -q {saved_path}
# The BentoService class name will become packaged name
import IrisClassifier
installed_svc = IrisClassifier.load()
installed_svc.predict(test_input_df) | _____no_output_____ | Apache-2.0 | guides/quick-start/bentoml-quick-start-guide.ipynb | andy51002000/BentoML |
This also allow users to upload their BentoService to pypi.org as public python packageor to their organization's private PyPi index to share with other developers.`cd {saved_path} & python setup.py sdist upload`*You will have to configure ".pypirc" file before uploading to pypi index. You can find more information ... | !bentoml run IrisClassifier:latest predict --input '{test_input_df.to_json()}' --quiet
!bentoml run IrisClassifier:latest predict \
--input-file "./test_input.csv" --format "csv" --quiet
# run inference with the docker image built above
!docker run -v $(PWD):/tmp iris-classifier:v1 \
bentoml run /bento pred... | [1, 0, 0, 0, 2]
| Apache-2.0 | guides/quick-start/bentoml-quick-start-guide.ipynb | andy51002000/BentoML |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn.datasets
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor
from sklearn import metrics
'https://github.com/WISSAL-MN'
house_price_dataset = sklearn.datasets.load_boston()
# Lo... | _____no_output_____ | MIT | House_Price_Prediction.ipynb | WISSAL-MN/House-Price-Prediction- | |
Understanding the correlation between various features in the dataset1. Positive Correlation2. Negative Correlation | correlation = house_price_dataframe.corr()
# constructing a heatmap to nderstand the correlation
plt.figure(figsize=(10,10))
sns.heatmap(correlation, cbar=True, square=True, fmt='.1f', annot=True, annot_kws={'size':8}, cmap='Blues') | _____no_output_____ | MIT | House_Price_Prediction.ipynb | WISSAL-MN/House-Price-Prediction- |
Splitting the data and Target | X = house_price_dataframe.drop(['price'], axis=1)
Y = house_price_dataframe['price']
print(X)
print(Y) | CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX \
0 0.00632 18.0 2.31 0.0 0.538 6.575 65.2 4.0900 1.0 296.0
1 0.02731 0.0 7.07 0.0 0.469 6.421 78.9 4.9671 2.0 242.0
2 0.02729 0.0 7.07 0.0 0.469 7.185 61.1 4.9671 2.0 242.0
3 0.03237 0.0 ... | MIT | House_Price_Prediction.ipynb | WISSAL-MN/House-Price-Prediction- |
Splitting the data into Training data and Test data | X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 2)
print(X.shape, X_train.shape, X_test.shape) | (506, 13) (404, 13) (102, 13)
| MIT | House_Price_Prediction.ipynb | WISSAL-MN/House-Price-Prediction- |
Model Training | # loading the model
model = XGBRegressor()
# training the model with X_train
model.fit(X_train, Y_train) | [12:46:08] WARNING: /workspace/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.
| MIT | House_Price_Prediction.ipynb | WISSAL-MN/House-Price-Prediction- |
Evaluation | # accuracy for prediction on training data
training_data_prediction = model.predict(X_train)
print(training_data_prediction)
# R squared error
score_1 = metrics.r2_score(Y_train, training_data_prediction)
# Mean Absolute Error
score_2 = metrics.mean_absolute_error(Y_train, training_data_prediction)
print("R squared e... | R squared error : 0.9733349094832763
Mean Absolute Error : 1.145314053261634
| MIT | House_Price_Prediction.ipynb | WISSAL-MN/House-Price-Prediction- |
Visualizing the actual Prices and predicted prices | plt.scatter(Y_train, training_data_prediction)
plt.xlabel("Actual Prices")
plt.ylabel("Predicted Prices")
plt.title("Actual Price vs Preicted Price")
plt.show()
| _____no_output_____ | MIT | House_Price_Prediction.ipynb | WISSAL-MN/House-Price-Prediction- |
Prediction on Test Data | # accuracy for prediction on test data
test_data_prediction = model.predict(X_test)
# R squared error
score_1 = metrics.r2_score(Y_test, test_data_prediction)
# Mean Absolute Error
score_2 = metrics.mean_absolute_error(Y_test, test_data_prediction)
print("R squared error : ", score_1)
print('Mean Absolute Error : ', ... | R squared error : 0.9115937697657654
Mean Absolute Error : 1.9922956859364223
| MIT | House_Price_Prediction.ipynb | WISSAL-MN/House-Price-Prediction- |
Time Complexity Examples | def logarithmic_problem(N):
i = N
while i > 1:
# do something
i = i // 2 # move on
%time logarithmic_problem(10000)
def linear_problem(N):
i = N
while i > 1:
# do something
i = i - 1 # move on
%time linear_problem(10000)
def quadratic_problem(N):
i = N... | CPU times: user 5.21 s, sys: 67.3 ms, total: 5.28 s
Wall time: 5.33 s
| MIT | geekgap_webinars/notebooks/webinar_1/algorithms_data_structures.ipynb | geekgap-io/geekgap_webinars |
Problem Given an array(A) of numbers sorted in increasing order, implement a function that returns the index of a target(k) if found in A, and -1 otherwise. Brute-force solution: Linear Search | A = [5, 8, 8, 15, 16, 19, 30, 35, 40, 51]
def linear_search(A, k):
for idx, element in enumerate(A):
if element == k:
return idx
return -1
linear_search(A, 15)
linear_search(A, 100) | _____no_output_____ | MIT | geekgap_webinars/notebooks/webinar_1/algorithms_data_structures.ipynb | geekgap-io/geekgap_webinars |
Efficient solution: Binary Search | A = [5, 8, 8, 15, 16, 19, 30, 35, 40, 51]
def binary_search(A, k):
left, right = 0, len(A)-1
while left<=right:
mid = (right - left)//2 + left
if A[mid] < k:
#look on the right
left = mid+1
elif A[mid] > k:
#look on the left
right = mid-1
... | _____no_output_____ | MIT | geekgap_webinars/notebooks/webinar_1/algorithms_data_structures.ipynb | geekgap-io/geekgap_webinars |
Binary Search common bugs: BUG-1: one-off bugnot handling arrays of size=1 | A = [5, 8, 8, 15, 16, 19, 30, 35, 40, 51]
def binary_search_bug1(A, k):
left, right = 0, len(A)-1
#HERE: < instead of <=
while left<right:
mid = (right - left)//2 + left
if A[mid] < k:
#look on the right
left = mid+1
elif A[mid] > k:
#look on the ... | _____no_output_____ | MIT | geekgap_webinars/notebooks/webinar_1/algorithms_data_structures.ipynb | geekgap-io/geekgap_webinars |
BUG-2: integer overflownot handling the case where summing two integers can return an integer bigger than what the memory can take | # because python3 only imposes limits
# on float, we are going to illustrate
# this issue using floats instead of ints
import sys
right = sys.float_info.max
left = sys.float_info.max - 1000
mid = (right + left) // 2
mid
mid = (right - left)//2 + left
mid | _____no_output_____ | MIT | geekgap_webinars/notebooks/webinar_1/algorithms_data_structures.ipynb | geekgap-io/geekgap_webinars |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.