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 |
|---|---|---|---|---|---|
Define the ModelThe following example uses a standard conv-net that has 4 layers with drop-out and batch normalization between each layer. Note that we are creating the model within a `strategy.scope`. | with strategy.scope():
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.BatchNormalization(input_shape=x_train.shape[1:]))
model.add(tf.keras.layers.Conv2D(64, (5, 5), padding='same', activation='elu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))
model.add(tf.keras.l... | _____no_output_____ | Apache-2.0 | site/en/r2/guide/_tpu.ipynb | christophmeyer/docs |
Train on the TPUTo train on the TPU, we can simply call `model.compile` under the strategy scope, and then call `model.fit` to start training. In this case, we are training for 5 epochs with 60 steps per epoch, and running evaluation at the end of 5 epochs.It may take a while for the training to start, as the data and... | with strategy.scope():
model.compile(
optimizer=tf.train.AdamOptimizer(learning_rate=1e-3),
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['sparse_categorical_accuracy']
)
model.fit(
(x_train, y_train),
epochs=5,
steps_per_epoch=60,
validation_data=(x_test, y_test)... | _____no_output_____ | Apache-2.0 | site/en/r2/guide/_tpu.ipynb | christophmeyer/docs |
Check our results with InferenceNow that we are done training, we can see how well the model can predict fashion categories: | LABEL_NAMES = ['t_shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt', 'sneaker', 'bag', 'ankle_boots']
from matplotlib import pyplot
%matplotlib inline
def plot_predictions(images, predictions):
n = images.shape[0]
nc = int(np.ceil(n / 4))
f, axes = pyplot.subplots(nc, 4)
for i in range(nc * 4)... | _____no_output_____ | Apache-2.0 | site/en/r2/guide/_tpu.ipynb | christophmeyer/docs |
Forecasting experiments for GEFCOM 2012 Wind Dataset Install Libs | !pip3 install -U git+https://github.com/PYFTS/pyFTS
!pip3 install -U git+https://github.com/cseveriano/spatio-temporal-forecasting
!pip3 install -U git+https://github.com/cseveriano/evolving_clustering
!pip3 install -U git+https://github.com/cseveriano/fts2image
!pip3 install -U hyperopt
!pip3 install -U pyts
import pa... | _____no_output_____ | MIT | notebooks/thesis_experiments/20200924_eMVFTS_Wind_Energy_Raw.ipynb | cseveriano/spatio-temporal-forecasting |
Aux Functions | def normalize(df):
mindf = df.min()
maxdf = df.max()
return (df-mindf)/(maxdf-mindf)
def denormalize(norm, _min, _max):
return [(n * (_max-_min)) + _min for n in norm]
def getRollingWindow(index):
pivot = index
train_start = pivot.strftime('%Y-%m-%d')
pivot = pivot + datetime.timedelta(da... | _____no_output_____ | MIT | notebooks/thesis_experiments/20200924_eMVFTS_Wind_Energy_Raw.ipynb | cseveriano/spatio-temporal-forecasting |
Load Dataset | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import math
from sklearn.metrics import mean_squared_error
#columns names
wind_farms = ['wp1', 'wp2', 'wp3', 'wp4', 'wp5', 'wp6', 'wp7']
# read raw dataset
import pandas as pd
df = pd.read_csv('https://query.data.world/s/3zx2jusk4z6zvlg2dafqgshqp3o... | _____no_output_____ | MIT | notebooks/thesis_experiments/20200924_eMVFTS_Wind_Energy_Raw.ipynb | cseveriano/spatio-temporal-forecasting |
Forecasting Methods Persistence | def persistence_forecast(train, test, step):
predictions = []
for t in np.arange(0,len(test), step):
yhat = [test.iloc[t]] * step
predictions.extend(yhat)
return predictions
def rolling_cv_persistence(df, step):
forecasts = []
lags_list = []
limit = df.index[-1]... | _____no_output_____ | MIT | notebooks/thesis_experiments/20200924_eMVFTS_Wind_Energy_Raw.ipynb | cseveriano/spatio-temporal-forecasting |
VAR | from statsmodels.tsa.api import VAR, DynamicVAR
def evaluate_VAR_models(test_name, train, validation,target, maxlags_list):
var_results = pd.DataFrame(columns=['Order','RMSE'])
best_score, best_cfg, best_model = float("inf"), None, None
for lgs in maxlags_list:
model = VAR(train)
result... | _____no_output_____ | MIT | notebooks/thesis_experiments/20200924_eMVFTS_Wind_Energy_Raw.ipynb | cseveriano/spatio-temporal-forecasting |
e-MVFTS | from spatiotemporal.models.clusteredmvfts.fts import evolvingclusterfts
def evolvingfts_forecast(train_df, test_df, params, train_model=True):
_variance_limit = params['variance_limit']
_defuzzy = params['defuzzy']
_t_norm = params['t_norm']
_membership_threshold = params['membership_threshold']
_o... | _____no_output_____ | MIT | notebooks/thesis_experiments/20200924_eMVFTS_Wind_Energy_Raw.ipynb | cseveriano/spatio-temporal-forecasting |
MLP | from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
from keras.constraints import maxnorm
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.normalization import BatchNormalization
#... | _____no_output_____ | MIT | notebooks/thesis_experiments/20200924_eMVFTS_Wind_Energy_Raw.ipynb | cseveriano/spatio-temporal-forecasting |
MLP Parameter Tuning | from spatiotemporal.util import parameter_tuning, sampling
from spatiotemporal.util import experiments as ex
from sklearn.metrics import mean_squared_error
from hyperopt import hp
import numpy as np
mlp_space = {'choice':
hp.choice('num_layers',
[
{'layers': 'two',
},
... | Running experiment: EXP_OAHU_MLP
{'batch_size': 256, 'choice': {'layers': 'two'}, 'dropout1': 0, 'dropout2': 0.25, 'epochs': 300, 'input': ('wp1', 'wp2', 'wp3', 'wp4', 'wp5', 'wp6', 'wp7'), 'order': 3, 'output': ('wp1', 'wp2', 'wp3', 'wp4', 'wp5', 'wp6', 'wp7'), 'units1': 16, 'units2': 512}
Error : 0.11210207774258987
... | MIT | notebooks/thesis_experiments/20200924_eMVFTS_Wind_Energy_Raw.ipynb | cseveriano/spatio-temporal-forecasting |
MLP Forecasting | def mlp_multi_forecast(train_df, test_df, params):
nfeat = len(train_df.columns)
nlags = params['order']
nsteps = params.get('step',1)
nobs = nlags * nfeat
output_index = -nfeat*nsteps
train_reshaped_df = series_to_supervised(train_df, n_in=nlags, n_out=nsteps)
train_X, train_Y = tra... | _____no_output_____ | MIT | notebooks/thesis_experiments/20200924_eMVFTS_Wind_Energy_Raw.ipynb | cseveriano/spatio-temporal-forecasting |
Granular FTS | from pyFTS.models.multivariate import granular
from pyFTS.partitioners import Grid, Entropy
from pyFTS.models.multivariate import variable
from pyFTS.common import Membership
from pyFTS.partitioners import Grid, Entropy | _____no_output_____ | MIT | notebooks/thesis_experiments/20200924_eMVFTS_Wind_Energy_Raw.ipynb | cseveriano/spatio-temporal-forecasting |
Granular Parameter Tuning | granular_space = {
'npartitions': hp.choice('npartitions', [100, 150, 200]),
'order': hp.choice('order', [1, 2]),
'knn': hp.choice('knn', [1, 2, 3, 4, 5]),
'alpha_cut': hp.choice('alpha_cut', [0, 0.1, 0.2, 0.3]),
'input': hp.choice('input', [['wp1', 'wp2', 'wp3']]),
'output': hp.choice('output', [... | Running experiment: EXP_WIND_GRANULAR
{'alpha_cut': 0.1, 'input': ('wp1', 'wp2', 'wp3'), 'knn': 1, 'npartitions': 100, 'order': 1, 'output': ('wp1', 'wp2', 'wp3')}
Error : 0.11669905532137337
{'alpha_cut': 0.2, 'input': ('wp1', 'wp2', 'wp3'), 'knn': 1, 'npartitions': 200, 'order': 2, 'output': ('wp1', 'wp2', 'wp3')}
Er... | MIT | notebooks/thesis_experiments/20200924_eMVFTS_Wind_Energy_Raw.ipynb | cseveriano/spatio-temporal-forecasting |
Granular Forecasting | def granular_forecast(train_df, test_df, params):
_input = list(params['input'])
_output = list(params['output'])
_npartitions = params['npartitions']
_knn = params['knn']
_alpha_cut = params['alpha_cut']
_order = params['order']
_step = params.get('step',1)
## create explanatory varia... | _____no_output_____ | MIT | notebooks/thesis_experiments/20200924_eMVFTS_Wind_Energy_Raw.ipynb | cseveriano/spatio-temporal-forecasting |
Result Analysis | import pandas as pd
from google.colab import files
files.upload()
def createBoxplot(filename, data, xticklabels, ylabel):
# Create a figure instance
fig = plt.figure(1, figsize=(9, 6))
# Create an axes instance
ax = fig.add_subplot(111)
# Create the boxplot
bp = ax.boxplot(data, patch_artist=T... | _____no_output_____ | MIT | notebooks/thesis_experiments/20200924_eMVFTS_Wind_Energy_Raw.ipynb | cseveriano/spatio-temporal-forecasting |
Use `Lale` `AIF360` scorers to calculate and mitigate bias for credit risk AutoAI model This notebook contains the steps and code to demonstrate support of AutoAI experiments in Watson Machine Learning service. It introduces commands for bias detecting and mitigation performed with `lale.lib.aif360` module.Some famili... | !pip install -U ibm-watson-machine-learning | tail -n 1
!pip install -U scikit-learn==0.23.2 | tail -n 1
!pip install -U autoai-libs | tail -n 1
!pip install -U lale | tail -n 1
!pip install -U aif360 | tail -n 1
!pip install -U liac-arff | tail -n 1
!pip install -U cvxpy | tail -n 1
!pip install -U fairlearn | tail -n... | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
Connection to WMLAuthenticate the Watson Machine Learning service on IBM Cloud. You need to provide Cloud `API key` and `location`.**Tip**: Your `Cloud API key` can be generated by going to the [**Users** section of the Cloud console](https://cloud.ibm.com/iam/users). From that page, click your name, scroll down to th... | api_key = 'PUT_YOUR_KEY_HERE'
location = 'us-south'
wml_credentials = {
"apikey": api_key,
"url": 'https://' + location + '.ml.cloud.ibm.com'
}
from ibm_watson_machine_learning import APIClient
client = APIClient(wml_credentials) | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
Working with spacesYou need to create a space that will be used for your work. If you do not have a space, you can use [Deployment Spaces Dashboard](https://dataplatform.cloud.ibm.com/ml-runtime/spaces?context=cpdaas) to create one.- Click **New Deployment Space**- Create an empty space- Select Cloud Object Storage- S... | space_id = 'PASTE YOUR SPACE ID HERE'
client.spaces.list(limit=10)
client.set.default_space(space_id) | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
Connections to COSIn next cell we read the COS credentials from the space. | cos_credentials = client.spaces.get_details(space_id=space_id)['entity']['storage']['properties'] | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
2. Optimizer definition Training data connectionDefine connection information to COS bucket and training data CSV file. This example uses the [German Credit Risk dataset](https://raw.githubusercontent.com/IBM/watson-machine-learning-samples/master/cloud/data/credit_risk/credit_risk_training_light.csv).The code in nex... | filename = 'german_credit_data_biased_training.csv'
datasource_name = 'bluemixcloudobjectstorage'
bucketname = cos_credentials['bucket_name'] | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
Download training data from git repository and split for training and test set. | import os, wget
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
url = 'https://raw.githubusercontent.com/IBM/watson-machine-learning-samples/master/cloud/data/credit_risk/german_credit_data_biased_training.csv'
if not os.path.isfile(filename): wget.download(url)
credit_risk... | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
Create connection | conn_meta_props= {
client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {datasource_name} ",
client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(datasource_name),
client.connections.ConfigurationMetaNames.DESCRIPTION: "Connectio... | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
**Note**: The above connection can be initialized alternatively with `api_key` and `resource_instance_id`. The above cell can be replaced with:```conn_meta_props= { client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {db_name} ", client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: c... | connection_id = client.connections.get_uid(conn_details) | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
Define connection information to training data and upload train dataset to COS bucket. | from ibm_watson_machine_learning.helpers import DataConnection, S3Location
credit_risk_conn = DataConnection(
connection_asset_id=connection_id,
location=S3Location(bucket=bucketname,
path=filename))
credit_risk_conn._wml_client = client
training_data_reference=[credit_risk_conn]
cr... | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
Optimizer configurationProvide the input information for AutoAI optimizer:- `name` - experiment name- `prediction_type` - type of the problem- `prediction_column` - target column name- `scoring` - optimization metric- `daub_include_only_estimators` - estimators which will be included during AutoAI training. More avail... | from ibm_watson_machine_learning.experiment import AutoAI
experiment = AutoAI(wml_credentials, space_id=space_id)
pipeline_optimizer = experiment.optimizer(
name='Credit Risk Bias detection in AutoAI',
prediction_type=AutoAI.PredictionType.BINARY,
prediction_column='Risk',
scoring=AutoAI.Metrics.ROC_A... | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
3. Experiment runCall the `fit()` method to trigger the AutoAI experiment. You can either use interactive mode (synchronous job) or background mode (asychronous job) by specifying `background_model=True`. | run_details = pipeline_optimizer.fit(
training_data_reference=training_data_reference,
background_mode=False)
pipeline_optimizer.get_run_status()
summary = pipeline_optimizer.summary()
summary | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
Get selected pipeline modelDownload pipeline model object from the AutoAI training job. | best_pipeline = pipeline_optimizer.get_pipeline() | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
4. Bias detection and mitigationThe `fairness_info` dictionary contains some fairness-related metadata. The favorable and unfavorable label are values of the target class column that indicate whether the loan was granted or denied. A protected attribute is a feature that partitions the population into groups whose out... | fairness_info = {'favorable_labels': ['No Risk'],
'protected_attributes': [
{'feature': X.columns.get_loc('Sex'),'reference_group': ['male']},
{'feature': X.columns.get_loc('Age'), 'reference_group': [[26, 40]]}]}
fairness_info | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
Calculate fairness metrics We will calculate some model metrics. Accuracy describes how accurate is the model according to dataset. Disparate impact is defined by comparing outcomes between a privileged group and an unprivileged group, so it needs to check the protected attribute to determine group membership for the ... | import sklearn.metrics
from lale.lib.aif360 import disparate_impact, accuracy_and_disparate_impact
accuracy_scorer = sklearn.metrics.make_scorer(sklearn.metrics.accuracy_score)
print(f'accuracy {accuracy_scorer(best_pipeline, X_test.values, y_test.values):.1%}')
disparate_impact_scorer = disparate_impact(**fairness_in... | accuracy 82.4%
disparate impact 0.68
accuracy and disparate impact metric 0.26
| Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
Mitigation`Hyperopt` minimizes (best_score - score_returned_by_the_scorer), where best_score is an argument to Hyperopt and score_returned_by_the_scorer is the value returned by the scorer for each evaluation point. We will use the `Hyperopt` to tune hyperparametres of the AutoAI pipeline to get new and more fair mode... | from sklearn.linear_model import LogisticRegression as LR
from sklearn.tree import DecisionTreeClassifier as Tree
from sklearn.neighbors import KNeighborsClassifier as KNN
from lale.lib.lale import Hyperopt
from lale.lib.aif360 import FairStratifiedKFold
from lale import wrap_imported_operators
wrap_imported_operators... | 100%|██████████| 10/10 [01:13<00:00, 7.35s/trial, best loss: 0.27222222222222214]
| Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
As with any trained model, we can evaluate and visualize the result. | print(f'accuracy {accuracy_scorer(pipeline_fairer, X_test.values, y_test.values):.1%}')
print(f'disparate impact {disparate_impact_scorer(pipeline_fairer, X_test.values, y_test.values):.2f}')
print(f'accuracy and disparate impact metric {combined_scorer(pipeline_fairer, X_test.values, y_test.values):.2f}')
pipeline_fai... | accuracy 75.8%
disparate impact 0.86
accuracy and disparate impact metric 0.63
| Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
As the result demonstrates, the best model found by AI Automationhas lower accuracy and much better disparate impact as the one we sawbefore. Also, it has tuned the repair level andhas picked and tuned a classifier. These results may vary by dataset and search space. You can get source code of the created pipeline. You... | pipeline_fairer.pretty_print(ipython_display=True, show_imports=False) | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
5. Deploy and ScoreIn this section you will learn how to deploy and score Lale pipeline model using WML instance. Custom software_specification Created model is AutoAI model refined with Lale. We will create new software specification based on default Python 3.7 environment extended by `autoai-libs` package. | base_sw_spec_uid = client.software_specifications.get_uid_by_name("default_py3.7")
print("Id of default Python 3.7 software specification is: ", base_sw_spec_uid)
url = 'https://raw.githubusercontent.com/IBM/watson-machine-learning-samples/master/cloud/configs/config.yaml'
if not os.path.isfile('config.yaml'): wget.dow... | name: python37
channels:
- defaults
dependencies:
- pip:
- autoai-libs
prefix: /opt/anaconda3/envs/python37 | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
`config.yaml` file describes details of package extention. Now you need to store new package extention with `APIClient`. | meta_prop_pkg_extn = {
client.package_extensions.ConfigurationMetaNames.NAME: "Scikt with autoai-libs",
client.package_extensions.ConfigurationMetaNames.DESCRIPTION: "Pkg extension for autoai-libs",
client.package_extensions.ConfigurationMetaNames.TYPE: "conda_yml"
}
pkg_extn_details = client.package_exten... | Creating package extensions
SUCCESS
| Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
Create new software specification and add created package extention to it. | meta_prop_sw_spec = {
client.software_specifications.ConfigurationMetaNames.NAME: "Mitigated AutoAI bases on scikit spec",
client.software_specifications.ConfigurationMetaNames.DESCRIPTION: "Software specification for scikt with autoai-libs",
client.software_specifications.ConfigurationMetaNames.BASE_SOFTWA... | SUCCESS
| Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
You can get details of created software specification using `client.software_specifications.get_details(sw_spec_uid)` Store the model | model_props = {
client.repository.ModelMetaNames.NAME: "Fairer AutoAI model",
client.repository.ModelMetaNames.TYPE: 'scikit-learn_0.23',
client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: sw_spec_uid
}
feature_vector = list(X.columns)
published_model = client.repository.store_model(
model=best_pi... | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
Deployment creation | metadata = {
client.deployments.ConfigurationMetaNames.NAME: "Deployment of fairer model",
client.deployments.ConfigurationMetaNames.ONLINE: {}
}
created_deployment = client.deployments.create(published_model_uid, meta_props=metadata)
deployment_id = client.deployments.get_uid(created_deployment) | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
Deployment scoring You need to pass scoring values as input data if the deployed model. Use `client.deployments.score()` method to get predictions from deployed model. | values = X_test.values
scoring_payload = {
"input_data": [{
'values': values[:5]
}]
}
predictions = client.deployments.score(deployment_id, scoring_payload)
predictions | _____no_output_____ | Apache-2.0 | cloud/notebooks/python_sdk/experiments/autoai/Use Lale AIF360 scorers to calculate and mitigate bias for credit risk AutoAI model.ipynb | muthukumarbala07/watson-machine-learning-samples |
Trade-off between classification accuracy and reconstruction error during dimensionality reduction- Low-dimensional LSTM representations are excellent at dimensionality reduction, but are poor at reconstructing the original data- On the other hand, PCs are excellent at reconstructing the original data but these high-v... | import numpy as np
import pandas as pd
import scipy as sp
import pickle
import os
import random
import sys
# visualizations
from _plotly_future_ import v4_subplots
import plotly.offline as py
py.init_notebook_mode(connected=True)
import plotly.graph_objs as go
import plotly.subplots as tls
import plotly.figure_factory... | _____no_output_____ | MIT | clip_gru_recon.ipynb | LCE-UMD/GRU |
Mean-squared error vs number of dimensions | '''
mse
'''
ss = 'mse'
fig = _plot_fig(ss)
fig.show() | _____no_output_____ | MIT | clip_gru_recon.ipynb | LCE-UMD/GRU |
Variance captured vs number of dimensions | '''
variance
'''
ss = 'var'
fig = _plot_fig(ss)
fig.show() | _____no_output_____ | MIT | clip_gru_recon.ipynb | LCE-UMD/GRU |
R-squared vs number of dimensions | '''
r2
'''
ss = 'r2'
fig = _plot_fig(ss)
fig.show()
results = r[10]
# variance not captured by pca recon
pca_not = 1 - np.sum(results['pca_var'])
print('percent variance captured by pca components = %0.3f' %(1 - pca_not))
# this is proportional to pca mse
pca_mse = results['test_pca_mse']
# variance not captured by l... | _____no_output_____ | MIT | clip_gru_recon.ipynb | LCE-UMD/GRU |
Comparison of LSTM and PCA: classification accuracy and variance captured | '''
variance
'''
r_pc = {}
PC_DIR = 'results/clip_pca'
for k_dim in args.dims:
r_pc[k_dim] = _get_pc_results(PC_DIR, k_dim)
colors = px.colors.qualitative.Set3
#colors = ["#D55E00", "#009E73", "#56B4E9", "#E69F00"]
ss = 'var'
fig = _plot_fig_ext(ss)
fig.show()
fig.write_image('figures/fig3c.png') | dict_keys(['train', 'val', 't_train', 't_test', 'test'])
dict_keys(['train', 'val', 't_train', 't_test', 'test'])
dict_keys(['train', 'val', 't_train', 't_test', 'test'])
dict_keys(['train', 'val', 't_train', 't_test', 'test'])
| MIT | clip_gru_recon.ipynb | LCE-UMD/GRU |
State $$x = [w,n,m,s,e,o]$$ $w$: wealth level size: 20 $n$: 401k level size: 10 $m$: mortgage level size: 10 $s$: economic state size: 8 $e$: employment state size: 2 $o$: housing state: size: 2 Action$c$: consumption amount size: 20 $b$: bond investment size: 20 $k$: stock investment der... | %%time
for t in tqdm(range(T_max-1,T_min-1, -1)):
if t == T_max-1:
v,cbkha = vmap(partial(V,t,Vgrid[:,:,:,:,:,:,t]))(Xs)
else:
v,cbkha = vmap(partial(V,t,Vgrid[:,:,:,:,:,:,t+1]))(Xs)
Vgrid[:,:,:,:,:,:,t] = v.reshape(dim)
cgrid[:,:,:,:,:,:,t] = cbkha[:,0].reshape(dim)
bgrid[:,:,:,:,:,... | _____no_output_____ | MIT | 20210519/housing_force00.ipynb | dongxulee/lifeCycle |
Quadrature rules for 2.5-D resistivity modellingWe consider the evaluation of the integral$$\Phi(x, y, z) = \frac{2}{\pi} \int_0^\infty \tilde\Phi(k, y, z) \cos(k x)\, dk$$where $$\tilde\Phi(k, y, z) = K_0\left({k}{\sqrt{y^2 + z^2}}\right).$$The function $\tilde\Phi$ exhibits a different asymptotic behaviour depending... | k = logspace(-6, 4, 101);
kk = 1e-3;
u = besselk(0, k * kk);
padln = 65;
padexp = 15;
loglog(k, u, 'k', k(1:padln), -log(kk * k(1:padln)), 'r.', ...
k(end-padexp:end), exp(-kk * k(end-padexp:end))./sqrt(kk * k(end-padexp:end)), 'b.')
legend('K_0(u)', '-ln(u)', 'exp(-u)/sqrt(u)')
ylabel('\Phi(u)')
xlabel('u') | _____no_output_____ | MIT | notebooks/Quadrature.ipynb | ruboerner/notebooks |
We split the integration at $k = k_0$, $0 < k_0 < \infty$.We obtain$$\int_0^\infty \tilde\Phi(k)\,dk = \int_0^{k_0}\tilde\Phi(k)\,dk + \int_{k_0}^\infty\tilde\Phi(k)\,dk.$$ Gauss-Legendre quadratureTo avoid the singularity at $k \to 0$ for the first integral, we substitute $k'=\sqrt{k / k_0}$ and obtain with $dk = 2 ... | rmin = 1;
rp = rmin:1:100;
rp = rp(:);
k0 = 1 / (2 * rmin);
[x1, w1] = gauleg(0, 1, 17);
[x2, w2] = gaulag(7);
kn1 = k0 * x1 .* x1;
wn1 = 2 * k0 * x1 .* w1;
kn2 = k0 * (x2 + 1);
wn2 = k0 * exp(x2) .* w2;
k = [kn1(:); kn2(:)];
w = [wn1(:); wn2(:)]; | _____no_output_____ | MIT | notebooks/Quadrature.ipynb | ruboerner/notebooks |
We check the validity of the approximation by checking against the analytical solution for the homogeneous halfspace, which, in the case of $\rho = 2 \pi$ and $I = 1$, is simply$$\Phi_a(r) = \dfrac{1}{r}.$$ | k(1)
v = zeros(length(rp), 1);
for i = 1:length(rp)
v(i) = 2 / pi * sum(w .* besselk(0, k * rp(i)));
end
plot(rp, v, 'r.-', rp, 1 ./ rp, 'b')
xlabel('r in m')
ylabel('potential in V')
legend('transformed', 'analytical') | _____no_output_____ | MIT | notebooks/Quadrature.ipynb | ruboerner/notebooks |
In the following plot, we display the relative error of the approximation$$e(r) := \left(1 - \dfrac{\Phi(r)}{\Phi_a(r)}\right) \cdot 100 \%$$with respect to the (normalized) electrode distance. | plot(rp / rmin, 100 * (1 - v .* rp), '.-');
grid();
xlabel('r / r_{min}');
ylabel('rel. error in %');
ylim([-0.05 0.05]) | _____no_output_____ | MIT | notebooks/Quadrature.ipynb | ruboerner/notebooks |
Introduction to Gym toolkit Gym EnvironmentsThe centerpiece of Gym is the environment, which defines the "game" in which your reinforcement algorithm will compete. An environment does not need to be a game; however, it describes the following game-like features:* **action space**: What actions can we take on the env... | import gym
def query_environment(name):
env = gym.make(name)
spec = gym.spec(name)
print(f"Action Space: {env.action_space}")
print(f"Observation Space: {env.observation_space}")
print(f"Max Episode Steps: {spec.max_episode_steps}")
print(f"Nondeterministic: {spec.nondeterministic}")
print(f"Reward Range... | Action Space: Discrete(2)
Observation Space: Box(-3.4028234663852886e+38, 3.4028234663852886e+38, (4,), float32)
Max Episode Steps: 500
Nondeterministic: False
Reward Range: (-inf, inf)
Reward Threshold: 475.0
| Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
The CartPole-v1 environment challenges the agent to move a cart while keeping a pole balanced. The environment has an observation space of 4 continuous numbers:* Cart Position* Cart Velocity* Pole Angle* Pole Velocity At TipTo achieve this goal, the agent can take the following actions:* Push cart to the left* Push car... | import random
from typing import List
class Environment:
def __init__(self):
self.steps_left = 10
def get_observation(self) -> List[float]:
return [0.0, 0.0, 0.0]
def get_actions(self) -> List[int]:
return [0, 1]
def is_done(self) -> bool:
return self.steps_left == 0... | Total reward got: 4.6979
| Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
Frozenlake | import gym
env = gym.make("FrozenLake-v0")
env.render()
print(env.observation_space)
print(env.action_space) | Discrete(4)
| Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
| Number | Action || ------ | ------ || 0 | Left || 1 | Down || 2 | Right || 3 | Up | We can obtain the transition probability and the reward function by just typing env.P[state][action]. So, to obtain the transition probability of moving from state S to the other states by performing the action right, we can type env.... | print(env.P[0][2]) | [(0.3333333333333333, 4, 0.0, False), (0.3333333333333333, 1, 0.0, False), (0.3333333333333333, 0, 0.0, False)]
| Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
Our output is in the form of [(transition probability, next state, reward, Is terminal state?)] | state = env.reset()
env.step(1)
(next_state, reward, done, info) = env.step(1) | _____no_output_____ | Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
- **next_state** represents the next state.- **reward** represents the obtained reward.- **done** implies whether our episode has ended. That is, if the next state is a terminal state, then our episode will end, so done will be marked as True else it will be marked as False.- **info** — Apart from the transition probab... | random_action = env.action_space.sample()
next_state, reward, done, info = env.step(random_action) | _____no_output_____ | Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
**Generating an episode**The episode is the agent environment interaction starting from the initial state to the terminal state. The agent interacts with the environment by performing some action in each state. An episode ends if the agent reaches the terminal state. So, in the Frozen Lake environment, the episode will... | import gym
env = gym.make("FrozenLake-v0")
state = env.reset()
print('Time Step 0 :')
env.render()
num_timesteps = 20
for t in range(num_timesteps):
random_action = env.action_space.sample()
new_state, reward, done, info = env.step(random_action)
print ('Time Step {} :'.format(t+1))
env.render()
if done:
... | Time Step 0 :
[41mS[0mFFF
FHFH
FFFH
HFFG
Time Step 1 :
(Right)
[41mS[0mFFF
FHFH
FFFH
HFFG
Time Step 2 :
(Right)
SFFF
[41mF[0mHFH
FFFH
HFFG
Time Step 3 :
(Left)
SFFF
FHFH
[41mF[0mFFH
HFFG
Time Step 4 :
(Right)
SFFF
[41mF[0mHFH
FFFH
HFFG
Time Step 5 :
(Up)
SFFF
F[41mH[0mFH
FFFH
HFFG
| Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
Instead of generating one episode, we can also generate a series of episodes by taking some random action in each state | import gym
env = gym.make("FrozenLake-v0")
num_episodes = 10
num_timesteps = 20
for i in range(num_episodes):
state = env.reset()
print('Time Step 0 :')
env.render()
for t in range(num_timesteps):
random_action = env.action_space.sample()
new_state, reward, done, info = env.st... | _____no_output_____ | Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
Cartpole | env = gym.make("CartPole-v0")
print(env.observation_space) | Box(-3.4028234663852886e+38, 3.4028234663852886e+38, (4,), float32)
| Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
Note that all of these values are continuous, that is:- The value of the cart position ranges from -4.8 to 4.8.- The value of the cart velocity ranges from -Inf to Inf ( to ).- The value of the pole angle ranges from -0.418 radians to 0.418 radians.- The value of the pole velocity at the tip ranges from -Inf to Inf. | print(env.reset())
print(env.observation_space.high) | [4.8000002e+00 3.4028235e+38 4.1887903e-01 3.4028235e+38]
| Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
It implies that:1. The maximum value of the cart position is 4.8.2. We learned that the maximum value of the cart velocity is +Inf, and we know that infinity is not really a number, so it is represented using the largest positive real value 3.4028235e+38.3. The maximum value of the pole angle is 0.418 radians.4. The ma... | print(env.observation_space.low) | [-4.8000002e+00 -3.4028235e+38 -4.1887903e-01 -3.4028235e+38]
| Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
It states that:1. The minimum value of the cart position is -4.8.2. We learned that the minimum value of the cart velocity is -Inf, and we know that infinity is not really a number, so it is represented using the largest negative real value -3.4028235e+38.3. The minimum value of the pole angle is -0.418 radians.4. The ... | print(env.action_space) | Discrete(2)
| Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
| Number | Action || ------ | ------ || 0 | Push cart to the left || 1 | Push cart to the right | | import gym
if __name__ == "__main__":
env = gym.make("CartPole-v0")
total_reward = 0.0
total_steps = 0
obs = env.reset()
while True:
action = env.action_space.sample()
obs, reward, done, _ = env.step(action)
total_reward += reward
total_steps += 1
if done:... | Episode done in 20 steps, total reward 20.00
| Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
WrappersVery frequently, you will want to extend the environment's functionality in some generic way. For example, imagine an environment gives you some observations, but you want to accumulate them in some buffer and provide to the agent the N last observations. This is a common scenario for dynamic computer games, w... | import gym
from typing import TypeVar
import random
Action = TypeVar('Action')
class RandomActionWrapper(gym.ActionWrapper):
def __init__(self, env, epsilon=0.1):
super(RandomActionWrapper, self).__init__(env)
self.epsilon = epsilon
def action(self, action: Action) -> Action:
if rand... | Reward got: 9.00
| Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
Atari GAN | ! wget http://www.atarimania.com/roms/Roms.rar
! mkdir /content/ROM/
! unrar e /content/Roms.rar /content/ROM/
! python -m atari_py.import_roms /content/ROM/ | _____no_output_____ | Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
Normal | import random
import argparse
import cv2
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
import torchvision.utils as vutils
import gym
import gym.spaces
import numpy as np
log = gym.logger
log.set_level(gym.logger.INFO)
LATENT_VECTOR_SIZE = 100
DISC... | INFO: Making new env: Breakout-v0
INFO: Making new env: AirRaid-v0
INFO: Making new env: Pong-v0
INFO: Iter 100: gen_loss=5.454e+00, dis_loss=5.009e-02
INFO: Iter 200: gen_loss=7.054e+00, dis_loss=4.306e-03
INFO: Iter 300: gen_loss=7.568e+00, dis_loss=2.140e-03
INFO: Iter 400: gen_loss=7.842e+00, dis_loss=1.272e-03
INF... | Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
Ignite | import random
import argparse
import cv2
import torch
import torch.nn as nn
import torch.optim as optim
from ignite.engine import Engine, Events
from ignite.metrics import RunningAverage
from ignite.contrib.handlers import tensorboard_logger as tb_logger
import torchvision.utils as vutils
import gym
import gym.space... | INFO: Making new env: Breakout-v0
INFO: 100: gen_loss=5.327549, dis_loss=0.200626
INFO: 200: gen_loss=6.850880, dis_loss=0.028281
INFO: 300: gen_loss=7.435633, dis_loss=0.004672
INFO: 400: gen_loss=7.708136, dis_loss=0.001331
INFO: 500: gen_loss=8.000729, dis_loss=0.000699
INFO: 600: gen_loss=8.314868, dis_loss=0.00047... | Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
Render environments in Colab Alternative 1It is possible to visualize the game your agent is playing, even on CoLab. This section provides information on how to generate a video in CoLab that shows you an episode of the game your agent is playing. This video process is based on suggestions found [here](https://colab... | !pip install gym pyvirtualdisplay > /dev/null 2>&1
!apt-get install -y xvfb python-opengl ffmpeg > /dev/null 2>&1
!apt-get update > /dev/null 2>&1
!apt-get install cmake > /dev/null 2>&1
!pip install --upgrade setuptools 2>&1
!pip install ez_setup > /dev/null 2>&1
!pip install gym[atari] > /dev/null 2>&1
!wget http:/... | _____no_output_____ | Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
Alternative 2 | !apt-get install -y xvfb python-opengl ffmpeg > /dev/null 2>&1
!pip install colabgymrender
import gym
from colabgymrender.recorder import Recorder
env = gym.make("Breakout-v0")
directory = './video'
env = Recorder(env, directory)
observation = env.reset()
terminal = False
while not terminal:
action = env.action_spa... | _____no_output_____ | Apache-2.0 | _docs/nbs/T726861-Introduction-to-Gym-toolkit.ipynb | sparsh-ai/recohut |
Implementation of Stack Stack Attributes and MethodsBefore we implement our own Stack class, let's review the properties and methods of a Stack.The stack abstract data type is defined by the following structure and operations. A stack is structured, as described above, as an ordered collection of items where items are... | class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(se... | _____no_output_____ | MIT | code/algorithms/course_udemy_1/Stacks, Queues and Deques/Implementation of Stack.ipynb | vicb1/miscellaneous |
Let's try it out! | s = Stack()
print s.isEmpty()
s.push(1)
s.push('two')
s.peek()
s.push(True)
s.size()
s.isEmpty()
s.pop()
s.pop()
s.size()
s.pop()
s.isEmpty() | _____no_output_____ | MIT | code/algorithms/course_udemy_1/Stacks, Queues and Deques/Implementation of Stack.ipynb | vicb1/miscellaneous |
| Name | Description | Date| :- |-------------: | :-:|__Reza Hashemi__| __Function approximation by linear model and deep network LOOP test__. | __On 10th of August 2019__ Function approximation with linear models and neural network* Are Linear models sufficient for approximating transcedental functions? What about p... | import numpy as np
import pandas as pd
import math
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | BSD-2-Clause | Function Approximation by Neural Network/Function approximation by linear model and deep network LOOP test.ipynb | rezapci/Machine-Learning |
Global variables for the program | N_points = 100 # Number of points for constructing function
x_min = 1 # Min of the range of x (feature)
x_max = 25 # Max of the range of x (feature)
noise_mean = 0 # Mean of the Gaussian noise adder
noise_sd = 10 # Std.Dev of the Gaussian noise adder
test_set_fraction = 0.2 | _____no_output_____ | BSD-2-Clause | Function Approximation by Neural Network/Function approximation by linear model and deep network LOOP test.ipynb | rezapci/Machine-Learning |
Generate feature and output vector for a non-linear function with transcedental termsThe ground truth or originating function is as follows:$$ y=f(x)= (20x+3x^2+0.1x^3).sin(x).e^{-0.1x}+\psi(x) $$$$ {OR} $$$$ y=f(x)= (20x+3x^2+0.1x^3)+\psi(x) $$$${where,}\ \psi(x) : {\displaystyle f(x\;|\;\mu ,\sigma ^{2})={\frac {1}{... | # Definition of the function with exponential and sinusoidal terms
def func_trans(x):
result = (20*x+3*x**2+0.1*x**3)*np.sin(x)*np.exp(-0.1*x)
return (result)
# Definition of the function without exponential and sinusoidal terms i.e. just the polynomial
def func_poly(x):
result = 20*x+3*x**2+0.1*x**3
re... | _____no_output_____ | BSD-2-Clause | Function Approximation by Neural Network/Function approximation by linear model and deep network LOOP test.ipynb | rezapci/Machine-Learning |
Plot the function(s), both the ideal characteristic and the observed output (with process and observation noise) | df.plot.scatter('X','y',title='True process and measured samples\n',
grid=True,edgecolors=(0,0,0),c='blue',s=60,figsize=(10,6))
plt.plot(x_smooth,y_smooth,'k') | _____no_output_____ | BSD-2-Clause | Function Approximation by Neural Network/Function approximation by linear model and deep network LOOP test.ipynb | rezapci/Machine-Learning |
Import scikit-learn librares and prepare train/test splits | from sklearn.linear_model import LinearRegression
from sklearn.linear_model import LassoCV
from sklearn.linear_model import RidgeCV
from sklearn.ensemble import AdaBoostRegressor
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_p... | _____no_output_____ | BSD-2-Clause | Function Approximation by Neural Network/Function approximation by linear model and deep network LOOP test.ipynb | rezapci/Machine-Learning |
Polynomial model with LASSO/Ridge regularization (pipelined) with lineary spaced samples** This is an advanced machine learning method which prevents over-fitting by penalizing high-valued coefficients i.e. keep them bounded ** | # Regression model parameters
ridge_alpha = tuple([10**(x) for x in range(-3,0,1) ]) # Alpha (regularization strength) of ridge regression
# Alpha (regularization strength) of LASSO regression
lasso_eps = 0.0001
lasso_nalpha=20
lasso_iter=5000
# Min and max degree of polynomials features to consider
degree_min = 2
deg... | _____no_output_____ | BSD-2-Clause | Function Approximation by Neural Network/Function approximation by linear model and deep network LOOP test.ipynb | rezapci/Machine-Learning |
1-hidden layer (Shallow) network | import tensorflow as tf
learning_rate = 1e-6
training_epochs = 150000
n_input = 1 # Number of features
n_output = 1 # Regression output is a number only
n_hidden_layer = 100 # layer number of features
weights = {
'hidden_layer': tf.Variable(tf.random_normal([n_input, n_hidden_layer])),
'out': tf.Variable(tf... | _____no_output_____ | BSD-2-Clause | Function Approximation by Neural Network/Function approximation by linear model and deep network LOOP test.ipynb | rezapci/Machine-Learning |
Deep Neural network for regression Import and declaration of variables | import tensorflow as tf
learning_rate = 1e-6
training_epochs = 15000
n_input = 1 # Number of features
n_output = 1 # Regression output is a number only
n_hidden_layer_1 = 30 # Hidden layer 1
n_hidden_layer_2 = 30 # Hidden layer 2 | _____no_output_____ | BSD-2-Clause | Function Approximation by Neural Network/Function approximation by linear model and deep network LOOP test.ipynb | rezapci/Machine-Learning |
Weights and bias variable | # Store layers weight & bias as Variables classes in dictionaries
weights = {
'hidden_layer_1': tf.Variable(tf.random_normal([n_input, n_hidden_layer_1])),
'hidden_layer_2': tf.Variable(tf.random_normal([n_hidden_layer_1, n_hidden_layer_2])),
'out': tf.Variable(tf.random_normal([n_hidden_layer_2, n_output])... | _____no_output_____ | BSD-2-Clause | Function Approximation by Neural Network/Function approximation by linear model and deep network LOOP test.ipynb | rezapci/Machine-Learning |
Input data as placeholder | # tf Graph input
x = tf.placeholder("float32", [None,n_input])
y = tf.placeholder("float32", [None,n_output]) | _____no_output_____ | BSD-2-Clause | Function Approximation by Neural Network/Function approximation by linear model and deep network LOOP test.ipynb | rezapci/Machine-Learning |
Hidden and output layers definition (using TensorFlow mathematical functions) | # Hidden layer with activation
layer_1 = tf.add(tf.matmul(x, weights['hidden_layer_1']),biases['hidden_layer_1'])
layer_1 = tf.sin(layer_1)
layer_2 = tf.add(tf.matmul(layer_1, weights['hidden_layer_2']),biases['hidden_layer_2'])
layer_2 = tf.nn.relu(layer_2)
# Output layer with linear activation
ops = tf.add(tf.matmu... | _____no_output_____ | BSD-2-Clause | Function Approximation by Neural Network/Function approximation by linear model and deep network LOOP test.ipynb | rezapci/Machine-Learning |
Gradient descent optimizer for training (backpropagation):For the training of the neural network we need to perform __backpropagation__ i.e. propagate the errors, calculated by this cost function, backwards through the layers all the way up to the input weights and bias in order to adjust them accordingly (minimize th... | # Define loss and optimizer
cost = tf.reduce_mean(tf.squared_difference(ops,y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost) | _____no_output_____ | BSD-2-Clause | Function Approximation by Neural Network/Function approximation by linear model and deep network LOOP test.ipynb | rezapci/Machine-Learning |
TensorFlow Session for training and loss estimation | from tqdm import tqdm
import time
# Initializing the variables
init = tf.global_variables_initializer()
# Empty lists for book-keeping purpose
epoch=0
log_epoch = []
epoch_count=[]
acc=[]
loss_epoch=[]
r2_DNN = []
test_size = []
for i in range(5):
X_train, X_test, y_train, y_test = train_test_split(df['X'], df['y... | C:\Users\Tirtha\Python\Anaconda3\lib\site-packages\ipykernel_launcher.py:19: FutureWarning: reshape is deprecated and will raise in a subsequent release. Please use .values.reshape(...) instead
C:\Users\Tirtha\Python\Anaconda3\lib\site-packages\ipykernel_launcher.py:20: FutureWarning: reshape is deprecated and will rai... | BSD-2-Clause | Function Approximation by Neural Network/Function approximation by linear model and deep network LOOP test.ipynb | rezapci/Machine-Learning |
Plot R2 score corss-validation results | plt.figure(figsize=(10,6))
plt.title("\nR2-score for cross-validation runs of \ndeep (2-layer) neural network\n",fontsize=25)
plt.xlabel("\nCross-validation run with random test/train split #",fontsize=15)
plt.ylabel("R2 score (test set)\n",fontsize=15)
plt.scatter([i+1 for i in range(5)],r2_DNN,edgecolors='k',s=100,c=... | _____no_output_____ | BSD-2-Clause | Function Approximation by Neural Network/Function approximation by linear model and deep network LOOP test.ipynb | rezapci/Machine-Learning |
Controlling Flow with Conditional StatementsNow that you've learned how to create conditional statements, let's learn how to use them to control the flow of our programs. This is done with `if`, `elif`, and `else` statements. The `if` Statement What if we wanted to check if a number was divisible by 2 and if so the... | # Let's translate this into Python code
def check_evenness(A):
if A % 2 == 0:
print(f"A ({A:02}) is even!")
for i in range(1, 11):
check_evenness(i)
# You can do multiple if statements and they're executed sequentially
A = 10
if A > 0:
print('A is positive')
if A % 2 == 0:
print('A is even!') | A is positive
A is even!
| MIT | Lecture Material/07_Conditional_Logic_and_Control_Flow/07.3_ControllingFlowWithConditionalStatements.ipynb | knherrera/pcc-cis-012-intro-to-programming-python |
The `else` StatementBut what if we wanted to know if the number was even OR odd? Let's diagram that out: Again, translating this to pseudocode, we're going to use the 'else' statement:```textif A is even: print "A is even"else: print "A is odd"``` | # Let's translate this into Python code
def check_evenness(A):
if A % 2 == 0:
print(f"A ({A:02}) is even!")
else:
print(f'A ({A:02}) is odd!')
for i in range(1, 11):
check_evenness(i) | A (01) is odd!
A (02) is even!
A (03) is odd!
A (04) is even!
A (05) is odd!
A (06) is even!
A (07) is odd!
A (08) is even!
A (09) is odd!
A (10) is even!
| MIT | Lecture Material/07_Conditional_Logic_and_Control_Flow/07.3_ControllingFlowWithConditionalStatements.ipynb | knherrera/pcc-cis-012-intro-to-programming-python |
The 'else if' or `elif` StatementWhat if we wanted to check if A is divisible by 2 or 3? Let's diagram that out:  Again, translating this into psuedocode, we're going to use the 'else if' statement.```textif A is divisible by 2: print "2 divides A"else if A is divisible by 3: p... | # Let's translate this into Python code
def check_divisible_by_2_and_3(A):
if A % 2 == 0:
print(f"2 divides A ({A:02})!")
# else if in Python is elif
elif A % 3 == 0:
print(f'3 divides A ({A:02})!')
else:
print(f'A ({A:02}) is not divisible by 2 or 3)')
for i in ra... | A (01) is not divisible by 2 or 3)
2 divides A (02)!
3 divides A (03)!
2 divides A (04)!
A (05) is not divisible by 2 or 3)
2 divides A (06)!
A (07) is not divisible by 2 or 3)
2 divides A (08)!
3 divides A (09)!
2 divides A (10)!
| MIT | Lecture Material/07_Conditional_Logic_and_Control_Flow/07.3_ControllingFlowWithConditionalStatements.ipynb | knherrera/pcc-cis-012-intro-to-programming-python |
Order MattersWhen chaining conditionals, you need to be careful how you order them. For example, what if we wanted te check if a number is divisible by 2, 3, or both:  | # Let's translate this into Python code
def check_divisible_by_2_and_3(A):
if A % 2 == 0:
print(f"2 divides A ({A:02})!")
elif A % 3 == 0:
print(f'3 divides A ({A:02})!')
elif A % 2 == 0 and A % 3 == 0:
print(f'2 and 3 divides A ({A:02})!')
else:
print(f"2 or 3 doesn't d... | 2 or 3 doesn't divide A (01)
2 divides A (02)!
3 divides A (03)!
2 divides A (04)!
2 or 3 doesn't divide A (05)
2 divides A (06)!
2 or 3 doesn't divide A (07)
2 divides A (08)!
3 divides A (09)!
2 divides A (10)!
| MIT | Lecture Material/07_Conditional_Logic_and_Control_Flow/07.3_ControllingFlowWithConditionalStatements.ipynb | knherrera/pcc-cis-012-intro-to-programming-python |
Wait! we would expect that 6, which is divisible by both 2 and 3 to show that! Looking back at the graphic, we can see that the flow is checking for 2 first, and since that's true we follow that path first. Let's make a correction to our diagram to fix this:  | # Let's translate this into Python code
def check_divisible_by_2_and_3(A):
if A % 2 == 0 and A % 3 == 0:
print(f'2 and 3 divides A ({A:02})!')
elif A % 3 == 0:
print(f'3 divides A ({A:02})!')
elif A % 2 == 0:
print(f"2 divides A ({A:02})!")
else:
print(f"2 or 3 doesn't d... | 2 or 3 doesn't divide A (01)
2 divides A (02)!
3 divides A (03)!
2 divides A (04)!
2 or 3 doesn't divide A (05)
2 and 3 divides A (06)!
2 or 3 doesn't divide A (07)
2 divides A (08)!
3 divides A (09)!
2 divides A (10)!
| MIT | Lecture Material/07_Conditional_Logic_and_Control_Flow/07.3_ControllingFlowWithConditionalStatements.ipynb | knherrera/pcc-cis-012-intro-to-programming-python |
**NOTE:** Always put your most restrictive conditional at the top of your if statements and then work your way down to the least restrictive. In-Class Assignments- Create a funcition that takes two inputs variables `A` and `divisor`. Check if `divisor` divides into `A`. If it does, ... | def is_divisible(A, divisor):
if A % divisor == 0:
print(f'{A} is divided by {divisor}')
A = 37
# this is actually a crude way to find if the number is prime
for i in range(2, int(A / 2)):
is_divisible(A, i)
# notice that nothing was printed? That's because 37 is prime
B = 27
for i ... | apple, peach, is found within the string
| MIT | Lecture Material/07_Conditional_Logic_and_Control_Flow/07.3_ControllingFlowWithConditionalStatements.ipynb | knherrera/pcc-cis-012-intro-to-programming-python |
Example 4.1Let \{0,1,2,3\} denote the actions \{up, right, down, left\} respectively. | import numpy as np
class gridworld:
def __init__(self):
self.terminal_state = [0,15]
self.action = [0,1,2,3]
self.value = np.zeros(16)
self.reward = -1
def next_state(self, s, a):
if s in self.terminal_state:
return s
if a == 0:
s = s ... | The state value for 1th iteration:
[[ 0. -1. -1. -1.]
[-1. -1. -1. -1.]
[-1. -1. -1. -1.]
[-1. -1. -1. 0.]]
The greedy policy for 1th iteration:
[[0. 0. 0. 0. ]
[0. 0. 0. 1. ]
[0.25 0.25 0.25 0.25]
[0.25 0.25 0.25 0.25]
[1. 0. 0. 0. ]
[0.25 0.25 0.25 0.25]
[0.25 0.25 0.25 0.25]
[0.25 0... | MIT | example4.1/example4.1.ipynb | jerryzenghao/ReinformanceLearning |
Laboratorio 8 | import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import plot_confusion_matrix
%matplotlib inline
digits_X, digits_y = datasets.load_digits(return_X_y=True, as_fr... | _____no_output_____ | MIT | labs/lab08.ipynb | Flipom/mat281_portfolio |
Ejercicio 1(1 pto.)Utilizando todos los datos, ajusta un modelo de regresión logística a los datos de dígitos. No agregues intercepto y define un máximo de iteraciones de 400.Obtén el _score_ y explica el tan buen resultado. | logistic = LogisticRegression(solver="lbfgs", max_iter=400, fit_intercept=False)
fit=logistic.fit(digits_X, digits_y)
print(f"El score del modelo de regresión logística es {fit.score(digits_X, digits_y)}") | El score del modelo de regresión logística es 1.0
| MIT | labs/lab08.ipynb | Flipom/mat281_portfolio |
__Respuesta:__ Supongo que es porque no estamos usando los datos originales, y no otros datos predecidos a partir de los originales Ejercicio 2(1 pto.)Utilizando todos los datos, ¿Cuál es la mejor elección del parámetro $k$ al ajustar un modelo kNN a los datos de dígitos? Utiliza valores $k=2, ..., 10$. | for k in range(2, 11):
kNN = KNeighborsClassifier(n_neighbors=k)
fit=kNN.fit(digits_X, digits_y)
print(f"El score del modelo de kNN con k={k} es {fit.score(digits_X, digits_y)}") | El score del modelo de kNN con k=2 es 0.9910962715637173
El score del modelo de kNN con k=3 es 0.993322203672788
El score del modelo de kNN con k=4 es 0.9922092376182526
El score del modelo de kNN con k=5 es 0.9905397885364496
El score del modelo de kNN con k=6 es 0.989983305509182
El score del modelo de kNN con k=7 es... | MIT | labs/lab08.ipynb | Flipom/mat281_portfolio |
__Respuesta:__ El caso k=3, porque es el mas cercano a 1. Ejercicio 3(1 pto.)Grafica la matriz de confusión normalizada por predicción de ambos modelos (regresión logística y kNN con la mejor elección de $k$).¿Qué conclusión puedes sacar?Hint: Revisa el argumento `normalize` de la matriz de confusión. | plot_confusion_matrix(logistic, digits_X, digits_y, normalize='true');
best_knn = KNeighborsClassifier(n_neighbors=3)
B_kNN = best_knn.fit(digits_X, digits_y)
plot_confusion_matrix(B_kNN, digits_X, digits_y, normalize='true'); | _____no_output_____ | MIT | labs/lab08.ipynb | Flipom/mat281_portfolio |
__Respuesta:__ Que la primera matriz es una mejor prediccion que la segunda, esto porque se pudo obtener una matriz diagonal con, asumo, menor cantidad de errores comparado a los valores que no se encuentran en la diagonal y que son distintos de 0 en el segundo caso. Ejercicio 4(1 pto.)Escoge algún registro donde kNN ... | neigh_tt = KNeighborsClassifier(n_neighbors=5)
neigh_tt.fit(digits_X, digits_y) | _____no_output_____ | MIT | labs/lab08.ipynb | Flipom/mat281_portfolio |
El valor real del registro seleccionado es | i = 5
neigh_tt.predict(digits_X.iloc[[i], :]) | _____no_output_____ | MIT | labs/lab08.ipynb | Flipom/mat281_portfolio |
Mentras que la predicción dada por kNN es | neigh_tt.predict_proba(digits_X.iloc[[i], :]) | _____no_output_____ | MIT | labs/lab08.ipynb | Flipom/mat281_portfolio |
A continuación la imagen | plt.imshow(digits_X.loc[[i], :].to_numpy().reshape(8, 8), cmap=plt.cm.gray_r, interpolation='nearest'); | _____no_output_____ | MIT | labs/lab08.ipynb | Flipom/mat281_portfolio |
**Spit some [tensor] flow**We need to learn the intricacies of tensorflow to master deep learning`Let's get this over with` | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
import cv2
print(tf.__version__)
def evaluation_tf(report, y_test, y_pred, classes):
plt.plot(report.history['loss'], label = 'training_loss')
plt.plot(report.history['val_loss'], label = 'validation_loss')
plt.legend()... | _____no_output_____ | MIT | Tensorflow_2X_Notebooks/Demo26_CNN_CIFAR10_DataAugmentation.ipynb | mahnooranjum/Tensorflow_DeepLearning |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.