input
stringlengths 6
17.2k
| output
stringclasses 1
value | instruction
stringclasses 1
value |
---|---|---|
<s> import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__))))
from .bin.aion_pipeline import aion_train_model
<s> import argparse
import sys
import os
import subprocess
INSTALL = 'install'
LINUXINSTALL = 'linuxinstall'
FE_MIGRATE = 'migrateappfe'
LAUNCH_KAFKA = 'launchkafkaconsumer'
RUN_LOCAL_MLAC_PIPELINE = 'runpipelinelocal'
BUILD_MLAC_CONTAINER = 'buildmlaccontainerlocal'
CONVERT_MODEL = 'convertmodel'
START_MLFLOW = 'mlflow'
COMMON_SERVICE = 'service'
TRAINING = 'training'
TRAINING_AWS = 'trainingonaws'
TRAINING_DISTRIBUTED = 'distributedtraining'
START_APPF = 'appfe'
ONLINE_TRAINING = 'onlinetraining'
TEXT_SUMMARIZATION = 'textsummarization'
GENERATE_MLAC = 'generatemlac'
AWS_TRAINING = 'awstraining'
LLAMA_7B_TUNING = 'llama7btuning'
LLM_PROMPT = 'llmprompt'
LLM_TUNING = 'llmtuning'
LLM_PUBLISH = 'llmpublish'
LLM_BENCHMARKING = 'llmbenchmarking'
TELEMETRY_PUSH = 'pushtelemetry'
def aion_aws_training(confFile):
from hyperscalers.aion_aws_training import awsTraining
status = awsTraining(confFile)
print(status)
def aion_training(confFile):
from bin.aion_pipeline import aion_train_model
status = aion_train_model(confFile)
print(status)
def aion_awstraining(config_file):
from hyperscalers import aws_instance
print(config_file)
aws_instance.training(config_file)
def aion_generatemlac(ConfFile):
from bin.aion_mlac import generate_mlac_code
status = generate_mlac_code(ConfFile)
print(status)
def aion_textsummarization(confFile):
from bin.aion_text_summarizer import aion_textsummary
status = aion_textsummary(confFile)
def aion_oltraining(confFile):
from bin.aion_online_pipeline import aion_ot_train_model
status = aion_ot_train_model(confFile)
print(status)
def do_telemetry_sync():
from appbe.telemetry import SyncTelemetry
SyncTelemetry()
def aion_llm_publish(cloudconfig,instanceid,hypervisor,model,usecaseid,region,image):
from llm.llm_inference import LLM_publish
LLM_publish(cloudconfig,instanceid,hypervisor,model,usecaseid,region,image)
def aion_migratefe(operation):
import os
import sys
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'appfe.ux.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
argi=[]
argi.append(os.path.abspath(__file__))
argi.append(operation)
execute_from_command_line(argi)
def aion_appfe(url,port):
#manage_location = os.path.join(os.path.dirname(os.path.abspath(__file__)),'manage.py')
#subprocess.check_call([sys.executable,manage_location, "runserver","%s:%s"%(url,port)])
import os
import sys
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'appfe.ux.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
argi=[]
argi.append(os.path.abspath(__file__))
argi.append('runaion')
argi.append("%s:%s"%(url,port))
execute_from_command_line(argi)
def aion_linux_install(version):
from install import linux_dependencies
linux_dependencies.process(version)
def aion_install(version):
from install import dependencies
dependencies.process(version)
def aion_service(ip,port,username,password):
from bin.aion_service import start_server
start_server(ip,port,username,password)
def aion_distributedLearning(confFile):
from distributed_learning import learning
learning.training(confFile)
def aion_launchkafkaconsumer():
from mlops import kafka_consumer
kafka_consumer.launch_kafka_consumer()
def aion_start_mlflow():
from appbe.dataPath import DEPLOY_LOCATION
import platform
import shutil
from os.path import expanduser
mlflowpath = os.path.normpath(os.path.join(os.path.dirname(__file__),'..','..','..','Scripts','mlflow.exe'))
print(mlflowpath)
home = expanduser("~")
if platform.system() == 'Windows':
DEPLOY_LOCATION = os.path.join(DEPLOY_LOCATION,'mlruns')
outputStr = subprocess.Popen([sys.executable, mlflowpath,"ui", "--backend-store-uri","file:///"+DEPLOY_LOCATION])
else:
DEPLOY_LOCATION = os.path.join(DEPLOY_LOCATION,'mlruns')
subprocess.check_call(['mlflow',"ui","-h","0.0.0.0","--backend-store-uri","file:///"+DEPLOY_LOCATION])
def aion_model_conversion(config_file):
from conversions import model_convertions
model_convertions.convert(config_file)
def aion_model_buildMLaCContainer(config):
from mlops import build_container
build_container.local_docker_build(config)
def aion_model_runpipelinelocal(config):
from mlops import local_pipeline
local_pipeline.run_pipeline(config)
def aion_llm_tuning(config):
from llm.llm_tuning import run
run(config)
def aion_llm_prompt(cloudconfig,instanceid,prompt):
from llm.aws_instance_api import LLM_predict
LLM_predict(cloudconfig,instanceid,prompt)
def llm_bench_marking(hypervisor,instanceid,model,usecaseid,eval):
print(eval)
from llm.bench_marking import bench_mark
bench_mark(hypervisor,instanceid,model,usecaseid,eval)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--configPath', help='Config File Path')
parser.add_argument('-i', '--instanceid', help='instanceid')
parser.add_argument('-hv', '--hypervisor', help='hypervisor')
parser.add_argument('-md', '--model', help='model')
parser.add_argument('-uc', '--usecase', help='usecase')
parser.add_argument('-cc', '--cloudConfigPath', help='Cloud Config File Path')
parser.add_argument('-m', '--module', help='MODULE=TRAINING, APPFE, ONLINETRAINING,DISTRIBUTEDTRAINING')
parser.add_argument('-ip', '--ipaddress', help='URL applicable only for APPFE method ')
parser.add_argument('-p', '--port', help='APP Front End Port applicable only for APPFE method ')
parser.add_argument('-ac', '--appfecommand', help='APP Front End Command ')
parser.add_argument('-un','--username', help="USERNAME")
parser.add_argument('-passw','--password', help="PASSWORD")
parser.add_argument('-j', '--jsoninput', help='JSON Input')
parser.add_argument('-v', '--version', help='Installer Version')
parser.add_argument('-pf', '--prompt', help='Prompt File')
parser.add_argument('-r', '--region', help='REGION NAME')
parser.add_argument('-im', '--image', help='IMAGE NAME')
parser.add_argument('-e', '--eval', help='evaluation for code or doc', default='doc')
args = parser.parse_args()
if args.module.lower() == TRAINING:
aion_training(args.configPath)
elif args.module.lower() == TRAINING_AWS:
aion_awstraining(args.configPath)
elif args.module.lower() == TRAINING_DISTRIBUTED:
aion_distributedLearning(args.configPath)
elif args.module.lower() == START_APPF:
aion_appfe(args.ipaddress,args.port)
elif args.module.lower() == ONLINE_TRAINING:
aion_oltraining(args.configPath)
elif args.module.lower() == TEXT_SUMMARIZATION:
aion_textsummarization(args.configPath)
elif args.module.lower() == GENERATE_MLAC:
aion_generatemlac(args.configPath)
elif args.module.lower() == COMMON_SERVICE:
aion_service(args.ipaddress,args.port,args.username,args.password)
elif args.module.lower() == START_MLFLOW:
aion_mlflow()
elif args.module.lower() == CONVERT_MODEL:
aion_model_conversion(args.configPath)
elif args.module.lower() == BUILD_MLAC_CONTAINER:
aion_model_buildMLaCContainer(args.jsoninput)
elif args.module.lower() == RUN_LOCAL_MLAC_PIPELINE:
aion_model_runpipelinelocal(args.jsoninput)
elif args.module.lower() == LAUNCH_KAFKA:
aion_launchkafkaconsumer()
elif args.module.lower() == INSTALL:
aion_install(args.version)
elif args.module.lower() == LINUXINSTALL:
aion_linux_install(args.version)
elif args.module.lower() == FE_MIGRATE:
aion_migratefe('makemigrations')
aion_migratefe('migrate')
elif args.module.lower() == AWS_TRAINING:
aion_aws_training(args.configPath)
elif args.module.lower() == LLAMA_7B_TUNING:
aion_llm_tuning(args.configPath)
elif args.module.lower() == LLM_TUNING:
aion_llm_tuning(args.configPath)
elif args.module.lower() == LLM_PROMPT:
aion_llm_prompt(args.cloudConfigPath,args.instanceid,args.prompt)
elif args.module.lower() == LLM_PUBLISH:
aion_llm_publish(args.cloudConfigPath,args.instanceid,args.hypervisor,args.model,args.usecase,args.region,args.image)
elif args.module.lower() == LLM_BENCHMARKING:
llm_bench_marking(args.hypervisor,args.instanceid,args.model,args.usecase, args.eval)
elif args.module.lower() == TELEMETRY_PUSH:
do_telemetry_sync()<s><s> import numpy as np
from scipy.stats import norm
from sklearn.metrics import mean_squared_error, r2_score
from ..utils.misc import fitted_ucc_w_nullref
def picp(y_true, y_lower, y_upper):
"""
Prediction Interval Coverage Probability (PICP). Computes the fraction of samples for which the grounds truth lies
within predicted interval. Measures the prediction interval calibration for regression.
Args:
y_true: Ground truth
y_lower: predicted lower bound
y_upper: predicted upper bound
Returns:
float: the fraction of samples for which the grounds truth lies within predicted interval.
"""
satisfies_upper_bound = y_true <= y_upper
satisfies_lower_bound = y_true >= y_lower
return np.mean(satisfies_upper_bound * satisfies_lower_bound)
def mpiw(y_lower, y_upper):
"""
Mean Prediction Interval Width (MPIW). Computes the average width of the the prediction intervals. Measures the
sharpness of intervals.
Args:
y_lower: predicted lower bound
y_upper: predicted upper bound
Returns:
float: the average width the prediction interval across samples.
"""
return np.mean(np.abs(y_lower - y_upper))
def auucc_gain(y_true, y_mean, y_lower, y_upper):
""" Computes the Area Under the Uncertainty Characteristics Curve (AUUCC) gain wrt to a null reference
with constant band.
Args:
y_true: Ground truth
y_mean: predicted mean
y_lower: predicted lower bound
y_upper: predicted upper bound
Returns:
float: AUUCC gain
"""
u = fitted_ucc_w_nullref(y_true, y_mean, y_lower, y_upper)
auucc = u.get_AUUCC()
assert(isinstance(auucc, list) and len(auucc) == 2), "Failed to calculate auucc gain"
assert (not np.isclose(auucc[1], 0.)), "Failed to calculate auucc gain"
auucc_gain = (auucc[1]-auucc[0])/auucc[0]
return auucc_gain
def negative_log_likelihood_Gaussian(y_true, y_mean, y_lower, y_upper):
""" Computes Gaussian negative_log_likelihood assuming symmetric band around the mean.
Args:
y_true: Ground truth
y_mean: predicted mean
y_lower: predicted lower bound
y_upper: predicted upper bound
Returns:
float: nll
"""
y_std = (y_upper - y_lower) / 4.0
nll = np.mean(-norm.logpdf(y_true.squeeze(), loc=y_mean.squeeze(), scale=y_std.squeeze()))
return nll
def compute_regression_metrics(y_true, y_mean, | ||
y_lower, y_upper, option="all", nll_fn=None):
"""
Computes the metrics specified in the option which can be string or a list of strings. Default option `all` computes
the ["rmse", "nll", "auucc_gain", "picp", "mpiw", "r2"] metrics.
Args:
y_true: Ground truth
y_mean: predicted mean
y_lower: predicted lower bound
y_upper: predicted upper bound
option: string or list of string contained the name of the metrics to be computed.
nll_fn: function that evaluates NLL, if None, then computes Gaussian NLL using y_mean and y_lower.
Returns:
dict: dictionary containing the computed metrics.
"""
assert y_true.shape == y_mean.shape, "y_true shape: {}, y_mean shape: {}".format(y_true.shape, y_mean.shape)
assert y_true.shape == y_lower.shape, "y_true shape: {}, y_mean shape: {}".format(y_true.shape, y_lower.shape)
assert y_true.shape == y_upper.shape, "y_true shape: {}, y_mean shape: {}".format(y_true.shape, y_upper.shape)
results = {}
if not isinstance(option, list):
if option == "all":
option_list = ["rmse", "nll", "auucc_gain", "picp", "mpiw", "r2"]
else:
option_list = [option]
if "rmse" in option_list:
results["rmse"] = mean_squared_error(y_true, y_mean, squared=False)
if "nll" in option_list:
if nll_fn is None:
nll = negative_log_likelihood_Gaussian(y_true, y_mean, y_lower, y_upper)
results["nll"] = nll
else:
results["nll"] = np.mean(nll_fn(y_true))
if "auucc_gain" in option_list:
gain = auucc_gain(y_true, y_mean, y_lower, y_upper)
results["auucc_gain"] = gain
if "picp" in option_list:
results["picp"] = picp(y_true, y_lower, y_upper)
if "mpiw" in option_list:
results["mpiw"] = mpiw(y_lower, y_upper)
if "r2" in option_list:
results["r2"] = r2_score(y_true, y_mean)
return results
def _check_not_tuple_of_2_elements(obj, obj_name='obj'):
"""Check object is not tuple or does not have 2 elements."""
if not isinstance(obj, tuple) or len(obj) != 2:
raise TypeError('%s must be a tuple of 2 elements.' % obj_name)
def plot_uncertainty_distribution(dist, show_quantile_dots=False, qd_sample=20, qd_bins=7,
ax=None, figsize=None, dpi=None,
title='Predicted Distribution', xlims=None, xlabel='Prediction', ylabel='Density', **kwargs):
"""
Plot the uncertainty distribution for a single distribution.
Args:
dist: scipy.stats._continuous_distns.
A scipy distribution object.
show_quantile_dots: boolean.
Whether to show quantil dots on top of the density plot.
qd_sample: int.
Number of dots for the quantile dot plot.
qd_bins: int.
Number of bins for the quantile dot plot.
ax: matplotlib.axes.Axes or None, optional (default=None).
Target axes instance. If None, new figure and axes will be created.
figsize: tuple of 2 elements or None, optional (default=None).
Figure size.
dpi : int or None, optional (default=None).
Resolution of the figure.
title : string or None, optional (default=Prediction Distribution)
Axes title.
If None, title is disabled.
xlims : tuple of 2 elements or None, optional (default=None). Tuple passed to ``ax.xlim()``.
xlabel : string or None, optional (default=Prediction)
X-axis title label.
If None, title is disabled.
ylabel : string or None, optional (default=Density)
Y-axis title label.
If None, title is disabled.
Returns:
matplotlib.axes.Axes: ax : The plot with prediction distribution.
"""
import matplotlib.pyplot as plt
if ax is None:
if figsize is not None:
_check_not_tuple_of_2_elements(figsize, 'figsize')
_, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)
x = np.linspace(dist.ppf(0.01), dist.ppf(0.99), 100)
ax.plot(x, dist.pdf(x), **kwargs)
if show_quantile_dots:
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollection
import matplotlib.ticker as ticker
data = dist.rvs(size=10000)
p_less_than_x = np.linspace(1 / qd_sample / 2, 1 - (1 / qd_sample / 2), qd_sample)
x_ = np.percentile(data, p_less_than_x * 100) # Inverce CDF (ppf)
# Create bins
hist = np.histogram(x_, bins=qd_bins)
bins, edges = hist
radius = (edges[1] - edges[0]) / 2
ax2 = ax.twinx()
patches = []
max_y = 0
for i in range(qd_bins):
x_bin = (edges[i + 1] + edges[i]) / 2
y_bins = [(i + 1) * (radius * 2) for i in range(bins[i])]
max_y = max(y_bins) if max(y_bins) > max_y else max_y
for _, y_bin in enumerate(y_bins):
circle = Circle((x_bin, y_bin), radius)
patches.append(circle)
p = PatchCollection(patches, alpha=0.4)
ax2.add_collection(p)
# Axis tweek
y_scale = (max_y + radius) / max(dist.pdf(x))
ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x_ / y_scale))
ax2.yaxis.set_major_formatter(ticks_y)
ax2.set_yticklabels([])
if xlims is not None:
ax2.set_xlim(left=xlims[0], right=xlims[1])
else:
ax2.set_xlim([min(x_) - radius, max(x) + radius])
ax2.set_ylim([0, max_y + radius])
ax2.set_aspect(1)
if title is not None:
ax.set_title(title)
if xlabel is not None:
ax.set_xlabel(xlabel)
if ylabel is not None:
ax.set_ylabel(ylabel)
return ax
def plot_picp_by_feature(x_test, y_test, y_test_pred_lower_total, y_test_pred_upper_total, num_bins=10,
ax=None, figsize=None, dpi=None, xlims=None, ylims=None, xscale="linear",
title=None, xlabel=None, ylabel=None):
"""
Plot how prediction uncertainty varies across the entire range of a feature.
Args:
x_test: One dimensional ndarray.
Feature column of the test dataset.
y_test: One dimensional ndarray.
Ground truth label of the test dataset.
y_test_pred_lower_total: One dimensional ndarray.
Lower bound of the total uncertainty range.
y_test_pred_upper_total: One dimensional ndarray.
Upper bound of the total uncertainty range.
num_bins: int.
Number of bins used to discritize x_test into equal-sample-sized bins.
ax: matplotlib.axes.Axes or None, optional (default=None). Target axes instance. If None, new figure and axes will be created.
figsize: tuple of 2 elements or None, optional (default=None). Figure size.
dpi : int or None, optional (default=None). Resolution of the figure.
xlims : tuple of 2 elements or None, optional (default=None). Tuple passed to ``ax.xlim()``.
ylims: tuple of 2 elements or None, optional (default=None). Tuple passed to ``ax.ylim()``.
xscale: Passed to ``ax.set_xscale()``.
title : string or None, optional
Axes title.
If None, title is disabled.
xlabel : string or None, optional
X-axis title label.
If None, title is disabled.
ylabel : string or None, optional
Y-axis title label.
If None, title is disabled.
Returns:
matplotlib.axes.Axes: ax : The plot with PICP scores binned by a feature.
"""
from scipy.stats.mstats import mquantiles
import matplotlib.pyplot as plt
if ax is None:
if figsize is not None:
_check_not_tuple_of_2_elements(figsize, 'figsize')
_, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)
x_uniques_sorted = np.sort(np.unique(x_test))
num_unique = len(x_uniques_sorted)
sample_bin_ids = np.searchsorted(x_uniques_sorted, x_test)
if len(x_uniques_sorted) > 10: # bin the values
q_bins = mquantiles(x_test, np.histogram_bin_edges([], bins=num_bins-1, range=(0.0, 1.0))[1:])
q_sample_bin_ids = np.digitize(x_test, q_bins)
picps = np.array([picp(y_test[q_sample_bin_ids==bin], y_test_pred_lower_total[q_sample_bin_ids==bin],
y_test_pred_upper_total[q_sample_bin_ids==bin]) for bin in range(num_bins)])
unique_sample_bin_ids = np.digitize(x_uniques_sorted, q_bins)
picp_replicated = [len(x_uniques_sorted[unique_sample_bin_ids == bin]) * [picps[bin]] for bin in range(num_bins)]
picp_replicated = np.array([item for sublist in picp_replicated for item in sublist])
else:
picps = np.array([picp(y_test[sample_bin_ids == bin], y_test_pred_lower_total[sample_bin_ids == bin],
y_test_pred_upper_total[sample_bin_ids == bin]) for bin in range(num_unique)])
picp_replicated = picps
ax.plot(x_uniques_sorted, picp_replicated, label='PICP')
ax.axhline(0.95, linestyle='--', label='95%')
ax.set_ylabel('PICP')
ax.legend(loc='best')
if title is None:
title = 'Test data overall PICP: {:.2f} MPIW: {:.2f}'.format(
picp(y_test,
y_test_pred_lower_total,
y_test_pred_upper_total),
mpiw(y_test_pred_lower_total,
y_test_pred_upper_total))
if xlims is not None:
ax.set_xlim(left=xlims[0], right=xlims[1])
if ylims is not None:
ax.set_ylim(bottom=ylims[0], top=ylims[1])
ax.set_title(title)
if xlabel is not None:
ax.set_xlabel(xlabel)
if ylabel is not None:
ax.set_ylabel(ylabel)
if xscale is not None:
ax.set_xscale(xscale)
return ax
def plot_uncertainty_by_feature(x_test, y_test_pred_mean, y_test_pred_lower_total, y_test_pred_upper_total,
y_test_pred_lower_epistemic=None, y_test_pred_upper_epistemic=None,
ax=None, figsize=None, dpi=None, xlims=None, xscale="linear",
title=None, xlabel=None, ylabel=None):
"""
Plot how prediction uncertainty varies across the entire range of a feature.
Args:
x_test: one dimensional ndarray.
Feature column of the test dataset.
y_test_pred_mean: One dimensional ndarray.
Model prediction for the test dataset.
y_test_pred_lower_total: One dimensional ndarray.
Lower bound of the total uncertainty range.
y_test_pred_upper_total: One dimensional ndarray.
Upper bound of the total uncertainty range.
y_test_pred_lower_epistemic: One dimensional ndarray.
Lower bound of the epistemic uncertainty range.
y_test_pred_upper_epistemic: One dimensional ndarray.
Upper bound of the epistemic uncertainty range.
ax: matplotlib.axes.Axes or None, optional (default=None). Target axes instance. If None, new figure and axes will be created.
figsize: tuple of 2 elements or None, optional (default=None). Figure size.
dpi : int or None, optional (default=None). Resolution of the figure.
xlims : tuple of 2 elements or None, optional (default=None). Tuple passed to ``ax.xlim()``.
xscale: Passed to ``ax.set_xscale()``.
title : string or None, optional
Axes title.
If None, title is disabled.
xlabel : string or None, optional
X-axis title label.
If None, title is disabled.
ylabel : string or None, optional
Y-axis title label.
If None, title is disabled.
Returns:
matplotlib.axes.Axes: ax : The plot with model's uncertainty binned by a feature.
"""
import matplotlib.pyplot as plt
if ax is None:
if figsize is not None:
_check_not_tuple_of_2_elements(figsize, 'figsize')
_, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)
x_uniques_sorted = np.sort(np.unique(x_test))
y_pred_var = ((y_test_pred_upper_total - y_test_pred_lower_total) / 4.0)**2
agg_y_std = np.array([np.sqrt(np.mean(y_pred_var[x_test==x])) for x in x_uniques_sorted])
agg_y_mean = | ||
np.array([np.mean(y_test_pred_mean[x_test==x]) for x in x_uniques_sorted])
ax.plot(x_uniques_sorted, agg_y_mean, '-b', lw=2, label='mean prediction')
ax.fill_between(x_uniques_sorted,
agg_y_mean - 2.0 * agg_y_std,
agg_y_mean + 2.0 * agg_y_std,
alpha=0.3, label='total uncertainty')
if y_test_pred_lower_epistemic is not None:
y_pred_var_epistemic = ((y_test_pred_upper_epistemic - y_test_pred_lower_epistemic) / 4.0)**2
agg_y_std_epistemic = np.array([np.sqrt(np.mean(y_pred_var_epistemic[x_test==x])) for x in x_uniques_sorted])
ax.fill_between(x_uniques_sorted,
agg_y_mean - 2.0 * agg_y_std_epistemic,
agg_y_mean + 2.0 * agg_y_std_epistemic,
alpha=0.3, label='model uncertainty')
ax.legend(loc='best')
if xlims is not None:
ax.set_xlim(left=xlims[0], right=xlims[1])
if title is not None:
ax.set_title(title)
if xlabel is not None:
ax.set_xlabel(xlabel)
if ylabel is not None:
ax.set_ylabel(ylabel)
if xscale is not None:
ax.set_xscale(xscale)
return ax
<s> import numpy as np
import pandas as pd
from scipy.stats import entropy
from sklearn.metrics import roc_auc_score, log_loss, accuracy_score
def entropy_based_uncertainty_decomposition(y_prob_samples):
""" Entropy based decomposition [2]_ of predictive uncertainty into aleatoric and epistemic components.
References:
.. [2] Depeweg, S., Hernandez-Lobato, J. M., Doshi-Velez, F., & Udluft, S. (2018, July). Decomposition of
uncertainty in Bayesian deep learning for efficient and risk-sensitive learning. In International Conference
on Machine Learning (pp. 1184-1193). PMLR.
Args:
y_prob_samples: list of array-like of shape (n_samples, n_classes) containing class prediction probabilities
corresponding to samples from the model posterior.
Returns:
tuple:
- total_uncertainty: entropy of the predictive distribution.
- aleatoric_uncertainty: aleatoric component of the total_uncertainty.
- epistemic_uncertainty: epistemic component of the total_uncertainty.
"""
y_preds_samples_stacked = np.stack(y_prob_samples)
preds_mean = np.mean(y_preds_samples_stacked, 0)
total_uncertainty = entropy(preds_mean, axis=1)
aleatoric_uncertainty = np.mean(
np.concatenate([entropy(y_pred, axis=1).reshape(-1, 1) for y_pred in y_prob_samples], axis=1),
axis=1)
epistemic_uncertainty = total_uncertainty - aleatoric_uncertainty
return total_uncertainty, aleatoric_uncertainty, epistemic_uncertainty
def multiclass_brier_score(y_true, y_prob):
"""Brier score for multi-class.
Args:
y_true: array-like of shape (n_samples,)
ground truth labels.
y_prob: array-like of shape (n_samples, n_classes).
Probability scores from the base model.
Returns:
float: Brier score.
"""
assert len(y_prob.shape) > 1, "y_prob should be array-like of shape (n_samples, n_classes)"
y_target = np.zeros_like(y_prob)
y_target[:, y_true] = 1.0
return np.mean(np.sum((y_target - y_prob) ** 2, axis=1))
def area_under_risk_rejection_rate_curve(y_true, y_prob, y_pred=None, selection_scores=None, risk_func=accuracy_score,
attributes=None, num_bins=10, subgroup_ids=None,
return_counts=False):
""" Computes risk vs rejection rate curve and the area under this curve. Similar to risk-coverage curves [3]_ where
coverage instead of rejection rate is used.
References:
.. [3] Franc, Vojtech, and Daniel Prusa. "On discriminative learning of prediction uncertainty."
In International Conference on Machine Learning, pp. 1963-1971. 2019.
Args:
y_true: array-like of shape (n_samples,)
ground truth labels.
y_prob: array-like of shape (n_samples, n_classes).
Probability scores from the base model.
y_pred: array-like of shape (n_samples,)
predicted labels.
selection_scores: scores corresponding to certainty in the predicted labels.
risk_func: risk function under consideration.
attributes: (optional) if risk function is a fairness metric also pass the protected attribute name.
num_bins: number of bins.
subgroup_ids: (optional) selectively compute risk on a subgroup of the samples specified by subgroup_ids.
return_counts: set to True to return counts also.
Returns:
float or tuple:
- aurrrc (float): area under risk rejection rate curve.
- rejection_rates (list): rejection rates for each bin (returned only if return_counts is True).
- selection_thresholds (list): selection threshold for each bin (returned only if return_counts is True).
- risks (list): risk in each bin (returned only if return_counts is True).
"""
if selection_scores is None:
assert len(y_prob.shape) > 1, "y_prob should be array-like of shape (n_samples, n_classes)"
selection_scores = y_prob[np.arange(y_prob.shape[0]), np.argmax(y_prob, axis=1)]
if y_pred is None:
assert len(y_prob.shape) > 1, "y_prob should be array-like of shape (n_samples, n_classes)"
y_pred = np.argmax(y_prob, axis=1)
order = np.argsort(selection_scores)[::-1]
rejection_rates = []
selection_thresholds = []
risks = []
for bin_id in range(num_bins):
samples_in_bin = len(y_true) // num_bins
selection_threshold = selection_scores[order[samples_in_bin * (bin_id+1)-1]]
selection_thresholds.append(selection_threshold)
ids = selection_scores >= selection_threshold
if sum(ids) > 0:
if attributes is None:
if isinstance(y_true, pd.Series):
y_true_numpy = y_true.values
else:
y_true_numpy = y_true
if subgroup_ids is None:
risk_value = 1.0 - risk_func(y_true_numpy[ids], y_pred[ids])
else:
if sum(subgroup_ids & ids) > 0:
risk_value = 1.0 - risk_func(y_true_numpy[subgroup_ids & ids], y_pred[subgroup_ids & ids])
else:
risk_value = 0.0
else:
risk_value = risk_func(y_true.iloc[ids], y_pred[ids], prot_attr=attributes)
else:
risk_value = 0.0
risks.append(risk_value)
rejection_rates.append(1.0 - 1.0 * sum(ids) / len(y_true))
aurrrc = np.nanmean(risks)
if not return_counts:
return aurrrc
else:
return aurrrc, rejection_rates, selection_thresholds, risks
def expected_calibration_error(y_true, y_prob, y_pred=None, num_bins=10, return_counts=False):
""" Computes the reliability curve and the expected calibration error [1]_ .
References:
.. [1] Chuan Guo, Geoff Pleiss, Yu Sun, Kilian Q. Weinberger; Proceedings of the 34th International Conference
on Machine Learning, PMLR 70:1321-1330, 2017.
Args:
y_true: array-like of shape (n_samples,)
ground truth labels.
y_prob: array-like of shape (n_samples, n_classes).
Probability scores from the base model.
y_pred: array-like of shape (n_samples,)
predicted labels.
num_bins: number of bins.
return_counts: set to True to return counts also.
Returns:
float or tuple:
- ece (float): expected calibration error.
- confidences_in_bins: average confidence in each bin (returned only if return_counts is True).
- accuracies_in_bins: accuracy in each bin (returned only if return_counts is True).
- frac_samples_in_bins: fraction of samples in each bin (returned only if return_counts is True).
"""
assert len(y_prob.shape) > 1, "y_prob should be array-like of shape (n_samples, n_classes)"
num_samples, num_classes = y_prob.shape
top_scores = np.max(y_prob, axis=1)
if y_pred is None:
y_pred = np.argmax(y_prob, axis=1)
if num_classes == 2:
bins_edges = np.histogram_bin_edges([], bins=num_bins, range=(0.5, 1.0))
else:
bins_edges = np.histogram_bin_edges([], bins=num_bins, range=(0.0, 1.0))
non_boundary_bin_edges = bins_edges[1:-1]
bin_centers = (bins_edges[1:] + bins_edges[:-1])/2
sample_bin_ids = np.digitize(top_scores, non_boundary_bin_edges)
num_samples_in_bins = np.zeros(num_bins)
accuracies_in_bins = np.zeros(num_bins)
confidences_in_bins = np.zeros(num_bins)
for bin in range(num_bins):
num_samples_in_bins[bin] = len(y_pred[sample_bin_ids == bin])
if num_samples_in_bins[bin] > 0:
accuracies_in_bins[bin] = np.sum(y_true[sample_bin_ids == bin] == y_pred[sample_bin_ids == bin]) / num_samples_in_bins[bin]
confidences_in_bins[bin] = np.sum(top_scores[sample_bin_ids == bin]) / num_samples_in_bins[bin]
ece = np.sum(
num_samples_in_bins * np.abs(accuracies_in_bins - confidences_in_bins) / num_samples
)
frac_samples_in_bins = num_samples_in_bins / num_samples
if not return_counts:
return ece
else:
return ece, confidences_in_bins, accuracies_in_bins, frac_samples_in_bins, bin_centers
def compute_classification_metrics(y_true, y_prob, option='all'):
"""
Computes the metrics specified in the option which can be string or a list of strings. Default option `all` computes
the [aurrrc, ece, auroc, nll, brier, accuracy] metrics.
Args:
y_true: array-like of shape (n_samples,)
ground truth labels.
y_prob: array-like of shape (n_samples, n_classes).
Probability scores from the base model.
option: string or list of string contained the name of the metrics to be computed.
Returns:
dict: a dictionary containing the computed metrics.
"""
results = {}
if not isinstance(option, list):
if option == "all":
option_list = ["aurrrc", "ece", "auroc", "nll", "brier", "accuracy"]
else:
option_list = [option]
if "aurrrc" in option_list:
results["aurrrc"] = area_under_risk_rejection_rate_curve(y_true=y_true, y_prob=y_prob)
if "ece" in option_list:
results["ece"] = expected_calibration_error(y_true=y_true, y_prob=y_prob)
if "auroc" in option_list:
results["auroc"], _ = roc_auc_score(y_true=y_true, y_score=y_prob)
if "nll" in option_list:
results["nll"] = log_loss(y_true=y_true, y_pred=np.argmax(y_prob, axis=1))
if "brier" in option_list:
results["brier"] = multiclass_brier_score(y_true=y_true, y_prob=y_prob)
if "accuracy" in option_list:
results["accuracy"] = accuracy_score(y_true=y_true, y_pred=np.argmax(y_prob, axis=1))
return results
def plot_reliability_diagram(y_true, y_prob, y_pred, plot_label=[""], num_bins=10):
"""
Plots the reliability diagram showing the calibration error for different confidence scores. Multiple curves
can be plot by passing data as lists.
Args:
y_true: array-like or or a list of array-like of shape (n_samples,)
ground truth labels.
y_prob: array-like or or a list of array-like of shape (n_samples, n_classes).
Probability scores from the base model.
y_pred: array-like or or a list of array-like of shape (n_samples,)
predicted labels.
plot_label: (optional) list of names identifying each curve.
num_bins: number of bins.
Returns:
tuple:
- ece_list: ece: list containing expected calibration error for each curve.
- accuracies_in_bins_list: list containing binned average accuracies for each curve.
- frac_samples_in_bins_list: list containing binned sample frequencies for each curve.
- confidences_in_bins_list: list containing binned average confidence for each curve.
"""
import matplotlib. | ||
pyplot as plt
if not isinstance(y_true, list):
y_true, y_prob, y_pred = [y_true], [y_prob], [y_pred]
if len(plot_label) != len(y_true):
raise ValueError('y_true and plot_label should be of same length.')
ece_list = []
accuracies_in_bins_list = []
frac_samples_in_bins_list = []
confidences_in_bins_list = []
for idx in range(len(plot_label)):
ece, confidences_in_bins, accuracies_in_bins, frac_samples_in_bins, bins = expected_calibration_error(y_true[idx],
y_prob[idx],
y_pred[idx],
num_bins=num_bins,
return_counts=True)
ece_list.append(ece)
accuracies_in_bins_list.append(accuracies_in_bins)
frac_samples_in_bins_list.append(frac_samples_in_bins)
confidences_in_bins_list.append(confidences_in_bins)
fig = plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
for idx in range(len(plot_label)):
plt.plot(bins, frac_samples_in_bins_list[idx], 'o-', label=plot_label[idx])
plt.title("Confidence Histogram")
plt.xlabel("Confidence")
plt.ylabel("Fraction of Samples")
plt.grid()
plt.ylim([0.0, 1.0])
plt.legend()
plt.subplot(1, 2, 2)
for idx in range(len(plot_label)):
plt.plot(bins, accuracies_in_bins_list[idx], 'o-',
label="{} ECE = {:.2f}".format(plot_label[idx], ece_list[idx]))
plt.plot(np.linspace(0, 1, 50), np.linspace(0, 1, 50), 'b.', label="Perfect Calibration")
plt.title("Reliability Plot")
plt.xlabel("Confidence")
plt.ylabel("Accuracy")
plt.grid()
plt.legend()
plt.show()
return ece_list, accuracies_in_bins_list, frac_samples_in_bins_list, confidences_in_bins_list
def plot_risk_vs_rejection_rate(y_true, y_prob, y_pred, selection_scores=None, plot_label=[""], risk_func=None,
attributes=None, num_bins=10, subgroup_ids=None):
"""
Plots the risk vs rejection rate curve showing the risk for different rejection rates. Multiple curves
can be plot by passing data as lists.
Args:
y_true: array-like or or a list of array-like of shape (n_samples,)
ground truth labels.
y_prob: array-like or or a list of array-like of shape (n_samples, n_classes).
Probability scores from the base model.
y_pred: array-like or or a list of array-like of shape (n_samples,)
predicted labels.
selection_scores: ndarray or a list of ndarray containing scores corresponding to certainty in the predicted labels.
risk_func: risk function under consideration.
attributes: (optional) if risk function is a fairness metric also pass the protected attribute name.
num_bins: number of bins.
subgroup_ids: (optional) ndarray or a list of ndarray containing subgroup_ids to selectively compute risk on a
subgroup of the samples specified by subgroup_ids.
Returns:
tuple:
- aurrrc_list: list containing the area under risk rejection rate curves.
- rejection_rate_list: list containing the binned rejection rates.
- selection_thresholds_list: list containing the binned selection thresholds.
- risk_list: list containing the binned risks.
"""
import matplotlib.pyplot as plt
if not isinstance(y_true, list):
y_true, y_prob, y_pred, selection_scores, subgroup_ids = [y_true], [y_prob], [y_pred], [selection_scores], [subgroup_ids]
if len(plot_label) != len(y_true):
raise ValueError('y_true and plot_label should be of same length.')
aurrrc_list = []
rejection_rate_list = []
risk_list = []
selection_thresholds_list = []
for idx in range(len(plot_label)):
aursrc, rejection_rates, selection_thresholds, risks = area_under_risk_rejection_rate_curve(
y_true[idx],
y_prob[idx],
y_pred[idx],
selection_scores=selection_scores[idx],
risk_func=risk_func,
attributes=attributes,
num_bins=num_bins,
subgroup_ids=subgroup_ids[idx],
return_counts=True
)
aurrrc_list.append(aursrc)
rejection_rate_list.append(rejection_rates)
risk_list.append(risks)
selection_thresholds_list.append(selection_thresholds)
plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
for idx in range(len(plot_label)):
plt.plot(rejection_rate_list[idx], risk_list[idx], label="{} AURRRC={:.5f}".format(plot_label[idx], aurrrc_list[idx]))
plt.legend(loc="best")
plt.xlabel("Rejection Rate")
if risk_func is None:
ylabel = "Prediction Error Rate"
else:
if 'accuracy' in risk_func.__name__:
ylabel = "1.0 - " + risk_func.__name__
else:
ylabel = risk_func.__name__
plt.ylabel(ylabel)
plt.title("Risk vs Rejection Rate Plot")
plt.grid()
plt.subplot(1, 2, 2)
for idx in range(len(plot_label)):
plt.plot(selection_thresholds_list[idx], risk_list[idx], label="{}".format(plot_label[idx]))
plt.legend(loc="best")
plt.xlabel("Selection Threshold")
if risk_func is None:
ylabel = "Prediction Error Rate"
else:
if 'accuracy' in risk_func.__name__:
ylabel = "1.0 - " + risk_func.__name__
else:
ylabel = risk_func.__name__
plt.ylabel(ylabel)
plt.title("Risk vs Selection Threshold Plot")
plt.grid()
plt.show()
return aurrrc_list, rejection_rate_list, selection_thresholds_list, risk_list
<s> from .classification_metrics import expected_calibration_error, area_under_risk_rejection_rate_curve, \\
compute_classification_metrics, entropy_based_uncertainty_decomposition
from .regression_metrics import picp, mpiw, compute_regression_metrics, plot_uncertainty_distribution, \\
plot_uncertainty_by_feature, plot_picp_by_feature
from .uncertainty_characteristics_curve import UncertaintyCharacteristicsCurve
<s> from copy import deepcopy
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import simps, trapz
from sklearn.isotonic import IsotonicRegression
DEFAULT_X_AXIS_NAME = 'excess'
DEFAULT_Y_AXIS_NAME = 'missrate'
class UncertaintyCharacteristicsCurve:
"""
Class with main functions of the Uncertainty Characteristics Curve (UCC).
"""
def __init__(self, normalize=True, precompute_bias_data=True):
"""
:param normalize: set initial axes normalization flag (can be changed via set_coordinates())
:param precompute_bias_data: if True, fit() will compute statistics necessary to generate bias-based
UCCs (in addition to the scale-based ones). Skipping this precomputation may speed up the fit() call
if bias-based UCC is not needed.
"""
self.axes_name2idx = {"missrate": 1, "bandwidth": 2, "excess": 3, "deficit": 4}
self.axes_idx2descr = {1: "Missrate", 2: "Bandwidth", 3: "Excess", 4: "Deficit"}
self.x_axis_idx = None
self.y_axis_idx = None
self.norm_x_axis = False
self.norm_y_axis = False
self.std_unit = None
self.normalize = normalize
self.d = None
self.gt = None
self.lb = None
self.ub = None
self.precompute_bias_data = precompute_bias_data
self.set_coordinates(x_axis_name=DEFAULT_X_AXIS_NAME, y_axis_name=DEFAULT_Y_AXIS_NAME, normalize=normalize)
def set_coordinates(self, x_axis_name=None, y_axis_name=None, normalize=None):
"""
Assigns user-specified type to the axes and normalization behavior (sticky).
:param x_axis_name: None-> unchanged, or name from self.axes_name2idx
:param y_axis_name: ditto
:param normalize: True/False will activate/deactivate norming for specified axes. Behavior for
Axes_name that are None will not be changed.
Value None will leave norm status unchanged.
Note, axis=='missrate' will never get normalized, even with normalize == True
:return: none
"""
normalize = self.normalize if normalize is None else normalize
if x_axis_name is None and self.x_axis_idx is None:
raise ValueError("ERROR(UCC): x-axis has not been defined.")
if y_axis_name is None and self.y_axis_idx is None:
raise ValueError("ERROR(UCC): y-axis has not been defined.")
if x_axis_name is None and y_axis_name is None and normalize is not None:
# just set normalization on/off for both axes and return
self.norm_x_axis = False if x_axis_name == 'missrate' else normalize
self.norm_y_axis = False if y_axis_name == 'missrate' else normalize
return
if x_axis_name is not None:
self.x_axis_idx = self.axes_name2idx[x_axis_name]
self.norm_x_axis = False if x_axis_name == 'missrate' else normalize
if y_axis_name is not None:
self.y_axis_idx = self.axes_name2idx[y_axis_name]
self.norm_y_axis = False if y_axis_name == 'missrate' else normalize
def set_std_unit(self, std_unit=None):
"""
Sets the UCC's unit to be used when displaying normalized axes.
:param std_unit: if None, the unit will be calculated as stddev of the ground truth data
(ValueError raised if data has not been set at this point)
or set to the user-specified value.
:return:
"""
if std_unit is None: # set it to stddev of data
if self.gt is None:
raise ValueError("ERROR(UCC): No data specified - cannot set stddev unit.")
self.std_unit = np.std(self.gt)
if np.isclose(self.std_unit, 0.):
print("WARN(UCC): data-based stddev is zero - resetting axes unit to 1.")
self.std_unit = 1.
else:
self.std_unit = float(std_unit)
def fit(self, X, gt):
"""
Calculates internal arrays necessary for other methods (plotting, auc, cost minimization).
Re-entrant.
:param X: [numsamples, 3] numpy matrix, or list of numpy matrices.
Col 1: predicted values
Col 2: lower band (deviate) wrt predicted value (always positive)
Col 3: upper band wrt predicted value (always positive)
If list is provided, all methods will output corresponding metrics as lists as well!
:param gt: Ground truth array (i.e.,the 'actual' values corresponding to predictions in X
:return: self
"""
if not isinstance(X, list):
X = [X]
newX = []
for x in X:
assert (isinstance(x, np.ndarray) and len(x.shape) == 2 and x.shape[1] == 3 and x.shape[0] == len(gt))
newX.append(self._sanitize_input(x))
self.d = [gt - x[:, 0] for x in newX]
self.lb = [x[:, 1] for x in newX]
self.ub = [x[:, 2] for x in newX]
self.gt = gt
self.set_std_unit()
self.plotdata_for_scale = []
self.plotdata_for_bias = []
# precompute plotdata:
for i in range(len(self.d)):
self.plotdata_for_scale.append(self._calc_plotdata(self.d[i], self.lb[i], self.ub[i], vary_bias=False))
if self.precompute_bias_data:
self.plotdata_for_bias.append(self._calc_plotdata(self.d[i], self.lb[i], self.ub[i], vary_bias=True))
return self
def minimize_cost(self, x_axis_cost=.5, y_axis_cost=.5, augment_cost_by_normfactor=True,
search=('scale', 'bias')):
"""
Find minima of a linear cost function for each component.
Cost function C = x_axis_cost * x_axis_value + y_axis_cost * y_axis_value.
A minimum can occur in the scale-based or bias-based UCC (this can be constrained by the 'search' arg).
The function returns a 'recipe' how to achieve the corresponding minimum, for each component.
:param x_axis_cost: weight of one unit on x_axis
:param y_axis_cost: weight of one unit on y_axis
:param augment_cost_by_normfactor: when False, the cost multipliers will apply as is. If True, they will be
pre-normed by the corresponding axis norm (where applicable), to account for range differences between axes.
:param search: list of types over which minimization is to be performed, valid elements are 'scale' and 'bias'.
:return: list of dicts - one per component, or a single dict, if there is only one component. Dict keys are -
'operation': can be 'bias' (additive) or 'scale' (multiplicative), 'modvalue': value to multiply by or to
add to error bars to achieve | ||
the minimum, 'new_x'/'new_y': new coordinates (operating point) with that
minimum, 'cost': new cost at minimum point, 'original_cost': original cost (original operating point).
"""
if self.d is None:
raise ValueError("ERROR(UCC): call fit() prior to using this method.")
if augment_cost_by_normfactor:
if self.norm_x_axis:
x_axis_cost /= self.std_unit
if self.norm_y_axis:
y_axis_cost /= self.std_unit
print("INFO(UCC): Pre-norming costs by corresp. std deviation: new x_axis_cost = %.4f, y_axis_cost = %.4f" %
(x_axis_cost, y_axis_cost))
if isinstance(search, tuple):
search = list(search)
if not isinstance(search, list):
search = [search]
min_costs = []
for d in range(len(self.d)):
# original OP cost
m, b, e, df = self._calc_missrate_bandwidth_excess_deficit(self.d[d], self.lb[d], self.ub[d])
original_cost = x_axis_cost * [0., m, b, e, df][self.x_axis_idx] + y_axis_cost * [0., m, b, e, df][
self.y_axis_idx]
plotdata = self.plotdata_for_scale[d]
cost_scale, minidx_scale = self._find_min_cost_in_component(plotdata, self.x_axis_idx, self.y_axis_idx,
x_axis_cost, y_axis_cost)
mcf_scale_multiplier = plotdata[minidx_scale][0]
mcf_scale_x = plotdata[minidx_scale][self.x_axis_idx]
mcf_scale_y = plotdata[minidx_scale][self.y_axis_idx]
if 'bias' in search:
if not self.precompute_bias_data:
raise ValueError(
"ERROR(UCC): Cannot perform minimization - instantiated without bias data computation")
plotdata = self.plotdata_for_bias[d]
cost_bias, minidx_bias = self._find_min_cost_in_component(plotdata, self.x_axis_idx, self.y_axis_idx,
x_axis_cost, y_axis_cost)
mcf_bias_add = plotdata[minidx_bias][0]
mcf_bias_x = plotdata[minidx_bias][self.x_axis_idx]
mcf_bias_y = plotdata[minidx_bias][self.y_axis_idx]
if 'bias' in search and 'scale' in search:
if cost_bias < cost_scale:
min_costs.append({'operation': 'bias', 'cost': cost_bias, 'modvalue': mcf_bias_add,
'new_x': mcf_bias_x, 'new_y': mcf_bias_y, 'original_cost': original_cost})
else:
min_costs.append({'operation': 'scale', 'cost': cost_scale, 'modvalue': mcf_scale_multiplier,
'new_x': mcf_scale_x, 'new_y': mcf_scale_y, 'original_cost': original_cost})
elif 'scale' in search:
min_costs.append({'operation': 'scale', 'cost': cost_scale, 'modvalue': mcf_scale_multiplier,
'new_x': mcf_scale_x, 'new_y': mcf_scale_y, 'original_cost': original_cost})
elif 'bias' in search:
min_costs.append({'operation': 'bias', 'cost': cost_bias, 'modvalue': mcf_bias_add,
'new_x': mcf_bias_x, 'new_y': mcf_bias_y, 'original_cost': original_cost})
else:
raise ValueError("(ERROR): Unknown search element (%s) requested." % ",".join(search))
if len(min_costs) < 2:
return min_costs[0]
else:
return min_costs
def get_specific_operating_point(self, req_x_axis_value=None, req_y_axis_value=None,
req_critical_value=None, vary_bias=False):
"""
Finds corresponding operating point on the current UCC, given a point on either x or y axis. Returns
a list of recipes how to achieve the point (x,y), for each component. If there is only one component,
returns a single recipe dict.
:param req_x_axis_value: requested x value on UCC (normalization status is taken from current display)
:param req_y_axis_value: requested y value on UCC (normalization status is taken from current display)
:param vary_bias: set to True when referring to bias-induced UCC (scale UCC default)
:return: list of dicts (recipes), or a single dict
"""
if self.d is None:
raise ValueError("ERROR(UCC): call fit() prior to using this method.")
if np.sum([req_x_axis_value is not None, req_y_axis_value is not None, req_critical_value is not None]) != 1:
raise ValueError("ERROR(UCC): exactly one axis value must be requested at a time.")
if vary_bias and not self.precompute_bias_data:
raise ValueError("ERROR(UCC): Cannot vary bias - instantiated without bias data computation")
xnorm = self.std_unit if self.norm_x_axis else 1.
ynorm = self.std_unit if self.norm_y_axis else 1.
recipe = []
for dc in range(len(self.d)):
plotdata = self.plotdata_for_bias[dc] if vary_bias else self.plotdata_for_scale[dc]
if req_x_axis_value is not None:
tgtidx = self.x_axis_idx
req_value = req_x_axis_value * xnorm
elif req_y_axis_value is not None:
tgtidx = self.y_axis_idx
req_value = req_y_axis_value * ynorm
elif req_critical_value is not None:
req_value = req_critical_value
tgtidx = 0 # first element in plotdata is always the critical value (scale of bias)
else:
raise RuntimeError("Unhandled case")
closestidx = np.argmin(np.asarray([np.abs(p[tgtidx] - req_value) for p in plotdata]))
recipe.append({'operation': ('bias' if vary_bias else 'scale'),
'modvalue': plotdata[closestidx][0],
'new_x': plotdata[closestidx][self.x_axis_idx] / xnorm,
'new_y': plotdata[closestidx][self.y_axis_idx] / ynorm})
if len(recipe) < 2:
return recipe[0]
else:
return recipe
def _find_min_cost_in_component(self, plotdata, idx1, idx2, cost1, cost2):
"""
Find s minimum cost function value and corresp. position index in plotdata
:param plotdata: liste of tuples
:param idx1: idx of x-axis item within the tuple
:param idx2: idx of y-axis item within the tuple
:param cost1: cost factor for x-axis unit
:param cost2: cost factor for y-axis unit
:return: min cost value, index within plotdata where minimum occurs
"""
raw = [cost1 * i[idx1] + cost2 * i[idx2] for i in plotdata]
minidx = np.argmin(raw)
return raw[minidx], minidx
def _sanitize_input(self, x):
"""
Replaces problematic values in input data (e.g, zero error bars)
:param x: single matrix of input data [n, 3]
:return: sanitized version of x
"""
if np.isclose(np.sum(x[:, 1]), 0.):
raise ValueError("ERROR(UCC): Provided lower bands are all zero.")
if np.isclose(np.sum(x[:, 2]), 0.):
raise ValueError("ERROR(UCC): Provided upper bands are all zero.")
for i in [1, 2]:
if any(np.isclose(x[:, i], 0.)):
print("WARN(UCC): some band values are 0. - REPLACING with positive minimum")
m = np.min(x[x[:, i] > 0, i])
x = np.where(np.isclose(x, 0.), m, x)
return x
def _calc_avg_excess(self, d, lb, ub):
"""
Excess is amount an error bar overshoots actual
:param d: pred-actual array
:param lb: lower band
:param ub: upper band
:return: average excess over array
"""
excess = np.zeros(d.shape)
posidx = np.where(d >= 0)[0]
excess[posidx] = np.where(ub[posidx] - d[posidx] < 0., 0., ub[posidx] - d[posidx])
negidx = np.where(d < 0)[0]
excess[negidx] = np.where(lb[negidx] + d[negidx] < 0., 0., lb[negidx] + d[negidx])
return np.mean(excess)
def _calc_avg_deficit(self, d, lb, ub):
"""
Deficit is error bar insufficiency: bar falls short of actual
:param d: pred-actual array
:param lb: lower band
:param ub: upper band
:return: average deficit over array
"""
deficit = np.zeros(d.shape)
posidx = np.where(d >= 0)[0]
deficit[posidx] = np.where(- ub[posidx] + d[posidx] < 0., 0., - ub[posidx] + d[posidx])
negidx = np.where(d < 0)[0]
deficit[negidx] = np.where(- lb[negidx] - d[negidx] < 0., 0., - lb[negidx] - d[negidx])
return np.mean(deficit)
def _calc_missrate_bandwidth_excess_deficit(self, d, lb, ub, scale=1.0, bias=0.0):
"""
Calculates recall at a given scale/bias, average bandwidth and average excess
:param d: delta
:param lb: lower band
:param ub: upper band
:param scale: scale * (x + bias)
:param bias:
:return: miss rate, average bandwidth, avg excess, avg deficit
"""
abslband = scale * np.where((lb + bias) < 0., 0., lb + bias)
absuband = scale * np.where((ub + bias) < 0., 0., ub + bias)
recall = np.sum((d >= - abslband) & (d <= absuband)) / len(d)
avgbandwidth = np.mean([absuband, abslband])
avgexcess = self._calc_avg_excess(d, abslband, absuband)
avgdeficit = self._calc_avg_deficit(d, abslband, absuband)
return 1 - recall, avgbandwidth, avgexcess, avgdeficit
def _calc_plotdata(self, d, lb, ub, vary_bias=False):
"""
Generates data necessary for various UCC metrics.
:param d: delta (predicted - actual) vector
:param ub: upper uncertainty bandwidth (above predicted)
:param lb: lower uncertainty bandwidth (below predicted) - all positive (bandwidth)
:param vary_bias: True will switch to additive bias instead of scale
:return: list. Elements are tuples (varyvalue, missrate, bandwidth, excess, deficit)
"""
# step 1: collect critical scale or bias values
critval = []
for i in range(len(d)):
if not vary_bias:
if d[i] >= 0:
critval.append(d[i] / ub[i])
else:
critval.append(-d[i] / lb[i])
else:
if d[i] >= 0:
critval.append(d[i] - ub[i])
else:
critval.append(-lb[i] - d[i])
critval = sorted(critval)
plotdata = []
for i in range(len(critval)):
if not vary_bias:
missrate, bandwidth, excess, deficit = self._calc_missrate_bandwidth_excess_deficit(d, lb, ub,
scale=critval[i])
else:
missrate, bandwidth, excess, deficit = self._calc_missrate_bandwidth_excess_deficit(d, lb, ub,
bias=critval[i])
plotdata.append((critval[i], missrate, bandwidth, excess, deficit))
return plotdata
def get_AUUCC(self, vary_bias=False, aucfct="trapz", partial_x=None, partial_y=None):
"""
returns approximate area under the curve on current coordinates, for each component.
:param vary_bias: False == varies scale, True == varies bias
:param aucfct: specifies AUC integrator (can be "trapz", "simps")
:param partial_x: tuple (x_min, x_max) defining interval on x to calc a a partial AUC.
The interval bounds refer to axes as visualized (ie. potentially normed)
:param partial_y: tuple (y_min, y_max) defining interval on y to calc a a partial AUC. partial_x must be None.
:return: list of floats with AUUCCs for each input component, or a single float, if there is only 1 component.
"""
if self.d is None:
raise ValueError("ERROR(UCC): call fit() prior to using this method.")
if vary_bias and not self.precompute_bias_data:
raise ValueError("ERROR(UCC): Cannot vary bias - instantiated without bias data computation")
if partial_x is not None and partial_y is not None:
raise ValueError("ERROR(UCC): partial_x and partial_y can not be specified at the same time.")
assert(partial_x is None or (isinstance(partial_x, tuple) and len(partial_x)==2))
assert(partial_y is None or (isinstance(partial_y, tuple) and len(partial_y)==2))
# find starting point (where the x axis value starts to actually change)
rv = []
# do this for individual streams
xind = self.x_axis_idx
aucfct = simps if aucfct == "simps" else trapz
for s in range(len(self.d)):
plotdata = self.plotdata_for_bias[s] if vary_bias else self.plotdata_for_scale[s]
prev = plotdata[0][xind]
t = 1
cval = plotdata[t | ||
][xind]
while cval == prev and t < len(plotdata) - 1:
t += 1
prev = cval
cval = plotdata[t][xind]
startt = t - 1 # from here, it's a valid function
endtt = len(plotdata)
if startt >= endtt - 2:
rvs = 0. # no area
else:
xnorm = self.std_unit if self.norm_x_axis else 1.
ynorm = self.std_unit if self.norm_y_axis else 1.
y=[(plotdata[i][self.y_axis_idx]) / ynorm for i in range(startt, endtt)]
x=[(plotdata[i][self.x_axis_idx]) / xnorm for i in range(startt, endtt)]
if partial_x is not None:
from_i = self._find_closest_index(partial_x[0], x)
to_i = self._find_closest_index(partial_x[1], x) + 1
elif partial_y is not None:
from_i = self._find_closest_index(partial_y[0], y)
to_i = self._find_closest_index(partial_y[1], y)
if from_i > to_i: # y is in reverse order
from_i, to_i = to_i, from_i
to_i += 1 # as upper bound in array indexing
else:
from_i = 0
to_i = len(x)
to_i = min(to_i, len(x))
if to_i < from_i:
raise ValueError("ERROR(UCC): Failed to find an appropriate partial-AUC interval in the data.")
if to_i - from_i < 2:
raise RuntimeError("ERROR(UCC): There are too few samples (1) in the partial-AUC interval specified")
rvs = aucfct(x=x[from_i:to_i], y=y[from_i:to_i])
rv.append(rvs)
if len(rv) < 2:
return rv[0]
else:
return rv
@ staticmethod
def _find_closest_index(value, array):
"""
Returns an index of the 'array' element closest in value to 'value'
:param value:
:param array:
:return:
"""
return np.argmin(np.abs(np.asarray(array)-value))
def _get_single_OP(self, d, lb, ub, scale=1., bias=0.):
"""
Returns Operating Point for original input data, on coordinates currently set up, given a scale/bias.
:param scale:
:param bias:
:return: single tuple (x point, y point, unit of x, unit of y)
"""
xnorm = self.std_unit if self.norm_x_axis else 1.
ynorm = self.std_unit if self.norm_y_axis else 1.
auxop = self._calc_missrate_bandwidth_excess_deficit(d, lb, ub, scale=scale, bias=bias)
op = [0.] + [i for i in auxop] # mimic plotdata (first element ignored here)
return (op[self.x_axis_idx] / xnorm, op[self.y_axis_idx] / ynorm, xnorm, ynorm)
def get_OP(self, scale=1., bias=0.):
"""
Returns all Operating Points for original input data, on coordinates currently set up, given a scale/bias.
:param scale:
:param bias:
:return: list of tuples (x point, y point, unit of x, unit of y) or a single tuple if there is only
1 component.
"""
if self.d is None:
raise ValueError("ERROR(UCC): call fit() prior to using this method.")
op = []
for dc in range(len(self.d)):
op.append(self._get_single_OP(self.d[dc], self.lb[dc], self.ub[dc], scale=scale, bias=bias))
if len(op) < 2:
return op[0]
else:
return op
def plot_UCC(self, titlestr='', syslabel='model', outfn=None, vary_bias=False, markers=None,
xlim=None, ylim=None, **kwargs):
""" Will plot/display the UCC based on current data and coordinates. Multiple curves will be shown
if there are multiple data components (via fit())
:param titlestr: Plot title string
:param syslabel: list is label strings to appear in the plot legend. Can be single, if one component.
:param outfn: base name of an image file to be created (will append .png before creating)
:param vary_bias: True will switch to varying additive bias (default is multiplicative scale)
:param markers: None or a list of marker styles to be used for each curve.
List must be same or longer than number of components.
Markers can be one among these ['o', 's', 'v', 'D', '+'].
:param xlim: tuples or lists of specifying the range for the x axis, or None (auto)
:param ylim: tuples or lists of specifying the range for the y axis, or None (auto)
:param `**kwargs`: Additional arguments passed to the main plot call.
:return: list of areas under the curve (or single area, if one data component)
list of operating points (or single op): format of an op is tuple (xaxis value, yaxis value, xunit, yunit)
"""
if self.d is None:
raise ValueError("ERROR(UCC): call fit() prior to using this method.")
if vary_bias and not self.precompute_bias_data:
raise ValueError("ERROR(UCC): Cannot vary bias - instantiated without bias data computation")
if not isinstance(syslabel, list):
syslabel = [syslabel]
assert (len(syslabel) == len(self.d))
assert (markers is None or (isinstance(markers, list) and len(markers) >= len(self.d)))
# main plot of (possibly multiple) datasets
plt.figure()
xnorm = self.std_unit if self.norm_x_axis else 1.
ynorm = self.std_unit if self.norm_y_axis else 1.
op_info = []
auucc = self.get_AUUCC(vary_bias=vary_bias)
auucc = [auucc] if not isinstance(auucc, list) else auucc
for s in range(len(self.d)):
# original operating point
x_op, y_op, x_unit, y_unit = self._get_single_OP(self.d[s], self.lb[s], self.ub[s])
op_info.append((x_op, y_op, x_unit, y_unit))
# display chart
plotdata = self.plotdata_for_scale[s] if not vary_bias else self.plotdata_for_bias[s]
axisX_data = [i[self.x_axis_idx] / xnorm for i in plotdata]
axisY_data = [i[self.y_axis_idx] / ynorm for i in plotdata]
marker = None
if markers is not None: marker = markers[s]
p = plt.plot(axisX_data, axisY_data, label=syslabel[s] + (" (AUC=%.3f)" % auucc[s]), marker=marker, **kwargs)
if s + 1 == len(self.d):
oplab = 'OP'
else:
oplab = None
plt.plot(x_op, y_op, marker='o', color=p[0].get_color(), label=oplab, markerfacecolor='w',
markeredgewidth=1.5, markeredgecolor=p[0].get_color())
axisX_label = self.axes_idx2descr[self.x_axis_idx]
axisY_label = self.axes_idx2descr[self.y_axis_idx]
axisX_units = "(raw)" if np.isclose(xnorm, 1.0) else "[in std deviations]"
axisY_units = "(raw)" if np.isclose(ynorm, 1.0) else "[in std deviations]"
axisX_label += ' ' + axisX_units
axisY_label += ' ' + axisY_units
if ylim is not None:
plt.ylim(ylim)
if xlim is not None:
plt.xlim(xlim)
plt.xlabel(axisX_label)
plt.ylabel(axisY_label)
plt.legend()
plt.title(titlestr)
plt.grid()
if outfn is None:
plt.show()
else:
plt.savefig(outfn)
if len(auucc) < 2:
auucc = auucc[0]
op_info = op_info[0]
return auucc, op_info
<s> from .uncertainty_characteristics_curve import UncertaintyCharacteristicsCurve
<s> import abc
import sys
# Ensure compatibility with Python 2/3
if sys.version_info >= (3, 4):
ABC = abc.ABC
else:
ABC = abc.ABCMeta(str('ABC'), (), {})
class BuiltinUQ(ABC):
""" BuiltinUQ is the base class for any algorithm that has UQ built into it.
"""
def __init__(self, *argv, **kwargs):
""" Initialize a BuiltinUQ object.
"""
@abc.abstractmethod
def fit(self, *argv, **kwargs):
""" Learn the UQ related parameters..
"""
raise NotImplementedError
@abc.abstractmethod
def predict(self, *argv, **kwargs):
""" Method to obtain the predicitve uncertainty, this can return the total, epistemic and/or aleatoric
uncertainty in the predictions.
"""
raise NotImplementedError
def set_params(self, **parameters):
for parameter, value in parameters.items():
setattr(self, parameter, value)
return self
<s> import abc
import sys
# Ensure compatibility with Python 2/3
if sys.version_info >= (3, 4):
ABC = abc.ABC
else:
ABC = abc.ABCMeta(str('ABC'), (), {})
class PostHocUQ(ABC):
""" PostHocUQ is the base class for any algorithm that quantifies uncertainty of a pre-trained model.
"""
def __init__(self, *argv, **kwargs):
""" Initialize a BuiltinUQ object.
"""
@abc.abstractmethod
def _process_pretrained_model(self, *argv, **kwargs):
""" Method to process the pretrained model that requires UQ.
"""
raise NotImplementedError
@abc.abstractmethod
def predict(self, *argv, **kwargs):
""" Method to obtain the predicitve uncertainty, this can return the total, epistemic and/or aleatoric
uncertainty in the predictions.
"""
raise NotImplementedError
def set_params(self, **parameters):
for parameter, value in parameters.items():
setattr(self, parameter, value)
return self
def get_params(self):
"""
This method should not take any arguments and returns a dict of the __init__ parameters.
"""
raise NotImplementedError
<s><s> from collections import namedtuple
import numpy as np
import torch
from scipy.stats import norm
from torch.utils.data import DataLoader
from torch.utils.data import TensorDataset
from uq360.algorithms.builtinuq import BuiltinUQ
from uq360.models.heteroscedastic_mlp import GaussianNoiseMLPNet as _MLPNet
np.random.seed(42)
torch.manual_seed(42)
class HeteroscedasticRegression(BuiltinUQ):
""" Wrapper for heteroscedastic regression. We learn to predict targets given features,
assuming that the targets are noisy and that the amount of noise varies between data points.
https://en.wikipedia.org/wiki/Heteroscedasticity
"""
def __init__(self, model_type=None, model=None, config=None, device=None, verbose=True):
"""
Args:
model_type: The base model architecture. Currently supported values are [mlp].
mlp modeltype learns a multi-layer perceptron with a heteroscedastic Gaussian likelihood. Both the
mean and variance of the Gaussian are functions of the data point ->git N(y_n | mlp_mu(x_n), mlp_var(x_n))
model: (optional) The prediction model. Currently support pytorch models that returns mean and log variance.
config: dictionary containing the config parameters for the model.
device: device used for pytorch models ignored otherwise.
verbose: if True, print statements with the progress are enabled.
"""
super(HeteroscedasticRegression).__init__()
self.config = config
self.device = device
self.verbose = verbose
if model_type == "mlp":
self.model_type = model_type
self.model = _MLPNet(
num_features=self.config["num_features"],
num_outputs=self.config["num_outputs"],
num_hidden=self.config["num_hidden"],
)
elif model_type == "custom":
self.model_type = model_type
self.model = model
else:
raise NotImplementedError
def get_params(self, deep=True):
return {"model_type": self.model_type, "config": self.config, "model": self.model,
"device": self.device, "verbose": self.verbose}
def _loss(self, y_true, y_pred_mu, y_pred_log_var):
return torch.mean(0.5 * torch.exp(-y_pred_log_var) * torch.abs(y_true - y_pred_mu) ** 2 +
0.5 * y_pred_log_var)
def fit(self, X, y):
""" Fit the Heteroscedastic Regression model.
Args:
X: array-like of shape (n_samples, n_features).
Features vectors of the training data.
y: array-like of shape (n_samples,) or (n_samples, n_targets)
Target values
Returns:
self
"""
X = torch.from_numpy(X).float().to(self.device)
y = torch.from_numpy(y).float().to(self.device)
dataset_loader = DataLoader(
TensorDataset(X,y),
batch_size=self.config["batch_size"]
)
optimizer = torch.optim.Adam(self.model.parameters(), lr=self.config["lr"])
for epoch in range(self.config["num_epochs"]):
avg_loss = 0.0
for batch_x, batch_y in dataset_loader:
self.model.train()
batch_y_pred_mu, batch_y_pred_log_var = self.model(batch_x)
loss = self.model.loss(batch_y, batch_y_pred_mu, batch_y_pred_log_var)
optimizer.zero_grad()
loss.backward()
optimizer.step()
avg_loss += loss.item()/len(dataset_loader)
| ||
if self.verbose:
print("Epoch: {}, loss = {}".format(epoch, avg_loss))
return self
def predict(self, X, return_dists=False):
"""
Obtain predictions for the test points.
In addition to the mean and lower/upper bounds, also returns epistemic uncertainty (return_epistemic=True)
and full predictive distribution (return_dists=True).
Args:
X: array-like of shape (n_samples, n_features).
Features vectors of the test points.
return_dists: If True, the predictive distribution for each instance using scipy distributions is returned.
Returns:
namedtuple: A namedtupe that holds
y_mean: ndarray of shape (n_samples, [n_output_dims])
Mean of predictive distribution of the test points.
y_lower: ndarray of shape (n_samples, [n_output_dims])
Lower quantile of predictive distribution of the test points.
y_upper: ndarray of shape (n_samples, [n_output_dims])
Upper quantile of predictive distribution of the test points.
dists: list of predictive distribution as `scipy.stats` objects with length n_samples.
Only returned when `return_dists` is True.
"""
self.model.eval()
X = torch.from_numpy(X).float().to(self.device)
dataset_loader = DataLoader(
X,
batch_size=self.config["batch_size"]
)
y_mean_list = []
y_log_var_list = []
for batch_x in dataset_loader:
batch_y_pred_mu, batch_y_pred_log_var = self.model(batch_x)
y_mean_list.append(batch_y_pred_mu.data.cpu().numpy())
y_log_var_list.append(batch_y_pred_log_var.data.cpu().numpy())
y_mean = np.concatenate(y_mean_list)
y_log_var = np.concatenate(y_log_var_list)
y_std = np.sqrt(np.exp(y_log_var))
y_lower = y_mean - 2.0*y_std
y_upper = y_mean + 2.0*y_std
Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])
res = Result(y_mean, y_lower, y_upper)
if return_dists:
dists = [norm(loc=y_mean[i], scale=y_std[i]) for i in range(y_mean.shape[0])]
Result = namedtuple('res', Result._fields + ('y_dists',))
res = Result(*res, y_dists=dists)
return res
<s> from .heteroscedastic_regression import HeteroscedasticRegression<s> from collections import namedtuple
import numpy as np
from sklearn.calibration import CalibratedClassifierCV
from sklearn.preprocessing import LabelEncoder
from uq360.utils.misc import DummySklearnEstimator
from uq360.algorithms.posthocuq import PostHocUQ
class ClassificationCalibration(PostHocUQ):
"""Post hoc calibration of classification models. Currently wraps `CalibratedClassifierCV` from sklearn and allows
non-sklearn models to be calibrated.
"""
def __init__(self, num_classes, fit_mode="features", method='isotonic', base_model_prediction_func=None):
"""
Args:
num_classes: number of classes.
fit_mode: features or probs. If probs the `fit` and `predict` operate on the base models probability scores,
useful when these are precomputed.
method: isotonic or sigmoid.
base_model_prediction_func: the function that takes in the input features and produces base model's
probability scores. This is ignored when operating in `probs` mode.
"""
super(ClassificationCalibration).__init__()
if fit_mode == "probs":
# In this case, the fit assumes that it receives the probability scores of the base model.
# create a dummy estimator
self.base_model = DummySklearnEstimator(num_classes, lambda x: x)
else:
self.base_model = DummySklearnEstimator(num_classes, base_model_prediction_func)
self.method = method
def get_params(self, deep=True):
return {"num_classes": self.num_classes, "fit_mode": self.fit_mode, "method": self.method,
"base_model_prediction_func": self.base_model_prediction_func}
def _process_pretrained_model(self, base_model):
return base_model
def fit(self, X, y):
""" Fits calibration model using the provided calibration set.
Args:
X: array-like of shape (n_samples, n_features) or (n_samples, n_classes).
Features vectors of the training data or the probability scores from the base model.
y: array-like of shape (n_samples,) or (n_samples, n_targets)
Target values
Returns:
self
"""
self.base_model.label_encoder_ = LabelEncoder().fit(y)
self.calib_model = CalibratedClassifierCV(base_estimator=self.base_model,
cv="prefit",
method=self.method)
self.calib_model.fit(X, y)
return self
def predict(self, X):
"""
Obtain calibrated predictions for the test points.
Args:
X: array-like of shape (n_samples, n_features) or (n_samples, n_classes).
Features vectors of the training data or the probability scores from the base model.
Returns:
namedtuple: A namedtupe that holds
y_pred: ndarray of shape (n_samples,)
Predicted labels of the test points.
y_prob: ndarray of shape (n_samples, n_classes)
Predicted probability scores of the classes.
"""
y_prob = self.calib_model.predict_proba(X)
if len(np.shape(y_prob)) == 1:
y_pred_labels = y_prob > 0.5
else:
y_pred_labels = np.argmax(y_prob, axis=1)
Result = namedtuple('res', ['y_pred', 'y_prob'])
res = Result(y_pred_labels, y_prob)
return res
<s> from .classification_calibration import ClassificationCalibration
<s> from collections import namedtuple
import botorch
import gpytorch
import numpy as np
import torch
from botorch.models import SingleTaskGP
from botorch.utils.transforms import normalize
from gpytorch.constraints import GreaterThan
from scipy.stats import norm
from sklearn.preprocessing import StandardScaler
from uq360.algorithms.builtinuq import BuiltinUQ
np.random.seed(42)
torch.manual_seed(42)
class HomoscedasticGPRegression(BuiltinUQ):
""" A wrapper around Botorch SingleTask Gaussian Process Regression [1]_ with homoscedastic noise.
References:
.. [1] https://botorch.org/api/models.html#singletaskgp
"""
def __init__(self,
kernel=gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel()),
likelihood=None,
config=None):
"""
Args:
kernel: gpytorch kernel function with default set to `RBFKernel` with output scale.
likelihood: gpytorch likelihood function with default set to `GaussianLikelihood`.
config: dictionary containing the config parameters for the model.
"""
super(HomoscedasticGPRegression).__init__()
self.config = config
self.kernel = kernel
self.likelihood = likelihood
self.model = None
self.scaler = StandardScaler()
self.X_bounds = None
def get_params(self, deep=True):
return {"kernel": self.kernel, "likelihood": self.likelihood, "config": self.config}
def fit(self, X, y, **kwargs):
"""
Fit the GP Regression model.
Additional arguments relevant for SingleTaskGP fitting can be passed to this function.
Args:
X: array-like of shape (n_samples, n_features).
Features vectors of the training data.
y: array-like of shape (n_samples,) or (n_samples, n_targets)
Target values
**kwargs: Additional arguments relevant for SingleTaskGP fitting.
Returns:
self
"""
y = self.scaler.fit_transform(y)
X, y = torch.tensor(X), torch.tensor(y)
self.X_bounds = X_bounds = torch.stack([X.min() * torch.ones(X.shape[1]),
X.max() * torch.ones(X.shape[1])])
X = normalize(X, X_bounds)
model_homo = SingleTaskGP(train_X=X, train_Y=y, covar_module=self.kernel, likelihood=self.likelihood, **kwargs)
model_homo.likelihood.noise_covar.register_constraint("raw_noise", GreaterThan(1e-5))
model_homo_marginal_log_lik = gpytorch.mlls.ExactMarginalLogLikelihood(model_homo.likelihood, model_homo)
botorch.fit.fit_gpytorch_model(model_homo_marginal_log_lik)
model_homo_marginal_log_lik.eval()
self.model = model_homo_marginal_log_lik
self.inferred_observation_noise = self.scaler.inverse_transform(self.model.likelihood.noise.detach().numpy()[0].reshape(1,1)).squeeze()
return self
def predict(self, X, return_dists=False, return_epistemic=False, return_epistemic_dists=False):
"""
Obtain predictions for the test points.
In addition to the mean and lower/upper bounds, also returns epistemic uncertainty (return_epistemic=True)
and full predictive distribution (return_dists=True).
Args:
X: array-like of shape (n_samples, n_features).
Features vectors of the test points.
return_dists: If True, the predictive distribution for each instance using scipy distributions is returned.
return_epistemic: if True, the epistemic upper and lower bounds are returned.
return_epistemic_dists: If True, the epistemic distribution for each instance using scipy distributions
is returned.
Returns:
namedtuple: A namedtuple that holds
y_mean: ndarray of shape (n_samples, [n_output_dims])
Mean of predictive distribution of the test points.
y_lower: ndarray of shape (n_samples, [n_output_dims])
Lower quantile of predictive distribution of the test points.
y_upper: ndarray of shape (n_samples, [n_output_dims])
Upper quantile of predictive distribution of the test points.
y_lower_epistemic: ndarray of shape (n_samples, [n_output_dims])
Lower quantile of epistemic component of the predictive distribution of the test points.
Only returned when `return_epistemic` is True.
y_upper_epistemic: ndarray of shape (n_samples, [n_output_dims])
Upper quantile of epistemic component of the predictive distribution of the test points.
Only returned when `return_epistemic` is True.
dists: list of predictive distribution as `scipy.stats` objects with length n_samples.
Only returned when `return_dists` is True.
"""
X = torch.tensor(X)
X_test_norm = normalize(X, self.X_bounds)
self.model.eval()
with torch.no_grad():
posterior = self.model.model.posterior(X_test_norm)
y_mean = posterior.mean
#y_epi_std = torch.sqrt(posterior.variance)
y_lower_epistemic, y_upper_epistemic = posterior.mvn.confidence_region()
predictive_posterior = self.model.model.posterior(X_test_norm, observation_noise=True)
#y_std = torch.sqrt(predictive_posterior.variance)
y_lower_total, y_upper_total = predictive_posterior.mvn.confidence_region()
y_mean, y_lower, y_upper, y_lower_epistemic, y_upper_epistemic = self.scaler.inverse_transform(y_mean.numpy()).squeeze(), \\
self.scaler.inverse_transform(y_lower_total.numpy()).squeeze(),\\
self.scaler.inverse_transform(y_upper_total.numpy()).squeeze(),\\
self.scaler.inverse_transform(y_lower_epistemic.numpy()).squeeze(),\\
self.scaler.inverse_transform(y_upper_epistemic.numpy()).squeeze()
y_epi_std = (y_upper_epistemic - y_lower_epistemic) / 4.0
y_std = (y_upper_total - y_lower_total) / 4.0
Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])
res = Result(y_mean, y_lower, y_upper)
if return_epistemic:
Result = namedtuple('res', Result._fields + ('y_lower_epistemic', 'y_upper_epistemic',))
res = Result(*res, y_lower_epistemic=y_lower_epistemic, y_upper_epistemic=y_upper_epistemic)
if return_dists:
dists = [norm(loc=y_mean[i], scale=y_std[i]) for i in range(y_mean.shape[0])]
Result = namedtuple('res', Result._fields + ('y_dists',))
res = Result(*res, y_dists=dists)
if return_epistemic_dists:
epi_dists = [norm(loc=y_mean[i], scale=y_epi_std[i]) for i in range(y_mean.shape[0])]
Result = namedtuple('res', Result._fields + ('y_epistemic_dists',))
res = Result(*res, y_epistemic_dists=epi_dists)
return res
<s> from .homoscedastic_gaussian_process_regression import HomoscedasticGPRegression<s> from collections import namedtuple
from sklearn.ensemble import GradientBoostingRegressor
from uq360.algorithms.builtinuq import BuiltinUQ
class QuantileRegression(BuiltinUQ):
"""Quantile Regression uses quantile loss and learns two separate models for the upper and lower quantile
to obtain the prediction intervals.
"""
def __init__(self, model_type="gbr | ||
", config=None):
"""
Args:
model_type: The base model used for predicting a quantile. Currently supported values are [gbr].
gbr is sklearn GradientBoostingRegressor.
config: dictionary containing the config parameters for the model.
"""
super(QuantileRegression).__init__()
if config is not None:
self.config = config
else:
self.config = {}
if "alpha" not in self.config:
self.config["alpha"] = 0.95
if model_type == "gbr":
self.model_type = model_type
self.model_mean = GradientBoostingRegressor(
loss='ls',
n_estimators=self.config["n_estimators"],
max_depth=self.config["max_depth"],
learning_rate=self.config["learning_rate"],
min_samples_leaf=self.config["min_samples_leaf"],
min_samples_split=self.config["min_samples_split"]
)
self.model_upper = GradientBoostingRegressor(
loss='quantile',
alpha=self.config["alpha"],
n_estimators=self.config["n_estimators"],
max_depth=self.config["max_depth"],
learning_rate=self.config["learning_rate"],
min_samples_leaf=self.config["min_samples_leaf"],
min_samples_split=self.config["min_samples_split"]
)
self.model_lower = GradientBoostingRegressor(
loss='quantile',
alpha=1.0 - self.config["alpha"],
n_estimators=self.config["n_estimators"],
max_depth=self.config["max_depth"],
learning_rate=self.config["learning_rate"],
min_samples_leaf=self.config["min_samples_leaf"],
min_samples_split=self.config["min_samples_split"])
else:
raise NotImplementedError
def get_params(self, deep=True):
return {"model_type": self.model_type, "config": self.config}
def fit(self, X, y):
""" Fit the Quantile Regression model.
Args:
X: array-like of shape (n_samples, n_features).
Features vectors of the training data.
y: array-like of shape (n_samples,) or (n_samples, n_targets)
Target values
Returns:
self
"""
self.model_mean.fit(X, y)
self.model_lower.fit(X, y)
self.model_upper.fit(X, y)
return self
def predict(self, X):
"""
Obtain predictions for the test points.
In addition to the mean and lower/upper bounds, also returns epistemic uncertainty (return_epistemic=True)
and full predictive distribution (return_dists=True).
Args:
X: array-like of shape (n_samples, n_features).
Features vectors of the test points.
Returns:
namedtuple: A namedtupe that holds
y_mean: ndarray of shape (n_samples, [n_output_dims])
Mean of predictive distribution of the test points.
y_lower: ndarray of shape (n_samples, [n_output_dims])
Lower quantile of predictive distribution of the test points.
y_upper: ndarray of shape (n_samples, [n_output_dims])
Upper quantile of predictive distribution of the test points.
"""
y_mean = self.model_mean.predict(X)
y_lower = self.model_lower.predict(X)
y_upper = self.model_upper.predict(X)
Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])
res = Result(y_mean, y_lower, y_upper)
return res
<s> from .quantile_regression import QuantileRegression
<s> import inspect
from collections import namedtuple
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import train_test_split
from sklearn.exceptions import NotFittedError
from uq360.algorithms.posthocuq import PostHocUQ
class BlackboxMetamodelRegression(PostHocUQ):
""" Extracts confidence scores from black-box regression models using a meta-model [2]_ .
References:
.. [2] Chen, Tongfei, et al. Confidence scoring using whitebox meta-models with linear classifier probes.
The 22nd International Conference on Artificial Intelligence and Statistics. PMLR, 2019.
"""
def _create_named_model(self, mdltype, config):
"""
Instantiates a model by name passed in 'mdltype'
:param mdltype: string with name (must be supprted)
:param config: dict with args passed in the instantiation call
:return: mdl instance
"""
assert (isinstance(mdltype, str))
if mdltype == 'gbr':
mdl = GradientBoostingRegressor(**config)
else:
raise NotImplementedError("ERROR: Requested model type unknown: \\"%s\\"" % mdltype)
return mdl
def _get_model_instance(self, model, config):
"""
Returns an instance of a model based on (a) a desired name or (b) passed in class, or
(c) passed in instance
:param model: string, class, or instance. Class and instance must have certain methods callable.
:param config: dict with args passed in during the instantiation
:return: model instance
"""
assert (model is not None and config is not None)
if isinstance(model, str): # 'model' is a name, create it
mdl = self._create_named_model(model, config)
elif inspect.isclass(model): # 'model' is a class, instantiate it
mdl = model(**config)
else: # 'model' is an instance, register it
mdl = model
if not all([hasattr(mdl, key) and callable(getattr(mdl, key)) for key in self.callable_keys]):
raise ValueError("ERROR: Passed model/method failed the interface test. Methods required: %s" %
','.join(self.callable_keys))
return mdl
def __init__(self, base_model=None, meta_model=None, base_config=None, meta_config=None, random_seed=42):
"""
:param base_model: Base model. Can be:
(1) None (default mdl will be set up),
(2) Named model (e.g., 'gbr'),
(3) Base model class declaration (e.g., sklearn.linear_model.LinearRegressor). Will instantiate.
(4) Model instance (instantiated outside). Will be re-used. Must have required callable methods.
Note: user-supplied classes and models must have certain callable methods ('predict', 'fit')
and be capable of raising NotFittedError.
:param meta_model: Meta model. Same values possible as with 'base_model'
:param base_config: None or a params dict to be passed to 'base_model' at instantiation
:param meta_config: None or a params dict to be passed to 'meta_model' at instantiation
:param random_seed: seed used in the various pipeline steps
"""
super(BlackboxMetamodelRegression).__init__()
self.random_seed = random_seed
self.callable_keys = ['predict', 'fit'] # required methods - must be present in models passed in
self.base_model_default = 'gbr'
self.meta_model_default = 'gbr'
self.base_config_default = {'loss': 'ls', 'n_estimators': 300, 'max_depth': 10, 'learning_rate': 0.001,
'min_samples_leaf': 10, 'min_samples_split': 10, 'random_state': self.random_seed}
self.meta_config_default = {'loss': 'quantile', 'alpha': 0.95, 'n_estimators': 300, 'max_depth': 10,
'learning_rate': 0.001, 'min_samples_leaf': 10, 'min_samples_split': 10,
'random_state': self.random_seed}
self.base_config = base_config if base_config is not None else self.base_config_default
self.meta_config = meta_config if meta_config is not None else self.meta_config_default
self.base_model = None
self.meta_model = None
self.base_model = self._get_model_instance(base_model if base_model is not None else self.base_model_default,
self.base_config)
self.meta_model = self._get_model_instance(meta_model if meta_model is not None else self.meta_model_default,
self.meta_config)
def get_params(self, deep=True):
return {"base_model": self.base_model, "meta_model": self.meta_model, "base_config": self.base_config,
"meta_config": self.meta_config, "random_seed": self.random_seed}
def fit(self, X, y, meta_fraction=0.2, randomize_samples=True, base_is_prefitted=False,
meta_train_data=(None, None)):
"""
Fit base and meta models.
:param X: input to the base model
:param y: ground truth for the base model
:param meta_fraction: float in [0,1] - a fractional size of the partition carved out to train the meta model
(complement will be used to train the base model)
:param randomize_samples: use shuffling when creating partitions
:param base_is_prefitted: Setting True will skip fitting the base model (useful for base models that have been
instantiated outside/by the user and are already fitted.
:param meta_train_data: User supplied data to train the meta model. Note that this option should only be used
with 'base_is_prefitted'==True. Pass a tuple meta_train_data=(X_meta, y_meta) to activate.
Note that (X,y,meta_fraction, randomize_samples) will be ignored in this mode.
:return: self
"""
X = np.asarray(X)
y = np.asarray(y)
assert(len(meta_train_data)==2)
if meta_train_data[0] is None:
X_base, X_meta, y_base, y_meta = train_test_split(X, y, shuffle=randomize_samples, test_size=meta_fraction,
random_state=self.random_seed)
else:
if not base_is_prefitted:
raise ValueError("ERROR: fit(): base model must be pre-fitted to use the 'meta_train_data' option")
X_base = y_base = None
X_meta = meta_train_data[0]
y_meta = meta_train_data[1]
# fit the base model
if not base_is_prefitted:
self.base_model.fit(X_base, y_base)
# get input for the meta model from the base
try:
y_hat_meta = self.base_model.predict(X_meta)
except NotFittedError as e:
raise RuntimeError("ERROR: fit(): The base model appears not pre-fitted (%s)" % repr(e))
# used base input and output as meta input
X_meta_in = self._process_pretrained_model(X_meta, y_hat_meta)
# train meta model to predict abs diff
self.meta_model.fit(X_meta_in, np.abs(y_hat_meta - y_meta))
return self
def _process_pretrained_model(self, X, y_hat):
"""
Given the original input features and the base output probabilities, generate input features
to train a meta model. Current implementation copies all input features and appends.
:param X: numpy [nsamples, dim]
:param y_hat: [nsamples,]
:return: array with new features [nsamples, newdim]
"""
y_hat_meta_prime = np.expand_dims(y_hat, -1) if len(y_hat.shape) < 2 else y_hat
X_meta_in = np.hstack([X, y_hat_meta_prime])
return X_meta_in
def predict(self, X):
"""
Generate prediction and uncertainty bounds for data X.
:param X: input features
:return: namedtuple: A namedtuple that holds
y_mean: ndarray of shape (n_samples, [n_output_dims])
Mean of predictive distribution of the test points.
y_lower: ndarray of shape (n_samples, [n_output_dims])
Lower quantile of predictive distribution of the test points.
y_upper: ndarray of shape (n_samples, [n_output_dims])
Upper quantile of predictive distribution of the test points.
"""
y_hat = self.base_model.predict(X)
y_hat_prime = np.expand_dims(y_hat, -1) if len(y_hat.shape) < 2 else y_hat
X_meta_in = np.hstack([X, y_hat_prime])
z_hat = self.meta_model.predict(X_meta_in)
Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])
res = Result(y_hat, y_hat - z_hat, y_hat + z_hat)
return res
<s> import inspect
from collections import namedtuple
import numpy as np
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.exceptions import NotFittedError
from uq360.algorithms.posthocuq import PostHocUQ
class BlackboxMetamodelClassification(PostHocUQ):
""" Extracts confidence scores from black-box classification models using a meta-model [4]_ .
References:
.. [4] Chen, Tongfei, et al. "Confidence scoring using whitebox meta-models with linear classifier probes."
The 22nd International Conference on Artificial Intelligence and Statistics. PMLR, 2019.
"""
def _create_named_model(self, mdltype, config):
""" Instantiates a model by name passed in 'mdltype'.
Args:
mdltype: string with name (must be supported)
config: dict with args passed in the instantiation call
Returns:
mdl instance
"""
assert (isinstance(mdltype, str))
if mdltype == 'lr':
mdl = LogisticRegression(**config)
elif mdltype == 'gbm':
mdl = GradientBoostingClassifier(**config)
else:
raise NotImplementedError("ERROR: Requested model type unknown: \\"%s\\"" % mdltype)
return mdl
def _get_model_instance(self, model, config):
""" Returns an instance of a model based on (a) a desired name or (b) passed in class, or
(c) passed in instance.
:param model: string, class, or instance. Class and instance must have certain methods callable.
: | ||
param config: dict with args passed in during the instantiation
:return: model instance
"""
assert (model is not None and config is not None)
if isinstance(model, str): # 'model' is a name, create it
mdl = self._create_named_model(model, config)
elif inspect.isclass(model): # 'model' is a class, instantiate it
mdl = model(**config)
else: # 'model' is an instance, register it
mdl = model
if not all([hasattr(mdl, key) and callable(getattr(mdl, key)) for key in self.callable_keys]):
raise ValueError("ERROR: Passed model/method failed the interface test. Methods required: %s" %
','.join(self.callable_keys))
return mdl
def __init__(self, base_model=None, meta_model=None, base_config=None, meta_config=None, random_seed=42):
"""
:param base_model: Base model. Can be:
(1) None (default mdl will be set up),
(2) Named model (e.g., logistic regression 'lr' or gradient boosting machine 'gbm'),
(3) Base model class declaration (e.g., sklearn.linear_model.LogisticRegression). Will instantiate.
(4) Model instance (instantiated outside). Will be re-used. Must have certain callable methods.
Note: user-supplied classes and models must have certain callable methods ('predict', 'fit')
and be capable of raising NotFittedError.
:param meta_model: Meta model. Same values possible as with 'base_model'
:param base_config: None or a params dict to be passed to 'base_model' at instantiation
:param meta_config: None or a params dict to be passed to 'meta_model' at instantiation
:param random_seed: seed used in the various pipeline steps
"""
super(BlackboxMetamodelClassification).__init__()
self.random_seed = random_seed
self.callable_keys = ['predict', 'fit'] # required methods - must be present in models passed in
self.base_model_default = 'gbm'
self.meta_model_default = 'lr'
self.base_config_default = {'n_estimators': 300, 'max_depth': 10,
'learning_rate': 0.001, 'min_samples_leaf': 10, 'min_samples_split': 10,
'random_state': self.random_seed}
self.meta_config_default = {'penalty': 'l1', 'C': 1, 'solver': 'liblinear', 'random_state': self.random_seed}
self.base_config = base_config if base_config is not None else self.base_config_default
self.meta_config = meta_config if meta_config is not None else self.meta_config_default
self.base_model = None
self.meta_model = None
self.base_model = self._get_model_instance(base_model if base_model is not None else self.base_model_default,
self.base_config)
self.meta_model = self._get_model_instance(meta_model if meta_model is not None else self.meta_model_default,
self.meta_config)
def get_params(self, deep=True):
return {"base_model": self.base_model, "meta_model": self.meta_model, "base_config": self.base_config,
"meta_config": self.meta_config, "random_seed": self.random_seed}
def _process_pretrained_model(self, X, y_hat_proba):
"""
Given the original input features and the base output probabilities, generate input features
to train a meta model. Current implementation copies all input features and appends.
:param X: numpy [nsamples, dim]
:param y_hat_proba: [nsamples, nclasses]
:return: array with new features [nsamples, newdim]
"""
assert (len(y_hat_proba.shape) == 2)
assert (X.shape[0] == y_hat_proba.shape[0])
# sort the probs sample by sample
faux1 = np.sort(y_hat_proba, axis=-1)
# add delta between top and second candidate
faux2 = np.expand_dims(faux1[:, -1] - faux1[:, -2], axis=-1)
return np.hstack([X, faux1, faux2])
def fit(self, X, y, meta_fraction=0.2, randomize_samples=True, base_is_prefitted=False,
meta_train_data=(None, None)):
"""
Fit base and meta models.
:param X: input to the base model,
array-like of shape (n_samples, n_features).
Features vectors of the training data.
:param y: ground truth for the base model,
array-like of shape (n_samples,)
:param meta_fraction: float in [0,1] - a fractional size of the partition carved out to train the meta model
(complement will be used to train the base model)
:param randomize_samples: use shuffling when creating partitions
:param base_is_prefitted: Setting True will skip fitting the base model (useful for base models that have been
instantiated outside/by the user and are already fitted.
:param meta_train_data: User supplied data to train the meta model. Note that this option should only be used
with 'base_is_prefitted'==True. Pass a tuple meta_train_data=(X_meta, y_meta) to activate.
Note that (X,y,meta_fraction, randomize_samples) will be ignored in this mode.
:return: self
"""
X = np.asarray(X)
y = np.asarray(y)
assert (len(meta_train_data) == 2)
if meta_train_data[0] is None:
X_base, X_meta, y_base, y_meta = train_test_split(X, y, shuffle=randomize_samples, test_size=meta_fraction,
random_state=self.random_seed)
else:
if not base_is_prefitted:
raise ValueError("ERROR: fit(): base model must be pre-fitted to use the 'meta_train_data' option")
X_base = y_base = None
X_meta = meta_train_data[0]
y_meta = meta_train_data[1]
# fit the base model
if not base_is_prefitted:
self.base_model.fit(X_base, y_base)
# get input for the meta model from the base
try:
y_hat_meta_proba = self.base_model.predict_proba(X_meta)
# determine correct-incorrect outcome - these are targets for the meta model trainer
# y_hat_meta_targets = np.asarray((y_meta == np.argmax(y_hat_meta_proba, axis=-1)), dtype=np.int) -- Fix for python 3.8.11 update (in 2.9.0.8)
y_hat_meta_targets = np.asarray((y_meta == np.argmax(y_hat_meta_proba, axis=-1)), dtype=int)
except NotFittedError as e:
raise RuntimeError("ERROR: fit(): The base model appears not pre-fitted (%s)" % repr(e))
# get input features for meta training
X_meta_in = self._process_pretrained_model(X_meta, y_hat_meta_proba)
# train meta model to predict 'correct' vs. 'incorrect' of the base
self.meta_model.fit(X_meta_in, y_hat_meta_targets)
return self
def predict(self, X):
"""
Generate a base prediction along with uncertainty/confidence for data X.
:param X: array-like of shape (n_samples, n_features).
Features vectors of the test points.
:return: namedtuple: A namedtuple that holds
y_pred: ndarray of shape (n_samples,)
Predicted labels of the test points.
y_score: ndarray of shape (n_samples,)
Confidence score the test points.
"""
y_hat_proba = self.base_model.predict_proba(X)
y_hat = np.argmax(y_hat_proba, axis=-1)
X_meta_in = self._process_pretrained_model(X, y_hat_proba)
z_hat = self.meta_model.predict_proba(X_meta_in)
index_of_class_1 = np.where(self.meta_model.classes_ == 1)[0][0] # class 1 corresponds to probab of positive/correct outcome
Result = namedtuple('res', ['y_pred', 'y_score'])
res = Result(y_hat, z_hat[:, index_of_class_1])
return res
<s> from .blackbox_metamodel_regression import BlackboxMetamodelRegression
from .blackbox_metamodel_classification import BlackboxMetamodelClassification
<s> from collections import namedtuple
from uq360.algorithms.posthocuq import PostHocUQ
from uq360.utils.misc import form_D_for_auucc
from uq360.metrics.uncertainty_characteristics_curve.uncertainty_characteristics_curve import UncertaintyCharacteristicsCurve
class UCCRecalibration(PostHocUQ):
""" Recalibration a regression model to specified operating point using Uncertainty Characteristics Curve.
"""
def __init__(self, base_model):
"""
Args:
base_model: pretrained model to be recalibrated.
"""
super(UCCRecalibration).__init__()
self.base_model = self._process_pretrained_model(base_model)
self.ucc = None
def get_params(self, deep=True):
return {"base_model": self.base_model}
def _process_pretrained_model(self, base_model):
return base_model
def fit(self, X, y):
"""
Fit the Uncertainty Characteristics Curve.
Args:
X: array-like of shape (n_samples, n_features).
Features vectors of the test points.
y: array-like of shape (n_samples,) or (n_samples, n_targets)
Target values
Returns:
self
"""
y_pred_mean, y_pred_lower, y_pred_upper = self.base_model.predict(X)[:3]
bwu = y_pred_upper - y_pred_mean
bwl = y_pred_mean - y_pred_lower
self.ucc = UncertaintyCharacteristicsCurve()
self.ucc.fit(form_D_for_auucc(y_pred_mean, bwl, bwu), y.squeeze())
return self
def predict(self, X, missrate=0.05):
"""
Generate prediction and uncertainty bounds for data X.
Args:
X: array-like of shape (n_samples, n_features).
Features vectors of the test points.
missrate: desired missrate of the new operating point, set to 0.05 by default.
Returns:
namedtuple: A namedtupe that holds
y_mean: ndarray of shape (n_samples, [n_output_dims])
Mean of predictive distribution of the test points.
y_lower: ndarray of shape (n_samples, [n_output_dims])
Lower quantile of predictive distribution of the test points.
y_upper: ndarray of shape (n_samples, [n_output_dims])
Upper quantile of predictive distribution of the test points.
"""
C = self.ucc.get_specific_operating_point(req_y_axis_value=missrate, vary_bias=False)
new_scale = C['modvalue']
y_pred_mean, y_pred_lower, y_pred_upper = self.base_model.predict(X)[:3]
bwu = y_pred_upper - y_pred_mean
bwl = y_pred_mean - y_pred_lower
if C['operation'] == 'bias':
calib_y_pred_upper = y_pred_mean + (new_scale + bwu) # lower bound width
calib_y_pred_lower = y_pred_mean - (new_scale + bwl) # Upper bound width
else:
calib_y_pred_upper = y_pred_mean + (new_scale * bwu) # lower bound width
calib_y_pred_lower = y_pred_mean - (new_scale * bwl) # Upper bound width
Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])
res = Result(y_pred_mean, calib_y_pred_lower, calib_y_pred_upper)
return res
<s> from .ucc_recalibration import UCCRecalibration
<s> from collections import namedtuple
import numpy as np
from uq360.algorithms.posthocuq import PostHocUQ
class InfinitesimalJackknife(PostHocUQ):
"""
Performs a first order Taylor series expansion around MLE / MAP fit.
Requires the model being probed to be twice differentiable.
"""
def __init__(self, params, gradients, hessian, config):
""" Initialize IJ.
Args:
params: MLE / MAP fit around which uncertainty is sought. d*1
gradients: Per data point gradients, estimated at the MLE / MAP fit. d*n
hessian: Hessian evaluated at the MLE / MAP fit. d*d
"""
super(InfinitesimalJackknife).__init__()
self.params_one = params
self.gradients = gradients
self.hessian = hessian
self.d, self.n = gradients.shape
self.dParams_dWeights = -np.linalg.solve(self.hessian, self.gradients)
self.approx_dParams_dWeights = -np.linalg.solve(np.diag(np.diag(self.hessian)), self.gradients)
self.w_one = np.ones([self.n])
self.config = config
def get_params(self, deep=True):
return {"params": self.params, "config": self.config, "gradients": self.gradients,
"hessian": self.hessian}
def _process_pretrained_model(self, *argv, **kwargs):
pass
def get_parameter_uncertainty(self):
if (self.config['resampling_strategy'] == "jackknife") or (self.config['resampling_strategy'] == "jackknife+"):
w_query = np.ones_like(self.w_one)
resampled_params = np.zeros([self.n, self.d])
for i in np.arange(self.n):
w_query[i] = 0
resampled_params[i] = self.ij(w_query)
w_query[i] = 1
return np.cov(resampled_params), resampled_params
elif self.config['resampling_strategy'] == "bootstrap":
pass
else:
raise NotImplemented | ||
Error("Only jackknife, jackknife+, and bootstrap resampling strategies are supported")
def predict(self, X, model):
"""
Args:
X: array-like of shape (n_samples, n_features).
Features vectors of the test points.
model: model object, must implement a set_parameters function
Returns:
namedtuple: A namedtupe that holds
y_mean: ndarray of shape (n_samples, [n_output_dims])
Mean of predictive distribution of the test points.
y_lower: ndarray of shape (n_samples, [n_output_dims])
Lower quantile of predictive distribution of the test points.
y_upper: ndarray of shape (n_samples, [n_output_dims])
Upper quantile of predictive distribution of the test points.
"""
n, _ = X.shape
y_all = model.predict(X)
_, d_out = y_all.shape
params_cov, params = self.get_parameter_uncertainty()
if d_out > 1:
print("Quantiles are computed independently for each dimension. May not be accurate.")
y = np.zeros([params.shape[0], n, d_out])
for i in np.arange(params.shape[0]):
model.set_parameters(params[i])
y[i] = model.predict(X)
y_lower = np.quantile(y, q=0.5 * self.config['alpha'], axis=0)
y_upper = np.quantile(y, q=(1. - 0.5 * self.config['alpha']), axis=0)
y_mean = y.mean(axis=0)
Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])
res = Result(y_mean, y_lower, y_upper)
return res
def ij(self, w_query):
"""
Args:
w_query: A n*1 vector to query parameters at.
Return:
new parameters at w_query
"""
assert w_query.shape[0] == self.n
return self.params_one + self.dParams_dWeights @ (w_query-self.w_one).T
def approx_ij(self, w_query):
"""
Args:
w_query: A n*1 vector to query parameters at.
Return:
new parameters at w_query
"""
assert w_query.shape[0] == self.n
return self.params_one + self.approx_dParams_dWeights @ (w_query-self.w_one).T<s> from .infinitesimal_jackknife import InfinitesimalJackknife
<s> import copy
from collections import namedtuple
import numpy as np
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torch.utils.data as data_utils
from scipy.stats import norm
from sklearn.preprocessing import StandardScaler
from uq360.algorithms.builtinuq import BuiltinUQ
from uq360.models.bayesian_neural_networks.bnn_models import horseshoe_mlp, bayesian_mlp
class BnnRegression(BuiltinUQ):
"""
Variationally trained BNNs with Gaussian and Horseshoe [6]_ priors for regression.
References:
.. [6] Ghosh, Soumya, Jiayu Yao, and Finale Doshi-Velez. "Structured variational learning of Bayesian neural
networks with horseshoe priors." International Conference on Machine Learning. PMLR, 2018.
"""
def __init__(self, config, prior="Gaussian"):
"""
Args:
config: a dictionary specifying network and learning hyperparameters.
prior: BNN priors specified as a string. Supported priors are Gaussian, Hshoe, RegHshoe
"""
super(BnnRegression, self).__init__()
self.config = config
if prior == "Gaussian":
self.net = bayesian_mlp.BayesianRegressionNet(ip_dim=config['ip_dim'], op_dim=config['op_dim'],
num_nodes=config['num_nodes'], num_layers=config['num_layers'])
self.config['use_reg_hshoe'] = None
elif prior == "Hshoe":
self.net = horseshoe_mlp.HshoeRegressionNet(ip_dim=config['ip_dim'], op_dim=config['op_dim'],
num_nodes=config['num_nodes'], num_layers=config['num_layers'],
hshoe_scale=config['hshoe_scale'])
self.config['use_reg_hshoe'] = False
elif prior == "RegHshoe":
self.net = horseshoe_mlp.HshoeRegressionNet(ip_dim=config['ip_dim'], op_dim=config['op_dim'],
num_nodes=config['num_nodes'], num_layers=config['num_layers'],
hshoe_scale=config['hshoe_scale'],
use_reg_hshoe=config['use_reg_hshoe'])
self.config['use_reg_hshoe'] = True
else:
raise NotImplementedError("'prior' must be a string. It can be one of Gaussian, Hshoe, RegHshoe")
def get_params(self, deep=True):
return {"prior": self.prior, "config": self.config}
def fit(self, X, y):
""" Fit the BNN regression model.
Args:
X: array-like of shape (n_samples, n_features).
Features vectors of the training data.
y: array-like of shape (n_samples,) or (n_samples, n_targets)
Target values
Returns:
self
"""
torch.manual_seed(1234)
optimizer = torch.optim.Adam(self.net.parameters(), lr=self.config['step_size'])
neg_elbo = torch.zeros([self.config['num_epochs'], 1])
params_store = {}
for epoch in range(self.config['num_epochs']):
loss = self.net.neg_elbo(num_batches=1, x=X, y=y.float().unsqueeze(dim=1)) / X.shape[0]
optimizer.zero_grad()
loss.backward()
optimizer.step()
if hasattr(self.net, 'fixed_point_updates'):
# for hshoe or regularized hshoe nets
self.net.fixed_point_updates()
neg_elbo[epoch] = loss.item()
if (epoch + 1) % 10 == 0:
# print ((net.noise_layer.bhat/net.noise_layer.ahat).data.numpy()[0])
print('Epoch[{}/{}], neg elbo: {:.6f}, noise var: {:.6f}'
.format(epoch + 1, self.config['num_epochs'], neg_elbo[epoch].item() / X.shape[0],
self.net.get_noise_var()))
params_store[epoch] = copy.deepcopy(self.net.state_dict()) # for small nets we can just store all.
best_model_id = neg_elbo.argmin() # loss_val_store.argmin() #
self.net.load_state_dict(params_store[best_model_id.item()])
return self
def predict(self, X, mc_samples=100, return_dists=False, return_epistemic=True, return_epistemic_dists=False):
"""
Obtain predictions for the test points.
In addition to the mean and lower/upper bounds, also returns epistemic uncertainty (return_epistemic=True)
and full predictive distribution (return_dists=True).
Args:
X: array-like of shape (n_samples, n_features).
Features vectors of the test points.
mc_samples: Number of Monte-Carlo samples.
return_dists: If True, the predictive distribution for each instance using scipy distributions is returned.
return_epistemic: if True, the epistemic upper and lower bounds are returned.
return_epistemic_dists: If True, the epistemic distribution for each instance using scipy distributions
is returned.
Returns:
namedtuple: A namedtupe that holds
y_mean: ndarray of shape (n_samples, [n_output_dims])
Mean of predictive distribution of the test points.
y_lower: ndarray of shape (n_samples, [n_output_dims])
Lower quantile of predictive distribution of the test points.
y_upper: ndarray of shape (n_samples, [n_output_dims])
Upper quantile of predictive distribution of the test points.
y_lower_epistemic: ndarray of shape (n_samples, [n_output_dims])
Lower quantile of epistemic component of the predictive distribution of the test points.
Only returned when `return_epistemic` is True.
y_upper_epistemic: ndarray of shape (n_samples, [n_output_dims])
Upper quantile of epistemic component of the predictive distribution of the test points.
Only returned when `return_epistemic` is True.
dists: list of predictive distribution as `scipy.stats` objects with length n_samples.
Only returned when `return_dists` is True.
"""
epistemic_out = np.zeros([mc_samples, X.shape[0]])
total_out = np.zeros([mc_samples, X.shape[0]])
for s in np.arange(mc_samples):
pred = self.net(X).data.numpy().ravel()
epistemic_out[s] = pred
total_out[s] = pred + np.sqrt(self.net.get_noise_var()) * np.random.randn(pred.shape[0])
y_total_std = np.std(total_out, axis=0)
y_epi_std = np.std(epistemic_out, axis=0)
y_mean = np.mean(total_out, axis=0)
y_lower = y_mean - 2 * y_total_std
y_upper = y_mean + 2 * y_total_std
y_epi_lower = y_mean - 2 * y_epi_std
y_epi_upper = y_mean + 2 * y_epi_std
Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])
res = Result(y_mean, y_lower, y_upper)
if return_epistemic:
Result = namedtuple('res', Result._fields + ('lower_epistemic', 'upper_epistemic',))
res = Result(*res, lower_epistemic=y_epi_lower, upper_epistemic=y_epi_upper)
if return_dists:
dists = [norm(loc=y_mean[i], scale=y_total_std[i]) for i in range(y_mean.shape[0])]
Result = namedtuple('res', Result._fields + ('y_dists',))
res = Result(*res, y_dists=dists)
if return_epistemic_dists:
epi_dists = [norm(loc=y_mean[i], scale=y_epi_std[i]) for i in range(y_mean.shape[0])]
Result = namedtuple('res', Result._fields + ('y_epistemic_dists',))
res = Result(*res, y_epistemic_dists=epi_dists)
return res
class BnnClassification(BuiltinUQ):
"""
Variationally trained BNNs with Gaussian and Horseshoe [6]_ priors for classification.
"""
def __init__(self, config, prior="Gaussian", device=None):
"""
Args:
config: a dictionary specifying network and learning hyperparameters.
prior: BNN priors specified as a string. Supported priors are Gaussian, Hshoe, RegHshoe
"""
super(BnnClassification, self).__init__()
self.config = config
self.device = device
if prior == "Gaussian":
self.net = bayesian_mlp.BayesianClassificationNet(ip_dim=config['ip_dim'], op_dim=config['op_dim'],
num_nodes=config['num_nodes'], num_layers=config['num_layers'])
self.config['use_reg_hshoe'] = None
elif prior == "Hshoe":
self.net = horseshoe_mlp.HshoeClassificationNet(ip_dim=config['ip_dim'], op_dim=config['op_dim'],
num_nodes=config['num_nodes'], num_layers=config['num_layers'],
hshoe_scale=config['hshoe_scale'])
self.config['use_reg_hshoe'] = False
elif prior == "RegHshoe":
self.net = horseshoe_mlp.HshoeClassificationNet(ip_dim=config['ip_dim'], op_dim=config['op_dim'],
num_nodes=config['num_nodes'], num_layers=config['num_layers'],
hshoe_scale=config['hshoe_scale'],
use_reg_hshoe=config['use_reg_hshoe'])
self.config['use_reg_hshoe'] = True
else:
raise NotImplementedError("'prior' must be a string. It can be one of Gaussian, Hshoe, RegHshoe")
if "batch_size" not in self.config:
self.config["batch_size"] = 50
self.net = self.net.to(device)
def get_params(self, deep=True):
return {"prior": self.prior, "config": self.config, "device": self.device}
def fit(self, X=None, y=None, train_loader=None):
""" Fits BNN regression model.
Args:
X: array-like of shape (n_samples, n_features) or (n_samples, n_classes).
Features vectors of the training data or the probability scores from the base model.
Ignored if train_loader is not None.
y: array-like of shape (n_samples,) or (n_samples, n_targets)
Target values
Ignored if train_loader is not None.
train_loader: pytorch train_loader object.
Returns:
self
"""
if train_loader is None:
train = data_utils.TensorDataset(torch.Tensor(X), torch.Tensor(y.values).long())
train_loader = data_utils.DataLoader(train, batch_size=self.config['batch_size'], shuffle=True)
torch.manual_seed(1234)
optimizer = torch.optim.Adam(self.net.parameters(), lr=self.config['step_size'])
neg_elbo = torch.zeros([self.config['num_epochs'], 1])
params_store = {}
for epoch in range(self.config['num_epochs']):
avg_loss = 0.0
for batch_x, batch_y in train_loader:
loss = self.net.neg_elbo(num_batches=len(train_ | ||
loader), x=batch_x, y=batch_y) / batch_x.size(0)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if hasattr(self.net, 'fixed_point_updates'):
# for hshoe or regularized hshoe nets
self.net.fixed_point_updates()
avg_loss += loss.item()
neg_elbo[epoch] = avg_loss / len(train_loader)
if (epoch + 1) % 10 == 0:
# print ((net.noise_layer.bhat/net.noise_layer.ahat).data.numpy()[0])
print('Epoch[{}/{}], neg elbo: {:.6f}'
.format(epoch + 1, self.config['num_epochs'], neg_elbo[epoch].item()))
params_store[epoch] = copy.deepcopy(self.net.state_dict()) # for small nets we can just store all.
best_model_id = neg_elbo.argmin() # loss_val_store.argmin() #
self.net.load_state_dict(params_store[best_model_id.item()])
return self
def predict(self, X, mc_samples=100):
"""
Obtain calibrated predictions for the test points.
Args:
X: array-like of shape (n_samples, n_features) or (n_samples, n_classes).
Features vectors of the training data or the probability scores from the base model.
mc_samples: Number of Monte-Carlo samples.
Returns:
namedtuple: A namedtupe that holds
y_pred: ndarray of shape (n_samples,)
Predicted labels of the test points.
y_prob: ndarray of shape (n_samples, n_classes)
Predicted probability scores of the classes.
y_prob_var: ndarray of shape (n_samples,)
Variance of the prediction on the test points.
y_prob_samples: ndarray of shape (mc_samples, n_samples, n_classes)
Samples from the predictive distribution.
"""
X = torch.Tensor(X)
y_prob_samples = [F.softmax(self.net(X), dim=1).detach().numpy() for _ in np.arange(mc_samples)]
y_prob_samples_stacked = np.stack(y_prob_samples)
prob_mean = np.mean(y_prob_samples_stacked, 0)
prob_var = np.std(y_prob_samples_stacked, 0) ** 2
if len(np.shape(prob_mean)) == 1:
y_pred_labels = prob_mean > 0.5
else:
y_pred_labels = np.argmax(prob_mean, axis=1)
Result = namedtuple('res', ['y_pred', 'y_prob', 'y_prob_var', 'y_prob_samples'])
res = Result(y_pred_labels, prob_mean, prob_var, y_prob_samples)
return res
<s><s> from collections import namedtuple
import numpy as np
import torch
import torch.nn.functional as F
from scipy.stats import norm
from torch.utils.data import DataLoader
from torch.utils.data import TensorDataset
from uq360.algorithms.builtinuq import BuiltinUQ
np.random.seed(42)
torch.manual_seed(42)
class _MLPNet_Main(torch.nn.Module):
def __init__(self, num_features, num_outputs, num_hidden):
super(_MLPNet_Main, self).__init__()
self.fc = torch.nn.Linear(num_features, num_hidden)
self.fc_mu = torch.nn.Linear(num_hidden, num_outputs)
self.fc_log_var = torch.nn.Linear(num_hidden, num_outputs)
def forward(self, x):
x = F.relu(self.fc(x))
mu = self.fc_mu(x)
log_var = self.fc_log_var(x)
return mu, log_var
class _MLPNet_Aux(torch.nn.Module):
def __init__(self, num_features, num_outputs, num_hidden):
super(_MLPNet_Aux, self).__init__()
self.fc = torch.nn.Linear(num_features, num_hidden)
self.fc_log_var = torch.nn.Linear(num_hidden, num_outputs)
def forward(self, x):
x = F.relu(self.fc(x))
log_var = self.fc_log_var(x)
return log_var
class AuxiliaryIntervalPredictor(BuiltinUQ):
""" Auxiliary Interval Predictor [1]_ uses an auxiliary model to encourage calibration of the main model.
References:
.. [1] Thiagarajan, J. J., Venkatesh, B., Sattigeri, P., & Bremer, P. T. (2020, April). Building calibrated deep
models via uncertainty matching with auxiliary interval predictors. In Proceedings of the AAAI Conference on
Artificial Intelligence (Vol. 34, No. 04, pp. 6005-6012). https://arxiv.org/abs/1909.04079
"""
def __init__(self, model_type=None, main_model=None, aux_model=None, config=None, device=None, verbose=True):
"""
Args:
model_type: The model type used to build the main model and the auxiliary model. Currently supported values
are [mlp, custom]. `mlp` modeltype learns a mlp neural network using pytorch framework. For `custom` the user
provide `main_model` and `aux_model`.
main_model: (optional) The main prediction model. Currently support pytorch models that return mean and log variance.
aux_model: (optional) The auxiliary prediction model. Currently support pytorch models that return calibrated log variance.
config: dictionary containing the config parameters for the model.
device: device used for pytorch models ignored otherwise.
verbose: if True, print statements with the progress are enabled.
"""
super(AuxiliaryIntervalPredictor).__init__()
self.config = config
self.device = device
self.verbose = verbose
if model_type == "mlp":
self.model_type = model_type
self.main_model = _MLPNet_Main(
num_features=self.config["num_features"],
num_outputs=self.config["num_outputs"],
num_hidden=self.config["num_hidden"],
)
self.aux_model = _MLPNet_Aux(
num_features=self.config["num_features"],
num_outputs=self.config["num_outputs"],
num_hidden=self.config["num_hidden"],
)
elif model_type == "custom":
self.model_type = model_type
self.main_model = main_model
self.aux_model = aux_model
else:
raise NotImplementedError
def get_params(self, deep=True):
return {"model_type": self.model_type, "config": self.config, "main_model": self.main_model,
"aux_model": self.aux_model, "device": self.device, "verbose": self.verbose}
def _main_model_loss(self, y_true, y_pred_mu, y_pred_log_var, y_pred_log_var_aux):
r = torch.abs(y_true - y_pred_mu)
# + 0.5 * y_pred_log_var +
loss = torch.mean(0.5 * torch.exp(-y_pred_log_var) * r ** 2) + \\
self.config["lambda_match"] * torch.mean(torch.abs(torch.exp(0.5 * y_pred_log_var) - torch.exp(0.5 * y_pred_log_var_aux)))
return loss
def _aux_model_loss(self, y_true, y_pred_mu, y_pred_log_var_aux):
deltal = deltau = 2.0 * torch.exp(0.5 * y_pred_log_var_aux)
upper = y_pred_mu + deltau
lower = y_pred_mu - deltal
width = upper - lower
r = torch.abs(y_true - y_pred_mu)
emce = torch.mean(torch.sigmoid((y_true - lower) * (upper - y_true) * 100000))
loss_emce = torch.abs(self.config["calibration_alpha"]-emce)
loss_noise = torch.mean(torch.abs(0.5 * width - r))
loss_sharpness = torch.mean(torch.abs(upper - y_true)) + torch.mean(torch.abs(lower - y_true))
#print(emce)
return loss_emce + self.config["lambda_noise"] * loss_noise + self.config["lambda_sharpness"] * loss_sharpness
def fit(self, X, y):
""" Fit the Auxiliary Interval Predictor model.
Args:
X: array-like of shape (n_samples, n_features).
Features vectors of the training data.
y: array-like of shape (n_samples,) or (n_samples, n_targets)
Target values
Returns:
self
"""
X = torch.from_numpy(X).float().to(self.device)
y = torch.from_numpy(y).float().to(self.device)
dataset_loader = DataLoader(
TensorDataset(X,y),
batch_size=self.config["batch_size"]
)
optimizer_main_model = torch.optim.Adam(self.main_model.parameters(), lr=self.config["lr"])
optimizer_aux_model = torch.optim.Adam(self.aux_model.parameters(), lr=self.config["lr"])
for it in range(self.config["num_outer_iters"]):
# Train the main model
for epoch in range(self.config["num_main_iters"]):
avg_mean_model_loss = 0.0
for batch_x, batch_y in dataset_loader:
self.main_model.train()
self.aux_model.eval()
batch_y_pred_log_var_aux = self.aux_model(batch_x)
batch_y_pred_mu, batch_y_pred_log_var = self.main_model(batch_x)
main_loss = self._main_model_loss(batch_y, batch_y_pred_mu, batch_y_pred_log_var, batch_y_pred_log_var_aux)
optimizer_main_model.zero_grad()
main_loss.backward()
optimizer_main_model.step()
avg_mean_model_loss += main_loss.item()/len(dataset_loader)
if self.verbose:
print("Iter: {}, Epoch: {}, main_model_loss = {}".format(it, epoch, avg_mean_model_loss))
# Train the auxiliary model
for epoch in range(self.config["num_aux_iters"]):
avg_aux_model_loss = 0.0
for batch_x, batch_y in dataset_loader:
self.aux_model.train()
self.main_model.eval()
batch_y_pred_log_var_aux = self.aux_model(batch_x)
batch_y_pred_mu, batch_y_pred_log_var = self.main_model(batch_x)
aux_loss = self._aux_model_loss(batch_y, batch_y_pred_mu, batch_y_pred_log_var_aux)
optimizer_aux_model.zero_grad()
aux_loss.backward()
optimizer_aux_model.step()
avg_aux_model_loss += aux_loss.item() / len(dataset_loader)
if self.verbose:
print("Iter: {}, Epoch: {}, aux_model_loss = {}".format(it, epoch, avg_aux_model_loss))
return self
def predict(self, X, return_dists=False):
"""
Obtain predictions for the test points.
In addition to the mean and lower/upper bounds, also returns full predictive distribution (return_dists=True).
Args:
X: array-like of shape (n_samples, n_features).
Features vectors of the test points.
return_dists: If True, the predictive distribution for each instance using scipy distributions is returned.
Returns:
namedtuple: A namedtupe that holds
y_mean: ndarray of shape (n_samples, [n_output_dims])
Mean of predictive distribution of the test points.
y_lower: ndarray of shape (n_samples, [n_output_dims])
Lower quantile of predictive distribution of the test points.
y_upper: ndarray of shape (n_samples, [n_output_dims])
Upper quantile of predictive distribution of the test points.
dists: list of predictive distribution as `scipy.stats` objects with length n_samples.
Only returned when `return_dists` is True.
"""
self.main_model.eval()
X = torch.from_numpy(X).float().to(self.device)
dataset_loader = DataLoader(
X,
batch_size=self.config["batch_size"]
)
y_mean_list = []
y_log_var_list = []
for batch_x in dataset_loader:
batch_y_pred_mu, batch_y_pred_log_var = self.main_model(batch_x)
y_mean_list.append(batch_y_pred_mu.data.cpu().numpy())
y_log_var_list.append(batch_y_pred_log_var.data.cpu().numpy())
y_mean = np.concatenate(y_mean_list)
y_log_var = np.concatenate(y_log_var_list)
y_std = np.sqrt(np.exp(y_log_var))
y_lower = y_mean - 2.0*y_std
y_upper = y_mean + 2.0*y_std
Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])
res = Result(y_mean, y_lower, y_upper)
if return_dists:
dists = [norm(loc=y_mean[i], scale=y_std[i]) for i in range(y_mean.shape[0])]
Result = namedtuple('res', Result._fields + ('y_dists',))
res = Result(*res, y_dists=dists)
return res
<s> from .auxiliary_interval_predictor import AuxiliaryIntervalPredictor
<s><s><s> import torch
import torch.nn.functional as F
from uq360.models.noise_models.heteroscedastic_noise_models import GaussianNoise
class GaussianNoiseMLPNet(torch.nn.Module):
def __init__(self, num | ||
_features, num_outputs, num_hidden):
super(GaussianNoiseMLPNet, self).__init__()
self.fc = torch.nn.Linear(num_features, num_hidden)
self.fc_mu = torch.nn.Linear(num_hidden, num_outputs)
self.fc_log_var = torch.nn.Linear(num_hidden, num_outputs)
self.noise_layer = GaussianNoise()
def forward(self, x):
x = F.relu(self.fc(x))
mu = self.fc_mu(x)
log_var = self.fc_log_var(x)
return mu, log_var
def loss(self, y_true=None, mu_pred=None, log_var_pred=None):
return self.noise_layer.loss(y_true, mu_pred, log_var_pred, reduce_mean=True)<s> """
Contains implementations of various Bayesian layers
"""
import numpy as np
import torch
import torch.nn.functional as F
from torch.nn import Parameter
from uq360.models.bayesian_neural_networks.layer_utils import InvGammaHalfCauchyLayer, InvGammaLayer
td = torch.distributions
def reparam(mu, logvar, do_sample=True, mc_samples=1):
if do_sample:
std = torch.exp(0.5 * logvar)
eps = torch.FloatTensor(std.size()).normal_()
sample = mu + eps * std
for _ in np.arange(1, mc_samples):
sample += mu + eps * std
return sample / mc_samples
else:
return mu
class BayesianLinearLayer(torch.nn.Module):
"""
Affine layer with N(0, v/H) or N(0, user specified v) priors on weights and
fully factorized variational Gaussian approximation
"""
def __init__(self, in_features, out_features, cuda=False, init_weight=None, init_bias=None, prior_stdv=None):
super(BayesianLinearLayer, self).__init__()
self.cuda = cuda
self.in_features = in_features
self.out_features = out_features
# weight mean params
self.weights = Parameter(torch.Tensor(out_features, in_features))
self.bias = Parameter(torch.Tensor(out_features))
# weight variance params
self.weights_logvar = Parameter(torch.Tensor(out_features, in_features))
self.bias_logvar = Parameter(torch.Tensor(out_features))
# numerical stability
self.fudge_factor = 1e-8
if not prior_stdv:
# We will use a N(0, 1/num_inputs) prior over weights
self.prior_stdv = torch.FloatTensor([1. / np.sqrt(self.weights.size(1))])
else:
self.prior_stdv = torch.FloatTensor([prior_stdv])
# self.prior_stdv = torch.Tensor([1. / np.sqrt(1e+3)])
self.prior_mean = torch.FloatTensor([0.])
# for Bias use a prior of N(0, 1)
self.prior_bias_stdv = torch.FloatTensor([1.])
self.prior_bias_mean = torch.FloatTensor([0.])
# init params either random or with pretrained net
self.init_parameters(init_weight, init_bias)
def init_parameters(self, init_weight, init_bias):
# init means
if init_weight is not None:
self.weights.data = torch.Tensor(init_weight)
else:
self.weights.data.normal_(0, np.float(self.prior_stdv.numpy()[0]))
if init_bias is not None:
self.bias.data = torch.Tensor(init_bias)
else:
self.bias.data.normal_(0, 1)
# init variances
self.weights_logvar.data.normal_(-9, 1e-2)
self.bias_logvar.data.normal_(-9, 1e-2)
def forward(self, x, do_sample=True, scale_variances=False):
# local reparameterization trick
mu_activations = F.linear(x, self.weights, self.bias)
var_activations = F.linear(x.pow(2), self.weights_logvar.exp(), self.bias_logvar.exp())
if scale_variances:
activ = reparam(mu_activations, var_activations.log() - np.log(self.in_features), do_sample=do_sample)
else:
activ = reparam(mu_activations, var_activations.log(), do_sample=do_sample)
return activ
def kl(self):
"""
KL divergence (q(W) || p(W))
:return:
"""
weights_logvar = self.weights_logvar
kld_weights = self.prior_stdv.log() - weights_logvar.mul(0.5) + \\
(weights_logvar.exp() + (self.weights.pow(2) - self.prior_mean)) / (
2 * self.prior_stdv.pow(2)) - 0.5
kld_bias = self.prior_bias_stdv.log() - self.bias_logvar.mul(0.5) + \\
(self.bias_logvar.exp() + (self.bias.pow(2) - self.prior_bias_mean)) / (
2 * self.prior_bias_stdv.pow(2)) \\
- 0.5
return kld_weights.sum() + kld_bias.sum()
class HorseshoeLayer(BayesianLinearLayer):
"""
Uses non-centered parametrization. w_k = v*tau_k*beta_k where k indexes an output unit and w_k and beta_k
are vectors of all weights incident into the unit
"""
def __init__(self, in_features, out_features, cuda=False, scale=1.):
super(HorseshoeLayer, self).__init__(in_features, out_features)
self.cuda = cuda
self.in_features = in_features
self.out_features = out_features
self.nodescales = InvGammaHalfCauchyLayer(out_features=out_features, b=1.)
self.layerscale = InvGammaHalfCauchyLayer(out_features=1, b=scale)
# prior on beta is N(0, I) when employing non centered parameterization
self.prior_stdv = torch.Tensor([1])
self.prior_mean = torch.Tensor([0.])
def forward(self, x, do_sample=True, debug=False, eps_scale=None, eps_w=None):
# At a particular unit k, preactivation_sample = scale_sample * pre_activation_sample
# sample scales
scale_mean = 0.5 * (self.nodescales.mu + self.layerscale.mu)
scale_var = 0.25 * (self.nodescales.log_sigma.exp() ** 2 + self.layerscale.log_sigma.exp() ** 2)
scale_sample = reparam(scale_mean, scale_var.log(), do_sample=do_sample).exp()
# sample preactivations
mu_activations = F.linear(x, self.weights, self.bias)
var_activations = F.linear(x.pow(2), self.weights_logvar.exp(), self.bias_logvar.exp())
activ_sample = reparam(mu_activations, var_activations.log(), do_sample=do_sample)
return scale_sample * activ_sample
def kl(self):
return super(HorseshoeLayer, self).kl() + self.nodescales.kl() + self.layerscale.kl()
def fixed_point_updates(self):
self.nodescales.fixed_point_updates()
self.layerscale.fixed_point_updates()
class RegularizedHorseshoeLayer(HorseshoeLayer):
"""
Uses the regularized Horseshoe distribution. The regularized Horseshoe soft thresholds the tails of the Horseshoe.
For all weights w_k incident upon node k in the layer we have:
w_k ~ N(0, (tau_k * v)^2 I) N(0, c^2 I), c^2 ~ InverseGamma(c_a, b).
c^2 controls the scale of the thresholding. As c^2 -> infinity, the regularized Horseshoe -> Horseshoe.
"""
def __init__(self, in_features, out_features, cuda=False, scale=1., c_a=2., c_b=6.):
super(RegularizedHorseshoeLayer, self).__init__(in_features, out_features, cuda=cuda, scale=scale)
self.c = InvGammaLayer(a=c_a, b=c_b)
def forward(self, x, do_sample=True, **kwargs):
# At a particular unit k, preactivation_sample = scale_sample * pre_activation_sample
# sample regularized scales
scale_mean = self.nodescales.mu + self.layerscale.mu
scale_var = self.nodescales.log_sigma.exp() ** 2 + self.layerscale.log_sigma.exp() ** 2
scale_sample = reparam(scale_mean, scale_var.log(), do_sample=do_sample).exp()
c_sample = reparam(self.c.mu, 2 * self.c.log_sigma, do_sample=do_sample).exp()
regularized_scale_sample = (c_sample * scale_sample) / (c_sample + scale_sample)
# sample preactivations
mu_activations = F.linear(x, self.weights, self.bias)
var_activations = F.linear(x.pow(2), self.weights_logvar.exp(), self.bias_logvar.exp())
activ_sample = reparam(mu_activations, var_activations.log(), do_sample=do_sample)
return torch.sqrt(regularized_scale_sample) * activ_sample
def kl(self):
return super(RegularizedHorseshoeLayer, self).kl() + self.c.kl()
class NodeSpecificRegularizedHorseshoeLayer(RegularizedHorseshoeLayer):
"""
Uses the regularized Horseshoe distribution. The regularized Horseshoe soft thresholds the tails of the Horseshoe.
For all weights w_k incident upon node k in the layer we have:
w_k ~ N(0, (tau_k * v)^2 I) N(0, c_k^2 I), c_k^2 ~ InverseGamma(a, b).
c_k^2 controls the scale of the thresholding. As c_k^2 -> infinity, the regularized Horseshoe -> Horseshoe
Note that we now have a per-node c_k.
"""
def __init__(self, in_features, out_features, cuda=False, scale=1., c_a=2., c_b=6.):
super(NodeSpecificRegularizedHorseshoeLayer, self).__init__(in_features, out_features, cuda=cuda, scale=scale)
self.c = InvGammaLayer(a=c_a, b=c_b, out_features=out_features)
<s><s> """
Contains implementations of various utilities used by Horseshoe Bayesian layers
"""
import numpy as np
import torch
from torch.nn import Parameter
td = torch.distributions
gammaln = torch.lgamma
def diag_gaussian_entropy(log_std, D):
return 0.5 * D * (1.0 + torch.log(2 * np.pi)) + torch.sum(log_std)
def inv_gamma_entropy(a, b):
return torch.sum(a + torch.log(b) + torch.lgamma(a) - (1 + a) * torch.digamma(a))
def log_normal_entropy(log_std, mu, D):
return torch.sum(log_std + mu + 0.5) + (D / 2) * np.log(2 * np.pi)
class InvGammaHalfCauchyLayer(torch.nn.Module):
"""
Uses the inverse Gamma parameterization of the half-Cauchy distribution.
a ~ C^+(0, b) <==> a^2 ~ IGamma(0.5, 1/lambda), lambda ~ IGamma(0.5, 1/b^2), where lambda is an
auxiliary latent variable.
Uses a factorized variational approximation q(ln a^2)q(lambda) = N(mu, sigma^2) IGamma(ahat, bhat).
This layer places a half Cauchy prior on the scales of each output node of the layer.
"""
def __init__(self, out_features, b):
"""
:param out_fatures: number of output nodes in the layer.
:param b: scale of the half Cauchy
"""
super(InvGammaHalfCauchyLayer, self).__init__()
self.b = b
self.out_features = out_features
# variational parameters for q(ln a^2)
self.mu = Parameter(torch.FloatTensor(out_features))
self.log_sigma = Parameter(torch.FloatTensor(out_features))
# self.log_sigma = torch.FloatTensor(out_features)
# variational parameters for q(lambda). These will be updated via fixed point updates, hence not parameters.
self.ahat = torch.FloatTensor([1.]) # The posterior parameter is always 1.
self.bhat = torch.ones(out_features) * (1.0 / self.b ** 2)
self.const = torch.FloatTensor([0.5])
self.initialize_from_prior()
def initialize_from_prior(self):
"""
Initializes variational parameters by sampling from the prior.
"""
# sample from half cauchy and log to initialize the mean of the log normal
sample = np.abs(self.b * (np.random.randn(self.out_features) / np.random.randn(self.out_features)))
self.mu.data = torch.FloatTensor(np.log(sample))
self.log_sigma.data = torch.FloatTensor(np.random.randn(self.out_features) - 10.)
def expectation_wrt_prior(self):
"""
Computes E[ln p(a^2 | lambda)] + E[ln p(lambda)]
"""
expected_a_given_lambda = -gammaln(self.const) - 0.5 * (torch.log(self.bhat) - torch.digamma(self.ahat)) + (
-0.5 - 1.) * self.mu - torch.exp(-self.mu + 0.5 * self.log_sigma.exp() ** 2) * (self.ahat / self.bhat)
expected_lambda = -gammaln(self.const) - 2 * 0.5 * np.log( | ||
self.b) + (-self.const - 1.) * (
torch.log(self.bhat) - torch.digamma(self.ahat)) - (1. / self.b ** 2) * (self.ahat / self.bhat)
return torch.sum(expected_a_given_lambda) + torch.sum(expected_lambda)
def entropy(self):
"""
Computes entropy of q(ln a^2) and q(lambda)
"""
return self.entropy_lambda() + self.entropy_a2()
def entropy_lambda(self):
return inv_gamma_entropy(self.ahat, self.bhat)
def entropy_a2(self):
return log_normal_entropy(self.log_sigma, self.mu, self.out_features)
def kl(self):
"""
Computes KL(q(ln(a^2)q(lambda) || IG(a^2 | 0.5, 1/lambda) IG(lambda | 0.5, 1/b^2))
"""
return -self.expectation_wrt_prior() - self.entropy()
def fixed_point_updates(self):
# update lambda moments
self.bhat = torch.exp(-self.mu + 0.5 * self.log_sigma.exp() ** 2) + (1. / self.b ** 2)
class InvGammaLayer(torch.nn.Module):
"""
Approximates the posterior of c^2 with prior IGamma(c^2 | a , b)
using a log Normal approximation q(ln c^2) = N(mu, sigma^2)
"""
def __init__(self, a, b, out_features=1):
super(InvGammaLayer, self).__init__()
self.a = torch.FloatTensor([a])
self.b = torch.FloatTensor([b])
# variational parameters for q(ln c^2)
self.mu = Parameter(torch.FloatTensor(out_features))
self.log_sigma = Parameter(torch.FloatTensor(out_features))
self.out_features = out_features
self.initialize_from_prior()
def initialize_from_prior(self):
"""
Initializes variational parameters by sampling from the prior.
"""
self.mu.data = torch.log(self.b / (self.a + 1) * torch.ones(self.out_features)) # initialize at the mode
self.log_sigma.data = torch.FloatTensor(np.random.randn(self.out_features) - 10.)
def expectation_wrt_prior(self):
"""
Computes E[ln p(c^2 | a, b)]
"""
# return self.c_a * np.log(self.c_b) - gammaln(self.c_a) + (
# - self.c_a - 1) * c_mu - self.c_b * Ecinv
return self.a * torch.log(self.b) - gammaln(self.a) + (- self.a - 1) \\
* self.mu - self.b * torch.exp(-self.mu + 0.5 * self.log_sigma.exp() ** 2)
def entropy(self):
return log_normal_entropy(self.log_sigma, self.mu, 1)
def kl(self):
"""
Computes KL(q(ln(c^2) || IG(c^2 | a, b))
"""
return -self.expectation_wrt_prior().sum() - self.entropy()
<s> import numpy as np
import torch
from uq360.models.noise_models.homoscedastic_noise_models import GaussianNoiseFixedPrecision
def compute_test_ll(y_test, y_pred_samples, std_y=1.):
"""
Computes test log likelihoods = (1 / Ntest) * \\sum_n p(y_n | x_n, D_train)
:param y_test: True y
:param y_pred_samples: y^s = f(x_test, w^s); w^s ~ q(w). S x Ntest, where S is the number of samples
q(w) is either a trained variational posterior or an MCMC approximation to p(w | D_train)
:param std_y: True std of y (assumed known)
"""
S, _ = y_pred_samples.shape
noise = GaussianNoiseFixedPrecision(std_y=std_y)
ll = noise.loss(y_pred=y_pred_samples, y_true=y_test.unsqueeze(dim=0), reduce_sum=False)
ll = torch.logsumexp(ll, dim=0) - np.log(S) # mean over num samples
return torch.mean(ll) # mean over test points
<s> from abc import ABC
import numpy as np
import torch
from torch import nn
from uq360.models.bayesian_neural_networks.layers import HorseshoeLayer, BayesianLinearLayer, RegularizedHorseshoeLayer
from uq360.models.noise_models.homoscedastic_noise_models import GaussianNoiseGammaPrecision
import numpy as np
td = torch.distributions
class HshoeBNN(nn.Module, ABC):
"""
Bayesian neural network with Horseshoe layers.
"""
def __init__(self, ip_dim=1, op_dim=1, num_nodes=50, activation_type='relu', num_layers=1,
hshoe_scale=1e-1, use_reg_hshoe=False):
if use_reg_hshoe:
layer = RegularizedHorseshoeLayer
else:
layer = HorseshoeLayer
super(HshoeBNN, self).__init__()
self.num_layers = num_layers
if activation_type == 'relu':
# activation
self.activation = nn.ReLU()
elif activation_type == 'tanh':
self.activation = nn.Tanh()
else:
print("Activation Type not supported")
self.fc_hidden = []
self.fc1 = layer(ip_dim, num_nodes, scale=hshoe_scale)
for _ in np.arange(self.num_layers - 1):
self.fc_hidden.append(layer(num_nodes, num_nodes))
self.fc_out = BayesianLinearLayer(num_nodes, op_dim)
self.noise_layer = None
def forward(self, x, do_sample=True):
x = self.fc1(x, do_sample=do_sample)
x = self.activation(x)
for layer in self.fc_hidden:
x = layer(x, do_sample=do_sample)
x = self.activation(x)
return self.fc_out(x, do_sample=do_sample, scale_variances=True)
def kl_divergence_w(self):
kld = self.fc1.kl() + self.fc_out.kl()
for layer in self.fc_hidden:
kld += layer.kl()
return kld
def fixed_point_updates(self):
if hasattr(self.fc1, 'fixed_point_updates'):
self.fc1.fixed_point_updates()
if hasattr(self.fc_out, 'fixed_point_updates'):
self.fc_out.fixed_point_updates()
for layer in self.fc_hidden:
if hasattr(layer, 'fixed_point_updates'):
layer.fixed_point_updates()
def prior_predictive_samples(self, n_sample=100):
n_eval = 1000
x = torch.linspace(-2, 2, n_eval)[:, np.newaxis]
y = np.zeros([n_sample, n_eval])
for i in np.arange(n_sample):
y[i] = self.forward(x).data.numpy().ravel()
return x.data.numpy(), y
### get and set weights ###
def get_weights(self):
assert len(self.fc_hidden) == 0 # only works for one layer networks.
weight_dict = {}
weight_dict['layerip_means'] = torch.cat([self.fc1.weights, self.fc1.bias.unsqueeze(1)], dim=1).data.numpy()
weight_dict['layerip_logvar'] = torch.cat([self.fc1.weights_logvar, self.fc1.bias_logvar.unsqueeze(1)], dim=1).data.numpy()
weight_dict['layerop_means'] = torch.cat([self.fc_out.weights, self.fc_out.bias.unsqueeze(1)], dim=1).data.numpy()
weight_dict['layerop_logvar'] = torch.cat([self.fc_out.weights_logvar, self.fc_out.bias_logvar.unsqueeze(1)], dim=1).data.numpy()
return weight_dict
def set_weights(self, weight_dict):
assert len(self.fc_hidden) == 0 # only works for one layer networks.
to_param = lambda x: nn.Parameter(torch.Tensor(x))
self.fc1.weights = to_param(weight_dict['layerip_means'][:, :-1])
self.fc1.weights = to_param(weight_dict['layerip_logvar'][:, :-1])
self.fc1.bias = to_param(weight_dict['layerip_means'][:, -1])
self.fc1.bias_logvar = to_param(weight_dict['layerip_logvar'][:, -1])
self.fc_out.weights = to_param(weight_dict['layerop_means'][:, :-1])
self.fc_out.weights = to_param(weight_dict['layerop_logvar'][:, :-1])
self.fc_out.bias = to_param(weight_dict['layerop_means'][:, -1])
self.fc_out.bias_logvar = to_param(weight_dict['layerop_logvar'][:, -1])
class HshoeRegressionNet(HshoeBNN, ABC):
"""
Horseshoe net with N(y_true | f(x, w), \\lambda^-1); \\lambda ~ Gamma(a, b) likelihoods.
"""
def __init__(self, ip_dim=1, op_dim=1, num_nodes=50, activation_type='relu',
num_layers=1, hshoe_scale=1e-5, use_reg_hshoe=False):
super(HshoeRegressionNet, self).__init__(ip_dim=ip_dim, op_dim=op_dim,
num_nodes=num_nodes, activation_type=activation_type,
num_layers=num_layers,
hshoe_scale=hshoe_scale,
use_reg_hshoe=use_reg_hshoe)
self.noise_layer = GaussianNoiseGammaPrecision(a0=6., b0=6.)
def likelihood(self, x=None, y=None):
out = self.forward(x)
return -self.noise_layer.loss(y_pred=out, y_true=y)
def neg_elbo(self, num_batches, x=None, y=None):
# scale the KL terms by number of batches so that the minibatch elbo is an unbiased estiamte of the true elbo.
Elik = self.likelihood(x, y)
neg_elbo = (self.kl_divergence_w() + self.noise_layer.kl()) / num_batches - Elik
return neg_elbo
def mse(self, x, y):
"""
scaled rmse (scaled by 1 / std_y**2)
"""
E_noise_precision = 1. / self.noise_layer.get_noise_var()
return (0.5 * E_noise_precision * (self.forward(x, do_sample=False) - y)**2).sum()
def get_noise_var(self):
return self.noise_layer.get_noise_var()
class HshoeClassificationNet(HshoeBNN, ABC):
"""
Horseshoe net with Categorical(y_true | f(x, w)) likelihoods. Use for classification.
"""
def __init__(self, ip_dim=1, op_dim=1, num_nodes=50, activation_type='relu',
num_layers=1, hshoe_scale=1e-5, use_reg_hshoe=False):
super(HshoeClassificationNet, self).__init__(ip_dim=ip_dim, op_dim=op_dim,
num_nodes=num_nodes, activation_type=activation_type,
num_layers=num_layers,
hshoe_scale=hshoe_scale,
use_reg_hshoe=use_reg_hshoe)
self.noise_layer = torch.nn.CrossEntropyLoss(reduction='sum')
def likelihood(self, x=None, y=None):
out = self.forward(x)
return -self.noise_layer(out, y)
def neg_elbo(self, num_batches, x=None, y=None):
# scale the KL terms by number of batches so that the minibatch elbo is an unbiased estiamte of the true elbo.
Elik = self.likelihood(x, y)
neg_elbo = (self.kl_divergence_w()) / num_batches - Elik
return neg_elbo
<s> from abc import ABC
import torch
from torch import nn
from uq360.models.bayesian_neural_networks.layers import BayesianLinearLayer
from uq360.models.noise_models.homoscedastic_noise_models import GaussianNoiseGammaPrecision
import numpy as np
td = torch.distributions
class BayesianNN(nn.Module, ABC):
"""
Bayesian neural network with zero mean Gaussian priors over weights.
"""
def __init__(self, layer=BayesianLinearLayer, ip_dim=1, op_dim=1, num_nodes=50,
activation_type='relu', num_layers=1):
super(BayesianNN, self).__init__()
self.num_layers = num_layers
if activation_type == 'relu':
# activation
self.activation = nn.ReLU()
elif activation_type == 'tanh':
self.activation = nn.Tanh()
else:
print("Activation Type not supported")
self.fc_hidden = []
self.fc1 = layer(ip_dim, num_nodes,)
for _ in np.arange(self.num_layers - 1):
self.fc_hidden.append(layer(num_nodes, num_nodes, ))
self.fc_out = layer(num_nodes, op_dim, )
self.noise_layer = None
def forward(self, x, do_sample=True):
x = self.fc1(x, do_sample=do_sample)
x = self.activation(x)
for layer in self.fc_hidden:
x = layer(x, do_ | ||
sample=do_sample)
x = self.activation(x)
return self.fc_out(x, do_sample=do_sample, scale_variances=True)
def kl_divergence_w(self):
kld = self.fc1.kl() + self.fc_out.kl()
for layer in self.fc_hidden:
kld += layer.kl()
return kld
def prior_predictive_samples(self, n_sample=100):
n_eval = 1000
x = torch.linspace(-2, 2, n_eval)[:, np.newaxis]
y = np.zeros([n_sample, n_eval])
for i in np.arange(n_sample):
y[i] = self.forward(x).data.numpy().ravel()
return x.data.numpy(), y
### get and set weights ###
def get_weights(self):
assert len(self.fc_hidden) == 0 # only works for one layer networks.
weight_dict = {}
weight_dict['layerip_means'] = torch.cat([self.fc1.weights, self.fc1.bias.unsqueeze(1)], dim=1).data.numpy()
weight_dict['layerip_logvar'] = torch.cat([self.fc1.weights_logvar, self.fc1.bias_logvar.unsqueeze(1)], dim=1).data.numpy()
weight_dict['layerop_means'] = torch.cat([self.fc_out.weights, self.fc_out.bias.unsqueeze(1)], dim=1).data.numpy()
weight_dict['layerop_logvar'] = torch.cat([self.fc_out.weights_logvar, self.fc_out.bias_logvar.unsqueeze(1)], dim=1).data.numpy()
return weight_dict
def set_weights(self, weight_dict):
assert len(self.fc_hidden) == 0 # only works for one layer networks.
to_param = lambda x: nn.Parameter(torch.Tensor(x))
self.fc1.weights = to_param(weight_dict['layerip_means'][:, :-1])
self.fc1.weights = to_param(weight_dict['layerip_logvar'][:, :-1])
self.fc1.bias = to_param(weight_dict['layerip_means'][:, -1])
self.fc1.bias_logvar = to_param(weight_dict['layerip_logvar'][:, -1])
self.fc_out.weights = to_param(weight_dict['layerop_means'][:, :-1])
self.fc_out.weights = to_param(weight_dict['layerop_logvar'][:, :-1])
self.fc_out.bias = to_param(weight_dict['layerop_means'][:, -1])
self.fc_out.bias_logvar = to_param(weight_dict['layerop_logvar'][:, -1])
class BayesianRegressionNet(BayesianNN, ABC):
"""
Bayesian neural net with N(y_true | f(x, w), \\lambda^-1); \\lambda ~ Gamma(a, b) likelihoods.
"""
def __init__(self, layer=BayesianLinearLayer, ip_dim=1, op_dim=1, num_nodes=50, activation_type='relu',
num_layers=1):
super(BayesianRegressionNet, self).__init__(layer=layer, ip_dim=ip_dim, op_dim=op_dim,
num_nodes=num_nodes, activation_type=activation_type,
num_layers=num_layers,
)
self.noise_layer = GaussianNoiseGammaPrecision(a0=6., b0=6.)
def likelihood(self, x=None, y=None):
out = self.forward(x)
return -self.noise_layer.loss(y_pred=out, y_true=y)
def neg_elbo(self, num_batches, x=None, y=None):
# scale the KL terms by number of batches so that the minibatch elbo is an unbiased estiamte of the true elbo.
Elik = self.likelihood(x, y)
neg_elbo = (self.kl_divergence_w() + self.noise_layer.kl()) / num_batches - Elik
return neg_elbo
def mse(self, x, y):
"""
scaled rmse (scaled by 1 / std_y**2)
"""
E_noise_precision = 1. / self.noise_layer.get_noise_var()
return (0.5 * E_noise_precision * (self.forward(x, do_sample=False) - y)**2).sum()
def get_noise_var(self):
return self.noise_layer.get_noise_var()
class BayesianClassificationNet(BayesianNN, ABC):
"""
Bayesian neural net with Categorical(y_true | f(x, w)) likelihoods. Use for classification.
"""
def __init__(self, layer=BayesianLinearLayer, ip_dim=1, op_dim=1, num_nodes=50, activation_type='relu',
num_layers=1):
super(BayesianClassificationNet, self).__init__(layer=layer, ip_dim=ip_dim, op_dim=op_dim,
num_nodes=num_nodes, activation_type=activation_type,
num_layers=num_layers)
self.noise_layer = torch.nn.CrossEntropyLoss(reduction='sum')
def likelihood(self, x=None, y=None):
out = self.forward(x)
return -self.noise_layer(out, y)
def neg_elbo(self, num_batches, x=None, y=None):
# scale the KL terms by number of batches so that the minibatch elbo is an unbiased estiamte of the true elbo.
Elik = self.likelihood(x, y)
neg_elbo = self.kl_divergence_w() / num_batches - Elik
return neg_elbo
<s><s> import math
import numpy as np
import torch
from scipy.special import gammaln
from uq360.models.noise_models.noisemodel import AbstractNoiseModel
from torch.nn import Parameter
td = torch.distributions
def transform(a):
return torch.log(1 + torch.exp(a))
class GaussianNoise(torch.nn.Module, AbstractNoiseModel):
"""
N(y_true | f_\\mu(x, w), f_\\sigma^2(x, w))
"""
def __init__(self, cuda=False):
super(GaussianNoise, self).__init__()
self.cuda = cuda
self.const = torch.log(torch.FloatTensor([2 * math.pi]))
def loss(self, y_true=None, mu_pred=None, log_var_pred=None, reduce_mean=True):
"""
computes -1 * ln N (y_true | mu_pred, softplus(log_var_pred))
:param y_true:
:param mu_pred:
:param log_var_pred:
:return:
"""
var_pred = transform(log_var_pred)
ll = -0.5 * self.const - 0.5 * torch.log(var_pred) - 0.5 * (1. / var_pred) * ((mu_pred - y_true) ** 2)
if reduce_mean:
return -ll.mean(dim=0)
else:
return -ll.sum(dim=0)
def get_noise_var(self, log_var_pred):
return transform(log_var_pred)
<s> import math
import numpy as np
import torch
from scipy.special import gammaln
from uq360.models.noise_models.noisemodel import AbstractNoiseModel
from torch.nn import Parameter
td = torch.distributions
def transform(a):
return torch.log(1 + torch.exp(a))
class GaussianNoiseGammaPrecision(torch.nn.Module, AbstractNoiseModel):
"""
N(y_true | f(x, w), \\lambda^-1); \\lambda ~ Gamma(a, b).
Uses a variational approximation; q(lambda) = Gamma(ahat, bhat)
"""
def __init__(self, a0=6, b0=6, cuda=False):
super(GaussianNoiseGammaPrecision, self).__init__()
self.cuda = cuda
self.a0 = a0
self.b0 = b0
self.const = torch.log(torch.FloatTensor([2 * math.pi]))
# variational parameters
self.ahat = Parameter(torch.FloatTensor([10.]))
self.bhat = Parameter(torch.FloatTensor([3.]))
def loss(self, y_pred=None, y_true=None):
"""
computes -1 * E_q(\\lambda)[ln N (y_pred | y_true, \\lambda^-1)], where q(lambda) = Gamma(ahat, bhat)
:param y_pred:
:param y_true:
:return:
"""
n = y_pred.shape[0]
ahat = transform(self.ahat)
bhat = transform(self.bhat)
return -1 * (-0.5 * n * self.const + 0.5 * n * (torch.digamma(ahat) - torch.log(bhat)) \\
- 0.5 * (ahat/bhat) * ((y_pred - y_true) ** 2).sum())
def kl(self):
ahat = transform(self.ahat)
bhat = transform(self.bhat)
return (ahat - self.a0) * torch.digamma(ahat) - torch.lgamma(ahat) + gammaln(self.a0) + \\
self.a0 * (torch.log(bhat) - np.log(self.b0)) + ahat * (self.b0 - bhat) / bhat
def get_noise_var(self):
ahat = transform(self.ahat)
bhat = transform(self.bhat)
return (bhat / ahat).data.numpy()[0]
class GaussianNoiseFixedPrecision(torch.nn.Module, AbstractNoiseModel):
"""
N(y_true | f(x, w), sigma_y**2); known sigma_y
"""
def __init__(self, std_y=1., cuda=False):
super(GaussianNoiseFixedPrecision, self).__init__()
self.cuda = cuda
self.const = torch.log(torch.FloatTensor([2 * math.pi]))
self.sigma_y = std_y
def loss(self, y_pred=None, y_true=None):
"""
computes -1 * ln N (y_pred | y_true, sigma_y**2)
:param y_pred:
:param y_true:
:return:
"""
ll = -0.5 * self.const - np.log(self.sigma_y) - 0.5 * (1. / self.sigma_y ** 2) * ((y_pred - y_true) ** 2)
return -ll.sum(dim=0)
def get_noise_var(self):
return self.sigma_y ** 2<s> import abc
import sys
# Ensure compatibility with Python 2/3
if sys.version_info >= (3, 4):
ABC = abc.ABC
else:
ABC = abc.ABCMeta(str('ABC'), (), {})
class AbstractNoiseModel(ABC):
""" Abstract class. All noise models inherit from here.
"""
def __init__(self, *argv, **kwargs):
""" Initialize an AbstractNoiseModel object.
"""
@abc.abstractmethod
def loss(self, *argv, **kwargs):
""" Compute loss given predictions and groundtruth labels
"""
raise NotImplementedError
@abc.abstractmethod
def get_noise_var(self, *argv, **kwargs):
"""
Return the current estimate of noise variance
"""
raise NotImplementedError
<s><s> import autograd
import autograd.numpy as np
import scipy.optimize
from autograd import grad
from autograd.scipy.special import logsumexp
from sklearn.cluster import KMeans
class HMM:
"""
A Hidden Markov Model with Gaussian observations with
unknown means and known precisions.
"""
def __init__(self, X, config_dict=None):
self.N, self.T, self.D = X.shape
self.K = config_dict['K'] # number of HMM states
self.I = np.eye(self.K)
self.Precision = np.zeros([self.D, self.D, self.K])
self.X = X
if config_dict['precision'] is None:
for k in np.arange(self.K):
self.Precision[:, :, k] = np.eye(self.D)
else:
self.Precision = config_dict['precision']
self.dParams_dWeights = None
self.alphaT = None # Store the final beliefs.
self.beta1 = None # store the first timestep beliefs from the beta recursion.
self.forward_trellis = {} # stores \\alpha
self.backward_trellis = {} # stores \\beta
def initialize_params(self, seed=1234):
np.random.seed(seed)
param_dict = {}
A = np.random.randn(self.K, self.K)
# use k-means to initialize the mean parameters
X = self.X.reshape([-1, self.D])
kmeans = KMeans(n_clusters=self.K, random_state=seed,
n_init=15).fit(X)
labels = kmeans.labels_
_, counts = np.unique(labels, return_counts=True)
pi = counts
phi = kmeans.cluster_centers_
param_dict['A'] = np.exp(A)
param_dict['pi0'] = pi
param_dict['phi'] = phi
return self.pack_params(param_dict)
def unpack_params(self, params):
param_dict = dict()
K = self.K
# For unpacking simplex parameters: have packed them as
# log(pi[:-1]) - log(pi[-1]).
unnorm_A = np.exp(np.append(params[:K**2-K].reshape(K, K-1),
np.zeros((K, 1)),
axis=1)
)
Z = np.sum(unnorm_A[:, :-1], axis=1)
unnorm_A /= Z[:, np.newaxis]
norm_A = unnorm_A / unnorm_A.sum(axis=1, keepdims=True)
param_dict['A'] = norm_A
unnorm_pi = np.exp(np.append(params[K**2-K:K**2-1], | ||
0.0))
Z = np.sum(unnorm_pi[:-1])
unnorm_pi /= Z
param_dict['pi0'] = unnorm_pi / unnorm_pi.sum()
param_dict['phi'] = params[K**2-K+K-1:].reshape(self.D, K)
return param_dict
def weighted_alpha_recursion(self, xseq, pi, phi, Sigma, A, wseq, store_belief=False):
"""
Computes the weighted marginal probability of the sequence xseq given parameters;
weights wseq turn on or off the emissions p(x_t | z_t) (weighting scheme B)
:param xseq: T * D
:param pi: K * 1
:param phi: D * K
:param wseq: T * 1
:param A:
:return:
"""
ll = self.log_obs_lik(xseq[:, :, np.newaxis], phi[np.newaxis, :, :], Sigma)
alpha = np.log(pi.ravel()) + wseq[0] * ll[0]
if wseq[0] == 0:
self.forward_trellis[0] = alpha[:, np.newaxis]
for t in np.arange(1, self.T):
alpha = logsumexp(alpha[:, np.newaxis] + np.log(A), axis=0) + wseq[t] * ll[t]
if wseq[t] == 0:
# store the trellis, would be used to compute the posterior z_t | x_1...x_t-1, x_t+1, ...x_T
self.forward_trellis[t] = alpha[:, np.newaxis]
if store_belief:
# store the final belief
self.alphaT = alpha
return logsumexp(alpha)
def weighted_beta_recursion(self, xseq, pi, phi, Sigma, A, wseq, store_belief=False):
"""
Runs beta recursion;
weights wseq turn on or off the emissions p(x_t | z_t) (weighting scheme B)
:param xseq: T * D
:param pi: K * 1
:param phi: D * K
:param wseq: T * 1
:param A:
:return:
"""
ll = self.log_obs_lik(xseq[:, :, np.newaxis], phi[np.newaxis, :, :], Sigma)
beta = np.zeros_like(pi.ravel()) # log(\\beta) of all ones.
max_t = ll.shape[0]
if wseq[max_t - 1] == 0:
# store the trellis, would be used to compute the posterior z_t | x_1...x_t-1, x_t+1, ...x_T
self.backward_trellis[max_t - 1] = beta[:, np.newaxis]
for i in np.arange(1, max_t):
t = max_t - i - 1
beta = logsumexp((beta + wseq[t + 1] * ll[t + 1])[np.newaxis, :] + np.log(A), axis=1)
if wseq[t] == 0:
# store the trellis, would be used to compute the posterior z_t | x_1...x_t-1, x_t+1, ...x_T
self.backward_trellis[t] = beta[:, np.newaxis]
# account for the init prob
beta = (beta + wseq[0] * ll[0]) + np.log(pi.ravel())
if store_belief:
# store the final belief
self.beta1 = beta
return logsumexp(beta)
def weighted_loss(self, params, weights):
"""
For LOOCV / IF computation within a single sequence. Uses weighted alpha recursion
:param params:
:param weights:
:return:
"""
param_dict = self.unpack_params(params)
logp = self.get_prior_contrib(param_dict)
logp = logp + self.weighted_alpha_recursion(self.X[0], param_dict['pi0'],
param_dict['phi'],
self.Precision,
param_dict['A'],
weights)
return -logp
def loss_at_missing_timesteps(self, weights, params):
"""
:param weights: zeroed out weights indicate missing values
:param params: packed parameters
:return:
"""
# empty forward and backward trellis
self.clear_trellis()
param_dict = self.unpack_params(params)
# populate forward and backward trellis
lpx = self.weighted_alpha_recursion(self.X[0], param_dict['pi0'],
param_dict['phi'],
self.Precision,
param_dict['A'],
weights,
store_belief=True )
lpx_alt = self.weighted_beta_recursion(self.X[0], param_dict['pi0'],
param_dict['phi'],
self.Precision,
param_dict['A'],
weights,
store_belief=True)
assert np.allclose(lpx, lpx_alt) # sanity check
test_ll = []
# compute loo likelihood
ll = self.log_obs_lik(self.X[0][:, :, np.newaxis], param_dict['phi'], self.Precision)
# compute posterior p(z_t | x_1,...t-1, t+1,...T) \\forall missing t
tsteps = []
for t in self.forward_trellis.keys():
lpz_given_x = self.forward_trellis[t] + self.backward_trellis[t] - lpx
test_ll.append(logsumexp(ll[t] + lpz_given_x.ravel()))
tsteps.append(t)
# empty forward and backward trellis
self.clear_trellis()
return -np.array(test_ll)
def fit(self, weights, init_params=None, num_random_restarts=1, verbose=False, maxiter=None):
if maxiter:
options_dict = {'disp': verbose, 'gtol': 1e-10, 'maxiter': maxiter}
else:
options_dict = {'disp': verbose, 'gtol': 1e-10}
# Define a function that returns gradients of training loss using Autograd.
training_loss_fun = lambda params: self.weighted_loss(params, weights)
training_gradient_fun = grad(training_loss_fun, 0)
if init_params is None:
init_params = self.initialize_params()
if verbose:
print("Initial loss: ", training_loss_fun(init_params))
res = scipy.optimize.minimize(fun=training_loss_fun,
jac=training_gradient_fun,
x0=init_params,
tol=1e-10,
options=options_dict)
if verbose:
print('grad norm =', np.linalg.norm(res.jac))
return res.x
def clear_trellis(self):
self.forward_trellis = {}
self.backward_trellis = {}
#### Required for IJ computation ###
def compute_hessian(self, params_one, weights_one):
return autograd.hessian(self.weighted_loss, argnum=0)(params_one, weights_one)
def compute_jacobian(self, params_one, weights_one):
return autograd.jacobian(autograd.jacobian(self.weighted_loss, argnum=0), argnum=1)\\
(params_one, weights_one).squeeze()
###################################################
@staticmethod
def log_obs_lik(x, phi, Sigma):
"""
:param x: T*D*1
:param phi: 1*D*K
:param Sigma: D*D*K --- precision matrices per state
:return: ll
"""
centered_x = x - phi
ll = -0.5 * np.einsum('tdk, tdk, ddk -> tk', centered_x, centered_x, Sigma )
return ll
@staticmethod
def pack_params(params_dict):
param_list = [(np.log(params_dict['A'][:, :-1]) -
np.log(params_dict['A'][:, -1])[:, np.newaxis]).ravel(),
np.log(params_dict['pi0'][:-1]) - np.log(params_dict['pi0'][-1]),
params_dict['phi'].ravel()]
return np.concatenate(param_list)
@staticmethod
def get_prior_contrib(param_dict):
logp = 0.0
# Prior
logp += -0.5 * (np.linalg.norm(param_dict['phi'], axis=0) ** 2).sum()
logp += (1.1 - 1) * np.log(param_dict['A']).sum()
logp += (1.1 - 1) * np.log(param_dict['pi0']).sum()
return logp
@staticmethod
def get_indices_in_held_out_fold(T, pct_to_drop, contiguous=False):
"""
:param T: length of the sequence
:param pct_to_drop: % of T in the held out fold
:param contiguous: if True generate a block of indices to drop else generate indices by iid sampling
:return: o (the set of indices in the fold)
"""
if contiguous:
l = np.floor(pct_to_drop / 100. * T)
anchor = np.random.choice(np.arange(l + 1, T))
o = np.arange(anchor - l, anchor).astype(int)
else:
# i.i.d LWCV
o = np.random.choice(T - 2, size=np.int(pct_to_drop / 100. * T), replace=False) + 1
return o
@staticmethod
def synthetic_hmm_data(K, T, D, sigma0=None, seed=1234, varainces_of_mean=1.0,
diagonal_upweight=False):
"""
:param K: Number of HMM states
:param T: length of the sequence
"""
N = 1 # For structured IJ we will remove data / time steps from a single sequence
np.random.seed(seed)
if sigma0 is None:
sigma0 = np.eye(D)
A = np.random.dirichlet(alpha=np.ones(K), size=K)
if diagonal_upweight:
A = A + 3 * np.eye(K) # add 3 to the diagonal and renormalize to encourage self transitions
A = A / A.sum(axis=1)
pi0 = np.random.dirichlet(alpha=np.ones(K))
mus = np.random.normal(size=(K, D), scale=np.sqrt(varainces_of_mean))
zs = np.empty((N, T), dtype=np.int)
X = np.empty((N, T, D))
for n in range(N):
zs[n, 0] = int(np.random.choice(np.arange(K), p=pi0))
X[n, 0] = np.random.multivariate_normal(mean=mus[zs[n, 0]], cov=sigma0)
for t in range(1, T):
zs[n, t] = int(np.random.choice(np.arange(K), p=A[zs[n, t - 1], :]))
X[n, t] = np.random.multivariate_normal(mean=mus[zs[n, t]], cov=sigma0)
return {'X': X, 'state_assignments': zs, 'A': A, 'initial_state_assignment': pi0, 'means': mus}
<s> from builtins import range
import autograd.numpy as np
def adam(grad, x, callback=None, num_iters=100, step_size=0.001, b1=0.9, b2=0.999, eps=10**-8, polyak=False):
"""Adapted from autograd.misc.optimizers"""
m = np.zeros(len(x))
v = np.zeros(len(x))
for i in range(num_iters):
g = grad(x, i)
if callback: callback(x, i, g, polyak)
m = (1 - b1) * g + b1 * m # First moment estimate.
v = (1 - b2) * (g**2) + b2 * v # Second moment estimate.
mhat = m / (1 - b1**(i + 1)) # Bias correction.
vhat = v / (1 - b2**(i + 1))
x = x - step_size*mhat/(np.sqrt(vhat) + eps)
return x<s> import matplotlib.pyplot as plt
import numpy as np
import numpy.random as npr
import torch as torch
def make_data_gap(seed, data_count=100):
import GPy
npr.seed(0)
x = np.hstack([np.linspace(-5, -2, int(data_count/2)), np.linspace(2, 5, int(data_count/2))])
x = x[:, np.newaxis]
k = GPy.kern.RBF(input_dim=1, variance=1., lengthscale=1.)
K = k.K(x)
L = np.linalg.cholesky(K + 1e-5 * np.eye(data_count))
# draw a noise free random function from a GP
eps = np.random.randn(data_count)
f = L @ eps
# use a homoskedastic Gaussian noise model N(f(x)_i, \\sigma^2). \\sigma^2 = 0.1
eps_noise = np.sqrt(0.1) * np.random.randn(data_count)
y = f + eps_noise
y = y[:, np.newaxis]
plt.plot(x, f, 'ko', ms=2)
plt.plot(x, y, 'ro')
plt.title("GP generated Data")
plt.pause(1)
return torch.FloatTensor(x), torch.FloatTensor(y), torch.FloatTensor(x), torch.FloatTensor(y)
def make_data_sine(seed, data_count=450):
# fix the random seed
np.random.seed(seed)
noise_var = 0.1
X = np.linspace(-4, 4, data_count)
y = 1*np.sin(X) + np.sqrt(noise_var)*npr.randn(data_count)
train_count = int (0.2 * data_count)
idx = npr.permutation(range(data_ | ||
count))
X_train = X[idx[:train_count], np.newaxis ]
X_test = X[ idx[train_count:], np.newaxis ]
y_train = y[ idx[:train_count] ]
y_test = y[ idx[train_count:] ]
mu = np.mean(X_train, 0)
std = np.std(X_train, 0)
X_train = (X_train - mu) / std
X_test = (X_test - mu) / std
mu = np.mean(y_train, 0)
std = np.std(y_train, 0)
# mu = 0
# std = 1
y_train = (y_train - mu) / std
y_test = (y_test -mu) / std
train_stats = dict()
train_stats['mu'] = torch.FloatTensor([mu])
train_stats['sigma'] = torch.FloatTensor([std])
return torch.FloatTensor(X_train), torch.FloatTensor(y_train), torch.FloatTensor(X_test), torch.FloatTensor(y_test),\\
train_stats<s> import autograd
import autograd.numpy as np
import numpy.random as npr
import scipy.optimize
sigmoid = lambda x: 0.5 * (np.tanh(x / 2.) + 1)
get_num_train = lambda inputs: inputs.shape[0]
logistic_predictions = lambda params, inputs: sigmoid(np.dot(inputs, params))
class LogisticRegression:
def __init__(self):
self.params = None
def set_parameters(self, params):
self.params = params
def predict(self, X):
if self.params is not None:
# Outputs probability of a label being true according to logistic model
return np.atleast_2d(sigmoid(np.dot(X, self.params))).T
else:
raise RuntimeError("Params need to be fit before predictions can be made.")
def loss(self, params, weights, inputs, targets):
# Training loss is the negative log-likelihood of the training labels.
preds = logistic_predictions(params, inputs)
label_probabilities = preds * targets + (1 - preds) * (1 - targets)
return -np.sum(weights * np.log(label_probabilities + 1e-16))
def fit(self, weights, init_params, inputs, targets, verbose=True):
training_loss_fun = lambda params: self.loss(params, weights, inputs, targets)
# Define a function that returns gradients of training loss using Autograd.
training_gradient_fun = autograd.grad(training_loss_fun, 0)
# optimize params
if verbose:
print("Initial loss:", self.loss(init_params, weights, inputs, targets))
# opt_params = sgd(training_gradient_fun, params, hyper=1, num_iters=5000, step_size=0.1)
res = scipy.optimize.minimize(fun=training_loss_fun,
jac=training_gradient_fun,
x0=init_params,
tol=1e-10,
options={'disp': verbose})
opt_params = res.x
if verbose:
print("Trained loss:", self.loss(opt_params, weights, inputs, targets))
self.params = opt_params
return opt_params
def get_test_acc(self, params, test_targets, test_inputs):
preds = np.round(self.predict(test_inputs).T).astype(np.int)
err = np.abs(test_targets - preds).sum()
return 1 - err/ test_targets.shape[1]
#### Required for IJ computation ###
def compute_hessian(self, params_one, weights_one, inputs, targets):
return autograd.hessian(self.loss, argnum=0)(params_one, weights_one, inputs, targets)
def compute_jacobian(self, params_one, weights_one, inputs, targets):
return autograd.jacobian(autograd.jacobian(self.loss, argnum=0), argnum=1)\\
(params_one, weights_one, inputs, targets).squeeze()
###################################################
@staticmethod
def synthetic_lr_data(N=10000, D=10):
x = 1. * npr.randn(N, D)
x_test = 1. * npr.randn(int(0.3 * N), D)
w = npr.randn(D, 1)
y = sigmoid((x @ w)).ravel()
y = npr.binomial(n=1, p=y) # corrupt labels
y_test = sigmoid(x_test @ w).ravel()
# y_test = np.round(y_test)
y_test = npr.binomial(n=1, p=y_test)
return x, np.atleast_2d(y), x_test, np.atleast_2d(y_test)
<s><s> import abc
import sys
# Ensure compatibility with Python 2/3
if sys.version_info >= (3, 4):
ABC = abc.ABC
else:
ABC = abc.ABCMeta(str('ABC'), (), {})
from copy import deepcopy
import numpy as np
import numpy.random as npr
def make_batches(n_data, batch_size):
return [slice(i, min(i+batch_size, n_data)) for i in range(0, n_data, batch_size)]
def generate_regression_data(seed, data_count=500):
"""
Generate data from a noisy sine wave.
:param seed: random number seed
:param data_count: number of data points.
:return:
"""
np.random.seed(seed)
noise_var = 0.1
x = np.linspace(-4, 4, data_count)
y = 1*np.sin(x) + np.sqrt(noise_var)*npr.randn(data_count)
train_count = int (0.2 * data_count)
idx = npr.permutation(range(data_count))
x_train = x[idx[:train_count], np.newaxis ]
x_test = x[ idx[train_count:], np.newaxis ]
y_train = y[ idx[:train_count] ]
y_test = y[ idx[train_count:] ]
mu = np.mean(x_train, 0)
std = np.std(x_train, 0)
x_train = (x_train - mu) / std
x_test = (x_test - mu) / std
mu = np.mean(y_train, 0)
std = np.std(y_train, 0)
y_train = (y_train - mu) / std
train_stats = dict()
train_stats['mu'] = mu
train_stats['sigma'] = std
return x_train, y_train, x_test, y_test, train_stats
def form_D_for_auucc(yhat, zhatl, zhatu):
# a handy routine to format data as needed by the UCC fit() method
D = np.zeros([yhat.shape[0], 3])
D[:, 0] = yhat.squeeze()
D[:, 1] = zhatl.squeeze()
D[:, 2] = zhatu.squeeze()
return D
def fitted_ucc_w_nullref(y_true, y_pred_mean, y_pred_lower, y_pred_upper):
"""
Instantiates an UCC object for the target predictor plus a 'null' (constant band) reference
:param y_pred_lower:
:param y_pred_mean:
:param y_pred_upper:
:param y_true:
:return: ucc object fitted for two systems: target + null reference
"""
# form matrix for ucc:
X_for_ucc = form_D_for_auucc(y_pred_mean.squeeze(),
y_pred_mean.squeeze() - y_pred_lower.squeeze(),
y_pred_upper.squeeze() - y_pred_mean.squeeze())
# form matrix for a 'null' system (constant band)
X_null = deepcopy(X_for_ucc)
X_null[:,1:] = np.std(y_pred_mean) # can be set to any other constant (no effect on AUUCC)
# create an instance of ucc and fit data
from uq360.metrics.uncertainty_characteristics_curve import UncertaintyCharacteristicsCurve as ucc
u = ucc()
u.fit([X_for_ucc, X_null], y_true.squeeze())
return u
def make_sklearn_compatible_scorer(task_type, metric, greater_is_better=True, **kwargs):
"""
Args:
task_type: (str) regression or classification.
metric: (str): choice of metric can be one of these - [aurrrc, ece, auroc, nll, brier, accuracy] for
classification and ["rmse", "nll", "auucc_gain", "picp", "mpiw", "r2"] for regression.
greater_is_better: is False the scores are negated before returning.
**kwargs: additional arguments specific to some metrics.
Returns:
sklearn compatible scorer function.
"""
from uq360.metrics.classification_metrics import compute_classification_metrics
from uq360.metrics.regression_metrics import compute_regression_metrics
def sklearn_compatible_score(model, X, y_true):
"""
Args:
model: The model being scored. Currently uq360 and sklearn models are supported.
X: Input features.
y_true: ground truth values for the target.
Returns:
Computed score of the model.
"""
from uq360.algorithms.builtinuq import BuiltinUQ
from uq360.algorithms.posthocuq import PostHocUQ
if isinstance(model, BuiltinUQ) or isinstance(model, PostHocUQ):
# uq360 models
if task_type == "classification":
score = compute_classification_metrics(
y_true=y_true,
y_prob=model.predict(X).y_prob,
option=metric,
**kwargs
)[metric]
elif task_type == "regression":
y_mean, y_lower, y_upper = model.predict(X)
score = compute_regression_metrics(
y_true=y_true,
y_mean=y_mean,
y_lower=y_lower,
y_upper=y_upper,
option=metric,
**kwargs
)[metric]
else:
raise NotImplementedError
else:
# sklearn models
if task_type == "classification":
score = compute_classification_metrics(
y_true=y_true,
y_prob=model.predict_proba(X),
option=metric,
**kwargs
)[metric]
else:
if metric in ["rmse", "r2"]:
score = compute_regression_metrics(
y_true=y_true,
y_mean=model.predict(X),
y_lower=None,
y_upper=None,
option=metric,
**kwargs
)[metric]
else:
raise NotImplementedError("{} is not supported for sklearn regression models".format(metric))
if not greater_is_better:
score = -score
return score
return sklearn_compatible_score
class DummySklearnEstimator(ABC):
def __init__(self, num_classes, base_model_prediction_fn):
self.base_model_prediction_fn = base_model_prediction_fn
self.classes_ = [i for i in range(num_classes)]
def fit(self):
pass
def predict_proba(self, X):
return self.base_model_prediction_fn(X)
<s> from .meps_dataset import MEPSDataset
<s> # Adapted from https://github.com/Trusted-AI/AIX360/blob/master/aix360/datasets/meps_dataset.py
# Utilization target is kept as a continuous target.
import os
import pandas as pd
def default_preprocessing(df):
"""
1.Create a new column, RACE that is 'White' if RACEV2X = 1 and HISPANX = 2 i.e. non Hispanic White
and 'non-White' otherwise
2. Restrict to Panel 19
3. RENAME all columns that are PANEL/ROUND SPECIFIC
4. Drop rows based on certain values of individual features that correspond to missing/unknown - generally < -1
5. Compute UTILIZATION.
"""
def race(row):
if ((row['HISPANX'] == 2) and (row['RACEV2X'] == 1)): #non-Hispanic Whites are marked as WHITE; all others as NON-WHITE
return 'White'
return 'Non-White'
df['RACEV2X'] = df.apply(lambda row: race(row), axis=1)
df = df.rename(columns = {'RACEV2X' : 'RACE'})
df = df[df['PANEL'] == 19]
# RENAME COLUMNS
df = df.rename(columns = {'FTSTU53X' : 'FTSTU', 'ACTDTY53' : 'ACTDTY', 'HONRDC53' : 'HONRDC', 'RTHLTH53' : 'RTHLTH',
'MNHLTH53' : 'MNHLTH', 'CHBRON53' : 'CHBRON', 'JTPAIN53' : 'JTPAIN', 'PREGNT53' : 'PREGNT',
'WLKLIM53' : 'WLKLIM', 'ACTLIM53' : 'ACTLIM', 'SOCLIM53' : 'SOCLIM', 'COGLIM53' : 'COGLIM',
'EMPST53' : 'EMPST', 'REGION53' : 'REGION', 'MARRY53X' : 'MARRY', 'AGE53X' : 'AGE',
'POVCAT15' : 'POVCAT', 'INSCOV15' : 'INSCOV'})
df = df[df['REGION'] >= 0] # remove values -1
df = df[df['AGE'] >= 0] # remove values -1
df = df[df['MARRY'] >= 0] # remove values -1, -7, -8, -9
df = df[df['ASTHDX'] >= 0] # remove values -1, -7, -8, -9
df = df[(df[['FTSTU','ACTDTY','HONRDC','RTHLTH','MNHLTH','HIBPDX','CHDDX','ANGIDX','EDUCYR','HIDEG',
| ||
'MIDX','OHRTDX','STRKDX','EMPHDX','CHBRON','CHOLDX','CANCERDX','DIABDX',
'JTPAIN','ARTHDX','ARTHTYPE','ASTHDX','ADHDADDX','PREGNT','WLKLIM',
'ACTLIM','SOCLIM','COGLIM','DFHEAR42','DFSEE42','ADSMOK42',
'PHQ242','EMPST','POVCAT','INSCOV']] >= -1).all(1)] #for all other categorical features, remove values < -1
def utilization(row):
return row['OBTOTV15'] + row['OPTOTV15'] + row['ERTOT15'] + row['IPNGTD15'] + row['HHTOTD15']
df['TOTEXP15'] = df.apply(lambda row: utilization(row), axis=1)
df = df.rename(columns = {'TOTEXP15' : 'UTILIZATION'})
df = df[['REGION','AGE','SEX','RACE','MARRY',
'FTSTU','ACTDTY','HONRDC','RTHLTH','MNHLTH','HIBPDX','CHDDX','ANGIDX',
'MIDX','OHRTDX','STRKDX','EMPHDX','CHBRON','CHOLDX','CANCERDX','DIABDX',
'JTPAIN','ARTHDX','ARTHTYPE','ASTHDX','ADHDADDX','PREGNT','WLKLIM',
'ACTLIM','SOCLIM','COGLIM','DFHEAR42','DFSEE42','ADSMOK42','PCS42',
'MCS42','K6SUM42','PHQ242','EMPST','POVCAT','INSCOV','UTILIZATION','PERWT15F']]
return df
class MEPSDataset():
"""
The Medical Expenditure Panel Survey (MEPS) [#]_ data consists of large scale surveys of families and individuals,
medical providers, and employers, and collects data on health services used, costs & frequency of services,
demographics, health status and conditions, etc., of the respondents.
This specific dataset contains MEPS survey data for calendar year 2015 obtained in rounds 3, 4, and 5 of Panel 19,
and rounds 1, 2, and 3 of Panel 20.
See :file:`uq360/datasets/data/meps_data/README.md` for more details on the dataset and instructions on downloading/processing the data.
References:
.. [#] `Medical Expenditure Panel Survey data <https://meps.ahrq.gov/mepsweb/>`_
"""
def __init__(self, custom_preprocessing=default_preprocessing, dirpath=None):
self._dirpath = dirpath
if not self._dirpath:
self._dirpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'meps_data')
self._filepath = os.path.join(self._dirpath, 'h181.csv')
try:
df = pd.read_csv(self._filepath, sep=',', na_values=[])
except IOError as err:
print("IOError: {}".format(err))
print("To use this class, please place the heloc_dataset.csv:")
print("file, as-is, in the folder:")
print("\\n\\t{}\\n".format(os.path.abspath(os.path.join(
os.path.abspath(__file__), 'data', 'meps_data'))))
import sys
sys.exit(1)
if custom_preprocessing:
self._data = custom_preprocessing(df)
def data(self):
return self._data<s><s> # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Base class for generating the feature_statistics proto from TensorFlow data.
The proto is used as input for the Overview visualization.
"""
from functools import partial
from facets_overview.base_generic_feature_statistics_generator import BaseGenericFeatureStatisticsGenerator
import tensorflow as tf
# The feature name used to track sequence length when analyzing
# tf.SequenceExamples.
SEQUENCE_LENGTH_FEATURE_NAME = 'sequence length (derived feature)'
class BaseFeatureStatisticsGenerator(BaseGenericFeatureStatisticsGenerator):
"""Base class for generator of stats proto from TF data."""
def __init__(self, fs_proto, datasets_proto, histogram_proto):
BaseGenericFeatureStatisticsGenerator.__init__(
self, fs_proto, datasets_proto, histogram_proto)
def ProtoFromTfRecordFiles(self,
files,
max_entries=10000,
features=None,
is_sequence=False,
iterator_options=None,
histogram_categorical_levels_count=None):
"""Creates a feature statistics proto from a set of TFRecord files.
Args:
files: A list of dicts describing files for each dataset for the proto.
Each
entry contains a 'path' field with the path to the TFRecord file on
disk
and a 'name' field to identify the dataset in the proto.
max_entries: The maximum number of examples to load from each dataset
in order to create the proto. Defaults to 10000.
features: A list of strings that is a whitelist of feature names to create
feature statistics for. If set to None then all features in the
dataset
are analyzed. Defaults to None.
is_sequence: True if the input data from 'tables' are tf.SequenceExamples,
False if tf.Examples. Defaults to false.
iterator_options: Options to pass to the iterator that reads the examples.
Defaults to None.
histogram_categorical_levels_count: int, controls the maximum number of
levels to display in histograms for categorical features.
Useful to prevent codes/IDs features from bloating the stats object.
Defaults to None.
Returns:
The feature statistics proto for the provided files.
"""
datasets = []
for entry in files:
entries, size = self._GetTfRecordEntries(entry['path'], max_entries,
is_sequence, iterator_options)
datasets.append({'entries': entries, 'size': size, 'name': entry['name']})
return self.GetDatasetsProto(
datasets,
features,
histogram_categorical_levels_count)
def _ParseExample(self, example_features, example_feature_lists, entries,
index):
"""Parses data from an example, populating a dictionary of feature values.
Args:
example_features: A map of strings to tf.Features from the example.
example_feature_lists: A map of strings to tf.FeatureLists from the
example.
entries: A dictionary of all features parsed thus far and arrays of their
values. This is mutated by the function.
index: The index of the example to parse from a list of examples.
Raises:
TypeError: Raises an exception when a feature has inconsistent types
across
examples.
"""
features_seen = set()
for feature_list, is_feature in zip(
[example_features, example_feature_lists], [True, False]):
sequence_length = None
for feature_name in feature_list:
# If this feature has not been seen in previous examples, then
# initialize its entry into the entries dictionary.
if feature_name not in entries:
entries[feature_name] = {
'vals': [],
'counts': [],
'feat_lens': [],
'missing': index
}
feature_entry = entries[feature_name]
feature = feature_list[feature_name]
value_type = None
value_list = []
if is_feature:
# If parsing a tf.Feature, extract the type and values simply.
if feature.HasField('float_list'):
value_list = feature.float_list.value
value_type = self.fs_proto.FLOAT
elif feature.HasField('bytes_list'):
value_list = feature.bytes_list.value
value_type = self.fs_proto.STRING
elif feature.HasField('int64_list'):
value_list = feature.int64_list.value
value_type = self.fs_proto.INT
else:
# If parsing a tf.FeatureList, get the type and values by iterating
# over all Features in the FeatureList.
sequence_length = len(feature.feature)
if sequence_length != 0 and feature.feature[0].HasField('float_list'):
for feat in feature.feature:
for value in feat.float_list.value:
value_list.append(value)
value_type = self.fs_proto.FLOAT
elif sequence_length != 0 and feature.feature[0].HasField(
'bytes_list'):
for feat in feature.feature:
for value in feat.bytes_list.value:
value_list.append(value)
value_type = self.fs_proto.STRING
elif sequence_length != 0 and feature.feature[0].HasField(
'int64_list'):
for feat in feature.feature:
for value in feat.int64_list.value:
value_list.append(value)
value_type = self.fs_proto.INT
if value_type is not None:
if 'type' not in feature_entry:
feature_entry['type'] = value_type
elif feature_entry['type'] != value_type:
raise TypeError('type mismatch for feature ' + feature_name)
feature_entry['counts'].append(len(value_list))
feature_entry['vals'].extend(value_list)
if sequence_length is not None:
feature_entry['feat_lens'].append(sequence_length)
if value_list:
features_seen.add(feature_name)
# For all previously-seen features not found in this example, update the
# feature's missing value.
for f in entries:
fv = entries[f]
if f not in features_seen:
fv['missing'] += 1
def _GetEntries(self,
paths,
max_entries,
iterator_from_file,
is_sequence=False):
"""Extracts examples into a dictionary of feature values.
Args:
paths: A list of the paths to the files to parse.
max_entries: The maximum number of examples to load.
iterator_from_file: A method that takes a file path string and returns an
iterator to the examples in that file.
is_sequence: True if the input data from 'iterator_from_file' are
tf.SequenceExamples, False if tf.Examples. Defaults to false.
Returns:
A tuple with two elements:
- A dictionary of all features parsed thus far and arrays of their
values.
- The number of examples parsed.
"""
entries = {}
index = 0
for filepath in paths:
reader = iterator_from_file(filepath)
for record in reader:
if is_sequence:
sequence_example = tf.train.SequenceExample.FromString(record)
self._ParseExample(sequence_example.context.feature,
sequence_example.feature_lists.feature_list,
entries, index)
else:
self._ParseExample(
tf.train.Example.FromString(record).features.feature, [], entries,
index)
index += 1
if index == max_entries:
return entries, index
return entries, index
def _GetTfRecordEntries(self, path, max_entries, is_sequence,
iterator_options):
"""Extracts TFRecord examples into a dictionary of feature values.
Args:
path: The path to the TFRecord file(s).
max_entries: The maximum number of examples to load.
is_sequence: True if the input data from 'path' are tf.SequenceExamples,
False if tf.Examples. Defaults to false.
iterator_options: Options to pass to the iterator that reads the examples.
Defaults to None.
Returns:
A tuple with two elements:
- A dictionary of all features parsed thus far and arrays of their
values.
- The number of examples parsed.
"""
return self._GetEntries([path], max_entries,
partial(
tf.compat.v1.io.tf_record_iterator,
options=iterator_options), is_sequence)
<s> # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from facets_overview.generic_feature_statistics_generator import GenericFeatureStatisticsGenerator
import numpy as np
import pandas as pd
from tensorflow.python.platform import googletest
class GenericFeatureStatisticsGeneratorTest(googletest.TestCase):
def setUp(self):
self.gfsg = GenericFeatureStatisticsGenerator()
def testProtoFromDataFrames(self):
data = [[1, 'hi'], [2, 'hello'], [3, 'hi']]
df = pd.DataFrame(data, columns=['testFeatureInt', 'testFeatureString'])
dataframes = [{'table': df, 'name': 'testDataset'}]
p = self.gfsg.ProtoFromDataFrames(dataframes)
self.assertEqual(1, len(p.datasets))
test_data = p.datasets[0]
self.assertEqual('testDataset', test_data.name)
self.assertEqual(3, test_data.num_examples)
self.assertEqual(2, len(test_data.features))
if test_data.features[0].name == 'testFeatureInt':
numfeat = test_data.features[0]
stringfeat = test_data.features[1]
else:
numfeat = test_data.features[1]
stringfeat = test_data.features[0]
self.assertEqual('testFeatureInt', numfeat.name)
self.assertEqual(self.gfsg.fs_proto.INT, numfeat.type)
self.assertEqual(1, numfeat.num_stats.min)
self.assertEqual(3, numfeat.num_stats.max)
self.assertEqual('testFeatureString', stringfeat.name) | ||
self.assertEqual(self.gfsg.fs_proto.STRING, stringfeat.type)
self.assertEqual(2, stringfeat.string_stats.unique)
def testNdarrayToEntry(self):
arr = np.array([1.0, 2.0, None, float('nan'), 3.0], dtype=float)
entry = self.gfsg.NdarrayToEntry(arr)
self.assertEqual(2, entry['missing'])
arr = np.array(['a', 'b', float('nan'), 'c'], dtype=str)
entry = self.gfsg.NdarrayToEntry(arr)
self.assertEqual(1, entry['missing'])
def testNdarrayToEntryTimeTypes(self):
arr = np.array(
[np.datetime64('2005-02-25'),
np.datetime64('2006-02-25')],
dtype=np.datetime64)
entry = self.gfsg.NdarrayToEntry(arr)
self.assertEqual([1109289600000000000, 1140825600000000000], entry['vals'])
arr = np.array(
[np.datetime64('2009-01-01') - np.datetime64('2008-01-01')],
dtype=np.timedelta64)
entry = self.gfsg.NdarrayToEntry(arr)
self.assertEqual([31622400000000000], entry['vals'])
def testDTypeToType(self):
self.assertEqual(self.gfsg.fs_proto.INT,
self.gfsg.DtypeToType(np.dtype(np.int32)))
# Boolean and time types treated as int
self.assertEqual(self.gfsg.fs_proto.INT,
self.gfsg.DtypeToType(np.dtype(np.bool)))
self.assertEqual(self.gfsg.fs_proto.INT,
self.gfsg.DtypeToType(np.dtype(np.datetime64)))
self.assertEqual(self.gfsg.fs_proto.INT,
self.gfsg.DtypeToType(np.dtype(np.timedelta64)))
self.assertEqual(self.gfsg.fs_proto.FLOAT,
self.gfsg.DtypeToType(np.dtype(np.float32)))
self.assertEqual(self.gfsg.fs_proto.STRING,
self.gfsg.DtypeToType(np.dtype(np.str)))
# Unsupported types treated as string for now
self.assertEqual(self.gfsg.fs_proto.STRING,
self.gfsg.DtypeToType(np.dtype(np.void)))
def testGetDatasetsProtoFromEntriesLists(self):
entries = {}
entries['testFeature'] = {
'vals': [1, 2, 3],
'counts': [1, 1, 1],
'missing': 0,
'type': self.gfsg.fs_proto.INT
}
datasets = [{'entries': entries, 'size': 3, 'name': 'testDataset'}]
p = self.gfsg.GetDatasetsProto(datasets)
self.assertEqual(1, len(p.datasets))
test_data = p.datasets[0]
self.assertEqual('testDataset', test_data.name)
self.assertEqual(3, test_data.num_examples)
self.assertEqual(1, len(test_data.features))
numfeat = test_data.features[0]
self.assertEqual('testFeature', numfeat.name)
self.assertEqual(self.gfsg.fs_proto.INT, numfeat.type)
self.assertEqual(1, numfeat.num_stats.min)
self.assertEqual(3, numfeat.num_stats.max)
hist = numfeat.num_stats.common_stats.num_values_histogram
buckets = hist.buckets
self.assertEqual(self.gfsg.histogram_proto.QUANTILES, hist.type)
self.assertEqual(10, len(buckets))
self.assertEqual(1, buckets[0].low_value)
self.assertEqual(1, buckets[0].high_value)
self.assertEqual(.3, buckets[0].sample_count)
self.assertEqual(1, buckets[9].low_value)
self.assertEqual(1, buckets[9].high_value)
self.assertEqual(.3, buckets[9].sample_count)
def testGetDatasetsProtoSequenceExampleHistogram(self):
entries = {}
entries['testFeature'] = {
'vals': [1, 2, 2, 3],
'counts': [1, 2, 1],
'feat_lens': [1, 2, 1],
'missing': 0,
'type': self.gfsg.fs_proto.INT
}
datasets = [{'entries': entries, 'size': 3, 'name': 'testDataset'}]
p = self.gfsg.GetDatasetsProto(datasets)
hist = p.datasets[0].features[
0].num_stats.common_stats.feature_list_length_histogram
buckets = hist.buckets
self.assertEqual(self.gfsg.histogram_proto.QUANTILES, hist.type)
self.assertEqual(10, len(buckets))
self.assertEqual(1, buckets[0].low_value)
self.assertEqual(1, buckets[0].high_value)
self.assertEqual(.3, buckets[0].sample_count)
self.assertEqual(1.8, buckets[9].low_value)
self.assertEqual(2, buckets[9].high_value)
self.assertEqual(.3, buckets[9].sample_count)
def testGetDatasetsProtoWithWhitelist(self):
entries = {}
entries['testFeature'] = {
'vals': [1, 2, 3],
'counts': [1, 1, 1],
'missing': 0,
'type': self.gfsg.fs_proto.INT
}
entries['ignoreFeature'] = {
'vals': [5, 6],
'counts': [1, 1],
'missing': 1,
'type': self.gfsg.fs_proto.INT
}
datasets = [{'entries': entries, 'size': 3, 'name': 'testDataset'}]
p = self.gfsg.GetDatasetsProto(datasets, features=['testFeature'])
self.assertEqual(1, len(p.datasets))
test_data = p.datasets[0]
self.assertEqual('testDataset', test_data.name)
self.assertEqual(3, test_data.num_examples)
self.assertEqual(1, len(test_data.features))
numfeat = test_data.features[0]
self.assertEqual('testFeature', numfeat.name)
self.assertEqual(1, numfeat.num_stats.min)
def testGetDatasetsProtoWithMaxHistigramLevelsCount(self):
# Selected entries' lengths make it easy to compute average length
data = [['hi'], ['good'], ['hi'], ['hi'], ['a'], ['a']]
df = pd.DataFrame(data, columns=['testFeatureString'])
dataframes = [{'table': df, 'name': 'testDataset'}]
# Getting proto from ProtoFromDataFrames instead of GetDatasetsProto
# directly to avoid any hand written values ex: size of dataset.
p = self.gfsg.ProtoFromDataFrames(dataframes,
histogram_categorical_levels_count=2)
self.assertEqual(1, len(p.datasets))
test_data = p.datasets[0]
self.assertEqual('testDataset', test_data.name)
self.assertEqual(6, test_data.num_examples)
self.assertEqual(1, len(test_data.features))
numfeat = test_data.features[0]
self.assertEqual('testFeatureString', numfeat.name)
top_values = numfeat.string_stats.top_values
self.assertEqual(3, top_values[0].frequency)
self.assertEqual('hi', top_values[0].value)
self.assertEqual(3, numfeat.string_stats.unique)
self.assertEqual(2, numfeat.string_stats.avg_length)
rank_hist = numfeat.string_stats.rank_histogram
buckets = rank_hist.buckets
self.assertEqual(2, len(buckets))
self.assertEqual('hi', buckets[0].label)
self.assertEqual(3, buckets[0].sample_count)
self.assertEqual('a', buckets[1].label)
self.assertEqual(2, buckets[1].sample_count)
if __name__ == '__main__':
googletest.main()
<s> # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Code for generating the feature_statistics proto from generic data.
The proto is used as input for the Overview visualization.
"""
from facets_overview.base_generic_feature_statistics_generator import BaseGenericFeatureStatisticsGenerator
import facets_overview.feature_statistics_pb2 as fs
class GenericFeatureStatisticsGenerator(BaseGenericFeatureStatisticsGenerator):
"""Generator of stats proto from generic data."""
def __init__(self):
BaseGenericFeatureStatisticsGenerator.__init__(
self, fs.FeatureNameStatistics, fs.DatasetFeatureStatisticsList,
fs.Histogram)
<s> # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from facets_overview.feature_statistics_generator import FeatureStatisticsGenerator
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import googletest
class FeatureStatisticsGeneratorTest(googletest.TestCase):
def setUp(self):
self.fs = FeatureStatisticsGenerator()
def testParseExampleInt(self):
# Tests parsing examples of integers
examples = []
for i in range(50):
example = tf.train.Example()
example.features.feature['num'].int64_list.value.append(i)
examples.append(example)
entries = {}
for i, example in enumerate(examples):
self.fs._ParseExample(example.features.feature, [], entries, i)
self.assertEqual(1, len(entries))
self.assertIn('num', entries)
info = entries['num']
self.assertEqual(0, info['missing'])
self.assertEqual(self.fs.fs_proto.INT, info['type'])
for i in range(len(examples)):
self.assertEqual(1, info['counts'][i])
self.assertEqual(i, info['vals'][i])
def testParseExampleMissingValueList(self):
# Tests parsing examples of integers
examples = []
example = tf.train.Example()
# pylint: disable=pointless-statement
example.features.feature['str']
# pylint: enable=pointless-statement
examples.append(example)
example = tf.train.Example()
example.features.feature['str'].bytes_list.value.append(b'test')
examples.append(example)
entries = {}
for i, example in enumerate(examples):
self.fs._ParseExample(example.features.feature, [], entries, i)
self.assertEqual(1, len(entries))
self.assertIn('str', entries)
info = entries['str']
self.assertEqual(1, info['missing'])
self.assertEqual(self.fs.fs_proto.STRING, info['type'])
self.assertEqual(0, info['counts'][0])
self.assertEqual(1, info['counts'][1])
def _check_sequence_example_entries(self,
entries,
n_examples,
n_features,
feat_len=None):
self.assertIn('num', entries)
info = entries['num']
self.assertEqual(0, info['missing'])
self.assertEqual(self.fs.fs_proto.INT, info['type'])
for i in range(n_examples):
self.assertEqual(n_features, info['counts'][i])
if feat_len is not None:
self.assertEqual(feat_len, info['feat_lens'][i])
for i in range(n_examples * n_features):
self.assertEqual(i, info['vals'][i])
if feat_len is None:
self.assertEqual(0, len(info['feat_lens']))
def testParseExampleSequenceContext(self):
# Tests parsing examples of integers in context field
examples = []
for i in range(50):
example = tf.train.SequenceExample()
example.context.feature['num'].int64_list.value.append(i)
examples.append(example)
entries = {}
for i, example in enumerate(examples):
self.fs._ParseExample(example.context.feature,
example.feature_lists.feature_list, entries, i)
self._check_sequence_example_entries(entries, 50, 1)
self.assertEqual(1, len(entries))
def testParseExampleSequenceFeatureList(self):
examples = []
for i in range(50):
example = tf.train.SequenceExample()
feat = example.feature_lists.feature_list['num'].feature.add()
feat.int64_list.value.append(i)
examples.append(example)
entries = {}
for i, example in enumerate(examples):
self.fs._ParseExample(example.context.feature,
example.feature_lists.feature_list, entries, i)
self._check_sequence_example_entries(entries, 50, 1, 1)
def testParseExampleSequenceFeature | ||
ListMultipleEntriesInner(self):
examples = []
for i in range(2):
example = tf.train.SequenceExample()
feat = example.feature_lists.feature_list['num'].feature.add()
for j in range(25):
feat.int64_list.value.append(i * 25 + j)
examples.append(example)
entries = {}
for i, example in enumerate(examples):
self.fs._ParseExample(example.context.feature,
example.feature_lists.feature_list, entries, i)
self._check_sequence_example_entries(entries, 2, 25, 1)
def testParseExampleSequenceFeatureListMultipleEntriesOuter(self):
# Tests parsing examples of integers in context field
examples = []
for i in range(2):
example = tf.train.SequenceExample()
for j in range(25):
feat = example.feature_lists.feature_list['num'].feature.add()
feat.int64_list.value.append(i * 25 + j)
examples.append(example)
entries = {}
for i, example in enumerate(examples):
self.fs._ParseExample(example.context.feature,
example.feature_lists.feature_list, entries, i)
self._check_sequence_example_entries(entries, 2, 25, 25)
def testVaryingCountsAndMissing(self):
# Tests parsing examples of when some examples have missing features
examples = []
for i in range(5):
example = tf.train.Example()
example.features.feature['other'].int64_list.value.append(0)
for _ in range(i):
example.features.feature['num'].int64_list.value.append(i)
examples.append(example)
example = tf.train.Example()
example.features.feature['other'].int64_list.value.append(0)
examples.append(example)
entries = {}
for i, example in enumerate(examples):
self.fs._ParseExample(example.features.feature, [], entries, i)
info = entries['num']
self.assertEqual(2, info['missing'])
self.assertEqual(4, len(info['counts']))
for i in range(4):
self.assertEqual(i + 1, info['counts'][i])
self.assertEqual(10, len(info['vals']))
def testParseExampleStringsAndFloats(self):
# Tests parsing examples of string and float features
examples = []
for i in range(50):
example = tf.train.Example()
example.features.feature['str'].bytes_list.value.append(b'hi')
example.features.feature['float'].float_list.value.append(i)
examples.append(example)
entries = {}
for i, example in enumerate(examples):
self.fs._ParseExample(example.features.feature, [], entries, i)
self.assertEqual(2, len(entries))
self.assertEqual(self.fs.fs_proto.FLOAT, entries['float']['type'])
self.assertEqual(self.fs.fs_proto.STRING, entries['str']['type'])
for i in range(len(examples)):
self.assertEqual(1, entries['str']['counts'][i])
self.assertEqual(1, entries['float']['counts'][i])
self.assertEqual(i, entries['float']['vals'][i])
self.assertEqual('hi', entries['str']['vals'][i].decode(
'UTF-8', 'strict'))
def testParseExamplesTypeMismatch(self):
examples = []
example = tf.train.Example()
example.features.feature['feat'].int64_list.value.append(0)
examples.append(example)
example = tf.train.Example()
example.features.feature['feat'].bytes_list.value.append(b'str')
examples.append(example)
entries = {}
self.fs._ParseExample(examples[0].features.feature, [], entries, 0)
with self.assertRaises(TypeError):
self.fs._ParseExample(examples[1].features.feature, [], entries, 1)
def testGetDatasetsProtoFromEntriesLists(self):
entries = {}
entries['testFeature'] = {
'vals': [1, 2, 3],
'counts': [1, 1, 1],
'missing': 0,
'type': self.fs.fs_proto.INT
}
datasets = [{'entries': entries, 'size': 3, 'name': 'testDataset'}]
p = self.fs.GetDatasetsProto(datasets)
self.assertEqual(1, len(p.datasets))
test_data = p.datasets[0]
self.assertEqual('testDataset', test_data.name)
self.assertEqual(3, test_data.num_examples)
self.assertEqual(1, len(test_data.features))
numfeat = test_data.features[0]
self.assertEqual('testFeature', numfeat.name)
self.assertEqual(self.fs.fs_proto.INT, numfeat.type)
self.assertEqual(1, numfeat.num_stats.min)
self.assertEqual(3, numfeat.num_stats.max)
def testGetProtoNums(self):
# Tests converting int examples into the feature stats proto
examples = []
for i in range(50):
example = tf.train.Example()
example.features.feature['num'].int64_list.value.append(i)
examples.append(example)
example = tf.train.Example()
example.features.feature['other'].int64_list.value.append(0)
examples.append(example)
entries = {}
for i, example in enumerate(examples):
self.fs._ParseExample(example.features.feature, [], entries, i)
datasets = [{'entries': entries, 'size': len(examples), 'name': 'test'}]
p = self.fs.GetDatasetsProto(datasets)
self.assertEqual(1, len(p.datasets))
test_data = p.datasets[0]
self.assertEqual('test', test_data.name)
self.assertEqual(51, test_data.num_examples)
numfeat = test_data.features[0] if (
test_data.features[0].name == 'num') else test_data.features[1]
self.assertEqual('num', numfeat.name)
self.assertEqual(self.fs.fs_proto.INT, numfeat.type)
self.assertEqual(0, numfeat.num_stats.min)
self.assertEqual(49, numfeat.num_stats.max)
self.assertEqual(24.5, numfeat.num_stats.mean)
self.assertEqual(24.5, numfeat.num_stats.median)
self.assertEqual(1, numfeat.num_stats.num_zeros)
self.assertAlmostEqual(14.430869689, numfeat.num_stats.std_dev, 4)
self.assertEqual(1, numfeat.num_stats.common_stats.num_missing)
self.assertEqual(50, numfeat.num_stats.common_stats.num_non_missing)
self.assertEqual(1, numfeat.num_stats.common_stats.min_num_values)
self.assertEqual(1, numfeat.num_stats.common_stats.max_num_values)
self.assertAlmostEqual(1, numfeat.num_stats.common_stats.avg_num_values, 4)
hist = numfeat.num_stats.common_stats.num_values_histogram
buckets = hist.buckets
self.assertEqual(self.fs.histogram_proto.QUANTILES, hist.type)
self.assertEqual(10, len(buckets))
self.assertEqual(1, buckets[0].low_value)
self.assertEqual(1, buckets[0].high_value)
self.assertEqual(5, buckets[0].sample_count)
self.assertEqual(1, buckets[9].low_value)
self.assertEqual(1, buckets[9].high_value)
self.assertEqual(5, buckets[9].sample_count)
self.assertEqual(2, len(numfeat.num_stats.histograms))
buckets = numfeat.num_stats.histograms[0].buckets
self.assertEqual(self.fs.histogram_proto.STANDARD,
numfeat.num_stats.histograms[0].type)
self.assertEqual(10, len(buckets))
self.assertEqual(0, buckets[0].low_value)
self.assertEqual(4.9, buckets[0].high_value)
self.assertEqual(5, buckets[0].sample_count)
self.assertAlmostEqual(44.1, buckets[9].low_value)
self.assertEqual(49, buckets[9].high_value)
self.assertEqual(5, buckets[9].sample_count)
buckets = numfeat.num_stats.histograms[1].buckets
self.assertEqual(self.fs.histogram_proto.QUANTILES,
numfeat.num_stats.histograms[1].type)
self.assertEqual(10, len(buckets))
self.assertEqual(0, buckets[0].low_value)
self.assertEqual(4.9, buckets[0].high_value)
self.assertEqual(5, buckets[0].sample_count)
self.assertAlmostEqual(44.1, buckets[9].low_value)
self.assertEqual(49, buckets[9].high_value)
self.assertEqual(5, buckets[9].sample_count)
def testQuantiles(self):
examples = []
for i in range(50):
example = tf.train.Example()
example.features.feature['num'].int64_list.value.append(i)
examples.append(example)
for i in range(50):
example = tf.train.Example()
example.features.feature['num'].int64_list.value.append(100)
examples.append(example)
entries = {}
for i, example in enumerate(examples):
self.fs._ParseExample(example.features.feature, [], entries, i)
datasets = [{'entries': entries, 'size': len(examples), 'name': 'test'}]
p = self.fs.GetDatasetsProto(datasets)
numfeat = p.datasets[0].features[0]
self.assertEqual(2, len(numfeat.num_stats.histograms))
self.assertEqual(self.fs.histogram_proto.QUANTILES,
numfeat.num_stats.histograms[1].type)
buckets = numfeat.num_stats.histograms[1].buckets
self.assertEqual(10, len(buckets))
self.assertEqual(0, buckets[0].low_value)
self.assertEqual(9.9, buckets[0].high_value)
self.assertEqual(10, buckets[0].sample_count)
self.assertEqual(100, buckets[9].low_value)
self.assertEqual(100, buckets[9].high_value)
self.assertEqual(10, buckets[9].sample_count)
def testInfinityAndNan(self):
examples = []
for i in range(50):
example = tf.train.Example()
example.features.feature['num'].float_list.value.append(i)
examples.append(example)
example = tf.train.Example()
example.features.feature['num'].float_list.value.append(float('inf'))
examples.append(example)
example = tf.train.Example()
example.features.feature['num'].float_list.value.append(float('-inf'))
examples.append(example)
example = tf.train.Example()
example.features.feature['num'].float_list.value.append(float('nan'))
examples.append(example)
entries = {}
for i, example in enumerate(examples):
self.fs._ParseExample(example.features.feature, [], entries, i)
datasets = [{'entries': entries, 'size': len(examples), 'name': 'test'}]
p = self.fs.GetDatasetsProto(datasets)
numfeat = p.datasets[0].features[0]
self.assertEqual('num', numfeat.name)
self.assertEqual(self.fs.fs_proto.FLOAT, numfeat.type)
self.assertTrue(np.isnan(numfeat.num_stats.min))
self.assertTrue(np.isnan(numfeat.num_stats.max))
self.assertTrue(np.isnan(numfeat.num_stats.mean))
self.assertTrue(np.isnan(numfeat.num_stats.median))
self.assertEqual(1, numfeat.num_stats.num_zeros)
self.assertTrue(np.isnan(numfeat.num_stats.std_dev))
self.assertEqual(53, numfeat.num_stats.common_stats.num_non_missing)
hist = buckets = numfeat.num_stats.histograms[0]
buckets = hist.buckets
self.assertEqual(self.fs.histogram_proto.STANDARD, hist.type)
self.assertEqual(1, hist.num_nan)
self.assertEqual(10, len(buckets))
self.assertEqual(float('-inf'), buckets[0].low_value)
self.assertEqual(4.9, buckets[0].high_value)
self.assertEqual(6, buckets[0].sample_count)
self.assertEqual(44.1, buckets[9].low_value)
self.assertEqual(float('inf'), buckets[9].high_value)
self.assertEqual(6, buckets[9].sample_count)
def testInfinitysOnly(self):
examples = []
example = tf.train.Example()
example.features.feature['num'].float_list.value.append(float('inf'))
examples.append(example)
example = tf.train.Example()
example.features.feature['num'].float_list.value.append(float('-inf'))
examples.append(example)
entries = {}
for i, example in enumerate(examples):
self.fs._ParseExample(example.features.feature, [], entries, i)
datasets = [{'entries': entries, 'size': len(examples), 'name': 'test'}]
p = self.fs.GetDatasetsProto(datasets)
numfeat = p.datasets[0].features[0]
hist = buckets = numfeat.num_stats.histograms[0]
buckets = hist.buckets
self.assertEqual(self.fs.histogram_proto.STANDARD, hist.type)
self.assertEqual(10, len(buckets))
self.assertEqual(float('-inf'), buckets[0].low_value)
self.assertEqual(0.1, buckets[0].high_value)
self.assertEqual(1, buckets[0].sample_count)
self.assertEqual(0. | ||
9, buckets[9].low_value)
self.assertEqual(float('inf'), buckets[9].high_value)
self.assertEqual(1, buckets[9].sample_count)
def testGetProtoStrings(self):
# Tests converting string examples into the feature stats proto
examples = []
for i in range(2):
example = tf.train.Example()
example.features.feature['str'].bytes_list.value.append(b'hello')
examples.append(example)
for i in range(3):
example = tf.train.Example()
example.features.feature['str'].bytes_list.value.append(b'hi')
examples.append(example)
example = tf.train.Example()
example.features.feature['str'].bytes_list.value.append(b'hey')
examples.append(example)
entries = {}
for i, example in enumerate(examples):
self.fs._ParseExample(example.features.feature, [], entries, i)
datasets = [{'entries': entries, 'size': len(examples), 'name': 'test'}]
p = self.fs.GetDatasetsProto(datasets)
self.assertEqual(1, len(p.datasets))
test_data = p.datasets[0]
self.assertEqual('test', test_data.name)
self.assertEqual(6, test_data.num_examples)
strfeat = test_data.features[0]
self.assertEqual('str', strfeat.name)
self.assertEqual(self.fs.fs_proto.STRING, strfeat.type)
self.assertEqual(3, strfeat.string_stats.unique)
self.assertAlmostEqual(19 / 6.0, strfeat.string_stats.avg_length, 4)
self.assertEqual(0, strfeat.string_stats.common_stats.num_missing)
self.assertEqual(6, strfeat.string_stats.common_stats.num_non_missing)
self.assertEqual(1, strfeat.string_stats.common_stats.min_num_values)
self.assertEqual(1, strfeat.string_stats.common_stats.max_num_values)
self.assertEqual(1, strfeat.string_stats.common_stats.avg_num_values)
hist = strfeat.string_stats.common_stats.num_values_histogram
buckets = hist.buckets
self.assertEqual(self.fs.histogram_proto.QUANTILES, hist.type)
self.assertEqual(10, len(buckets))
self.assertEqual(1, buckets[0].low_value)
self.assertEqual(1, buckets[0].high_value)
self.assertEqual(.6, buckets[0].sample_count)
self.assertEqual(1, buckets[9].low_value)
self.assertEqual(1, buckets[9].high_value)
self.assertEqual(.6, buckets[9].sample_count)
self.assertEqual(2, len(strfeat.string_stats.top_values))
self.assertEqual(3, strfeat.string_stats.top_values[0].frequency)
self.assertEqual('hi', strfeat.string_stats.top_values[0].value)
self.assertEqual(2, strfeat.string_stats.top_values[1].frequency)
self.assertEqual('hello', strfeat.string_stats.top_values[1].value)
buckets = strfeat.string_stats.rank_histogram.buckets
self.assertEqual(3, len(buckets))
self.assertEqual(0, buckets[0].low_rank)
self.assertEqual(0, buckets[0].high_rank)
self.assertEqual(3, buckets[0].sample_count)
self.assertEqual('hi', buckets[0].label)
self.assertEqual(2, buckets[2].low_rank)
self.assertEqual(2, buckets[2].high_rank)
self.assertEqual(1, buckets[2].sample_count)
self.assertEqual('hey', buckets[2].label)
def testGetProtoMultipleDatasets(self):
# Tests converting multiple datsets into the feature stats proto
# including ensuring feature order is consistent in the protos.
examples1 = []
for i in range(2):
example = tf.train.Example()
example.features.feature['str'].bytes_list.value.append(b'one')
example.features.feature['num'].int64_list.value.append(0)
examples1.append(example)
examples2 = []
example = tf.train.Example()
example.features.feature['num'].int64_list.value.append(1)
example.features.feature['str'].bytes_list.value.append(b'two')
examples2.append(example)
entries1 = {}
for i, example1 in enumerate(examples1):
self.fs._ParseExample(example1.features.feature, [], entries1, i)
entries2 = {}
for i, example2 in enumerate(examples2):
self.fs._ParseExample(example2.features.feature, [], entries2, i)
datasets = [{
'entries': entries1,
'size': len(examples1),
'name': 'test1'
}, {
'entries': entries2,
'size': len(examples2),
'name': 'test2'
}]
p = self.fs.GetDatasetsProto(datasets)
self.assertEqual(2, len(p.datasets))
test_data_1 = p.datasets[0]
self.assertEqual('test1', test_data_1.name)
self.assertEqual(2, test_data_1.num_examples)
num_feat_index = 0 if test_data_1.features[0].name == 'num' else 1
self.assertEqual(0, test_data_1.features[num_feat_index].num_stats.max)
test_data_2 = p.datasets[1]
self.assertEqual('test2', test_data_2.name)
self.assertEqual(1, test_data_2.num_examples)
self.assertEqual(1, test_data_2.features[num_feat_index].num_stats.max)
def testGetEntriesNoFiles(self):
features, num_examples = self.fs._GetEntries(['test'], 10,
lambda unused_path: [])
self.assertEqual(0, num_examples)
self.assertEqual({}, features)
@staticmethod
def get_example_iter():
def ex_iter(unused_filename):
examples = []
for i in range(50):
example = tf.train.Example()
example.features.feature['num'].int64_list.value.append(i)
examples.append(example.SerializeToString())
return examples
return ex_iter
def testGetEntries_one(self):
features, num_examples = self.fs._GetEntries(['test'], 1,
self.get_example_iter())
self.assertEqual(1, num_examples)
self.assertTrue('num' in features)
def testGetEntries_oneFile(self):
unused_features, num_examples = self.fs._GetEntries(['test'], 1000,
self.get_example_iter())
self.assertEqual(50, num_examples)
def testGetEntries_twoFiles(self):
unused_features, num_examples = self.fs._GetEntries(['test0', 'test1'],
1000,
self.get_example_iter())
self.assertEqual(100, num_examples)
def testGetEntries_stopInSecondFile(self):
unused_features, num_examples = self.fs._GetEntries([
'test@0', 'test@1', 'test@2', 'test@3', 'test@4', 'test@5', 'test@6',
'test@7', 'test@8', 'test@9'
], 75, self.get_example_iter())
self.assertEqual(75, num_examples)
if __name__ == '__main__':
googletest.main()
<s> # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: feature_statistics.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='feature_statistics.proto',
package='featureStatistics',
syntax='proto3',
serialized_pb=_b('\\n\\x18\\x66\\x65\\x61ture_statistics.proto\\x12\\x11\\x66\\x65\\x61tureStatistics\\"]\\n\\x1c\\x44\\x61tasetFeatureStatisticsList\\x12=\\n\\x08\\x64\\x61tasets\\x18\\x01 \\x03(\\x0b\\x32+.featureStatistics.DatasetFeatureStatistics\\"\\x99\\x01\\n\\x18\\x44\\x61tasetFeatureStatistics\\x12\\x0c\\n\\x04name\\x18\\x01 \\x01(\\t\\x12\\x14\\n\\x0cnum_examples\\x18\\x02 \\x01(\\x04\\x12\\x1d\\n\\x15weighted_num_examples\\x18\\x04 \\x01(\\x01\\x12:\\n\\x08\\x66\\x65\\x61tures\\x18\\x03 \\x03(\\x0b\\x32(.featureStatistics.FeatureNameStatistics\\"\\x8b\\x03\\n\\x15\\x46\\x65\\x61tureNameStatistics\\x12\\x0c\\n\\x04name\\x18\\x01 \\x01(\\t\\x12;\\n\\x04type\\x18\\x02 \\x01(\\x0e\\x32-.featureStatistics.FeatureNameStatistics.Type\\x12\\x39\\n\\tnum_stats\\x18\\x03 \\x01(\\x0b\\x32$.featureStatistics.NumericStatisticsH\\x00\\x12;\\n\\x0cstring_stats\\x18\\x04 \\x01(\\x0b\\x32#.featureStatistics.StringStatisticsH\\x00\\x12\\x39\\n\\x0b\\x62ytes_stats\\x18\\x05 \\x01(\\x0b\\x32\\".featureStatistics.BytesStatisticsH\\x00\\x12\\x38\\n\\x0c\\x63ustom_stats\\x18\\x06 \\x03(\\x0b\\x32\\".featureStatistics.CustomStatistic\\"1\\n\\x04Type\\x12\\x07\\n\\x03INT\\x10\\x00\\x12\\t\\n\\x05\\x46LOAT\\x10\\x01\\x12\\n\\n\\x06STRING\\x10\\x02\\x12\\t\\n\\x05\\x42YTES\\x10\\x03\\x42\\x07\\n\\x05stats\\"x\\n\\x18WeightedCommonStatistics\\x12\\x17\\n\\x0fnum_non_missing\\x18\\x01 \\x01(\\x01\\x12\\x13\\n\\x0bnum_missing\\x18\\x02 \\x01(\\x01\\x12\\x16\\n\\x0e\\x61vg_num_values\\x18\\x03 \\x01(\\x01\\x12\\x16\\n\\x0etot_num_values\\x18\\x04 \\x01(\\x01\\"w\\n\\x0f\\x43ustomStatistic\\x12\\x0c\\n\\x04name\\x18\\x01 \\x01(\\t\\x12\\r\\n\\x03num\\x18\\x02 \\x01(\\x01H\\x00\\x12\\r\\n\\x03str\\x18\\x03 \\x01(\\tH\\x00\\x12\\x31\\n\\thistogram\\x18\\x04 \\x01(\\x0b\\x32\\x1c.featureStatistics.HistogramH\\x00\\x42\\x05\\n\\x03val\\"\\xaa\\x02\\n\\x11NumericStatistics\\x12\\x39\\n\\x0c\\x63ommon_stats\\x18\\x01 \\x01(\\x0b\\x32#.featureStatistics.CommonStatistics\\x12\\x0c\\n\\x04mean\\x18\\x02 \\x01(\\x01\\x12\\x0f\\n\\x07std_dev\\x18\\x03 \\x01(\\x01\\x12\\x11\\n\\tnum_zeros\\x18\\x04 \\x01(\\x04\\x12\\x0b\\n\\x03min\\x18\\x05 \\x01(\\x01\\x12\\x0e\\n\\x06median\\x18\\x06 \\x01(\\x01\\x12\\x0b\\n\\x03max\\x18\\x07 \\x01(\\x01\\x12\\x30\\n\\nhistograms\\x18\\x08 \\x03(\\x0b\\x32\\x1c.featureStatistics.Histogram\\x12L\\n\\x16weighted_numeric_stats\\x18\\t \\x01(\\x0b\\x32,.featureStatistics.WeightedNumericStatistics\\"\\x8c\\x03\\n\\x10StringStatistics\\x12\\x39\\n\\x0c\\x63ommon_stats\\x18\\x01 \\x01(\\x0b\\x32#.featureStatistics.CommonStatistics\\x12\\x0e\\n\\x06unique\\x18\\x02 \\x01(\\x04\\x12\\x44\\n\\ntop_values | ||
\\x18\\x03 \\x03(\\x0b\\x32\\x30.featureStatistics.StringStatistics.FreqAndValue\\x12\\x12\\n\\navg_length\\x18\\x04 \\x01(\\x02\\x12\\x38\\n\\x0erank_histogram\\x18\\x05 \\x01(\\x0b\\x32 .featureStatistics.RankHistogram\\x12J\\n\\x15weighted_string_stats\\x18\\x06 \\x01(\\x0b\\x32+.featureStatistics.WeightedStringStatistics\\x1aM\\n\\x0c\\x46reqAndValue\\x12\\x1b\\n\\x0f\\x64\\x65precated_freq\\x18\\x01 \\x01(\\x04\\x42\\x02\\x18\\x01\\x12\\r\\n\\x05value\\x18\\x02 \\x01(\\t\\x12\\x11\\n\\tfrequency\\x18\\x03 \\x01(\\x01\\"|\\n\\x19WeightedNumericStatistics\\x12\\x0c\\n\\x04mean\\x18\\x01 \\x01(\\x01\\x12\\x0f\\n\\x07std_dev\\x18\\x02 \\x01(\\x01\\x12\\x0e\\n\\x06median\\x18\\x03 \\x01(\\x01\\x12\\x30\\n\\nhistograms\\x18\\x04 \\x03(\\x0b\\x32\\x1c.featureStatistics.Histogram\\"\\x9a\\x01\\n\\x18WeightedStringStatistics\\x12\\x44\\n\\ntop_values\\x18\\x01 \\x03(\\x0b\\x32\\x30.featureStatistics.StringStatistics.FreqAndValue\\x12\\x38\\n\\x0erank_histogram\\x18\\x02 \\x01(\\x0b\\x32 .featureStatistics.RankHistogram\\"\\xa1\\x01\\n\\x0f\\x42ytesStatistics\\x12\\x39\\n\\x0c\\x63ommon_stats\\x18\\x01 \\x01(\\x0b\\x32#.featureStatistics.CommonStatistics\\x12\\x0e\\n\\x06unique\\x18\\x02 \\x01(\\x04\\x12\\x15\\n\\ravg_num_bytes\\x18\\x03 \\x01(\\x02\\x12\\x15\\n\\rmin_num_bytes\\x18\\x04 \\x01(\\x02\\x12\\x15\\n\\rmax_num_bytes\\x18\\x05 \\x01(\\x02\\"\\xed\\x02\\n\\x10\\x43ommonStatistics\\x12\\x17\\n\\x0fnum_non_missing\\x18\\x01 \\x01(\\x04\\x12\\x13\\n\\x0bnum_missing\\x18\\x02 \\x01(\\x04\\x12\\x16\\n\\x0emin_num_values\\x18\\x03 \\x01(\\x04\\x12\\x16\\n\\x0emax_num_values\\x18\\x04 \\x01(\\x04\\x12\\x16\\n\\x0e\\x61vg_num_values\\x18\\x05 \\x01(\\x02\\x12\\x16\\n\\x0etot_num_values\\x18\\x08 \\x01(\\x04\\x12:\\n\\x14num_values_histogram\\x18\\x06 \\x01(\\x0b\\x32\\x1c.featureStatistics.Histogram\\x12J\\n\\x15weighted_common_stats\\x18\\x07 \\x01(\\x0b\\x32+.featureStatistics.WeightedCommonStatistics\\x12\\x43\\n\\x1d\\x66\\x65\\x61ture_list_length_histogram\\x18\\t \\x01(\\x0b\\x32\\x1c.featureStatistics.Histogram\\"\\xc4\\x02\\n\\tHistogram\\x12\\x0f\\n\\x07num_nan\\x18\\x01 \\x01(\\x04\\x12\\x15\\n\\rnum_undefined\\x18\\x02 \\x01(\\x04\\x12\\x34\\n\\x07\\x62uckets\\x18\\x03 \\x03(\\x0b\\x32#.featureStatistics.Histogram.Bucket\\x12\\x38\\n\\x04type\\x18\\x04 \\x01(\\x0e\\x32*.featureStatistics.Histogram.HistogramType\\x12\\x0c\\n\\x04name\\x18\\x05 \\x01(\\t\\x1a\\x63\\n\\x06\\x42ucket\\x12\\x11\\n\\tlow_value\\x18\\x01 \\x01(\\x01\\x12\\x12\\n\\nhigh_value\\x18\\x02 \\x01(\\x01\\x12\\x1c\\n\\x10\\x64\\x65precated_count\\x18\\x03 \\x01(\\x04\\x42\\x02\\x18\\x01\\x12\\x14\\n\\x0csample_count\\x18\\x04 \\x01(\\x01\\",\\n\\rHistogramType\\x12\\x0c\\n\\x08STANDARD\\x10\\x00\\x12\\r\\n\\tQUANTILES\\x10\\x01\\"\\xc9\\x01\\n\\rRankHistogram\\x12\\x38\\n\\x07\\x62uckets\\x18\\x01 \\x03(\\x0b\\x32\\'.featureStatistics.RankHistogram.Bucket\\x12\\x0c\\n\\x04name\\x18\\x02 \\x01(\\t\\x1ap\\n\\x06\\x42ucket\\x12\\x10\\n\\x08low_rank\\x18\\x01 \\x01(\\x04\\x12\\x11\\n\\thigh_rank\\x18\\x02 \\x01(\\x04\\x12\\x1c\\n\\x10\\x64\\x65precated_count\\x18\\x03 \\x01(\\x04\\x42\\x02\\x18\\x01\\x12\\r\\n\\x05label\\x18\\x04 \\x01(\\t\\x12\\x14\\n\\x0csample_count\\x18\\x05 \\x01(\\x01\\x62\\x06proto3')
)
_FEATURENAMESTATISTICS_TYPE = _descriptor.EnumDescriptor(
name='Type',
full_name='featureStatistics.FeatureNameStatistics.Type',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='INT', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='FLOAT', index=1, number=1,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='STRING', index=2, number=2,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='BYTES', index=3, number=3,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=636,
serialized_end=685,
)
_sym_db.RegisterEnumDescriptor(_FEATURENAMESTATISTICS_TYPE)
_HISTOGRAM_HISTOGRAMTYPE = _descriptor.EnumDescriptor(
name='HistogramType',
full_name='featureStatistics.Histogram.HistogramType',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='STANDARD', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='QUANTILES', index=1, number=1,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=2735,
serialized_end=2779,
)
_sym_db.RegisterEnumDescriptor(_HISTOGRAM_HISTOGRAMTYPE)
_DATASETFEATURESTATISTICSLIST = _descriptor.Descriptor(
name='DatasetFeatureStatisticsList',
full_name='featureStatistics.DatasetFeatureStatisticsList',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='datasets', full_name='featureStatistics.DatasetFeatureStatisticsList.datasets', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=47,
serialized_end=140,
)
_DATASETFEATURESTATISTICS = _descriptor.Descriptor(
name='DatasetFeatureStatistics',
full_name='featureStatistics.DatasetFeatureStatistics',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='featureStatistics.DatasetFeatureStatistics.name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='num_examples', full_name='featureStatistics.DatasetFeatureStatistics.num_examples', index=1,
number=2, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='weighted_num_examples', full_name='featureStatistics.DatasetFeatureStatistics.weighted_num_examples', index=2,
number=4, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='features', full_name='featureStatistics.DatasetFeatureStatistics.features', index=3,
number=3, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=143,
serialized_end=296,
)
_FEATURENAMESTATISTICS = _descriptor.Descriptor(
name='FeatureNameStatistics',
full_name='featureStatistics.FeatureNameStatistics',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='featureStatistics.FeatureNameStatistics.name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='type', full_name='featureStatistics.FeatureNameStatistics.type', index=1,
number=2, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='num_stats', full_name='featureStatistics.FeatureNameStatistics.num_stats', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='string_stats', full_name='featureStatistics.FeatureNameStatistics.string_stats', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='bytes_stats', full_name='featureStatistics.FeatureNameStatistics.bytes_stats', index=4,
number=5, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='custom_stats', full_name='featureStatistics.FeatureNameStatistics.custom_stats', index=5,
number=6, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope= | ||
None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_FEATURENAMESTATISTICS_TYPE,
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='stats', full_name='featureStatistics.FeatureNameStatistics.stats',
index=0, containing_type=None, fields=[]),
],
serialized_start=299,
serialized_end=694,
)
_WEIGHTEDCOMMONSTATISTICS = _descriptor.Descriptor(
name='WeightedCommonStatistics',
full_name='featureStatistics.WeightedCommonStatistics',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='num_non_missing', full_name='featureStatistics.WeightedCommonStatistics.num_non_missing', index=0,
number=1, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='num_missing', full_name='featureStatistics.WeightedCommonStatistics.num_missing', index=1,
number=2, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='avg_num_values', full_name='featureStatistics.WeightedCommonStatistics.avg_num_values', index=2,
number=3, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='tot_num_values', full_name='featureStatistics.WeightedCommonStatistics.tot_num_values', index=3,
number=4, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=696,
serialized_end=816,
)
_CUSTOMSTATISTIC = _descriptor.Descriptor(
name='CustomStatistic',
full_name='featureStatistics.CustomStatistic',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='featureStatistics.CustomStatistic.name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='num', full_name='featureStatistics.CustomStatistic.num', index=1,
number=2, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='str', full_name='featureStatistics.CustomStatistic.str', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='histogram', full_name='featureStatistics.CustomStatistic.histogram', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='val', full_name='featureStatistics.CustomStatistic.val',
index=0, containing_type=None, fields=[]),
],
serialized_start=818,
serialized_end=937,
)
_NUMERICSTATISTICS = _descriptor.Descriptor(
name='NumericStatistics',
full_name='featureStatistics.NumericStatistics',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='common_stats', full_name='featureStatistics.NumericStatistics.common_stats', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='mean', full_name='featureStatistics.NumericStatistics.mean', index=1,
number=2, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='std_dev', full_name='featureStatistics.NumericStatistics.std_dev', index=2,
number=3, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='num_zeros', full_name='featureStatistics.NumericStatistics.num_zeros', index=3,
number=4, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='min', full_name='featureStatistics.NumericStatistics.min', index=4,
number=5, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='median', full_name='featureStatistics.NumericStatistics.median', index=5,
number=6, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='max', full_name='featureStatistics.NumericStatistics.max', index=6,
number=7, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='histograms', full_name='featureStatistics.NumericStatistics.histograms', index=7,
number=8, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='weighted_numeric_stats', full_name='featureStatistics.NumericStatistics.weighted_numeric_stats', index=8,
number=9, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=940,
serialized_end=1238,
)
_STRINGSTATISTICS_FREQANDVALUE = _descriptor.Descriptor(
name='FreqAndValue',
full_name='featureStatistics.StringStatistics.FreqAndValue',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='deprecated_freq', full_name='featureStatistics.StringStatistics.FreqAndValue.deprecated_freq', index=0,
number=1, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\\030\\001'))),
_descriptor.FieldDescriptor(
name='value', full_name='featureStatistics.StringStatistics.FreqAndValue.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='frequency', full_name='featureStatistics.StringStatistics.FreqAndValue.frequency', index=2,
number=3, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1560,
serialized_end=1637,
)
_STRINGSTATISTICS = _descriptor.Descriptor(
name='StringStatistics',
full_name='featureStatistics.StringStatistics',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='common_stats', full_name='featureStatistics.StringStatistics.common_stats', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='unique', full_name='featureStatistics.StringStatistics.unique', index=1,
number=2, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='top_values', full_name='featureStatistics.StringStatistics.top_values', index=2,
number=3, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='avg_length', full_name='featureStatistics.StringStatistics.avg_length', index=3,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='rank_histogram', full_name='featureStatistics.StringStatistics.rank_histogram', index=4,
number=5, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='weighted_string_stats', full_name='featureStatistics.StringStatistics.weighted_string_stats', index=5,
number=6, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_STRINGSTATISTICS_FREQANDVALUE, ],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1241,
| ||
serialized_end=1637,
)
_WEIGHTEDNUMERICSTATISTICS = _descriptor.Descriptor(
name='WeightedNumericStatistics',
full_name='featureStatistics.WeightedNumericStatistics',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='mean', full_name='featureStatistics.WeightedNumericStatistics.mean', index=0,
number=1, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='std_dev', full_name='featureStatistics.WeightedNumericStatistics.std_dev', index=1,
number=2, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='median', full_name='featureStatistics.WeightedNumericStatistics.median', index=2,
number=3, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='histograms', full_name='featureStatistics.WeightedNumericStatistics.histograms', index=3,
number=4, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1639,
serialized_end=1763,
)
_WEIGHTEDSTRINGSTATISTICS = _descriptor.Descriptor(
name='WeightedStringStatistics',
full_name='featureStatistics.WeightedStringStatistics',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='top_values', full_name='featureStatistics.WeightedStringStatistics.top_values', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='rank_histogram', full_name='featureStatistics.WeightedStringStatistics.rank_histogram', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1766,
serialized_end=1920,
)
_BYTESSTATISTICS = _descriptor.Descriptor(
name='BytesStatistics',
full_name='featureStatistics.BytesStatistics',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='common_stats', full_name='featureStatistics.BytesStatistics.common_stats', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='unique', full_name='featureStatistics.BytesStatistics.unique', index=1,
number=2, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='avg_num_bytes', full_name='featureStatistics.BytesStatistics.avg_num_bytes', index=2,
number=3, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='min_num_bytes', full_name='featureStatistics.BytesStatistics.min_num_bytes', index=3,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='max_num_bytes', full_name='featureStatistics.BytesStatistics.max_num_bytes', index=4,
number=5, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1923,
serialized_end=2084,
)
_COMMONSTATISTICS = _descriptor.Descriptor(
name='CommonStatistics',
full_name='featureStatistics.CommonStatistics',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='num_non_missing', full_name='featureStatistics.CommonStatistics.num_non_missing', index=0,
number=1, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='num_missing', full_name='featureStatistics.CommonStatistics.num_missing', index=1,
number=2, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='min_num_values', full_name='featureStatistics.CommonStatistics.min_num_values', index=2,
number=3, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='max_num_values', full_name='featureStatistics.CommonStatistics.max_num_values', index=3,
number=4, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='avg_num_values', full_name='featureStatistics.CommonStatistics.avg_num_values', index=4,
number=5, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='tot_num_values', full_name='featureStatistics.CommonStatistics.tot_num_values', index=5,
number=8, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='num_values_histogram', full_name='featureStatistics.CommonStatistics.num_values_histogram', index=6,
number=6, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='weighted_common_stats', full_name='featureStatistics.CommonStatistics.weighted_common_stats', index=7,
number=7, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='feature_list_length_histogram', full_name='featureStatistics.CommonStatistics.feature_list_length_histogram', index=8,
number=9, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=2087,
serialized_end=2452,
)
_HISTOGRAM_BUCKET = _descriptor.Descriptor(
name='Bucket',
full_name='featureStatistics.Histogram.Bucket',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='low_value', full_name='featureStatistics.Histogram.Bucket.low_value', index=0,
number=1, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='high_value', full_name='featureStatistics.Histogram.Bucket.high_value', index=1,
number=2, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='deprecated_count', full_name='featureStatistics.Histogram.Bucket.deprecated_count', index=2,
number=3, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\\030\\001'))),
_descriptor.FieldDescriptor(
name='sample_count', full_name='featureStatistics.Histogram.Bucket.sample_count', index=3,
number=4, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=2634,
serialized_end=2733,
)
_HISTOGRAM = _descriptor.Descriptor(
name='Histogram',
full_name='featureStatistics.Histogram',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='num_nan', full_name='featureStatistics.Histogram.num_nan', index=0,
number=1, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='num_undefined', full_name='featureStatistics.Histogram.num_undefined', index=1,
number=2, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='buckets', full_name='featureStatistics.Histogram.buckets', index=2,
number=3, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
| ||
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='type', full_name='featureStatistics.Histogram.type', index=3,
number=4, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='name', full_name='featureStatistics.Histogram.name', index=4,
number=5, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_HISTOGRAM_BUCKET, ],
enum_types=[
_HISTOGRAM_HISTOGRAMTYPE,
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=2455,
serialized_end=2779,
)
_RANKHISTOGRAM_BUCKET = _descriptor.Descriptor(
name='Bucket',
full_name='featureStatistics.RankHistogram.Bucket',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='low_rank', full_name='featureStatistics.RankHistogram.Bucket.low_rank', index=0,
number=1, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='high_rank', full_name='featureStatistics.RankHistogram.Bucket.high_rank', index=1,
number=2, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='deprecated_count', full_name='featureStatistics.RankHistogram.Bucket.deprecated_count', index=2,
number=3, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\\030\\001'))),
_descriptor.FieldDescriptor(
name='label', full_name='featureStatistics.RankHistogram.Bucket.label', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='sample_count', full_name='featureStatistics.RankHistogram.Bucket.sample_count', index=4,
number=5, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=2871,
serialized_end=2983,
)
_RANKHISTOGRAM = _descriptor.Descriptor(
name='RankHistogram',
full_name='featureStatistics.RankHistogram',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='buckets', full_name='featureStatistics.RankHistogram.buckets', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='name', full_name='featureStatistics.RankHistogram.name', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_RANKHISTOGRAM_BUCKET, ],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=2782,
serialized_end=2983,
)
_DATASETFEATURESTATISTICSLIST.fields_by_name['datasets'].message_type = _DATASETFEATURESTATISTICS
_DATASETFEATURESTATISTICS.fields_by_name['features'].message_type = _FEATURENAMESTATISTICS
_FEATURENAMESTATISTICS.fields_by_name['type'].enum_type = _FEATURENAMESTATISTICS_TYPE
_FEATURENAMESTATISTICS.fields_by_name['num_stats'].message_type = _NUMERICSTATISTICS
_FEATURENAMESTATISTICS.fields_by_name['string_stats'].message_type = _STRINGSTATISTICS
_FEATURENAMESTATISTICS.fields_by_name['bytes_stats'].message_type = _BYTESSTATISTICS
_FEATURENAMESTATISTICS.fields_by_name['custom_stats'].message_type = _CUSTOMSTATISTIC
_FEATURENAMESTATISTICS_TYPE.containing_type = _FEATURENAMESTATISTICS
_FEATURENAMESTATISTICS.oneofs_by_name['stats'].fields.append(
_FEATURENAMESTATISTICS.fields_by_name['num_stats'])
_FEATURENAMESTATISTICS.fields_by_name['num_stats'].containing_oneof = _FEATURENAMESTATISTICS.oneofs_by_name['stats']
_FEATURENAMESTATISTICS.oneofs_by_name['stats'].fields.append(
_FEATURENAMESTATISTICS.fields_by_name['string_stats'])
_FEATURENAMESTATISTICS.fields_by_name['string_stats'].containing_oneof = _FEATURENAMESTATISTICS.oneofs_by_name['stats']
_FEATURENAMESTATISTICS.oneofs_by_name['stats'].fields.append(
_FEATURENAMESTATISTICS.fields_by_name['bytes_stats'])
_FEATURENAMESTATISTICS.fields_by_name['bytes_stats'].containing_oneof = _FEATURENAMESTATISTICS.oneofs_by_name['stats']
_CUSTOMSTATISTIC.fields_by_name['histogram'].message_type = _HISTOGRAM
_CUSTOMSTATISTIC.oneofs_by_name['val'].fields.append(
_CUSTOMSTATISTIC.fields_by_name['num'])
_CUSTOMSTATISTIC.fields_by_name['num'].containing_oneof = _CUSTOMSTATISTIC.oneofs_by_name['val']
_CUSTOMSTATISTIC.oneofs_by_name['val'].fields.append(
_CUSTOMSTATISTIC.fields_by_name['str'])
_CUSTOMSTATISTIC.fields_by_name['str'].containing_oneof = _CUSTOMSTATISTIC.oneofs_by_name['val']
_CUSTOMSTATISTIC.oneofs_by_name['val'].fields.append(
_CUSTOMSTATISTIC.fields_by_name['histogram'])
_CUSTOMSTATISTIC.fields_by_name['histogram'].containing_oneof = _CUSTOMSTATISTIC.oneofs_by_name['val']
_NUMERICSTATISTICS.fields_by_name['common_stats'].message_type = _COMMONSTATISTICS
_NUMERICSTATISTICS.fields_by_name['histograms'].message_type = _HISTOGRAM
_NUMERICSTATISTICS.fields_by_name['weighted_numeric_stats'].message_type = _WEIGHTEDNUMERICSTATISTICS
_STRINGSTATISTICS_FREQANDVALUE.containing_type = _STRINGSTATISTICS
_STRINGSTATISTICS.fields_by_name['common_stats'].message_type = _COMMONSTATISTICS
_STRINGSTATISTICS.fields_by_name['top_values'].message_type = _STRINGSTATISTICS_FREQANDVALUE
_STRINGSTATISTICS.fields_by_name['rank_histogram'].message_type = _RANKHISTOGRAM
_STRINGSTATISTICS.fields_by_name['weighted_string_stats'].message_type = _WEIGHTEDSTRINGSTATISTICS
_WEIGHTEDNUMERICSTATISTICS.fields_by_name['histograms'].message_type = _HISTOGRAM
_WEIGHTEDSTRINGSTATISTICS.fields_by_name['top_values'].message_type = _STRINGSTATISTICS_FREQANDVALUE
_WEIGHTEDSTRINGSTATISTICS.fields_by_name['rank_histogram'].message_type = _RANKHISTOGRAM
_BYTESSTATISTICS.fields_by_name['common_stats'].message_type = _COMMONSTATISTICS
_COMMONSTATISTICS.fields_by_name['num_values_histogram'].message_type = _HISTOGRAM
_COMMONSTATISTICS.fields_by_name['weighted_common_stats'].message_type = _WEIGHTEDCOMMONSTATISTICS
_COMMONSTATISTICS.fields_by_name['feature_list_length_histogram'].message_type = _HISTOGRAM
_HISTOGRAM_BUCKET.containing_type = _HISTOGRAM
_HISTOGRAM.fields_by_name['buckets'].message_type = _HISTOGRAM_BUCKET
_HISTOGRAM.fields_by_name['type'].enum_type = _HISTOGRAM_HISTOGRAMTYPE
_HISTOGRAM_HISTOGRAMTYPE.containing_type = _HISTOGRAM
_RANKHISTOGRAM_BUCKET.containing_type = _RANKHISTOGRAM
_RANKHISTOGRAM.fields_by_name['buckets'].message_type = _RANKHISTOGRAM_BUCKET
DESCRIPTOR.message_types_by_name['DatasetFeatureStatisticsList'] = _DATASETFEATURESTATISTICSLIST
DESCRIPTOR.message_types_by_name['DatasetFeatureStatistics'] = _DATASETFEATURESTATISTICS
DESCRIPTOR.message_types_by_name['FeatureNameStatistics'] = _FEATURENAMESTATISTICS
DESCRIPTOR.message_types_by_name['WeightedCommonStatistics'] = _WEIGHTEDCOMMONSTATISTICS
DESCRIPTOR.message_types_by_name['CustomStatistic'] = _CUSTOMSTATISTIC
DESCRIPTOR.message_types_by_name['NumericStatistics'] = _NUMERICSTATISTICS
DESCRIPTOR.message_types_by_name['StringStatistics'] = _STRINGSTATISTICS
DESCRIPTOR.message_types_by_name['WeightedNumericStatistics'] = _WEIGHTEDNUMERICSTATISTICS
DESCRIPTOR.message_types_by_name['WeightedStringStatistics'] = _WEIGHTEDSTRINGSTATISTICS
DESCRIPTOR.message_types_by_name['BytesStatistics'] = _BYTESSTATISTICS
DESCRIPTOR.message_types_by_name['CommonStatistics'] = _COMMONSTATISTICS
DESCRIPTOR.message_types_by_name['Histogram'] = _HISTOGRAM
DESCRIPTOR.message_types_by_name['RankHistogram'] = _RANKHISTOGRAM
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
DatasetFeatureStatisticsList = _reflection.GeneratedProtocolMessageType('DatasetFeatureStatisticsList', (_message.Message,), dict(
DESCRIPTOR = _DATASETFEATURESTATISTICSLIST,
__module__ = 'feature_statistics_pb2'
# @@protoc_insertion_point(class_scope:featureStatistics.DatasetFeatureStatisticsList)
))
_sym_db.RegisterMessage(DatasetFeatureStatisticsList)
DatasetFeatureStatistics = _reflection.GeneratedProtocolMessageType('DatasetFeatureStatistics', (_message.Message,), dict(
DESCRIPTOR = _DATASETFEATURESTATISTICS,
__module__ = 'feature_statistics_pb2'
# @@protoc_insertion_point(class_scope:featureStatistics.DatasetFeatureStatistics)
))
_sym_db.RegisterMessage(DatasetFeatureStatistics)
FeatureNameStatistics = _reflection.GeneratedProtocolMessageType('FeatureNameStatistics', (_message.Message,), dict(
DESCRIPTOR = _FEATURENAMESTATISTICS,
__module__ = 'feature_statistics_pb2'
# @@protoc_insertion_point(class_scope:featureStatistics.FeatureNameStatistics)
))
_sym_db.RegisterMessage(FeatureNameStatistics)
WeightedCommonStatistics = _reflection.GeneratedProtocolMessageType('WeightedCommonStatistics', (_message.Message,), dict(
DESCRIPTOR = _WEIGHTEDCOMMONSTATISTICS,
__module__ = 'feature_statistics_pb2'
# @@protoc_insertion_point(class_scope:featureStatistics.WeightedCommonStatistics)
))
_sym_db.RegisterMessage(WeightedCommonStatistics)
CustomStatistic = _reflection.GeneratedProtocolMessageType('CustomStatistic', (_message.Message,), dict(
DESCRIPTOR = _CUSTOMSTATISTIC,
__module__ = 'feature_statistics_pb2'
# @@protoc_insertion_point(class_scope:featureStatistics.CustomStatistic)
))
_sym_db.RegisterMessage(CustomStatistic)
NumericStatistics = _reflection.GeneratedProtocolMessageType('NumericStatistics', (_message.Message,), dict(
DESCRIPTOR = _NUMERICSTATISTICS,
__module__ = 'feature_statistics_pb2' | ||
# @@protoc_insertion_point(class_scope:featureStatistics.NumericStatistics)
))
_sym_db.RegisterMessage(NumericStatistics)
StringStatistics = _reflection.GeneratedProtocolMessageType('StringStatistics', (_message.Message,), dict(
FreqAndValue = _reflection.GeneratedProtocolMessageType('FreqAndValue', (_message.Message,), dict(
DESCRIPTOR = _STRINGSTATISTICS_FREQANDVALUE,
__module__ = 'feature_statistics_pb2'
# @@protoc_insertion_point(class_scope:featureStatistics.StringStatistics.FreqAndValue)
))
,
DESCRIPTOR = _STRINGSTATISTICS,
__module__ = 'feature_statistics_pb2'
# @@protoc_insertion_point(class_scope:featureStatistics.StringStatistics)
))
_sym_db.RegisterMessage(StringStatistics)
_sym_db.RegisterMessage(StringStatistics.FreqAndValue)
WeightedNumericStatistics = _reflection.GeneratedProtocolMessageType('WeightedNumericStatistics', (_message.Message,), dict(
DESCRIPTOR = _WEIGHTEDNUMERICSTATISTICS,
__module__ = 'feature_statistics_pb2'
# @@protoc_insertion_point(class_scope:featureStatistics.WeightedNumericStatistics)
))
_sym_db.RegisterMessage(WeightedNumericStatistics)
WeightedStringStatistics = _reflection.GeneratedProtocolMessageType('WeightedStringStatistics', (_message.Message,), dict(
DESCRIPTOR = _WEIGHTEDSTRINGSTATISTICS,
__module__ = 'feature_statistics_pb2'
# @@protoc_insertion_point(class_scope:featureStatistics.WeightedStringStatistics)
))
_sym_db.RegisterMessage(WeightedStringStatistics)
BytesStatistics = _reflection.GeneratedProtocolMessageType('BytesStatistics', (_message.Message,), dict(
DESCRIPTOR = _BYTESSTATISTICS,
__module__ = 'feature_statistics_pb2'
# @@protoc_insertion_point(class_scope:featureStatistics.BytesStatistics)
))
_sym_db.RegisterMessage(BytesStatistics)
CommonStatistics = _reflection.GeneratedProtocolMessageType('CommonStatistics', (_message.Message,), dict(
DESCRIPTOR = _COMMONSTATISTICS,
__module__ = 'feature_statistics_pb2'
# @@protoc_insertion_point(class_scope:featureStatistics.CommonStatistics)
))
_sym_db.RegisterMessage(CommonStatistics)
Histogram = _reflection.GeneratedProtocolMessageType('Histogram', (_message.Message,), dict(
Bucket = _reflection.GeneratedProtocolMessageType('Bucket', (_message.Message,), dict(
DESCRIPTOR = _HISTOGRAM_BUCKET,
__module__ = 'feature_statistics_pb2'
# @@protoc_insertion_point(class_scope:featureStatistics.Histogram.Bucket)
))
,
DESCRIPTOR = _HISTOGRAM,
__module__ = 'feature_statistics_pb2'
# @@protoc_insertion_point(class_scope:featureStatistics.Histogram)
))
_sym_db.RegisterMessage(Histogram)
_sym_db.RegisterMessage(Histogram.Bucket)
RankHistogram = _reflection.GeneratedProtocolMessageType('RankHistogram', (_message.Message,), dict(
Bucket = _reflection.GeneratedProtocolMessageType('Bucket', (_message.Message,), dict(
DESCRIPTOR = _RANKHISTOGRAM_BUCKET,
__module__ = 'feature_statistics_pb2'
# @@protoc_insertion_point(class_scope:featureStatistics.RankHistogram.Bucket)
))
,
DESCRIPTOR = _RANKHISTOGRAM,
__module__ = 'feature_statistics_pb2'
# @@protoc_insertion_point(class_scope:featureStatistics.RankHistogram)
))
_sym_db.RegisterMessage(RankHistogram)
_sym_db.RegisterMessage(RankHistogram.Bucket)
_STRINGSTATISTICS_FREQANDVALUE.fields_by_name['deprecated_freq'].has_options = True
_STRINGSTATISTICS_FREQANDVALUE.fields_by_name['deprecated_freq']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\\030\\001'))
_HISTOGRAM_BUCKET.fields_by_name['deprecated_count'].has_options = True
_HISTOGRAM_BUCKET.fields_by_name['deprecated_count']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\\030\\001'))
_RANKHISTOGRAM_BUCKET.fields_by_name['deprecated_count'].has_options = True
_RANKHISTOGRAM_BUCKET.fields_by_name['deprecated_count']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\\030\\001'))
# @@protoc_insertion_point(module_scope)
<s> # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
<s> # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Class for generating the feature_statistics proto.
The proto is used as input for the Overview visualization.
"""
from facets_overview.base_feature_statistics_generator import BaseFeatureStatisticsGenerator
import facets_overview.feature_statistics_pb2 as fs
class FeatureStatisticsGenerator(BaseFeatureStatisticsGenerator):
"""Generator of stats proto from TF data."""
def __init__(self):
BaseFeatureStatisticsGenerator.__init__(self, fs.FeatureNameStatistics,
fs.DatasetFeatureStatisticsList,
fs.Histogram)
<s> # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Base class for generating the feature_statistics proto from generic data.
The proto is used as input for the Overview visualization.
"""
import numpy as np
import pandas as pd
import sys
class BaseGenericFeatureStatisticsGenerator(object):
"""Base class for generator of stats proto from generic data."""
def __init__(self, fs_proto, datasets_proto, histogram_proto):
self.fs_proto = fs_proto
self.datasets_proto = datasets_proto
self.histogram_proto = histogram_proto
def ProtoFromDataFrames(self, dataframes,
histogram_categorical_levels_count=None):
"""Creates a feature statistics proto from a set of pandas dataframes.
Args:
dataframes: A list of dicts describing tables for each dataset for the
proto. Each entry contains a 'table' field of the dataframe of the
data
and a 'name' field to identify the dataset in the proto.
histogram_categorical_levels_count: int, controls the maximum number of
levels to display in histograms for categorical features.
Useful to prevent codes/IDs features from bloating the stats object.
Defaults to None.
Returns:
The feature statistics proto for the provided tables.
"""
datasets = []
for dataframe in dataframes:
table = dataframe['table']
table_entries = {}
for col in table:
table_entries[col] = self.NdarrayToEntry(table[col])
datasets.append({
'entries': table_entries,
'size': len(table),
'name': dataframe['name']
})
return self.GetDatasetsProto(
datasets,
histogram_categorical_levels_count=histogram_categorical_levels_count)
def DtypeToType(self, dtype):
"""Converts a Numpy dtype to the FeatureNameStatistics.Type proto enum."""
if dtype.char in np.typecodes['AllFloat']:
return self.fs_proto.FLOAT
elif (dtype.char in np.typecodes['AllInteger'] or dtype == bool or
np.issubdtype(dtype, np.datetime64) or
np.issubdtype(dtype, np.timedelta64)):
return self.fs_proto.INT
else:
return self.fs_proto.STRING
def DtypeToNumberConverter(self, dtype):
"""Converts a Numpy dtype to a converter method if applicable.
The converter method takes in a numpy array of objects of the provided
dtype
and returns a numpy array of the numbers backing that object for
statistical
analysis. Returns None if no converter is necessary.
Args:
dtype: The numpy dtype to make a converter for.
Returns:
The converter method or None.
"""
if np.issubdtype(dtype, np.datetime64):
def DatetimesToNumbers(dt_list):
return np.array([pd.Timestamp(dt).value for dt in dt_list])
return DatetimesToNumbers
elif np.issubdtype(dtype, np.timedelta64):
def TimedetlasToNumbers(td_list):
return np.array([pd.Timedelta(td).value for td in td_list])
return TimedetlasToNumbers
else:
return None
def NdarrayToEntry(self, x):
"""Converts an ndarray to the Entry format."""
row_counts = []
for row in x:
try:
rc = np.count_nonzero(~np.isnan(row))
if rc != 0:
row_counts.append(rc)
except TypeError:
try:
row_counts.append(row.size)
except AttributeError:
row_counts.append(1)
data_type = self.DtypeToType(x.dtype)
converter = self.DtypeToNumberConverter(x.dtype)
flattened = x.ravel()
orig_size = len(flattened)
# Remove all None and nan values and count how many were removed.
flattened = flattened[flattened != np.array(None)]
if converter:
flattened = converter(flattened)
if data_type == self.fs_proto.STRING:
flattened_temp = []
for x in flattened:
try:
if str(x) != 'nan':
flattened_temp.append(x)
except UnicodeEncodeError:
if x.encode('utf-8') != 'nan':
flattened_temp.append(x)
flattened = flattened_temp
else:
flattened = flattened[~np.isnan(flattened)].tolist()
missing = orig_size - len(flattened)
return {
'vals': flattened,
'counts': row_counts,
'missing': missing,
'type': data_type
}
def GetDatasetsProto(self, datasets, features=None,
histogram_categorical_levels_count=None):
"""Generates the feature stats proto from dictionaries of feature values.
Args:
datasets: An array of dictionaries, one per dataset, each one containing:
- 'entries': The dictionary of features in the dataset from the parsed
examples.
- 'size': The number of examples parsed for the dataset.
- 'name': The name of the dataset.
features: A list of strings that is a whitelist of feature names to create
feature statistics for. If set to None then all features in the
dataset
are analyzed. Defaults to None.
histogram_categorical_levels_count: int, controls the maximum number of
levels to display in histograms for categorical features.
Useful to prevent codes/IDs features from bloating the stats object.
Defaults to None.
Returns:
The feature statistics proto for the provided datasets.
"""
features_seen = set()
whitelist_features = set(features) if features else None
all_datasets = self.datasets_proto()
# TODO(jwexler): Add ability to generate weighted feature stats
# if there is a specified weight feature in the dataset.
# Initialize each dataset
for dataset in datasets:
all_datasets.datasets.add(
name=dataset['name'], num_examples=dataset['size'])
# This outer loop ensures that for each feature seen in any of the provided
# datasets, we check the feature once against all datasets.
for outer_dataset in datasets:
for key, value in outer_dataset['entries'].items():
# If we have a feature whitelist and this feature is not in the
# whitelist then do not process it.
# If we have processed this feature already, no need to do it again.
if ((whitelist_features and key not in whitelist_features) or
key in features_seen):
continue
features_seen.add(key)
# Default to type int if no type is found, so that the fact that all
# values are missing from this feature can be displayed.
feature_type = value['type'] if 'type' in value else self.fs_proto.INT
# Process the found feature for each dataset.
for j, dataset in enumerate(datasets):
feat = all_datasets.datasets[j].features.add(
type=feature_type, name=key.encode('utf-8'))
value = dataset['entries'].get(key)
has_data = value is not None and (value['vals'].size != 0
if isinstance(
value['vals'], np.ndarray) else
value['vals'])
commonstats = None
# For numeric features, calculate numeric statistics.
if feat.type in (self.fs_proto | ||
.INT, self.fs_proto.FLOAT):
featstats = feat.num_stats
commonstats = featstats.common_stats
if has_data:
nums = value['vals']
featstats.std_dev = np.std(nums).item()
featstats.mean = np.mean(nums).item()
featstats.min = np.min(nums).item()
featstats.max = np.max(nums).item()
featstats.median = np.median(nums).item()
featstats.num_zeros = len(nums) - np.count_nonzero(nums)
nums = np.array(nums)
num_nan = len(nums[np.isnan(nums)])
num_posinf = len(nums[np.isposinf(nums)])
num_neginf = len(nums[np.isneginf(nums)])
# Remove all non-finite (including NaN) values from the numeric
# values in order to calculate histogram buckets/counts. The
# inf values will be added back to the first and last buckets.
nums = nums[np.isfinite(nums)]
counts, buckets = np.histogram(nums)
hist = featstats.histograms.add()
hist.type = self.histogram_proto.STANDARD
hist.num_nan = num_nan
for bucket_count in range(len(counts)):
bucket = hist.buckets.add(
low_value=buckets[bucket_count],
high_value=buckets[bucket_count + 1],
sample_count=counts[bucket_count].item())
# Add any negative or positive infinities to the first and last
# buckets in the histogram.
if bucket_count == 0 and num_neginf > 0:
bucket.low_value = float('-inf')
bucket.sample_count += num_neginf
elif bucket_count == len(counts) - 1 and num_posinf > 0:
bucket.high_value = float('inf')
bucket.sample_count += num_posinf
if not hist.buckets:
if num_neginf:
hist.buckets.add(
low_value=float('-inf'),
high_value=float('-inf'),
sample_count=num_neginf)
if num_posinf:
hist.buckets.add(
low_value=float('inf'),
high_value=float('inf'),
sample_count=num_posinf)
self._PopulateQuantilesHistogram(featstats.histograms.add(),nums.tolist())
elif feat.type == self.fs_proto.STRING:
featstats = feat.string_stats
commonstats = featstats.common_stats
if has_data:
strs = []
for item in value['vals']:
strs.append(item if hasattr(item, '__len__') else
item.encode('utf-8') if hasattr(item, 'encode') else str(
item))
featstats.avg_length = np.mean(np.vectorize(len)(strs))
vals, counts = np.unique(strs, return_counts=True)
featstats.unique = len(vals)
sorted_vals = sorted(zip(counts, vals), reverse=True)
sorted_vals = sorted_vals[:histogram_categorical_levels_count]
for val_index, val in enumerate(sorted_vals):
try:
if (sys.version_info.major < 3 or
isinstance(val[1], (bytes, bytearray))):
printable_val = val[1].decode('UTF-8', 'strict')
else:
printable_val = val[1]
except (UnicodeDecodeError, UnicodeEncodeError):
printable_val = '__BYTES_VALUE__'
bucket = featstats.rank_histogram.buckets.add(
low_rank=val_index,
high_rank=val_index,
sample_count=(val[0].item()),
label=printable_val)
if val_index < 2:
featstats.top_values.add(
value=bucket.label, frequency=bucket.sample_count)
# Add the common stats regardless of the feature type.
if has_data:
commonstats.num_missing = value['missing']
commonstats.num_non_missing = (all_datasets.datasets[j].num_examples
- featstats.common_stats.num_missing)
commonstats.min_num_values = int(np.min(value['counts']).astype(int))
commonstats.max_num_values = int(np.max(value['counts']).astype(int))
commonstats.avg_num_values = np.mean(value['counts'])
if 'feat_lens' in value and value['feat_lens']:
self._PopulateQuantilesHistogram(
commonstats.feature_list_length_histogram, value['feat_lens'])
self._PopulateQuantilesHistogram(commonstats.num_values_histogram,
value['counts'])
else:
commonstats.num_non_missing = 0
commonstats.num_missing = all_datasets.datasets[j].num_examples
return all_datasets
def _PopulateQuantilesHistogram(self, hist, nums):
"""Fills in the histogram with quantile information from the provided array.
Args:
hist: A Histogram proto message to fill in.
nums: A list of numbers to create a quantiles histogram from.
"""
if not nums:
return
num_quantile_buckets = 10
quantiles_to_get = [
x * 100 / num_quantile_buckets for x in range(num_quantile_buckets + 1)
]
try:
quantiles = np.percentile(nums, quantiles_to_get)
except:
quantiles = [0.0]
hist.type = self.histogram_proto.QUANTILES
quantiles_sample_count = float(len(nums)) / num_quantile_buckets
for low, high in zip(quantiles, quantiles[1:]):
hist.buckets.add(
low_value=low, high_value=high, sample_count=quantiles_sample_count)
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import pandas as pd
import numpy as np
import sys
import math
import markov_clustering as mc
import os
import networkx as nx
import logging
import json
## How far you'd like your random-walkers to go (bigger number -> more walking)
EXPANSION_POWER = 2
## How tightly clustered you'd like your final picture to be (bigger number -> more clusters)
INFLATION_POWER = 2
## If you can manage 100 iterations then do so - otherwise, check you've hit a stable end-point.
ITERATION_COUNT = 100
def normalize(matrix):
return matrix/np.sum(matrix, axis=0)
def expand(matrix, power):
return np.linalg.matrix_power(matrix, power)
def inflate(matrix, power):
for entry in np.nditer(matrix, op_flags=['readwrite']):
entry[...] = math.pow(entry, power)
return matrix
class pattern:
def __init__(self,modelFeatures,targetFeature):
self.modelFeatures = modelFeatures.split(',')
self.targetFeature = targetFeature
self.log = logging.getLogger('eion')
def training(self,df,outputLocation):
df["code"] = df[self.targetFeature].astype("category")
df['code'] = df.code.cat.codes
df2 = df[[self.targetFeature,'code']]
df2 = df2.drop_duplicates()
code_book = df2.to_dict('records')
size = len(code_book)
if self.targetFeature in self.modelFeatures:
self.modelFeatures.remove(self.targetFeature)
df['prev_code'] = df.groupby(self.modelFeatures)['code'].shift()
df['prev_activity'] = df.groupby(self.modelFeatures)[self.targetFeature].shift()
print(self.modelFeatures)
df = df.dropna(axis=0, subset=['prev_code'])
df['prev_code'] = df['prev_code'].astype('int32')
matrix = np.zeros((size, size),float)
np.set_printoptions(suppress=True)
for index, row in df.iterrows():
matrix[int(row['prev_code'])][int(row['code'])] += 1
np.fill_diagonal(matrix, 1)
matrix = normalize(matrix)
pmatrix = matrix
i = 0
records = []
for row in matrix:
j = 0
for val in row:
for event in code_book:
if event['code'] == i:
page = event[self.targetFeature]
if event['code'] == j:
nextpage = event[self.targetFeature]
record = {}
record['State'] = page
record['NextState'] = nextpage
record['Probability'] = round(val,2)
records.append(record)
j = j+1
i = i+1
df_probability = pd.DataFrame(records)
self.log.info('Status:- |... StateTransition Probability Matrix')
for _ in range(ITERATION_COUNT):
matrix = normalize(inflate(expand(matrix, EXPANSION_POWER), INFLATION_POWER))
result = mc.run_mcl(matrix) # run MCL with default parameters
c = 0
clusters = mc.get_clusters(matrix) # get clusters
self.log.info('Status:- |... StateTransition Algorithm applied: MarkovClustering')
clusterrecords = []
for cluster in clusters:
clusterid = c
clusterlist = ''
for pageid in cluster:
for event in code_book:
if event['code'] == pageid:
page = event[self.targetFeature]
if clusterlist != '':
clusterlist = clusterlist+','
clusterlist = clusterlist+page
record = {}
record['clusterid'] = c
record['clusterlist'] = clusterlist
clusterrecords.append(record)
c = c+1
df_cluster = pd.DataFrame(clusterrecords)
probabilityoutputfile = os.path.join(outputLocation, 'stateTransitionProbability.csv')
self.log.info('-------> State Transition Probability Matrix:' + probabilityoutputfile)
df_probability.to_csv(probabilityoutputfile,index=False)
clusteringoutputfile = os.path.join(outputLocation, 'stateClustering.csv')
self.log.info('-------> State Transition Probability Grouping:' + clusteringoutputfile)
df_cluster.to_csv(clusteringoutputfile,index=False)
datadetailsfile = os.path.join(outputLocation, 'datadetails.json')
dataanalytics = {}
dataanalytics['activity'] = self.targetFeature
dataanalytics['sessionid'] = self.modelFeatures[0]
updatedConfig = json.dumps(dataanalytics)
with open(datadetailsfile, "w") as fpWrite:
fpWrite.write(updatedConfig)
fpWrite.close()
evaulatemodel = '{"Model":"MarkovClustering","Score":0}'
return(evaulatemodel,probabilityoutputfile,clusteringoutputfile)
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import warnings
warnings.filterwarnings("ignore")
import json
import os
import sys
import pandas as pd
from pandas import json_normalize
#from selector import selector
#from inputprofiler import inputprofiler
#from trained_model import trained_model
#from output_format import output_format
from autogluon.tabular import TabularDataset, TabularPredictor
from autogluon.core.utils.utils import setup_outputdir
from autogluon.core.utils.loaders import load_pkl
from autogluon.core.utils.savers import save_pkl
import os.path
class MultilabelPredictor():
""" Tabular Predictor for predicting multiple columns in table.
Creates multiple TabularPredictor objects which you can also use individually.
You can access the TabularPredictor for a particular label via: `multilabel_predictor.get_predictor(label_i)`
Parameters
----------
labels : List[str]
The ith element of this list is the column (i.e. `label`) predicted by the ith TabularPredictor stored in this object.
path : str
Path to directory where models and intermediate outputs should be saved.
If unspecified, a time-stamped folder called "AutogluonModels/ag-[TIMESTAMP]" will be created in the working directory to store all models.
Note: To call `fit()` twice and save all results of each fit, you must specify different `path` locations or don't specify `path` at all.
Otherwise files from first `fit()` will be overwritten by second `fit()`.
Caution: when predicting many labels, this directory may grow large as it needs to store many TabularPredictors.
problem_types : List[str]
The ith element is the `problem_type` for the | ||
ith TabularPredictor stored in this object.
eval_metrics : List[str]
The ith element is the `eval_metric` for the ith TabularPredictor stored in this object.
consider_labels_correlation : bool
Whether the predictions of multiple labels should account for label correlations or predict each label independently of the others.
If True, the ordering of `labels` may affect resulting accuracy as each label is predicted conditional on the previous labels appearing earlier in this list (i.e. in an auto-regressive fashion).
Set to False if during inference you may want to individually use just the ith TabularPredictor without predicting all the other labels.
kwargs :
Arguments passed into the initialization of each TabularPredictor.
"""
multi_predictor_file = 'multilabel_predictor.pkl'
def __init__(self, labels, path, problem_types=None, eval_metrics=None, consider_labels_correlation=True, **kwargs):
if len(labels) < 2:
raise ValueError("MultilabelPredictor is only intended for predicting MULTIPLE labels (columns), use TabularPredictor for predicting one label (column).")
self.path = setup_outputdir(path, warn_if_exist=False)
self.labels = labels
self.consider_labels_correlation = consider_labels_correlation
self.predictors = {} # key = label, value = TabularPredictor or str path to the TabularPredictor for this label
if eval_metrics is None:
self.eval_metrics = {}
else:
self.eval_metrics = {labels[i] : eval_metrics[i] for i in range(len(labels))}
problem_type = None
eval_metric = None
for i in range(len(labels)):
label = labels[i]
path_i = self.path + "Predictor_" + label
if problem_types is not None:
problem_type = problem_types[i]
if eval_metrics is not None:
eval_metric = self.eval_metrics[i]
self.predictors[label] = TabularPredictor(label=label, problem_type=problem_type, eval_metric=eval_metric, path=path_i, **kwargs)
def fit(self, train_data, tuning_data=None, **kwargs):
""" Fits a separate TabularPredictor to predict each of the labels.
Parameters
----------
train_data, tuning_data : str or autogluon.tabular.TabularDataset or pd.DataFrame
See documentation for `TabularPredictor.fit()`.
kwargs :
Arguments passed into the `fit()` call for each TabularPredictor.
"""
if isinstance(train_data, str):
train_data = TabularDataset(train_data)
if tuning_data is not None and isinstance(tuning_data, str):
tuning_data = TabularDataset(tuning_data)
train_data_og = train_data.copy()
if tuning_data is not None:
tuning_data_og = tuning_data.copy()
save_metrics = len(self.eval_metrics) == 0
for i in range(len(self.labels)):
label = self.labels[i]
predictor = self.get_predictor(label)
if not self.consider_labels_correlation:
labels_to_drop = [l for l in self.labels if l!=label]
else:
labels_to_drop = [labels[j] for j in range(i+1,len(self.labels))]
train_data = train_data_og.drop(labels_to_drop, axis=1)
if tuning_data is not None:
tuning_data = tuning_data_og.drop(labels_to_drop, axis=1)
print(f"Fitting TabularPredictor for label: {label} ...")
predictor.fit(train_data=train_data, tuning_data=tuning_data, **kwargs)
self.predictors[label] = predictor.path
if save_metrics:
self.eval_metrics[label] = predictor.eval_metric
self.save()
def predict(self, data, **kwargs):
""" Returns DataFrame with label columns containing predictions for each label.
Parameters
----------
data : str or autogluon.tabular.TabularDataset or pd.DataFrame
Data to make predictions for. If label columns are present in this data, they will be ignored. See documentation for `TabularPredictor.predict()`.
kwargs :
Arguments passed into the predict() call for each TabularPredictor.
"""
return self._predict(data, as_proba=False, **kwargs)
def predict_proba(self, data, **kwargs):
""" Returns dict where each key is a label and the corresponding value is the `predict_proba()` output for just that label.
Parameters
----------
data : str or autogluon.tabular.TabularDataset or pd.DataFrame
Data to make predictions for. See documentation for `TabularPredictor.predict()` and `TabularPredictor.predict_proba()`.
kwargs :
Arguments passed into the `predict_proba()` call for each TabularPredictor (also passed into a `predict()` call).
"""
return self._predict(data, as_proba=True, **kwargs)
def evaluate(self, data, **kwargs):
""" Returns dict where each key is a label and the corresponding value is the `evaluate()` output for just that label.
Parameters
----------
data : str or autogluon.tabular.TabularDataset or pd.DataFrame
Data to evalate predictions of all labels for, must contain all labels as columns. See documentation for `TabularPredictor.evaluate()`.
kwargs :
Arguments passed into the `evaluate()` call for each TabularPredictor (also passed into the `predict()` call).
"""
data = self._get_data(data)
eval_dict = {}
for label in self.labels:
print(f"Evaluating TabularPredictor for label: {label} ...")
predictor = self.get_predictor(label)
eval_dict[label] = predictor.evaluate(data, **kwargs)
if self.consider_labels_correlation:
data[label] = predictor.predict(data, **kwargs)
return eval_dict
def save(self):
""" Save MultilabelPredictor to disk. """
for label in self.labels:
if not isinstance(self.predictors[label], str):
self.predictors[label] = self.predictors[label].path
save_pkl.save(path=self.path+self.multi_predictor_file, object=self)
print(f"MultilabelPredictor saved to disk. Load with: MultilabelPredictor.load('{self.path}')")
@classmethod
def load(cls, path):
""" Load MultilabelPredictor from disk `path` previously specified when creating this MultilabelPredictor. """
path = os.path.expanduser(path)
if path[-1] != os.path.sep:
path = path + os.path.sep
return load_pkl.load(path=path+cls.multi_predictor_file)
def get_predictor(self, label):
""" Returns TabularPredictor which is used to predict this label. """
predictor = self.predictors[label]
if isinstance(predictor, str):
return TabularPredictor.load(path=predictor)
return predictor
def _get_data(self, data):
if isinstance(data, str):
return TabularDataset(data)
return data.copy()
def _predict(self, data, as_proba=False, **kwargs):
data = self._get_data(data)
if as_proba:
predproba_dict = {}
for label in self.labels:
print(f"Predicting with TabularPredictor for label: {label} ...")
predictor = self.get_predictor(label)
if as_proba:
predproba_dict[label] = predictor.predict_proba(data, as_multiclass=True, **kwargs)
data[label] = predictor.predict(data, **kwargs)
if not as_proba:
return data[self.labels]
else:
return predproba_dict
def predict(data):
try:
if os.path.splitext(data)[1] == ".tsv":
df=pd.read_csv(data,encoding='utf-8',sep='\\t')
elif os.path.splitext(data)[1] == ".csv":
df=pd.read_csv(data,encoding='utf-8')
else:
if os.path.splitext(data)[1] == ".json":
with open(data,'r',encoding='utf-8') as f:
jsonData = json.load(f)
else:
jsonData = json.loads(data)
df = json_normalize(jsonData)
#df0 = df.copy()
#profilerobj = inputprofiler()
#df = profilerobj.apply_profiler(df)
#selectobj = selector()
#df = selectobj.apply_selector(df)
#modelobj = trained_model()
#output = modelobj.predict(df,"")
# Load the Test data for Prediction
# ----------------------------------------------------------------------------#
test_data = df#TabularDataset(data) #'testingDataset.csv'
#subsample_size = 2
# ----------------------------------------------------------------------------#
# Specify the corresponding target features to be used
# ----------------------------------------------------------------------------#
#labels = ['education-num','education','class']
configFile = os.path.join(os.path.dirname(os.path.abspath(__file__)),'etc','predictionConfig.json')
with open(configFile, 'rb') as cfile:
data = json.load(cfile)
labels = data['targetFeature']
# ----------------------------------------------------------------------------#
for x in labels:
if x in list(test_data.columns):
test_data.drop(x,axis='columns', inplace=True)
# ----------------------------------------------------------------------------#
#test_data = test_data.sample(n=subsample_size, random_state=0)
#print(test_data)
#test_data_nolab = test_data.drop(columns=labels)
#test_data_nolab.head()
test_data_nolab = test_data
# ----------------------------------------------------------------------------#
# Load the trained model from where it's stored
# ----------------------------------------------------------------------------#
model_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'ModelPath')
multi_predictor = MultilabelPredictor.load(model_path)
# ----------------------------------------------------------------------------#
# Start the prediction and perform the evaluation
# ----------------------------------------------------------------------------#
predictions = multi_predictor.predict(test_data_nolab)
for label in labels:
df[label+'_predict'] = predictions[label]
#evaluations = multi_predictor.evaluate(test_data)
#print(evaluations)
#print("Evaluated using metrics:", multi_predictor.eval_metrics)
# ----------------------------------------------------------------------------#
# ----------------------------------------------------------------------------#
#outputobj = output_format()
#output = outputobj.apply_output_format(df0,output)
outputjson = df.to_json(orient='records')
outputjson = {"status":"SUCCESS","data":json.loads(outputjson)}
output = json.dumps(outputjson)
print("predictions:",output)
return(output)
# ----------------------------------------------------------------------------#
except KeyError as e:
output = {"status":"FAIL","message":str(e).strip('"')}
print("predictions:",json.dumps(output))
return (json.dumps(output))
except Exception as e:
output = {"status":"FAIL","message":str(e).strip('"')}
print("predictions:",json.dumps(output))
return (json.dumps(output))
if __name__ == "__main__":
output = predict(sys.argv[1])
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import warnings
warnings.filterwarnings("ignore")
import json
import os
import sys
import pandas as pd
import numpy as np
from pandas import json_normalize
from autogluon.text import TextPredictor
import os.path
def predict(data):
try:
if os.path.splitext(data)[1] == ".tsv":
df=pd.read_csv(data,encoding='utf-8',sep='\\t')
elif os.path.splitext(data)[1] == ".csv":
df=pd.read_csv(data,encoding='utf-8')
else:
if os.path.splitext(data)[1] == ".json":
with open(data,'r',encoding='utf-8') as f:
jsonData = json.load(f)
else:
jsonData = json.loads(data)
df = json_normalize(jsonData)
model_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'text_prediction')
predictor = TextPredictor.load(model_path)
predictions = predictor.predict(df)
df['predict'] = predictions
outputjson = df.to_json(orient='records')
outputjson = {"status":"SUCCESS","data":json.loads(outputjson)}
output = json.dumps(outputjson)
print("predictions:",output)
return(output)
except KeyError as e:
output = {"status":"FAIL","message":str(e).strip('"')}
print("predictions:",json.dumps(output))
return (json.dumps(output))
except Exception as e:
output = {"status":"FAIL","message":str(e).strip('"')}
print("predictions:",json.dumps(output))
return (json.dumps(output))
if __name__ == "__main__":
output = predict(sys.argv[1])
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,20 | ||
23
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os.path
import time
import subprocess
import sys
from appbe.aion_config import kafka_setting
from appbe.aion_config import running_setting
from appbe import installPackage
from appbe import compute
from appbe.models import getusercasestatus
import json
import pandas as pd
from os.path import expanduser
import ntpath
import shutil
import platform
from pathlib import Path
home = expanduser("~")
if platform.system() == 'Windows':
LOG_FILE_PATH = os.path.join(home,'AppData','Local','HCLT','AION','logs')
else:
LOG_FILE_PATH = os.path.join(home,'HCLT','AION','logs')
def convert(obj):
if isinstance(obj, bool):
return str(obj).capitalize()
if isinstance(obj, (list, tuple)):
return [convert(item) for item in obj]
if isinstance(obj, dict):
return {convert(key):convert(value) for key, value in obj.items()}
return obj
def fl_command(request,Existusecases,usecasedetails):
command = request.POST.get('flsubmit')
print(command)
#kafkaSetting = kafka_setting()
ruuningSetting = running_setting()
computeinfrastructure = compute.readComputeConfig()
modelID = request.POST.get('modelID')
p = Existusecases.objects.get(id=modelID)
usecasename = p.ModelName.UsecaseName
runningStatus,pid,ip,port = installPackage.checkModelServiceRunning(usecasename)
installationStatus,modelName,modelVersion=installPackage.checkInstalledPackge(usecasename)
usecasedetail = usecasedetails.objects.get(id=p.ModelName.id)
usecase = usecasedetails.objects.all()
models = Existusecases.objects.filter(ModelName=usecasedetail,Status='SUCCESS')
for model in models:
model.scoringCreteria = 'NA'
model.score = 'NA'
model.deploymodel = 'NA'
if os.path.isdir(str(model.DeployPath)):
modelPath = os.path.join(str(model.DeployPath),'etc','output.json')
try:
with open(modelPath) as file:
outputconfig = json.load(file)
file.close()
if outputconfig['status'] == 'SUCCESS':
model.scoringCreteria = outputconfig['data']['ScoreType']
model.score = outputconfig['data']['BestScore']
model.deploymodel = outputconfig['data']['BestModel']
model.modelType = outputconfig['data']['ModelType']
model.featuresused = eval(outputconfig['data']['featuresused'])
model.targetFeature = outputconfig['data']['targetFeature']
model.modelParams = outputconfig['data']['params']
model.dataPath = os.path.join(str(model.DeployPath),'data', 'postprocesseddata.csv.gz')
model.maacsupport = 'True'
model.flserversupport = 'False'
supportedmodels = ["Logistic Regression","Neural Network","Linear Regression"]
if model.deploymodel in supportedmodels:
model.flserversupport = 'True'
else:
model.flserversupport = 'False'
supportedmodels = ["Logistic Regression",
"Naive Bayes","Decision Tree","Support Vector Machine","K Nearest Neighbors","Gradient Boosting","Random Forest","Linear Regression","Lasso","Ridge","Extreme Gradient Boosting (XGBoost)","Light Gradient Boosting (LightGBM)","Categorical Boosting (CatBoost)"]
if model.deploymodel in supportedmodels:
model.maacsupport = 'True'
else:
model.maacsupport = 'False'
supportedmodels = ["Extreme Gradient Boosting (XGBoost)"]
if model.deploymodel in supportedmodels:
model.encryptionsupport = 'True'
else:
model.encryptionsupport = 'False'
except Exception as e:
pass
flserver = os.path.join(str(p.DeployPath),'publish','FedLearning')
if command == 'startServer':
flservicefile = os.path.join(flserver,'fedServer','aionfls.py')
confilefile = os.path.join(flserver,'fedServer','config.json')
if platform.system() == 'Windows':
outputStr = subprocess.Popen([sys.executable, flservicefile,confilefile],creationflags = subprocess.CREATE_NEW_CONSOLE)
else:
outputStr = subprocess.Popen([sys.executable, flservicefile,confilefile])
Status = 'SUCCESS'
Msg = 'Federated Learning Server Started'
if command == 'saveflconfig':
#print(command)
fedserverPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','utilities','fedServer'))
shutil.rmtree(flserver, ignore_errors=True)
Path(flserver).mkdir(parents=True, exist_ok=True)
flcopypath = os.path.join(flserver,'fedServer')
shutil.copytree(fedserverPath,flcopypath)
fedserverDataPath = os.path.join(flcopypath,'data')
shutil.copy2(request.POST.get('flserver_datalocation'),fedserverDataPath)
flcon = {}
AlgorithmNames={'Logistic Regression':'LogisticRegression','Neural Network':'deeplearning','Linear Regression':'LinearRegression'}
flcon['server_IP'] = request.POST.get('flserver_ipaddress')
flcon['server_port'] = request.POST.get('flserver_port')
flcon['model_name'] = AlgorithmNames[request.POST.get('flserver_model')]
flcon['version'] = request.POST.get('flserver_Version')
flcon['model_hyperparams'] = convert(eval(request.POST.get('flserver_params')))
dataLocation = request.POST.get('flserver_datalocation')
dataPath,datafile = ntpath.split(dataLocation)
flcon['data_location'] = 'data/'+datafile
flcon['selected_feature'] = ",".join([model for model in eval(request.POST.get('flserver_trainingfeatures'))])
flcon['target_feature'] = request.POST.get('flserver_targetfeature')
flcon['problem_type'] = request.POST.get('flserver_modelType')
flcon['min_available_clients'] = request.POST.get('flserver_noofclient')
flcon['min_fit_clients'] = 2
flcon['fl_round'] = request.POST.get('flserver_trainround')
flcon['evaluation_required'] = request.POST.get('flserver_evaluation')
flcon['model_store'] = ""
flconfigfile = os.path.join(flcopypath,'config.json')
flconjson = json.dumps(flcon)
f = open(flconfigfile, "w+")
f.seek(0)
f.write(flconjson)
f.truncate()
f.close()
nouc = 0
Status = 'Success'
Msg = 'Federated Learning Server Configured'
if command =='startClient':
flconfigfile = os.path.join(str(model.DeployPath),'publish','FedLearning','fedServer','config.json')
if os.path.isfile(flconfigfile):
with open(flconfigfile) as file:
flconfig = json.load(file)
file.close()
numberofclient = flconfig['min_available_clients']
for x in range(int(numberofclient)):
flclientdirectory = os.path.join(str(model.DeployPath),'publish','FedLearning','fedClient_'+str(x+1))
flclientpath = os.path.join(str(model.DeployPath),'publish','FedLearning','fedClient_'+str(x+1),'fedClient.bat')
if platform.system() == 'Windows':
outputStr = subprocess.Popen([flclientpath],creationflags = subprocess.CREATE_NEW_CONSOLE,cwd=flclientdirectory)
else:
outputStr = subprocess.Popen([flclientpath],cwd=flclientdirectory)
Status = 'SUCCESS'
Msg = 'Federated Learning Client Started'
if command == 'generateClient':
flconfigfile = os.path.join(str(model.DeployPath),'publish','FedLearning','fedServer','config.json')
if os.path.isfile(flconfigfile):
with open(flconfigfile) as file:
flconfig = json.load(file)
file.close()
numberofclient = flconfig['min_available_clients']
trainingDataLocation = os.path.join(str(p.DeployPath),'data','postprocesseddata.csv.gz')
from utils.file_ops import read_df_compressed
status,df = read_df_compressed(trainingDataLocation,encoding='utf8')
for x in range(int(numberofclient)):
flclientpath = os.path.join(str(model.DeployPath),'publish','FedLearning','fedClient_'+str(x+1))
logPath = os.path.join(flclientpath,'logs')
modelsPath = os.path.join(flclientpath,'models')
Path(flclientpath).mkdir(parents=True, exist_ok=True)
Path(logPath).mkdir(parents=True, exist_ok=True)
Path(modelsPath).mkdir(parents=True, exist_ok=True)
flclientor = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','utilities','fedClient','aionflc.py'))
shutil.copy2(flclientor,flclientpath)
flclientor = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','utilities','fedClient','utils.py'))
shutil.copy2(flclientor,flclientpath)
flclientor = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','utilities','fedClient','dl_model.py'))
shutil.copy2(flclientor,flclientpath)
subset = df.sample(frac=0.8)
dataPath = os.path.join(flclientpath,'data')
Path(dataPath).mkdir(parents=True, exist_ok=True)
datafile = os.path.join(dataPath,'data.dat')
subset.to_csv(datafile, index=False)
flclient = {}
flclient['server_IP'] = flconfig['server_IP']
flclient['server_port'] = flconfig['server_port']
flclient['model_name'] = flconfig['model_name']
flclient['problem_type'] = flconfig['problem_type']
flclient['version'] = flconfig['version']
flclient['model_hyperparams'] = flconfig['model_hyperparams']
flclient['data_location'] = 'data\\data.dat'
flclient['selected_feature'] = flconfig['selected_feature']
flclient['target_feature'] = flconfig['target_feature']
flclient['train_size'] = 80
#flclient['deploy_location'] = flconfig['deploy_location']
flclient['num_records_per_round'] = request.POST.get('flserver_recordperround')
flclient['wait_time'] = request.POST.get('flserver_roundtime')
flclient['model_overwrite'] = request.POST.get('model_overwritelabel')
configPath = os.path.join(flclientpath,'config')
Path(configPath).mkdir(parents=True, exist_ok=True)
configFile = os.path.join(configPath,'config.json')
flconjson = json.dumps(flclient)
f = open(configFile, "w+")
f.seek(0)
f.write(flconjson)
f.truncate()
f.close()
locate_python = sys.exec_prefix
bathfilePath = os.path.join(flclientpath,'fedClient.bat')
batfilecontent='''
@ECHO OFF
GOTO weiter
:setenv
SET "Path={python_path}\\;%Path%;"
GOTO :EOF
:weiter
IF "%1" EQU "setenv" (
ECHO.
ECHO Setting environment for AION Federated Learning Client.
CALL :setenv
python %CD%\\\\aionflc.py %CD%\\config\\config.json
) ELSE (
SETLOCAL EnableDelayedExpansion
TITLE ION Federated Learning Client
PROMPT %username%@%computername%$S$P$_#$S
IF EXIST aion.config (FOR /F "delims=" %%A IN (aion.config) DO SET "%%A")
START "" /B %COMSPEC% /K "%~f0" setenv
)
'''.format(python_path=str(locate_python))
f = open(bathfilePath, "w",encoding="utf-8")
f.write(str(batfilecontent))
f.close()
Status = 'Success'
Msg = 'Federated Learning Client Code Generated'
nouc = 0
#selected_use_case,ModelVersion,ModelStatus = getusercasestatus(request)
from appbe.pages import get_usecase_page
status,context,action = get_usecase_page(request,usecasedetails,Existusecases)
context['Status'] = Status
context['Msg'] = Msg
return(context) <s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import csv
import logging
import pandas as pd
class csv_validator:
def __init__(self):
self.log = logging.getLogger('eion')
def __text_header(self, filename, threshold=0.75):
df = pd.read_csv(filename, header=None,nrows=1000)
numeric_columns = df.dtypes[df.dtypes != object]
if not len(numeric_columns):
first_row_len = df.iloc[0].str.len()
index = 0
for c in df | ||
:
if (df[c].map(len).mean() * threshold <= first_row_len[index]):
return False
index += 1
return True
return False
def validate_header(self, filename,delimiter,textqualifier,threshold=0.75):
with open(filename, 'rt',encoding='utf-8') as csvfile:
has_header = csv.Sniffer().has_header(csvfile.read(8192))
csvfile.seek(0)
if not has_header:
has_header = self.__text_header(filename, threshold)
reader = csv.reader(csvfile, delimiter=delimiter,quotechar=textqualifier)
good_csv = True
col_len = len(next(reader))
bad_lines = []
offset = 2 # +1 for first read and +1 for python index start at 0
for index, row in enumerate(reader):
if len(row) != col_len:
good_csv = False
if(index == 1 and has_header):
offset += 1
bad_lines.append(index + offset)
return has_header, good_csv, bad_lines
if __name__ == '__main__':
import sys
val = csv_validator()
print(val.validate_header(sys.argv[1]))
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
from typing import Tuple, Union, List
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import SGDClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from flwr.common.logger import log
from logging import INFO
TRUE_FALSE_MAPPING = {'True':'False','true':'false',True:False,'y':'n','Y':'N','Yes':'No','yes':'no','YES':'NO'}
XY = Tuple[np.ndarray, np.ndarray]
Dataset = Tuple[XY, XY]
LogRegParams = Union[XY, Tuple[np.ndarray]]
XYList = List[XY]
modelUsed=None
modelname=None
def setmodelName(modelselected):
try:
modelname=str(modelselected)
print("setmodelName ,given modelname: \\n",modelname)
if (modelname.lower() == 'logisticregression'):
modelUsed=LogisticRegression()
return True
elif (modelname.lower() == "naivebayes"):
modelUsed = GaussianNB()
return True
elif (modelname.lower() == "sgdclassifier"):
#from sklearn.linear_model import SGDClassifier
modelUsed=SGDClassifier()
return True
elif (modelname.lower() == "knn"):
modelUsed = KNeighborsClassifier()
return True
elif (modelname.lower() == "decisiontreeclassifier"):
modelUsed = DecisionTreeClassifier()
return True
else:
return False
except Exception as e:
log(INFO, "set fl model name fn issue: ",e)
def get_model_parameters(model:modelUsed) -> LogRegParams:
"""Returns the paramters of a sklearn LogisticRegression model."""
model_name=model.__class__.__name__
if model.fit_intercept:
params = (model.coef_, model.intercept_)
else:
params = (model.coef_,)
return params
def set_model_params(
model:modelUsed, params: LogRegParams
) -> modelUsed:
"""Sets the parameters of a sklean LogisticRegression model."""
model.coef_ = params[0]
model_name=model.__class__.__name__
try:
if model.fit_intercept:
model.intercept_ = params[1]
except Exception as e:
log(INFO, "set_model_params fn issue: ",e)
pass
return model
def set_initial_params(model,no_classes,no_features):
"""Sets initial parameters as zeros Required since model params are
uninitialized until model.fit is called.
But server asks for initial parameters from clients at launch. Refer
to sklearn.linear_model.LogisticRegression documentation for more
information.
"""
n_classes = no_classes
n_features = no_features
model.classes_ = np.array([i for i in range(n_classes)])
model.coef_ = np.zeros((n_classes, n_features))
model_name=model.__class__.__name__
try:
if model.fit_intercept:
model.intercept_ = np.zeros((n_classes,))
except Exception as e:
log(INFO, "set_initial_params fn issue: ",e)
pass
def shuffle(X: np.ndarray, y: np.ndarray) -> XY:
"""Shuffle X and y."""
rng = np.random.default_rng()
idx = rng.permutation(len(X))
return X[idx], y[idx]
def partition(X: np.ndarray, y: np.ndarray, num_partitions: int) -> XYList:
"""Split X and y into a number of partitions."""
return list(
zip(np.array_split(X, num_partitions), np.array_split(y, num_partitions))
)
def get_true_option(d, default_value=None):
if isinstance(d, dict):
for k,v in d.items():
if v in TRUE_FALSE_MAPPING.keys():
return k
return default_value
def get_true_options( d):
options = []
if isinstance(d, dict):
for k,v in d.items():
if v in TRUE_FALSE_MAPPING.keys():
options.append(k)
return options
def set_true_option(d, key=None, value='True'):
if key in d.keys():
if value in TRUE_FALSE_MAPPING.keys():
for k in d.keys():
d[ k] = TRUE_FALSE_MAPPING[ value]
d[key] = value
return d
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os
import pandas as pd
import requests
from io import StringIO
import json
import time
import shutil
import sys
from appbe import compute
from appbe.aion_config import kafka_setting
from appbe.aion_config import running_setting
from appbe.s3bucketsDB import get_s3_bucket
from appbe.gcsbucketsDB import get_gcs_bucket
from appbe.azureStorageDB import get_azureStorage
from appbe.aion_config import eda_setting
from appbe.s3bucketsDB import read_s3_bucket
from appbe.gcsbucketsDB import read_gcs_bucket
from appbe.azureStorageDB import read_azureStorage
from appbe.validatecsv import csv_validator
import time
from appbe.dataPath import LOG_LOCATION
from appbe.dataPath import DATA_FILE_PATH
from appbe.log_ut import logg
import logging
def langchain_splittext(filename):
try:
from langchain.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
loader = PyPDFLoader(filename)
pages = loader.load()
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500,chunk_overlap=50)
texts = text_splitter.split_documents(pages)
return(texts)
except Exception as e:
print(e)
def pd_lanfchain_textsplitter(datalocation,data):
try:
document=[]
for i in range(len(data)):
filename = os.path.join(datalocation,data.loc[i,"File"])
out = langchain_splittext(filename)
for doc in out:
print(doc.page_content)
document.append(doc.page_content)
my_data = pd.DataFrame({'instruction': document})
n = 1
my_data["response"] = my_data["instruction"].tolist()[n:] + my_data["instruction"].tolist()[:n]
filetimestamp = str(int(time.time()))
filename = os.path.join(DATA_FILE_PATH, 'LLMTuning_' + filetimestamp+'.csv')
my_data.to_csv(filename,index=False)
return(filename)
except Exception as e:
print(e)
def getimpfeatures(dataFile, numberoffeatures,delimiter,textqualifier):
imp_features = []
if numberoffeatures > 20:
try:
from appbe.eda import ux_eda
eda_obj = ux_eda(dataFile,delimiter,textqualifier,optimize=1)
if eda_obj.getNumericFeatureCount() >= 2:
pca_map = eda_obj.getPCATop10Features()
imp_features = pca_map.index.values.tolist()
except Exception as e:
print(e)
pass
return imp_features
def pdf2text(inpFileName):
try:
from pypdf import PdfReader
reader = PdfReader(inpFileName)
number_of_pages = len(reader.pages)
text=""
OrgTextOutputForFile=""
for i in range(number_of_pages) :
page = reader.pages[i]
text1 = page.extract_text()
text=text+text1
import nltk
tokens = nltk.sent_tokenize(text)
for sentence in tokens:
sentence=sentence.replace("\\n", " ")
if len(sentence.split()) < 4 :
continue
if len(str(sentence.split(',')).split()) < 8 :
continue
if any(chr.isdigit() for chr in sentence) :
continue
OrgTextOutputForFile= OrgTextOutputForFile+str(sentence.strip())
#print("\\n\\n\\n\\nOrgTextOutputForFile------------->\\n\\n\\n",OrgTextOutputForFile)
return (OrgTextOutputForFile)
except Exception as e:
print("Encountered exception. {0}".format(e))
def getcommonfields():
computeinfrastructure = compute.readComputeConfig()
from appbe.aion_config import settings
usecasetab = settings()
kafkaSetting = kafka_setting()
ruuningSetting = running_setting()
context = {'s3buckets':get_s3_bucket(),'gcsbuckets':get_gcs_bucket(),'computeinfrastructure':computeinfrastructure,'kafkaSetting':kafkaSetting,'ruuningSetting':ruuningSetting,'usecasetab':usecasetab,'azurestorage':get_azureStorage()}
return context
def getusercasestatus(request):
if 'UseCaseName' in request.session:
selected_use_case = request.session['UseCaseName']
else:
selected_use_case = 'Not Defined'
if 'ModelVersion' in request.session:
ModelVersion = request.session['ModelVersion']
else:
ModelVersion = 0
if 'ModelStatus' in request.session:
ModelStatus = request.session['ModelStatus']
else:
ModelStatus = 'Not Trained'
return selected_use_case,ModelVersion,ModelStatus
def delimitedsetting(delimiter='',textqualifier='',other=''):
if delimiter != '':
if delimiter.lower() == 'tab' or delimiter.lower() == '\\t':
delimiter = '\\t'
elif delimiter.lower() == 'semicolon' or delimiter.lower() == ';':
delimiter = ';'
elif delimiter.lower() == 'comma' or delimiter.lower() == ',':
delimiter = ','
elif delimiter.lower() == 'space' or delimiter.lower() == ' ':
delimiter = ' '
elif delimiter.lower() == 'other' or other.lower() != '':
if other != '':
delimiter = other
else:
delimiter = ','
elif delimiter != '':
delimiter = delimiter
else:
delimiter = ','
else:
delimiter = ','
if textqualifier == '':
textqualifier = '"'
return delimiter,textqualifier
def multipleZipExtraction(data,DATA_FILE_PATH):
from zipfile import ZipFile
try:
import glob
filetimestamp = str(int(time.time()))
extracted_data = os.path.join(DATA_FILE_PATH, 'extracted_' + filetimestamp)
os.mkdir(extracted_data)
with ZipFile(data, 'r') as zObject:
zObject.extractall(extracted_data)
csv_files = glob.glob(r'{}\\*.{}'.format(extracted_data,'csv'))
df_csv_append = pd.DataFrame()
for file in csv_files:
df = pd.read_csv(file)
df_csv_append = df_csv_append.append(df, ignore_index=True)
for f in os.listdir(extracted_data):
os.remove(os.path.join(extracted_data, f))
#os.mkdir(extracted_data)
combined_data = os.path.join(extracted_data,filetimestamp+'.csv')
df_csv_append.to_csv(combined_data)
return combined_data
except Exception as e:
if os.path.exists(extracted_data):
shutil.rmtree(extracted_data)
#print (e)
return ''
def tarFileExtraction(data,DATA_FILE_PATH):
try:
import tarfile
filetimestamp = str(int(time.time()))
extracted_data = os.path.join(DATA_FILE_PATH, 'extracted_' + filetimestamp)
os.mkdir(extracted_data)
if data.endswith('tar'):
file = tarfile.open(data)
file.extractall(extracted_data)
file.close()
for f in os.listdir(extracted_data):
if f.endswith('csv') or f.endswith('tsv'):
dataFile = os.path.join(extracted_data,f)
return dataFile
except Exception as e:
if os.path.exists(extracted_data):
shutil.rmtree(extracted_data)
print (e)
return ''
# ------ changes for the bug 1 | ||
0379 starts---------------- By Usnish ------
def checkRamAfterLoading(dataPath):
import psutil
availableRam = psutil.virtual_memory()[1]/1e9
filesize = os.path.getsize(dataPath)/1e9
return availableRam < 2*filesize
def checkRamBeforeLoading(dataPath):
import psutil
filesize = os.path.getsize(dataPath)/1e9
totalRam = psutil.virtual_memory()[0] / 1e9
if( filesize > 0.8 * totalRam):
return "File size is larger than the 80% of Total RAM."
return ""
# ------ changes for the bug 10379 ends---------------- By Usnish ------
# ---------- 10012:Decision Threshold related Changes S T A R T ----------
# This method is used to check If ->
# 80% of available RAM size is greater than ingested data (or not).
def checkRAMThreshold(dataPath):
import psutil
availableRam = psutil.virtual_memory()[1]/1e9
filesize = os.path.getsize(dataPath)/1e9
return (0.8 * availableRam) > filesize
# ---------------------- E N D ----------------------
# Text Data Labelling using LLM related changes
# --------------------------------------------------------
def ingestTextData(request, DATA_FILE_PATH):
log = logging.getLogger('log_ux')
try:
Datapath = request.FILES['DataFilePath']
from appbe.eda import ux_eda
ext = str(Datapath).split('.')[-1]
request.session['uploadfiletype'] = 'Local'
request.session['datatype'] = 'Normal'
filetimestamp = str(int(time.time()))
if ext.lower() in ['csv','tsv','tar','zip','avro','parquet']:
dataFile = os.path.join(DATA_FILE_PATH,'AION_' + filetimestamp+'.'+ext)
else:
dataFile = os.path.join(DATA_FILE_PATH,'AION_' + filetimestamp)
with open(dataFile, 'wb+') as destination:
for chunk in Datapath.chunks():
destination.write(chunk)
destination.close()
dataPath = dataFile
request.session['textdatapath'] = dataPath
# import pdb
# pdb.set_trace()
# check_df = pd.read_csv(dataPath)
eda_obj = ux_eda(dataPath)
check_df = eda_obj.getdata()
df_top = check_df.head(10)
df_json = df_top.to_json(orient="records")
df_json = json.loads(df_json)
# featuresList = check_df.columns.tolist()
features,dateFeature,seqFeature,constantFeature,textFeature,targetFeature,numericCatFeatures,numericFeature,catfeatures = eda_obj.getFeatures()
noTextFeature = False
if len(textFeature) == 0:
noTextFeature = True
context = {'raw_data':df_json, 'featuresList':textFeature, 'selected':'DataOperations', 'noTextFeature':noTextFeature}
return context
except Exception as e:
print(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
context = {'error': 'Failed to read data','emptycsv' : 'emptycsv'}
log.info('Text Data Ingestion -- Error : Failed to read data, '+str(e))
log.info('Details : '+ str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
return context
# ---------------------- E N D ---------------------------
def ingestDataFromFile(request,DATA_FILE_PATH):
log = logging.getLogger('log_ux')
delimiter,textqualifier = delimitedsetting(request.POST.get('delimiters'),request.POST.get('qualifier'),request.POST.get('delimiters_custom_value'))
request.session['delimiter'] = delimiter
request.session['textqualifier'] = textqualifier
context = getcommonfields()
selected_use_case,ModelVersion,ModelStatus = getusercasestatus(request)
context.update({'selected_use_case': selected_use_case,'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion,})
try:
t1 = time.time()
request.session['uploadfiletype'] = ''
request.session['uploadLocation'] = ''
data_is_large = False
check_df = pd.DataFrame()
if request.method == 'POST':
if 'ModelVersion' in request.session:
ModelVersion = request.session['ModelVersion']
else:
ModelVersion = 0
if 'ModelName' not in request.session:
movenext = False
request.session['currentstate'] = 0
context.update({'tab': 'tabconfigure', 'error': 'Please Create/Select the Use Case First', 'movenext': movenext,'currentstate': request.session['currentstate']})
log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(
ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : Please Create/Select the Use Case First')
return context
else:
type = request.POST.get("optradio")
if type == "s3Bucket":
try:
request.session['uploadfiletype'] = 'S3Bucket'
bucketname = request.POST.get('s3bucketname')
fileName = request.POST.get('s3file')
if fileName != '':
status,msg,check_df = read_s3_bucket(bucketname,fileName,DATA_FILE_PATH)
if status == 'Success':
filetimestamp = str(int(time.time()))
dataFile = os.path.join(DATA_FILE_PATH, 'AION_' + filetimestamp+'.csv')
check_df.to_csv(dataFile, index=False)
request.session['datalocation'] = dataFile
else :
request.session['currentstate'] = 0 #usnish
context.update({'error': str(msg),'ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})
log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(
ModelVersion) + ' : ' + '0' + 'sec' + ' : ' + 'Error : ' + str(msg))
return context
else: #usnish
request.session['currentstate'] = 0
context.update({'error': 'Please provide a file name','ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})
log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(
ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : Please provide a file name')
return context
except Exception as e:
request.session['currentstate'] = 0
context.update({'error': str(e),'ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})
log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(
ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : '+ str(e))
return context
'''request.session['datalocation'] = "S3"'''
# -------------------------------- Graviton-Integration Changes S T A R T --------------------------------
elif type == "graviton":
try:
dataServiceId = request.POST.get('dataservice')
metadataId = request.POST.get('metadata')
data = []
from appbe.aion_config import get_graviton_data
graviton_url,graviton_userid = get_graviton_data()
gravitonURL = graviton_url
gravitonUserId = graviton_userid
# url = 'https://xenius.azurewebsites.net/api/getdata?userid=1&dataserviceid='+str(dataserviceId) +'&metadataid=' +str(metadataId)
url = gravitonURL + 'getdata?userid=' + gravitonUserId +'&dataserviceid='+str(dataServiceId) +'&metadataid=' +str(metadataId)
print(url)
response = requests.get(url)
statuscode = response.status_code
if statuscode == 200:
json_dictionary = json.loads(response.content)
data = json_dictionary['result']
firstElement = next(iter(data[0].keys()))
check_df = pd.DataFrame.from_dict(data[0][firstElement])
filetimestamp = str(int(time.time()))
dataFile = os.path.join(DATA_FILE_PATH, 'AION_' + filetimestamp+'.csv')
check_df.to_csv(dataFile, index=False)
request.session['uploadfiletype'] = 'Graviton'
request.session['datalocation'] = str(dataFile)
except Exception as e:
print(e)
request.session['currentstate'] = 0
context.update({'error':'Check log file for more details','ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})
log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error :'+str(e))
return context
# ------------------------------------------------ E N D -------------------------------------------------
elif type == "azurestorage":
try:
request.session['uploadfiletype'] = 'AzureStorage'
azurename = request.POST.get('azurename')
directoryname = request.POST.get('azuredirectory')
if directoryname != '':
status,msg,check_df = read_azureStorage(azurename,directoryname,DATA_FILE_PATH)
if status == 'Success':
filetimestamp = str(int(time.time()))
dataFile = os.path.join(DATA_FILE_PATH, 'AION_' + filetimestamp+'.csv')
check_df.to_csv(dataFile, index=False)
'''request.session['datalocation'] = "S3"'''
request.session['datalocation'] = dataFile
else :
request.session['currentstate'] = 0 #usnish
context.update({'error': str(msg),'ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})
log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(
ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : ' +str(msg))
return context
else: #usnish
request.session['currentstate'] = 0
context.update({'error': 'Please provide a file name','ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})
log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(
ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : Please provide a file name')
return context
except Exception as e:
print(e)
request.session['currentstate'] = 0
context.update({'error': 'File does not exist','ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})
log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(
ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : File does not exist, '+str(e))
return context
elif type == "googleBucket":
try:
request.session['uploadfiletype'] = 'GCPBucket'
bucketname = request.POST.get('gcpbucketname')
fileName = request.POST.get('file1')
if fileName != '':
status,msg,check_df = read_gcs_bucket(bucketname,fileName,DATA_FILE_PATH)
if status == 'Success':
filetimestamp = str(int(time.time()))
dataFile = os.path.join(DATA_FILE_PATH, 'AION_' + filetimestamp+'.csv')
check_df.to_csv(dataFile, index=False)
'''request.session['datalocation'] = "S3"'''
request.session['datalocation'] = dataFile
else :
request.session['currentstate'] = 0 #usnish
context.update({'error': str(msg),'ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})
log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(
ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : '+str(msg))
return context
else: #usnish
request.session['currentstate'] = 0
context.update({'error': 'Please provide a file name','ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})
log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(
ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : Please provide a file name')
return context
except Exception as e:
request.session['currentstate'] = 0
context.update({'error': 'File does not exist','ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})
log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(
ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : File does not exist, ' + str(e))
return context
elif type == "url":
try:
request.session['uploadfiletype'] = 'URL'
url_text = request.POST.get('urlpathinput')
log.info('Data ingesttion from URL..')
request.session['uploadLocation'] = url_text
url = url_text
check_df = pd.read_csv(url)
filetimestamp = str(int(time.time()))
dataFile = os.path.join(DATA_FILE_PATH, 'AION_' + filetimestamp+'.csv')
check_df.to_csv(dataFile,index=False)
request.session['datalocation'] = dataFile
except Exception as e:
request.session['currentstate'] = 0
e = str(e)
print(e)
if e.find("tokenizing")!=-1:
error | ||
= "This is not an open source URL to access data"
context.update({'error': error, 'ModelVersion': ModelVersion, 'emptycsv': 'emptycsv'})
elif e.find("connection")!=-1:
error = | ||
(selected_use_case) + ' : ' + str(ModelVersion) + ' : ' + str(
round(t2 - t1)) + ' sec' + ' : ' + 'Success')
# EDA Subsampling changes
context.update({'range':range(1,101),'samplePercentage':samplePercentage, 'samplePercentval':samplePercentval, 'showRecommended':showRecommended,'featuresList': featuresList,'tab': 'tabconfigure', 'data': df_json, 'status_msg': statusmsg,
'selected': 'modeltraning','imp_features':imp_features,'numberoffeatures':numberoffeatures,
'currentstate': request.session['currentstate'], 'finalstate': request.session['finalstate'],
'exploratory': False})
if msg!="":
context.update({'data_size_alert': msg})
return context
except Exception as e:
print(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
request.session['currentstate'] = 0
context.update({'error': 'Failed to read data','emptycsv' : 'emptycsv'})
log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(ModelVersion) + ' : ' + '0' + ' sec' + ' : ' + 'Error : Failed to read data, '+str(e))
log.info('Details : '+ str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
return context
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
from pathlib import Path
import sqlite3
class sqlite_db():
def __init__(self, location, database_file=None):
if not isinstance(location, Path):
location = Path(location)
if database_file:
self.database_name = database_file
else:
self.database_name = location.stem
db_file = str(location / self.database_name)
self.conn = sqlite3.connect(db_file)
self.cursor = self.conn.cursor()
def table_exists(self, name):
query = f"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}';"
listOfTables = self.cursor.execute(query).fetchall()
return len(listOfTables) > 0
def read_data(self, table_name, condition = None):
if condition:
query = f"SELECT * FROM {table_name} WHERE "+condition
else:
query = f"SELECT * FROM {table_name}"
row = self.cursor.execute(query).fetchall()
return list(row)
def column_names(self, table_name):
query = f"SELECT * FROM {table_name}"
row = self.cursor.execute(query).fetchall()
column_names = list(map(lambda x:x[0],self.cursor.description))
return column_names
# return pd.read_sql_query(f"SELECT * FROM {table_name}", self.conn)
def create_table(self, name, columns, dtypes):
query = f'CREATE TABLE IF NOT EXISTS {name} ('
for column, data_type in zip(columns, dtypes):
query += f"'{column}' TEXT,"
query = query[:-1]
query += ');'
self.conn.execute(query)
return True
def delete_record(self, table_name, col_name, col_value):
try:
query = f"DELETE FROM {table_name} WHERE {col_name}='{col_value}'"
self.conn.execute(query)
self.conn.commit()
return 'success'
except Exception as e:
print(str(e))
print("Deletion Failed")
return 'error'
def drop_table(self,table_name):
query = f"DROP TABLE {table_name}"
self.cursor.execute(query)
print("Table dropped... ")
# Commit your changes in the database
self.conn.commit()
def get_data(self, table_name, col_name, col_value):
query = f"SELECT * FROM {table_name} WHERE {col_name}='{col_value}'"
row = self.cursor.execute(query).fetchone()
if (row == None):
return []
return list(row)
def execute_query(self,query):
self.cursor.execute(query)
self.conn.commit()
def write_data(self, data, table_name):
if not self.table_exists(table_name):
self.create_table(table_name, data.columns, data.dtypes)
tuple_data = list(data.itertuples(index=False, name=None))
insert_query = f'INSERT INTO {table_name} VALUES('
for i in range(len(data.columns)):
insert_query += '?,'
insert_query = insert_query[:-1] + ')'
self.cursor.executemany(insert_query, tuple_data)
self.conn.commit()
return True
def update_dict_data(self,data:dict,condition,table_name):
if not data:
return
if not table_name:
raise ValueError('Database table name is not provided')
updates = ''
#TODO validation of keys
for i,kv in enumerate(data.items()):
if i:
updates += ','
updates += f'"{kv[0]}"="{kv[1]}"'
if condition == '':
update_query = f'UPDATE {table_name} SET {updates}'
else:
update_query = f'UPDATE {table_name} SET {updates} WHERE {condition}'
self.cursor.execute(update_query)
self.conn.commit()
def update_data(self,updates,condition,table_name):
if condition == '':
update_query = f'UPDATE {table_name} SET {updates}'
else:
update_query = f'UPDATE {table_name} SET {updates} WHERE {condition}'
self.cursor.execute(update_query)
self.conn.commit()
def close(self):
self.conn.close()<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os
import platform
import shutil
import subprocess
import sys
import time
import glob
import re
from appbe.pages import get_usecase_page
import json
from django.http import FileResponse
def startIncrementallearning(request,usecasedetails,Existusecases,DATA_FILE_PATH):
try:
modelid = request.POST.get('modelid')
#incfilepath = request.POST.get('incfilepath')
Datapath = request.FILES['incfilepath']
filetimestamp = str(int(time.time()))
dataFile = os.path.join(DATA_FILE_PATH,'AION_' + filetimestamp+'.csv')
with open(dataFile, 'wb+') as destination:
for chunk in Datapath.chunks():
destination.write(chunk)
# destination.close()#bugfix 11656
incfilepath = dataFile
p = Existusecases.objects.get(id=modelid)
deployPath = str(p.DeployPath)
scriptPath = os.path.abspath(os.path.join(deployPath,'aion_inclearning.py'))
request.session['IsRetraining'] = 'No'
if not os.path.exists(scriptPath):
status,context,action = get_usecase_page(request,usecasedetails,Existusecases)
context['Msg'] = 'Incremental/Online learning not supported for this model.For online training select Online Training in basic configuration page and provide with training'
else:
outputStr = subprocess.check_output([sys.executable, scriptPath, incfilepath])
outputStr = outputStr.decode('utf-8')
outputStr = re.search(r'aion_learner_status:(.*)', str(outputStr), re.IGNORECASE).group(1)
outputStr = outputStr.strip()
decoded_data = json.loads(outputStr)
status,context,action = get_usecase_page(request,usecasedetails,Existusecases)
if decoded_data['status'] == 'SUCCESS':
msg = decoded_data['Msg']
context['Status'] = 'SUCCESS'
context['Msg'] = msg
else:
msg = decoded_data['Msg']
context['Status'] = 'SUCCESS'
context['Msg'] = msg
except Exception as e:
print(e)
try:
status,context,action = get_usecase_page(request,usecasedetails,Existusecases)
except Exception as msg:
context['errorMsg'] = msg
return action,context
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import sqlite3
from pathlib import Path
import json
import os
import rsa
import boto3 #usnish
import pandas as pd
import time
import sqlite3
class sqlite_db():
def __init__(self, location, database_file=None):
if not isinstance(location, Path):
location = Path(location)
if database_file:
self.database_name = database_file
else:
self.database_name = location.stem
db_file = str(location/self.database_name)
self.conn = sqlite3.connect(db_file)
self.cursor = self.conn.cursor()
def table_exists(self, name):
query = f"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}';"
listOfTables = self.cursor.execute(query).fetchall()
return len(listOfTables) > 0
def read_data(self, table_name):
query = f"SELECT * FROM {table_name}"
row = self.cursor.execute(query).fetchall()
return list(row)
#return pd.read_sql_query(f"SELECT * FROM {table_name}", self.conn)
def create_table(self,name, columns, dtypes):
query = f'CREATE TABLE IF NOT EXISTS {name} ('
for column, data_type in zip(columns, dtypes):
query += f"'{column}' TEXT,"
query = query[:-1]
query += ');'
self.conn.execute(query)
return True
def delete_record(self,table_name,col_name, col_value):
try:
query = f"DELETE FROM {table_name} WHERE {col_name}='{col_value}'"
self.conn.execute(query)
self.conn.commit()
return 'success'
except Exception as e :
print(str(e))
print("Deletion Failed")
return 'error'
def get_data(self,table_name,col_name,col_value):
query = f"SELECT * FROM {table_name} WHERE {col_name}='{col_value}'"
row = self.cursor.execute(query).fetchone()
if(row == None):
return []
return list(row)
def write_data(self,data, table_name):
if not self.table_exists(table_name):
self.create_table(table_name, data.columns, data.dtypes)
tuple_data = list(data.itertuples(index=False, name=None))
insert_query = f'INSERT INTO {table_name} VALUES('
for i in range(len(data.columns)):
insert_query += '?,'
insert_query = insert_query[:-1] + ')'
self.cursor.executemany(insert_query, tuple_data)
self.conn.commit()
return True
def close(self):
self.conn.close()
def add_new_GCSBucket(request):
try:
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
print(request.POST["aionreferencename"])
print(request.POST["serviceaccountkey"])
print(request.POST["bucketname"])
if request.POST["aionreferencename"] =='' or request.POST["serviceaccountkey"] == '' or request.POST["bucketname"] == '' :
return 'error'
newdata = {}
newdata['Name'] = [request.POST["aionreferencename"]]
newdata['GCSServiceAccountKey'] = [request.POST["serviceaccountkey"]]
newdata['GCSbucketname'] = [request.POST["bucketname"]]
name = request.POST["aionreferencename"]
if sqlite_obj.table_exists("gcsbucket"):
if(len(sqlite_obj.get_data("gcsbucket",'Name',name))>0):
return 'error1'
sqlite_obj.write_data(pd.DataFrame.from_dict(newdata),'gcsbucket')
except:
return 'error'
def get_gcs_bucket():
try:
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
temp_data = sqlite_obj.read_data('gcsbucket')
data = []
for x in temp_data:
data_dict = {}
data_dict['Name'] = x[0]
data_dict['GCSServiceAccountKey'] = x[1]
data_dict['GCSbucketname'] = x[2]
data.append(data_dict)
except Exception as e:
print(e)
data = []
return data
def read_gcs_ | ||
bucket(name,filename,DATA_FILE_PATH):
try:
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
data = sqlite_obj.get_data("gcsbucket",'Name',name)
except:
data = []
found = False
if len(data)!=0:
GCSServiceAccountKey = data[1]
GCSbucketname = data[2]
found = True
#print(found)
#print(name)
try:
if found:
import io
from google.cloud import storage
#print(GCSServiceAccountKey)
#print(GCSbucketname)
try:
storage_client = storage.Client.from_service_account_json(GCSServiceAccountKey)
bucket = storage_client.get_bucket(GCSbucketname)
blob = bucket.blob(filename)
data = blob.download_as_string()
df = pd.read_csv(io.BytesIO(data), encoding = 'utf-8', sep = ',',encoding_errors= 'replace')
except Exception as e:
return "Error",str(e), pd.DataFrame()
return 'Success',"",df
except Exception as e:
print(e)
return 'Error',"Please check bucket configuration",pd.DataFrame()
def remove_gcs_bucket(name):
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
return sqlite_obj.delete_record('gcsbucket','Name',name)
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import sqlite3
from pathlib import Path
import json
import os
import rsa
import boto3 #usnish
import pandas as pd
import time
class sqlite_db():
def __init__(self, location, database_file=None):
if not isinstance(location, Path):
location = Path(location)
if database_file:
self.database_name = database_file
else:
self.database_name = location.stem
db_file = str(location/self.database_name)
self.conn = sqlite3.connect(db_file)
self.cursor = self.conn.cursor()
def table_exists(self, name):
query = f"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}';"
listOfTables = self.cursor.execute(query).fetchall()
return len(listOfTables) > 0
def read_data(self, table_name):
query = f"SELECT * FROM {table_name}"
row = self.cursor.execute(query).fetchall()
return list(row)
#return pd.read_sql_query(f"SELECT * FROM {table_name}", self.conn)
def create_table(self,name, columns, dtypes):
query = f'CREATE TABLE IF NOT EXISTS {name} ('
for column, data_type in zip(columns, dtypes):
query += f"'{column}' TEXT,"
query = query[:-1]
query += ');'
self.conn.execute(query)
return True
def delete_record(self,table_name,col_name, col_value):
try:
query = f"DELETE FROM {table_name} WHERE {col_name}='{col_value}'"
self.conn.execute(query)
self.conn.commit()
return 'success'
except Exception as e :
print(str(e))
print("Deletion Failed")
return 'error'
def get_data(self,table_name,col_name,col_value):
query = f"SELECT * FROM {table_name} WHERE {col_name}='{col_value}'"
row = self.cursor.execute(query).fetchone()
if(row == None):
return []
return list(row)
def write_data(self,data, table_name):
if not self.table_exists(table_name):
self.create_table(table_name, data.columns, data.dtypes)
tuple_data = list(data.itertuples(index=False, name=None))
insert_query = f'INSERT INTO {table_name} VALUES('
for i in range(len(data.columns)):
insert_query += '?,'
insert_query = insert_query[:-1] + ')'
self.cursor.executemany(insert_query, tuple_data)
self.conn.commit()
return True
def close(self):
self.conn.close()
def add_new_s3bucket(request):
try:
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
if request.POST["aionreferencename"] =='' or request.POST["s3bucketname"] == '' or request.POST["awsaccesskey"] == '' :
return 'error'
pkeydata='''-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAxIHM1FphEMMwViUrG0b2Bqf8tOxbhUWlnmjgFt5A25qbY1AfnrMv
fVx8+7iCcZ/3TY9Jv2I584SOc1tvsgESCke/t6+o/u2esPBsnDFzV62l3Zvw0m4e
wQeKlFC8EoOblyIXRbZdelSJinzlr9lOiKuid/xPvXHou6jxF1A2W7a89A2PM4Re
n0W9YkjB7dRGW1sSrpruHdVJvgHhGZFZ7sCTue0jVOnc5sT3Tq5saLfEDqHyKxlq
i/mcThmcTfisRIYFH5pyt/Ysr4VVP924QlcoqPOyg3RMCS3G0VjstSoVwNhxWrs/
lujDuCnpxvWzNpq21OWmF66GXxwiq+6W0wIDAQAB
-----END RSA PUBLIC KEY-----'''
pubkey = rsa.PublicKey.load_pkcs1(pkeydata)
awssecretaccesskey = rsa.encrypt(request.POST["awssecretaccesskey"].encode(), pubkey)
newdata = {}
newdata['Name'] = [request.POST["aionreferencename"]]
newdata['AWSAccessKeyID'] = [request.POST["awsaccesskey"]]
newdata['AWSSecretAccessKey'] = [str(awssecretaccesskey)]
newdata['S3BucketName'] = [request.POST["s3bucketname"]]
name = request.POST["aionreferencename"]
if sqlite_obj.table_exists("s3bucket"):
if(len(sqlite_obj.get_data("s3bucket","Name",name)) > 0):
return 'error1'
sqlite_obj.write_data(pd.DataFrame.from_dict(newdata),'s3bucket')
except Exception as e:
print(e)
return 'error'
def get_s3_bucket():
try:
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
temp_data = sqlite_obj.read_data('s3bucket')
data = []
for x in temp_data:
data_dict = {}
data_dict['Name'] = x[0]
data_dict['AWSAccessKeyID'] = x[1]
data_dict['AWSSecretAccessKey'] = x[2]
data_dict['S3BucketName'] = x[3]
data.append(data_dict)
except Exception as e:
print(e)
data = []
return data
def remove_s3_bucket(name):
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
return sqlite_obj.delete_record('s3bucket','Name',name)
def read_s3_bucket(name,filename,DATA_FILE_PATH):
privkey = '''-----BEGIN RSA PRIVATE KEY-----
MIIEqQIBAAKCAQEAxIHM1FphEMMwViUrG0b2Bqf8tOxbhUWlnmjgFt5A25qbY1Af
nrMvfVx8+7iCcZ/3TY9Jv2I584SOc1tvsgESCke/t6+o/u2esPBsnDFzV62l3Zvw
0m4ewQeKlFC8EoOblyIXRbZdelSJinzlr9lOiKuid/xPvXHou6jxF1A2W7a89A2P
M4Ren0W9YkjB7dRGW1sSrpruHdVJvgHhGZFZ7sCTue0jVOnc5sT3Tq5saLfEDqHy
Kxlqi/mcThmcTfisRIYFH5pyt/Ysr4VVP924QlcoqPOyg3RMCS3G0VjstSoVwNhx
Wrs/lujDuCnpxvWzNpq21OWmF66GXxwiq+6W0wIDAQABAoIBAC/VbNfQPEqJSO3f
VFPqfR73q2MbGdgiMQOTgeDvLxiF1QdizJ+j/I5mgiIAMviXuOpPU+NbdMHbZZWd
D15kNlD8UCXVg6yyiOuHStjmjK4uHe8I86E1nxTb0hbyZCWZlbk/WizlDHInu+dT
KdIZcq2AIidU6tAxtwA0ingHaRSoXDlSGwOTEigNqmWOKnDTVg0SMscoHOD7siXF
DHm1/lkvD3uvcZk6c7fGxC8SgNX2dj6n/Nbuy0Em+bJ0Ya5wq4HFdLJn3EHZYORF
ODUDYoGaSxeXqYsGg/KHJBc8J7xW9FdN9fGbHfw1YplrmiGL3daATtArjMmAh0EQ
H8Sj7+ECgYkA3oWMCHi+4t8txRPkg1Fwt8dcqYhGtqpAus3NESVurAdi0ZPqEJcQ
4cUbflwQPhX0TOaBlkgzdP8DMdcW/4RalxHsAh5N8ezx/97PQMb3Bht0WsQUBeYJ
xLV7T2astjTRWactGCG7dwTaUYRtU3FqL6//3CysmA12B5EMX0udNBOTKwmaYKww
AwJ5AOISS7f12Q0fgTEVY0H8Zu5hHXNOA7DN92BUzf99iPx+H+codLet4Ut4Eh0C
cFmjA3TC78oirp5mOOQmYxwaFaxlZ7Rs60dlPFrhz0rsHYPK1yUOWRr3RcXWSR13
r+kn+f+8k7nItfGi7shdcQW+adm/EqPfwTHM8QKBiQCIPEMrvKFBzVn8Wt2A+I+G
NOyqbuC8XSgcNnvij4RelncN0P1xAsw3LbJTfpIDMPXNTyLvm2zFqIuQLBvMfH/q
FfLkqSEXiPXwrb0975K1joGCQKHxqpE4edPxHO+I7nVt6khVifF4QORZHDbC66ET
aTHA3ykcPsGQiGGGxoiMpZ9orgxyO3l5Anh92jmU26RNjfBZ5tIu9dhHdID0o8Wi
M8c3NX7IcJZGGeCgywDPEFmPrfRHeggZnopaAfuDx/L182pQeJ5MEqlmI72rz8bb
JByJa5P+3ZtAtzc2RdqNDIMnM7fYU7z2S279U3nZv0aqkk3j9UDqNaqvsZMq73GZ
y8ECgYgoeJDi+YyVtqgzXyDTLv6MNWKna9LQZlbkRLcpg6ELRnb5F/dL/eB/D0Sx
QpUFi8ZqBWL+A/TvgrCrTSIrfk71CKv6h1CGAS02dXorYro86KBLbJ0yp1T/WJUj
rHrGHczglvoB+5stY/EpquNpyca03GcutgIi9P2IsTIuFdnUgjc7t96WEQwL
-----END RSA PRIVATE KEY-----'''
try:
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
data = sqlite_obj.get_data("s3bucket",'Name',name)
except:
data = []
awssecretaccesskey = ''
found = False
if len(data)!=0:
aws_access_key_id = data[1]
awssecretaccesskey = data[2]
bucketName = data[3]
found = True
if found:
privkey = rsa.PrivateKey.load_pkcs1(privkey,'PEM')
awssecretaccesskey = eval(awssecretaccesskey)
awssecretaccesskey = rsa.decrypt(aws | ||
secretaccesskey, privkey)
awssecretaccesskey = awssecretaccesskey.decode('utf-8')
#awssecretaccesskey = 'SGcyJavYEQPwTbOg1ikqThT+Op/ZNsk7UkRCpt9g'#rsa.decrypt(awssecretaccesskey, privkey)
client_s3 = boto3.client('s3', aws_access_key_id=aws_access_key_id, aws_secret_access_key=str(awssecretaccesskey))
#print(bucketName,filename)
try:
response = client_s3.get_object(Bucket=bucketName, Key=filename)
df = pd.read_csv(response['Body'])
except Exception as e:
print(str(e))#usnish
return 'Error',str(e), pd.DataFrame()
#return 'Error', pd.DataFrame()
return 'Success','',df
return 'Error',"Please check bucket configuration", pd.DataFrame()<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import plotly.figure_factory as ff
from plotly.subplots import make_subplots
import plotly.graph_objects as go
from wordcloud import WordCloud, STOPWORDS
import pandas as pd
import numpy as np
from appbe import distribution
import io
import urllib
import os
import sys
import base64
from appbe import help_Text as ht
import math
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from natsort import natsorted
from sklearn.cluster import KMeans
import json
from facets_overview.generic_feature_statistics_generator import GenericFeatureStatisticsGenerator
from appbe.aion_config import eda_setting
from dython.nominal import associations
def calculateNumberofCluster(featureData):
Sum_of_squared_distances = []
K = range(1, 15)
for k in K:
km = KMeans(n_clusters=k)
km = km.fit(featureData)
Sum_of_squared_distances.append(km.inertia_)
x1, y1 = 1, Sum_of_squared_distances[0]
x2, y2 = 15, Sum_of_squared_distances[len(Sum_of_squared_distances) - 1]
distances = []
for inertia in range(len(Sum_of_squared_distances)):
x0 = inertia + 2
y0 = Sum_of_squared_distances[inertia]
numerator = abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1)
denominator = math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)
distances.append(numerator / denominator)
n_clusters = distances.index(max(distances)) + 2
#print(n_clusters)
return (n_clusters)
def get_eda(request):
hopkins_val = ''
hopkins_tip = ''
if request.session['datatype'] == 'Normal':
from appbe.eda import ux_eda
# EDA Subsampling changes
# ----------------------------
edasampleSize = request.POST.get('SubsampleSize')
edasampleSize = str(int(edasampleSize)/100)
sampleFile = str(request.session['datalocation'])
repText = sampleFile[sampleFile.find('sub_'):sampleFile.find('_sampled_') + 9]
if len(repText) == 30:
dataLocation = sampleFile.replace(repText,"")
else:
dataLocation = sampleFile
eda_obj = ux_eda(dataLocation,request.session['delimiter'],request.session['textqualifier'])
df0 = eda_obj.getdata()
if os.path.isfile(dataLocation):
if(len(edasampleSize) > 0):
df0 = df0.sample(frac = float(edasampleSize))
#EDA Performance change
# ----------------------------
dflength = len(df0)
# sample_size = int(eda_setting())
# if dflength >= sample_size:
# eda_obj.subsampleData(sample_size)
# else:
eda_obj.subsampleData(dflength)
# ----------------------------
TrainSampleSelected = request.POST.get('TrainSampleSize')
if(TrainSampleSelected == 'EDASize'):
from pathlib import Path
filePath = Path(dataLocation)
import datetime
timestamp = datetime.datetime.now().replace(microsecond=0).isoformat()
timestamp = str(timestamp.replace(":",""))
sub_sampledFile = filePath.parent/("sub_" + timestamp + "_sampled_"+filePath.name)
# sub_sampledFile = filePath.parent/(usename + "_sub_sampled_"+filePath.name)
df0.to_csv(sub_sampledFile,index=False,)
request.session['datalocation'] = str(sub_sampledFile)
records = df0.shape[0]
request.session['NoOfRecords'] = records
edaFeatures = request.POST.getlist('InputFeatures')
request.session['edaFeatures'] = edaFeatures
if(len(edaFeatures) > 0):
eda_obj.subsetFeatures(edaFeatures)
# ----------------------------
features,dateFeature,seqFeature,constantFeature,textFeature,targetFeature,numericCatFeatures,numericFeature,catfeatures = eda_obj.getFeatures()
request.session['edanumericCatFeatures'] = numericCatFeatures
request.session['edatextFeature'] = textFeature
categoricalfeatures = catfeatures
numericfeaturecount = eda_obj.getNumericFeatureCount()
cluster_details = []
dataCharts = []
# correlated_features=[]
pca_details = []
if numericfeaturecount > 1:
try:
cluster_details,hopkins_val = eda_obj.getClusterDetails()
if hopkins_val!='':
if float(hopkins_val) <0.3:
hopkins_tip = ht.hopkins_tip[0]
elif float(hopkins_val)>0.7:
hopkins_tip = ht.hopkins_tip[2]
else:
hopkins_tip = ht.hopkins_tip[1]
else:
hopkins_tip = ''
except Exception as e:
print("========================"+str(e))
pass
try:
pca_map = eda_obj.getPCATop10Features()
pca_details = pca_map
yaxis_data = pca_map.tolist()
xaxis_data = pca_map.index.values.tolist()
import plotly.graph_objects as go
cfig = go.Figure()
cfig.add_trace(go.Bar(x=xaxis_data, y=yaxis_data, name='Feature Importance'))
cfig.update_layout(barmode='stack', xaxis_title='Features',yaxis_title='Explained Variance Ratio')
bargraph = cfig.to_html(full_html=False, default_height=450, default_width=1000)
dataCharts.append(bargraph)
except:
pass
df = eda_obj.getdata()
# try:
# top5highcorr = eda_obj.getHighlyCorrelatedFeatures(5)
# correlated_features = getHighlyCorrelatedFeatureCharts(df,top5highcorr)
# except:
# pass
else:
df = eda_obj.getdata()
# # EDA Subsampling changes
# # ----------------------------
# if os.path.isfile(dataLocation):
# if dflength < 10000:
# if(len(edasampleSize) > 0):
# df = df.sample(frac = float(edasampleSize))
# ----------------------------
if len(textFeature) > 0:
commonfeatures = eda_obj.getTopTextFeatures(10)
# comment_words = eda_obj.word_token()
del eda_obj
wordcloudpic = ''
showtextFeature = False
if len(textFeature) > 0:
showtextFeature = True
# try:
# stopwords = set(STOPWORDS)
# wordcloud = WordCloud(width=800, height=800, background_color='white', stopwords=stopwords,
# min_font_size=10).generate(comment_words)
# try:
# plt.clf()
# except:
# pass
# plt.imshow(wordcloud, interpolation='bilinear')
# plt.axis("off")
# plt.tight_layout(pad=0)
# image = io.BytesIO()
# plt.savefig(image, format='png')
# image.seek(0)
# string = base64.b64encode(image.read())
# wordcloudpic = 'data:image/png;base64,' + urllib.parse.quote(string)
# except:
# pass
xaxis_data = commonfeatures['most_common_words'].tolist()
yaxis_data = commonfeatures['freq'].tolist()
import plotly.graph_objects as go
cfig = go.Figure()
cfig.add_trace(go.Bar(x=xaxis_data, y=yaxis_data, name='Feature Importance'))
cfig.update_layout(barmode='stack', xaxis_title='Features',yaxis_title='Count')
bargraph = cfig.to_html(full_html=False, default_height=450, default_width=1000)
dataCharts.append(bargraph)
df_top = df.head(10)
df_json = df_top.to_json(orient="records")
df_json = json.loads(df_json)
# if len(df) > 10000:
# df1 = df.sample(n=10000, random_state=1)
# else:
# df1 = df
df1 = df
data_deep_json = df_top.to_json(orient='records') #df1.to_json(orient='records')
try:
gfsg = GenericFeatureStatisticsGenerator()
proto = gfsg.ProtoFromDataFrames([{'name': 'train', 'table': df1}])
protostr = base64.b64encode(proto.SerializeToString()).decode("utf-8")
except Exception as e:
protostr=''
print('protostr '+str(e))
try:
correlationgraph = getCorrelationMatrix(df)
except Exception as e:
print(e)
try:
dataDrift = 'onRequest' #getDriftDistribution(numericCatFeatures, df[numericCatFeatures])
except Exception as e:
dataDrift = ''
print(e)
selected_use_case = request.session['UseCaseName']
ModelVersion = request.session['ModelVersion']
ModelStatus = request.session['ModelStatus']
statusmsg = 'Successfully Done'
DF_list = list()
des1 = df.describe(include='all').T
des1['missing count %'] = df.isnull().mean() * 100
des1['zero count %'] = df.isin([0]).mean() * 100
data = list(df.columns.values)
des1.insert(0, 'Features', data)
des1 = des1.to_json(orient="records")
pca_df=pd.DataFrame()
#print(pca_details)
# if pca_details.empty:
if len(pca_details) > 0:
pca_df = pd.DataFrame({'Feature':pca_details.index, 'Explained Variance Ratio':pca_details.values}).round(4)
pca_df = pca_df.to_json(orient="records")
if len(df.columns) > 25:
df3 = df[df.columns[0:24]]
else:
df3 = df.copy()
#cor_mat = abs(df3.corr())
#cor_mat = cor_mat.round(2)
try:
if len(df3.columns) > 25:
df3 = df3[df3.columns[0:24]]
cor_mat= associations(df3,compute_only=True)
cor_mat=cor_mat['corr']
#cor_mat = df3.corr()
cor_mat = cor_mat.astype(float).round(2)
except Exception as e:
print("creating correlation mat issue: \\n",e)
pass
data = list(cor_mat.index)
cor_mat.insert(0, 'Features', data)
cor_mat = cor_mat.to_json(orient="records")
cluster_df = pd.DataFrame.from_dict(cluster_details)
cluster_df = cluster_df.to_json(orient="records")
#textFeature = json.dumps(textFeature)
# 2.2 patch changes
#-------------------------------------------------
request.session['edaRecords'] = df.shape[0]
print(textFeature)
context = {'data_deep_json': data_deep_json, 'sampleFile':sampleFile,'protostr': protostr, 'data': df_json, 'oneda': True,
'dataCharts': dataCharts,'dataDrift': dataDrift, 'drift_tip': ht.drift_tip,'des1':des1,'cluster_df':cluster_df,'hopkins_val':hopkins_val,
'pca_df':pca_df,'cor_mat':cor_mat,'correlationgraph': correlationgraph, 'centroids':cluster_details, 'wordcloudpic': wordcloudpic, 'showtextFeature': showtextFeature, 'textFeature': textFeature,
# 'featurepairgraph': correlated_features,
'data_overview_tip': ht.data_overview_tip,'timeseries_analysis_tip':ht.timeseries_analysis_tip, 'feature_importance_tip': ht.feature_importance_tip,'hopkins_tip':hopkins_tip,
'correlation_analysis_tip': ht.correlation_analysis_tip,
'exploratory_analysis_tip': ht.exploratory_analysis_tip, 'data_deep_drive_tip': ht.data_deep_drive_tip,'status_msg': statusmsg,'selected_use_case': selected_use_case,
'pair | ||
_graph_tip':ht.pair_graph_tip, 'fair_metrics_tip':ht.fair_metrics_tip, 'categoricalfeatures':categoricalfeatures, 'numericCatFeatures':numericCatFeatures,
'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion,'selected': 'modeltraning',
'currentstate': request.session['currentstate'], 'finalstate': request.session['finalstate'],'exploratory':True,'NumericFeatureList':numericFeature,'dateFeature':dateFeature,'targetFeature':targetFeature}
return(context)
# EDA Visualization changes
# ----------------------------
def get_edaGraph(request):
if request.session['datatype'] == 'Normal':
from appbe.eda import ux_eda
df_temp = dict(request.GET).get('features[]')
graphType = request.GET.get('graphType')
d3_url = request.GET.get('d3_url')
mpld3_url = request.GET.get('mpld3_url')
dataLocation = request.session['datalocation']
eda_obj = ux_eda(dataLocation)
# 2.2 patch changes
#-------------------------------------------------
edaRecords = request.session['edaRecords']
#df = df.sample(n=int(edaRecords), random_state=1)
eda_obj.subsampleData(edaRecords)
eda_obj.subsetFeatures(df_temp)
features,dateFeature,seqFeature,constantFeature,textFeature,targetFeature,numericCatFeatures,numericFeature, catfeatures = eda_obj.getFeatures()
numericfeaturecount = eda_obj.getNumericFeatureCount()
correlated_features=[]
df = eda_obj.getdata()
if numericfeaturecount > 1:
try:
if graphType == 'Default':
top5highcorr = eda_obj.getHighlyCorrelatedFeatures(5)
correlated_features = getHighlyCorrelatedFeatureCharts(df,top5highcorr)
else:
correlated_features = getFeatureCharts(df,graphType,d3_url,mpld3_url)
except:
pass
return correlated_features
# ----------------------------
# ---------------------- 12686:Data Distribution related Changes S T A R T ----------------------
def get_DataDistribution(request):
selectedFeature = request.GET.get('selected_feature')
_featureItem = []
_featureItem.append(selectedFeature)
from appbe.eda import ux_eda
dataLocation = request.session['datalocation']
eda_obj = ux_eda(dataLocation)
df = eda_obj.getdata()
numericCatFeatures = request.session['edanumericCatFeatures']
textFeature = request.session['edatextFeature']
# features,dateFeature,seqFeature,constantFeature,textFeature,targetFeature,numericCatFeatures,numericFeature,catfeatures = eda_obj.getFeatures()
dataDrift = ''
if selectedFeature in numericCatFeatures:
dataDrift = getDriftDistribution(_featureItem, df[numericCatFeatures])
elif selectedFeature in textFeature:
try:
comment_words = eda_obj.word_token_for_feature(selectedFeature, df[_featureItem])
stopwords = set(STOPWORDS)
wordcloud = WordCloud(width=800, height=800, background_color='white', stopwords=stopwords,
min_font_size=10).generate(comment_words)
try:
plt.clf()
except:
pass
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.tight_layout(pad=0)
image = io.BytesIO()
plt.savefig(image, format='png')
image.seek(0)
string = base64.b64encode(image.read())
# wordcloudpic = 'data:image/png;base64,' + urllib.parse.quote(string)
dataDrift = urllib.parse.quote(string)
except:
dataDrift = ''
del eda_obj
return dataDrift
# -------------------------------------------- E N D --------------------------------------------
def get_DeepDiveData(request):
if request.session['datatype'] == 'Normal':
from appbe.eda import ux_eda
dataLocation = request.session['datalocation']
eda_obj = ux_eda(dataLocation)
edaRecords = request.session['edaRecords']
edaFeatures = request.session['edaFeatures']
eda_obj.subsampleData(edaRecords)
eda_obj.subsetFeatures(edaFeatures)
df = eda_obj.getdata()
data_deep_json = df.to_json(orient='records')
return (data_deep_json)
# Fairness Metrics changes
# ----------------------------
def get_fairmetrics(request):
import mpld3
if request.session['datatype'] == 'Normal':
from appbe.eda import ux_eda
df_temp = dict(request.GET).get('features[]')
d3_url = request.GET.get('d3_url')
mpld3_url = request.GET.get('mpld3_url')
global metricvalue
metricvalue = request.GET.get('metricvalue')
dataLocation = request.session['datalocation']
# dataLocation = 'C:\\\\MyFolder\\\\AION\\\\AION Datasets\\\\AIF360\\\\database.csv'
eda_obj = ux_eda(dataLocation, optimize=1)
features,dateFeature,seqFeature,constantFeature,textFeature,targetFeature,numericCatFeatures,numericFeature,catfeatures = eda_obj.getFeatures()
# data = eda_obj.getdata()
data = pd.read_csv(dataLocation, na_values=['Unknown', ' '])
features_toEncode = features
from sklearn.preprocessing import MinMaxScaler, LabelEncoder
data_encoded = data.copy()
categorical_names = {}
encoders = {}
# Use Label Encoder for categorical columns (including target column)
for feature in features_toEncode:
le = LabelEncoder()
le.fit(data_encoded[feature])
data_encoded[feature] = le.transform(data_encoded[feature])
categorical_names[feature] = le.classes_
encoders[feature] = le
data_perp = data_encoded
protected_feature = df_temp[0] #'Victim Race'
target_feature = df_temp[1] #'Perpetrator Sex'
# ------Theil index----- Task->13843
from aif360.sklearn.metrics import generalized_entropy_index
Ti_List = []
for items in categorical_names[protected_feature]:
df = data[data[protected_feature]==items]
le = LabelEncoder()
le.fit(df[target_feature])
df[target_feature] = le.transform(df[target_feature])
tf = generalized_entropy_index(df[target_feature], alpha = 1)
tf = round(tf, 4)
Ti_List.append(tf)
global Thi_idx
Thi_idx = Ti_List
#claas_size = categorical_names[protected_feature].size
new_list = [item for item in categorical_names[protected_feature] if not(pd.isnull(item)) == True]
claas_size = len(new_list)
if claas_size > 10:
return 'HeavyFeature'
metrics = fair_metrics(categorical_names, data_perp, protected_feature, target_feature, claas_size)
figure = plot_fair_metrics(metrics)
html_graph = mpld3.fig_to_html(figure,d3_url=d3_url,mpld3_url=mpld3_url)
return html_graph
def fair_metrics(categorical_names, data_perp, protected_feature, target_feature, claas_size):
import aif360
from aif360.datasets import StandardDataset
from aif360.metrics import BinaryLabelDatasetMetric
cols = [metricvalue]
obj_fairness = [[0]]
fair_metrics = pd.DataFrame(data=obj_fairness, index=['objective'], columns=cols)
for indx in range(claas_size):
priv_group = categorical_names[protected_feature][indx]
privileged_class = np.where(categorical_names[protected_feature] == priv_group)[0]
data_orig = StandardDataset(data_perp,
label_name=target_feature,
favorable_classes=[1],
protected_attribute_names=[protected_feature],
privileged_classes=[privileged_class])
dataset_pred = data_orig
attr = dataset_pred.protected_attribute_names[0]
idx = dataset_pred.protected_attribute_names.index(attr)
privileged_groups = [{attr:dataset_pred.privileged_protected_attributes[idx][0]}]
unprivileged_size = dataset_pred.unprivileged_protected_attributes[0].size
unprivileged_groups = []
for idx2 in range(unprivileged_size):
unprivileged_groups.extend([{attr:dataset_pred.unprivileged_protected_attributes[idx][idx2]}])
metric_pred = BinaryLabelDatasetMetric(dataset_pred,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
if metricvalue == "Theil Index":
row = pd.DataFrame([Thi_idx[indx]],
columns = cols ,
index = [priv_group])
elif metricvalue == "Disparate Impact":
row = pd.DataFrame([[metric_pred.disparate_impact()]],
columns = cols ,
index = [priv_group])
elif metricvalue == "Statistical Parity Difference":
row = pd.DataFrame([[metric_pred.mean_difference()]],
columns = cols ,
index = [priv_group])
#fair_metrics = fair_metrics.append(row)
fair_metrics = pd.concat([fair_metrics,row])
return fair_metrics
def plot_fair_metrics(fair_metrics):
import matplotlib.patches as patches
plt.style.use('default')
import seaborn as sns
fig, ax = plt.subplots(figsize=(10,4), ncols=1, nrows=1)
plt.subplots_adjust(
left = 0.125,
bottom = 0.1,
right = 0.9,
top = 0.9,
wspace = .5,
hspace = 1.1
)
y_title_margin = 1.2
plt.suptitle("Fairness metrics", y = 1.09, fontsize=20)
sns.set(style="dark")
cols = fair_metrics.columns.values
obj = fair_metrics.loc['objective']
if metricvalue == "Theil Index":
size_rect = [0.5]
rect = [-0.1]
bottom = [-0.1]
top = [2]
bound = [[-0.1,0.1]]
elif metricvalue == "Disparate Impact":
size_rect = [0.4]
rect = [0.8]
bottom = [0]
top = [2]
bound = [[-0.1,0.1]]
elif metricvalue == "Statistical Parity Difference":
size_rect = [0.2]
rect = [-0.1]
bottom = [-1]
top = [1]
bound = [[-0.1,0.1]]
#display(Markdown("### Check bias metrics :"))
#display(Markdown("A model can be considered bias if just one of these five metrics show that this model is biased."))
for attr in fair_metrics.index[0:len(fair_metrics)].values:
#display(Markdown("#### For the %s attribute :"%attr))
check = [bound[i][0] < fair_metrics.loc[attr][i] < bound[i][1] for i in range(0,1)]
#display(Markdown("With default thresholds, bias against unprivileged group detected in **%d** out of 5 metrics"%(5 - sum(check))))
for i in range(0,1):
plt.subplot(1, 1, i+1)
xx = fair_metrics.index[1:len(fair_metrics)].values.tolist()
yy = fair_metrics.iloc[1:len(fair_metrics)][cols[i]].values.tolist()
palette = sns.color_palette('husl', len(xx))
ax = sns.pointplot(x=fair_metrics.index[1:len(fair_metrics)], y=yy, palette=palette, hue=xx)
index = 0
for p in zip(ax.get_xticks(), yy):
if (p[1] > 2.0):
_color = palette.as_hex()[index]
_val = 'Outlier(' + str(round(p[1],3)) + ')'
ax.text(p[0]-0.5, 0.02, _val, color=_color)
else:
ax.text(p[0], p[1]+0.05, round(p[1],3), color='k')
index = index + 1
plt.ylim(bottom[i], top[i])
plt.setp(ax.patches, linewidth=0)
ax.get_xaxis().set_visible(False)
ax.legend(loc='right', bbox_to_anchor=(1, 0.8), ncol=1)
ax.add_patch(patches.Rectangle((-5,rect[i]), 10, size_rect[i], alpha=0.3, facecolor="green", linewidth=1, linestyle='solid'))
# plt.axhline(obj[i], color='black', alpha=0.3)
plt.title(cols[i], fontname="Times New Roman", size=20,fontweight="bold")
ax.set_ylabel('')
ax.set_xlabel('')
return fig
# ----------------------------
def getDriftDistribution(feature, dataframe, newdataframe=pd.DataFrame()):
try:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import scipy
from scipy import stats
from scipy.stats import norm
import matplotlib.gridspec as gridspec
import math
import io, base64, urllib
np.seterr(divide='ignore', invalid='ignore')
from appbe.eda import ux_eda
| ||
eda_obj = ux_eda()
try:
plt.clf()
except:
pass
plt.rcParams.update({'figure.max_open_warning': 0})
sns.set(color_codes=True)
pandasNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
if len(feature) > 4:
numneroffeatures = len(feature)
plt.figure(figsize=(10, numneroffeatures*2))
else:
plt.figure(figsize=(10,5))
for i in enumerate(feature):
dataType = dataframe[i[1]].dtypes
if dataType not in pandasNumericDtypes:
dataframe[i[1]] = pd.Categorical(dataframe[i[1]])
dataframe[i[1]] = dataframe[i[1]].cat.codes
dataframe[i[1]] = dataframe[i[1]].astype(int)
dataframe[i[1]] = dataframe[i[1]].fillna(dataframe[i[1]].mode()[0])
else:
dataframe[i[1]] = dataframe[i[1]].fillna(dataframe[i[1]].mean())
plt.subplots_adjust(hspace=0.5, wspace=0.7, top=1)
plt.subplot(math.ceil((len(feature) / 2)), 2, i[0] + 1)
distname, sse = eda_obj.DistributionFinder(dataframe[i[1]])
try:
ax = sns.distplot(dataframe[i[1]], label=distname)
ax.legend(loc='best')
if newdataframe.empty == False:
dataType = newdataframe[i[1]].dtypes
if dataType not in pandasNumericDtypes:
newdataframe[i[1]] = pd.Categorical(newdataframe[i[1]])
newdataframe[i[1]] = newdataframe[i[1]].cat.codes
newdataframe[i[1]] = newdataframe[i[1]].astype(int)
newdataframe[i[1]] = newdataframe[i[1]].fillna(newdataframe[i[1]].mode()[0])
else:
newdataframe[i[1]] = newdataframe[i[1]].fillna(newdataframe[i[1]].mean())
distname, sse = distribution.DistributionFinder(newdataframe[i[1]])
ax = sns.distplot(newdataframe[i[1]], label=distname)
ax.legend(loc='best')
except Exception as e:
print(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type) + ' ' + str(fname) + ' ' + str(exc_tb.tb_lineno))
pass
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
string = base64.b64encode(buf.read())
uri = urllib.parse.quote(string)
return uri
except Exception as e:
print(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
def getCategoryWordCloud(df):
labels = df.Label.unique()
df_output = pd.DataFrame()
tcolumns=['text']
for label in labels:
df2 = df[df['Label'] == label]
df2 = df2.reset_index()
wordcloud,df_text = getWordCloud(df2,tcolumns)
newrow = {'Label':label,'wordCloud':wordcloud}
df_output = df_output.append(newrow,ignore_index=True)
return(df_output)
def getHighlyCorrelatedFeatureCharts(df, df_top):
numOfRows = df.shape[0]
cratio = 0.01
if (numOfRows < 1000):
cratio = 0.2
elif (numOfRows < 10000):
cratio = 0.1
elif (numOfRows < 100000):
cratio = 0.01
barcolor = ["red", "green", "blue", "goldenrod", "magenta"]
ffig = make_subplots(rows=2, cols=3)
height = 800
rowno = 1
colno = 1
featureCharts = []
try:
for index, row in df_top.iterrows():
feature1 = row['FEATURE_1']
feature2 = row['FEATURE_2']
df_temp = df[[feature1, feature2]]
feature1data = df_temp[feature1]
feature2data = df_temp[feature2]
nUnique = len(feature1data.unique().tolist())
if nUnique / numOfRows >= cratio:
feature1type = 'Continous'
else:
feature1type = 'Category'
nUnique = len(feature2data.unique().tolist())
if nUnique / numOfRows >= cratio:
feature2type = 'Continous'
else:
feature2type = 'Category'
charttype = 0
if feature1type == 'Continous' and feature2type == 'Continous':
df_temp[feature1] = pd.qcut(df_temp[feature1], q=8, duplicates='drop',precision=0)
df_temp[feature1] = df_temp[feature1].astype(str).str.strip('()[]')
feature1type = 'Category'
xaxis = feature1
yaxis = feature2
charttype = 1
if feature1type == 'Category' and feature2type == 'Continous':
xaxis = feature1
yaxis = feature2
charttype = 1
if feature1type == 'Continous' and feature2type == 'Category':
xaxis = feature1 #xaxis = feature2
yaxis = feature2 #yaxis = feature1
charttype = 1
if feature1type == 'Category' and feature2type == 'Category':
if (len(feature1data.unique().tolist()) < len(feature2data.unique().tolist())):
xaxis = feature1 #xaxis = feature2
yaxis = feature2 #yaxis = feature1
else:
xaxis = feature1
yaxis = feature2
if (len(df_temp[xaxis].unique().tolist()) > 5):
df_temp[xaxis] = pd.qcut(df_temp[xaxis], q=5, duplicates='drop',precision=0)
df_temp[xaxis] = df_temp[xaxis].astype(str).str.strip('()[]')
if (len(df_temp[yaxis].unique().tolist()) > 5):
df_temp[yaxis] = pd.qcut(df_temp[yaxis], q=3, duplicates='drop',precision=0)
df_temp[yaxis] = df_temp[yaxis].astype(str).str.strip('()[]')
charttype = 2
# if feature1type == 'Category' and feature2type == 'Category':
if charttype == 2:
uniqueclasses = df_temp[yaxis].unique().tolist()
cfig = go.Figure()
i = 1
for x in uniqueclasses:
df_temp3 = df_temp.loc[df_temp[yaxis] == x]
df_temp2 = df_temp3.groupby(xaxis, as_index=False)[yaxis].count()
if df_temp2[xaxis].dtypes == "object":
df_temp2 = df_temp2.set_index(xaxis).reindex(
natsorted(df_temp2[xaxis].tolist(), key=lambda y: y.lower())).reset_index()
xaxis_data = df_temp2[xaxis].tolist()
yaxis_data = df_temp2[yaxis].tolist()
cfig.add_trace(go.Bar(x=xaxis_data, y=yaxis_data, name=x, marker_color=barcolor[i]))
i = i + 1
if i == 5:
break
cfig.update_layout(barmode='stack', xaxis_title=xaxis, yaxis_title=yaxis)
bargraph = cfig.to_html(full_html=False, default_height=450, default_width=400)
featureCharts.append(bargraph)
if charttype == 1:
df_temp2 = df_temp.groupby(xaxis, as_index=False)[yaxis].mean()
if df_temp2[xaxis].dtypes == "object":
df_temp2 = df_temp2.set_index(xaxis).reindex(
natsorted(df_temp2[xaxis].tolist(), key=lambda y: y.lower())).reset_index()
xaxis_data = df_temp2[xaxis].tolist()
yaxis_data = df_temp2[yaxis].tolist()
cfig = go.Figure()
cfig.add_trace(go.Bar(x=xaxis_data, y=yaxis_data, name='Primary Product', marker_color='blue'))
cfig.update_layout(xaxis_title=xaxis, yaxis_title=yaxis)
bargraph = cfig.to_html(full_html=False, default_height=450, default_width=400)
featureCharts.append(bargraph)
colno += 1
if colno > 3:
colno = 1
rowno += 1
except Exception as e:
print(e)
return (featureCharts)
# EDA Visualization changes
# ----------------------------
def getFeatureCharts(df, graphType, d3_url,mpld3_url):
featureCharts = []
feature1 = df.columns[0]
feature2 = df.columns[1]
import seaborn as sns
import mpld3
fig, ax = plt.subplots(figsize=[10,5])
if graphType == 'marker':
df.plot(ax=ax, marker='o')
# df[['age','education-num']].plot(ax=ax, marker='o')
if graphType == 'area':
df.plot(ax=ax, kind ="area")
# df[['education-num','age']].plot(ax=ax, kind ="area") # UIprb
if graphType == 'hexbin':
df.plot.hexbin(ax=ax, x=feature1, y=feature2, gridsize=2)
if graphType == 'boxplot':
plt.boxplot(df)
if graphType == 'scatter':
ax.scatter(df[feature1], df[feature2])
if graphType == 'regplot':
ax = sns.regplot(x= feature1, y=feature2, data= df, fit_reg = False, scatter_kws={"alpha": 0.5})
if graphType == 'lineplot':
ax = sns.lineplot(x= feature1, y=feature2, data= df)
if graphType == 'barplot':
ax = sns.barplot(x= feature1, y=feature2, data= df)
# ax = sns.barplot(x= 'age', y='fnlwgt', data= df) #Start_prb
ax.legend()
ax.set_xlabel(feature1)
ax.set_ylabel(feature2)
#print(d3_url)
#print(mpld3_url)
html_graph = mpld3.fig_to_html(fig,d3_url=d3_url,mpld3_url=mpld3_url)
if graphType == 'kde':
ax = sns.pairplot(df, kind="kde", height=4, x_vars=feature1,y_vars = feature2)
# ax = sns.pairplot(df[['age','fnlwgt']], kind="kde")
html_graph = mpld3.fig_to_html(ax.fig)
if graphType == 'relplot':
sns.set(style ="darkgrid")
ax = sns.relplot(x =feature1, y =feature2, data = df)
html_graph = mpld3.fig_to_html(ax.fig)
featureCharts.append(html_graph)
return (featureCharts)
# ----------------------------
def MostCommonWords(stopwords, inputCorpus, num_of_words=10):
try:
from collections import Counter
new = inputCorpus.str.split()
new = new.values.tolist()
corpus = [word for i in new for word in i if word not in stopwords]
counter = Counter(corpus)
most = counter.most_common()
x, y = [], []
for word, count in most[: num_of_words + 1]:
x.append(word)
y.append(count)
return pd.DataFrame([x, y], index=['most_common_words', 'freq']).T
except:
print("exception", sys.exc_info())
return False
def removeFeature(df):
featuresList = df.columns.values.tolist()
modelFeatures = featuresList.copy()
datetimeFeatures = []
sequenceFeatures = []
unimportantFeatures = []
featuresRatio = {}
for i in featuresList:
check = match_date_format(df[i])
if check == True:
modelFeatures.remove(i)
continue
seq_check = check_seq_feature(df[i])
if seq_check == True:
modelFeatures.remove(i)
continue
ratio = check_category(df[i])
if ratio != 0:
featuresRatio[i] = ratio
else:
modelFeatures.remove(i)
return featuresList, modelFeatures
def check_category(data):
total_record = len(data)
nUnique = len(data.unique().tolist())
if nUnique == 1:
return 0
ratio = nUnique / total_record
return (ratio)
def check_seq_feature(data):
if data.dtypes in ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']:
total_record = data.count()
count = (data - data.shift() == 1).sum()
if ((total_record - count) == 1):
return True
return False
def match_date_format(data):
data = data.astype(str)
beforecheckcount = (data.count()*80)/100
#####YYYY-MM-DD HH:MM:SS####
check1 = data[data.str.match(
r'(^\\d\\d\\d\\d-(0?[1-9]|1[0-2 | ||
])-(0?[1-9]|[12][0-9]|3[01]) (00|0?[0-9]|1[0-9]|2[0-4]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])$)') == True]
aftercheckcount = check1.count()
if (beforecheckcount <= aftercheckcount):
return True
#####MM/DD/YYYY HH:MM####
check2 = data[data.str.match(
r'(^(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])/(\\d\\d\\d\\d) (00|0?[0-9]|1[0-9]|2[0-4]):([0-9]|[0-5][0-9])$)') == True]
aftercheckcount = check2.count()
if (beforecheckcount <= aftercheckcount):
return True
#####DD-MM-YYYY HH:MM####
check2 = data[data.str.match(
r'(^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[0-2])-(\\d\\d\\d\\d) (00|0?[0-9]|1[0-9]|2[0-4]):([0-9]|[0-5][0-9])$)') == True]
aftercheckcount = check2.count()
if (beforecheckcount <= aftercheckcount):
return True
#####YYYY/MM/DD####
check2 = data[data.str.match(r'(^\\d\\d\\d\\d/(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])$)') == True]
aftercheckcount = check2.count()
if (beforecheckcount <= aftercheckcount):
return True
#####MM/DD/YYYY####
check2 = data[data.str.match(r'(^(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])/(\\d\\d\\d\\d)$)') == True]
aftercheckcount = check2.count()
if (beforecheckcount <= aftercheckcount):
return True
return False
def check_text_features(df, modelFeatures):
aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
textFeature = []
for i in enumerate(modelFeatures):
dataType = df[i[1]].dtypes
numOfRows = df.shape[0]
if dataType not in aionNumericDtypes:
if dataType != 'bool':
nUnique = len(df[i[1]].unique().tolist())
textnumbericratio = 0.01
if (numOfRows < 1000):
textnumbericratio = 0.2
elif (numOfRows < 10000):
textnumbericratio = 0.1
elif (numOfRows < 100000):
textnumbericratio = 0.01
if nUnique / numOfRows >= textnumbericratio:
textFeature.append(i[1])
return (textFeature)
def getWordCloud(df, text_columns):
df_text = pd.DataFrame()
stopwords = set(STOPWORDS)
if (len(text_columns) > 1):
df_text['combined'] = df[text_columns].apply(lambda row: ' '.join(row.values.astype(str)), axis=1)
features = ['combined']
else:
df_text[['combined']] = df[text_columns]
features = ['combined']
df_text[features[0]] = df_text[features[0]].fillna("NA")
textCorpus = df_text[features[0]]
from text import TextProcessing
tp = TextProcessing.TextProcessing()
preprocessed_text = tp.transform(textCorpus)
df_text['combined'] = preprocessed_text
df_text_list = df_text.values.tolist()
comment_words = ""
for val in df_text_list:
val = str(val)
tokens = val.split()
for i in range(len(tokens)):
tokens[i] = tokens[i].lower()
comment_words += " ".join(tokens) + " "
wordcloud = WordCloud(stopwords=stopwords).generate(comment_words)
try:
plt.clf()
except:
pass
try:
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.tight_layout(pad=0)
image = io.BytesIO()
plt.savefig(image, format='png')
image.seek(0)
string = base64.b64encode(image.read())
image_64 = 'data:image/png;base64,' + urllib.parse.quote(string)
except Exception as inst:
print(inst)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
image_64=''
return (image_64, df_text)
def getTopTextFeatures(df_text):
stopwords = set(STOPWORDS)
commonfeatures = MostCommonWords(stopwords, df_text['combined'])
xaxis_data = commonfeatures['most_common_words'].tolist()
yaxis_data = commonfeatures['freq'].tolist()
import plotly.graph_objects as go
cfig = go.Figure()
cfig.add_trace(go.Bar(x=xaxis_data, y=yaxis_data, name='Feature Importance'))
cfig.update_layout(barmode='stack', xaxis_title='Features')
bargraph = cfig.to_html(full_html=False, default_height=450, default_width=1000)
return (bargraph)
def getPCATop10Features(df, modelFeatures):
aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
categorial_features = []
for i in enumerate(modelFeatures):
dataType = df[i[1]].dtypes
if dataType not in aionNumericDtypes:
categorial_features.append(i[1])
df[i[1]] = pd.Categorical(df[i[1]])
df[i[1]] = df[i[1]].cat.codes
df[i[1]] = df[i[1]].astype(int)
df[i[1]] = df[i[1]].fillna(df[i[1]].mode()[0])
else:
df[i[1]] = df[i[1]].fillna(df[i[1]].mean())
from sklearn.decomposition import PCA
pca = PCA(n_components=2).fit(df)
map = pd.DataFrame(pca.components_, columns=modelFeatures)
map = map.diff(axis=0).abs()
map = map.iloc[1]
map = map.sort_values(ascending=False).head(10)
yaxis_data = map.tolist()
xaxis_data = map.index.values.tolist()
import plotly.graph_objects as go
cfig = go.Figure()
cfig.add_trace(go.Bar(x=xaxis_data, y=yaxis_data, name='Feature Importance'))
cfig.update_layout(barmode='stack', xaxis_title='Features')
bargraph = cfig.to_html(full_html=False, default_height=450, default_width=1000)
return (bargraph)
def getCorrelationMatrix(df):
try:
#from dython.nominal import associations
if len(df.columns) > 25:
df3 = df[df.columns[0:24]]
else:
df3 = df.copy()
cor_mat= associations(df3,compute_only=True)
cor_mat=cor_mat['corr']
#cor_mat = df3.corr()
cor_mat = cor_mat.astype(float).round(2)
#print(cor_mat)
z = cor_mat.values.tolist()
fig = ff.create_annotated_heatmap(z, x=cor_mat.columns.tolist(), y=cor_mat.index.tolist(), annotation_text=z,
colorscale='Blues')
fig.layout.yaxis.automargin = True
correlationgraph = fig.to_html(full_html=True, default_height=450, default_width=1000)
except Exception as e:
print(e)
correlationgraph = ''
return (correlationgraph)
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
from appbe import exploratory_Analysis as ea
import pandas as pd
from appbe.checkConfiguration import start_check
import json
import os
import ast
import time
import numpy as np
from appfe.modelTraining.models import usecasedetails
from appfe.modelTraining.models import Existusecases
# from modelTraining.models import view
from appbe.aion_config import kafka_setting
from appbe.aion_config import running_setting
from appbe.s3buckets import get_s3_bucket
from appbe.gcsbuckets import get_gcs_bucket
from appbe import help_Text as ht
def is_value_na( value):
if isinstance( value, str):
return value.strip().lower() in ['','na','none']
return not value
def set_ts_preprocessing(request,configSettingsJson): #Task 13052 Timeseries Preprocessing
interpolationType = request.POST.get('interpolationType')
ts_config = configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']
for key in ts_config['interpolation']:
configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']['interpolation'][
key] = 'False'
if interpolationType != 'na':
configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']['interpolation'][
interpolationType] = 'True'
ts_config['rollingWindow'] = request.POST.get('rollingWindow')
if ts_config['rollingWindow'] == 'True':
ts_config['rollingWindowSize'] = request.POST.get('rollWindowsize')
aggregation = request.POST.get('aaggregationType')
for key in ts_config['aggregation']['type']:
ts_config['aggregation']['type'][key]='False'
if is_value_na(aggregation) == False:
ts_config['aggregation']['type'][aggregation] = 'True'
granularityType = request.POST.get('unitType')
granularitySize = request.POST.get('garnularitysize')
for key in ts_config['aggregation']['granularity']['unit']:
ts_config['aggregation']['granularity']['unit'][key] = 'False'
ts_config['aggregation']['granularity']['unit'][granularityType]='True'
ts_config['aggregation']['granularity']['size'] = granularitySize
configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']= ts_config
return configSettingsJson
def update_granularity(configSettingsJson,datapath=None):
try:
from AION.appbe.utils import set_true_option
import pandas as pd
from pathlib import Path
MINUTES = 60
if not is_value_na(configSettingsJson['basic']['dateTimeFeature']):
if not datapath:
datapath = configSettingsJson['basic']['dataLocation']
if Path( datapath).exists():
df = pd.read_csv(datapath, nrows=2)
if isinstance( configSettingsJson['basic']['dateTimeFeature'], list):
datetime_feature = configSettingsJson['basic']['dateTimeFeature'][0]
else:
datetime_feature = configSettingsJson['basic']['dateTimeFeature']
datetime = pd.to_datetime(df[ datetime_feature])
if len(datetime) > 1:
time_delta = (datetime[1] - datetime[0]).total_seconds()
granularity_unit = configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']['aggregation']['granularity']['unit']
if time_delta < (1 * MINUTES):
set_true_option(granularity_unit, key='second')
elif time_delta < (60 * MINUTES):
set_true_option(granularity_unit, key='minute')
elif time_delta < (24 * 60 * MINUTES):
set_true_option(granularity_unit, key='hour')
elif time_delta < (7 * 24 * 60 * MINUTES):
set_true_option(granularity_unit, key='day')
elif time_delta < (30 * 24 * 60 * MINUTES):
set_true_option(granularity_unit, key='week')
elif time_delta < (365 * 24 * 60 * MINUTES):
set_true_option(granularity_unit, key='month')
else:
set_true_option(granularity_unit, key='year')
return configSettingsJson
except Exception as e:
print(f'\\nIgnoring error during granularity unit conversion\\n:{str(e)}')
return configSettingsJson
def save(request):
try:
status = 'pass'
msg = ""
DEPLOY_LOCATION = request.session['deploylocation']
if request.method == 'POST':
submittype = request.POST.get('BasicSubmit')
if submittype != 'BasicDefault':
filterjson = 'NA'
timegroupingjson = 'NA'
groupingjson = 'NA'
if request.POST.get('filters') != '':
filterjson = str(json.loads(request.POST.get('filters')))
if request.POST.get('timegroup') != '':
timegroupingjson = str(json.loads(request.POST.get('timegroup')))
if request.POST.get('idgroup') != '':
groupingjson = str(json.loads(request.POST.get('idgroup')))
configFile = request.session['config_json']
f = open(configFile, "r")
configSettings = f.read()
f.close()
configSettings | ||
Json = json.loads(configSettings)
temp = {}
# Retraing settings changes
# -------- S T A R T --------
prbType = request.POST.get('ProblemType')
if prbType is None:
prbType = request.POST.get('tempProblemType')
# temp['ProblemType'] = request.POST.get('ProblemType')
# request.session['Problem'] = request.POST.get('ProblemType')
temp['ProblemType'] = prbType
request.session['Problem'] = request.POST.get('ProblemType')
# ---------------------------
temp['ModelName'] = request.session['usecaseid']
temp['Version'] = str(request.session['ModelVersion'])
temp['InputFeatures'] = request.POST.getlist('IncInputFeatures')
temp['dataLocation'] = str(request.session['datalocation'])
onlinelearning=request.POST.get('onlineLearning',None)
if (onlinelearning is not None):
if onlinelearning.lower() == 'onlinelearning':
configSettingsJson['basic']['onlineLearning'] = 'True'
if onlinelearning.lower() == 'distributedlearning':
configSettingsJson['basic']['distributedLearning'] = 'True'
temp['InputFeatures'] = request.POST.getlist('IncInputFeatures')
temp['TargetFeatures'] = request.POST.getlist('TargetFeatures')
temp['DateTimeFeatures'] = ''
temp['IndexFeatures'] = ''
for x in configSettingsJson['advance']['profiler']['normalization'].keys():
configSettingsJson['advance']['profiler']['normalization'][x] = 'False'
configSettingsJson['advance']['profiler']['normalization']['standardScaler'] = 'True'
for x in configSettingsJson['advance']['profiler']['numericalFillMethod'].keys():
configSettingsJson['advance']['profiler']['numericalFillMethod'][x] = 'False'
configSettingsJson['advance']['profiler']['numericalFillMethod']['Mean'] = 'True'
if onlinelearning.lower() == 'distributedlearning':
for x in configSettingsJson['advance']['profiler']['categoricalFillMethod'].keys():
configSettingsJson['advance']['profiler']['categoricalFillMethod'][x] = 'False'
configSettingsJson['advance']['profiler']['categoricalFillMethod']['MostFrequent'] = 'True'
for x in configSettingsJson['advance']['profiler']['categoryEncoding'].keys():
configSettingsJson['advance']['profiler']['categoryEncoding'][x] = 'False'
configSettingsJson['advance']['profiler']['categoryEncoding']['OneHotEncoding'] = 'True'
configSettingsJson['advance']['profiler']['normalization']['standardScaler'] = 'False'
for x in configSettingsJson['advance']['selector']['featureEngineering'].keys():
if x != 'numberofComponents':
configSettingsJson['advance']['selector']['featureEngineering'][x] = 'False'
elif prbType == 'llmFineTuning':
if configSettingsJson['basic']['preprocessing']['llmFineTuning']['unstructuredData'] == 'False':
temp['InputFeatures'] = request.POST.getlist('IncInputFeatures')
temp['TargetFeatures'] = request.POST.getlist('TargetFeatures')
contextFeatures = request.POST.getlist('contextFeatures')
configSettingsJson['basic']['contextFeature'] = ",".join([model for model in contextFeatures])
temp['DateTimeFeatures'] = ''
temp['IndexFeatures'] = ''
if request.POST.get('promptfriendlyname') != '':
configSettingsJson['basic']['preprocessing']['llmFineTuning']['friendlyNames']['prompt'] = request.POST.get('promptfriendlyname')
else:
configSettingsJson['basic']['preprocessing']['llmFineTuning']['friendlyNames']['prompt'] = 'Instruction'
if request.POST.get('responsefriendlyname') != '':
configSettingsJson['basic']['preprocessing']['llmFineTuning']['friendlyNames']['response'] = request.POST.get('responsefriendlyname')
else:
configSettingsJson['basic']['preprocessing']['llmFineTuning']['friendlyNames']['response'] = ''
else:
if request.session['datatype'] == 'LLM_Document':
for x in configSettingsJson['basic']['preprocessing']['llmFineTuning']['document'].keys():
configSettingsJson['basic']['preprocessing']['llmFineTuning']['document'][x] = 'False'
configSettingsJson['basic']['preprocessing']['llmFineTuning']['document'][request.POST.get('dataPreprocessing')] = 'True'
if request.session['datatype'] == 'LLM_Code':
for x in configSettingsJson['basic']['preprocessing']['llmFineTuning']['objective'].keys():
configSettingsJson['basic']['preprocessing']['llmFineTuning']['objective'][x] = 'False'
configSettingsJson['basic']['preprocessing']['llmFineTuning']['objective'][request.POST.get('llmObjective')] = 'True'
for x in configSettingsJson['basic']['preprocessing']['llmFineTuning']['code'].keys():
configSettingsJson['basic']['preprocessing']['llmFineTuning']['code'][x] = 'False'
configSettingsJson['basic']['preprocessing']['llmFineTuning']['code'][request.POST.get('dataPreprocessing')] = 'True'
else:
configSettingsJson['basic']['onlineLearning'] = 'False'
configSettingsJson['basic']['distributedLearning'] = 'False'
temp['InputFeatures'] = request.POST.getlist('InputFeatures')
temp['TargetFeatures'] = request.POST.getlist('TargetFeatures')
temp['DateTimeFeatures'] = request.POST.getlist('DateTimeFeatures')
temp['IndexFeatures'] = request.POST.getlist('IndexFeatures')
if (configSettingsJson['basic']['algorithms']['timeSeriesAnomalyDetection']['AutoEncoder'] == 'True'):#task 11997
if (request.POST.get('analysis') == 'MultiVariate'):
configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['multiVariate'] = 'True' #task 11997
configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['uniVariate'] = 'False' #task 11997
else:
#print(configSettingsJson)
configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['uniVariate'] = 'True'
configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['multiVariate'] = 'False' #task 11997
temp['UserID'] = ''
temp['ItemID'] = ''
temp['rating'] = ''
temp['secondDocFeature'] = ''
temp['firstDocFeature'] = ''
temp['invoiceNoFeature'] = ''
temp['itemFeature'] = ''
model = ''
if temp['ProblemType'].lower() == 'recommendersystem':
model = request.POST.get('MachineLearningModels')
if model == 'ItemRating':
temp['ProblemType'] = 'RecommenderSystem'
temp['MachineLearningModels'] = ['ItemRating']
temp['DeepLearningModels'] = ''
temp['UserID'] = request.POST.get('UserID')
temp['ItemID'] = request.POST.get('ItemID')
temp['rating'] = request.POST.get('rating')
temp['InputFeatures'] = []
temp['InputFeatures'].append(temp['UserID'])
temp['InputFeatures'].append(temp['ItemID'])
temp['InputFeatures'].append(temp['rating'])
if model == 'TextSimilarity-Siamese':
temp['ProblemType'] = 'recommenderSystem'
temp['MachineLearningModels'] = ['TextSimilarity-Siamese']
temp['secondDocFeature'] = request.POST.get('secondDocFeature')
temp['firstDocFeature'] = request.POST.get('firstDocFeature')
temp['InputFeatures'] = []
temp['InputFeatures'].append(temp['secondDocFeature'])
temp['InputFeatures'].append(temp['firstDocFeature'])
if model == 'AssociationRules-Apriori':
temp['ProblemType'] = 'recommenderSystem'
temp['DeepLearningModels'] = ''
temp['MachineLearningModels'] = ['AssociationRules-Apriori']
temp['invoiceNoFeature'] = request.POST.get('associationRuleInvoiceNo')
temp['itemFeature'] = request.POST.get('associationRuleItem')
temp['InputFeatures'] = []
temp['InputFeatures'].append(temp['invoiceNoFeature'])
temp['InputFeatures'].append(temp['itemFeature'])
temp['ScoringCriteria'] = request.POST.get('ScoringCriteria')
if temp['ProblemType'].lower() not in ['recommendersystem','textsimilarity','associationrules','llmfinetuning']:
temp['MachineLearningModels'] = request.POST.getlist('MachineLearningModels')
temp['DeepLearningModels'] = request.POST.getlist('SelectDeepLearningModels')
elif temp['ProblemType'].lower() == 'llmfinetuning':
temp['MachineLearningModels'] = request.POST.getlist('MachineLearningModels')
model = temp['MachineLearningModels'][0]
supportedModelsSize = configSettingsJson['basic']['modelSize'][temp['ProblemType']][model]
selectedModelSize = request.POST.get('modelSize')
for x in supportedModelsSize.keys():
configSettingsJson['basic']['modelSize'][temp['ProblemType']][model][x] = 'False'
configSettingsJson['basic']['modelSize'][temp['ProblemType']][model][selectedModelSize] = 'True'
temp['noofforecasts'] = request.POST.get('noofforecasts')
temp['inlierLabels'] = request.POST.get('inlierLabels')
#temp['filterExpression'] = request.POST.get('filterExpression')
if temp['ProblemType'].lower() in ['clustering','topicmodelling','similarityidentification','contextualsearch']:
temp['TargetFeatures'] = ''
configSettingsJson['basic']['modelName'] = temp['ModelName']
configSettingsJson['basic']['modelVersion'] = temp['Version']
configSettingsJson['basic']['dataLocation'] = str(temp['dataLocation'])
configSettingsJson['basic']['deployLocation'] = DEPLOY_LOCATION
if configSettingsJson['basic']['preprocessing']['llmFineTuning']['unstructuredData'] == 'False':
configSettingsJson['basic']['trainingFeatures'] = ",".join([model for model in temp['InputFeatures']])
configSettingsJson['basic']['dateTimeFeature'] = ",".join([model for model in temp['DateTimeFeatures']])
configSettingsJson['basic']['targetFeature'] = ",".join([model for model in temp['TargetFeatures']])
configSettingsJson['basic']['indexFeature'] = ",".join([model for model in temp['IndexFeatures']])
if filterjson == 'NA':
configSettingsJson['basic']['filter'] = 'NA'
else:
configSettingsJson['basic']['filter'] = eval(filterjson)
if timegroupingjson == 'NA':
configSettingsJson['basic']['timegrouper'] = 'NA'
else:
configSettingsJson['basic']['timegrouper'] = eval(timegroupingjson)
if groupingjson == 'NA':
configSettingsJson['basic']['group'] = 'NA'
else:
configSettingsJson['basic']['group'] = eval(groupingjson)
problemtyp = configSettingsJson['basic']['analysisType']
for i in list(problemtyp.keys()):
configSettingsJson['basic']['analysisType'][i]='False'
algorithm = configSettingsJson['basic']['algorithms']
for i in list(algorithm.keys()):
for x in list(configSettingsJson['basic']['algorithms'][i].keys()):
if x not in ['textSimilarityConfig','itemRatingConfig','associationRulesConfig','textSummarization']:
configSettingsJson['basic']['algorithms'][i][x] = 'False'
configSettingsJson['basic']['analysisType'][temp['ProblemType'][0].lower() + temp['ProblemType'][1:]] = 'True'
# configSettingsJson['basic']['problem_type'] = temp['ProblemType']
scoring = configSettingsJson['basic']['scoringCriteria']
for i in list(scoring.keys()):
for x in list(configSettingsJson['basic']['scoringCriteria'][i].keys()):
configSettingsJson['basic']['scoringCriteria'][i][x] = 'False'
if temp['ProblemType'].lower() in ["classification","regression","survivalanalysis","similarityidentification","timeseriesforecasting","contextualsearch"]: #task 11997
configSettingsJson['basic']['scoringCriteria'][temp['ProblemType'][0].lower() + temp['ProblemType'][1:]][temp['ScoringCriteria']] = 'True'
# configSettingsJson['basic']['problem_type'] = temp['ProblemType']
# configSettingsJson['basic']['scoringCriteria'] = temp['ScoringCriteria']
configSettingsJson['basic']['noofforecasts'] = temp['noofforecasts']
configSettingsJson['basic']['inlierLabels'] = temp['inlierLabels']
#configSettingsJson['basic']['filterExpression'] = temp['filterExpression']
configSettingsJson['basic']['algorithms']['recommenderSystem']['itemRatingConfig']['userID'] = temp['UserID']
configSettingsJson['basic']['algorithms']['recommenderSystem']['itemRatingConfig']['itemID'] = temp['ItemID']
configSettingsJson['basic']['algorithms']['recommenderSystem']['itemRatingConfig']['rating'] = temp['rating']
configSettingsJson['basic']['algorithms']['recommenderSystem']['textSimilarityConfig']['baseFeature'] = temp['firstDocFeature']
configSettingsJson['basic']['algorithms']['recommenderSystem']['textSimilarityConfig']['comparisonFeature'] = temp['secondDocFeature']
configSettingsJson['basic']['algorithms']['recommenderSystem']['associationRulesConfig']['invoiceNoFeature'] = temp['invoiceNoFeature']
configSettingsJson['basic']['algorithms']['recommenderSystem']['associationRulesConfig']['itemFeature'] = temp['itemFeature']
for x in temp['MachineLearningModels']:
if temp['ProblemType'].lower() =='associationrules' or temp['ProblemType'].lower() == 'textsimilarity':
temp['ProblemType'] = 'recommenderSystem'
if request.POST.get('SearchType') != 'NAS' and request.POST.get('SearchType') != 'GoogleModelSearch'and request.POST.get('SearchType') != 'AutoGluon':
configSettingsJson['basic']['algorithms'][temp['ProblemType'][0].lower() + temp['ProblemType'][1:]][x] = 'True'
#for y in temp['DeepLearningModels']:
# configSettingsJson['basic']['algorithms'][temp['ProblemType'][0].lower() + temp['ProblemType'][1:]][y] = 'True'
configSettingsJson['basic']['output']['profilerStage'] = 'True'
config | ||
SettingsJson['basic']['output']['selectorStage'] = 'True'
for key in configSettingsJson['advance']['profiler']['textConversionMethod']:
configSettingsJson['advance']['profiler']['textConversionMethod'][key] = 'False'
if temp['ProblemType'].lower() != 'topicmodelling':
configSettingsJson['advance']['profiler']['textConversionMethod']['TF_IDF'] ='True'
else:
configSettingsJson['advance']['profiler']['textConversionMethod']['CountVectors'] ='True'
#print('============================')
#print(temp['ProblemType'].lower())
#print('============================')
if temp['ProblemType'].lower() == 'textsummarization':
configSettingsJson['basic']['algorithms']['textSummarization']['Text Summarization'] = 'True'
configSettingsJson['basic']['textSummarization']['KeyWords'] = str(request.POST.get('addKeywordsForSummarization'))
configSettingsJson['basic']['textSummarization']['pathForKeywordFile'] = str(request.POST.get('DataFilePath'))
if temp['ProblemType'].lower() not in ['recommendersystem','textsummarization','llmfinetuning']:
if configSettingsJson['basic']['onlineLearning'] != 'True' and configSettingsJson['basic']['distributedLearning'] != 'True':
jsonarr =request.POST.get('jsonarr')
res = ast.literal_eval(jsonarr)
for x in res:
if x['type'].lower() == 'text':
configSettingsJson['advance']['selector']['featureSelection']['allFeatures'] = 'False'
configSettingsJson['advance']['selector']['featureSelection']['statisticalBased'] = 'True'
configSettingsJson['advance']['selector']['featureSelection']['modelBased'] = 'False'
if len(request.POST.get('traindfeatures').split(',')) > 30:
configSettingsJson['advance']['selector']['featureSelection']['allFeatures'] = 'False'
configSettingsJson['advance']['selector']['featureSelection']['statisticalBased'] = 'True'
configSettingsJson['advance']['selector']['featureSelection']['modelBased'] = 'False'
configSettingsJson['advance']['profiler']['featureDict'] = res
configSettingsJson['basic']['indexFeature'] = request.POST.get('indexfeatures')
configSettingsJson['basic']['trainingFeatures'] = request.POST.get('traindfeatures')
configSettingsJson['basic']['dateTimeFeature'] = request.POST.get('datefeatures')
if request.POST.get('SearchType') == 'GoogleModelSearch':
configSettingsJson['basic']['algorithms'][temp['ProblemType'][0].lower() + temp['ProblemType'][1:]]['GoogleModelSearch_DNN'] = 'True'
configSettingsJson['basic']['output']['profilerStage']= 'True'
#---------- Time series Changes Task 13052 -----------------
if temp['ProblemType'].lower() == 'timeseriesforecasting':
configSettingsJson = set_ts_preprocessing(request,configSettingsJson)
status,msg= start_check(configSettingsJson)
updatedConfigSettings = json.dumps(configSettingsJson)
updatedConfigFile = request.session['config_json']
with open(updatedConfigFile, "w") as fpWrite:
fpWrite.write(updatedConfigSettings)
fpWrite.close()
request.session['ModelStatus'] = 'Not Trained'
selected_use_case = request.session['UseCaseName']
ModelVersion = request.session['ModelVersion']
ModelStatus = request.session['ModelStatus']
request.session['currentstate'] = 1
from appbe.telemetry import UpdateTelemetry
UpdateTelemetry(request.session['usecaseid']+'-'+str(request.session['ModelVersion']),'ProblemType',prbType)
UpdateTelemetry(request.session['usecaseid']+'-'+str(request.session['ModelVersion']),'Operation','Configured')
context = {'tab': 'configure', 'temp': temp,'advconfig': configSettingsJson,
'basic_status_msg': 'Configuration Done',
'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion,
'currentstate': request.session['currentstate'], 'selected': 'modeltraning','training':True,'basic_help':ht.basic_help}
# return render(request, 'basicconfig.html', context)
if submittype == 'BasicDefault':
temp = {}
temp['ModelName'] = request.session['UseCaseName']
temp['Version'] = request.session['ModelVersion']
dataLocation = str(request.session['datalocation'])
df = pd.read_csv(dataLocation, encoding='latin1')
featuresList = df.columns.values.tolist()
datetimeFeatures = []
sequenceFeatures = []
unimportantFeatures = []
featuresRatio = {}
for i in featuresList:
check = ea.match_date_format(df[i])
if check == True:
datetimeFeatures.append(i)
unimportantFeatures.append(i)
seq_check = ea.check_seq_feature(df[i])
if seq_check == True:
sequenceFeatures.append(i)
unimportantFeatures.append(i)
ratio = ea.check_category(df[i])
if ratio != 0:
featuresRatio[i] = ratio
else:
unimportantFeatures.append(i)
targetFeature = min(featuresRatio, key=featuresRatio.get)
unimportantFeatures.append(targetFeature)
config = {}
config['modelName'] = request.session['UseCaseName']
config['modelVersion'] = request.session['ModelVersion']
config['datetimeFeatures'] = datetimeFeatures
config['sequenceFeatures'] = sequenceFeatures
config['FeaturesList'] = featuresList
config['unimportantFeatures'] = unimportantFeatures
config['targetFeature'] = targetFeature
request.session['currentstate'] = 1
context = {'tab': 'configure', 'temp': temp, 'config': config,
'currentstate': request.session['currentstate'], 'selected': 'modeltraning'}
except Exception as e:
print(e)
import sys
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
return status,msg,context
def openbasicconf(request):
# 10012:Decision Threshold related Changes
data_is_under_RAM_threshold = True
updatedConfigFile = request.session['config_json']
f = open(updatedConfigFile, "r+")
configSettingsData = f.read()
configSettingsJson = json.loads(configSettingsData)
temp = {}
# temp['ModelName'] = request.session['UseCaseName']
# temp['Version'] = request.session['ModelVersion']
if request.session['datatype'] == 'Video' or request.session['datatype'] == 'Image' or request.session['datatype'] == 'Document':
folderLocation = str(request.session['datalocation'])
dataFile = os.path.join(folderLocation, request.session['csvfullpath'])
else:
dataFile = str(request.session['datalocation'])
# -------------------------------- 10012:Decision Threshold related Changes S T A R T -------------------------------
from appbe.dataIngestion import checkRAMThreshold
data_is_under_RAM_threshold = checkRAMThreshold(request.session['datalocation'])
# ------------------------------------------------------ E N D ------------------------------------------------------
# Retraing settings changes
# -------- S T A R T --------
IsReTrainingCase = False
if request.session['IsRetraining'] == 'Yes':
IsReTrainingCase = True
IsSameFeatures = True
# ---------------------------
featuresList = configSettingsJson['basic']['featureList']
unimportantFeatures = []
modelfeatures = configSettingsJson['basic']['trainingFeatures']
for x in featuresList:
if x not in modelfeatures:
unimportantFeatures.append(x)
config = {}
config['ModelName'] = request.session['usecaseid']
config['Version'] = request.session['ModelVersion']
config['datetimeFeatures'] = configSettingsJson['basic']['dateTimeFeature'] # .split(",")
if configSettingsJson['basic']['indexFeature']:
config['sequenceFeatures'] = configSettingsJson['basic']['indexFeature'] # .split(",")
config['FeaturesList'] = featuresList
config['unimportantFeatures'] = unimportantFeatures
config['targetFeature'] = configSettingsJson['basic']['targetFeature'].split(",")
problemtypes = configSettingsJson['basic']['analysisType']
onlineLearning = configSettingsJson['basic']['onlineLearning']
problem_type = ""
for k in problemtypes.keys():
if configSettingsJson['basic']['analysisType'][k] == 'True':
problem_type = k
break
#print('123',problem_type)
config['ProblemType'] = problem_type
# config['ProblemType'] = configSettingsJson['basic']['problem_type']
scoring = configSettingsJson['basic']['scoringCriteria']
scoringCriteria = ""
for k in scoring.keys():
if configSettingsJson['basic']['scoringCriteria'][k] == 'True':
scoringCriteria = k
break
config['ScoringCriteria'] = scoringCriteria
# config['ProblemType'] = configSettingsJson['basic']['problem_type']
# config['ScoringCriteria'] = configSettingsJson['basic']['scoringCriteria']
selected_use_case = request.session['UseCaseName']
ModelVersion = request.session['ModelVersion']
ModelStatus = request.session['ModelStatus']
if 'NoOfRecords' in request.session:
records = request.session['NoOfRecords']
else:
records = 'NA'
if request.session['finalstate'] <= 1:
request.session['finalstate'] = 1
request.session['currentstate'] = 1
# dataFile = str(request.session['datalocation'])
# df = pd.read_csv(dataFile,encoding='utf8')
if 'NoOfRecords' in request.session:
noofforecast = 20
else:
noofforecast = 20
config['noofforecasts'] = noofforecast
if 'numericFeature' in request.session:
numericFeature = request.session['numericFeature']
else:
numericFeature = ''
problemType = 'classification'
for key in configSettingsJson['basic']['analysisType']:
if configSettingsJson['basic']['analysisType'][key] == 'True':
problemType = key
break
scoringCreteria = 'NA'
if problemType in ['classification','regression','survivalAnalysis','timeSeriesForecasting']: #task 11997
for key in configSettingsJson['basic']['scoringCriteria'][problemType]:
if configSettingsJson['basic']['scoringCriteria'][problemType][key] == 'True':
scoringCreteria = key
break
selectAlgo = ""
if problemType in ['classification','regression','timeSeriesForecasting',
'timeSeriesAnomalyDetection',
'recommenderSystem','clustering','anomalyDetection','topicModelling','survivalAnalysis','videoForecasting','imageClassification','objectDetection','stateTransition','llmFineTuning']: #task 11997
for key in configSettingsJson['basic']['algorithms'][problemType]:
if configSettingsJson['basic']['algorithms'][problemType][key] == 'True':
if selectAlgo != "":
selectAlgo += ','
selectAlgo += key
modelSize = ''
if problemType == 'llmFineTuning':
for key in configSettingsJson['basic']['modelSize']['llmFineTuning'][selectAlgo].keys():
if configSettingsJson['basic']['modelSize']['llmFineTuning'][selectAlgo][key] == 'True':
modelSize = key
break
featuresdict = [feature['feature'] for feature in configSettingsJson['advance']['profiler']['featureDict']]
context = {'tab': 'tabconfigure','modelSize':modelSize,'featuresdict':featuresdict, 'configsettings': configSettingsJson, 'temp': temp, 'config': config,'numericFeature':numericFeature,'onlineLearning':onlineLearning,
'noOfRecords': records, 'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,'problemType':problemType,'scoringCreteria':scoringCreteria,'selectAlgo':selectAlgo,
'ModelVersion': ModelVersion, 'currentstate': request.session['currentstate'],
'finalstate': request.session['finalstate'], 'selected': 'modeltraning','IsSameFeatures':IsSameFeatures,'IsReTrainingCase':IsReTrainingCase,'basic_help':ht.basic_help
# 10012:Decision Threshold related changes
, 'DLCheckpoint':data_is_under_RAM_threshold}
return context
def gotoconf(request):
selected_use_case = request.session['UseCaseName']
ModelVersion = request.session['ModelVersion']
ModelStatus = request.session['ModelStatus']
try:
# 10012:Decision Threshold related Changes
data_is_under_RAM_threshold = True
ModelName = usecasedetails.objects.get(id=request.session['ModelName'])
Version = request.session['ModelVersion']
import os
if request.session['datatype'] in ['Video', 'Image','Document','Object']:
folderLocation = str(request.session['datalocation'])
dataFile = os.path.join(folderLocation, request.session['csvfullpath'])
else:
dataFile = str(request.session['datalocation'])
# -------------------------------- 10012:Decision Threshold related Changes S T A R T -------------------------------
from appbe.dataIngestion import checkRAMThreshold
data_is_under_RAM_threshold = checkRAMThreshold(request.session['datalocation'])
# ------------------------------------------------------ E N D ------------------------------------------------------
if request.session['datatype'] not in ['LLM_Document','LLM_Code']:
from appbe.eda import ux_eda
if 'delimiter' not in request.session:
request.session['delimiter'] = ','
if 'textqualifier' not in request.session:
request.session['textqualifier'] = '"'
eda_obj = ux_eda(dataFile,request.session['delimiter'],request.session['textqualifier'],optimize=1)
featuresList,datetimeFeatures,sequenceFeatures,constantFeature,textFeature,targetFeature,numericCatFeatures,numericFeature,catFeatures = eda_obj.getFeatures()
else:
featuresList = []
featuresList.append('Instruction')
datetimeFeatures=[]
sequenceFeatures=[]
constantFeature=[]
textFeature=[]
targetFeature='Response'
numericCatFeatures = []
numericFeature=[]
catFeatures=[]
featuresListJson = []
for x in featuresList:
featureOperation={}
featureOperation['feature'] = x
if x in datetimeFeatures:
featureOperation['type'] = 'date'
featureOperation['fillMethod'] = 'na' | ||
featureOperation['categoryEncoding'] = 'na'
elif x in textFeature:
featureOperation['type'] = 'text'
featureOperation['fillMethod'] = 'na'
featureOperation['categoryEncoding'] = 'na'
elif x in sequenceFeatures:
featureOperation['type'] = 'index'
featureOperation['fillMethod'] = 'median'
featureOperation['categoryEncoding'] = 'na'
elif (x in catFeatures) or (x in constantFeature):
featureOperation['type'] = 'categorical'
featureOperation['fillMethod'] = 'mode'
featureOperation['categoryEncoding'] = 'targetEncoding'
else:
featureOperation['type'] = 'numerical'
featureOperation['fillMethod'] = 'medium'
featureOperation['categoryEncoding'] = 'na'
featureOperation['outlierDetection'] = 'disable'
featureOperation['outlierOperation'] = 'nochange'
featureOperation['normalizer'] = 'none'
featuresListJson.append(featureOperation)
request.session['numericFeature'] = numericFeature
records = 0
import os
if os.path.isfile(dataFile):
for chunk in pd.read_csv(dataFile, chunksize=20000,encoding="utf-8",encoding_errors= 'replace'):
records = records+len(chunk)
request.session['NoOfRecords'] = records
filetimestamp = str(int(time.time()))
CONFIG_FILE_PATH = request.session['configfilepath']
config_json_filename = os.path.join(CONFIG_FILE_PATH, 'AION_' + filetimestamp + '.json')
outputfile = os.path.join(CONFIG_FILE_PATH, 'AION_OUTPUT_' + filetimestamp + '.json')
request.session['outputfilepath'] = str(outputfile)
modelname = request.session['usecaseid']
modelname = modelname.replace(" ", "_")
DEPLOY_LOCATION = request.session['deploylocation']
request.session['logfilepath'] = os.path.join(DEPLOY_LOCATION, modelname,str(Version),'log','model_training_logs.log')
request.session['config_json'] = config_json_filename
#request.session['ModelVersion'] = Version
request.session['ModelStatus'] = 'Not Trained'
# p = Existusecases(DataFilePath=dataFile, DeployPath=DEPLOY_LOCATION, Status='Not Trained',
# ConfigPath=config_json_filename, Version=Version, ModelName=ModelName,
# TrainOuputLocation=outputfile)
# p.save()
# from AION_UX import telemetry
# telemetry.telemetry_data('UseCaseCreated',modelname+'_'+str(Version),'UseCaseCreated')
# request.session['modelid'] = p.id
temp = {}
temp['ModelName'] = request.session['usecaseid']
temp['Version'] = request.session['ModelVersion']
'''
featuresList = features #df.columns.values.tolist()
datetimeFeatures =
datetimeFeatures = []
sequenceFeatures = []
unimportantFeatures = []
featuresRatio = {}
for i in featuresList:
check = ea.match_date_format(df[i])
if check == True:
datetimeFeatures.append(i)
unimportantFeatures.append(i)
seq_check = ea.check_seq_feature(df[i])
if seq_check == True:
sequenceFeatures.append(i)
unimportantFeatures.append(i)
ratio = ea.check_category(df[i])
if ratio != 0:
featuresRatio[i] = ratio
else:
unimportantFeatures.append(i)
targetFeature = min(featuresRatio, key=featuresRatio.get)
unimportantFeatures.append(targetFeature)
'''
unimportantFeatures = list(datetimeFeatures)
unimportantFeatures.extend(sequenceFeatures)
#unimportantFeatures = list(set(unimportantFeatures) + set(sequenceFeatures))
unimportantFeatures.append(targetFeature)
config = {}
noofforecast = 20
config['ModelName'] = request.session['usecaseid']
config['Version'] = request.session['ModelVersion']
config['datetimeFeatures'] = datetimeFeatures
config['sequenceFeatures'] = sequenceFeatures
config['FeaturesList'] = featuresList
config['unimportantFeatures'] = unimportantFeatures
config['targetFeature'] = targetFeature
config['noofforecasts'] = noofforecast
DEFAULT_FILE_PATH = request.session['defaultfilepath']
# Retraing settings changes
# -------- S T A R T --------
IsReTrainingCase = False
if request.session['IsRetraining'] == 'Yes':
id = request.session['ModelName']
p = usecasedetails.objects.get(id=id)
model = Existusecases.objects.filter(ModelName=p)
indexVal = model.count() - 1
configFile = str(model[indexVal].ConfigPath)
# configFile = str(model[0].ConfigPath)
# request.session['IsRetraining'] = 'No'
IsReTrainingCase = True
# ---------------------------
else:
configFile = os.path.join(DEFAULT_FILE_PATH, 'aion_config.json')
f = open(configFile, "r")
configSettings = f.read()
f.close()
configSettingsJson = json.loads(configSettings)
# Retraing settings changes
# -------- S T A R T --------
pickDefaultSettings = False
IsSameFeatures = False
if 'featureList' not in configSettingsJson['basic']:
pickDefaultSettings = True
IsSameFeatures = True
else:
if configSettingsJson['basic']['featureList'] == featuresList:
pickDefaultSettings = False
IsSameFeatures = True
else:
pickDefaultSettings = True
if pickDefaultSettings:
# ---------------------------
configSettingsJson['basic']['featureList'] = featuresList
configSettingsJson['basic']['dateTimeFeature'] = ",".join([feature for feature in datetimeFeatures])
configSettingsJson['basic']['indexFeature'] = sequenceFeatures
trainingFeatures = list(set(featuresList) - set(unimportantFeatures))
configSettingsJson['basic']['trainingFeatures'] = ",".join([feature for feature in trainingFeatures])
configSettingsJson['basic']['targetFeature'] = targetFeature
if request.session['datatype'].lower() in ['video','image','object','document','llm_document','llm_code']:
for x in configSettingsJson['basic']['analysisType'].keys():
configSettingsJson['basic']['analysisType'][x] = 'False'
configSettingsJson['basic']['folderSettings']['fileType'] = request.session['datatype']
configSettingsJson['basic']['folderSettings']['labelDataFile'] = request.session['csvfullpath']
configSettingsJson['basic']['folderSettings']['fileExtension'] = request.session['fileExtension']
if request.session['datatype'] in ['LLM_Document','LLM_Code']:
configSettingsJson['basic']['analysisType']['llmFineTuning'] = 'True'
configSettingsJson['basic']['preprocessing']['llmFineTuning']['friendlyNames']['prompt']='Instruction'
configSettingsJson['basic']['preprocessing']['llmFineTuning']['friendlyNames']['response']='Response'
configSettingsJson['basic']['preprocessing']['llmFineTuning']['unstructuredData'] = 'True'
elif request.session['datatype'] == 'Video':
configSettingsJson['basic']['analysisType']['videoForecasting'] = 'True'
elif request.session['datatype'] == 'Image':
configSettingsJson['basic']['analysisType']['imageClassification'] = 'True'
elif request.session['datatype'] == 'Object':
configSettingsJson['basic']['analysisType']['objectDetection'] = 'True'
elif request.session['datatype'].lower() == 'document':
df = pd.read_csv(dataFile, encoding='utf8',sep=request.session['delimiter'],quotechar=request.session['textqualifier'],nrows=100)
noOfEmotyLevels = 0
shape = df.shape
if shape[1] == 2:
noOfEmotyLevels = df['Label'].isnull().sum()
#print(noOfEmotyLevels)
if noOfEmotyLevels == 100:
configSettingsJson['basic']['analysisType']['topicModelling'] = 'True'
else:
configSettingsJson['basic']['analysisType']['classification'] = 'True'
else:
if 'uploadfiletype' in request.session:
configSettingsJson['basic']['folderSettings']['fileType'] = request.session['uploadfiletype']
configSettingsJson['basic']['folderSettings']['labelDataFile'] = request.session['uploadLocation']
try:
if isinstance(datetimeFeatures, list):
if len(datetimeFeatures) != 0:
configSettingsJson = update_granularity(configSettingsJson,datapath=dataFile)
elif isinstance(datetimeFeatures, str):
if datetimeFeatures != '':
configSettingsJson = update_granularity(configSettingsJson,datapath=dataFile)
except:
pass
# Retraing settings changes
# -------- S T A R T --------
tot_count=len(numericCatFeatures)
#task 11997
if (tot_count > 1):
configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['multiVariate'] = 'True'
configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['uniVariate'] = 'False'
else:
configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['uniVariate'] = 'True'
configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['multiVariate'] = 'False'
if 'delimiter' in request.session:
configSettingsJson['basic']['fileSettings']['delimiters'] = request.session['delimiter']
else:
configSettingsJson['basic']['fileSettings']['delimiters'] = ','
if 'textqualifier' in request.session:
configSettingsJson['basic']['fileSettings']['textqualifier'] = request.session['textqualifier']
else:
request.session['textqualifier'] = '"'
configSettingsJson['advance']['profiler']['featureDict'] = featuresListJson
configSettingsJson['basic']['onlineLearning'] = 'False'
configSettingsJson['basic']['dataLocation'] = request.session['datalocation']
configSettingsJson['basic']['noOfRecords'] = request.session['NoOfRecords']
onlineLearning = configSettingsJson['basic']['onlineLearning']
updatedConfigSettings = json.dumps(configSettingsJson)
with open(config_json_filename, "w") as fpWrite:
fpWrite.write(updatedConfigSettings)
fpWrite.close()
'''
p = Existusecases(DataFilePath=dataFile, DeployPath=DEPLOY_LOCATION, Status='Not Trained',
ConfigPath=config_json_filename, Version=Version, ModelName=ModelName,
TrainOuputLocation=outputfile)
p.save()
'''
p = Existusecases.objects.get(ModelName=ModelName,Version=Version)
p.DataFilePath = dataFile
p.DeployPath = DEPLOY_LOCATION
p.ConfigPath = config_json_filename
p.TrainOuputLocation = outputfile
p.save()
#from appbe import telemetry
#telemetry.telemetry_data('UseCaseCreated',modelname+'_'+str(Version),'UseCaseCreated')
request.session['modelid'] = p.id
# ---------------------------
from appbe.compute import selectedInfratructure
infra = selectedInfratructure()
if infra.lower() in ['aws','gcp']:
problemType = 'llmFineTuning'
else:
problemType = 'classification'
#print(problemType)
for key in configSettingsJson['basic']['analysisType']:
if configSettingsJson['basic']['analysisType'][key] == 'True':
problemType = key
break
scoringCreteria = 'NA'
if problemType in ['classification','regression','survivalAnalysis','timeSeriesForecasting']: #task 11997
for key in configSettingsJson['basic']['scoringCriteria'][problemType]:
if configSettingsJson['basic']['scoringCriteria'][problemType][key] == 'True':
scoringCreteria = key
break
selectAlgo = ""
if problemType in ['classification','regression','timeSeriesForecasting','timeSeriesAnomalyDetection',
'recommenderSystem','clustering','anomalyDetection','topicModelling','survivalAnalysis','videoForecasting','imageClassification','objectDetection','stateTransition','llmFineTuning']: #task 11997
for key in configSettingsJson['basic']['algorithms'][problemType]:
if configSettingsJson['basic']['algorithms'][problemType][key] == 'True':
if selectAlgo != "":
selectAlgo += ','
selectAlgo += key
modelSize = ''
if problemType == 'llmFineTuning':
for key in configSettingsJson['basic']['modelSize']['llmFineTuning'][selectAlgo].keys():
if configSettingsJson['basic']['modelSize']['llmFineTuning'][selectAlgo][key] == 'True':
modelSize = key
break
movenext = True
request.session['finalstate'] = 1
request.session['currentstate'] = 1
context = {'tab': 'tabconfigure','modelSize':modelSize,'tot_count':tot_count, 'temp': temp, 'configsettings': configSettingsJson, 'config': config,'numericFeature':numericFeature,'onlineLearning':onlineLearning,
'noOfRecords': records, 'selected_use_case': selected_use_case,'problemType':problemType,'scoringCreteria':scoringCreteria,'selectAlgo':selectAlgo,'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion, 'movenext': movenext,
'currentstate': request.session['currentstate'], 'finalstate': request.session['finalstate'],
'selected': 'modeltraning','advance':True,'basic_help':ht.basic_help
# Retraing settings changes
,'IsSameFeatures':IsSameFeatures,'IsReTrainingCase':IsReTrainingCase
# 10012:Decision Threshold related
,'DLCheckpoint':data_is_under_RAM_threshold}
return context
except UnicodeDecodeError as e:
print(e)
context = {'tab': 'tabconfigure','selected_use_case': selected_use_case,'ModelVersion': ModelVersion,'ModelStatus': ModelStatus,'selected': 'modeltraning','error': 'File Reading Error: '+str(e)}
return context
except Exception as e:
print(e)
import sys,os
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
context = {'tab': 'tabconfigure','selected_use_case': selected_use_case | ||
,'ModelVersion': ModelVersion,'ModelStatus': ModelStatus,'selected': 'modeltraning','error': 'Config Error: '+str(e)}
return context<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import kfp
import kfp.dsl as dsl
import json
from pathlib import Path
class aionpipelinets():
containerRegistry = str()
containerLabel = str()
containerSecret = str()
pipelineName = 'AION MLOps Pipeline {0}'
exeCmd = 'python'
codeFile = 'aionCode.py'
mntPoint = '/aion'
inputArg = '-i'
msIP = '0.0.0.0'
port = '8094'
cachingStrategy = 'P0D'
deafultVolume = '2Gi'
volName = 'aion-pvc'
volMode = 'ReadWriteMany'
fileExt = '.tar.gz'
fileName = 'aion_mlops_pipeline_{0}'
containerMM = 'modelmonitoring'
containerDI = 'dataingestion'
containerDT = 'datatransformation'
containerFE = 'featureengineering'
containerMR = 'modelregistry'
containerMS = 'modelserving'
containerImage = '{0}/{1}:{2}'
models = {}
nameSeprator = '-'
modelsLiteral = 'models'
modelNameLiteral = 'modelname'
msTemplate = '{"apiVersion": "v1", "kind": "Pod", "metadata": {"name": "{{workflow.name}}-{0}"}, "spec": {"containers": [{"name": "{0}", "image": "{1}", "command": ["python"], "args": ["aionCode.py", "-ip", "{2}", "-pn", "{3}"],"volumeMounts": [{"name": "aion-pvc", "mountPath": "{4}"}], "ports": [{"name": "http", "containerPort": {3}, "protocol": "TCP"}]}], "imagePullSecrets": [{"name": "{5}"}], "volumes": [{"name": "aion-pvc", "persistentVolumeClaim": {"claimName": "{{workflow.name}}-{6}"}}]}}'
def __init__(self, models, containerRegistry, containerLabel, containerSecret=str()):
self.models = models
self.containerRegistry = containerRegistry
self.containerLabel = containerLabel
self.containerSecret = containerSecret
@dsl.pipeline(
name=pipelineName.format(containerLabel),
description=pipelineName.format(containerLabel),
)
def aion_mlops(self, inputUri=str(), volSize=deafultVolume):
vop = dsl.VolumeOp(
name=self.volName + self.nameSeprator + self.containerLabel,
resource_name=self.volName,
modes=[self.volMode],
size=volSize
)
mm = dsl.ContainerOp(
name=self.containerMM,
image=self.containerImage.format(self.containerRegistry,self.containerMM,self.containerLabel),
command=self.exeCmd,
arguments=[
self.codeFile,
self.inputArg,
inputUri,
],
pvolumes={self.mntPoint: vop.volume}
)
mm.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy
di = dsl.ContainerOp(
name=self.containerDI,
image=self.containerImage.format(self.containerRegistry,self.containerDI,self.containerLabel),
command=self.exeCmd,
arguments=[
self.codeFile,
],
pvolumes={self.mntPoint: mm.pvolume}
)
di.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy
dt = dsl.ContainerOp(
name=self.containerDT,
image=self.containerImage.format(self.containerRegistry,self.containerDT,self.containerLabel),
command=self.exeCmd,
arguments=[
self.codeFile,
],
pvolumes={self.mntPoint: di.pvolume}
)
dt.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy
fe = dsl.ContainerOp(
name=self.containerFE,
image=self.containerImage.format(self.containerRegistry,self.containerFE,self.containerLabel),
command=self.exeCmd,
arguments=[
self.codeFile,
],
pvolumes={self.mntPoint: dt.pvolume}
)
fe.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy
dictMT = {}
listMTOps = []
for model in self.models[self.modelsLiteral]:
modelName = model[self.modelNameLiteral]
mt=dsl.ContainerOp(
name=modelName,
image=self.containerImage.format(self.containerRegistry,modelName,self.containerLabel),
command=self.exeCmd,
arguments=[
self.codeFile,
],
pvolumes={self.mntPoint: fe.pvolume})
mt.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy
listMTOps.append(mt)
dictMT[self.mntPoint]=mt.pvolume
mr = dsl.ContainerOp(
name=self.containerMR,
image=self.containerImage.format(self.containerRegistry,self.containerMR,self.containerLabel),
command=self.exeCmd,
arguments=[
self.codeFile,
],
pvolumes=dictMT
).after(*tuple(listMTOps))
mr.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy
msJson = self.msTemplate.replace(str({0}),self.containerMS).replace(str({1}),self.containerImage.format(self.containerRegistry,self.containerMS,self.containerLabel)).replace(str({2}),self.msIP).replace(str({3}),self.port).replace(str({4}),self.mntPoint).replace(str({5}),self.containerSecret).replace(str({6}),self.volName)
ms = dsl.ResourceOp(
name=self.containerMS + self.nameSeprator + self.containerLabel,
k8s_resource=json.loads(msJson),
)
ms.after(mr)
def compilepl(self, targetPath=str()):
filePath = self.fileName.format(self.containerLabel.lower()) + self.fileExt
if targetPath != str():
filePath = Path(targetPath, filePath)
kfp.compiler.Compiler().compile(self.aion_mlops, str(filePath))
def executepl(self, kfhost=str()):
client = kfp.Client(kfhost)
client.create_run_from_pipeline_func(self.aion_mlops,arguments={})
<s> import pandas as pd
import numpy as np
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.stattools import kpss
from statsmodels.tsa.seasonal import seasonal_decompose
import logging
import os
import warnings
warnings.filterwarnings('ignore')
## Main class to find out seassonality and stationary in timeseries data.
class StationarySeasonalityTest:
def __init__(self,df,featurename,datetimefeature):
self.df=df
self.targetFeature=featurename
self.datetimefeature=datetimefeature
## to get the timeseries data stationary information
def stationary_model(self,df,target_feature,stationary_check_method):
stationary_status=None
if (stationary_check_method.lower()=='adfuller'):
stats_model=adfuller(df[target_feature])
statistic, p_value, n_lags, num_bservations,critical_values,info_criterion_best=stats_model[0],stats_model[1],stats_model[2],stats_model[3],stats_model[4],stats_model[5]
if (p_value>0.05):
stationary_status=str("Non-Stationary")
elif(p_value<0.05):
stationary_status=str("Stationary")
##kpss is opposite to ADF in considering null hypothesis. In KPSS, if null hypothesis,then it is stationary as oppose to ADF.
elif (stationary_check_method.lower()=='kpss'):
from statsmodels.tsa.stattools import kpss
stats_model = kpss(df[target_feature])
statistic, p_value, n_lags, critical_values=stats_model[0],stats_model[1],stats_model[2],stats_model[3]
##In kpss, the stationary condition is opposite to Adafuller.
if (p_value>0.05):
stationary_status=str("Stationary")
else:
stationary_status=str("Non-Stationary")
return stats_model,n_lags,p_value,stationary_status
## Get stationary details
def stationary_check(self,target_feature,time_col,method):
df=self.df
df[time_col]=pd.to_datetime(df[time_col])
df=df.set_index(time_col)
try:
stationary_check_method=method
except:
stationary_check_method='adfuller'
if (len(target_feature) == 1):
try:
if isinstance(target_feature,list):
target_feature=''.join(target_feature)
elif isinstance(target_feature,int):
target_feature=str(target_feature)
elif isinstance(target_feature,str):
pass
except Exception as e:
pass
stationary_result={}
stats_model,n_lags,p_value,stationary_status=self.stationary_model(df,target_feature,stationary_check_method)
# stationary_result[target_feature]=stationary_status
stationary_result[target_feature]=stationary_status
elif(len(target_feature) > 1):
stationary_result={}
for col in df.columns:
stats_model,n_lags,p_value,stationary_status=self.stationary_model(df,col,stationary_check_method)
stationary_result[col]=stationary_status
else:
pass
stationary_val=None
for v in stationary_result.values():
stationary_val=v
stationary_combined_res=dict()
c_dict=[k for k,v in stationary_result.items() if 'non-stationary' in v]
if (len(c_dict)>=1):
stationary_combined_res['dataframe_stationarity']='Non-Stationary'
else:
stationary_combined_res['dataframe_stationarity']='Stationary'
return stats_model,n_lags,p_value,stationary_val,stationary_combined_res
#Get seasonality by using seasonal_decompose lib.
def seasonality_model(self,target_feature,df):
seasonality_status=None
try:
try:
stats_model = kpss(df[target_feature])
statistic, p_value, n_lags, critical_values=stats_model[0],stats_model[1],stats_model[2],stats_model[3]
except:
n_lags=1
pass
try:
df_target=self.df[target_feature]
decompose_result_mult = seasonal_decompose(df_target,model='additive', extrapolate_trend='freq', period=n_lags)
except Exception as e:
##If additive model (type of seasonal component) failed, use multiplicative
decompose_result_mult = seasonal_decompose(df_target,model='multiplicative', extrapolate_trend='freq', period=1)
trend = decompose_result_mult.trend
observed=decompose_result_mult.observed
seasonal = decompose_result_mult.seasonal
residual = decompose_result_mult.resid
try:
if isinstance(df_target, pd.Series):
auto_correlation = df_target.autocorr(lag=n_lags)
elif isinstance(df_target, pd.DataFrame):
df_target = df_target.squeeze()
auto_correlation = df_target.autocorr(lag=n_lags)
except:
pass
if (seasonal.sum()==0):
seasonality_status="Non-Seasonal"
else:
seasonality_status="Seasonal"
# #Please use the below plot for GUI show (seasonality components)
# decompose_result_mult.plot().savefig('seasonality_plot.png')
df['observed'] = decompose_result_mult.observed
df['residual'] = decompose_result_mult.resid
df['seasonal'] = decompose_result_mult.seasonal
df['trend'] = decompose_result_mult.trend
except Exception as e:
print("Seasonality function exception: \\t",e)
return df,decompose_result_mult,seasonality_status
##Main function to check seasonlity in data
def seasonal_check(self,target_feature,time_col,seasonal_model):
df=self.df
try:
df[time_col]=pd.to_datetime(df[time_col])
except Exception as e:
pass
df=df.set_index(time_col)
if (len(target_feature)==1):
try:
if isinstance(target_feature,list):
target_feature=''.join(target_feature)
elif isinstance(target_feature,int):
target_feature=str(target_feature)
elif isinstance(target_feature,str):
pass
except Exception as e:
## Because of EDA, all log messages removed. (self.log.info )
pass
## Seasonal component for individual feature based.
seasonality_result=dict()
df,decompose_result_mult,seasonality_status = self.seasonality_model(target_feature,df)
# seasonality_result[target_feature]=seasonality_status
seasonality_result['Feature: '+str(target_feature)]=seasonality_status
elif(len(target_feature) > 1):
seasonality_result=dict()
for col in df.columns:
df,decompose_result_mult,seasonality_status = self.seasonality_model(col,df)
seasonality_result[col]=seasonality_status
else:
pass
# ## Seasonal component for whole dataset
seasonality_val=None
for v in seasonality_result.values():
seasonality_val=v
seasonality_combined_res=dict()
c | ||
_dict=[k for k,v in seasonality_result.items() if 'non-seasonality' in v]
if (len(c_dict)>=1):
seasonality_combined_res['dataframe_seasonality']='No Seasonal elements'
else:
seasonality_combined_res['dataframe_seasonality']='contains seasonal elements.'
return df,decompose_result_mult,seasonality_val,seasonality_combined_res
#Main user defined caller for stationary and seasonality (SS)
def analysis(self,seasonality_status,stationarity_status):
seasonal_model="additive"
time_col=self.datetimefeature
stationary_method='adfuller'
if (isinstance(self.targetFeature,list)):
target=self.targetFeature
pass
elif (isinstance(self.targetFeature,str)):
target=list(self.targetFeature.split(','))
if (stationarity_status.lower()=="true"):
stats_model,n_lags,p_value,stationary_result,stationary_combined_res=self.stationary_check(target,time_col,stationary_method)
return stationary_result
if (seasonality_status.lower()=="true"):
df,decompose_result_mult,seasonality_result,seasonality_combined_res=self.seasonal_check(target,time_col,seasonal_model)
return seasonality_result
#Main fn for standalone test purpose
if __name__=='__main__':
print("Inside seasonality-stationary test main function...")
print("Below code used for standalone test purpose.")
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os.path
import time
import subprocess
import sys
from appbe.aion_config import kafka_setting
from appbe.aion_config import running_setting
from appbe import installPackage
from appbe import compute
from appbe.models import getusercasestatus
import json
import pandas as pd
import ntpath
import shutil
import platform
from pathlib import Path
from appbe.dataPath import DATA_DIR
LOG_FILE_PATH = os.path.join(DATA_DIR,'logs')
def encrptpackage_command(request,Existusecases,usecasedetails):
command = request.POST.get('encryptedsubmit')
kafkaSetting = kafka_setting()
ruuningSetting = running_setting()
computeinfrastructure = compute.readComputeConfig()
modelID = request.POST.get('modelID')
p = Existusecases.objects.get(id=modelID)
usecasename = p.ModelName.UsecaseName
usecaseid = p.ModelName.usecaseid
runningStatus,pid,ip,port = installPackage.checkModelServiceRunning(usecasename)
installationStatus,modelName,modelVersion=installPackage.checkInstalledPackge(usecasename)
try:
tacking_url =request.get_host()
except Exception as e:
tacking_url = '127.0.0.1'
usecasedetail = usecasedetails.objects.get(id=p.ModelName.id)
usecase = usecasedetails.objects.all()
models = Existusecases.objects.filter(ModelName=usecasedetail,Status='SUCCESS')
for model in models:
model.scoringCreteria = 'NA'
model.score = 'NA'
model.deploymodel = 'NA'
if os.path.isdir(str(model.DeployPath)):
modelPath = os.path.join(str(model.DeployPath),'etc','output.json')
try:
with open(modelPath) as file:
outputconfig = json.load(file)
file.close()
if outputconfig['status'] == 'SUCCESS':
model.scoringCreteria = outputconfig['data']['ScoreType']
model.score = outputconfig['data']['BestScore']
model.deploymodel = outputconfig['data']['BestModel']
model.modelType = outputconfig['data']['ModelType']
model.maacsupport = 'True'
model.flserversupport = 'False'
supportedmodels = ["Logistic Regression","Neural Network","Linear Regression"]
if model.deploymodel in supportedmodels:
model.flserversupport = 'True'
else:
model.flserversupport = 'False'
supportedmodels = ["Logistic Regression",
"Naive Bayes","Decision Tree","Support Vector Machine","K Nearest Neighbors","Gradient Boosting","Random Forest","Linear Regression","Lasso","Ridge","Extreme Gradient Boosting (XGBoost)","Light Gradient Boosting (LightGBM)","Categorical Boosting (CatBoost)"]
if model.deploymodel in supportedmodels:
model.maacsupport = 'True'
else:
model.maacsupport = 'False'
supportedmodels = ["Extreme Gradient Boosting (XGBoost)"]
if model.deploymodel in supportedmodels:
model.encryptionsupport = 'True'
else:
model.encryptionsupport = 'False'
except Exception as e:
pass
if command.lower() == 'secureclient':
try:
encryptedclient = os.path.join(str(p.DeployPath),'publish','SecureClient')
shutil.rmtree(encryptedclient, ignore_errors=True)
logPath = os.path.join(encryptedclient,'logs')
scriptPath = os.path.join(encryptedclient,'script')
modelPath = os.path.join(encryptedclient,'model')
Path(modelPath).mkdir(parents=True, exist_ok=True)
Path(encryptedclient).mkdir(parents=True, exist_ok=True)
Path(logPath).mkdir(parents=True, exist_ok=True)
Path(scriptPath).mkdir(parents=True, exist_ok=True)
encryptedclientOrg = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','utilities','encryptedPackage'))
modelProfiler = os.path.normpath(os.path.join(str(p.DeployPath),'script','inputprofiler.py'))
modelselector = os.path.normpath(os.path.join(str(p.DeployPath),'aion_predict.py'))
preprocessmodel = os.path.normpath(os.path.join(str(p.DeployPath),'model','preprocess_pipe.pkl'))
# shutil.copy2(modelProfiler,scriptPath)
# shutil.copy2(modelselector,scriptPath)
## For bug 15975
if os.path.exists(modelProfiler):
shutil.copy2(modelProfiler,scriptPath)
if os.path.exists(modelselector):
shutil.copy2(modelselector,scriptPath)
if os.path.exists(preprocessmodel):
shutil.copy2(preprocessmodel,modelPath)
if model.modelType.lower() == 'classification':
try:
opfile = os.path.normpath(os.path.join(encryptedclientOrg,'Readme.txt'))
shutil.copy2(opfile,encryptedclient)
opfile = os.path.normpath(os.path.join(encryptedclientOrg,'requirements.txt'))
shutil.copy2(opfile,encryptedclient)
except:
#failed to copy readme,requirements.txt files
pass
opfile = os.path.normpath(os.path.join(encryptedclientOrg,'client','heMulticlass.py'))
shutil.copy2(opfile,scriptPath)
opfile = os.path.normpath(os.path.join(encryptedclientOrg,'client','aion_hemulticlient.py'))
shutil.copy2(opfile,encryptedclient)
os.rename(os.path.join(encryptedclient,'aion_hemulticlient.py'),os.path.join(encryptedclient,'aion_sclient.py'))
elif model.modelType.lower() == 'regression':
try:
opfile = os.path.normpath(os.path.join(encryptedclientOrg,'Readme.txt'))
shutil.copy2(opfile,encryptedclient)
opfile = os.path.normpath(os.path.join(encryptedclientOrg,'requirements.txt'))
shutil.copy2(opfile,encryptedclient)
except Exception as e:
print(e)
#failed to copy readme,requirements.txt files
pass
opfile = os.path.normpath(os.path.join(encryptedclientOrg,'client','heRegression.py'))
shutil.copy2(opfile,scriptPath)
opfile = os.path.normpath(os.path.join(encryptedclientOrg,'client','aion_heregressionclient.py'))
shutil.copy2(opfile,encryptedclient)
os.rename(os.path.join(encryptedclient,'aion_hemulticlient.py'),os.path.join(encryptedclient,'aion_sclient.py'))
except Exception as e:
Status = 'Error'
Msg = 'Secure client error: Check log file for more details'
Status = 'SUCCESS'
Msg = 'Secure Client Code Generated at '+encryptedclient
path= encryptedclient #Task 9981
elif command.lower() == 'secureserver':
try:
configPath = os.path.join(str(p.DeployPath),'etc','secure_config.json')
modelpath = usecasename+'_'+str(p.Version)+'.sav'
config = {'model_name':modelpath}
with open(configPath, "w") as outfile:
json.dump(config, outfile)
encryptedclientOrg = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','utilities','encryptedPackage'))
if model.modelType.lower() == 'classification':
opfile = os.path.normpath(os.path.join(encryptedclientOrg,'server','heMulticlass.py'))
shutil.copy2(opfile,str(p.DeployPath))
try:
os.remove(os.path.join(str(p.DeployPath),'aion_spredict.py'))
except OSError:
pass
os.rename(os.path.join(str(p.DeployPath),'heMulticlass.py'),os.path.join(str(p.DeployPath),'aion_spredict.py'))
Status = 'SUCCESS'
Msg = 'Secure rest end point enabled http://'+str(tacking_url)+'/api/spredict?usecaseid='+usecaseid+'&version='+str(p.Version)
except Exception as e:
Status = 'Error'
Msg = 'Secure rest end point error: Check log file for more details'
nouc = 0
from appbe.pages import get_usecase_page
status,context,action = get_usecase_page(request,usecasedetails,Existusecases)
context['Status'] = Status
context['Msg'] = Msg
if command.lower() == 'secureclient': #Task 9981
context['path'] = path
'''
selected_use_case,ModelVersion,ModelStatus = getusercasestatus(request)
context = {'tab': 'upload','nouc':nouc,'usecasedetail': usecase, 'models': models, 'selected_use_case': selected_use_case,
'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion, 'selected': 'usecase','computeinfrastructure':computeinfrastructure,'installationStatus':installationStatus,'modelName':modelName,'modelVersion':modelVersion,'usecasename':usecasename,'pid':pid,'ip':ip,'port':port,'usecaseid':p.ModelName.id,'Status':Status,'Msg':Msg}
'''
return(context)
def download_sclient(request,context): #Task 9981
import os
from django.http import HttpResponse, Http404
try:
file_name = 'SecureClient_'+request.POST.get('modelsignature')
path = context['path']
file_path = shutil.make_archive(file_name, 'zip', path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(),content_type='application/x-zip-compressed')
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
os.remove(file_path)
return response
except:
raise Http404<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os,sys
def read_service_url_params(request):
hosturl =request.get_host()
url='http://'+hosturl+'/api/'
return url
def read_monitoring_service_url_params(request):
hosturl =request.get_host()
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','config','aion.config'))
file = open(file_path, "r")
data = file.read()
file.close()
service_url = '127.0.0.1'
service_port='60050'
for line in data.splitlines():
if 'aion_service_url=' in line:
service_url= line.split('=',1)[1]
if 'aion_service_port=' in line:
service_port= line.split('=',1)[1]
url='http://'+hosturl+'/api/'
return url
def read_performance_service_url_params(request):
hosturl =request.get_host()
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','config','aion.config'))
file = open(file_path, "r")
data = file.read()
file.close()
service_url = '127.0.0.1'
service_port='60050'
for line in data.splitlines():
if 'aion_service_url=' in line:
service_url= line.split('=',1)[1]
if 'aion_service_port=' in line:
service_port= line.split('=',1)[1]
url='http://'+hosturl+'/api/'
return url
def read_pattern_an | ||
omaly_url_params(request):
hosturl =request.get_host()
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','config','aion.config'))
file = open(file_path, "r")
data = file.read()
file.close()
service_url = '127.0.0.1'
service_port='60050'
for line in data.splitlines():
if 'aion_service_url=' in line:
service_url= line.split('=',1)[1]
if 'aion_service_port=' in line:
service_port= line.split('=',1)[1]
url='http://'+hosturl+'/api/pattern_anomaly_predict/'
return url
def read_pattern_anomaly_setting_url_params(request):
hosturl =request.get_host()
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','config','aion.config'))
file = open(file_path, "r")
data = file.read()
file.close()
service_url = '127.0.0.1'
service_port='60050'
for line in data.splitlines():
if 'aion_service_url=' in line:
service_url= line.split('=',1)[1]
if 'aion_service_port=' in line:
service_port= line.split('=',1)[1]
url='http://'+hosturl+'/api/pattern_anomaly_settings/'
return url<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import numpy as np
import os
import sys
import scipy.stats as st
def DistributionFinder(data):
try:
distributionName = ""
sse = 0.0
KStestStatic = 0.0
dataType = ""
if (data.dtype == "float64"):
dataType = "Continuous"
elif (data.dtype == "int"):
dataType = "Discrete"
elif (data.dtype == "int64"):
dataType = "Discrete"
if (dataType == "Discrete"):
distributions = [st.bernoulli, st.binom, st.geom, st.nbinom, st.poisson]
index, counts = np.unique(data.astype(int), return_counts=True)
if (len(index) >= 2):
best_sse = np.inf
y1 = []
total = sum(counts)
mean = float(sum(index * counts)) / total
variance = float((sum(index ** 2 * counts) - total * mean ** 2)) / (total - 1)
dispersion = mean / float(variance)
theta = 1 / float(dispersion)
r = mean * (float(theta) / 1 - theta)
for j in counts:
y1.append(float(j) / total)
pmf1 = st.bernoulli.pmf(index, mean)
pmf2 = st.binom.pmf(index, len(index), p=mean / len(index))
pmf3 = st.geom.pmf(index, 1 / float(1 + mean))
pmf4 = st.nbinom.pmf(index, mean, r)
pmf5 = st.poisson.pmf(index, mean)
sse1 = np.sum(np.power(y1 - pmf1, 2.0))
sse2 = np.sum(np.power(y1 - pmf2, 2.0))
sse3 = np.sum(np.power(y1 - pmf3, 2.0))
sse4 = np.sum(np.power(y1 - pmf4, 2.0))
sse5 = np.sum(np.power(y1 - pmf5, 2.0))
sselist = [sse1, sse2, sse3, sse4, sse5]
best_distribution = 'NA'
for i in range(0, len(sselist)):
if best_sse > sselist[i] > 0:
best_distribution = distributions[i].name
best_sse = sselist[i]
elif (len(index) == 1):
best_distribution = "Constant Data-No Distribution"
best_sse = 0.0
distributionName = best_distribution
sse = best_sse
elif (dataType == "Continuous"):
distributions = [st.uniform, st.expon, st.weibull_max, st.weibull_min, st.chi, st.norm, st.lognorm, st.t,
st.gamma, st.beta]
best_distribution = st.norm.name
best_sse = np.inf
datamin = data.min()
datamax = data.max()
nrange = datamax - datamin
y, x = np.histogram(data.astype(float), bins='auto', density=True)
x = (x + np.roll(x, -1))[:-1] / 2.0
for distribution in distributions:
params = distribution.fit(data.astype(float))
arg = params[:-2]
loc = params[-2]
scale = params[-1]
pdf = distribution.pdf(x, loc=loc, scale=scale, *arg)
sse = np.sum(np.power(y - pdf, 2.0))
if (best_sse > sse > 0):
best_distribution = distribution.name
best_sse = sse
distributionName = best_distribution
sse = best_sse
except:
response = str(sys.exc_info()[0])
message = 'Job has Failed' + response
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type) + ' ' + str(fname) + ' ' + str(exc_tb.tb_lineno))
print(message)
return distributionName, sse<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import random
import string
from sklearn import datasets
import pandas as pd
import names # pip install names
import time
import numpy as np
import argparse
import json
import os
import platform
import time
import sys
from appbe.dataPath import CONFIG_FILE_PATH
def randStr(chars = 'XYZABCDE', N=2):
return ''.join(random.choice(chars) for _ in range(N))
def load_json_config(file):
with open(file, 'r') as openfile:
json_object = json.load(openfile)
for key, value in json_object.items():
print(key, value)
return json_object
def gen_data_classification(number_samples=10000, number_numerical_features=25,
file_name='file_class.csv', number_categorical_features=2,
number_text_features=2,
missing_proportion=0.1,
number_informative=20, number_class=2,
weights=[0.5,0.5], shift=0.0,
value_range_dict={0:(1, 2)}):
# TO-DO: need to add min max vlinear/non-linear
try:
features, output = datasets.make_classification(
n_samples=number_samples,
n_features=number_numerical_features,
n_informative=number_informative,
n_classes=number_class,
weights = weights, # 20% of the targets will be 0, 80% will be 1. default is 50/50
shift=shift,
)
columns = []
# Numerical Features
for i in range(number_numerical_features):
columns.append('Feature_' + str(i))
features = pd.DataFrame(features, columns=columns)
# Setting min max value for features
for col_name in features.columns:
for key, value in value_range_dict.items():
if (str(features.columns.get_loc(col_name)) == key):
for item in features[col_name].values:
if item < value[0]:
features.loc[features[col_name] == item,
col_name] = random.uniform(value[0],value[1])
if item > value[1]:
features.loc[features[col_name] == item,
col_name] = random.uniform(value[0],value[1])
df_list = []
df_list.append(features)
# Add Categorical Features
for j in range(number_categorical_features):
categorical_feature1_list = []
number_categories_per_feature = random.randint(2, 5)
for i in range(number_categories_per_feature):
categorical_feature1_list.append(randStr(N=3))
print("Categories of Categorical Feature " + str(j) + ": ", categorical_feature1_list)
categorical_feature1 = []
for k in range(number_samples):
categorical_feature1.append(random.choice(categorical_feature1_list))
categorical_feature1 = pd.DataFrame(categorical_feature1, columns=['Categorical'+str(j)])
df_list.append(categorical_feature1)
# Add Text Features
for l in range(number_text_features):
text_feature = []
for k in range(number_samples):
text_feature.append(names.get_full_name())
# text_feature.append(r.get_random_word())
text_feature = pd.DataFrame(text_feature, columns=['Name'+str(l)])
# text_feature = pd.DataFrame(text_feature, columns=['Word' + str(l)])
df_list.append(text_feature)
output = pd.DataFrame(output, columns=['Target'])
df_list.append(output)
df_final = pd.concat(df_list, axis=1)
for col in df_final.columns:
# df_final.loc[df_final.sample(frac=0.1).index, col] = np.NaN
df_final.loc[df_final[col].sample(frac=missing_proportion).index, col] = np.NaN
# Check to see proportion of NaN values:
# df.isnull().sum() / len(df)
df_final.to_csv(file_name)
return True
except Exception as e:
print(e)
return False
def gen_data_regression(
number_samples=10000, number_numerical_features=25,
file_name='file_regress.csv', number_categorical_features=2,
number_text_features=2,
missing_proportion=0.1,
number_informative=10,
number_target=1, bias=0.0, noise=0.0,
value_range_dict={1:(5, 10)}
):
try:
features, output = datasets.make_regression(
n_samples=number_samples,
n_features=number_numerical_features,
n_informative=number_informative,
n_targets=number_target,
bias=bias,
noise=noise,
)
columns = []
for i in range(number_numerical_features):
columns.append('Feature_' + str(i))
features = pd.DataFrame(features, columns=columns)
for col_name in features.columns:
for key, value in value_range_dict.items():
if (str(features.columns.get_loc(col_name)) == key):
for item in features[col_name].values:
if item < value[0]:
features.loc[features[col_name] == item,
col_name] = random.uniform(value[0],value[1])
if item > value[1]:
features.loc[features[col_name] == item,
col_name] = random.uniform(value[0],value[1])
df_list = []
df_list.append(features)
for j in range(number_categorical_features):
categorical_feature1_list = []
number_categories_per_feature = random.randint(2, 5)
for i in range(number_categories_per_feature):
categorical_feature1_list.append(randStr(N=3))
print("Categories of Categorical Feature " + str(j) + ": ", categorical_feature1_list)
categorical_feature1 = []
for k in range(number_samples):
categorical_feature1.append(random.choice(categorical_feature1_list))
categorical_feature1 = pd.DataFrame(categorical_feature1, columns=['Categorical' + str(j)])
df_list.append(categorical_feature1)
for l in range(number_text_features):
text_feature = []
for k in range(number_samples):
text_feature.append(names.get_full_name())
text_feature = pd.DataFrame(text_feature, columns=['Name'+str(l)])
df_list.append(text_feature)
output = pd.DataFrame(output, columns=['Target'])
df_list.append(output)
df_final = pd.concat(df_list, axis=1)
for col in df_final.columns:
# df_final.loc[df_final.sample(frac=0.1).index, col] = np.NaN
df_final.loc[df_final[col].sample(frac=missing_proportion).index, col] = np.NaN
# Check to see proportion of NaN values:
# df.isnull().sum() / len(df)
df_final.to_csv(file_name)
| ||
return True
except Exception as e:
print(e)
return False
def gen_data_series(univariate="True",
start_time='2000-01-01 00:00',
end_time='2022-12-31 00:00',
number_samples=10000, number_numerical_features=25,
file_name='file_regress.csv', number_categorical_features=2,
# number_text_features=2,
missing_proportion=0.1,
number_informative=10,
number_target=1, bias=0.0, noise=0.0,
value_range_dict={1:(5, 10)}
):
try:
if univariate == "True":
number_numerical_features = 1
number_categorical_features = 0
features, output = datasets.make_regression(
n_samples=number_samples,
n_features=number_numerical_features,
n_informative=number_informative,
n_targets=number_target,
bias=bias,
noise=noise,
)
columns = []
# Numerical Features
for i in range(number_numerical_features):
columns.append('Feature_' + str(i))
features = pd.DataFrame(features, columns=columns)
# Setting min max value for features
for col_name in features.columns:
for key, value in value_range_dict.items():
if (str(features.columns.get_loc(col_name)) == key):
for item in features[col_name].values:
if item < value[0]:
features.loc[features[col_name] == item,
col_name] = random.uniform(value[0],value[1])
if item > value[1]:
features.loc[features[col_name] == item,
col_name] = random.uniform(value[0],value[1])
df_list = []
df_list.append(features)
# Add Categorical Features
for j in range(number_categorical_features):
categorical_feature1_list = []
number_categories_per_feature = random.randint(2, 5)
for i in range(number_categories_per_feature):
categorical_feature1_list.append(randStr(N=3))
print("Categories of Categorical Feature " + str(j) + ": ", categorical_feature1_list)
categorical_feature1 = []
for k in range(number_samples):
categorical_feature1.append(random.choice(categorical_feature1_list))
categorical_feature1 = pd.DataFrame(categorical_feature1, columns=['Categorical'+str(j)])
df_list.append(categorical_feature1)
# df2['date'] = pd.date_range(start='1890-01-01', freq="sec",periods=len(df2))
time_feature = pd.date_range(start=start_time, end=end_time, periods=number_samples) #freq="1sec"
time_feature = pd.DataFrame(time_feature, columns=['Date'])
# df_list.append(time_feature)
df_list.insert(0, time_feature)
output = pd.DataFrame(output, columns=['Feature_' + str(number_numerical_features)])
if univariate != "True":
df_list.append(output)
df_final = pd.concat(df_list, axis=1)
for col in df_final.columns:
# df_final.loc[df_final.sample(frac=0.1).index, col] = np.NaN
df_final.loc[df_final[col].sample(frac=missing_proportion).index, col] = np.NaN
# Check to see proportion of NaN values:
# df.isnull().sum() / len(df)
df_final.to_csv(file_name)
return True
except Exception as e:
print(e)
return False
def data_generated_csv():
datajson = os.path.join(CONFIG_FILE_PATH, 'data_generated.json')
with open(datajson, 'r+') as f:
dictionary = json.load(f)
# f.close()
if dictionary.get('problemType') == 'classification':
number_samples = dictionary.get("number_samples")
number_numerical_features = dictionary.get("number_numerical_features")
number_categorical_features = dictionary.get("number_categorical_features")
number_text_features = dictionary.get("number_text_features")
missing_proportion = dictionary.get("missing_proportion")
number_informative = dictionary.get("number_informative")
number_class = dictionary.get("number_class")
weights = dictionary.get("weights")
shift = dictionary.get("shift")
data_path = dictionary.get("data_path")
value_range_dict = dictionary.get("value_range_dict")
gen_data_classification(number_samples=number_samples,
number_numerical_features=number_numerical_features,
file_name=data_path,
number_categorical_features=number_categorical_features,
number_text_features=number_text_features,
missing_proportion=missing_proportion,
number_informative=number_informative,
number_class=number_class, weights=weights,
shift=shift, value_range_dict=value_range_dict)
elif dictionary.get('problemType') == 'regression':
number_samples = dictionary.get("number_samples")
number_numerical_features = dictionary.get("number_numerical_features")
number_categorical_features = dictionary.get("number_categorical_features")
number_text_features = dictionary.get("number_text_features")
missing_proportion = dictionary.get("missing_proportion")
number_informative = dictionary.get("number_informative")
number_target = dictionary.get("number_target")
bias = dictionary.get("bias")
noise = dictionary.get("noise")
data_path = dictionary.get("data_path")
value_range_dict = dictionary.get("value_range_dict")
gen_data_regression(number_samples=number_samples,
number_numerical_features=number_numerical_features,
file_name=data_path,
number_categorical_features=number_categorical_features,
number_text_features=number_text_features,
missing_proportion=missing_proportion,
number_informative=number_informative,
number_target=number_target, bias=bias,
noise=noise, value_range_dict=value_range_dict)
elif dictionary.get('problemType') == 'timeseriesforecasting': #task 11997
data_path = dictionary.get("data_path")
is_univariate = dictionary.get("univariate")
number_samples = dictionary.get("number_samples")
number_numerical_features = dictionary.get("number_numerical_features")
number_categorical_features = dictionary.get("number_categorical_features")
missing_proportion = dictionary.get("missing_proportion")
number_informative = dictionary.get("number_informative")
number_target = dictionary.get("number_target")
bias = dictionary.get("bias")
noise = dictionary.get("noise")
value_range_dict = dictionary.get("value_range_dict")
gen_data_series(univariate=is_univariate,
number_samples=number_samples,
number_numerical_features=number_numerical_features,
file_name=data_path,
number_categorical_features=number_categorical_features,
# number_text_features=2,
missing_proportion=missing_proportion,
number_informative=number_informative,
number_target=number_target, bias=bias,
noise=noise,
value_range_dict=value_range_dict)
if __name__ == "__main__":
data_generated_csv()
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import json
import os
import rsa
import boto3 #usnish
import pandas as pd
import time
def add_new_azureStorage(request):
try:
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','azurestorage.conf'))
with open(file_path, 'r') as f:
data = json.load(f)
f.close()
if data == '':
data = []
except:
data = []
if request.POST["azurename"] =='' or request.POST["azureaccountkey"] == '' or request.POST["containername"] == '' :
return 'error'
newdata = {}
newdata['azurename'] = request.POST["azurename"]
newdata['azureaccountkey'] = request.POST["azureaccountkey"]
newdata['containername'] = request.POST["containername"]
data.append(newdata)
with open(file_path, 'w') as f:
json.dump(data, f)
f.close()
return 'success'
def get_azureStorage():
try:
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','azurestorage.conf'))
with open(file_path, 'r') as f:
data = json.load(f)
except:
data = []
return data
def read_azureStorage(name,directoryname,DATA_FILE_PATH):
try:
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','azurestorage.conf'))
with open(file_path, 'r') as f:
data = json.load(f)
except:
data = []
found = False
for x in data:
if x['azurename'] == name:
storage_account_name = str(x['azurename'])
storage_account_key = str(x['azureaccountkey'])
azure_container_name = x['containername']
found = True
break
try:
if found:
root_dir = str(directoryname)
from azure.storage.filedatalake import DataLakeServiceClient
import io
import pandavro as pdx
from detect_delimiter import detect
try:
service_client = DataLakeServiceClient(account_url="{}://{}.dfs.core.windows.net".format("https", storage_account_name), credential=storage_account_key)
print(azure_container_name)
file_system_client = service_client.get_file_system_client(azure_container_name)
print(root_dir)
file_paths = file_system_client.get_paths(path=root_dir)
main_df = pd.DataFrame()
for path in file_paths:
if not path.is_directory:
file_client = file_system_client.get_file_client(path.name)
file_ext = os.path.basename(path.name).split('.', 1)[1]
if file_ext in ["csv", "tsv"]:
with open(csv_local, "wb") as my_file:
download = file_client.download_file()
download.readinto(my_file)
with open(csv_local, 'r') as file:
data = file.read()
row_delimiter = detect(text=data, default=None, whitelist=[',', ';', ':', '|', '\\t'])
processed_df = pd.read_csv(csv_local, sep=row_delimiter)
if file_ext == "parquet":
download = file_client.download_file()
stream = io.BytesIO()
download.readinto(stream)
processed_df = pd.read_parquet(stream, engine='pyarrow')
if file_ext == "avro":
with open(avro_local, "wb") as my_file:
download = file_client.download_file()
download.readinto(my_file)
processed_df = pdx.read_avro(avro_local)
if not main_df.empty:
main_df = main_df.append(processed_df, ignore_index=True)
else:
main_df = pd.DataFrame(processed_df)
except Exception as e:
print(e)
return 'Success',main_df
except Exception as e:
print(e)
return 'Error', pd.DataFrame()<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import pyodbc as pyodbc
import pandas as pd
import json
import sqlalchemy as db
import pandas as pd
import urllib
def get_connection(request):
dbType = request.session['dbType']
connection_string = ""
if dbType.lower()=="sqlite":
filepath = request.session['filepath']
#table = request.session["tablenamesql"]
connection_string = "sqlite:///"+str(filepath)
elif dbType.lower() in ["postgresql","mysql","mssql"]:
db_name = request.session['dbname']
password = request.session['password']
user = request.session['username']
port = request.session['port']
host = request.session['host']
| ||
password=urllib.parse.quote_plus(password)
if dbType.lower()=="postgresql":
connection_string = "postgresql+psycopg2://" + user + ":" + password + "@" + host + ":" + port + "/" + db_name
if dbType.lower()=="mysql":
connection_string = "mysql+pyodbc://" + user + ":" + password + "@" + host + ":" + port + "/" + db_name
if dbType.lower()=="mssql":
driver=request.session['driver']
params = urllib.parse.quote_plus(
'Driver=%s;' % driver +
'Server=tcp:%s,' % host +
'%s;' % port +
'Database=%s;' % db_name +
'Uid=%s;' % user +
'Pwd={%s};' % password +
'Encrypt=yes;' +
'TrustServerCertificate=no;' +
'Connection Timeout=30;')
connection_string = 'mssql+pyodbc:///?odbc_connect=' + params
return connection_string
def list_tables(request):
connection_string = get_connection(request)
engine = db.create_engine(connection_string)
connection = engine.connect()
metadata = db.MetaData()
metadata.reflect(engine)
dt_list = []
try:
dt_list= list(metadata.tables.keys())
print(dt_list)
return dt_list
except:
print("Something went wrong")
return dt_list
def list_tables_fields(request,table_list):
connection_string = get_connection(request)
engine = db.create_engine(connection_string)
connection = engine.connect()
metadata = db.MetaData()
metadata.reflect(engine)
table_field_obj = {}
table_field_obj['data'] = []
try:
# filepath = request.session['filepath']
#table = request.session["tablenamesql"]
table_list = json.loads(table_list)
for table in table_list:
tf_obj = {}
tf_obj['TableName'] = str(table).strip()
tf_obj['Fields']= []
table = db.Table(table, metadata, autoload=True, autoload_with=engine)
col = table.columns.keys()
tempdata = []
for x in col:
my_list = {"column_name": x,"is_select":"false"}
tempdata.append(my_list)
tf_obj['Fields'] = tempdata
table_field_obj['data'].append(tf_obj)
return json.dumps(table_field_obj)
except Exception as e:
print("Something went wrong "+str(e))
return table_field_obj
def get_data(connection_string,table):
engine = db.create_engine(connection_string)
connection = engine.connect()
metadata = db.MetaData()
metadata.reflect(engine)
table = db.Table(table,metadata, autoload=True, autoload_with=engine)
query = db.select([table])
ResultProxy = connection.execute(query)
ResultSet = ResultProxy.fetchall()
col = table.columns.keys()
return pd.DataFrame(ResultSet, columns=col)
def getDataFromSingleTable(request):
dbType = request.session['dbType']
if dbType.lower() == "sqlite":
table = request.session["tablenamesql"]
else:
table = request.session["tablename"]
connection_string = get_connection(request)
df = get_data(connection_string,table)
return df
def validatequery(request,table_details,join_details,where_details):
resultdata = []
try:
table_details = json.loads(table_details)
join_details = json.loads(join_details)
where_details = json.loads(where_details)
connection_string = get_connection(request)
engine = db.create_engine(connection_string)
connection = engine.connect()
metadata = db.MetaData()
metadata.reflect(engine)
sel_col = []
for item in table_details:
table = item["TableName"]
table = db.Table(table, metadata, autoload=True, autoload_with=engine)
for ele in item["Fields"]:
if str(ele["is_select"]).lower() == 'true':
sel_col.append(table.columns[ele["column_name"]])
join_condition = []
where_clause = ""
for item in join_details:
table1 = item["Table1Name"]
table1 = db.Table(table1, metadata, autoload=True, autoload_with=engine)
left_join = table1.columns[item["Table1Field"]]
table2 = item["Table2Name"]
table2 = db.Table(table2, metadata, autoload=True, autoload_with=engine)
right_join = table2.columns[item["Table2Field"]]
join_condition = "{left_join} {Condition}= {right_join}".format(left_join=left_join,
Condition=item["Condition"],right_join= right_join)
'''dbType = request.session['dbType']
if dbType.lower()=="sqlite":
for item in where_details:
where_clause = "{table}.'{column}'{condition}{value}".format(table=item["TableName"],column=str(item["FieldName"]),condition=item["Condition"],value=item["CompareValue"])
if dbType.lower()=="postgresql":
for item in where_details:
where_clause = "{table}.{column}{condition}{value}".format(table=item["TableName"],column=str(item["FieldName"]),condition=item["Condition"],value=item["CompareValue"])
'''
if len(join_details)!=0:
try:
for item in where_details:
where_clause = "{table}.'{column}'{condition}{value}".format(table=item["TableName"],column=str(item["FieldName"]),condition=item["Condition"],value=item["CompareValue"])
query =db.select(sel_col).\\
select_from(table1.join(table2,db.text(join_condition))). \\
where(db.and_(db.text(where_clause)))
ResultProxy = connection.execute(query)
ResultSet = ResultProxy.fetchall()
except:
for item in where_details:
where_clause = "{table}.{column}{condition}{value}".format(table=item["TableName"],column=str(item["FieldName"]),condition=item["Condition"],value=item["CompareValue"])
query =db.select(sel_col).\\
select_from(table1.join(table2,db.text(join_condition))). \\
where(db.and_(db.text(where_clause)))
ResultProxy = connection.execute(query)
ResultSet = ResultProxy.fetchall()
else:
table = table_details[0]["TableName"]
table = db.Table(table, metadata, autoload=True, autoload_with=engine)
try:
for item in where_details:
where_clause = "{table}.'{column}'{condition}{value}".format(table=item["TableName"],column=str(item["FieldName"]),condition=item["Condition"],value=item["CompareValue"])
query = db.select(sel_col). \\
select_from(table). \\
where(db.and_(db.text(where_clause)))
ResultProxy = connection.execute(query)
ResultSet = ResultProxy.fetchall()
except:
for item in where_details:
where_clause = "{table}.{column}{condition}{value}".format(table=item["TableName"],column=str(item["FieldName"]),condition=item["Condition"],value=item["CompareValue"])
query = db.select(sel_col). \\
select_from(table). \\
where(db.and_(db.text(where_clause)))
ResultProxy = connection.execute(query)
ResultSet = ResultProxy.fetchall()
if len(ResultSet) > 0:
data = pd.DataFrame(ResultSet)
data.columns = ResultSet[0].keys()
print(data)
return data,"query exectuted successfully"
else:
return pd.DataFrame(),"No rows returned"
# conn = get_connection(server_url,username_actian,password_actian,database_actian)
# sql_text = query
# cur = conn.cursor()
# resultdata = simple_select(cur, query)
# cur.close()
#df = pd.DataFrame(resultdata)
#print(df)
except Exception as e:
print(e)
return pd.DataFrame(), str(e) <s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
from appbe.data_io import sqlite_db
from os.path import expanduser
import platform
import pandas as pd
import os
from appbe.dataPath import DATA_DIR
PUBLISH_PATH = os.path.join(DATA_DIR,'publish')
DEPLOY_DATABASE_PATH = os.path.join(DATA_DIR,'sqlite')
def chech_publish_info(usecasename):
version = 0
status = 'Not Published'
inputDriftStatus = 'No Drift'
MODEL_DEPLOY_DATABASE_PATH = os.path.join(PUBLISH_PATH,usecasename,'database')
sqlite_dbObj = sqlite_db(DEPLOY_DATABASE_PATH,'deploy.db')
if sqlite_dbObj.table_exists('publish'):
data = sqlite_dbObj.read('publish',"usecase = '"+usecasename+"' and status = 'Published'")
if data.shape[0] > 0:
model_sqlite_dbObj = sqlite_db(MODEL_DEPLOY_DATABASE_PATH,'deploy.db')
version = data['version'].iloc[0]
status = 'Published'
if model_sqlite_dbObj.table_exists('monitoring'):
data = model_sqlite_dbObj.read('monitoring',"version = '"+str(version)+"'")
if data.shape[0] > 0:
msg = data['Msg'].iloc[-1]
if 'Affected Columns' in msg:
inputDriftStatus = 'Input Drift Found'
return version,status,inputDriftStatus
def check_input_data(usecasename):
MODEL_DEPLOY_DATABASE_PATH = os.path.join(PUBLISH_PATH,usecasename,'database')
sqlite_dbObj = sqlite_db(DEPLOY_DATABASE_PATH,'deploy.db')
data = pd.DataFrame()
if sqlite_dbObj.table_exists('publish'):
dataa = sqlite_dbObj.read('publish',"usecase = '"+usecasename+"' and status = 'Published'")
if dataa.shape[0] > 0:
modelsqlite_dbObj = sqlite_db(MODEL_DEPLOY_DATABASE_PATH,'deploy.db')
if modelsqlite_dbObj.table_exists('prodData'):
data = modelsqlite_dbObj.read('prodData')
return data
<s> # -*- coding: utf-8 -*-
import os
# import glob
from glob import glob
import ast
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
import pandas as pd
import json
import time
import logging
from datetime import datetime
""" Code clone detection based on user input files. """
class codeCloneDetectionSklearn:
""" Detect code clones based on sklearn text vectorizer modules.
Input params: files_dir: python files folder,
deply_dir: logs,resultant dataframe stored location.
chunk_size: max size split for the input text or code function.
return values: report_dict which contains clone type, path and clones. """
def __init__(self,files_dir,deploy_dir, chunk_size):
self.files_dir = files_dir
self.deploy_dir = deploy_dir
self.chunk_size = chunk_size
try:
self.ccdreportpath = os.path.join(self.deploy_dir, "codeCloneReport")
os.makedirs(self.ccdreportpath, exist_ok = True)
except OSError as error:
print("Directory 'codeCloneReport' cann't be created.Error msg: ",error)
try:
current_datetime = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
str_current_datetime = str(current_datetime)
log_file_name = 'codeclonelog_sklearn'+f"_{str_current_datetime}"+".log"
logpath = os.path.join(self.ccdreportpath,log_file_name)
logging.basicConfig(level=logging.INFO,filename=logpath,filemode='w',format='%(message)s')
self.log = logging.getLogger()
except Exception as e:
print("code clone log object creation error.",e)
pass
def get_function_names(self,filename):
""" Get the function names from python files """
try:
with open(filename, 'r') as file:
content = file.read()
tree = ast.parse(content)
function_names = []
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
function_names.append(node.name)
except Exception as e:
self.log.info("function name read error: "+str(e))
return function_names
def get_function_code(self,filename, function_name):
""" To get the function codes """
try:
with open(filename, 'r') as file:
content = file.read()
tree = ast. | ||
parse(content)
function_code = ""
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef) and node.name == function_name:
function_code = ast.unparse(node)
except Exception as e:
self.log.info("function name read error: "+str(e))
return function_code
def get_python_files(self,root_dir):
""" Walk thru the directory user given, get all py files. """
try:
code_files = [y for x in os.walk(root_dir) for y in glob(os.path.join(x[0], '*.py'))]
except Exception as e:
self.log.info("Python file read error: "+str(e))
return code_files
def chunk_functions(self,function_code, chunk_size):
""" Check the function size based on chunk size. """
try:
if (len(function_code) > 20):
chunks = [function_code[i:i + chunk_size] for i in range(0, len(function_code), chunk_size)]
else:
chunks = list((function_code,))
except Exception as e:
self.log.info("function chunk based on chunk_size error: "+str(e))
total_tokens = round(len(function_code)/4)
return chunks,total_tokens
def get_clone(self):
""" Main code clone detection function using sklearn tfidf_vectorizer and cosine_similarity.
return values:report_dict which contains total_clones, """
try:
start_time = time.time()
chunk_size = int(self.chunk_size)
ccdreportpath = os.path.join(self.deploy_dir, "codeCloneReport")
python_files = self.get_python_files(self.files_dir)
total_files = len(python_files)
# print('python_files: \\n',python_files)
function_codes = []
function_n = []
file_name=[]
# files_info=[]
total_tokens_used = []
for file in python_files:
function_names = self.get_function_names(file)
for i,function_name in enumerate(function_names):
file_name.append(file)
function_n.append(function_name)
function_code = self.get_function_code(file, function_name)
chunks,total_tokens = self.chunk_functions(function_code, chunk_size)
total_tokens_used.append(total_tokens)
function_codes.extend(chunks)
total_functions = len(function_n)
files_info=list(zip(file_name, function_n,function_codes))
tfidf_vectorizer = TfidfVectorizer()
## we can use other vectorizer models also.
# tfidf_vectorizer = HashingVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(function_codes)
similarity_matrix = cosine_similarity(tfidf_matrix)
#Uncomment if you want to send two different code clonne blocks at a time for similarity comparison
# similarity_matrix = cosine_similarity(tfidf_matrix, tfidf_matrix)
clone_d = dict()
total_clones = 0
final_report=list()
#getting funtion and next function for comparison
for i in range(len(similarity_matrix)):
for j in range(i + 1, len(similarity_matrix)):
if(similarity_matrix[i, j] >= 0.90 and similarity_matrix[i, j] <= 0.95):
clone_d.update({f'codeclone_{total_clones+1}':{f'function{i}':{'clone_fun_name':function_n[i],'clone1_path':files_info[i][0]},f'function{j}':{'clone_fun_name':function_n[j],'clone1_path':files_info[j][0]},'cloneType':'parametricClone'}})
report_json = json.dumps(clone_d, indent = 4)
total_clones=total_clones+1
elif(similarity_matrix[i, j] > 0.95):
clone_d.update({f'codeclone_{total_clones+1}':{f'function{i}':{'clone_fun_name':function_n[i],'clone_path':files_info[i][0]},f'function{j}':{'clone_fun_name':function_n[j],'clone_path':files_info[j][0]
},'cloneType':'exactClone'}})
report_json = json.dumps(clone_d, indent = 4)
final_report.append(clone_d)
total_clones=total_clones+1
elif(similarity_matrix[i, j] > 0.80 and similarity_matrix[i, j] < 0.90):
clone_d.update({f'codeclone_{total_clones+1}':{f'function{i}':{'clone_fun_name':function_n[i],'clone_path':files_info[i][0]},f'function{j}':{'clone_fun_name':function_n[j],'clone_path':files_info[j][0]
},'cloneType':'NearMissClones'}})
report_json = json.dumps(clone_d, indent = 4)
final_report.append(clone_d)
total_clones=total_clones+1
else:
##add other conditionas in future
pass
## To get clone type
clone_type = [list(item.values())[2] for item in list(clone_d.values())]
report_str = json.dumps(final_report)
json_l=json.loads(report_str)
json_keys = list(json_l[0].keys())
json_values = list(json_l[0].values())
end_time = time.time()
total_time_taken = end_time - start_time
# self.log.info("ccd_report: \\n"+str(ccd_report))
f_df=pd.DataFrame(list(zip(json_keys, json_values,clone_type)),
columns =['Clone', 'CloneDetails','CloneType'])
codeclonereport_file = os.path.join(self.ccdreportpath,'clone_detection_report_sklearn.csv')
f_df.to_csv(codeclonereport_file, index=False)
ccd_report = f_df.to_markdown(tablefmt='psql')
self.log.info("total_clones: \\n"+str(total_clones))
exact_clone_count = f_df['CloneType'].str.count("exactClone").sum()
parametric_clone_count = f_df['CloneType'].str.count("parametricClone").sum()
nearmiss_clone_count = f_df['CloneType'].str.count("NearMissClones").sum()
total_tokens = sum(total_tokens_used)
# nearmiss_clone_count =0
self.log.info("exact_clone_count: \\n"+str(exact_clone_count))
self.log.info("parametric_clone_count: \\n"+str(parametric_clone_count))
self.log.info("nearmiss_clone_count: \\n"+str(nearmiss_clone_count))
self.log.info("Total tokens used: \\n"+str(total_tokens))
self.log.info("Total time taken to excute code clone detction: \\t"+str(total_time_taken))
clone_info="1. Exact clone: Two code fragments similar to each other with little transformation in comments, layout, or whitespaces,\\
2. Parameterized clone: Changes made in names of variables, keywords, identifiers, or bypassing parameter during function call in code fragments and less similarity threshold (0.90-0.95), result in this clone,\\
3. Near-miss clone: Near-miss clone are clones detected with less similarity threshold."
clone_count = {"Exact Clone":exact_clone_count,"Parametric Clone":parametric_clone_count,"Nearmiss Clone":nearmiss_clone_count}
report_str = f"""Code_directory: {self.files_dir}
Files: {total_files}
Functions: {total_functions}
Total_code_clones_detected: {total_clones}
Tokens used: {total_tokens}
Three_types_of_clone:
1. Exact clone: Two code fragments similar to each other with little transformation in comments, layout, or whitespaces.
2. Parameterized clone: Changes made in names of variables, keywords, identifiers, or bypassing parameter during function call in code fragments and less similarity threshold (0.90-0.95), result in this clone.
3. Near-miss clone: Near-miss clone are clones detected with less similarity threshold.
Code_clones_count_by_clone_type:
{clone_count}
Clone_functions:
{ccd_report}
total_time_taken: {total_time_taken}
"""
codeclonereport_txt = os.path.join(self.ccdreportpath,'code_clone_report.txt')
with open(codeclonereport_txt, "w") as f:
f.write(report_str)
report_dict = {"clone_info":clone_info,"total_clones":total_clones,'total_files':total_files,"exact_clone_count":exact_clone_count,'total_functions':total_functions,"total_tokens":total_tokens, "parametric_clone_count":parametric_clone_count,"nearmiss_clone_count":nearmiss_clone_count,"result_df":f_df }
self.log.info("ccd_report: \\n"+str(ccd_report))
# print("report_dict:\\n\\n",report_dict)
# end_time = time.time()
# total_time = (end_time - start_time)
return report_dict
except Exception as e:
self.log.info("Clone detection function error. error msg: "+str(e))
# import traceback
# print("traceback error: \\n",traceback.print_exc())
if __name__ == "__main__":
print("code clone detection started....")
##Use this for standalone fn debuging.<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os
from os.path import expanduser
import platform
import json
import subprocess
import re
import sys
import pandas as pd
from django.http import HttpResponse
from appbe.dataPath import DATA_DIR
Usecaselocation = os.path.join(DATA_DIR,'Usecases')
def mlstyles(request):
try:
from appbe.aion_config import settings
usecasetab = settings()
selectid = request.GET['usecaseid']
configFile = os.path.join(Usecaselocation, 'usecases.json')
f = open(configFile, "r")
configSettings = f.read()
f.close()
configSettingsJson = json.loads(configSettings)
#usecase = configSettingsJson['usecaselist']
desciption=""
usecasename=""
found = False
for v_id in configSettingsJson['verticallist']:
for p_id in v_id['usecaselist']:
usecaseid = p_id.get('usecaseid')
if str(usecaseid) == str(selectid) :
usecasename = p_id.get('usecasename')
desciption = p_id.get('desciption')
usecaseid = p_id.get('usecaseid')
iconname = p_id.get('iconname')
prediction_input = p_id.get('prediction_input')
outputtype = p_id.get('outputtype')
smalldescription = p_id.get('smalldescription')
trainingFeatures = p_id.get('trainingFeatures','None')
if trainingFeatures != 'None':
trainingFeatures = trainingFeatures.split(',')
found = True
break
if found == True:
break
#print(usecaseid,selectid)
context ={'usecasename':usecasename,'desciption':desciption,'prediction_input':prediction_input,'usecaseid':usecaseid,'trainingFeatures':trainingFeatures,'iconname':iconname,'smalldescription':smalldescription,'outputtype':outputtype,'usecasetab':usecasetab}
return context
except Exception as inst:
print(inst)
context = { 'error3':'error3','error1': "No UseCases to show"}
return context
def getusecasedetails(selectid):
configFile = os.path.join(Usecaselocation, 'usecases.json')
f = open(configFile, "r")
configSettings = f.read()
f.close()
configSettingsJson = json.loads(configSettings)
#usecase = configSettingsJson['usecaselist']
desciption=""
usecasename=""
found = False
for v_id in configSettingsJson['verticallist']:
for p_id in v_id['usecaselist']:
usecaseid = p_id.get('usecaseid')
if str(usecaseid) == str(selectid) :
usecasename = p_id.get('usecasename')
desciption = p_id.get('desciption')
usecaseid = p_id.get('usecaseid')
modelConfig = p_id.get('modelConfig')
folder = p_id.get('folder')
prediction = p_id.get('prediction')
prediction_input = p_id.get('prediction_input')
ai_modeldata = p_id.get('modeldata')
outputtype = p_id.get('outputtype')
smalldescription = p_id.get('smalldescription')
prediction_template = p_id.get('prediction_template')
trainingFeatures = p_id.get('trainingFeatures','None')
if trainingFeatures != 'None':
trainingFeatures = trainingFeatures.split(',')
found = True
break
if found == True:
break
#print(usecasename)
return(usecasename,desciption,usecaseid,modelConfig,folder,prediction,prediction_input,ai_modeldata,outputtype,smalldescription,prediction_template,trainingFeatures)
def mlpredict(request):
selectid=request.POST.get('usecaseid')
mlpredict =request.POST.get('mlpredict')
usecasename,desciption,usecaseid,modelConfig,folder,prediction,prediction_input,ai_modeldata,output | ||
type,smalldescription,prediction_template,trainingFeatures = getusecasedetails(selectid)
from appbe.aion_config import settings
usecasetab = settings()
usecasename = usecasename
desciption = desciption
input=''
for x in prediction_input:
if input != '':
input += ','
input = request.POST.get(x['name'])
if mlpredict in ['prediction','predictsingle']:
if mlpredict == 'prediction':
dataFile = request.POST.get('predictfilePath')
if(os.path.isfile(dataFile) == False) or dataFile=="":
context = {'usecaseid':selectid ,'dataFile':dataFile,'usecasename':usecasename,'desciption':desciption , 'error1': 'Please enter a valid csv filepath','usecasetab':usecasetab}
return context, mlpredict
else:
inputFieldsDict = {}
for feature in trainingFeatures:
inputFieldsDict[feature] = request.POST.get(feature)
dataFile = json.dumps(inputFieldsDict)
try:
predictionScriptPath= os.path.join(Usecaselocation,folder,'model',prediction)
# predictionScriptPath = os.path.join(predictionscript, 'aion_prediction.py')
outputStr = subprocess.check_output([sys.executable, predictionScriptPath, dataFile,input])
outputStr = outputStr.decode('utf-8')
outputStr = re.search(r'predictions:(.*)', str(outputStr), re.IGNORECASE).group(1)
outputStr = outputStr.strip()
predict_dict = json.loads(outputStr)
#print(predict_dict)
heading =''
timetaken=''
print(predict_dict)
if (predict_dict['status'] == 'SUCCESS'):
predictionResults = predict_dict['data']
#print(predictionResults)
if 'heading' in predict_dict:
heading = predict_dict['heading']
if 'Time' in predict_dict:
timetaken = round(predict_dict['Time'],2)
if outputtype.lower() in ['similarityidentification','contextualsearch']:
data = predictionResults[0]
predictionResults= []
Results={}
prediction = data['prediction']
i = 1
for x in prediction:
te = ''
for y in x:
info = (str(x[y])[:100] + '...') if len(str(x[y])) > 100 else str(x[y])
te += y+': '+info+'\\n\\n'
Results[i] = te
i = i+1
predictionResults.append(Results)
else:
context = {'usecaseid':selectid ,'dataFile':dataFile,'prediction_input':prediction_input,'usecasename':usecasename,'desciption':desciption , 'error': 'Failed To perform prediction','usecasetab':usecasetab}
return context, mlpredict
print(heading)
context = {'usecasename':usecasename,'desciption':desciption,'prediction_input':prediction_input,'usecaseid':selectid ,'dataFile':dataFile,'predictionResults': predictionResults,'outputtype':outputtype,'heading':heading,'timetaken':timetaken,'usecasetab':usecasetab,'trainingFeatures':trainingFeatures}
return context, mlpredict
except Exception as inst:
print(inst)
context = { 'usecaseid':selectid ,'dataFile':dataFile,'usecasename':usecasename,'desciption':desciption ,'errorp': 'Failed To perform prediction','usecasetab':usecasetab}
return context, mlpredict
if mlpredict == 'download_predict':
# predictionResults = 'C:\\\\DataSets\\\\Classification\\\\bug_severity_class.csv'
try:
csvdata= os.path.join(Usecaselocation,folder,'Data',prediction_template)
if os.path.isfile(csvdata) and os.path.exists(csvdata):
df = pd.read_csv(csvdata,encoding='utf8',encoding_errors= 'replace')
downloadFileName = usecasename.replace(" ", "_") + '_predict.csv'
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename='+downloadFileName
df.to_csv(response, index=False)
return response,mlpredict
else:
context = {'usecaseid':selectid ,'dataFile':dataFile,'usecasename':usecasename,'desciption':desciption, 'error': 'File not found','usecasetab':usecasetab}
return context, mlpredict
except Exception as inst:
context = { 'usecaseid':selectid ,'usecasename':usecasename,'desciption':desciption, 'error3':'error3','error1': 'Failed To Download','usecasetab':usecasetab}
return context, mltrain
def process(data):
cleaned_data = {"verticallist":[]}
for vertical in data['verticallist']:
updated_list = []
for usecase in vertical['usecaselist']:
if usecase['prediction'] and usecase['prediction'] != "Not Implemented":
updated_list.append(usecase)
if updated_list:
cleaned_data['verticallist'].append({'id':vertical['id'],'name':vertical['name'],'usecaselist':updated_list})
return cleaned_data
def Aiusecases(request,selectedoption='Implemented'):
try:
from appbe.aion_config import settings
usecasetab = settings()
configFile = os.path.join(Usecaselocation, 'usecases.json')
f = open(configFile, "r")
configSettings = f.read()
f.close()
configSettingsJson = json.loads(configSettings)
if selectedoption == 'Implemented':
configSettingsJson = process(configSettingsJson)
usecasedetails = configSettingsJson['verticallist']
context ={'desciption1':usecasedetails,'selected':'AIusecases','usecasetab':usecasetab}
return context
except Exception as e:
print(e)
context ={'error':"No Usecases to Show",'selected':'AIusecases','usecasetab':usecasetab}
return context
def mltrain(request):
from appbe.aion_config import settings
usecasetab = settings()
selectid =request.POST.get('usecaseid1')
mltrain =request.POST.get('mltrain')
usecasename,desciption,usecaseid,modelConfig,folder,prediction,prediction_input,ai_modeldata,outputtype,smalldescription,prediction_template,trainingFeatures = getusecasedetails(selectid)
usecasename = usecasename
desciption = desciption
if mltrain == 'training':
dataFile = request.POST.get('trainfilePath')
if(os.path.isfile(dataFile) == False) or dataFile=="":
context = {'usecaseid':selectid ,'datatrainFile':dataFile,'usecasename':usecasename,'desciption':desciption ,'error3':'error3','error1': 'Please enter a valid csv filepath'}
return context, mltrain
try:
scriptPath = os.path.join(Usecaselocation,folder,'config','aion_train.py')
print(scriptPath,dataFile)
outputStr = subprocess.check_output([sys.executable, scriptPath, dataFile])
outputStr = outputStr.decode('utf-8')
outputStr = re.search(r'aion_learner_status:(.*)', str(outputStr), re.IGNORECASE).group(1)
outputStr = outputStr.strip()
train = json.loads(outputStr)
status = train['status']
DeployLocation = train['data']['deployLocation']
ModelType = train['data']['ModelType']
BestModel = train['data']['BestModel']
BestScore = train['data']['BestScore']
ScoreType = train['data']['ScoreType']
FeaturesUsed = train['data']['featuresused']
context={'result':train,'usecaseid':selectid ,'datatrainFile':dataFile,'usecasename':usecasename,'desciption':desciption,'status':status,'DeployLocation':DeployLocation,'ModelType':ModelType,'BestModel':BestModel,'BestScore':BestScore,'ScoreType':ScoreType,'FeaturesUsed':FeaturesUsed,'result':'result','usecasetab':usecasetab}
return context,mltrain
except Exception as inst:
context = {'usecaseid':selectid ,'datatrainFile':dataFile,'usecasename':usecasename,'desciption':desciption, 'errort': 'Failed To perform Training','usecasetab':usecasetab}
return context, mltrain
if mltrain == 'download_train':
try:
csvdata= os.path.join(Usecaselocation,folder,'data',ai_modeldata)
#print(csvdata)
if os.path.isfile(csvdata) and os.path.exists(csvdata):
df = pd.read_csv(csvdata,encoding='utf8',encoding_errors= 'replace')
downloadFileName = usecasename.replace(" ", "_") + '_training.csv'
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename='+downloadFileName
df.to_csv(response, index=False)
return response,mltrain
else:
context = {'usecaseid':selectid ,'datatrainFile':dataFile,'usecasename':usecasename,'desciption':desciption, 'error': 'File not found','usecasetab':usecasetab}
return context, mltrain
except Exception as inst:
context = { 'usecaseid':selectid ,'usecasename':usecasename,'desciption':desciption, 'error3':'error3','error1': 'Failed To Download','usecasetab':usecasetab}
return context, mltrain
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import math
import sys,os
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
import numpy as np
import scipy.stats as st
from sklearn.preprocessing import StandardScaler
from dython.nominal import associations
class ux_eda ():
def __init__(self, dataPath=pd.DataFrame(),delimiter=',',textqualifier='"',optimize=None,):
aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
self.dataFrame = pd.DataFrame()
if isinstance(dataPath, pd.DataFrame):
self.dataFrame = dataPath
if optimize == 1:
self.dataFrame = self.dataFrame.sample(n=1000, random_state=1)
else:
if optimize == 1:
self.dataFrame = pd.read_csv(dataPath,nrows=1000,encoding='utf-8',sep=delimiter,quotechar=textqualifier,skipinitialspace = True,na_values=['-','?'],encoding_errors= 'replace')
else:
self.dataFrame = pd.read_csv(dataPath, encoding='utf-8',sep=delimiter,quotechar=textqualifier,skipinitialspace = True,na_values=['-','?'],encoding_errors= 'replace')
self.dataFrame.rename(columns=lambda x: x.strip(), inplace=True)
self.features = self.dataFrame.columns.tolist()
self.indexFeature = []
self.dateFeature = []
self.categoricalFeature = []
self.constantFeature = []
self.textFeature = []
self.numericFeature = []
self.numericAndCatFeature = []
for feature, featureType in zip(self.features, self.dataFrame.dtypes):
if self.__check_seq_feature(self.dataFrame[feature]):
self.indexFeature.append(feature)
elif self.__match_date_format(self.dataFrame[feature]):
self.dateFeature.append(feature)
elif self.__check_constant_features(self.dataFrame[feature]):
self.constantFeature.append(feature)
elif self.__check_category_features(self.dataFrame[feature]):
self.categoricalFeature.append(feature)
elif featureType == 'object':
'''
numOfRows = self.dataFrame.shape[0]
distinctCount = len(self.dataFrame[feature].unique())
tempDff = self.dataFrame[feature]
self.dataFrame[feature]=self.dataFrame[feature].apply(lambda x: self.testNum(x))
tempDf = self.dataFrame[feature]
tempDf = tempDf.dropna()
numberOfNonNullVals = tempDf.count()
numericRatio = 0.8
if(numberOfNonNullVals > int(numOfRows * numericRatio)):
self.numericFeature.append(feature)
else:
self.dataFrame[feature] = tempDff
'''
self.textFeature.append(feature)
elif featureType in aionNumericDtypes:
self.numericFeature.append(feature)
# self.dataFrame[self.categoricalFeature] = self.dataFrame[self.categoricalFeature].apply(lambda x: x.cat.codes)
self.numericAndCatFeature = self.numericFeature + self.categoricalFeature
# EDA Performance change
# ----------------------------
def subsampleData(self, subsampleData):
self.dataFrame = self.dataFrame.sample(n=subsampleData, random_state=1)
def get_features_datatype(self,v,num_list,cat_list,text_list):
""" To get exact datatype of the feature in Data Overview."""
if v in cat_list:
return 'Categorical'
elif v in num_list:
return 'Numerical'
elif v in text_list:
return 'Text'
def getCorrelationMatrix(self):
try:
if len(self.dataFrame.columns) > 25:
df3 = df[self.dataFrame.columns[0:24]]
else:
df3 = self.dataFrame.copy()
cor_mat= associations(self.dataFrame,compute_only=True)
cor_mat=cor_mat['corr']
cor_mat = cor_mat.astype(float).round(2)
cor_mat.replace(np.nan, 0, inplace=True)
cor_mat.fillna('None',inplace=True)
return cor_mat
except Exception as e:
print(e)
correlationgraph = pd.DataFrame()
return (correlationgraph)
def dataDistribution(self):
df_eda_actual = self.dataFrame.copy()
| ||
des1 = df_eda_actual.describe(include='all').T
des1['missing count %'] = df_eda_actual.isnull().mean() * 100
des1['zero count %'] = df_eda_actual.isin([0]).mean() * 100
dataColumns = list(self.dataFrame.columns.values)
des1.insert(0, 'Features', dataColumns)
actual_df_numerical_features = df_eda_actual.select_dtypes(exclude='object')
actual_df_categorical_features = df_eda_actual.select_dtypes(include='object')
#For text features
textFeature_df = df_eda_actual.filter(self.textFeature)
actual_df_categorical_features = actual_df_categorical_features.drop(self.textFeature, axis=1)
for i in des1['Features']:
num_cols = actual_df_numerical_features.columns.to_list()
cat_cols = actual_df_categorical_features.columns.to_list()
text_cols = self.textFeature
des1['Features Type'] = des1['Features'].apply(lambda x: self.get_features_datatype(x, num_cols,cat_cols,text_cols))
curr_columns = des1.columns.to_list()
curr_columns.remove('Features Type')
insert_i = curr_columns.index('Features')+1
curr_columns.insert(insert_i,'Features Type')
des1 = des1[curr_columns]
return des1
# ----------------------------
def subsetFeatures(self, edaFeatures):
print(self.dataFrame.columns)
self.dataFrame = self.dataFrame[edaFeatures]
self.features = edaFeatures
self.indexFeature = []
self.dateFeature = []
self.categoricalFeature = []
self.constantFeature = []
self.textFeature = []
self.numericFeature = []
self.numericAndCatFeature = []
print('abc')
aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
for feature, featureType in zip(self.features, self.dataFrame.dtypes):
if self.__check_seq_feature(self.dataFrame[feature]):
self.indexFeature.append(feature)
elif self.__match_date_format(self.dataFrame[feature]):
self.dateFeature.append(feature)
elif self.__check_constant_features(self.dataFrame[feature]):
self.constantFeature.append(feature)
elif self.__check_category_features(self.dataFrame[feature]):
self.categoricalFeature.append(feature)
elif featureType == 'object':
'''
numOfRows = self.dataFrame.shape[0]
distinctCount = len(self.dataFrame[feature].unique())
tempDff = self.dataFrame[feature]
self.dataFrame[feature]=self.dataFrame[feature].apply(lambda x: self.testNum(x))
tempDf = self.dataFrame[feature]
tempDf = tempDf.dropna()
numberOfNonNullVals = tempDf.count()
numericRatio = 0.8
if(numberOfNonNullVals > int(numOfRows * numericRatio)):
self.numericFeature.append(feature)
else:
self.dataFrame[feature] = tempDff
'''
self.textFeature.append(feature)
elif featureType in aionNumericDtypes:
self.numericFeature.append(feature)
print('def')
self.numericAndCatFeature = self.numericFeature + self.categoricalFeature
# ----------------------------
def testNum(self,value):
try:
x=eval(value)
return x
except:
return np.nan
def getFeatures(self):
leastRatioFeature = self.__LeastfeatureRatio()
return (self.features, self.dateFeature, self.indexFeature, self.constantFeature, self.textFeature, leastRatioFeature,self.numericAndCatFeature,self.numericFeature,self.categoricalFeature)
def getNumericFeatureCount(self):
return(len(self.numericAndCatFeature))
def calculateNumberofCluster(self):
df = self.dataFrame[self.numericFeature]
return self.__NumberofCluster(df)
def getTopTextFeatures(self,topn):
df_text = pd.DataFrame()
if (len(self.textFeature) > 1):
df_text['combined'] = self.dataFrame[self.textFeature].apply(lambda row: ' '.join(row.values.astype(str)), axis=1)
features = ['combined']
else:
df_text[['combined']] = self.dataFrame[self.textFeature]
features = ['combined']
df_text[features[0]] = df_text[features[0]].fillna("NA")
textCorpus = df_text[features[0]]
from text import eda
texteda_obj = eda.ExploreTextData()
df = texteda_obj.MostCommonWords(textCorpus,topn)
return df
def __NumberofCluster(self, featureData):
Sum_of_squared_distances = []
K = range(1, 15)
for k in K:
km = KMeans(n_clusters=k)
km = km.fit(featureData)
Sum_of_squared_distances.append(km.inertia_)
x1, y1 = 1, Sum_of_squared_distances[0]
x2, y2 = 15, Sum_of_squared_distances[len(Sum_of_squared_distances) - 1]
distances = []
for inertia in range(len(Sum_of_squared_distances)):
x0 = inertia + 2
y0 = Sum_of_squared_distances[inertia]
numerator = abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1)
denominator = math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)
distances.append(numerator / denominator)
n_clusters = distances.index(max(distances)) + 2
return (n_clusters)
#13841 : TrustedAI: hopkins stat
def getHopkinsVal(self,df):
try:
from appbe.hopkinsStat import hopkins
from sklearn.preprocessing import StandardScaler,OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
numeric_transformer = Pipeline(
steps=[("imputer", SimpleImputer(missing_values=np.nan,strategy="mean")),
("standard_scaler", StandardScaler())]
)
categorical_transformer = Pipeline(
steps=[
("imputer", SimpleImputer(missing_values=np.nan,strategy="most_frequent")),
("encoder", OneHotEncoder(handle_unknown="ignore"))
]
)
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, self.numericFeature),
("cat", categorical_transformer, self.categoricalFeature)
]
)
pipe = Pipeline([('scaler',preprocessor)])
scaled_df = pipe.fit_transform(df)
if type(scaled_df) != np.ndarray:
scaled_df = scaled_df.toarray()
score = round(hopkins(scaled_df,scaled_df.shape[0]),2)
return str(score)
except Exception as e:
print(e)
return ''
def getClusterDetails(self):
aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
df_clus = pd.get_dummies(self.dataFrame[self.numericAndCatFeature], prefix_sep='####')
for i in df_clus.columns:
dataType = df_clus[i].dtypes
if dataType not in aionNumericDtypes:
df_clus[i] = df_clus[i].fillna(df_clus[i].mode()[0])
else:
df_clus[i] = df_clus[i].fillna(df_clus[i].mean())
n = self.__NumberofCluster(df_clus)
n = n - 1
kmeans = KMeans(n_clusters=n, init='k-means++', max_iter=10, n_init=10, random_state=0)
# Fit and predict
y_means = kmeans.fit_predict(df_clus)
centroids = kmeans.cluster_centers_.squeeze()
labels = kmeans.labels_
features = df_clus.columns
cluster_details = []
for j in range(len(features)):
cluster = {}
feature = features[j]
perflag = 0
if '####' in feature:
x = features[j].split('####')
feature = x[0] + ' ' + x[1] + '(%)'
perflag = 1
else:
feature = feature + '(AVG)'
cluster['label'] = feature
total_sum = 0
if perflag == 1:
for i in range(n):
centroid = centroids[i]
value = round(centroid[j], 2)
total_sum = total_sum + value
for i in range(n):
centroid = centroids[i]
value = round(centroid[j], 2)
if perflag == 1:
value = (value / total_sum) * 100
value = round(value, 2)
cluster['Cluster ' + str(i + 1)] = value
cluster_details.append(cluster)
hopkins_val = self.getHopkinsVal(self.dataFrame,)
return cluster_details,hopkins_val
def getHighlyCorrelatedFeatures(self,noOfTop):
df_corr = abs(self.dataFrame[self.numericAndCatFeature].corr()).stack().reset_index()
df_corr.columns = ['FEATURE_1', 'FEATURE_2', 'CORRELATION']
mask_dups = (df_corr[['FEATURE_1', 'FEATURE_2']].apply(frozenset, axis=1).duplicated()) | (
df_corr['FEATURE_1'] == df_corr['FEATURE_2'])
df_corr = df_corr[~mask_dups]
df_corr = df_corr.sort_values(by='CORRELATION', ascending=False)
df_top = df_corr.head(n=noOfTop)
return(df_top)
# ---------------------- 12686:Data Distribution related Changes S T A R T ----------------------
def word_token_for_feature(self, selectedFeature, dataframe):
comment_words = ""
try:
df_text = pd.DataFrame()
df_text[[selectedFeature]] = dataframe
features = [selectedFeature]
df_text[features[0]] = df_text[features[0]].fillna("NA")
textCorpus = df_text[features[0]]
from text import TextProcessing
tp = TextProcessing.TextProcessing()
preprocessed_text = tp.transform(textCorpus)
df_text[selectedFeature] = preprocessed_text
df_text_list = df_text.values.tolist()
for val in df_text_list:
val = str(val)
tokens = val.split()
for i in range(len(tokens)):
tokens[i] = tokens[i].lower()
comment_words += " ".join(tokens) + " "
except:
comment_words = ""
return comment_words
# -------------------------------------------- E N D --------------------------------------------
def word_token(self):
df_text = pd.DataFrame()
if (len(self.textFeature) > 1):
df_text['combined'] = self.dataFrame[self.textFeature].apply(lambda row: ' '.join(row.values.astype(str)), axis=1)
features = ['combined']
else:
df_text[['combined']] = self.dataFrame[self.textFeature]
features = ['combined']
df_text[features[0]] = df_text[features[0]].fillna("NA")
textCorpus = df_text[features[0]]
from text import TextProcessing
tp = TextProcessing.TextProcessing()
preprocessed_text = tp.transform(textCorpus)
df_text['combined'] = preprocessed_text
df_text_list = df_text.values.tolist()
comment_words = ""
for val in df_text_list:
val = str(val)
tokens = val.split()
for i in range(len(tokens)):
tokens[i] = tokens[i].lower()
comment_words += " ".join(tokens) + " "
if comment_words == "":
comment_words = 'Not found any token'
return comment_words
def getdata(self):
return self.dataFrame
def getPCATop10Features(self):
aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
df = self.dataFrame[self.numericAndCatFeature]
for feature in self.numericAndCatFeature:
if feature in self.categoricalFeature:
df[feature] = pd.Categorical(df[feature])
df[feature] = df[feature].cat.codes
df[feature] = df[feature].fillna(df[feature].mode()[0])
else:
df[feature] = df[feature].fillna(df[feature].mean())
pca = PCA(n_components=2).fit(StandardScaler().fit_transform(df))
mapping = pd.DataFrame(pca.components_, columns=self.numericAndCatFeature)
mapping = mapping.diff(axis=0).abs()
mapping = mapping.iloc[1]
mapping = mapping.sort_values(ascending=False).head(10)
return mapping
def getTopRows(self, rows=5):
return self.dataFrame.head(rows)
def __check_seq_feature(self, data):
if data.dtypes in ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']:
total_record = data.count()
count = (data - data.shift() == 1).sum()
if ((total_record - count) == 1):
return True
return False
def __match_date_format(self, data):
try:
## Using regex lib, we are check if any col contains datetime format like yyyy-mm-dd or yyyy/mm/dd format. if it finds return true.
import re
u_data = data.to_string()
date_find = (re.findall(r"[0-9]{1,4}[\\_|\\-|\\/|\\|][0-9]{1,2}[\\_|\\-|\\/ | ||
|\\|][0-9]{1,4}", u_data) or re.findall(r'\\d{,2}\\-[A-Za-z]{,9}\\-\\d{,4}', u_data) or re.findall(r"[0-9]{1,4}[\\_|\\-|\\/|\\|][0-9]{1,2}[\\_|\\-|\\/|\\|][0-9]{1,4}.\\d" , u_data) or re.findall(r"[0-9]{1,4}[\\_|\\-|\\/|\\|][A-Za-z]{,9}[\\_|\\-|\\/|\\|][0-9]{1,4}", u_data))
if (date_find):
try:
data = pd.to_datetime(data, utc=True)
return True
except Exception as e:
##If not a datetime col, just pass to return false statement.
pass
except Exception as e:
data = data.astype(str)
beforecheckcount = data.count()
#####YYYY-MM-DD HH:MM:SS####
check1 = data[data.str.match(
r'(^\\d\\d\\d\\d-(0?[1-9]|1[0-2])-(0?[1-9]|[12][0-9]|3[01]) (00|0?[0-9]|1[0-9]|2[0-4]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])$)') == True]
aftercheckcount = check1.count()
if (beforecheckcount == aftercheckcount):
return True
#####MM/DD/YYYY HH:MM####
check2 = data[data.str.match(
r'(^(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])/(\\d\\d\\d\\d) (00|0?[0-9]|1[0-9]|2[0-4]):([0-9]|[0-5][0-9])$)') == True]
aftercheckcount = check2.count()
if (beforecheckcount == aftercheckcount):
return True
#####DD-MM-YYYY HH:MM####
check2 = data[data.str.match(
r'(^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[0-2])-(\\d\\d\\d\\d) (00|0?[0-9]|1[0-9]|2[0-4]):([0-9]|[0-5][0-9])$)') == True]
aftercheckcount = check2.count()
if (beforecheckcount == aftercheckcount):
return True
#####YYYY/MM/DD####
check2 = data[data.str.match(r'(^\\d\\d\\d\\d/(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])$)') == True]
aftercheckcount = check2.count()
if (beforecheckcount == aftercheckcount):
return True
#####MM/DD/YYYY####
check2 = data[data.str.match(r'(^(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])/(\\d\\d\\d\\d)$)') == True]
aftercheckcount = check2.count()
if (beforecheckcount == aftercheckcount):
return True
#####YYYY-MM-DD HH:MM:SS.fff####
check11 = data[data.str.match(
r'(^\\d\\d\\d\\d-(0?[1-9]|1[0-2])-(0?[1-9]|[12][0-9]|3[01]) (00|0?[0-9]|1[0-9]|2[0-4]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])\\.(\\d{3})$)') == True]
aftercheckcount = check11.count()
if (beforecheckcount == aftercheckcount):
return True
return False
def __check_category_features(self, modelFeatures):
aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
dataType = modelFeatures.dtypes
numOfRows = len(modelFeatures)
if dataType not in aionNumericDtypes:
if dataType != 'bool':
nUnique = len(modelFeatures.unique().tolist())
if nUnique <= 30:
return True
return False
def __check_constant_features(self, modelFeatures):
return len(modelFeatures.unique().tolist()) == 1
def __featureRatio(self, modelFeatures):
if len(modelFeatures):
return len(modelFeatures.unique().tolist()) / len(modelFeatures)
return 0
def __LeastfeatureRatio(self):
ratio = 1
feat = ""
for feature in (self.numericAndCatFeature + self.textFeature):
r = self.__featureRatio(self.dataFrame[feature])
if r < ratio:
ratio = r
feat = feature
return feat
def getDistribution(self):
aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
df = self.dataFrame[self.numericAndCatFeature]
dist={}
for feature in self.numericAndCatFeature:
if feature in self.categoricalFeature:
df[feature] = pd.Categorical(df[feature])
df[feature] = df[feature].cat.codes
df[feature] = df[feature].fillna(df[feature].mode()[0])
else:
df[feature] = df[feature].fillna(df[feature].mean())
distributionname,sse = self.DistributionFinder(df[feature])
if distributionname == '':
dist[feature] = 'Unknown'
else:
dist[feature] = distributionname
return dist
def DistributionFinder(self,data):
try:
distributionName = ""
sse = 0.0
KStestStatic = 0.0
dataType = ""
if (data.dtype == "float64"):
dataType = "Continuous"
elif (data.dtype == "int"):
dataType = "Discrete"
elif (data.dtype == "int64"):
dataType = "Discrete"
if (dataType == "Discrete"):
distributions = [st.bernoulli, st.binom, st.geom, st.nbinom, st.poisson]
index, counts = np.unique(data.astype(int), return_counts=True)
if (len(index) >= 2):
best_sse = np.inf
y1 = []
total = sum(counts)
mean = float(sum(index * counts)) / total
variance = float((sum(index ** 2 * counts) - total * mean ** 2)) / (total - 1)
dispersion = mean / float(variance)
theta = 1 / float(dispersion)
r = mean * (float(theta) / 1 - theta)
datamin = data.min()
datamax = data.max()
for j in counts:
y1.append(float(j) / total)
pmf1 = st.bernoulli.pmf(index, mean)
pmf2 = st.binom.pmf(index, len(index), p=mean / len(index))
pmf3 = st.geom.pmf(index, 1 / float(1 + mean))
pmf4 = st.nbinom.pmf(index, mean, r)
pmf5 = st.poisson.pmf(index, mean)
sse1 = np.sum(np.power(y1 - pmf1, 2.0))
sse2 = np.sum(np.power(y1 - pmf2, 2.0))
sse3 = np.sum(np.power(y1 - pmf3, 2.0))
sse4 = np.sum(np.power(y1 - pmf4, 2.0))
sse5 = np.sum(np.power(y1 - pmf5, 2.0))
sselist = [sse1, sse2, sse3, sse4, sse5]
best_distribution = 'NA'
for i in range(0, len(sselist)):
if best_sse > sselist[i] > 0:
best_distribution = distributions[i].name
best_sse = sselist[i]
elif (len(index) == 1):
best_distribution = "Constant Data-No Distribution"
best_sse = 0.0
distributionName = best_distribution
sse = best_sse
elif (dataType == "Continuous"):
distributions = [st.uniform, st.expon, st.weibull_max, st.weibull_min, st.chi, st.norm, st.lognorm, st.t,
st.gamma, st.beta]
best_distribution = st.norm.name
best_sse = np.inf
datamin = data.min()
datamax = data.max()
nrange = datamax - datamin
y, x = np.histogram(data.astype(float), bins='auto', density=True)
x = (x + np.roll(x, -1))[:-1] / 2.0
for distribution in distributions:
params = distribution.fit(data.astype(float))
arg = params[:-2]
loc = params[-2]
scale = params[-1]
pdf = distribution.pdf(x, loc=loc, scale=scale, *arg)
sse = np.sum(np.power(y - pdf, 2.0))
if (best_sse > sse > 0):
best_distribution = distribution.name
best_sse = sse
distributionName = best_distribution
sse = best_sse
except:
response = str(sys.exc_info()[0])
message = 'Job has Failed' + response
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type) + ' ' + str(fname) + ' ' + str(exc_tb.tb_lineno))
return distributionName, sse
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
#Standard Library modules
import sqlite3
import pandas as pd
from pathlib import Path
class sqlite_writer():
def __init__(self, target_path):
self.target_path = Path(target_path)
database_file = self.target_path.stem + '.db'
self.db = sqlite_db(self.target_path, database_file)
def file_exists(self, file):
if file:
return self.db.table_exists(file)
else:
return False
def read(self, file):
return self.db.read(file)
def write(self, data, file):
self.db.write(data, file)
def close(self):
self.db.close()
class sqlite_db():
def __init__(self, location, database_file=None):
if not isinstance(location, Path):
location = Path(location)
if database_file:
self.database_name = database_file
else:
self.database_name = location.stem + '.db'
db_file = str(location/self.database_name)
self.conn = sqlite3.connect(db_file)
self.cursor = self.conn.cursor()
self.tables = []
def table_exists(self, name):
if name in self.tables:
return True
elif name:
query = f"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}';"
listOfTables = self.cursor.execute(query).fetchall()
if len(listOfTables) > 0 :
self.tables.append(name)
return True
return False
def read(self, table_name,condition=''):
if condition == '':
return pd.read_sql_query(f"SELECT * FROM {table_name}", self.conn)
else:
return pd.read_sql_query(f"SELECT * FROM {table_name} WHERE {condition}", self.conn)
def create_table(self,name, columns, dtypes):
query = f'CREATE TABLE IF NOT EXISTS {name} ('
for column, data_type in zip(columns, dtypes):
query += f"'{column}' TEXT,"
query = query[:-1]
query += ');'
self.conn.execute(query)
return True
def update(self,table_name,updates,condition):
update_query = f'UPDATE {table_name} SET {updates} WHERE {condition}'
self.cursor.execute(update_query)
self.conn.commit()
return True
def write(self,data, table_name):
if not self.table_exists(table_name):
self.create_table(table_name, data.columns, data.dtypes)
tuple_data = list(data.itertuples(index=False, name=None))
insert_query = f'INSERT INTO {table_name} VALUES('
for i in range(len(data.columns)):
insert_query += '?,'
insert_query = insert_query[:-1] + ')'
self.cursor.executemany(insert_query, tuple_data)
self.conn.commit()
return True
def delete(self, name):
pass
def close(self):
self.conn.close()
<s> import json
import os
import random
import time
from avro.datafile import DataFileReader
from avro.io import DatumReader
from pyarrow.parquet import ParquetFile
from snorkel.labeling.model import LabelModel
from snorkel.labeling import PandasLFApplier, LFAnalysis
import pandas as pd
import pandavro as pdx
import pyarrow as pa
import numpy as np
import platform
from os.path import expanduser
home = expanduser("~")
if platform.system() == 'Windows':
DATA_FILE_PATH = os.path.join(home,'AppData','Local','Programs','HCLTech','AION','data','storage')
else:
DATA_FILE_PATH = os.path.join(home,'HCLT','AION','data')
def get_join(condition):
if condition["join"] == 'and':
return " | ||
&"
elif condition["join"] == 'or':
return "|"
else:
return ""
def create_labelling_function(rule_list, label_list):
lfs_main_func = 'def lfs_list_create():\\n'
lfs_main_func += '\\tfrom snorkel.labeling import labeling_function\\n'
lfs_main_func += '\\timport numpy as np\\n'
lfs_main_func += '\\timport json\\n'
lfs_main_func += '\\tABSTAIN = -1\\n'
lfs_main_func += '\\tlabels = json.loads(json.dumps(' + json.dumps(label_list) + '))\\n'
lfs_list = '\\tlfs_list=['
for rule in rule_list:
lfs_list += 'lf_' + rule["rule_name"] + ','
lfs = '\\t@labeling_function()\\n'
lfs += '\\tdef lf_' + rule["rule_name"] + '(data):\\n'
lfs += '\\t\\treturn np.where('
for condition in rule["conditions"]:
if "string" in condition["sel_datatype"]:
if condition["sel_condition"] in ["==", "!="]:
cond_statement = '(data["' + condition["sel_column"] + '"]' + condition[
"sel_condition"] + '("' + str(condition["input_value"]) + '"))' + get_join(condition)
else:
cond_statement = '(data["' + condition["sel_column"] + '"].' + condition[
"sel_condition"] + '("' + str(condition["input_value"]) + '"))' + get_join(condition)
else:
cond_statement = '(data["' + condition["sel_column"] + '"]' + condition["sel_condition"] + \\
str(condition["input_value"]) + ')' + get_join(condition)
lfs += cond_statement
lfs += ', labels.index("' + rule["label"] + '"), ABSTAIN)\\n'
lfs_main_func += lfs
if lfs_list.endswith(","):
lfs_list = lfs_list.rstrip(lfs_list[-1])
lfs_list += ']\\n'
else:
lfs_list += ']\\n'
lfs_main_func += lfs_list
lfs_main_func += '\\treturn lfs_list\\n'
lfs_main_func += 'lfs_list_create()'
f = open(os.path.join(DATA_FILE_PATH, 'lfs_list.txt'), 'w')
f.write(lfs_main_func)
f.close()
return lfs_main_func
def label_dataset(rule_list, file_ext, label_list, not_satisfy_label):
file_path = os.path.join(DATA_FILE_PATH, "uploaded_file." + file_ext)
if file_ext in ["csv", "tsv"]:
df = pd.read_csv(file_path)
elif file_ext == "json":
df = pd.json_normalize(pd.read_json(file_path).to_dict("records"))
elif file_ext == "avro":
reader = DataFileReader(open(file_path, "rb"), DatumReader())
schema = json.loads(reader.meta.get('avro.schema').decode('utf-8'))
df = pdx.read_avro(file_path, schema=schema, na_dtypes=True)
elif file_ext == "parquet":
df = pd.read_parquet(file_path, engine="pyarrow")
labelling_functions = create_labelling_function(rule_list, label_list)
exec(labelling_functions)
lfs = eval('lfs_list_create()')
applier = PandasLFApplier(lfs)
l_data = applier.apply(df)
label_model = LabelModel(cardinality=len(label_list) + 1, verbose=True)
label_model.fit(l_data, n_epochs=500, log_freq=50, seed=123)
df["label"] = label_model.predict(L=l_data, tie_break_policy="abstain")
df.loc[df["label"] == -1, "label"] = not_satisfy_label
for item in label_list:
df.loc[df["label"] == label_list.index(item), "label"] = item
if file_ext in ["csv", "tsv"]:
df.to_csv(os.path.join(DATA_FILE_PATH, "result_file." + file_ext), index=False)
elif file_ext == "parquet":
df.to_parquet(os.path.join(DATA_FILE_PATH, "result_file." + file_ext),
engine="pyarrow", index=False)
elif file_ext == "avro":
pdx.to_avro(os.path.join(DATA_FILE_PATH, "result_file." + file_ext), df)
else:
raise ValueError("Invalid file format")
num_records = len(df.index)
size_take = 100
if num_records <= size_take:
size_take = num_records
display_df = df.sample(n=size_take)
return display_df.to_html(classes='table table-striped text-left', justify='left', index=False)
def create_sample_function(rule, label_list, not_satisfy_label):
lfs_main_func = 'def lf_rule_apply(data):\\n'
lfs_main_func += '\\timport numpy as np\\n'
lfs_main_func += '\\tABSTAIN = -1\\n'
lfs_main_func += '\\tlabels = json.loads(json.dumps(' + json.dumps(label_list) + '))\\n'
lfs = '\\treturn np.where('
for condition in rule["conditions"]:
if "string" in condition["sel_datatype"]:
if condition["sel_condition"] in ["==", "!="]:
cond_statement = '(data["' + condition["sel_column"] + '"]' + condition["sel_condition"] + '("' + str(
condition["input_value"]) + '"))' + get_join(condition)
else:
cond_statement = '(data["' + condition["sel_column"] + '"].str.' + condition[
"sel_condition"] + '("' + str(condition["input_value"]) + '"))' + get_join(condition)
print(cond_statement)
else:
cond_statement = '(data["' + condition["sel_column"] + '"]' + condition["sel_condition"] + \\
str(condition["input_value"]) + ')' + get_join(condition)
lfs += cond_statement
lfs += ', "' + rule["label"] + '", "' + not_satisfy_label + '")\\n'
lfs_main_func += lfs
return lfs_main_func
def get_sample_result_of_individual_rule(rule_json, file_ext, label_list, not_satisfy_label):
file_path = os.path.join(DATA_FILE_PATH, "uploaded_file." + file_ext)
size_take = 100
if file_ext in ["csv", "tsv"]:
num_records = sum(1 for line in open(file_path)) - 1
if num_records > size_take:
skip = sorted(random.sample(range(1, num_records + 1), num_records - size_take))
else:
skip = 0
df = pd.read_csv(file_path, skiprows=skip)
elif file_path.endswith(".json"):
df = pd.read_json(file_path)
df = pd.json_normalize(df.to_dict("records"))
elif file_path.endswith(".avro"):
reader = DataFileReader(open(file_path, "rb"), DatumReader())
schema = json.loads(reader.meta.get('avro.schema').decode('utf-8'))
df = pdx.read_avro(file_path, schema=schema, na_dtypes=True)
elif file_path.endswith(".parquet"):
pf = ParquetFile(file_path)
take_rows = next(pf.iter_batches(batch_size=size_take))
df = pa.Table.from_batches([take_rows]).to_pandas()
# file_content = pd.read_parquet(file_path, engine="pyarrow")
else:
raise ValueError("Invalid file format")
rule_applier_func = create_sample_function(rule_json, label_list, not_satisfy_label)
exec(rule_applier_func)
df[rule_json["rule_name"]] = eval('lf_rule_apply')(df)
return df.to_html(classes='table table-striped text-left', justify='left', index=False)
def create_sample_function_ver2(rule_json, label_list, not_satisfy_label):
lfs_main_func = 'def lf_rule_apply(data):\\n'
lfs_main_func += '\\timport numpy as np\\n'
lfs_main_func += '\\tABSTAIN = -1\\n'
lfs_main_func += '\\tlabels = json.loads(json.dumps(' + json.dumps(label_list) + '))\\n'
counter = 0
for condition in rule_json["conditions"]:
lfs_return = condition["sel_label"]
if counter > 0:
lfs_return_condition = '\\telif'
else:
lfs_return_condition = '\\tif'
for label_condition in condition["label_condition"]:
if label_condition["sel_datatype"] == "string":
if label_condition["sel_condition"] == "contains":
lfs_return_condition += '((' + str(label_condition["input_value"]) + ') in data["' + \\
label_condition["sel_column"] + '"])' + get_join(label_condition)
elif label_condition["sel_condition"] in ["==", "!="]:
lfs_return_condition += '(data["' + label_condition["sel_column"] + '"]' + label_condition[
"sel_condition"] + '("' + str(
label_condition["input_value"]) + '"))' + get_join(label_condition)
else:
lfs_return_condition += '(data["' + label_condition["sel_column"] + '"].' + label_condition[
"sel_condition"] + '("' + str(label_condition["input_value"]) + '"))' + get_join(
label_condition)
else:
lfs_return_condition += '(data["' + label_condition["sel_column"] + '"]' + label_condition[
"sel_condition"] + str(label_condition["input_value"]) + ')' + get_join(label_condition)
if get_join(label_condition) == "":
lfs_return_condition += ":\\n"
lfs_return_condition += '\\t\\treturn "' + lfs_return + '"\\n'
lfs_main_func += lfs_return_condition
counter += 1
lfs_return_condition = '\\n\\telse:\\n'
lfs_return_condition += '\\t\\treturn "' + not_satisfy_label + '"'
lfs_main_func += lfs_return_condition
return lfs_main_func
def get_sample_result_of_individual_rule_ver2(rule_json, file_ext, label_list, not_satisfy_label):
file_path = os.path.join(DATA_FILE_PATH, "uploaded_file." + file_ext)
size_take = 100
if file_ext in ["csv", "tsv"]:
num_records = sum(1 for line in open(file_path)) - 1
if num_records > size_take:
skip = sorted(random.sample(range(1, num_records + 1), num_records - size_take))
else:
skip = 0
df = pd.read_csv(file_path, skiprows=skip)
elif file_path.endswith(".json"):
df = pd.read_json(file_path)
df = pd.json_normalize(df.to_dict("records"))
elif file_path.endswith(".avro"):
reader = DataFileReader(open(file_path, "rb"), DatumReader())
schema = json.loads(reader.meta.get('avro.schema').decode('utf-8'))
df = pdx.read_avro(file_path, schema=schema, na_dtypes=True)
elif file_path.endswith(".parquet"):
pf = ParquetFile(file_path)
take_rows = next(pf.iter_batches(batch_size=size_take))
df = pa.Table.from_batches([take_rows]).to_pandas()
# file_content = pd.read_parquet(file_path, engine="pyarrow")
else:
raise ValueError("Invalid file format")
rule_applier_func = create_sample_function_ver2(rule_json, label_list, not_satisfy_label)
exec(rule_applier_func)
df[rule_json["rule_name"]] = df.apply(eval('lf_rule_apply'), axis=1)
return df.to_html(classes='table table-striped text-left', justify='left', index=False)
def create_labelling_function_ver2(rule_list, label_list):
lfs_main_func = 'def lfs_list_create():\\n'
lfs_main_func += '\\tfrom snorkel.labeling import labeling_function\\n'
lfs_main_func += '\\timport numpy as np\\n'
lfs_main_func += '\\timport json\\n'
lfs_main_func += '\\tABSTAIN = -1\\n'
lfs_main_func += '\\tlabels = json.loads(json.dumps(' + json.dumps(label_list) + '))\\n'
lfs_list = '\\tlfs_list=['
for rule in rule_list:
lfs_list += 'lf_' + rule["rule_name"] + ','
lfs = '\\t@labeling_function()\\n'
lfs += '\\tdef lf_' + rule["rule_name"] + '(data):\\n'
counter = 0
for condition in rule["conditions"]:
lfs_return = 'labels.index("' + condition["sel_label"] + '")'
if counter > 0:
lfs_return_condition = '\\t\\telif'
else:
lfs_return_condition = '\\t\\tif'
for label_condition in condition["label_condition"]:
if label_condition["sel_datatype"] == "string":
if label_condition["sel_condition"] == "contains":
lfs_return_condition += '((' + str(label_condition["input_value"]) + ') in data["' + \\
label_condition["sel_column"] + '"])' + get_join(label_condition)
elif label_condition["sel_condition"] in ["==", "!="]:
lfs_return_condition += '(data["' + label_condition["sel_column"] + '"]' + label_condition[
"sel_condition"] + '("' + str( | ||
label_condition["input_value"]) + '"))' + get_join(label_condition)
else:
lfs_return_condition += '(data["' + label_condition["sel_column"] + '"].' + label_condition[
"sel_condition"] + '("' + str(label_condition["input_value"]) + '"))' + get_join(
label_condition)
else:
lfs_return_condition += '(data["' + label_condition["sel_column"] + '"]' + label_condition[
"sel_condition"] + str(label_condition["input_value"]) + ')' + get_join(label_condition)
if get_join(label_condition) == "":
lfs_return_condition += ":\\n"
lfs_return_condition += '\\t\\t\\treturn ' + lfs_return + '\\n'
lfs += lfs_return_condition
counter += 1
lfs_return_condition = '\\n\\t\\telse:\\n'
lfs_return_condition += '\\t\\t\\treturn ABSTAIN\\n'
lfs += lfs_return_condition
lfs_main_func += lfs
if lfs_list.endswith(","):
lfs_list = lfs_list.rstrip(lfs_list[-1])
lfs_list += ']\\n'
else:
lfs_list += ']\\n'
lfs_main_func += lfs_list
lfs_main_func += '\\treturn lfs_list\\n'
lfs_main_func += 'lfs_list_create()'
# f = open(os.path.join(DATA_FILE_PATH, 'lfs_list.txt'), 'w')
# f.write(lfs_main_func)
# f.close()
return lfs_main_func
def get_rule_name_list(rule_list):
rule_name_list = []
for rule in rule_list:
rule_name_list.append(rule["rule_name"])
return rule_name_list
def label_dataset_ver2(request,rule_list, file_ext, label_list, not_satisfy_label, label_weightage, include_proba):
file_path = os.path.join(DATA_FILE_PATH, "uploaded_file." + file_ext)
if file_ext in ["csv", "tsv"]:
df = pd.read_csv(file_path)
elif file_ext == "json":
df = pd.json_normalize(pd.read_json(file_path).to_dict("records"))
elif file_ext == "avro":
reader = DataFileReader(open(file_path, "rb"), DatumReader())
schema = json.loads(reader.meta.get('avro.schema').decode('utf-8'))
df = pdx.read_avro(file_path, schema=schema, na_dtypes=True)
elif file_ext == "parquet":
df = pd.read_parquet(file_path, engine="pyarrow")
labelling_functions = create_labelling_function_ver2(rule_list, label_list)
exec(labelling_functions)
lfs = eval('lfs_list_create()')
applier = PandasLFApplier(lfs)
l_data = applier.apply(df)
label_model = LabelModel(cardinality=len(label_list), verbose=True)
label_model.fit(l_data, n_epochs=500, log_freq=50, seed=123, class_balance=label_weightage)
df["label"] = label_model.predict(L=l_data, tie_break_policy="abstain")
if include_proba:
prediction_of_prob = label_model.predict_proba(L=l_data)
for label in label_list:
df[label + "_prob"] = np.around(prediction_of_prob[:, label_list.index(label)], 2) * 100
df.loc[df["label"] == -1, "label"] = not_satisfy_label
filetimestamp = str(int(time.time()))
datasetName = "AION_labelled_"+filetimestamp + '.' + file_ext
request.session['AION_labelled_Dataset'] = datasetName
for item in label_list:
df.loc[df["label"] == label_list.index(item), "label"] = item
if file_ext in ["csv", "tsv"]:
df.to_csv(os.path.join(DATA_FILE_PATH, datasetName), index=False)
elif file_ext == "parquet":
df.to_parquet(os.path.join(DATA_FILE_PATH, datasetName),
engine="pyarrow", index=False)
elif file_ext == "avro":
pdx.to_avro(os.path.join(DATA_FILE_PATH, datasetName), df)
else:
raise ValueError("Invalid file format")
#### saving file to database
from appbe.dataPath import DATA_DIR
from appbe.sqliteUtility import sqlite_db
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'config.db')
newdata = {}
newdata['datapath'] = [os.path.join(DATA_FILE_PATH, datasetName)]
newdata['datasetname'] = [datasetName]
sqlite_obj.write_data(pd.DataFrame.from_dict(newdata), 'dataingest')
num_records = len(df.index)
size_take = 100
if num_records <= size_take:
size_take = num_records
display_df = df.sample(n=size_take)
weightage = np.around(label_model.get_weights(), 2)
rule_name_list = get_rule_name_list(rule_list)
analysis_df = LFAnalysis(l_data, lfs).lf_summary()
analysis_df["Rule"] = analysis_df.index
analysis_df["Rule"] = analysis_df["Rule"].str.replace("lf_", "")
analysis_df = analysis_df[["Rule", "Polarity", "Coverage", "Overlaps", "Conflicts"]]
weightage_dict = dict(zip(rule_name_list, weightage))
analysis_json = analysis_df.to_dict(orient="records")
for item in analysis_json:
item["Weightage"] = weightage_dict[item["Rule"]]
analysis_df = pd.json_normalize(analysis_json)
# rules_weightage = []
# for key in weightage_dict:
# rules_weightage.append({
# "label": key,
# "y": weightage_dict[key],
# "legendText": key
# })
response = {
# "rule_name_list": rule_name_list,
# "weightage_list": list(weightage),
"analysis_df": analysis_df.to_html(classes='table table-striped text-left', justify='left', index=False),
"result_html": display_df.to_html(classes='table table-striped text-left', justify='left', index=False)
}
return response
def get_label_and_weightage(test_file_ext, marked_label_column,file_delim_test, custom_test_delim ):
file_path = os.path.join(DATA_FILE_PATH, "test_data_file." + test_file_ext)
if test_file_ext in ["csv", "tsv"]:
df = pd.read_csv(file_path)
elif test_file_ext == "json":
df = pd.json_normalize(pd.read_json(file_path).to_dict("records"))
elif test_file_ext == "avro":
reader = DataFileReader(open(file_path, "rb"), DatumReader())
schema = json.loads(reader.meta.get('avro.schema').decode('utf-8'))
df = pdx.read_avro(file_path, schema=schema, na_dtypes=True)
elif test_file_ext == "parquet":
df = pd.read_parquet(file_path, engine="pyarrow")
json_df = pd.DataFrame(df[marked_label_column].value_counts(normalize=True) * 100)
json_dict = json.loads(json_df.to_json())
label_with_weightage = []
for k in json_dict[marked_label_column]:
label_with_weightage.append(
{"label_name": k, "label_weightage": np.around(json_dict[marked_label_column][k], 2)})
return label_with_weightage
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os
from os.path import expanduser
import platform
DEFAULT_FILE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),'conf')
cur_dir = os.path.dirname(os.path.abspath(__file__))
home = expanduser("~")
if platform.system() == 'Windows':
DATA_DIR = os.path.normpath(os.path.join(cur_dir,'..','..','..','..','..','..','data'))
DATA_FILE_PATH = os.path.join(DATA_DIR,'storage')
CONFIG_FILE_PATH = os.path.join(DATA_DIR,'config')
DEPLOY_LOCATION = os.path.join(DATA_DIR,'target')
LOG_LOCATION = os.path.join(DATA_DIR,'logs')
LOG_FILE = os.path.join(DATA_DIR,'logs','ux.log')
else:
DATA_DIR = os.path.join(home,'HCLT','data')
DATA_FILE_PATH = os.path.join(DATA_DIR,'storage')
CONFIG_FILE_PATH = os.path.join(DATA_DIR,'config')
DEPLOY_LOCATION = os.path.join(DATA_DIR,'target')
LOG_FILE = os.path.join(DATA_DIR,'logs','ux.log')
LOG_LOCATION = os.path.join(DATA_DIR,'logs')<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os
import platform
import shutil
import subprocess
import sys
import glob
from pathlib import Path
import json
from django.http import FileResponse
from django.http import HttpResponse
from importlib.metadata import version
COMMON_PACKAGES = "'setuptools >=62.3.0','pandas==1.5.3','numpy==1.24.2','joblib==1.2.0','Cython==0.29.33','scipy==1.10.1',' scikit-learn==1.2.1','word2number==1.1','category_encoders==2.6.0'"
DL_COMMON_PACKAGE = "'tensorflow==2.11.0'"
TEXT_PACKAGES = "'spacy==3.5.0','nltk==3.8.1','textblob==0.15.3','demoji==1.1.0','bs4==0.0.1','text-unidecode==1.3','pyspellchecker==0.6.2','contractions==0.1.73','protobuf==3.19.6','lxml'"
def createPackagePackage(request,id,version,usecasedetails,Existusecases):
from appbe.pages import get_usecase_page
#print('2')
usecasedetail = usecasedetails.objects.get(id=id)
models = Existusecases.objects.filter(ModelName=usecasedetail,Status='SUCCESS',Version=version)
modelid = models[0].id
p = Existusecases.objects.get(id=modelid)
deploymentfolder = str(p.DeployPath)
modelname = p.ModelName.usecaseid
version = p.Version
deployed_code = 'AION'
dockerimage = os.path.join(deploymentfolder,'publish','docker_image')
dockersetup = os.path.join(deploymentfolder,'publish','docker_setup')
tempPath = os.path.join(os.path.dirname(os.path.abspath(__file__)),'temp_'+modelname+'_'+str(version))
try:
shutil.rmtree(tempPath,ignore_errors=True)
except:
pass
shutil.copytree(deploymentfolder,tempPath)
shutil.rmtree(os.path.join(tempPath,'publish'), ignore_errors=True)
try:
Path(os.path.join(deploymentfolder,'publish')).mkdir(parents=True, exist_ok=True)
os.mkdir(dockersetup)
except:
shutil.rmtree(dockersetup,ignore_errors=True)
os.mkdir(dockersetup)
try:
os.mkdir(dockerimage)
except:
shutil.rmtree(dockerimage,ignore_errors=True)
os.mkdir(dockerimage)
shutil.copytree(tempPath, os.path.join(dockersetup,deployed_code))
shutil.rmtree(tempPath)
docker_setup = os.path.join(dockersetup,'AION')
try:
os.mkdir(dockerimage)
except:
pass
requirementfilename = os.path.join(dockersetup,'requirements.txt')
installfilename = os.path.join(dockersetup,'install.py')
dockerfile = os.path.join(dockersetup,'Dockerfile')
dockerdata='FROM python:3.10-slim-buster'
dockerdata+='\\n'
dockerdata+='WORKDIR /app'
dockerdata+='\\n'
dockerdata+='COPY AION AION'
dockerdata+='\\n'
dockerdata+='''RUN apt-get update \\
&& apt-get install -y build-essential manpages-dev \\
&& apt-get install -y libgomp1 \\
&& python -m pip install --no-cache-dir -r AION/requirements.txt
'''
f = open(dockerfile, "w")
f.write(str(dockerdata))
f.close()
try:
try:
import docker
client = docker.from_env()
client.containers.list()
except:
status,context,action = get_usecase_page(request,usecasedetails,Existusecases)
context['Status'] = 'Error'
context['Msg'] = 'Docker should be installed and running on your machine. To build the docker image manually, the setup script is available at the following location: \\\\n'+dockersetup.replace('\\\\', '/')
return context
| ||
command = 'docker pull python:3.10-slim-buster'
os.system(command);
subprocess.check_call(["docker", "build", "-t",modelname.lower()+":"+str(version),"."], cwd=dockersetup)
subprocess.check_call(["docker", "save", "-o",modelname.lower()+"_"+str(version)+".tar",modelname.lower()+":"+str(version)], cwd=dockersetup)
dockerfilepath = os.path.join(dockersetup,modelname.lower()+"_"+str(version)+".tar")
shutil.copyfile(dockerfilepath, os.path.join(dockerimage,modelname.lower()+"_"+str(version)+".tar"))
shutil.rmtree(dockersetup)
msg = 'Done'
Status = 'SUCCESS'
except Exception as e:
msg = 'Error in docker images creation. To build manually docker image setup available in following location: '+dockersetup.replace('\\\\', '\\\\\\\\')
Status = 'Fail'
status,context,action = get_usecase_page(request,usecasedetails,Existusecases)
context['Status'] = Status
context['Msg'] = msg
return context
def downloadPackage(request,id,version,usecasedetails,Existusecases):
try:
if 'downloadstatus' in request.session:
if request.session['downloadstatus'] == 'Downloading':
return HttpResponse(json.dumps("Error Creating Package"), content_type="application/error")
request.session['downloadstatus'] = 'Downloading'
usecasedetail = usecasedetails.objects.get(id=id)
models = Existusecases.objects.filter(ModelName=usecasedetail,Status='SUCCESS',Version=version)
modelid = models[0].id
p = Existusecases.objects.get(id=modelid)
deployPath = str(p.DeployPath)
if os.path.isdir(os.path.join(deployPath,'publish','package')):
for f in os.listdir(os.path.join(deployPath,'publish','package')):
if f.endswith('whl'):
os.remove(os.path.join(deployPath,'publish','package',f))
usecasename = p.ModelName.usecaseid
Version = p.Version
deployed_code = usecasename
targetname = usecasename+'_'+str(Version)
whl_dir_name = 'WHEEL_'+usecasename+'_'+str(Version)
deployLocation = os.path.join (deployPath,'..',whl_dir_name)
try:
os.makedirs(deployLocation)
except OSError as e:
shutil.rmtree(deployLocation)
os.makedirs(deployLocation)
shutil.copytree(deployPath,os.path.join(deployLocation,deployed_code))
initstring = 'import os'
initstring += '\\n'
initstring += 'import sys'
initstring += '\\n'
initstring += 'sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__))))'
filename = os.path.join(deployLocation,deployed_code,'__init__.py')
f = open(filename, "w")
f.write(str(initstring))
f.close()
textdata=0
learner_type = 'ml'
requirementfile = os.path.join(deployPath,'requirements.txt')
install_requires = ''
if os.path.exists(requirementfile):
fileobj = open(requirementfile, 'r')
requirePackages = fileobj.readlines()
fileobj.close()
for package in requirePackages:
if install_requires != '':
install_requires = install_requires+','
install_requires = install_requires+'\\''+package.strip()+'\\''
setup_string = 'from setuptools import setup,find_packages'
setup_string += '\\n'
setup_string += 'setup(name=\\''+deployed_code+'\\','
setup_string += '\\n'
setup_string += 'version=\\'1\\','
setup_string += '\\n'
setup_string += 'packages = find_packages(),'
setup_string += '\\n'
setup_string += 'install_requires = ['+install_requires+'],'
setup_string += '\\n'
setup_string += 'package_data={"'+deployed_code+'.pytransform":["*.*"],"'+deployed_code+'":["*.sav","*.json"],"":["*","*/*","*/*/*"]}'
setup_string += '\\n'
setup_string += ')'
filename = os.path.join(deployLocation,'setup.py')
f = open(filename, "w")
f.write(str(setup_string))
f.close()
subprocess.check_call([sys.executable, "setup.py", "bdist_wheel"], cwd=deployLocation)
shutil.copytree(os.path.join(deployLocation,'dist'),os.path.join(deployPath,'publish','package'),dirs_exist_ok=True)
shutil.rmtree(deployLocation)
if os.path.isdir(os.path.join(deployPath,'publish','package')):
for f in os.listdir(os.path.join(deployPath,'publish','package')):
if f.endswith('whl'):
package = f
zip_file = open(os.path.join(deployPath,'publish','package',package), 'rb')
request.session['downloadstatus'] = 'Done'
return FileResponse(zip_file)
except Exception as e:
print(e)
request.session['downloadstatus'] = 'Done'
return HttpResponse(json.dumps("Error Creating Package"), content_type="application/error")
def installPackage(model,version,deployedPath):
deployedPath = os.path.join(deployedPath,'publish','package')
whlfilename='na'
if os.path.isdir(deployedPath):
for file in os.listdir(deployedPath):
if file.endswith(".whl"):
whlfilename = os.path.join(deployedPath,file)
if whlfilename != 'na':
subprocess.check_call([sys.executable, "-m", "pip", "uninstall","-y",model])
subprocess.check_call([sys.executable, "-m", "pip", "install","--no-dependencies",whlfilename])
status,pid,ip,port = checkModelServiceRunning(model)
if status == 'Running':
stopService(pid)
startService(model,ip,port)
return('Success')
else:
return('Installation Package not Found')
def getMIDFromUseCaseVersion(id,version,usecasedetails,Existusecases):
usecasedetail = usecasedetails.objects.get(id=id)
models = Existusecases.objects.filter(ModelName=usecasedetail,Status='SUCCESS',Version=version)
return(models[0].id)
def stopService(pid):
import psutil
p = psutil.Process(int(pid))
p.terminate()
def checkModelServiceRunning(package_name):
from os.path import expanduser
home = expanduser("~")
if platform.system() == 'Windows':
modelServices = os.path.join(home,'AppData','Local','HCLT','AION','services')
else:
modelServices = os.path.join(home,'HCLT','AION','target','services')
filename = package_name+'_service.py'
modelservicefile = os.path.join(modelServices,filename)
status = 'Not Initialized'
ip = ''
port = ''
pid = ''
if os.path.exists(modelservicefile):
status = 'Not Running'
import psutil
for proc in psutil.process_iter():
pinfo = proc.as_dict(attrs=['pid', 'name', 'cmdline','connections'])
if 'python' in pinfo['name']:
if filename in pinfo['cmdline'][1]:
status = 'Running'
pid = pinfo['pid']
for x in pinfo['connections']:
ip = x.laddr.ip
port = x.laddr.port
return(status,pid,ip,port)
def startService(package_name,ip,portNo):
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','bin','model_service.py'))
from os.path import expanduser
home = expanduser("~")
if platform.system() == 'Windows':
modelServices = os.path.join(home,'AppData','Local','HCLT','AION','services')
else:
modelServices = os.path.join(home,'HCLT','AION','target','services')
if not os.path.isdir(modelServices):
os.makedirs(modelServices)
filename = package_name+'_service.py'
modelservicefile = os.path.join(modelServices,filename)
status = 'File Not Exist'
if os.path.exists(modelservicefile):
status = 'File Exist'
r = ([line.split() for line in subprocess.check_output("tasklist").splitlines()])
for i in range(len(r)):
if filename in r[i]:
status = 'Running'
if status == 'File Not Exist':
shutil.copy(file_path,modelservicefile)
with open(modelservicefile, 'r+') as file:
content = file.read()
file.seek(0, 0)
line = 'from '+package_name+' import aion_performance'
file.write(line+"\\n")
line = 'from '+package_name+' import aion_drift'
file.write(line+ "\\n")
line = 'from '+package_name+' import featureslist'
file.write(line+ "\\n")
line = 'from '+package_name+' import aion_prediction'
file.write(line+ "\\n")
file.write(content)
file.close()
status = 'File Exist'
if status == 'File Exist':
command = "python "+modelservicefile+' '+str(portNo)+' '+str(ip)
os.system('start cmd /c "'+command+'"')
def checkInstalledPackge(package_name):
import importlib.util
spec = importlib.util.find_spec(package_name)
if spec is None:
return('Not Installed','','')
else:
if len(spec.submodule_search_locations) > 0:
displaypath = os.path.join(spec.submodule_search_locations[0],'etc','display.json')
with open(displaypath) as file:
config = json.load(file)
file.close()
if 'usecasename' in config:
modelName = config['usecasename']
else:
modelName = 'NA'
if 'version' in config:
version = config['version']
else:
version = 'NA'
return('Installed',modelName,version)<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os,sys
from appbe import compute
from appbe.aion_config import kafka_setting
from appbe.aion_config import running_setting
from records import pushrecords
from appbe import service_url
import json
import time
import pandas as pd
from django.db.models import Max, F
from os.path import expanduser
import platform
from appbe.data_io import sqlite_db
import subprocess
from appbe.dataPath import DEFAULT_FILE_PATH
from appbe.dataPath import DATA_FILE_PATH
from appbe.dataPath import CONFIG_FILE_PATH
from appbe.dataPath import DEPLOY_LOCATION
from appbe.dataPath import DATA_DIR
DEPLOY_DATABASE_PATH = os.path.join(DATA_DIR,'sqlite')
def pushRecordForTraining():
from appbe.pages import getversion
AION_VERSION = getversion()
try:
status,msg = pushrecords.enterRecord(AION_VERSION)
except Exception as e:
print("Exception", e)
status = False
msg = str(e)
return status,msg
def getversion():
configFolder = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','config')
version = 'NA'
for file in os.listdir(configFolder):
if file.endswith(".var"):
version = file.rsplit('.', 1)
version = version[0]
break
return version
def getusercasestatus(request):
if 'UseCaseName' in request.session:
selected_use_case = request.session['UseCaseName']
else:
selected_use_case = 'Not Defined'
if 'ModelVersion' in request.session:
ModelVersion = request.session['ModelVersion']
else:
ModelVersion = 0
if 'ModelStatus' in request.session:
ModelStatus = request.session['ModelStatus']
else:
ModelStatus = 'Not Trained'
return selected_use_case,ModelVersion,ModelStatus
def getMLModels(configSettingsJson):
mlmodels =''
dlmodels = ''
problem_type = ""
problemtypes = configSettingsJson['basic']['analysisType']
for k in problemtypes.keys():
if configSettingsJson['basic']['analysisType'][k] == 'True':
problem_type = k
break
sc = ""
if problemtypes in ['classification','regression','survivalAnalysis']:
scoringCreteria = configSettingsJson['basic']['scoringCriteria'][problem_type]
for k in scoringCreteria.keys():
if configSettingsJson['basic']['scoringCriteria'][problem_type][k] == 'True':
sc = k
break
else:
sc = 'NA'
if problem_type in ['classification','regression']:
algorihtms = configSettingsJson['basic']['algorithms'][problem_type]
#print(algorihtms)
for k in algorihtms.keys():
#print(configSettingsJson['basic']['algorithms'][problem_type][k])
if configSettingsJson['basic']['algorithms'][problem_type][k] == 'True':
if k in ['SNN','RNN','CNN']:
if dlmodels != '':
dlmodels += ', '
dlmodels += k
else:
if mlmodels != '':
mlmodels += ', '
mlmodels += k
elif problem_type in ['videoForecasting','imageClassification','objectDetection']:
algorihtms = configSettingsJson['basic']['algorithms'][problem_type]
for k in algorihtms.keys():
if configSettingsJson['basic']['algorithms'][problem_type][k] == 'True':
if dlmodels != '':
dlmodels += ', '
dlmodels += k
else:
algorihtms = configSettingsJson['basic']['alg | ||
orithms'][problem_type]
for k in algorihtms.keys():
if configSettingsJson['basic']['algorithms'][problem_type][k] == 'True':
if mlmodels != '':
mlmodels += ', '
mlmodels += k
displayProblemType = problem_type
selected_model_size = ''
if problem_type.lower() == 'llmfinetuning':
displayProblemType = 'LLM Fine-Tuning'
supported_model_types = configSettingsJson['basic']['modelSize'][problem_type][mlmodels]
for k in supported_model_types.keys():
if configSettingsJson['basic']['modelSize'][problem_type][mlmodels][k] == 'True':
selected_model_size = k
break
#print(selected_model_size)
if mlmodels == 'TF_IDF':
mlmodels = 'TF-IDF'
if mlmodels == 'LatentSemanticAnalysis':
mlmodels = 'Latent Semantic Analysis (LSA)'
if mlmodels == 'SentenceTransformer_distilroberta':
mlmodels = 'SentenceTransformer (DistilRoBERTa)'
if mlmodels == 'SentenceTransformer_miniLM':
mlmodels = 'SentenceTransformer (MiniLM)'
if mlmodels == 'SentenceTransformer_mpnet':
mlmodels = 'SentenceTransformer (MPNet)'
return(problem_type,displayProblemType,sc,mlmodels,dlmodels,selected_model_size)
def get_usecase_page(request,usecasedetails,Existusecases,usecaseId = None,search_text=None):
try:
x = request.build_absolute_uri().split("http://")
y = x[1].split("/")
url = y[0].split(":")
tacking_url = url[0]
except:
tacking_url = '127.0.0.1'
computeinfrastructure = compute.readComputeConfig()
ruuningSetting = running_setting()
selected_use_case,ModelVersion,ModelStatus = getusercasestatus(request)
status = 'SUCCESS'
ser_url = service_url.read_service_url_params(request)
hosturl =request.get_host()
hosturl = hosturl.split(':')
hosturl = hosturl[0]
packagetip='''
Call From Command Line
1. Click AION Shell
2. python {packageAbsolutePath}/aion_prediction.py {json_data}
Call As a Package
1. Go To package_path\\WHEELfile
2. python -m pip install {packageName}-py3-none-any.whl
Call the predict function after wheel package installation
1. from {packageName} import aion_prediction as p1
2. p1.predict({json_data})'''
models = Existusecases.objects.filter(Status='SUCCESS').order_by('-id')
usecase = usecasedetails.objects.all().order_by('-id')
usecase = landing_page(usecasedetails,Existusecases,hosturl,usecaseId,search_text)
if len(usecase) > 0:
nouc = usecasedetails.objects.latest('id')
nouc = (nouc.id)+1
nouc = str(nouc).zfill(4)
else:
nouc = 1
nouc = str(nouc).zfill(4)
description_text = 'This is a usecase for AI' + str(nouc)
context = {'description_text':description_text,'usecasedetail': usecase, 'nouc': nouc, 'models': models, 'selected_use_case': selected_use_case,'ser_url':ser_url,'packagetip':packagetip,'tacking_url':tacking_url,
'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion, 'selected': 'usecase','computeinfrastructure':computeinfrastructure,'computeinfrastructure':computeinfrastructure,'ruuningSetting':ruuningSetting}
return status,context,'usecases.html'
def checkText(configPath):
isText='False'
with open(configPath) as config:
data = json.load(config)
for feature in data['advance']['profiler']['featureDict'] :
if feature['type']=='text':
isText = 'True';
break;
return isText
# For Task ID 12393
# For BUG ID 13161
def checkFE(configPath):
isFE = 'False'
with open(configPath) as config:
data = json.load(config)
is_selection_method = data.get('advance', {}).get('selector', {}).get('selectionMethod', {}).get('featureEngineering','False')
feature_dict= data.get('advance', {}).get('selector', {}).get('featureEngineering', {})
if 'null' in feature_dict.keys():
feature_dict.pop('null')
if is_selection_method == 'True' or 'True' in list(feature_dict.values()):
isFE = 'True'
return isFE
def get_model(Existusecases,usercaseid,version=-1):
from django.core import serializers
if version == -1:
models = Existusecases.objects.filter(ModelName=usercaseid).order_by('-id')
else:
models = Existusecases.objects.filter(ModelName=usercaseid,Version=version).order_by('-id')
for model in models:
model.scoringCreteria = 'NA'
model.score = 'NA'
model.deploymodel = 'NA'
model.problemType = 'NA'
model.maacsupport = 'False'
model.flserversupport = 'False'
model.onlinelerningsupport = 'False'
model.oltrainingdetails=''
model.xplain = 'True'
model.isText = 'False'
problemTypeNames = {'topicmodelling':'TopicModelling','anomalydetection':'AnomalyDetection'}
if model.Status == 'SUCCESS':
if os.path.isdir(str(model.DeployPath)):
modelPath = os.path.join(str(model.DeployPath),'etc','output.json')
try:
with open(modelPath) as file:
outputconfig = json.load(file)
file.close()
if outputconfig['status'] == 'SUCCESS':
model.scoringCreteria = outputconfig['data']['ScoreType']
model.score = outputconfig['data']['BestScore']
model.deploymodel = outputconfig['data']['BestModel']
model.problemType = outputconfig['data']['ModelType']
if model.problemType in ['topicmodelling','anomalydetection']:
model.problemType = problemTypeNames[model.problemType]
model.featuresused = outputconfig['data']['featuresused']
model.targetFeature = outputconfig['data']['targetFeature']
if 'params' in outputconfig['data']:
model.modelParams = outputconfig['data']['params']
model.modelType = outputconfig['data']['ModelType']
model.isText = checkText(str(model.ConfigPath))
model.isFeatureEng = checkFE(str(model.ConfigPath))#task id 12393
model.dataPath = os.path.join(str(model.DeployPath),'data', 'postprocesseddata.csv.gz')
mlacSupportedModel = ["Logistic Regression","Naive Bayes","Decision Tree","Random Forest",
"Support Vector Machine","K Nearest Neighbors","Gradient Boosting","Extreme Gradient Boosting (XGBoost)","Light Gradient Boosting (LightGBM)",
"Categorical Boosting (CatBoost)","Linear Regression","Lasso","Ridge","MLP","LSTM"]
if model.problemType.lower() in ['classification','regression','timeseriesforecasting']: #task 11997
if model.deploymodel in mlacSupportedModel:
model.maacsupport = 'True'
if model.problemType.lower() not in ['classification','regression']:
model.xplain = 'False'
elif model in ["Neural Architecture Search"]:
model.xplain = 'False'
model.flserversupport = 'False'
model.onlinelerningsupport = 'False'
supportedmodels = ["Logistic Regression","Neural Network","Linear Regression"]
if model.deploymodel in supportedmodels:
model.flserversupport = 'True'
else:
model.flserversupport = 'False'
supportedmodels = ["Extreme Gradient Boosting (XGBoost)"]
if model.deploymodel in supportedmodels:
model.encryptionsupport = 'True'
else:
model.encryptionsupport = 'False'
supportedmodels = ["Online Decision Tree Classifier","Online Logistic Regression","Online Linear Regression","Online Decision Tree Regressor","Online KNN Regressor","Online Softmax Regression","Online KNN Classifier"]
if model.deploymodel in supportedmodels:
model.onlinelerningsupport = 'True'
onlineoutputPath = os.path.join(str(model.DeployPath),'production','Config.json')
with open(onlineoutputPath) as file:
onlineoutputPath = json.load(file)
file.close()
details = {'Score' :onlineoutputPath['metricList'],'DataSize':onlineoutputPath['trainRowsList']}
dfonline = pd.DataFrame(details)
model.oltrainingdetails = dfonline
else:
model.onlinelerningsupport = 'False'
except Exception as e:
print(e)
pass
return models
def landing_page(usecasedetails,Existusecases,hosturl,usecaseId = None,search_text=None):
sqlite_dbObj = sqlite_db(DEPLOY_DATABASE_PATH,'deploy.db')
if usecaseId:
usecase = usecasedetails.objects.filter(id=usecaseId)
else:
if search_text:
usecase = usecasedetails.objects.filter(UsecaseName__contains=str(search_text)).order_by('-id')
else:
#usecase = usecasedetails.objects.all().order_by('-id')[:100] #top 100 records
usecase = usecasedetails.objects.all().order_by('-id') #top 100 records
usecaselist=[]
if not usecaseId:
for x in usecase:
problemType= 'NA'
publish_url = ''
otherModel = {}
models = Existusecases.objects.filter(Status='SUCCESS',publishStatus='Published',ModelName=x.id).order_by('-id')
if len(models) > 0:
#print(models[0])
version = models[0].Version
if os.path.isdir(str(models[0].DeployPath)):
modelPath = os.path.join(str(models[0].DeployPath),'etc','output.json')
with open(modelPath) as file:
outputconfig = json.load(file)
problemType = outputconfig['data']['ModelType']
#print(problemType.lower())
if problemType.lower() == "llm fine-tuning":
cloudconfig = os.path.normpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'config', 'compute_conf.json'))
print(cloudconfig)
from appbe.models import get_instance
hypervisor,instanceid,region,image,status = get_instance(x.usecaseid+ '_' + str(version))
from llm.llm_inference import get_ip
instanceip = get_ip(cloudconfig,instanceid,hypervisor,region,image) #usnish__ server maynot running
if instanceip != '':
publish_url = 'http://' + instanceip + ':' + '8000' + '/generate'
else:
publish_url = 'service not available'
else:
publish_url = 'http://'+hosturl+':'+str(models[0].portNo)+'/AION/'+x.usecaseid+'/predict'
publish_status = 'Published'
#publish_url = 'http://'+hosturl+':'+str(models[0].portNo)+'/AION/'+x.usecaseid+'/predict'
parentModel = get_model(Existusecases,x.id,int(version))
else:
models = Existusecases.objects.filter(Status='SUCCESS',ModelName=x.id).order_by('-id')
if len(models) > 0:
publish_status = 'Trained'
version = models[0].Version
parentModel = get_model(Existusecases,x.id,int(version))
else:
models = Existusecases.objects.filter(ModelName=x.id).order_by('-id')
if len(models)==0:
publish_status= 'Not Trained'
version = -1
else:
if models[0].Status == 'FAIL':
publish_status= 'Failed'
elif models[0].Status == 'Running':
publish_status = 'Running'
else:
publish_status='Not Trained'
problemType = models[0].ProblemType
version = models[0].Version
parentModel={}
usecasedetails = {'uuid':x.id,'description':x.Description,'usecaseid':x.usecaseid,'usecase':x.UsecaseName,'status':publish_status,'publish_url':publish_url,'version':version,'parentModel':parentModel,'otherModel':otherModel,'problemType':problemType}
usecaselist.append(usecasedetails)
else:
for x in usecase:
otherModel = get_model(Existusecases,x.id)
problemType = otherModel[0].problemType
usecasedetails = {'uuid':x.id,'description':x.Description,'usecase':x.UsecaseName,'status':'','version':'','parentModel':{},'otherModel':otherModel,'problemType':problemType}
usecaselist.append(usecasedetails)
return usecaselist
def get_landing_model(Existusecases):
models = Existusecases.objects.filter(Status='SUCCESS').order_by('-id')
for model in models:
model.scoringCreteria = 'NA'
model.score = 'NA'
model.deploymodel = 'NA'
if os.path.isdir(str(model.DeployPath)):
modelPath = os.path.join(str(model.DeployPath),'etc','output.json')
try:
with open(modelPath) as file:
outputconfig = json.load(file)
file.close()
if outputconfig['status'] == 'SUCCESS':
model.scoringCreteria = outputconfig['data']['ScoreType']
model.score = outputconfig['data']['BestScore']
model.deploymodel = outputconfig['data']['BestModel']
model.problemType = outputconfig['data']['ModelType']
model.ma | ||
acsupport = 'True'
model.flserversupport = 'False'
model.onlinelerningsupport = 'False'
supportedmodels = ["Logistic Regression","Neural Network","Linear Regression"]
if model.deploymodel in supportedmodels:
model.flserversupport = 'True'
else:
model.flserversupport = 'False'
supportedmodels = ["Extreme Gradient Boosting (XGBoost)"]
if model.deploymodel in supportedmodels:
model.encryptionsupport = 'True'
else:
model.encryptionsupport = 'False'
supportedmodels = ["Online Decision Tree Classifier","Online Logistic Regression"]
if model.deploymodel in supportedmodels:
model.onlinelerningsupport = 'True'
onlineoutputPath = os.path.join(str(model.DeployPath),'production','Config.json')
with open(onlineoutputPath) as file:
onlineoutputPath = json.load(file)
file.close()
details = {'Score' :onlineoutputPath['metricList'],'DataSize':onlineoutputPath['trainRowsList']}
dfonline = pd.DataFrame(details)
model.oltrainingdetails = dfonline
else:
model.onlinelerningsupport = 'False'
except Exception as e:
pass
return models
def usecase_page(request,usecasedetails,Existusecases,usecaseid,search_text):
try:
from appbe import read_service_url_params
tacking_url = read_service_url_params(request)
except:
tacking_url = '127.0.0.1'
hosturl =request.get_host()
hosturl = hosturl.split(':')
hosturl = hosturl[0]
computeinfrastructure = compute.readComputeConfig()
from appbe.aion_config import settings
usecasetab = settings()
kafkaSetting = kafka_setting()
ruuningSetting = running_setting()
selected_use_case,ModelVersion,ModelStatus = getusercasestatus(request)
status,msg = pushRecordForTraining()
if status == False:
context = {'msg':msg}
context['selected'] = 'License'
return status,context,'licenseexpired.html'
ser_url = service_url.read_service_url_params(request)
packagetip='''
Call From Command Line
1. Click AION Shell
2. python {packageAbsolutePath}/aion_predict.py {json_data}
Call As a Package
1. Go To package_path\\publish\\package
2. python -m pip install {packageName}-py3-none-any.whl
Call the predict function after wheel package installation
1. from {packageName} import aion_predict as p1
2. p1.predict({json_data})'''
if request.method == "POST":
usecasename = request.POST.get('UsecaseName')
description = request.POST.get('Description')
usecaseid = request.POST.get('usecaseid')
#print('1',usecasename)
if (usecasename == ''):
usecase = landing_page(usecasedetails,Existusecases,hosturl)
if len(usecase) > 0:
nouc = usecasedetails.objects.latest('id')
nouc = (nouc.id)+1
else:
nouc = 1
nouc = str(nouc).zfill(4)
description_text = 'This is a usecase for AI' + str(nouc)
context = {'description_text':description_text,'usecase':'usecase','Notallowed':'Usecasename is mandatory','ser_url':ser_url,'packagetip':packagetip,'usecasedetail': usecase,'nouc':nouc, 'ser_url':ser_url,'packagetip':packagetip, 'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,'tacking_url':tacking_url,'usecasetab':usecasetab,
'ModelVersion': ModelVersion, 'selected': 'usecase','computeinfrastructure':computeinfrastructure,'kafkaSetting':kafkaSetting,'ruuningSetting':ruuningSetting}
return status,context,'usecases.html'
else:
usecase_count = usecasedetails.objects.filter(usecaseid=usecaseid).count()
usecasename_count = usecasedetails.objects.filter(UsecaseName=usecasename).count()
usecase = landing_page(usecasedetails,Existusecases,hosturl)
if (usecase_count > 0) or (usecasename_count > 0):
nouc = usecasedetails.objects.latest('id')
nouc = (nouc.id)+1
nouc = str(nouc).zfill(4)
Msg = 'Error in usecase creating, try again'
if usecase_count > 0:
Msg = 'Error in usecase creating, try again'
if usecasename_count > 0:
Msg = 'There is already a use case with same name, please provide unique name'
description_text = 'This is a usecase for AI' + str(nouc)
context = {'description_text':description_text,'usecasedetail': usecase, 'nouc': nouc,'Status':'error','Msg': Msg,'tacking_url':tacking_url,'usecasetab':usecasetab,'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,'ser_url':ser_url,'packagetip':packagetip,
'ModelVersion': ModelVersion, 'selected': 'usecase','computeinfrastructure':computeinfrastructure,'kafkaSetting':kafkaSetting,'ruuningSetting':ruuningSetting}
return status,context,'usecases.html'
else:
clusteringModels = Existusecases.objects.filter(Status='SUCCESS',ProblemType='unsupervised').order_by('-id')
from appbe.s3bucketsDB import get_s3_bucket
from appbe.gcsbucketsDB import get_gcs_bucket
from appbe.azureStorageDB import get_azureStorage
p = usecasedetails(UsecaseName=usecasename,usecaseid=usecaseid,Description=description)
p.save()
s1 = Existusecases.objects.filter(ModelName=p.id).annotate(maxver=Max('ModelName__existusecases__Version'))
config_list = s1.filter(Version=F('maxver'))
if config_list.count() > 0:
Version = config_list[0].Version
Version = Version + 1
else:
Version = 1
ps = Existusecases(DataFilePath='', DeployPath='', Status='Not Trained',ConfigPath='', Version=Version, ModelName=p,TrainOuputLocation='')
ps.save()
request.session['ModelName'] = p.id
request.session['UseCaseName'] = usecasename
request.session['usecaseid'] = usecaseid
request.session['ModelVersion'] = Version
request.session['ModelStatus'] = 'Not Trained'
request.session['currentstate'] = 0
request.session['finalstate'] = 0
selected_use_case = usecasename
model_status = 'Not Trained'
ModelVersion = Version
from appbe.telemetry import UseCaseCreated
UseCaseCreated(usecaseid+'-'+str(Version))
if len(usecase) > 0:
nouc = usecasedetails.objects.latest('id')
nouc = (nouc.id)+1
else:
nouc = 1
nouc = str(nouc).zfill(4)
description_text = 'This is a usecase for AI' + str(nouc)
context = {'description_text':description_text,'usecasedetail': usecase, 'nouc': nouc, 'newusercase': usecasename,'tacking_url':tacking_url,'finalstate':request.session['finalstate'],
'description': description,'selected_use_case': selected_use_case,'ser_url':ser_url,'packagetip':packagetip,'clusteringModels':clusteringModels,'s3buckets':get_s3_bucket(),'gcsbuckets':get_gcs_bucket(),'usecasetab':usecasetab,'azurestorage':get_azureStorage(),
'ModelStatus': model_status, 'ModelVersion': ModelVersion, 'selected': 'modeltraning','computeinfrastructure':computeinfrastructure}
return status,context,'upload.html'
else:
models = get_landing_model(Existusecases)
usecase = landing_page(usecasedetails,Existusecases,hosturl,usecaseid,search_text)
if len(usecase) > 0:
nouc = usecasedetails.objects.latest('id')
nouc = (nouc.id)+1
else:
nouc = 1
nouc = str(nouc).zfill(4)
description_text = 'This is a usecase for AI' + str(nouc)
context = {'description_text':description_text,'usecasedetail': usecase, 'nouc': nouc, 'models': models, 'selected_use_case': selected_use_case,'ser_url':ser_url,'packagetip':packagetip,'tacking_url':tacking_url,'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion, 'selected': 'usecase','computeinfrastructure':computeinfrastructure,'kafkaSetting':kafkaSetting,'ruuningSetting':ruuningSetting,'usecasetab':usecasetab}
if usecaseid:
context.update({'ucdetails':'True'})
return status,context,'usecases.html'
def index_page(request,usecasedetails,Existusecases):
if 'ModelVersion' in request.session:
del request.session['ModelVersion']
if 'UseCaseName' in request.session:
del request.session['UseCaseName']
if 'ModelStatus' in request.session:
del request.session['ModelStatus']
if 'currentstate' in request.session:
del request.session['currentstate']
if 'finalstate' in request.session:
del request.session['finalstate']
return usecases_page(request,usecasedetails,Existusecases)
def usecases_page(request,usecasedetails,Existusecases,usecaseid=None,substring=None):
return usecase_page(request,usecasedetails,Existusecases,usecaseid,substring)
def mllite_page(request):
from appbe.aion_config import settings
usecasetab = settings()
status,msg = pushRecordForTraining()
if status == False:
context = {'selected':'mllite','lerror':msg}
return context
configFile = os.path.join(DEFAULT_FILE_PATH, 'model_converter.json')
f = open(configFile, "r")
configSettings = f.read()
f.close()
configSettingsJson = json.loads(configSettings)
context = {}
context = {'selected':'mllite','sagemaker':configSettingsJson,'usecasetab':usecasetab}
return context
def mltesting_page(request):
from appbe.aion_config import settings
usecasetab = settings()
status,msg = pushRecordForTraining()
if status == False:
context = {'lerror':msg}
return context
if request.method == "POST":
models = request.POST['model']
datap = request.POST['data']
if(os.path.isfile(models) and os.path.isfile(datap)):
request.session['datalocation'] = datap
df = pd.read_csv(datap,encoding='utf-8',skipinitialspace = True,encoding_errors= 'replace')
trainfea = df.columns.tolist()
featurs = request.POST.getlist('Training')
feature = ",".join(featurs)
filetimestamp = str(int(time.time()))
settingconfig = os.path.join(CONFIG_FILE_PATH, 'MLTest_' + filetimestamp + '.json')
request.session['MLTestResult'] = settingconfig
mltestresult={}
mltestresult['models'] = models
mltestresult['datap'] = datap
mltestresult['feature'] = feature
# features = ['PetalLengthCm','PetalWidthCm']
targ = request.POST['Target']
tar =[targ]
mltestresult['target'] = targ
mltestresult = json.dumps(mltestresult)
with open(settingconfig, "w") as fpWrite:
fpWrite.write(mltestresult)
fpWrite.close()
from pathlib import Path
mltest={}
if Path(models).is_file() and Path(datap).is_file():
try:
from mltest import baseline
outputStr = baseline.baseline_testing(models,datap, feature, targ)
#scriptPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..','bin','run_mltest.py'))
#print(scriptPath, models, datap, feature, targ)
#outputStr = subprocess.check_output([sys.executable, scriptPath, models, datap, feature, targ])
#print(outputStr)
#outputStr = outputStr.decode('utf-8')
#outputStr= outputStr.replace('\\'','\\"')
#print('ou',outputStr)
#outputStr = outputStr.strip()
mltest = json.loads(outputStr)
Problemtype= mltest['Problemtype']
with open(request.session['MLTestResult'], 'r+') as f:
mltestresult = json.load(f)
f.close()
mltestresult['Problemtype'] = Problemtype
mltestresult['ProblemName'] = mltest['ProblemName']
status = mltest['Status']
if status == 'Fail':
errormsg= mltest['Msg']
context = {'error':errormsg,'mltest':'mltest'}
else:
if Problemtype == 'Classification':
mltestresult['Score'] = mltest['Accuracy']
mltestresult['Params'] = mltest['Params']
Problem= mltest['ProblemName']
Parameters= mltest['Params']
round_params = {}
for key, value in Parameters.items():
if isinstance(value, float):
round_params[key] = round(value,2)
else:
round_params[key] = value
matrixconfusion = mltest['Confusionmatrix']
classificationreport = mltest['classificationreport']
classificationreport = json.loads(classificationreport)
matrixconfusion = json.loads(matrixconfusion)
indexName =[]
columnName = []
for i in matrixconfusion.keys():
indexName.append("act:"+str(i))
for j in matrixconfusion[i].keys():
columnName.append("pre:"+str(j))
df3 = pd.DataFrame.from_dict(classificationreport)
df = df3.transpose()
df2 = pd.DataFrame.from_dict(matrixconfusion)
df1 = pd.DataFrame(df2.values, | ||
index=indexName,columns=columnName)
report = df.to_html()
report1 = df1.to_html()
recordone = mltest['onerecord']
recordsten = mltest['tenrecords']
recordshund = mltest['hundrecords']
context = {'modelname': models,'datapath':datap,'features':featurs,'target':tar,'Problemtype':Problem,'modeltype':Problemtype,'Parameter':round_params,'Onerecord':recordone,'Tenrecords':recordsten,'Hundrecords':recordshund,'matrixconfusion':report1,'classificationreport':report,'classification':'classification','df':df,'df1':df1,'basemltest':'basemltest','success':'success','trainfea':trainfea,'selected':'mltesting','usecasetab':usecasetab}
elif Problemtype == 'Regression':
Problem= mltest['ProblemName']
mltestresult['Params'] = mltest['Params']
mltestresult['Score'] = mltest['R2']
Parameters= mltest['Params']
round_params = {}
for key, value in Parameters.items():
if isinstance(value, float):
round_params[key] = round(value,2)
else:
round_params[key] = value
Mse = mltest['MSE']
Mae = mltest['MAE']
Rmse = mltest['RMSE']
R2 = mltest['R2']
recordone = mltest['onerecord']
recordsten = mltest['tenrecords']
recordshund = mltest['hundrecords']
context = {'modelname': models,'datapath':datap,'features':featurs,'target':tar, 'Problemtype':Problem,'Parameter':round_params,'Onerecord':recordone,'Tenrecords':recordsten,'Hundrecords':recordshund,'Mse':Mse,'Mae':Mae,'Rmse':Rmse,'R2Score':R2,'regression':'regression','success':"success",'selected': 'mltest','basemltest':'basemltest','usecasetab':usecasetab}
else:
errormsg= mltest['Msg']
context = {'error':errormsg,'mltest':'mltest'}
mltestresult = json.dumps(mltestresult)
with open(settingconfig, "w") as fpWrite:
fpWrite.write(mltestresult)
fpWrite.close()
except Exception as e:
print("-------------"+str(e)+'=================')
e = str(e).replace('\\'','')
errormsg = 'Error: Exception '+str(e)
context = {'error':errormsg,'mltest':'mltest'}
else:
if not (Path(models).is_file() and Path(datap).is_file()):
context = {'error':"Please Check ModelPath & Datapath Format","result":"result",'selected':'mltesting','usecasetab':usecasetab}
elif not Path(models).is_file():
context = {'error':"Please Check ModelPath Format","result":"result",'selected':'mltesting','usecasetab':usecasetab}
elif not Path(datap).is_file():
context = {'error':"Please Check DataPath Format","result":"result",'selected':'mltesting','usecasetab':usecasetab}
else:
context = {'error':'Either model path or data path does not exist','mltest':'mltest','usecasetab':usecasetab}
else:
context = {'selected':'mltesting','usecasetab':usecasetab}
return context<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os
import pandas as pd
import requests
import re
import json
import sys
import time
from appbe.aion_config import get_llm_data
from appbe.dataPath import LOG_LOCATION
from appbe.log_ut import logg
import logging
import openai
import tiktoken
openai.api_key = ''
openai.api_base = ''
openai.api_type = ''
openai.api_version = ''
deployment_name="Text-Datvinci-03"
def generateLabelPerRecord(OrgData):
OrgData['LabelFromGPT'] = OrgData['Head_Description'].apply(lambda x: \\
generate_gpt3_response\\
("I am giving you the title and short description \\
in the format [Title:Description], \\
give me the related low level topics in one word in the \\
format[Topic: your primary topic] along with top 5 important keywords in the \\
format[Keywords: keywords]'{}' ".format(x)))
#Cleaning the output as it is from ChatGPT
OrgData['temp1'] = OrgData['LabelFromGPT'].apply(lambda x: (x.split('Topic:')[1]).replace(']',''))
OrgData['LabelFromGPT'] = OrgData['temp1'].apply(lambda x: (x.split('Keywords:')[0]).replace(']','').rstrip())
OrgData['Keywords'] = OrgData['temp1'].apply(lambda x: (x.split('Keywords:')[1]).replace(']',''))
OrgData = OrgData.drop(['temp1','Head_Description'], axis=1)
return OrgData
def generateLabelForChunkedRecords(OrgData):
import io
# OrgData = OrgData.head(120)
Head_Description = {"Head_Description": [] }
Head_Description2 = {"Head_Description": [] }
Head_Description['Head_Description'] = OrgData['Head_Description']
strt_ind = 0
brk_ind = 0
# encoding = tiktoken.get_encoding('p50k_base')
encoding = tiktoken.encoding_for_model("text-davinci-003")
chunks = []
_cur_token_count = 0
_chunk_token_count = 0
for ind in Head_Description['Head_Description'].index:
tokenized_text = encoding.encode(Head_Description['Head_Description'][ind])
_cur_token_count = len(tokenized_text)
if _cur_token_count >= 600:
OrgData['Head_Description'][ind] = OrgData['Head_Description'][ind][:1000]
upto_ind = ind + 1
Head_Description2['Head_Description'] = OrgData['Head_Description'][brk_ind:ind]
_chunk_token_count = encoding.encode(Head_Description2['Head_Description'].to_string())
if len(_chunk_token_count) >= 1200:
brk_ind = ind
# print(brk_ind)
chunks.append(ind-1)
_start_count = 0
if len(chunks) == 0:
output = generate_gpt3_response("I am giving you datatable of text records \\
for each record give me the related low level topics in one word as a data column called Topic\\
and important top five keywords as a data column called Keywords. \\
Provide me record number as Record and these two data columns as datatable for each record in the given datatable and number of records should be equivalent to the number of records in the given datatable of text records. '{}' ".format(Head_Description['Head_Description']))
out = io.StringIO(output[2:])
df = pd.read_csv(out, sep='\\t')
else:
chunks.append(len(Head_Description['Head_Description']))
for ind_val in chunks:
_cur_ind_val = ind_val
_recordsSent = 0
Head_Description = {"Head_Description": [] }
if _start_count == 0:
Head_Description['Head_Description'] = OrgData['Head_Description'][strt_ind:_cur_ind_val].to_string()
_recordsSent = len(OrgData['Head_Description'][strt_ind:_cur_ind_val])
else:
Head_Description['Head_Description'] = OrgData['Head_Description'][_pre_ind_val:_cur_ind_val].to_string()
_recordsSent = len(OrgData['Head_Description'][_pre_ind_val:_cur_ind_val])
_pre_ind_val = ind_val
# if _start_count <= 5:
output = generate_gpt3_response("I am giving you datatable of text records \\
for each record give me the related low level topics in one word as a data column called Topic\\
and important top five keywords as a data column called Keywords. \\
Provide me record number as Record and these two data columns as datatable for each record in the given datatable and number of records should be equivalent to the number of records in the given datatable of text records. '{}' ".format(Head_Description['Head_Description']))
out = io.StringIO(output[2:])
if _start_count == 0:
df = pd.read_csv(out, sep='\\t')
else:
df_tmp = pd.read_csv(out, sep='\\t')
if len(df_tmp) > _recordsSent:
df_tmp = df_tmp.head(_recordsSent)
# df = df.append(df_tmp, ignore_index=True)
df = pd.concat([df, df_tmp], ignore_index=True)
_start_count += 1
OrgData['LabelFromGPT'] = df['Topic']
OrgData['Keywords'] = df['Keywords']
OrgData = OrgData.drop(['Head_Description'], axis=1)
return OrgData
# Text Data Labelling using LLM related changes
# --------------------------------------------------------
def generateTextLabel(request, DATA_FILE_PATH):
log = logging.getLogger('log_ux')
key,url,api_type,api_version = get_llm_data()
openai.api_key = key
openai.api_base = url
openai.api_type = api_type
openai.api_version = api_version
try:
features = request.POST.getlist('InputFeatures')
datapath = request.session['textdatapath']
OrgData = pd.read_csv(datapath)
# OrgData = OrgData.head(2000)
OrgData.fillna("", inplace = True)
OrgData['Head_Description'] = OrgData[features[0]]
if (len(features) > 1):
for indx in range(len(features)):
if (indx > 0):
OrgData['Head_Description'] = OrgData['Head_Description'] + " "+ OrgData[features[indx]]
# OrgData = generateLabelPerRecord(OrgData)
OrgData = generateLabelForChunkedRecords(OrgData)
df = OrgData
filetimestamp = str(int(time.time()))
datasetName = 'AION_TextLabelled' + filetimestamp+'.csv'
dataFile = os.path.join(DATA_FILE_PATH,datasetName)
df.to_csv(dataFile)
request.session['texttopicdatapath'] = dataFile
df_json = df.to_json(orient="records")
df_json = json.loads(df_json)
from appbe.dataPath import DATA_DIR
from appbe.sqliteUtility import sqlite_db
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'config.db')
newdata = {}
newdata['datapath'] = [dataFile]
newdata['datasetname'] = [datasetName]
sqlite_obj.write_data(pd.DataFrame.from_dict(newdata), 'dataingest')
################################################
context = {'data_topic':df_json, 'selected':'DataOperations'}
return context
except Exception as e:
print(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
errormsg = str(e)
if 'Invalid URL' in errormsg or 'No connection adapters' in errormsg or 'invalid subscription key' in errormsg:
errormsg = 'Access denied due to invalid subscription key or wrong API endpoint. Please go to settings and make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource.'
if 'Max retries exceeded with url' in errormsg:
errormsg = 'Please make sure you have good internet connection and access to API endpoint for your resource.'
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
context = {'error': 'Failed to communicate LLM','LLM' : 'openAI', 'selected':'DataOperations', 'errormessage':errormsg}
log.info('generateTextLabel -- Error : Failed to generate Text-Label.. '+str(e))
log.info('Details : '+ str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
return context
#function to return the queried response
def generate_gpt3_response(user_text, print_output=False):
"""
Query OpenAI GPT-3 for the specific key and get back a response
:type user_text: str the user's text to query for
:type print_output: boolean whether or not to print the raw output JSON
"""
time.sleep(2)
completions = openai.Completion.create(
# engine='Text-Datvinci-03', # Determines the quality, speed, and cost. engine='text-davinci-003',
engine=deployment_name, # Determines the quality, speed, and cost. engine='text-davinci-003',
temperature=0, # Level of creativity in the response
prompt=user_text, # What the user typed in
max_tokens=2000, # Maximum tokens in the prompt AND response
n=1, # The number of completions to generate
stop=None, # An optional setting to control response generation
)
# Displaying the output can be helpful if things go wrong
if print_output:
print(completions)
# Return the first choice's text
# print(completions.choices[0].text)
return completions.choices[0].text
# --------------------------------------------------------<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
| ||
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import json
import pandas as pd
def get_true_option(d, default_value=None):
if isinstance(d, dict):
for k, v in d.items():
if (isinstance(v, str) and v.lower() == 'true') or (isinstance(v, bool) and v == True):
return k
return default_value
def get_true_options(d):
options = []
if isinstance(d, dict):
for k, v in d.items():
if (isinstance(v, str) and v.lower() == 'true') or (isinstance(v, bool) and v == True):
options.append(k)
return options
def check_datetime(config):
dateTime = config['basic']['dateTimeFeature']
if dateTime == '' or dateTime.lower()=='na':
return False
return True
def check_dtype(d):
flag= 1
for item in d:
if item["type"].lower() != "text" and item["type"].lower() != "index":
flag = 0
break
return flag
def check_text(d): #task 12627
flag= 0
for item in d:
if item["type"].lower() == "text":
flag = 1
break
return flag
def check_labelencoding(ftr_dict_list, target_ftr):
for ftr_dict in ftr_dict_list:
if ftr_dict['feature']!=target_ftr and ftr_dict['type'].lower()=='categorical' and ftr_dict['categoryEncoding'].lower()!='labelencoding':
return False
return True
class timeseries():
def __init__(self,config):
self.config=config
if self.config['basic']['analysisType']['timeSeriesForecasting'].lower()=='true': #task 11997
self.problemType = 'timeSeriesForecasting'
elif self.config['basic']['analysisType']['timeSeriesAnomalyDetection'].lower()=='true':
self.problemType = 'timeSeriesAnomalyDetection' #task 11997
def validate_basic_config(self,status='pass',msg=None):
#task 12627
date_time_status = check_datetime(self.config)
text_status = check_text(self.config['advance']['profiler']['featureDict'])
if not date_time_status and text_status:
msg = 'For time series problem,\\\\n* One feature should be in datetime format\\\\n* Text feature not supported '
return 'error', msg
elif not date_time_status:
msg = 'For time series problem, one feature should be in datetime format'
return 'error', msg
elif text_status:
msg = 'For time series problem, text feature not supported '
return 'error', msg
selected_algos = get_true_options(self.config['basic']['algorithms'][self.problemType]) #task 11997
if isinstance(self.config['basic']['targetFeature'],str):
targetFeature = list(self.config['basic']['targetFeature'].split(','))
if self.problemType=='timeSeriesForecasting': #task 11997
if len(targetFeature) > 1:
if 'ARIMA' in selected_algos:
status = 'error'
msg = "ARIMA is not supported for multilabel (target) feature"
return status, msg
if "FBPROPHET" in selected_algos:
status = 'error'
msg = "FBPROPHET is not supported for multiLabel (target) feature"
return status, msg
if 'MLP' in selected_algos:
status = 'error'
msg = "MLP is not supported for multiLabel (target) feature"
return status, msg
if len(targetFeature) == 1 and 'VAR' in selected_algos:
status = 'error'
msg = "VAR is not supported for singleLabel (target) feature"
return status, msg
elif self.problemType=='timeSeriesAnomalyDetection': #task 11997
anomChecker = anomaly(self.config)
status, msg = anomChecker.validate_basic_config()
return status, msg
class anomaly():
def __init__(self,config):
self.config = config
if self.config['basic']['analysisType']['anomalyDetection'].lower()=='true': #task 11997
self.problemType = 'anomalyDetection'
elif self.config['basic']['analysisType']['timeSeriesAnomalyDetection'].lower()=='true': #task 11997
self.problemType = 'timeSeriesAnomalyDetection'
def validate_basic_config(self,status='pass',msg=None):
#task 12627
date_time_status = check_datetime(self.config)
targetFeature = self.config['basic']['targetFeature']
if self.problemType=='anomalyDetection' and date_time_status:
status = 'error'
msg = 'Date feature detected. For anomaly detection on time series change problem type to Time Series Anomaly Detection or drop Date feature'
return status, msg
if targetFeature.lower()!= 'na' and targetFeature!= "" and self.config['basic']['inlierLabels'] == '':
status = 'error'
msg = 'Please provide inlier label in case of supervised anomaly detection'
return status, msg
class survival():
def __init__(self,config):
self.config = config
self.problemType= 'survivalAnalysis'
def validate_basic_config(self):
dateTimeStatus = check_datetime(self.config)
labelencoding_status = check_labelencoding(self.config['advance']['profiler']['featureDict'], self.config['basic']['targetFeature'])
if not dateTimeStatus and not labelencoding_status:
msg = 'For survival analysis problem,\\\\n* One feature should be in datetime format\\\\n* Encoding of categorical features should be of label encoding '
return 'error', msg
elif not dateTimeStatus:
msg = 'One feature should be in datetime format for survival analysis problem. Please select it from model feature'
return 'error', msg
elif not labelencoding_status:
msg = 'Categorical features are expected to be label encoded for survival analysis problem. Please select it from feature encoding'
return 'error', msg
else:
return 'pass', " "
class associationrule():
def __init__(self,config):
self.config=config
def validate_basic_config(self,status='pass', msg=None):
if self.config['basic']['algorithms']['recommenderSystem']['associationRulesConfig']['invoiceNoFeature'].lower() == '' or self.config['basic']['algorithms']['recommenderSystem']['associationRulesConfig']['invoiceNoFeature'].lower() == 'na' or self.config['basic']['algorithms']['recommenderSystem']['associationRulesConfig']['itemFeature'].lower() == '' or self.config['basic']['algorithms']['recommenderSystem']['associationRulesConfig']['itemFeature'].lower() == 'na':
return "error","Make sure to configure invoice feature and item feature"
elif self.config['basic']['algorithms']['recommenderSystem']['associationRulesConfig']['invoiceNoFeature'] == self.config['basic']['algorithms']['recommenderSystem']['associationRulesConfig']['itemFeature']:
return "error","Make sure to invoice feature and item feature is configure correctly"
else:
return "pass", " "
class itemrating(): #task 6081
def __init__(self,config):
self.config = config
def validate_basic_config(self):
data_loc = self.config['basic']['dataLocation']
data_length = len(pd.read_csv(data_loc))
if data_length >= 1000000:
return 'error', "Recommender System can handle data up to 1 million records. Please try with a smaller dataset."
else:
return "pass"," "
class documentsimilarity():
def __init__(self,config):
self.config=config
def validate_basic_config(self,status='pass', msg=None):
flag = check_dtype(self.config['advance']['profiler']['featureDict'])
if flag == 1:
return "pass", " "
else:
msg="Make sure to change the feature type from Categorical to Text and drop Numerical features for document similarity"
return "error", msg
def validate(config):
try:
problem_type = get_true_option(config['basic']['analysisType'])
status = 'pass'
msg = ''
if 'timeseries' in problem_type.lower(): #task 11997
obj = timeseries(config)
elif problem_type.lower() == 'survivalanalysis':
obj = survival(config)
elif problem_type.lower() == 'anomalydetection':
obj = anomaly(config)
elif problem_type.lower() in ['similarityidentification','contextualsearch']:
obj = documentsimilarity(config)
elif problem_type.lower() == 'recommendersystem':
if config['basic']['algorithms']['recommenderSystem']['AssociationRules-Apriori'].lower() == 'true':
obj = associationrule(config)
elif config['basic']['algorithms']['recommenderSystem']['ItemRating'].lower() == 'true': #task 6081
obj = itemrating(config)
else:
return 'pass',""
else:
return 'pass',""
status,msg= obj.validate_basic_config()
print(status, msg, 'io')
return(status,msg)
except Exception as e:
print(e)
def start_check(config):
return validate(config)
<s> import json
import os
import pandas as pd
import urllib, base64
def check_deepCheckPlots(deployedLocation):
deepCheck = 'False'
boostOverfit = 'False'
boostOverfitCond = 'False'
mi='False'
miCond='False'
smc = 'False'
smsCond = 'False'
boostOverfitFile= os.path.join(deployedLocation,'log','boosting_overfit.html')
boostOverfitCondFile= os.path.join(deployedLocation,'log','boosting_overfit_condition.html')
smcFile= os.path.join(deployedLocation,'log','smc.html')
smcCondFile= os.path.join(deployedLocation,'log','smc_condition.html')
miFile= os.path.join(deployedLocation,'log','mi.html')
miConFile= os.path.join(deployedLocation,'log','mi_con.html')
file_exists = os.path.exists(boostOverfitFile)
if file_exists:
deepCheck = 'True'
boostOverfit = 'True'
file_exists = os.path.exists(boostOverfitCondFile)
if file_exists:
deepCheck = 'True'
boostOverfitCond = 'True'
file_exists = os.path.exists(miFile)
if file_exists:
deepCheck = 'True'
mi = 'True'
file_exists = os.path.exists(miConFile)
if file_exists:
deepCheck = 'True'
miCond = 'True'
file_exists = os.path.exists(smcFile)
if file_exists:
deepCheck = 'True'
smc = 'True'
file_exists = os.path.exists(smcCondFile)
if file_exists:
deepCheck = 'True'
smsCond = 'True'
output = {'deepCheck':deepCheck,'boostOverfit':boostOverfit,'boostOverfitCond':boostOverfitCond,'mi':mi,'miCond':miCond,'smc':smc,'smsCond':smsCond}
return output
def FeaturesUsedForTraining(output_json):
resultJsonObj = json.loads(output_json)
result = {}
result['Status'] = resultJsonObj['status']
result['ModelType'] = resultJsonObj['data']['ModelType']
result['ScoreType'] = resultJsonObj['data']['ScoreType']
result['FeaturesUsed'] = resultJsonObj['data']['featuresused']
result['BestModel'] = resultJsonObj['data']['BestModel']
return result
def ParseResults(output_json):
msg1 = 'Results...'
resultJsonObj = json.loads(output_json)
result = {}
survical_images = []
result['Status'] = resultJsonObj['status']
result['ModelType'] = resultJsonObj['data']['ModelType']
if 'vmDetails' in resultJsonObj['data']:
result['DeployLocation'] = resultJsonObj['data']['vmDetails']
else:
result['DeployLocation'] = resultJsonObj['data']['deployLocation']
result['BestModel'] = resultJsonObj['data']['BestModel']
if str(resultJsonObj['data']['BestScore']) == "NA":
result['BestScore'] = 'NA'
else:
result['BestScore'] = round(float(resultJsonObj['data']['BestScore']), 2)
result['ScoreType'] = resultJsonObj['data']['ScoreType']
result['FeaturesUsed'] = resultJsonObj['data']['featuresused']
##### Training Confusion Matrix
result['problem_type'] = result['ModelType']
if result['ModelType'].lower() == 'timeseriesanomalydetection':
result['problem_type'] = 'TimeSeriesAnomalydetection'
if result['ModelType'] == 'classification' or result['ModelType'].lower() == 'distributed classification' or (result['ModelType'] == 'anomalydetection' and (result['BestScore']) != 0) or result['ModelType'] == 'ImageClassification':
bestmodel = resultJsonObj['data']['BestModel']
if bestmodel.lower() == 'nas':
modelSummary= os.path.join(result['DeployLocation'],'summary.txt')
f = open(modelSummary, 'r')
file_content = f.read()
f.close()
#print(file_content)
result['modelSummary'] = file_content
#task 11997
if result['ModelType'].lower() == 'classification':
result['problem_type'] = 'Classification'
elif result['ModelType'].lower() == 'anomalydetection':
result['problem_type'] = 'AnomalyDetection'
elif result['ModelType'].lower() == 'imageclassification':
result['problem_type'] = 'ImageClassification'
elif result['ModelType'].lower() == 'distributed classification':
result['problem_type'] = | ||
'Distributed Classification'
try:
result['deepCheck'] = check_deepCheckPlots(result['DeployLocation'])
except Exception as e:
print(e)
if 'ConfusionMatrix' in resultJsonObj['data']['trainmatrix']:
TrainConfusionMatrix = resultJsonObj['data']['trainmatrix']['ConfusionMatrix']
numLabels = len(TrainConfusionMatrix)
TrainConfusionMatrixList = []
for act_key, value in TrainConfusionMatrix.items():
temp = {}
temp['Label'] = act_key
for pred_key, pred_value in value.items():
temp[pred_key] = pred_value
TrainConfusionMatrixList.append(temp)
result['TrainConfusionMatrix'] = TrainConfusionMatrixList
TrainClassificationReport = resultJsonObj['data']['trainmatrix']['ClassificationReport']
numRows = len(TrainClassificationReport)
TrainClassificationReportList = []
metrics_keys_list = []
for key, value in TrainClassificationReport.items():
temp = {}
temp['Label'] = key
if isinstance( value, dict):
for metricsKey, metricsValue in value.items():
temp[metricsKey] = round(metricsValue, 4)
if metricsKey not in metrics_keys_list:
metrics_keys_list.append( metricsKey)
else:
if metrics_keys_list:
for key in metrics_keys_list:
temp[key] = round(value, 4)
TrainClassificationReportList.append(temp)
result['TrainClassificationReport'] = TrainClassificationReportList
result['Train_ROC_AUC_SCORE'] = round(float(resultJsonObj['data']['trainmatrix']['ROC_AUC_SCORE']), 4)
else:
result['TrainClassificationReport'] = ''
result['Train_ROC_AUC_SCORE']=''
##### Testing Confusion Matix
if 'ConfusionMatrix' in resultJsonObj['data']['matrix']:
ConfusionMatrix = resultJsonObj['data']['matrix']['ConfusionMatrix']
numLabels = len(ConfusionMatrix)
ConfusionMatrixList = []
for act_key, value in ConfusionMatrix.items():
temp = {}
temp['Label'] = act_key
for pred_key, pred_value in value.items():
temp[pred_key] = pred_value
ConfusionMatrixList.append(temp)
result['ConfusionMatrix'] = ConfusionMatrixList
ClassificationReport = resultJsonObj['data']['matrix']['ClassificationReport']
numRows = len(ClassificationReport)
ClassificationReportList = []
metrics_keys_list = []
for key, value in ClassificationReport.items():
temp = {}
temp['Label'] = key
if isinstance( value, dict):
for metricsKey, metricsValue in value.items():
temp[metricsKey] = round(metricsValue, 4)
if metricsKey not in metrics_keys_list:
metrics_keys_list.append( metricsKey)
else:
if metrics_keys_list:
for key in metrics_keys_list:
temp[key] = round(value, 4)
ClassificationReportList.append(temp)
result['ClassificationReport'] = ClassificationReportList
result['ROC_AUC_SCORE'] = round(float(resultJsonObj['data']['matrix']['ROC_AUC_SCORE']), 4)
elif result['ModelType'] == 'similarityIdentification':
result['problem_type'] = 'similarityIdentification'
elif result['ModelType'] == 'contextualSearch':
result['problem_type'] = 'contextualSearch'
elif result['ModelType'] == 'MultiLabelPrediction':
result['problem_type'] = 'MultiLabelPrediction'
matrix = resultJsonObj['data']['matrix']
training_matrix = []
for x in matrix:
fmatrix = {}
fmatrix['feature'] = x
performance = {}
for y in matrix[x]:
performance[y] = matrix[x][y]
fmatrix['performance'] = performance
training_matrix.append(fmatrix)
testmatrix = resultJsonObj['data']['testmatrix']
testing_matrix = []
for x in testmatrix:
fmatrix = {}
fmatrix['feature'] = x
performance = {}
for y in testmatrix[x]:
performance[y] = testmatrix[x][y]
fmatrix['performance'] = performance
testing_matrix.append(fmatrix)
result['testing_matrix'] = testing_matrix
result['training_matrix'] = training_matrix
elif result['ModelType'] == 'regression' or result['ModelType'].lower() == 'distributed regression':
try:
result['deepCheck'] = check_deepCheckPlots(result['DeployLocation'])
except Exception as e:
print(e)
try:
result['problem_type'] = 'Regression'
testing_matrix = {}
if 'MAE' in resultJsonObj['data']['matrix']:
testing_matrix['MAE'] = float(resultJsonObj['data']['matrix'].get('MAE','0'))
testing_matrix['R2Score'] = float(resultJsonObj['data']['matrix'].get('R2Score','0'))
testing_matrix['MSE'] = float(resultJsonObj['data']['matrix'].get('MSE','0'))
testing_matrix['MAPE'] = float(resultJsonObj['data']['matrix'].get('MAPE','0'))
testing_matrix['RMSE'] = float(resultJsonObj['data']['matrix'].get('RMSE','0'))
testing_matrix['NormalisedRMSEPercentage'] = float(resultJsonObj['data']['matrix'].get('Normalised RMSE(%)','0'))
result['testing_matrix'] = testing_matrix
training_matrix = {}
training_matrix['MAE'] = float(resultJsonObj['data']['trainmatrix'].get('MAE','0'))
training_matrix['R2Score'] = float(resultJsonObj['data']['trainmatrix'].get('R2Score','0'))
training_matrix['MSE'] = float(resultJsonObj['data']['trainmatrix'].get('MSE','0'))
training_matrix['MAPE'] = float(resultJsonObj['data']['trainmatrix'].get('MAPE','0'))
training_matrix['RMSE'] = float(resultJsonObj['data']['trainmatrix'].get('RMSE','0'))
training_matrix['NormalisedRMSEPercentage'] = float(resultJsonObj['data']['trainmatrix'].get('Normalised RMSE(%)','0'))
result['training_matrix'] = training_matrix
except Exception as e:
print(e)
elif result['ModelType'] == 'Text Similarity':
result['problem_type'] = 'textsimilarity'
testing_matrix = {}
testing_matrix['Accuracy'] = float(resultJsonObj['data']['matrix']['Accuracy'])
testing_matrix['ROC_AUC'] = float(resultJsonObj['data']['matrix']['ROC AUC'])
result['testing_matrix'] = testing_matrix
training_matrix = {}
training_matrix['Accuracy'] = float(resultJsonObj['data']['trainmatrix']['Accuracy'])
training_matrix['ROC_AUC'] = float(resultJsonObj['data']['trainmatrix']['ROC AUC'])
result['training_matrix'] = training_matrix
elif result['ModelType'] == 'RecommenderSystem': #taskid 11190
result['problem_type'] = 'Recommender'
testing_matrix = {}
testing_matrix['RMSE'] = 'NA'
result['testing_matrix'] = testing_matrix
training_matrix = {}
training_matrix['RMSE'] = 'NA'
result['training_matrix'] = training_matrix
elif result['ModelType'] == 'SurvivalAnalysis':
result['problem_type'] = 'SurvivalAnalysis'
survivalProbabilityjson = resultJsonObj['data']['survivalProbability']
performanceimages = resultJsonObj['data']['imageLocation']
start = '['
end = ']'
performanceimages = performanceimages[performanceimages.find(start) + len(start):performanceimages.rfind(end)]
performanceimages = performanceimages.split(',')
for imagefile in performanceimages:
imagefile = imagefile.replace("'", "")
string = base64.b64encode(open(imagefile, "rb").read())
image_64 = 'data:image/png;base64,' + urllib.parse.quote(string)
survical_images.append(image_64)
result['survivalProbability'] = survivalProbabilityjson
elif result['ModelType'] == 'StateTransition':
result['problem_type'] = 'StateTransition'
stateprobabilityfile = os.path.join(result['DeployLocation'],'stateTransitionProbability.csv')
clusterfile = os.path.join(result['DeployLocation'],'stateClustering.csv')
if(os.path.isfile(stateprobabilityfile)):
df_prob = pd.read_csv(stateprobabilityfile)
df_prob = df_prob[['State','NextState','Probability']]
result['probability'] = df_prob
if(os.path.isfile(clusterfile)):
df_clus = pd.read_csv(clusterfile)
df_clus = df_clus[['clusterid','clusterlist']]
result['cluster'] = df_clus
elif result['ModelType'].lower() == 'timeseriesforecasting': #task 11997
result['problem_type'] = 'TimeSeriesForecasting'
if result['BestModel'] == 'FBPROPHET':
imagefile = os.path.join(result['DeployLocation'],'log','img','prophet_fig.png')
string = base64.b64encode(open(imagefile, "rb").read())
image_64 = 'data:image/png;base64,' + urllib.parse.quote(string)
survical_images.append(image_64)
testing_matrix = {}
testing_matrix['MAE'] = float(resultJsonObj['data']['matrix']['MAE'])
testing_matrix['MSE'] = float(resultJsonObj['data']['matrix']['MSE'])
testing_matrix['R2'] = float(resultJsonObj['data']['matrix']['R2'])
testing_matrix['RMSE'] = float(resultJsonObj['data']['matrix']['RMSE'])
result['testing_matrix'] = testing_matrix
forecastjson = resultJsonObj['data']['forecasts']
result['forecast'] = forecastjson
if result['BestModel'] == 'VAR':
'''
FeaturesMatrix = resultJsonObj['data']['matrix']['FeaturesMatrix']
mae = ''
mse = ''
mape = ''
rmse = ''
for x in FeaturesMatrix:
if mae != '':
mae += ','
if mse != '':
mse += ','
if R2 != '':
R2 += ','
if rmse != '':
rmse += ','
featurename = x['Features']
mae = mae + featurename + '=' + x['MAE']
mse = mse + featurename + '=' + x['MSE']
R2 = R2 + featurename + '=' + x['R2']
rmse = rmse + featurename + '=' + x['RMSE']
testing_matrix = {}
testing_matrix['MAE'] = mae
testing_matrix['MSE'] = mse
testing_matrix['R2'] = R2
testing_matrix['RMSE'] = rmse
result['testing_matrix'] = testing_matrix
forecastjson = resultJsonObj['data']['forecasts']
result['forecast'] = forecastjson
'''
testing_matrix = {}
testing_matrix['MAE'] = float(resultJsonObj['data']['matrix']['MAE'])
testing_matrix['MSE'] = float(resultJsonObj['data']['matrix']['MSE'])
testing_matrix['R2'] = float(resultJsonObj['data']['matrix']['R2'])
testing_matrix['RMSE'] = float(resultJsonObj['data']['matrix']['RMSE'])
result['testing_matrix'] = testing_matrix
forecastjson = resultJsonObj['data']['forecasts']
result['forecast'] = forecastjson
elif result['BestModel'] == 'LSTM' or result['BestModel'] == 'MLP':
testing_matrix = {}
testing_matrix['MSE'] = float(resultJsonObj['data']['matrix']['MSE'])
testing_matrix['RMSE'] = float(resultJsonObj['data']['matrix']['RMSE'])
result['testing_matrix'] = testing_matrix
forecastjson = resultJsonObj['data']['forecasts']
result['forecast'] = forecastjson
else:
testing_matrix = {}
testing_matrix['MAE'] = float(resultJsonObj['data']['matrix']['MAE'])
testing_matrix['MSE'] = float(resultJsonObj['data']['matrix']['MSE'])
testing_matrix['R2'] = float(resultJsonObj['data']['matrix']['R2'])
testing_matrix['RMSE'] = float(resultJsonObj['data']['matrix']['RMSE'])
result['testing_matrix'] = testing_matrix
forecastjson = resultJsonObj['data']['forecasts']
result['forecast'] = forecastjson
elif result['ModelType'] == 'topicmodelling':
result['problem_type'] = 'TopicModelling'
topics = resultJsonObj['topics']
df_topic = []
dataDict = {}
for x in topics:
dataDict = {}
words = topics[x]
print(words)
word = ''
for key in words:
print(key)
if word != '':
word = word+', '
word = word+key+'('+str(round(words[key],2))+')'
dataDict["ID"] = x
dataDict["Words"] = word
df_topic.append(dataDict)
result['topics'] = df_topic
elif result['ModelType'].lower() == 'association rule':
result['problem_type'] = 'AssociationRules'
deploy_location = result['DeployLocation']
freq_item_file = os.path.join(result['DeployLocation'],'frequentItems.csv')
if(os.path.isfile(freq_item_file)):
rules_file = os.path.join(result['DeployLocation'],'associationRules.csv')
if(os.path.isfile(rules_file)):
df_rules = pd.read_csv(rules_file)
df_rules = df_rules[['antecedents','consequents','support','confidence','lift']]
#df_rules['antecedents'] = df_rules['antecedents']
result['rules'] = df_rules
else:
result['error'] = 'There are no association found in frequent items above that threshold (minThreshold)'
else:
result['error'] = 'There are no frequent items above that threshold (minSupport), try by reducing the minSupport value'
elif result['ModelType'] == 'clustering':
result['problem_type'] = 'Clustering'
testing_matrix = {}
if 'SilHouette_Avg' in resultJsonObj['data']['matrix']:
testing_matrix['SilHouette_Avg'] = round(float(resultJsonObj['data']['matrix']['SilHouette_Avg']),2)
else:
testing_matrix['SilHouette_Avg'] = 'NA'
if 'DaviesBouldinScore' in resultJsonObj['data']['matrix']:
testing_matrix['DaviesBouldinScore'] = round(float(resultJsonObj['data']['matrix']['DaviesBouldinScore']),2)
else:
testing_matrix['DaviesBouldinScore'] = 'NA'
if 'CalinskiHarabazScore' | ||
in resultJsonObj['data']['matrix']:
testing_matrix['CalinskiHarabazScore'] = round(float(resultJsonObj['data']['matrix']['CalinskiHarabazScore']),2)
else:
testing_matrix['CalinskiHarabazScore'] = 'NA'
centroidpath = os.path.join(result['DeployLocation'],'centers.csv')
if(os.path.isfile(centroidpath)):
df_center = pd.read_csv(centroidpath)
df_center = df_center.rename(columns={"Unnamed: 0": "Cluster"})
result['centerpoints'] = round(df_center,2)
result['testing_matrix'] = testing_matrix
training_matrix = {}
if 'SilHouette_Avg' in resultJsonObj['data']['matrix']:
training_matrix['SilHouette_Avg'] = round(float(resultJsonObj['data']['matrix']['SilHouette_Avg']),2)
training_matrix['DaviesBouldinScore'] = round(float(resultJsonObj['data']['matrix']['DaviesBouldinScore']),2)
training_matrix['CalinskiHarabazScore'] = round(float(resultJsonObj['data']['matrix']['CalinskiHarabazScore']),2)
else:
training_matrix['SilHouette_Avg'] = 'NA'
training_matrix['DaviesBouldinScore'] = 'NA'
training_matrix['CalinskiHarabazScore'] = 'NA'
result['training_matrix'] = training_matrix
#print(result)
evaluatedModelsList = resultJsonObj['data']['EvaluatedModels']
#print(evaluatedModelsList)
for index in range(len(evaluatedModelsList)):
if evaluatedModelsList[index]['Score'] == 'NA':
evaluatedModelsList[index]['Score'] = 'NA'
else:
evaluatedModelsList[index]['Score'] = round(float(evaluatedModelsList[index]['Score']), 4)
if result['ModelType'] == 'classification':
evaluatedModelsList = sorted(evaluatedModelsList, key=lambda k: k['Score'],reverse=True)
else:
evaluatedModelsList = sorted(evaluatedModelsList, key=lambda k: k['Score'])
result['EvaluatedModels'] = evaluatedModelsList
result['LogFile'] = resultJsonObj['data']['LogFile']
return result, survical_images<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import pyodbc as pyodbc
import pandas as pd
import json
def simple_select(c, sql_query, bind_params=None, display_sql=False):
"""where c is a cursor"""
if bind_params is None:
c.execute(sql_query)
else:
if display_sql:
c.execute(sql_query, bind_params)
headers = []
if c.description is not None:
# We have a SELECT statement
for x in c.description:
headers.append(x[0])
row_count = 0
row = c.fetchone()
data=[]
while row:
row_count += 1
xrow={}
for i in range(len(row)):
xrow[headers[i]] = row[i]
data.append(xrow)
row = c.fetchone()
#df = pd.DataFrame(data)
return(data)
def validatequery(request,query):
resultdata = []
try:
server_url = request.session['server_url']
username_actian = request.session['username']
password_actian = request.session['password']
database_actian = request.session['database']
conn = get_connection(server_url,username_actian,password_actian,database_actian)
sql_text = query
cur = conn.cursor()
resultdata = simple_select(cur, query)
cur.close()
if len(resultdata) > 0:
return "Query executed successfully"
else:
return "No rows returned"
except Exception as e:
print(e)
return str(e)
def executequery(request,query):
resultdata = []
try:
server_url = request.session['server_url']
username_actian = request.session['username']
password_actian = request.session['password']
database_actian = request.session['database']
conn = get_connection(server_url,username_actian,password_actian,database_actian)
sql_text = query
cur = conn.cursor()
resultdata = simple_select(cur, query)
cur.close()
return(resultdata)
except Exception as e:
print(e)
return(resultdata)
def list_tables_fields(request,table_list):
table_field_obj = {}
table_field_obj['data'] = []
try:
server_url = request.session['server_url']
username_actian = request.session['username']
password_actian = request.session['password']
database_actian = request.session['database']
table_list = json.loads(table_list)
conn = get_connection(server_url,username_actian,password_actian,database_actian)
for table in table_list:
tf_obj = {}
tf_obj['TableName'] = str(table).strip()
tf_obj['Fields']= []
field_list = []
sql_text = "SELECT column_name, false as is_select FROM iicolumns WHERE table_name='"+table+"'"
cur = conn.cursor()
field_list = simple_select(cur, sql_text)
cur.close()
print(field_list)
tf_obj['Fields'] = field_list
table_field_obj['data'].append(tf_obj)
print("----------------------")
print(table_field_obj)
print(json.dumps(table_field_obj))
print("----------------------")
return json.dumps(table_field_obj)
except Exception as e:
print("Something went wrong "+str(e))
return table_field_obj
def list_tables(request):
server_url = request.session['server_url']
username_actian = request.session['username']
password_actian = request.session['password']
database_actian = request.session['database']
dt_list = []
try:
conn = get_connection(server_url,username_actian,password_actian,database_actian)
sql_text = "select table_name from iitables where table_type='T' and table_owner='"+username_actian+"'"
cur = conn.cursor()
dt_list = simple_select(cur, sql_text)
cur.close()
return dt_list
except:
print("Something went wrong")
return dt_list
def get_connection(server_url,username_actian,password_actian,database_actian):
conn = pyodbc.connect("driver=Ingres;servertype=ingres;server=@"+str(server_url)+",tcp_ip,VW;uid="+str(username_actian)+";pwd="+str(password_actian)+";database="+str(database_actian))
print("connected")
return conn
def getDataFromActianAvalanche(request):
server_url = request.POST.get('server_url')
username_actian = request.POST.get('username')
password_actian = request.POST.get('password')
database_actian = request.POST.get('database')
table_actian = request.POST.get('table')
conn = get_connection(server_url,username_actian,password_actian,database_actian)
c = conn.cursor()
sql_text = "select * from "+str(table_actian)
data = simple_select(c, sql_text)
df = pd.DataFrame(data)
return(df)<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import pandas as pd
import numpy as np
import json
import os
def downloadtrainingfile(request,Existusecases):
usename = request.session['UseCaseName'].replace(" ", "_") + '_' + str(request.session['ModelVersion'])
updatedConfigFile = request.session['config_json']
f = open(updatedConfigFile, "r+", encoding="utf-8")
configSettingsData = f.read()
configSettingsJson = json.loads(configSettingsData)
modelName = request.session['UseCaseName']
modelVersion = request.session['ModelVersion']
modelStatus = request.session['ModelStatus']
model = Existusecases.objects.get(ModelName=request.session['ModelName'],Version=request.session['ModelVersion'])
output_train_json_filename = str(model.TrainOuputLocation)
f = open(output_train_json_filename, "r+")
training_output = f.read()
f.close()
dict = {'Attribute':[],
'Value':[]
}
training_output = json.loads(training_output)
dfdashbord = pd.DataFrame(dict)
dfdashbord.loc[len(dfdashbord.index)] = ['UseCaseName',modelName]
dfdashbord.loc[len(dfdashbord.index)] = ['ProblemType',training_output['data']['ModelType']]
dfdashbord.loc[len(dfdashbord.index)] = ['Version',str(modelVersion)]
dfdashbord.loc[len(dfdashbord.index)] = ['Status',modelStatus]
if 'vmDetails' in training_output['data']:
dfdashbord.loc[len(dfdashbord.index)] = ['DeployLocation', training_output['data']['vmDetails']]
else:
dfdashbord.loc[len(dfdashbord.index)] = ['DeployLocation',training_output['data']['deployLocation']]
dfdashbord.loc[len(dfdashbord.index)] = ['BestModel',training_output['data']['BestModel']]
dfdashbord.loc[len(dfdashbord.index)] = ['BestScore',training_output['data']['BestScore']]
dfdashbord.loc[len(dfdashbord.index)] = ['ScoringParam',training_output['data']['ScoreType']]
if training_output['data']['ModelType'] != 'LLM Fine-Tuning':
dfdashbord.loc[len(dfdashbord.index)] = ['Test%',configSettingsJson['advance']['testPercentage']]
dfdashbord.loc[len(dfdashbord.index)] = ['FeaturesUsed',training_output['data']['featuresused']]
from io import BytesIO as IO
excel_file = IO()
edaFileName = usename + '_training.xlsx'
excel_writer = pd.ExcelWriter(excel_file, engine="xlsxwriter")
dfdashbord.to_excel(excel_writer, sheet_name='Dashboard',index=False)
if training_output['data']['ModelType'].lower() != 'multimodellearning' and training_output['data']['ModelType'].lower() != 'multilabelprediction':
EvaluatedModels = training_output['data']['EvaluatedModels']
EvaluatedModels = pd.DataFrame(EvaluatedModels)
EvaluatedModels.to_excel(excel_writer, sheet_name='EvaluatedModels',startrow=0 , startcol=0)
if training_output['data']['ModelType'].lower() == 'classification':
#print(training_output['data']['matrix'])
row1 = 10
row2 = 10
if 'ConfusionMatrix' in training_output['data']['matrix']:
confusionMatrix = training_output['data']['matrix']['ConfusionMatrix']
confusionMatrix = pd.DataFrame(confusionMatrix)
confusionMatrix.to_excel(excel_writer, sheet_name='Testing Matrix',startrow=0 , startcol=0)
row1 =confusionMatrix.shape[0]+5
if 'ConfusionMatrix' in training_output['data']['trainmatrix']:
confusionMatrix = training_output['data']['trainmatrix']['ConfusionMatrix']
confusionMatrix = pd.DataFrame(confusionMatrix)
confusionMatrix.to_excel(excel_writer, sheet_name='Training Matrix',startrow=0 , startcol=0)
if 'ClassificationReport' in training_output['data']['matrix']:
confusionMatrix = training_output['data']['matrix']['ClassificationReport']
confusionMatrix = pd.DataFrame(confusionMatrix)
confusionMatrix.to_excel(excel_writer, sheet_name='Testing Matrix',startrow=row1 , startcol=0)
if 'ClassificationReport' in training_output['data']['trainmatrix']:
confusionMatrix = training_output['data']['trainmatrix']['ClassificationReport']
confusionMatrix = pd.DataFrame(confusionMatrix)
confusionMatrix.to_excel(excel_writer, sheet_name='Training Matrix',startrow=row2 , startcol=0)
if training_output['data']['ModelType'].lower() == 'regression':
dict = {'Attribute':[],'Value':[]}
testingDF = pd.DataFrame(dict)
try:
testingDF.loc[len(testingDF.index)] = ['MAE',training_output['data']['matrix']['MAE']]
testingDF.loc[len(testingDF.index)] = ['R2Score',training_output['data']['matrix']['R2Score']]
testingDF.loc[len(testingDF.index)] = ['MSE',training_output['data']['matrix']['MSE']]
testingDF.loc[len(testingDF.index)] = ['MAPE',training_output['data']['matrix']['MAPE']]
testingDF.loc[len(testingDF.index)] = ['RMSE',training_output['data']['matrix']['RMSE']]
except:
pass
testingDF.to_excel(excel_writer, sheet_name='Testing Matrix',startrow=0 , startcol=0)
trainingDF = pd.DataFrame(dict)
try:
trainingDF.loc[len(trainingDF.index)] = ['MAE',training_output['data']['trainmatrix']['MAE']]
trainingDF.loc[len(trainingDF.index)] = ['R2Score',training_output['data']['trainmatrix']['R2Score']]
trainingDF.loc[len(trainingDF.index)] = ['MSE',training_output['data']['trainmatrix']['MSE']]
trainingDF.loc[len(trainingDF.index)] = ['MAPE',training_output['data']['trainmatrix']['MAPE']]
trainingDF.loc[len(trainingDF.index)] = ['RMSE',training_output['data']['trainmatrix']['RMSE']]
except:
pass
trainingDF.to_excel(excel_writer, sheet_name='Training Matrix',startrow=0 , startcol=0)
if training_output['data']['ModelType'].lower() == 'clustering':
dict = {'Attribute':[],'Value':[]}
trainingDF = pd.DataFrame(dict)
try:
trainingDF.loc[len(trainingDF.index)] = ['SilHouette_ | ||
Avg',round(training_output['data']['trainmatrix']['SilHouette_Avg'],2)]
trainingDF.loc[len(trainingDF.index)] = ['DaviesBouldinScore',round(training_output['data']['trainmatrix']['DaviesBouldinScore'],2)]
trainingDF.loc[len(trainingDF.index)] = ['CalinskiHarabazScore',round(training_output['data']['trainmatrix']['CalinskiHarabazScore'],2)]
except:
pass
trainingDF.to_excel(excel_writer, sheet_name='Training Matrix',startrow=0 , startcol=0)
centroidpath = os.path.join(training_output['data']['deployLocation'],'centers.csv')
if(os.path.isfile(centroidpath)):
df_center = pd.read_csv(centroidpath)
df_center = df_center.rename(columns={"Unnamed: 0": "Cluster"})
df_center.to_excel(excel_writer, sheet_name='Centroid',startrow=0 , startcol=0)
if training_output['data']['ModelType'].lower() == 'timeseriesforecasting': #task 11997
if training_output['data']['BestModel'].lower() == 'var':
dict = {'Features':[],'Attribute':[],'Value':[]}
trainingDF = pd.DataFrame(dict)
FeaturesMatrix = training_output['data']['matrix']
for x in FeaturesMatrix:
try:
trainingDF.loc[len(trainingDF.index)] = [x['Features'],'MAE',x['MAE']]
trainingDF.loc[len(trainingDF.index)] = [x['Features'],'MSE',x['MSE']]
trainingDF.loc[len(trainingDF.index)] = [x['Features'],'MAPE',x['MAPE']]
trainingDF.loc[len(trainingDF.index)] = [x['Features'],'RMSE',x['RMSE']]
except:
pass
trainingDF.to_excel(excel_writer, sheet_name='Testing Matrix',startrow=0 , startcol=0)
else:
dict = {'Attribute':[],'Value':[]}
trainingDF = pd.DataFrame(dict)
try:
trainingDF.loc[len(trainingDF.index)] = ['MAE',training_output['data']['matrix']['MAE']]
trainingDF.loc[len(trainingDF.index)] = ['MSE',training_output['data']['matrix']['MSE']]
trainingDF.loc[len(trainingDF.index)] = ['MAPE',training_output['data']['matrix']['MAPE']]
trainingDF.loc[len(trainingDF.index)] = ['RMSE',training_output['data']['matrix']['RMSE']]
except:
pass
trainingDF.to_excel(excel_writer, sheet_name='Testing Matrix',startrow=0 , startcol=0)
workbook = excel_writer.book
#excel_writer.save()
excel_writer.close()
excel_file.seek(0)
return edaFileName,excel_file
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os.path
from pathlib import Path
import time
import subprocess
import sys
import shutil
from appbe.aion_config import kafka_setting
from appbe.aion_config import running_setting
from appbe.publish import chech_publish_info
from llm.llm_tuning import update_sqllite_data
from appbe.data_io import sqlite_db
from appbe.dataPath import DATA_DIR
from appbe import installPackage
from appbe import compute
import json
import os
import signal
from os.path import expanduser
import platform
import pandas as pd
LOG_FILE_PATH = os.path.join(DATA_DIR,'logs')
GITHUB_FILE_PATH = os.path.join(DATA_DIR,'github')
PUBLISH_PATH = os.path.join(DATA_DIR,'target')
DEPLOY_DATABASE_PATH = os.path.join(DATA_DIR,'sqlite')
os.makedirs(LOG_FILE_PATH, exist_ok=True)
'''
def check_publish_info(usecase,version):
sqlite_dbObj = sqlite_db(DEPLOY_DATABASE_PATH,'deploy.db')
if sqlite_dbObj.table_exists('publish'):
publishState= 'Published'
'''
def get_instance(modelID):
from appbe.sqliteUtility import sqlite_db
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
if sqlite_obj.table_exists("LLMTuning"):
data = sqlite_obj.get_data('LLMTuning','usecaseid',modelID)
if len(data) > 0:
return (data[3],data[2],data[5],data[6],data[4])
else:
return '','','','',''
else:
return '','','','',''
def startServices(request,usecasedetails,Existusecases):
try:
models = Existusecases.objects.filter(publishStatus='Published')
print(models)
if len(models) > 0:
for model in models:
try:
portNo = model.portNo
ppid = model.publishPID
if ppid == 0:
continue
try:
os.kill(int(model.publishPID), signal.SIGTERM)
except Exception as e:
print(e)
scriptPath = os.path.join(PUBLISH_PATH,model.ModelName.usecaseid,'aion_publish_service.py')
if os.path.exists(scriptPath):
outputStr = subprocess.Popen([sys.executable, scriptPath,'-ip','0.0.0.0','-p',str(portNo)])
model.publishStatus = 'Published'
model.publishPID = outputStr.pid
model.portNo = portNo
model.save()
else:
print("Pass")
pass
except Exception as e:
print(e)
except Exception as e:
print(e)
def publishmodel(request,usecaseid,version,Existusecases,usecasedetails):
portNo=0
usecased = usecasedetails.objects.get(usecaseid=usecaseid)
models = Existusecases.objects.filter(ModelName=usecased,publishStatus='Published')
if len(models) > 0:
for model in models:
try:
portNo = model.portNo
try:
os.kill(int(model.publishPID), signal.SIGTERM)
except Exception as e:
print(e)
mod = Existusecases.objects.get(id=model.id)
mod.publishStatus = ''
mod.publishPID = 0
mod.portNo = 0
mod.save()
except Exception as e:
print(e)
pass
missingNumbers = []
if portNo == 0:
models = Existusecases.objects.filter(publishStatus='Published')
usedPortNo=[]
for model in models:
usedPortNo.append(model.portNo)
startPortNo = 8091
endPortNo = 8091+5
missingNumbers = [ i for i in range(startPortNo,endPortNo) if i not in usedPortNo]
if len(missingNumbers) > 0:
portNo = missingNumbers[0]
if portNo != 0:
scriptPath = os.path.join(PUBLISH_PATH,usecaseid,'aion_publish_service.py')
model = Existusecases.objects.get(ModelName=usecased,Version=version)
isExist = os.path.exists(scriptPath)
if isExist:
configfile = os.path.join(PUBLISH_PATH,usecaseid,'config.json')
configdata = {'version': str(version)}
with open(configfile, "w") as outfile:
json.dump(configdata, outfile)
outfile.close()
outputStr = subprocess.Popen([sys.executable, scriptPath,'-ip','0.0.0.0','-p',str(portNo)])
model.publishStatus = 'Published'
model.publishPID = outputStr.pid
model.portNo = portNo
model.save()
Status = 'SUCCESS'
hosturl =request.get_host()
hosturl = hosturl.split(':')
url = 'http://'+hosturl[0]+':'+str(portNo)+'/AION/'+str(usecaseid)+'/predict'
Msg = 'Model Published Successfully'
else:
Status = 'Error'
Msg = 'Model Published Error'
url = ''
else:
Status = 'Error'
Msg = 'All ports are utilized'
url=''
return Status,Msg,url
def get_published_models(instanceid):
from appbe.sqliteUtility import sqlite_db
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
if sqlite_obj.table_exists("LLMTuning"):
condition = f'"instance"=="{instanceid}" AND "status"=="Published"'
datas = sqlite_obj.read_data('LLMTuning',condition)
if len(datas)>0:
return True,datas[0][0]
return False,''
def maac_command(request,Existusecases,usecasedetails):
command = request.POST.get('maacsubmit')
kafkaSetting = kafka_setting()
ruuningSetting = running_setting()
computeinfrastructure = compute.readComputeConfig()
modelID = request.POST.get('modelID')
Version = request.POST.get('Version')
p = Existusecases.objects.get(id=modelID,Version=Version)
usecasename = p.ModelName.usecaseid #bugid 13339
usecaseid = p.ModelName.id
# runningStatus,pid,ip,port = installPackage.checkModelServiceRunning(usecasename)
# installationStatus,modelName,modelVersion=installPackage.checkInstalledPackge(usecasename)
usecasedetail = usecasedetails.objects.get(id=p.ModelName.id)
usecase = usecasedetails.objects.all()
problemType = p.ProblemType
score = 0
scoreType = ''
deployedModel = ''
deployedModelVersion = p.Version
models = Existusecases.objects.filter(ModelName=usecasedetail,Status='SUCCESS')
computeinfrastructure = compute.readComputeConfig()
for model in models:
model.scoringCreteria = 'NA'
model.score = 'NA'
model.deploymodel = 'NA'
if os.path.isdir(str(model.DeployPath)):
modelPath = os.path.join(str(model.DeployPath),'etc','output.json')
try:
with open(modelPath) as file:
outputconfig = json.load(file)
file.close()
if outputconfig['status'] == 'SUCCESS':
if deployedModelVersion == model.Version:
problemType = outputconfig['data']['ModelType']
scoreType = outputconfig['data']['ScoreType']
score = outputconfig['data']['BestScore']
deployedModel = outputconfig['data']['BestModel']
model.scoringCreteria = outputconfig['data']['ScoreType']
model.score = outputconfig['data']['BestScore']
model.deploymodel = outputconfig['data']['BestModel']
model.maacsupport = 'True'
model.flserversupport = 'False'
supportedmodels = ["Logistic Regression","Neural Network","Linear Regression"]
if model.deploymodel in supportedmodels:
model.flserversupport = 'True'
else:
model.flserversupport = 'False'
supportedmodels = ["Extreme Gradient Boosting (XGBoost)"]
if model.deploymodel in supportedmodels:
model.encryptionsupport = 'True'
else:
model.encryptionsupport = 'False'
except Exception as e:
print(e)
pass
MLaaC_output = ''
if command == 'generatemaac':
deployPath = str(p.DeployPath)
codeconfig = os.path.join(deployPath,'etc','code_config.json')
if os.path.isfile(codeconfig):
with open(codeconfig,'r') as f:
cconfig = json.load(f)
f.close()
dbserver = request.POST.get('productiondb')
db_config = {}
if dbserver.lower() == 'influxdb':
cconfig['prod_db_type'] = 'influx'
db_config['host'] = request.POST.get('influxdbhost')
db_config['port'] = request.POST.get('influxdbportno')
db_config['user'] = request.POST.get('influxdbuser')
db_config['password'] = request.POST.get('influxpassword')
db_config['database'] = 'production'
db_config['measurement'] = usecasename
tags = {}
db_config['tags']=tags
cconfig['db_config'] = db_config
else:
cconfig['prod_db_type'] = 'sqlite'
cconfig['db_config'] = db_config
dbserver = request.POST.get('mlflowserver')
mlflow_config = {}
if dbserver.lower() == 'local':
cconfig['mlflow_config'] = mlflow_config
else:
mlflow_config['tracking_uri_type'] = request.POST.get('mlflowserverurl')
mlflow_config['tracking_uri'] = request.POST.get('mlflowserverurl')
mlflow_config['registry_uri'] = request.POST.get('mlflowserverurl')
mlflow_config['artifacts_uri'] = request.POST.get('mlflowserverurl')
cconfig['mlflow_config'] = mlflow_config
with open(codeconfig,'w') as f:
json.dump(cconfig, f)
f.close()
from bin.aion_mlac import generate_mlac_code
outputStr = generate_mlac_code(codeconfig)
output = json.loads(outputStr)
from appbe.telemetry import UpdateTelemetry
UpdateTelemetry(request.session['usecaseid']+'-'+str(request.session['ModelVersion']),'MLaC','Yes')
if output['Status'] == 'SUCCESS':
Status = 'SUCCESS'
MLaaC_output = output['MLaC_Location'].replace('\\\\', '\\\\\\\\')
Msg = 'MLaC code successfully generated'
else:
Status = ' | ||
Failure'
Msg = output['msg']
else:
Status = 'Failure'
Msg = 'Code Config Not Present'
if command == 'buildContainer':
deployPath = str(p.DeployPath)
maac_path = os.path.join(deployPath,'publish','MLaC')
if os.path.isdir(maac_path):
config={'usecase':str(usecasename),'version':str(p.Version),'mlacPath':maac_path}
config = json.dumps(config)
scriptPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','aion.py'))
if platform.system() == 'Windows':
outputStr = subprocess.Popen([sys.executable, scriptPath,'-m','buildMLaCContainerLocal' ,'-j',config],creationflags = subprocess.CREATE_NEW_CONSOLE)
else:
outputStr = subprocess.Popen([sys.executable, scriptPath,'-m','buildMLaCContainerLocal' ,'-j',config])
#cmd = scriptPath+" "+str(usecasename)+" "+str(p.Version)+" "+str(maac_path)
#subprocess.Popen(cmd,shell=True)
Status = 'SUCCESS'
Msg = 'Build Container Started'
else:
Status = 'Failure'
Msg = 'Run Code Generator'
if command == 'runpipeline':
deployPath = str(p.DeployPath)
dockerlist = os.path.join(deployPath,'publish','MLaC','dockerlist.json')
if os.path.isfile(dockerlist):
persistancevolume = request.POST.get('persistancevolume')
datasetpath = request.POST.get('dataset')
filetimestamp = str(int(time.time()))
logfilepath = os.path.join(LOG_FILE_PATH,'AIONPipeline_'+str(filetimestamp)+'.log')
config={'usecase':str(usecasename),'version':str(p.Version),'persistancevolume':persistancevolume,'datasetpath':datasetpath,'dockerlist':str(dockerlist),'logfilepath':logfilepath}
config = json.dumps(config)
scriptPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','aion.py'))
if platform.system() == 'Windows':
outputStr = subprocess.Popen([sys.executable, scriptPath,'-m','runpipelinelocal','-j',config],creationflags = subprocess.CREATE_NEW_CONSOLE)
else:
outputStr = subprocess.Popen([sys.executable, scriptPath, str(usecasename),str(p.Version),persistancevolume,datasetpath,str(dockerlist),logfilepath])
Status = 'SUCCESS'
Msg = 'Pipeline Started'
MLaaC_output = 'Check log file for pipeline execution status: ' + str(logfilepath)
else:
Status = 'Failure'
Msg = 'Not found container information'
if command == 'generateyaml':
deployPath = str(p.DeployPath)
maac_path = os.path.join(deployPath,'publish','MLaC')
if os.path.isdir(maac_path):
persistancevolume = request.POST.get('persistancevolume')
datasetpath = request.POST.get('dataset')
supported_urls_starts_with = ('gs://','https://','http://')
if datasetpath.startswith(supported_urls_starts_with):
datasetpath = request.POST.get('dataset')
else:
datasetpath = '/aion/'+request.POST.get('dataset')
serviceport = request.POST.get('serviceport')
scriptPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..','bin','run_generateyaml.py'))
outputStr = subprocess.check_output([sys.executable, scriptPath, str(usecasename),str(p.Version),persistancevolume,datasetpath,maac_path,serviceport])
outputStr = outputStr.decode('utf-8')
outputStr=outputStr.strip()
print(outputStr)
output = json.loads(outputStr)
if output['Status'] == 'SUCCESS':
Status = 'SUCCESS'
MLaaC_output = output['location']
Msg = 'MLaaC dockerfile successfully generated'
else:
Status = 'Failure'
Msg = output['msg']
else:
Status = 'Failure'
Msg = 'Execute generate code first'
if command == 'githubupload':
if shutil.which('git') is None:
Status = 'Failure'
Msg = 'Git is not installed, Please install Git first.'
else:
try:
deployPath = str(p.DeployPath)
maac_path = os.path.join(deployPath,'publish','MLaC')
if os.path.isdir(maac_path):
githuburl = request.POST.get('githuburl')
githubusername = request.POST.get('githubusername')
githubtoken = request.POST.get('githubtoken')
githubemail = request.POST.get('githubemail')
githubconfig = {"url_type":"https","url":githuburl,"username":githubusername,"email":githubemail,"token":githubtoken,"location":maac_path,"modelName":usecasename,"gitFolderLocation":GITHUB_FILE_PATH}
from mlops import git_upload
outputStr = git_upload.upload(githubconfig)
print(outputStr)
output = json.loads(outputStr)
if output['Status'] == 'SUCCESS':
Status = 'SUCCESS'
MLaaC_output = githuburl
Msg = 'Code Uploaded to GitHub Successfully'
else:
Status = 'Failure'
Msg = output['msg']
else:
Status = 'Failure'
Msg = 'GitHub Upload failed'
except Exception as e:
print(e)
Status = 'Failure'
Msg = 'GitHub Upload failed'
if command == 'unpublishmodel':
try:
models = Existusecases.objects.filter(ModelName=usecasedetail,publishStatus='Published')
if len(models) > 0:
for model in models:
try:
if problemType.lower() == "llm fine-tuning":
cloudconfig = os.path.normpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'config', 'compute_conf.json'))
modelid = usecasename + '_' + str(Version)
usecasename = usecasename.replace(" ", "_")
hypervisor,instanceid,region,image,status = get_instance(usecasename + '_' + str(Version))
from llm.llm_inference import kill_inference_server
kill_inference_server(cloudconfig,instanceid,hypervisor,region,image)
update_sqllite_data(modelid,'status','Success')
else:
try:
os.kill(int(model.publishPID), signal.SIGTERM)
mod.publishPID = 0
except Exception as e:
print(e)
mod = Existusecases.objects.get(id=model.id)
mod.publishStatus = ''
mod.portNo = 0
mod.save()
Status = 'SUCCESS'
Msg = 'Model Unpublished Successfully'
except Exception as e:
print(e)
Status = 'Error'
Msg = 'Model Unpublished Error'
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
print(e)
pass
if command == 'publishmodel':
try:
portNo=0
models = Existusecases.objects.filter(ModelName=usecasedetail,publishStatus='Published')
if len(models) > 0:
for model in models:
try:
portNo = model.portNo
try:
os.kill(int(model.publishPID), signal.SIGTERM)
except Exception as e:
print(e)
mod = Existusecases.objects.get(id=model.id)
mod.publishStatus = ''
mod.publishPID = 0
mod.portNo = 0
mod.save()
except Exception as e:
print(e)
pass
missingNumbers = []
if problemType.lower() == "llm fine-tuning":
model = Existusecases.objects.get(ModelName=usecasedetail,Version=Version)
try:
usecasename = usecasename.replace(" ", "_")
hypervisor,instanceid,region,image,status = get_instance(usecasename + '_' + str(Version))
if status.lower() in ['published','success'] :
if status.lower() == 'published':
from llm.llm_inference import kill_inference_server
kill_inference_server('',instanceid, hypervisor, region, image)
update_sqllite_data(usecasename + '_' + str(Version), 'status', 'Success')
already_published,published_usecase = get_published_models(instanceid)
if already_published:
Status = 'Error'
Msg = f'{published_usecase} is published at the same id, Please Unpublish mentioned model to proceed.'
else:
if not region:
region = ''
cloudconfig = os.path.normpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'config', 'compute_conf.json'))
usecase = usecasename + '_' + str(Version)
#modelid = usecasename + '_' + str(Version)
scriptPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'aion.py'))
cmd = [sys.executable, scriptPath, '-m', 'llmpublish', '-cc', cloudconfig, '-i',instanceid,'-hv',hypervisor,'-md',deployedModel,'-uc',usecase,'-r',region,'-im',image ]
outputStr = subprocess.Popen(cmd)
model.publishStatus = 'Published'
model.publishPID = 0
model.portNo = 8000
model.save()
Status = 'SUCCESS'
from llm.llm_inference import get_ip
instanceip = get_ip(cloudconfig,instanceid,hypervisor,region,image)
print(instanceip)
url = 'http://' + instanceip + ':' + str(model.portNo) + '/generate'
Msg = 'Model Published Successfully, Server will take few minutes to be ready for Inferencing. URL: ' + url
update_sqllite_data(usecase,'status','Published')
else:
Status = 'Error'
Msg = 'Only Trained models are availble for Publish.'
except Exception as e:
print(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
Status = 'Error'
Msg = 'Model Published Error'
else:
if portNo == 0:
models = Existusecases.objects.filter(publishStatus='Published')
usedPortNo=[]
for model in models:
usedPortNo.append(model.portNo)
startPortNo = 8091
endPortNo = 8091+5
missingNumbers = [ i for i in range(startPortNo,endPortNo) if i not in usedPortNo]
if len(missingNumbers) > 0:
portNo = missingNumbers[0]
if portNo != 0:
model = Existusecases.objects.get(ModelName=usecasedetail,Version=Version)
scriptPath = os.path.join(PUBLISH_PATH,usecasename,'aion_publish_service.py')
isExist = os.path.exists(scriptPath)
if isExist:
configfile = os.path.join(PUBLISH_PATH,usecasename,'config.json')
configdata = {'version': str(Version)}
with open(configfile, "w") as outfile:
json.dump(configdata, outfile)
outfile.close()
outputStr = subprocess.Popen([sys.executable, scriptPath,'-ip','0.0.0.0','-p',str(portNo)])
model.publishStatus = 'Published'
model.publishPID = outputStr.pid
model.portNo = portNo
model.save()
Status = 'SUCCESS'
hosturl =request.get_host()
hosturl = hosturl.split(':')
url = 'http://'+hosturl[0]+':'+str(portNo)+'/AION/'+str(usecasename)+'/predict'
Msg = 'Model Published Successfully URL: '+url
else:
Status = 'Error'
Msg = 'Model Published Error'
else:
Status = 'Error'
Msg = 'All ports are utilized'
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
print(e)
pass
if command == 'generatekubeflowyaml':
try:
if problemType.lower() == 'timeseriesforecasting': #task 11997
from appbe.aionpipelinets import aionpipelinets
else:
from appbe.aionpipeline import aionpipeline
deployPath = str(p.DeployPath)
codeconfig = os.path.join(deployPath,'etc','code_config.json')
featuresmapping = {'modelBased':'mlbased','statisticalBased':'statisticalBased'}
if os.path.isfile(codeconfig):
with open(codeconfig,'r') as f:
codeconfig = json.load(f)
f.close()
modelsarray=[]
for featureselection in codeconfig['feature_selector']:
for algo in codeconfig['algorithms'].keys():
if problemType.lower() == 'timeseriesforecasting': #task 11997
modelname = 'modeltraining_'+algo.lower()
else:
modelname = | ||
'modeltraining_'+algo.lower()+'_'+featuresmapping[featureselection]
modelx = {'modelname':modelname}
modelsarray.append(modelx)
modelsjson = {'models':modelsarray}
kubeflowhost= request.POST.get('kubeflowhost')
containerregistry= request.POST.get('containerregistry')
containerlabel= request.POST.get('containerlabel')
containersecret= request.POST.get('containersecret')
if problemType.lower() == 'timeseriesforecasting': #task 11997
ap = aionpipelinets(modelsjson,containerregistry,containerlabel,containersecret)
else:
ap = aionpipeline(modelsjson,containerregistry,containerlabel,containersecret)
ap.aion_mlops()
ap.compilepl()
ap.executepl(kubeflowhost)
Status = 'SUCCESS'
MLaaC_output = ''
Msg = 'MLOps pipeline executed successfully'
except Exception as e:
print(e)
Status = 'Failure'
Msg = 'Error in pipeline execution'
from appbe.pages import get_usecase_page
if command in ['publishmodel','unpublishmodel']:
status,context,action = get_usecase_page(request,usecasedetails,Existusecases,usecaseid)
context['Status'] = Status
context['MLaaC_output'] = MLaaC_output
context['Msg'] = Msg
return(context,'usecasedetails.html')
else:
status,context,action = get_usecase_page(request,usecasedetails,Existusecases)
context['Status'] = Status
context['MLaaC_output'] = MLaaC_output
context['Msg'] = Msg
return(context,'usecases.html')
def getusercasestatus(request):
if 'UseCaseName' in request.session:
selected_use_case = request.session['UseCaseName']
else:
selected_use_case = 'Not Defined'
if 'ModelVersion' in request.session:
ModelVersion = request.session['ModelVersion']
else:
ModelVersion = 0
if 'ModelStatus' in request.session:
ModelStatus = request.session['ModelStatus']
else:
ModelStatus = 'Not Trained'
return selected_use_case,ModelVersion,ModelStatus<s> # -*- coding: utf-8 -*-
import os
import glob, os
import pandas as pd
from openai.embeddings_utils import cosine_similarity
import numpy as np
from openai.embeddings_utils import get_embedding
import tiktoken
import openai
import importlib.util
from sklearn.preprocessing import StandardScaler
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn import metrics
import time
from tqdm import tqdm
import concurrent.futures
from openai.error import RateLimitError, Timeout
try:
import chromadb
from chromadb.api.types import Documents, Embeddings
except:
#Looks no chromadb installed,just proceed to use csv embedd
pass
from openai.embeddings_utils import get_embedding
import json
from openai.embeddings_utils import cosine_similarity
from langchain.schema import Document
from langchain.vectorstores import Chroma
import warnings
import logging
warnings.simplefilter(action='ignore', category=FutureWarning)
"""Code clone detection parent class, based on user input data,the class will detect similar code snippets in the python file """
class CodeCloneDetection:
#Constructor for base inputs
def __init__(self,rootdir,openai_baseurl, openai_key,openai_api_type,openai_api_version,embedd_storage_path,generativeai_embedding_engine,generativeai_embedding_model,generativeai_chat_model,generativeai_deploymentId):
self.rootdir=rootdir
self.embedd_storage_path=embedd_storage_path
self.openai_baseurl=openai_baseurl
self.openai_key=openai_key
self.openai_api_type=openai_api_type
self.openai_api_version=openai_api_version
self.ccdreportpath = os.path.join(self.embedd_storage_path, "codeCloneReport")
self.generativeai_chat_model=generativeai_chat_model
self.generativeai_embedding_engine = generativeai_embedding_engine
self.generativeai_embedding_model = generativeai_embedding_model
self.generativeai_deploymentId = generativeai_deploymentId
try:
os.makedirs(self.ccdreportpath, exist_ok = True)
except OSError as error:
print("Directory 'codeclonedetection' can not be created",self.ccdreportpath)
try:
self.logpath = os.path.join(self.ccdreportpath,'codeclonelog.log')
logging.basicConfig(level=logging.INFO,filename=self.logpath,filemode='w',format='%(message)s')
self.log = logging.getLogger()
except Exception as e:
print("code clone log object creation error.",e)
def get_function_name(self,code):
"""
Extract function name from a line beginning with "def "
"""
assert code.startswith("def ")
return code[len("def "): code.index("(")]
def get_until_no_space(self,all_lines, i) -> str:
"""
Get all lines until a line outside the function definition is found.
"""
ret = [all_lines[i]]
for j in range(i + 1, i + 10000):
if j < len(all_lines):
if len(all_lines[j]) == 0 or all_lines[j][0] in [" ", "\\t", ")"]:
ret.append(all_lines[j])
else:
break
return "\\n".join(ret)
def chunk_functions(self,function_code, chunk_size):
""" To chunk input for gpt models because max token per model is 4090 """
try:
# chunk_size = 1900
chunks = [function_code[i:i + chunk_size] for i in range(0, len(function_code), chunk_size)]
except Exception as e:
self.log.info('Error in chunking input prompt data.')
return chunks
def get_functions(self,filepath):
"""
Get all functions in a Python file.
"""
try:
whole_code = open(filepath).read().replace("\\r", "\\n")
all_lines = whole_code.split("\\n")
for i, l in enumerate(all_lines):
if l.startswith("def "):
code = self.get_until_no_space(all_lines, i)
function_name = self.get_function_name(code)
yield {"code": code, "function_name": function_name, "filepath": filepath}
except Exception as e:
self.log.info("Error in getting function from file. Error message: \\n"+str(e))
def get_clone_function_details(self):
""" To get available functions from python files """
try:
code_root=self.rootdir
from glob import glob
code_files = [y for x in os.walk(code_root) for y in glob(os.path.join(x[0], '*.py'))]
if code_files:
all_funcs = []
total_locs = 0
for code_file in code_files:
with open(code_file) as f:
total_locs += len(f.readlines())
funcs = list(self.get_functions(code_file))
for func in funcs:
all_funcs.append(func)
return all_funcs,code_root,code_files,total_locs
else:
self.log.info("no python files available in the dir:"+str(code_root))
return {"pythondiles_error":"No python files are found."}
except Exception as e:
print("Error in reading the functions from the given directory. Error message: \\n",e)
self.log.info("Error in reading the functions from the given directory. Error message: \\n"+str(e))
def getOpenAICredentials(self):
""" To set openai credential using user input """
#Currently only support openai
try:
package_name = 'openai'
lib_name = importlib.util.find_spec(package_name)
if lib_name is None:
return "openai_pkg_check_failed"
else:
embedding_model_lib ='openai'
#
if isinstance(self.openai_baseurl,str) and isinstance(self.openai_key,str) and isinstance(self.openai_api_type,str):
os.environ['OPENAI_API_TYPE'] = self.openai_api_type
os.environ['OPENAI_API_BASE'] = self.openai_baseurl
# os.environ['OPENAI_API_VERSION'] = '2023-05-15'
# os.environ['OPENAI_API_VERSION'] = "2022-12-01"
os.environ['OPENAI_API_VERSION'] = self.openai_api_version
os.environ['OPENAI_API_KEY'] = self.openai_key
if (embedding_model_lib.lower()=='openai'):
try:
openai.api_type=os.getenv('OPENAI_API_TYPE')
openai.api_base = os.getenv('OPENAI_API_BASE')
openai.api_key = os.getenv('OPENAI_API_KEY')
openai.api_version = os.getenv('OPENAI_API_VERSION')
except Exception as e:
self.log.info("Unable to get openai credentials,please provide proper credentials."+str(e))
return {"error_msg":"openai_environment_error"}
except Exception as e:
print("Openai credential set and get function error. Error message: \\n",e)
return openai.api_type,openai.api_base,openai.api_key,openai.api_version
def get_embedding_local(self,model: str, text: str) -> list[float]:
""" To get embedding data for single user given prompt text"""
try:
response = openai.Embedding.create(
input=text,
engine=self.generativeai_embedding_engine)
except Exception as e:
self.log.info("openai embedding creation error."+str(e))
return result['data'][0]['embedding']
def get_embeddings_pyfiles(self,all_funcs):
""" To get embedding for python functions """
try:
import tiktoken
openai_api_type,openai_api_base,openai_api_key,openai_api_version = self.getOpenAICredentials()
encoding = tiktoken.encoding_for_model("text-embedding-ada-002")
df = pd.DataFrame(all_funcs)
df["tokens"] = df["code"].apply(lambda c: len(encoding.encode(c)))
embedding_cost = df["tokens"].sum() * (0.0004/1000)
EMBEDDING_FILEPATH=self.ccdreportpath+'\\code_embeddings.csv'
self.log.info("embedding storage location: "+str(EMBEDDING_FILEPATH))
vdb_status = self.get_vdb_status('chromadb')
##Currently chromadb not integrated
vdb_status = False
if not vdb_status:
df['code_embedding'] = df['code'].apply(lambda x: get_embedding(x, engine=self.generativeai_embedding_engine))
df['filepath'] = df['filepath'].apply(lambda x: x.replace(self.rootdir, ""))
df.to_csv(EMBEDDING_FILEPATH, index=False)
else:
df = self.chromadb_embedding(df)
""" Please uncomment below, currently assumption is each run we create embedd based on python files dir """
import numpy as np
df = pd.read_csv(EMBEDDING_FILEPATH)
df["code_embedding"] = df["code_embedding"].apply(eval).apply(np.array)
except Exception as e:
self.log.info("Error in get_embeddings_pyfiles for embedding conversion process. Error Message: "+str(e))
raise Exception("Error in get_embeddings_pyfiles for embedding conversion process.")
return df,embedding_cost
def search_functions_vectordb(df,db, code_query, n=3, pprint=True, n_lines=7):
""" Search function for user query (prompt content), used for vector database embedding query option. """
try:
docs = db.similarity_search_with_score(code_query )[:n]
docs = [{"similarities":score, "code": d.page_content, **d.metadata} for d,score in docs]
res = pd.DataFrame(docs).drop("_additional", axis=1)
##Uncomment for debug
# if pprint:
# for r in res.iterrows():
# print(r[1].filepath+" : "+r[1].function_name + " score=" + str(round(r[1].similarities, 3)))
# print("\\n".join(r[1].code.split("\\n")[:n_lines]))
# print('-'*70)
except Exception as e:
self.log.info("Error in search_functions_vectordb to get similarity information based on user query. Error Message: "+str(e))
raise Exception("Error in search_functions_csv to get similarity information based on user query.")
return res
def search_functions_csv(self,df, code_query, n=3, pprint=True, n_lines=7):
""" Search function for user query (prompt content), used for csv embedding query option. """
try:
embedding = get_embedding(code_query, engine=self.generativeai_embedding_engine)
df['similarities'] = df.code_embedding.apply(lambda x: cosine_similarity(x, embedding))
res = df.sort_values('similarities', ascending=False)
## uncomment for debug purpose
# if pprint:
# for r in res.iterrows():
# print(r[1].filepath+" : "+r[1].function_name + " score=" + str(round(r[1].similarities, 3)))
# print("\\n".join(r[1].code.split("\\n")[:n_lines]))
# print('-'*70)
except Exception as e:
self.log.info("Error in search_functions_functions_csv to get similarity information based on user query. Error Message: "+str(e))
raise Exception("Error in search_functions_csv to get similarity information based on user query.")
return res
def get_prediction(self,prompt_data):
""" To get prediction for given user data """
try:
all_funcs,code_root, | ||
code_files,total_locs=self.get_clone_function_details()
if not isinstance(all_funcs,type(None)):
df,embedding_cost=self.get_embeddings_pyfiles(all_funcs)
res = self.search_functions_csv(df, prompt_data, n=3)
return res
else:
return dict({"error":"Empty_root_directory"})
except Exception as e:
self.log.info("Error in get prediction for user prompt information. Error Message: "+str(e))
raise Exception("Error in get prediction for user prompt information. .")
def get_vdb_status(self,vdb_name):
""" To check chromadb python package installed or not"""
try:
vdb_name = 'chromadb'
vdb_status=False
lib_name = importlib.util.find_spec(vdb_name)
if lib_name is None:
vdb_status=False
else:
vdb_status=True
## Processing the files and create a embedding and save it using csv.
except Exception as e:
self.log.info("Error in checking chromadb installed or not. Error Message: "+str(e))
raise Exception("Error in checking chromadb installed or not. .")
## Currently vector db (chromadb) not implemented, so vdb_status is set as False
vdb_status = False
return vdb_status
def create_chroma_db(self,documents, name):
""" Craete chromadb instance (persistant) """
#get openai status
openai_api_type,openai_api_base,openai_api_key,openai_api_version = self.getOpenAICredentials()
# openai_api_type,openai_api_base,openai_api_key = self.getOpenAICredentials()
try:
from langchain.embeddings.openai import OpenAIEmbeddings
embed_function = OpenAIEmbeddings(deployment=self.generativeai_embedding_engine, chunk_size=1)
except:
from chromadb.utils import embedding_functions
embed_function = embedding_functions.OpenAIEmbeddingFunction(
api_key=openai.api_key,
api_base=openai.api_base,
api_type = openai.api_type,
model_name=self.generativeai_embedding_model
)
try:
# chroma_client = chromadb.Client()
persist_directory = self.embedd_storage_path
chroma_client = chromadb.Client(
Settings(
persist_directory=persist_directory,
chroma_db_impl="duckdb+parquet",
)
)
# Start from scratch
chroma_client.reset()
chroma_client.persist()
try:
embed_function = OpenAIEmbeddings(deployment=self.generativeai_embedding_engine, chunk_size=1)
except:
embed_function = OpenAIEmbeddings()
db = Chroma.from_documents(documents, embed_function, persist_directory=persist_directory)
db.persist()
except Exception as e:
self.log.info("Error in chromadb based embeding creation. Error Message: "+str(e))
raise Exception("Error in chromadb based embeding creation.")
return db,chroma_client
def chromadb_embedding(self,df):
""" Base chromadb embedding creation and storage function, it calls above create_chroma_db() to create db.
"""
try:
documents = df.apply(lambda x: Document(page_content= x["code"], metadata= {"function_name": x["function_name"], "filepath": x["filepath"]}), axis=1)
#setup the chromadb
db,chroma_client = self.create_chroma_db(documents,collection_name)
try:
chromadb_df=pd.DataFrame(db)
except:
db_json = db.get(include=['embeddings', 'documents', 'metadatas'])
chromadb_df = pd.read_json(db_json)
self.log.info("chromadb_df records (top ~5 records): "+str(chromadb_df.head(5)))
except Exception as e:
self.log.info("chromadb embedding error. Error message: "+str(e))
return chromadb_df
def num_tokens_from_string(self, string: str) -> int:
""" Get number of tokens of text using tiktokens lib."""
encoding = tiktoken.encoding_for_model("text-embedding-ada-002")
num_tokens = len(encoding.encode(string))
return num_tokens
def validate_code_clone_with_explanation(self,code1, code2, verbose=False):
""" Validate clone detection code snippet and get explanation from openai chat model (gpt-3.5-turbo) """
## Openai using 4 chars as 1 token, same method here followed. Here,we dont need to call tiktoken lib to save cost.
if (len(code1)/4 >1900):
chunk = self.chunk_functions(code1, 1900)
code1 = chunk[0]
print("In side , len of code1\\n",len(code1))
if (len(code2)/4 >1900):
chunk = self.chunk_functions(code2, 1900)
code2 = chunk[0]
print("In side , len of code2\\n",len(code2))
try:
SYS_ROLE = "You are a Senior Code Reviewer, who helps in Code review and integration using code clone detection approach."
openai_api_type,openai_api_base,openai_api_key,openai_api_version = self.getOpenAICredentials()
# openai_api_type,openai_api_base,openai_api_key = self.getOpenAICredentials()
prompt = f"""Given two code snippets, find if they are clones or not with suitable explaination.
Four types of clone:
1. Exact clone: Two code fragments similar to each other with little transformation in comments, layout, or whitespaces.
2. Parameterized clone: Changes made in names of variables, keywords, identifiers, or bypassing parameter during function call in code fragments, result in this clone.
3. Near-miss clone: Near-miss clone occurs by adding, deleting statements in code fragments of type 2 clones.
4. Semantic clone: The code snippets have different syntax but with alike functionality results in this clone.
Use JSON object format with following keys:
IsClone: (True, False) wheather two code snippets are clone or not.
CloneType: (Exact clone, Parameterized clone, Never-miss clone, Semantic clone) Choose appropriate clone type or "None".
Explanation: A short explanation for the above answer.
### Code Snippets:
## Code 1:
{code1}
## Code 2:
{code2}
### Answer(Valid JSON object):
"""
response = openai.ChatCompletion.create(deployment_id=self.generativeai_deploymentId,
messages=[{"role": "system", "content": SYS_ROLE},
{"role": "user", "content": prompt},],
temperature = 0,max_tokens = 3900,request_timeout=90)
text = response['choices'][0]['message']['content']
if verbose:
self.log.info("validate_code_clone_with_explanation, text: "+str(text))
except Exception as e:
print(" validate_code_clone_with_explanation: \\n",e)
response = "OpenAI Model Connection"
if e.code == "invalid_request" and "token limit" in e.message.lower():
# Implement your logic to reduce the length of messages or split them into smaller parts
# Modify messages or take appropriate action
self.log.info("Given function is too large and exceeds openai chat model token limit,please review the source file function length. "+str(e))
return response
def validate_code_clone_with_explanation_davinci(self,code1, code2, verbose=False):
""" Validate clone detection code snippet and get explanation from openai chat model (davinci) """
if (len(code1)/4 >1900):
chunk = self.chunk_functions(code1, 1900)
code1 = chunk[0]
if (len(code2)/4 >1900):
chunk = self.chunk_functions(code2, 1900)
code2 = chunk[0]
try:
SYS_ROLE = "You are a Senior Code Reviewer, who helps in Code review and integration. Detecting code clone in the repository."
openai_api_type,openai_api_base,openai_api_key,openai_api_version = self.getOpenAICredentials()
# openai_api_type,openai_api_base,openai_api_key = self.getOpenAICredentials()
prompt = f"""Given two code snippets, find if they are clones or not with suitable explaination.
Four types of clone:
1. Exact clone: Two code fragments similar to each other with little transformation in comments, layout, or whitespaces.
2. Parameterized clone: Changes made in names of variables, keywords, identifiers, or bypassing parameter during function call in code fragments, result in this clone.
3. Near-miss clone: Near-miss clone occurs by adding, deleting statements in code fragments of type 2 clones.
4. Semantic clone: The code snippets have different syntax but with alike functionality results in this clone.
Use JSON object format with following keys:
IsClone: (True, False) wheather two code snippets are clone or not.
CloneType: (Exact clone, Parameterized clone, Never-miss clone, Semantic clone) Choose appropriate clone type or "None".
Explanation: A short explanation for the above answer.
### Code Snippets:
## Code 1:
{code1}
## Code 2:
{code2}
### Answer(Valid JSON object):
"""
# response = openai.Completion.create(engine='Text-Datvinci-03', prompt=prompt, temperature=0, max_tokens=1166)
response = openai.Completion.create(engine=self.generativeai_chat_model, prompt=prompt, temperature=0, max_tokens=3900)
text = response.choices[0]["text"]
if verbose:
self.log.info("validate_code_clone_with_explanation, text (chatmodel response) "+str(text))
except Exception as e:
response = "OpenAI Model Connection Error"
if e.code == "invalid_request" and "token limit" in e.message.lower():
# Implement your logic to reduce the length of messages or split them into smaller parts
# Modify messages or take appropriate action
self.log.info("Given function is too large and exceeds openai chat model token limit,please review the source file function length. Error msg: "+str(e))
return response
## For dbscan based clone detction from python files, we use CodeCloneDetection parent class. (Using inheritance)
class CodeCloneDetectionFiles(CodeCloneDetection):
"""For dbscan based clone detction from python files, we use CodeCloneDetection
parent class. (Using inheritance)
"""
def __init__(self,root_dir,openai_baseurl, openai_key,openai_api_type,openai_api_version,embedd_storage_path,generativeai_embedding_engine,generativeai_embedding_model,generativeai_chat_model,generativeai_deploymentId):
super().__init__(root_dir,openai_baseurl, openai_key,openai_api_type,openai_api_version,embedd_storage_path,generativeai_embedding_engine,generativeai_embedding_model,generativeai_chat_model,generativeai_deploymentId)
def get_embedd_fns(self):
""" To get embedd vector, using parent class methods"""
try:
## Processing the files and create a embedding and save it using csv.
vdb_status = super().get_vdb_status('chromadb')
self.log.info("<------- AION Code Clone Detection started ... ------>\\n ")
if not vdb_status:
openai_api_type,openai_api_base,openai_api_key,openai_api_version = super().getOpenAICredentials()
# openai_api_type,openai_api_base,openai_api_key = self.getOpenAICredentials()
all_funcs,code_root,code_files,total_locs = super().get_clone_function_details()
if (openai.api_key or openai_api_key):
if not isinstance(all_funcs,type(None)):
embedded_df,embedding_cost=super().get_embeddings_pyfiles(all_funcs)
else:
return status
except Exception as e:
# print("Error in getting embedding vector using openai. Error message: ",e)
self.log.info("Error in getting embedding vector using openai. Error message: "+str(e))
raise Exception("Error in getting embedding vector using openai.")
return embedded_df,embedding_cost
def dbscan_clone_detection(self,df):
""" DBScan based code clone similarity detection (for functions in given dir """
try:
vdb_status = super().get_vdb_status('chromadb')
if not vdb_status:
X = np.array(list(df.code_embedding.values))
else:
X = np.array(list(df.embeddings.values))
#X = StandardScaler().fit_transform(X)
db = DBSCAN(eps=0.2, min_samples=2).fit(X)
labels = db.labels_
# Number of clusters in labels, ignoring noise if present.
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
n_noise_ = list(labels).count(-1)
df["cluster"] = labels
cluster_result = []
for i in range(n_clusters_):
cluster_df = df.loc[df['cluster'] == i]
# with open("{}/cluster_{}.txt".format(self.ccdreportpath,i), "w") as f:
for index, row in cluster_df.iterrows():
cluster_result.append({"cluster_id": i,"filepath": row.filepath,"function_name": row.function_name,"code": row.code })
# f.write(f"Source File: {row.filepath}, Function Name: {row.function_name}")
#f.write(f"\\n{row.code}\\n\\n{'-'*80}\\n\\n")
cluster_result_df = pd.DataFrame(cluster_result)
codeclonereport_df = os.path.join(self.ccdreportpath,'cluster_result.csv')
cluster_result_df.to_csv(codeclonereport_df, index=False)
return cluster_result_df
except Exception as e:
self.log.info("Error in dbscan based similar code clone clustering. Error Message: "+str(e))
raise Exception("Error in dbscan based similar code clone clustering | ||
.")
def make_pairs(self,data_list:list):
try:
if len(data_list) <=1:
return []
return [(data_list[0], d) for d in data_list[1:]] + self.make_pairs(data_list[1:])
except Exception as e:
self.log.info("Error in make pairs function, error message: "+str(e))
raise Exception("Error in clone code mapping.")
def code_clone_check_with_retry(self,code1,code2, retry_interval=1):
""" Call chat models for code clone detection with retry mechanism. """
try:
# res = super().validate_code_clone_with_explanation(code1,code2)
##sj
if (self.generativeai_embedding_model.lower() =='text-embedding-ada-002' and self.generativeai_chat_model.lower() == 'text-datvinci-03'):
res = super().validate_code_clone_with_explanation_davinci(code1,code2)
return res
elif (self.generativeai_embedding_model.lower() =='text-embedding-ada-002' and self.generativeai_chat_model.lower() == 'gpt-3.5-turbo'):
res = super().validate_code_clone_with_explanation(code1,code2)
return res
except (RateLimitError, Timeout) as e:
self.log.info("Calling chat model issue in code clone check function, error message: "+str(e))
time.sleep(retry_interval)
return self.code_clone_check_with_retry(code1, code2)
def res_formater(self,inp):
""" Function to format gpt-3.5 or text-davinci-003 response body. """
try:
line = inp.replace('{','')
line = line.replace('}','')
line = line.replace('"','')
end=line.split(',')
d1={}
l2=[]
for l in end:
l=l.split(',')
for i in l:
l1=i.split(":")
l2.append(l1)
import pandas as pd
df=pd.DataFrame(l2)
df=df.T
df.columns = df.iloc[0]
df = df[1:]
df.columns = df.columns.str.replace('[#,@,&,\\']', '')
# df.to_csv('test1.csv', index=False)
response=df.iloc[0]
fl=response.to_list()
clone_status=fl[0]
clone_type=fl[1]
result=fl[2]
except Exception as e:
self.log.info("chat model response formatter error. Error message: "+str(e))
return clone_status,clone_type,result
def getcloneresult_modelspecific(self,code_clone_check_tasks,embedding_cost):
""" get the clone type and associated information from chat model response data. """
try:
max_workers = min(len(code_clone_check_tasks), 100)
all_funcs,code_root,code_files,total_locs = super().get_clone_function_details()
if (self.generativeai_chat_model.lower() == 'text-datvinci-03'):
self.log.info("<--- Text-Datvinci-03 chat model based code clone detection. --->")
code_clone_result = []
for task in code_clone_check_tasks:
response=self.code_clone_check_with_retry(task[0]["code"], task[1]["code"])
with concurrent.futures.ThreadPoolExecutor(max_workers= max_workers) as executor:
llm_requests = {
executor.submit(self.code_clone_check_with_retry, task[0]["code"], task[1]["code"]): task for task in code_clone_check_tasks
}
with tqdm(total= len(llm_requests)) as progress:
for future in concurrent.futures.as_completed(llm_requests):
task = llm_requests[future]
try:
res = future.result()
try:
my_openai_obj1 = res["choices"][0]["text"]
clone_status,clone_type,result = self.res_formater(my_openai_obj1)
model_value=res['model']
total_tokens_value=res['usage']['total_tokens']
code_clone_result.append({"task": task,
"result":result,
"IsClone": clone_status,
"CloneType": clone_type,
"model":model_value,
"total_tokens":total_tokens_value})
except Exception as e:
self.log.info("getCloneReport, code_clone_result.append error: "+str(e))
except Exception as exc:
self.log.info("getCloneReport error (text davinci chat model): "+str(exc))
progress.update()
## Please uncomment below part if you need to check chat model response body.
#codeclonecheckresult_json = os.path.join(self.ccdreportpath,'code_clone_chatmodel_responsebody.json')
#with open(codeclonecheckresult_json, "w+") as fp:
#json.dump(code_clone_result, fp, indent=2)
code_clone_result_json=json.dumps(code_clone_result)
clone_report=pd.read_json(code_clone_result_json)
cr_totaltokens = clone_report['total_tokens']
total_amt = (cr_totaltokens).sum() * (0.002/1000)
clone_report["function1"] = clone_report["task"].apply(lambda x: x[0]["filepath"] + " -> " + x[0]["function_name"])
clone_report["function2"] = clone_report["task"].apply(lambda x: x[1]["filepath"] + " -> " + x[1]["function_name"])
# clone_report["clone_type"] = clone_report["result"].apply(lambda x: x["CloneType"])
clone_report["clone_type"] = clone_report["CloneType"]
code_dir = code_root
total_files = len(code_files)
total_locs = total_locs
total_functions = len(all_funcs)
total_tokens = clone_report['total_tokens'].sum()
total_cost= embedding_cost + clone_report['total_tokens'].sum() * (0.002/1000)
total_clones = len(clone_report[clone_report.clone_type != "None"])
code_clone_count_by_df = clone_report[clone_report.clone_type != "None"].groupby("clone_type").agg(Count=('clone_type', 'count')).to_markdown(tablefmt='psql')
clone_functions = clone_report[["function1", "function2", "clone_type"]][clone_report.clone_type != "None"].sort_values("function1").to_markdown(tablefmt='psql', index=False)
code_clone_count_dict = clone_report[clone_report.clone_type != "None"].groupby("clone_type").agg(Count=('clone_type', 'count'))
clone_function_dict = clone_report[["function1", "function2", "clone_type"]][clone_report.clone_type != "None"].sort_values("function1")
##Final report on code clone detection
report_str = f"""Code_directory: {code_dir}
Files: {total_files}
LOCs: {total_locs}
Functions: {total_functions}
Total_code_clones_detected: {total_clones}
Tokens used: {total_tokens}
Total cost(embedding + clone check): {total_cost}
Four_types_of_clone:
1. Exact clone: Two code fragments similar to each other with little transformation in comments, layout, or whitespaces.
2. Parameterized clone: Changes made in names of variables, keywords, identifiers, or bypassing parameter during function call in code fragments, result in this clone.
3. Near-miss clone: Near-miss clone occurs by adding, deleting statements in code fragments of type 2 clones.
4. Semantic clone: The code snippets have different syntax but with alike functionality results in this clone.
Code_clones_count_by_clone_type:
{code_clone_count_by_df}
Clone_functions:
{clone_functions}
"""
codeclonereport_txt = os.path.join(self.ccdreportpath,'code_clone_report.txt')
with open(codeclonereport_txt, "w") as f:
f.write(report_str)
report_dict=dict({"Code_directory":code_dir,"total_files":total_files,
"total_locs":total_locs,"total_functions":total_functions,"total_clones":total_clones,
"total_tokens":total_tokens,"total_cost":total_cost,
"Code_clones_count_by_clone_type":code_clone_count_dict,"clone_functions":clone_function_dict})
## report for chat model is gpt 3.5 turbo
elif (self.generativeai_chat_model.lower() == 'gpt-3.5-turbo'):
try:
self.log.info("<--- gpt-3.5-turbo chat model based code clone detection. --->")
code_clone_result = []
for task in code_clone_check_tasks:
response=self.code_clone_check_with_retry(task[0]["code"], task[1]["code"])
with concurrent.futures.ThreadPoolExecutor(max_workers= max_workers) as executor:
llm_requests = {
executor.submit(self.code_clone_check_with_retry, task[0]["code"], task[1]["code"]): task for task in code_clone_check_tasks
}
with tqdm(total= len(llm_requests)) as progress:
for future in concurrent.futures.as_completed(llm_requests):
task = llm_requests[future]
try:
res = future.result()
my_openai_obj1 = res["choices"][0]["message"]['content']
clone_status,clone_type,result = self.res_formater(my_openai_obj1)
# result = json.loads(res['choices'][0]['message']['content'])
total_tokens = res["usage"]["total_tokens"]
code_clone_result.append({"task": task,
"result":result ,
"CloneType": clone_type,
"total_tokens": total_tokens})
except Exception as exc:
self.log.info("gpt 3.5 chat model error: "+str(exc))
progress.update()
except Exception as e:
print("In gpt3.5,getcloneresult_modelspecific fn exception : \\n",e)
import traceback
print("traceback, In gpt3.5,getcloneresult_modelspecific fn exception \\n",traceback.print_exc())
## Please uncomment below part if you need to check chat model response body.
#codeclonecheckresult_json = os.path.join(self.ccdreportpath,'code_clone_chatmodel_responsebody.json')
#with open(codeclonecheckresult_json, "w+") as fp:
#json.dump(code_clone_result, fp, indent=2)
try:
code_clone_result_json=json.dumps(code_clone_result)
clone_report = pd.read_json(code_clone_result_json)
codeclone_total_amt = clone_report["total_tokens"].sum() * (0.002/1000)
clone_report["function1"] = clone_report["task"].apply(lambda x: x[0]["filepath"] + " -> " + x[0]["function_name"])
clone_report["function2"] = clone_report["task"].apply(lambda x: x[1]["filepath"] + " -> " + x[1]["function_name"])
# clone_report["clone_type"] = clone_report["result"].apply(lambda x: x["CloneType"])
clone_report["clone_type"] = clone_report["CloneType"]
code_dir = code_root
total_files = len(code_files)
total_locs = total_locs
total_functions = len(all_funcs)
total_tokens = clone_report["total_tokens"].sum()
except Exception as e:
self.log.info("Error in getting clone report: "+str(e))
total_cost= embedding_cost + clone_report["total_tokens"].sum() * (0.002/1000)
total_clones = len(clone_report[clone_report.clone_type != "None"])
code_clone_count_by_df = clone_report[clone_report.clone_type != "None"].groupby("clone_type").agg(Count=('clone_type', 'count')).to_markdown(tablefmt='psql')
clone_functions = clone_report[["function1", "function2", "clone_type"]][clone_report.clone_type != "None"].sort_values("function1").to_markdown(tablefmt='psql', index=False)
code_clone_count_dict = clone_report[clone_report.clone_type != "None"].groupby("clone_type").agg(Count=('clone_type', 'count'))
clone_function_dict = clone_report[["function1", "function2", "clone_type"]][clone_report.clone_type != "None"].sort_values("function1")
report_str = f"""Code_directory: {code_dir}
Files: {total_files}
LOCs: {total_locs}
Functions: {total_functions}
Total code clones detected: {total_clones}
Tokens used: {total_tokens}
Total cost(embedding + clone check): {total_cost}
Four types of clone:
1. Exact clone: Two code fragments similar to each other with little transformation in comments, layout, or whitespaces.
2. Parameterized clone: Changes made in names of variables, keywords, identifiers, or bypassing parameter during function call in code fragments, result in this clone.
3. Near-miss clone: Near-miss clone occurs by adding, deleting statements in code fragments of type 2 clones.
4. Semantic clone: The code snippets have different syntax but with alike functionality results in this clone.
5. None: Not a clone, discard this one.
Code_clones_count_by_clone_type:
{code_clone_count_by_df}
Clone_functions:
{clone_functions}
"""
codeclonereport_txt = os.path.join(self.ccdreportpath,'code_clone_report.txt')
with open(codeclonereport_txt, "w") as | ||
f:
f.write(report_str)
report_dict=dict({"Code_directory":code_dir,"total_files":total_files,
"total_locs":total_locs,"total_functions":total_functions,"total_clones":total_clones,
"total_tokens":total_tokens,"total_cost":total_cost,
"Code_clones_count_by_clone_type":code_clone_count_dict,"clone_functions":clone_function_dict})
except Exception as e:
self.log.info("Error in clone type and information retrival process .Error message: "+str(e))
return code_clone_result,report_str,report_dict
def getCloneReport(self):
""" To get the clone report from the given python directory """
try:
self.log.info("To get clone report, we are calling embedding and chat model.")
import time
vdb_status = super().get_vdb_status('chromadb')
start_time = time.time()
# self.log.info("code clone detection start time."+str(start_time))
if not vdb_status:
embedded_df,embedding_cost = self.get_embedd_fns()
cluster_df = self.dbscan_clone_detection(embedded_df)
cluster_df_group = cluster_df.groupby("cluster_id")
len_cluster_df_group = len(cluster_df_group)
code_clone_check_tasks = []
for name, group in cluster_df_group:
res = self.make_pairs(group.to_dict(orient="records"))
code_clone_check_tasks += res
#For text-embedding-ada-002 and gpt 3.5 chat model
code_clone_result,report_str,report_dict = self.getcloneresult_modelspecific(code_clone_check_tasks,embedding_cost)
end_time = time.time()
total_time_taken = end_time - start_time
self.log.info("Total time taken for code clone detction: "+str(total_time_taken))
self.log.info("<------------- Final code clone report: -------------------> \\n"+str(report_str))
report_df = pd.DataFrame.from_dict(report_dict, orient="index").reset_index()
report_df.columns = ['ccd_properties', 'Values']
report_df=report_df.T
codecloneresult_df = os.path.join(self.ccdreportpath,'code_clone_report_df.csv')
report_df.to_csv(codecloneresult_df)
return report_str,report_dict,report_df,json.dumps(report_str)
else:
#Below code indended for vector db.
all_funcs,code_root,code_files,total_locs = super().get_clone_function_details()
df = pd.DataFrame(all_funcs)
df['filepath'] = df['filepath'].apply(lambda x: x.replace(code_root, ""))
chromadb_df=super().chromadb_embedding(df)
df = self.dbscan_clone_detection(chromadb_df)
cluster_df_group = cluster_df.groupby("cluster_id")
len_cluster_df_group = len(cluster_df_group)
code_clone_check_tasks = []
for name, group in cluster_df_group:
res = self.make_pairs(group.to_dict(orient="records"))
code_clone_check_tasks += res
code_clone_result = []
max_workers = min(len(code_clone_check_tasks), 100)
with concurrent.futures.ThreadPoolExecutor(max_workers= max_workers) as executor:
llm_requests = {
executor.submit(self.code_clone_check_with_retry, task[0]["code"], task[1]["code"]): task for task in code_clone_check_tasks
}
with tqdm(total= len(llm_requests)) as progress:
for future in concurrent.futures.as_completed(llm_requests):
task = llm_requests[future]
try:
res = future.result()
code_clone_result.append({"task": task,
"result": json.loads(res['choices'][0]['message']['content']),
"total_tokens": res["usage"]["total_tokens"]})
except Exception as exc:
print('%r generated an exception: %s' % (task, exc))
progress.update()
with open("code_clone_check_result.json", "w+") as fp:
json.dump(code_clone_result, fp, indent=2)
code_clone_result_json=json.dumps(code_clone_result)
clone_report=pd.read_json(code_clone_result_json)
total_amt = clone_report["total_tokens"].sum() * (0.002/1000)
clone_report["function1"] = clone_report["task"].apply(lambda x: x[0]["filepath"] + " -> " + x[0]["function_name"])
clone_report["function2"] = clone_report["task"].apply(lambda x: x[1]["filepath"] + " -> " + x[1]["function_name"])
clone_report["clone_type"] = clone_report["result"].apply(lambda x: x["CloneType"])
all_funcs,code_root,code_files,total_locs = super().get_clone_function_details()
code_dir = code_root
total_files = len(code_files)
total_locs = total_locs
total_functions = len(all_funcs)
total_tokens = clone_report["total_tokens"].sum()
# total_cost= embedding_cost + clone_report["total_tokens"].sum() * (0.002/1000)
total_clones = len(clone_report[clone_report.clone_type != "None"])
code_clone_count_by_df = clone_report[clone_report.clone_type != "None"].groupby("clone_type").agg(Count=('clone_type', 'count')).to_markdown(tablefmt='psql')
clone_functions = clone_report[["function1", "function2", "clone_type"]][clone_report.clone_type != "None"].sort_values("function1").to_markdown(tablefmt='psql', index=False)
code_clone_count_dict = clone_report[clone_report.clone_type != "None"].groupby("clone_type").agg(Count=('clone_type', 'count'))
clone_function_dict = clone_report[["function1", "function2", "clone_type"]][clone_report.clone_type != "None"].sort_values("function1")
##Final report on code clone detection
report_str = f"""Code_directory: {code_dir}
Files: {total_files}
LOCs: {total_locs}
Functions: {total_functions}
Total code clones detected: {total_clones}
Tokens used: {total_tokens}
Four types of clone:
1. Exact clone: Two code fragments similar to each other with little transformation in comments, layout, or whitespaces.
2. Parameterized clone: Changes made in names of variables, keywords, identifiers, or bypassing parameter during function call in code fragments, result in this clone.
3. Near-miss clone: Near-miss clone occurs by adding, deleting statements in code fragments of type 2 clones.
4. Semantic clone: The code snippets have different syntax but with alike functionality results in this clone.
Code_clones_count_by_clone_type:
{code_clone_count_by_df}
Clone_functions:
{clone_functions}
"""
with open("code_clone_report.txt", "w") as f:
f.write(report_str)
# print(report_str)
self.log.info("<------------- Final code clone report: -------------------> \\n"+str(report_str))
self.log.info("<------------- clone_functions code clone report: -------------------> \\n"+str(clone_functions))
report_dict=dict({"Code_directory":code_dir,"total_files":total_files,
"total_locs":total_locs,"total_functions":total_functions,"total_clones":total_clones,
"total_tokens":total_tokens,
"Code_clones_count_by_clone_type":code_clone_count_dict,"clone_functions": clone_function_dict})
report_df= pd.DataFrame([report_dict.keys(), report_dict.values()]).T
report_df.columns = ["Code_directory", "total_files","total_locs","total_functions","total_clones","total_tokens","Code_clones_count_by_clone_type","clone_functions"]
report_df.to_csv("code_clone_report_df.csv")
return report_str,report_dict,report_df,json.dumps(report_str)
except Exception as e:
self.log.info("Error in clone detection function call. Error Message: \\n"+str(e))
raise Exception("Error in clone detection function.")
#For testing and code instance privacy
if __name__=='__main__':
## For testing purpose.Uncomment n use.
root_directory = r"C:\\AION_Works\\Anomaly_Detection\\anomalydetectionpackage\\code_clone_testing_pyfiles\\code_clone_testing_pyfiles_large"
embedd_storage_path = r"C:\\AION_Works\\ccddir"
generativeai_credentials={'openai_baseurl':"",
'openai_key':"",
'openai_api_type':"",
'openai_api_version':"",
'generativeai_embedding_engine':"",
'generativeai_embedding_model':"",
'generativeai_chat_model':"",
'generativeai_deploymentId':""}
openai_baseurl = generativeai_credentials['openai_baseurl']
openai_key = generativeai_credentials['openai_key']
openai_api_type = generativeai_credentials['openai_api_type']
openai_api_version = generativeai_credentials['openai_api_version']
generativeai_embedding_engine = generativeai_credentials['generativeai_embedding_engine']
generativeai_embedding_model = generativeai_credentials['generativeai_embedding_model']
generativeai_chat_model = generativeai_credentials['generativeai_chat_model']
generativeai_deploymentId = generativeai_credentials['generativeai_deploymentId']
codeclonedetection_obj = CodeCloneDetectionFiles(root_directory,openai_baseurl, openai_key,openai_api_type,openai_api_version,embedd_storage_path,generativeai_embedding_engine,generativeai_embedding_model,generativeai_chat_model,generativeai_deploymentId)
report_str,report_dict,report_json = codeclonedetection_obj.getCloneReport()
print("End of code clone detection....\\n")
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os,sys
import json
def getInstanceonGCP(image,instances):
try:
from appbe.sqliteUtility import sqlite_db
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'config.db')
if sqlite_obj.table_exists('LLMTuning'):
data = sqlite_obj.read_data('LLMTuning','image="'+image['id']+'"')
for values in data:
instance = {}
instance['type'] = 'instance'
instance['id'] = values[2]
instance['workLoad'] = image['workLoad']
instance['machineImageProjectID'] = image['machineImageProjectID']
instance['ssh'] = image['ssh']
instance['machineConfiguration'] = image['machineConfiguration']
instance['instanceType'] = image['instanceType']
instances.append(instance)
except Exception as e:
print(e)
return instances
def getInstanceonAWS(amiid,instances):
try:
from appbe.sqliteUtility import sqlite_db
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'config.db')
if sqlite_obj.table_exists('LLMTuning'):
data = sqlite_obj.read_data('LLMTuning','image="'+amiid['id']+'"')
for values in data:
instance = {}
instance['type'] = 'instance'
instance['id'] = values[2]
instance['workLoad'] = amiid['workLoad']
instance['regionName'] = amiid['regionName']
instance['ssh'] = amiid['ssh']
instance['machineConfiguration'] = amiid['machineConfiguration']
instance['instanceType'] = amiid['instanceType']
instances.append(instance)
except Exception as e:
print(e)
return instances
def updatelocalsetings(request):
from appbe.sqliteUtility import sqlite_db
from appbe.dataPath import DATA_DIR
import pandas as pd
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'config.db')
if sqlite_obj.table_exists('computeInfrastructure'):
updated_data = 'selectedInfrastructure="Local"'
sqlite_obj.update_data(updated_data,'','computeInfrastructure')
def updateToComputeSettings(infratructure):
from appbe.sqliteUtility import sqlite_db
from appbe.dataPath import DATA_DIR
import pandas as pd
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'config.db')
if sqlite_obj.table_exists('computeInfrastructure'):
updated_data = 'selectedInfrastructure="'+infratructure+'"'
sqlite_obj.update_data(updated_data,'','computeInfrastructure')
def updateGCPConfig(request):
try:
credentialsJson = request.POST.get('credentialsJson')
projectID = request.POST.get('gcpProjectid')
machineType = request.POST.get('gcpmachineType')
selectedID = request.POST.get('gcpInstance')
gcpZone = request.POST.get('gcpZone')
workload = request.POST.get('gcpworkload')
noOfInstance = request.POST.get('GCPnoofinstance')
#print(credentialsJson,projectID,machineType,selectedID,gcpZone,workload,noOfInstance)
if credentialsJson != '' and projectID != '':
from appbe | ||
.sqliteUtility import sqlite_db
from appbe.dataPath import DATA_DIR
import pandas as pd
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'config.db')
if sqlite_obj.table_exists('gcpCredentials'):
updated_data = 'credentialsJson="'+credentialsJson+'",projectID="'+projectID+'",machineType="'+machineType+'",selectedID="'+selectedID+'",regionName="'+gcpZone+'",noOfInstance="'+str(noOfInstance)+'",workload="'+workload+'"'
sqlite_obj.update_data(updated_data,'','gcpCredentials')
else:
newdata = {}
newdata.update({'id':['1'],'credentialsJson': [credentialsJson],'projectID': [projectID],'machineType':[machineType],'selectedID':[selectedID],'regionName':[gcpZone],'noOfInstance':[noOfInstance],'workload':[workload]})
sqlite_obj.write_data(pd.DataFrame.from_dict(newdata),'gcpCredentials')
return('success')
else:
return('error')
except Exception as e:
print(e)
return('error')
def updateComputeConfig(request):
try:
AWSAccessKeyID = request.POST.get('AWSAccessKeyID')
AWSSecretAccessKey = request.POST.get('AWSSecretAccessKey')
workload = request.POST.get('workload')
machineType = request.POST.get('machineType')
selectedID = request.POST.get('amiInstance')
regionName = request.POST.get('regionName')
noOfInstance = request.POST.get('NoOfInstance')
securitygroupid = request.POST.get('AWSSecuritygroupID')
if AWSAccessKeyID != '' and AWSSecretAccessKey != '':
from appbe.sqliteUtility import sqlite_db
from appbe.dataPath import DATA_DIR
import pandas as pd
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'config.db')
if sqlite_obj.table_exists('awsCredentials'):
column_names = sqlite_obj.column_names('awsCredentials')
if 'securitygroupid' not in column_names:
query = 'Alter Table awsCredentials ADD securitygroupid TEXT'
sqlite_obj.execute_query(query)
updated_data = 'AWSAccessKeyID="'+AWSAccessKeyID+'",AWSSecretAccessKey="'+AWSSecretAccessKey+'",machineType="'+machineType+'",selectedID="'+selectedID+'",regionName="'+regionName+'",noOfInstance="'+noOfInstance+'",workload="'+workload+'",securitygroupid="'+securitygroupid+'"'
sqlite_obj.update_data(updated_data,'','awsCredentials')
else:
newdata = {}
newdata.update({'id':['1'],'AWSAccessKeyID': [AWSAccessKeyID],'AWSSecretAccessKey': [AWSSecretAccessKey],'machineType':[machineType],'selectedID':[selectedID],'regionName':[regionName],'noOfInstance':[noOfInstance],'workload':[workload],'securitygroupid':[securitygroupid]})
sqlite_obj.write_data(pd.DataFrame.from_dict(newdata),'awsCredentials')
return('success')
else:
return('error')
except Exception as e:
print(e)
return('error')
def selectedInfratructure():
from appbe.sqliteUtility import sqlite_db
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'config.db')
selcInfra = 'Local'
if sqlite_obj.table_exists('computeInfrastructure'):
data = sqlite_obj.read_data('computeInfrastructure')
for values in data:
selcInfra = values[1]
return selcInfra
def readComputeConfig():
try:
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','config','compute_conf.json'))
f = open(file_path, "r")
configSettings = f.read()
f.close()
configSettingsJson = json.loads(configSettings)
from appbe.sqliteUtility import sqlite_db
from appbe.dataPath import DATA_DIR
import pandas as pd
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'config.db')
selcInfra = 'Local'
if sqlite_obj.table_exists('computeInfrastructure'):
data = sqlite_obj.read_data('computeInfrastructure')
for values in data:
selcInfra = values[1]
else:
data = {}
data.update({'id':['1'],'selectedInfrastructure': ['Local']})
sqlite_obj.write_data(pd.DataFrame.from_dict(data),'computeInfrastructure')
configSettingsJson['computeInfrastructure'] = selcInfra
for ami in configSettingsJson['AWS_EC2']['amis']:
configSettingsJson['AWS_EC2']['instances'] = getInstanceonAWS(ami,configSettingsJson['AWS_EC2']['instances'])
for image in configSettingsJson['GCP']['machineImage']:
configSettingsJson['GCP']['instances'] = getInstanceonGCP(image,configSettingsJson['GCP']['instances'])
AWSAccessKeyID = ''
AWSSecretAccessKey = ''
securitygroupid = ''
machineType = 'AMI'
selectedID = ''
regionName = ''
noofInfra = 1
workLoad = 'LLM'
if sqlite_obj.table_exists('awsCredentials'):
column_names = sqlite_obj.column_names('awsCredentials')
#print(column_names)
if 'workload' not in column_names:
query = 'Alter Table awsCredentials ADD workload TEXT'
sqlite_obj.execute_query(query)
if 'securitygroupid' not in column_names:
query = 'Alter Table awsCredentials ADD securitygroupid TEXT'
sqlite_obj.execute_query(query)
data = sqlite_obj.read_data('awsCredentials')
for values in data:
AWSAccessKeyID = values[1]
AWSSecretAccessKey = values[2]
machineType = values[3]
selectedID = values[4]
regionName = values[5]
noofInfra = values[6]
workLoad = values[7]
securitygroupid = values[8]
selectedAWS = {}
selectedAWS['accessKey'] = AWSAccessKeyID
selectedAWS['secretAccessKey'] = AWSSecretAccessKey
selectedAWS['machineType']=machineType
selectedAWS['selectedID'] = selectedID
selectedAWS['regionName'] = regionName
selectedAWS['noOfInstance']=noofInfra
selectedAWS['workLoad'] = workLoad
selectedAWS['securitygroupid'] = securitygroupid
configSettingsJson['awsCredentials'] = selectedAWS
gcpCredentials=''
projectID = ''
selectedID = ''
machineType = ''
regionName = ''
noOfInstance = 1
workLoad = 'LLM'
if sqlite_obj.table_exists('gcpCredentials'):
column_names = sqlite_obj.column_names('gcpCredentials')
if 'workload' not in column_names:
query = 'Alter Table gcpCredentials ADD workload TEXT'
sqlite_obj.execute_query(query)
data = sqlite_obj.read_data('gcpCredentials')
for values in data:
gcpCredentials = values[1]
projectID = values[2]
machineType = values[3]
selectedID = values[4]
regionName = values[5]
noOfInstance = values[6]
workLoad = values[7]
selectedGCP = {}
selectedGCP['gcpCredentials'] = gcpCredentials
selectedGCP['selectedID'] = selectedID
selectedGCP['projectID'] = projectID
selectedGCP['machineType'] = machineType
selectedGCP['regionName'] = regionName
selectedGCP['noOfInstance'] = noOfInstance
selectedAWS['workLoad'] = workLoad
configSettingsJson['gcpCredentials'] = selectedGCP
#print(configSettingsJson)
return(configSettingsJson)
except Exception as e:
print(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import json
import os
import rsa
import boto3 #usnish
import pandas as pd
import time
def add_new_bucket(request):
try:
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','s3bucket.conf'))
with open(file_path, 'r') as f:
data = json.load(f)
except:
data = []
if request.POST["aionreferencename"] =='' or request.POST["s3bucketname"] == '' or request.POST["awsaccesskey"] == '' :
return 'error'
pkeydata='''-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAxIHM1FphEMMwViUrG0b2Bqf8tOxbhUWlnmjgFt5A25qbY1AfnrMv
fVx8+7iCcZ/3TY9Jv2I584SOc1tvsgESCke/t6+o/u2esPBsnDFzV62l3Zvw0m4e
wQeKlFC8EoOblyIXRbZdelSJinzlr9lOiKuid/xPvXHou6jxF1A2W7a89A2PM4Re
n0W9YkjB7dRGW1sSrpruHdVJvgHhGZFZ7sCTue0jVOnc5sT3Tq5saLfEDqHyKxlq
i/mcThmcTfisRIYFH5pyt/Ysr4VVP924QlcoqPOyg3RMCS3G0VjstSoVwNhxWrs/
lujDuCnpxvWzNpq21OWmF66GXxwiq+6W0wIDAQAB
-----END RSA PUBLIC KEY-----'''
pubkey = rsa.PublicKey.load_pkcs1(pkeydata)
awssecretaccesskey = rsa.encrypt(request.POST["awssecretaccesskey"].encode(), pubkey)
print(awssecretaccesskey)
newdata = {}
newdata['Name'] = request.POST["aionreferencename"]
newdata['AWSAccessKeyID'] = request.POST["awsaccesskey"]
newdata['AWSSecretAccessKey'] = str(awssecretaccesskey)
newdata['S3BucketName'] = request.POST["s3bucketname"]
data.append(newdata)
with open(file_path, 'w') as f:
json.dump(data, f)
f.close()
def get_s3_bucket():
try:
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','s3bucket.conf'))
with open(file_path, 'r') as f:
data = json.load(f)
except:
data = []
return data
def read_s3_bucket(name,filename,DATA_FILE_PATH):
privkey = '''-----BEGIN RSA PRIVATE KEY-----
MIIEqQIBAAKCAQEAxIHM1FphEMMwViUrG0b2Bqf8tOxbhUWlnmjgFt5A25qbY1Af
nrMvfVx8+7iCcZ/3TY9Jv2I584SOc1tvsgESCke/t6+o/u2esPBsnDFzV62l3Zvw
0m4ewQeKlFC8EoOblyIXRbZdelSJinzlr9lOiKuid/xPvXHou6jxF1A2W7a89A2P
M4Ren0W9YkjB7dRGW1sSrpruHdVJvgHhGZFZ7sCTue0jVOnc5sT3Tq5saLfEDqHy
Kxlqi/mcThmcTfisRIYFH5pyt/Ysr4VVP924QlcoqPOyg3RMCS3G0VjstSoVwNhx
Wrs/lujDuCnpxvWzNpq21OWmF66GXxwiq+6W0wIDAQABAoIBAC/VbNfQPEqJSO3f
VFPqfR73q2MbGdgiMQOTgeDvLxiF1QdizJ+j/I5mgiIAMviXuOpPU+NbdMHbZZWd
D15kNlD8UCXVg6yyiOuHStjmjK4uHe8I86E1nxTb0hbyZCWZlbk/WizlDHInu+dT
KdIZcq2AIidU6tAxtwA0ingHaRSoXDlSGwOTEigNqmWOKnDTVg0SMscoHOD7siXF
DHm1/lkvD3uvcZk6c7fGxC8SgNX2dj6n/Nbuy0Em+bJ0Ya5wq4HFdLJn3EHZYORF
ODUDYoGaSxeXqYsGg/KHJBc8J7xW9FdN9fGbHfw1YplrmiGL3daATtArjMmAh0EQ
H8Sj7+ECgYkA3oWMCHi+4t8txRPkg1Fwt8dcqYhGtqpAus3NESVurAdi0ZPqEJcQ
4cUbflwQPhX0TOaBlkgzdP8DMdcW/4RalxHsAh5N8ezx/97PQMb3Bht0WsQUBeYJ
xLV7T2astjTRWactGCG7dwTaUYRtU3FqL6//3CysmA12B5EMX0udNBOTKwmaYKww
AwJ5AOISS7f12Q0fgTEVY0H8Zu5hHXNOA7DN92BUzf99iPx+H+codLet4Ut4Eh0C
cFmjA3TC78oirp5mOOQmYxwaF | ||
axlZ7Rs60dlPFrhz0rsHYPK1yUOWRr3RcXWSR13
r+kn+f+8k7nItfGi7shdcQW+adm/EqPfwTHM8QKBiQCIPEMrvKFBzVn8Wt2A+I+G
NOyqbuC8XSgcNnvij4RelncN0P1xAsw3LbJTfpIDMPXNTyLvm2zFqIuQLBvMfH/q
FfLkqSEXiPXwrb0975K1joGCQKHxqpE4edPxHO+I7nVt6khVifF4QORZHDbC66ET
aTHA3ykcPsGQiGGGxoiMpZ9orgxyO3l5Anh92jmU26RNjfBZ5tIu9dhHdID0o8Wi
M8c3NX7IcJZGGeCgywDPEFmPrfRHeggZnopaAfuDx/L182pQeJ5MEqlmI72rz8bb
JByJa5P+3ZtAtzc2RdqNDIMnM7fYU7z2S279U3nZv0aqkk3j9UDqNaqvsZMq73GZ
y8ECgYgoeJDi+YyVtqgzXyDTLv6MNWKna9LQZlbkRLcpg6ELRnb5F/dL/eB/D0Sx
QpUFi8ZqBWL+A/TvgrCrTSIrfk71CKv6h1CGAS02dXorYro86KBLbJ0yp1T/WJUj
rHrGHczglvoB+5stY/EpquNpyca03GcutgIi9P2IsTIuFdnUgjc7t96WEQwL
-----END RSA PRIVATE KEY-----'''
try:
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','s3bucket.conf'))
with open(file_path, 'r') as f:
data = json.load(f)
except:
data = []
awssecretaccesskey = ''
found = False
for x in data:
if x['Name'] == name:
awssecretaccesskey = x['AWSSecretAccessKey']
aws_access_key_id = x['AWSAccessKeyID']
bucketName = x['S3BucketName']
found = True
break
if found:
privkey = rsa.PrivateKey.load_pkcs1(privkey,'PEM')
awssecretaccesskey = eval(awssecretaccesskey)
awssecretaccesskey = rsa.decrypt(awssecretaccesskey, privkey)
awssecretaccesskey = awssecretaccesskey.decode('utf-8')
#awssecretaccesskey = 'SGcyJavYEQPwTbOg1ikqThT+Op/ZNsk7UkRCpt9g'#rsa.decrypt(awssecretaccesskey, privkey)
client_s3 = boto3.client('s3', aws_access_key_id=aws_access_key_id, aws_secret_access_key=str(awssecretaccesskey))
#print(bucketName,filename)
try:
response = client_s3.get_object(Bucket=bucketName, Key=filename)
df = pd.read_csv(response['Body'])
except Exception as e:
print(e)#usnish
return 'Error', pd.DataFrame()
#return 'Error', pd.DataFrame()
return 'Success',df
return 'Error', pd.DataFrame()<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os,sys
import json
import platform
import subprocess
def kafka_setting():
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','config','kafkaConfig.conf'))
f = open(file_path, "r")
configSettings = f.read()
f.close()
configSettingsJson = json.loads(configSettings)
from os.path import expanduser
home = expanduser("~")
if platform.system() == 'Windows':
DEPLOY_LOCATION = os.path.join(home,'AppData','Local','HCLT','AION','target','kafka')
else:
DEPLOY_LOCATION = os.path.join(home,'HCLT','AION','target','kafka')
configSettingsJson['kafkalocation'] = DEPLOY_LOCATION
return(configSettingsJson)
def start_tracking():
from appbe.dataPath import DEPLOY_LOCATION
import platform
mlflowpath = os.path.normpath(os.path.join(os.path.dirname(__file__),'..','..','..','..','Scripts','mlflow.exe'))
script_path = os.path.normpath(os.path.join(os.path.dirname(__file__),'..','..','..','..','Scripts'))
#Updating path for system environment; Bug-13835
os.environ['PATH']= os.environ['PATH']+ ';'+ str(script_path)
DEPLOY_LOCATION = os.path.join(DEPLOY_LOCATION,'mlruns')
if platform.system() == 'Windows':
subprocess.Popen([sys.executable, mlflowpath,"ui", "--backend-store-uri","file:///"+DEPLOY_LOCATION])
else:
subprocess.Popen(['mlflow',"ui","-h","0.0.0.0","--backend-store-uri","file:///"+DEPLOY_LOCATION])
def aion_tracking():
status = 'Success'
import requests
try:
response = requests.get('http://localhost:5000')
if response.status_code != 200:
status = 'Error'
except Exception as inst:
print(inst)
status = 'Error'
return status
def aion_service():
try:
if platform.system() == 'Windows':
nooftasks = getrunningstatus('AION_Service')
else:
nooftasks = getrunningstatus('run_service')
if len(nooftasks):
status = 'Running'
else:
if platform.system() == 'Windows':
servicepath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','sbin','AION_Service.bat'))
os.system('start cmd /c "'+servicepath+'"')
else:
servicepath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','bin','run_service.py'))
subprocess.Popen([sys.executable,servicepath])
status = 'Started'
except Exception as inst:
print(inst)
status = 'Error'
return status
def getrunningstatus(name):
try:
taskdetails = []
if platform.system() == 'Windows':
r = ([line.split() for line in subprocess.check_output('tasklist /v /FI "IMAGENAME eq conhost.exe"').decode('UTF-8').splitlines()])
r.append([line.split() for line in subprocess.check_output('tasklist /v /FI "IMAGENAME eq cmd.exe"').decode('UTF-8').splitlines()])
else:
r = ([line.split() for line in subprocess.check_output("ps -ef | grep .py",shell=True).decode('UTF-8').splitlines()])
for i in range(len(r)):
s = r[i]
if any(name in j for j in s):
taskdetails.append('Yes')
break
return (taskdetails)
except Exception as inst:
print(inst)
status = 'Error'
return status
def getTasks(mlflow,consumer,service):
mlflowlist = []
consumerlist=[]
servicelist = []
#r = os.popen('tasklist /v').read().strip().split('\\n')
try:
if platform.system() == 'Windows':
r = ([line.split() for line in subprocess.check_output('tasklist /v /FI "IMAGENAME eq conhost.exe"').decode('UTF-8').splitlines()])
r.append([line.split() for line in subprocess.check_output('tasklist /v /FI "IMAGENAME eq cmd.exe"').decode('UTF-8').splitlines()])
else:
r = ([line.split() for line in subprocess.check_output("ps -ef | grep .py",shell=True).decode('UTF-8').splitlines()])
except Exception as e:
print(e)
r = []
#print(r)
#print ('# of tasks is %s' % (len(r)))
for i in range(len(r)):
s = r[i]
if any(mlflow in j for j in s):
mlflowlist.append('Yes')
if any(consumer in j for j in s):
consumerlist.append('Yes')
if any(service in j for j in s):
servicelist.append('Yes')
return (mlflowlist,consumerlist,servicelist)
def running_setting():
otherApps = {}
if platform.system() == 'Windows':
mlflowlist,consumerlist,servicelist = getTasks('AION_MLFlow','AION_Consumer','AION_Service')
else:
mlflowlist,consumerlist,servicelist = getTasks('run_mlflow','AION_Consumer','run_service')
if len(mlflowlist):
otherApps['modeltracking'] = 'Running'
else:
otherApps['modeltracking'] = 'Not Running'
#nooftasks = getTasks('AION_Consumer')
if len(consumerlist):
otherApps['consumer'] = 'Running'
else:
otherApps['consumer'] = 'Not Running'
#nooftasks = getTasks('AION_Service')
if len(servicelist):
otherApps['service'] = 'Running'
else:
otherApps['service'] = 'Not Running'
return(otherApps)
#EDA Performance change
# ----------------------------
def eda_setting():
configfilepath = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','config','eda.config')
sample_size=''
try:
if(os.path.isfile(configfilepath)):
file = open(configfilepath, "r")
read = file.read()
file.close()
for line in read.splitlines():
if 'sample_size=' in line:
sample_size = line.split('=',1)[1]
except Exception as inst:
pass
return(sample_size)
def get_telemetryoptout():
telemetryoptuout = "No"
from appbe.sqliteUtility import sqlite_db
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'config.db')
try:
if sqlite_obj.table_exists('settings'):
data = sqlite_obj.read_data('settings')
for values in data:
telemetryoptuout = values[7]
else:
telemetryoptuout = 'No'
except Exception as e:
print(e)
telemetryoptuout ='No'
return telemetryoptuout
def get_edafeatures():
No_of_Permissible_Features_EDA = ""
from appbe.sqliteUtility import sqlite_db
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'config.db')
try:
if sqlite_obj.table_exists('settings'):
data = sqlite_obj.read_data('settings')
for values in data:
No_of_Permissible_Features_EDA = values[3]
else:
configfilepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'config', 'aion.config')
if (os.path.isfile(configfilepath)):
file = open(configfilepath, "r")
read = file.read()
file.close()
for line in read.splitlines():
if 'No_of_Permissible_Features_EDA=' in line:
No_of_Permissible_Features_EDA = line.split('=', 1)[1]
except Exception as e:
print(e)
No_of_Permissible_Features_EDA =20
return No_of_Permissible_Features_EDA
def get_graviton_data():
graviton_url = ""
graviton_userid = ""
from appbe.sqliteUtility import sqlite_db
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'config.db')
try:
if sqlite_obj.table_exists('settings'):
data = sqlite_obj.read_data('settings')
for values in data:
graviton_url = values[0]
graviton_userid = values[1]
else:
configfilepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'config', 'aion.config')
if (os.path.isfile(configfilepath)):
file = open(configfilepath, "r")
read = file.read()
file.close()
for line in read.splitlines():
if 'graviton_url=' in line:
graviton_url = line.split('=', 1)[1]
if 'graviton_userid=' in line:
graviton_userid = line.split('=', 1)[1]
except Exception as e:
print(e)
graviton_url = ""
graviton_userid = ""
return graviton_url,graviton_userid
def get_llm_data():
apiKeyIdLLM = ""
apiUrlLLM = ""
from appbe.sqliteUtility import sqlite_db
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'config.db')
try:
if sqlite_obj.table_exists('openai'):
data = sqlite_obj.read_data('openai')[0]
param_keys | ||
= ['api_type','api_key','api_base','api_version']
openai_data = dict((x,y) for x,y in zip(param_keys,data))
return openai_data['api_key'],openai_data['api_base'],openai_data['api_type'],openai_data[ | ||
write_data(pd.DataFrame.from_dict(newdata),'dataingest')
else:
raise Exception("Data Genration failed.")
except Exception as e:
print(e)
raise Exception(str(e))
if __name__ == "__main__":
generate_json_config('classification')
generate_json_config('regression')
generate_json_config('timeseriesforecasting') #task 11997<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import time
from pathlib import Path
import logging
from datetime import datetime as dt
class logg():
from appbe.dataPath import LOG_LOCATION
def __init__(self, LOG_LOCATION):
self.log_location = LOG_LOCATION
def create_log(self,version):
log_file_path = Path(self.log_location)
log_file_path.mkdir(parents=True, exist_ok=True)
time_stamp = dt.fromtimestamp(time.time()).strftime('%Y-%m-%d-%H-%M-%S')
fileName='log_ux_'+time_stamp+'.log'
filehandler = logging.FileHandler(log_file_path/fileName, 'a','utf-8')
formatter = logging.Formatter('%(asctime)s %(message)s')
filehandler.setFormatter(formatter)
log = logging.getLogger('log_ux')
log.propagate = False
for hdlr in log.handlers[:]: # remove the existing file handlers
if isinstance(hdlr,logging.FileHandler):
log.removeHandler(hdlr)
log.addHandler(filehandler)
log.setLevel(logging.INFO)
log.info('********** AION_'+str(version)+' **********')
return log<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import requests
import json
import os
from datetime import datetime
import socket
import getmac
from appbe.sqliteUtility import sqlite_db
import pandas as pd
from appbe.dataPath import DATA_DIR
def TelemetryCreateSyncState(state):
try:
newdata = {}
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'telemetry.db')
now = datetime.now()
SyncingTime = int(datetime.timestamp(now))
newdata.update({'ID':['1'],'state':[state],'syncingTime':[SyncingTime]})
sqlite_obj.write_data(pd.DataFrame.from_dict(newdata),'syncState')
except Exception as e:
print(e)
pass
def TelemetryUpdateSyncState(state):
try:
newdata = {}
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'telemetry.db')
now = datetime.now()
SyncingTime = int(datetime.timestamp(now))
updated_data = '"state"="'+state+'","syncingTime"="'+str(SyncingTime)+'"'
sqlite_obj.update_data(updated_data,'ID="1"','syncState')
except Exception as e:
print(e)
pass
def checkTelemtry():
import subprocess
import sys
scriptPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','aion.py'))
if os.path.exists(scriptPath):
outputStr = subprocess.Popen([sys.executable,scriptPath,'-m','pushtelemetry'])
def SyncTelemetry():
try:
newdata = {}
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'telemetry.db')
if sqlite_obj.table_exists('syncState'):
data = sqlite_obj.read_data('syncState')[0]
param_keys = ['ID','state','syncingTime']
sync_data = dict((x,y) for x,y in zip(param_keys,data))
#print(sync_data['state'],sync_data['syncingTime'])
if sync_data['state'].lower() != 'syncing':
sync_time = sync_data['syncingTime']
now = datetime.now()
currTime = datetime.timestamp(now)
diffTime = int(float(currTime)) - int(float(sync_time))
#print(diffTime)
if int(diffTime) > 86400:
TelemetryUpdateSyncState('Syncing')
SendTelemetryUpdate(sync_time)
TelemetryUpdateSyncState('Done')
else:
TelemetryCreateSyncState('Initialize')
except Exception as e:
print(e)
pass
def UseCaseCreated(Usecase):
try:
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'telemetry.db')
newdata = {}
now = datetime.now()
ID = datetime.timestamp(now)
record_date = int(datetime.timestamp(now))
computername = socket.getfqdn()
macaddress = getmac.get_mac_address()
try:
user = os.getlogin()
except:
user = 'NA'
newdata.update({'ID':[str(int(ID))],'RecordDate': [record_date],'Usecase': [Usecase],'Operation':['Created'],'User':[str(user)],'HostName' :[computername],'MACAddress':[macaddress],'ProblemType':[''],'Algorithms':[''],'EDA':['No'],'Prediction':['No'],'MLaC':['No'],'Drift':['No'],'TrustedAI':['No']})
sqlite_obj.write_data(pd.DataFrame.from_dict(newdata),'logs')
except Exception as e:
print(e)
pass
def UpdateTelemetry(Usecase,operation,value):
try:
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'telemetry.db')
data = sqlite_obj.read_data('logs','Usecase="'+Usecase+'"')
#print(data)
if sqlite_obj.table_exists('logs'):
updated_data = operation+'="'+value+'"'
now = datetime.now()
ID = datetime.timestamp(now)
record_date = int(datetime.timestamp(now))
updated_data += ',"RecordDate"="'+str(record_date)+'"'
sqlite_obj.update_data(updated_data,'Usecase="'+Usecase+'"','logs')
except Exception as e:
print(e)
pass
def SendTelemetryUpdate(sync_time):
file_path = os.path.join(DATA_DIR, 'sqlite')
sqlite_obj = sqlite_db(file_path, 'telemetry.db')
if sqlite_obj.table_exists('logs'):
ddata = sqlite_obj.read_data("logs","RecordDate >= '"+str(sync_time)+"'")
#print(ddata)
keys = sqlite_obj.column_names('logs')
for data in ddata:
now = datetime.now()
ID = datetime.timestamp(now)
item = {}
item['ID'] = str(int(ID))
item['RecordID'] = data[ keys.index('ID')]
item['RecordDate'] = data[ keys.index('RecordDate')]
item['Usecase'] = data[ keys.index('Usecase')]
item['Operation'] = data[ keys.index('Operation')]
item['User'] = data[ keys.index('User')]
item['HostName'] = data[ keys.index('HostName')]
item['MACAddress'] = data[ keys.index('MACAddress')]
item['Algorithms'] = data[ keys.index('Algorithms')]
item['ProblemType'] = data[ keys.index('ProblemType')]
item['EDA'] = data[ keys.index('EDA')]
item['Prediction'] = data[ keys.index('Prediction')]
item['MLaC'] = data[ keys.index('MLaC')]
item['Drift'] = data[ keys.index('Drift')]
item['TrustedAI'] = data[ keys.index('TrustedAI')]
url = 'https://l5m119j6v9.execute-api.ap-south-1.amazonaws.com/default/aion_telemetry'
record = {}
record['TableName'] = 'AION_LOGS'
record['Item'] = item
record = json.dumps(record)
#print(record)
try:
response = requests.post(url, data=record,headers={"x-api-key":"Obzt8ijfOT3dgBYma9JCt1tE3W6tzHaV8rVuQdMK","Content-Type":"application/json",})
except Exception as e:
print(e)
def telemetry_data(operation,Usecase,data):
now = datetime.now()
ID = datetime.timestamp(now)
record_date = now.strftime("%y-%m-%d %H:%M:%S")
computername = socket.getfqdn()
macaddress = getmac.get_mac_address()
try:
user = os.getlogin()
except:
user = 'NA'
item = {}
item['ID'] = str(int(ID))
item['record_date'] = record_date
item['UseCase'] = Usecase
item['operation'] = operation
item['remarks'] = data
item['user'] = str(user)
item['hostname'] = computername
item['macaddress'] = macaddress
url = 'https://l5m119j6v9.execute-api.ap-south-1.amazonaws.com/default/aion_telemetry'
record = {}
record['TableName'] = 'AION_OPERATION'
record['Item'] = item
record = json.dumps(record)
try:
response = requests.post(url, data=record,headers={"x-api-key":"Obzt8ijfOT3dgBYma9JCt1tE3W6tzHaV8rVuQdMK","Content-Type":"application/json",})
check_telemetry_file()
except Exception as inst:
filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),'telemetry.txt')
f=open(filename, "a+")
f.write(record+'\\n')
f.close()
def check_telemetry_file():
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'telemetry.txt')
if(os.path.isfile(file_path)):
f = open(file_path, 'r')
url = 'https://l5m119j6v9.execute-api.ap-south-1.amazonaws.com/default/aion_telemetry'
file_content = f.read()
f.close()
matched_lines = file_content.split('\\n')
write_lines = []
for record in matched_lines:
try:
response = requests.post(url, data=record,headers={"x-api-key":"Obzt8ijfOT3dgBYma9JCt1tE3W6tzHaV8rVuQdMK","Content-Type":"application/json",})
except:
write_lines.append(record)
f = open(file_path, "a")
f.seek(0)
f.truncate()
for record in write_lines:
f.write(record+'\\n')
f.close()
else:
return True<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os
import time
import subprocess
import sys
import json
import pandas as pd
def getDataSetRecordsCount(datalocation):
try:
records = 0
if os.path.isfile(datalocation):
for chunk in pd.read_csv(datalocation, chunksize=20000):
records = records+len(chunk)
if records == 0:
records = 'NA'
except Exception as e:
print(e)
records = 'NA'
return records
def get_train_model_details(deploy_location,request):
updatedConfigFile = request.session['config_json']
f = open(updatedConfigFile, "r")
configSettings = f.read()
f.close()
usename = request.session['usecaseid'].replace(" ", "_")
outputfile = os.path.join(deploy_location,usename,str(request.session['ModelVersion']),'etc','output.json')
if os.path.isfile(outputfile):
f1 = open(outputfile, "r+", encoding="utf-8")
outputStr = f1.read()
f1.close()
resultJsonObj = json.loads(outputStr)
trainingStatus = resultJsonObj['status']
if trainingStatus.lower() == 'success':
details = resultJsonObj['data']
modelType = details['ModelType']
bestModel = details['BestModel']
return trainingStatus,modelType,bestModel
else:
return trainingStatus,'NA','NA'
else:
return 'Not Trained','NA','NA'<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import json
import os
import rsa
import boto3 #usnish
import pandas as pd
import time
def add_new_GCSBucket(request):
try:
file_path = os.path.abspath( | ||
os.path.join(os.path.dirname(__file__),'..','..','config','gcsbuckets.conf'))
with open(file_path, 'r') as f:
data = json.load(f)
f.close()
if data == '':
data = []
except:
data = []
print(request.POST["aionreferencename"])
print(request.POST["serviceaccountkey"])
print(request.POST["bucketname"])
if request.POST["aionreferencename"] =='' or request.POST["serviceaccountkey"] == '' or request.POST["bucketname"] == '' :
return 'error'
newdata = {}
newdata['Name'] = request.POST["aionreferencename"]
newdata['GCSServiceAccountKey'] = request.POST["serviceaccountkey"]
newdata['GCSbucketname'] = request.POST["bucketname"]
data.append(newdata)
with open(file_path, 'w') as f:
json.dump(data, f)
f.close()
return 'success'
def get_gcs_bucket():
try:
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','gcsbuckets.conf'))
with open(file_path, 'r') as f:
data = json.load(f)
except:
data = []
return data
def read_gcs_bucket(name,filename,DATA_FILE_PATH):
try:
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','gcsbuckets.conf'))
with open(file_path, 'r') as f:
data = json.load(f)
except:
data = []
found = False
print(data)
for x in data:
if x['Name'] == name:
GCSServiceAccountKey = x['GCSServiceAccountKey']
GCSbucketname = x['GCSbucketname']
found = True
break
print(found)
print(name)
try:
if found:
import io
from google.cloud import storage
storage_client = storage.Client.from_service_account_json(GCSServiceAccountKey)
print(GCSServiceAccountKey)
print(GCSbucketname)
bucket = storage_client.get_bucket(GCSbucketname)
blob = bucket.blob(filename)
data = blob.download_as_string()
df = pd.read_csv(io.BytesIO(data), encoding = 'utf-8', sep = ',',encoding_errors= 'replace')
return 'Success',df
except Exception as e:
print(e)
return 'Error', pd.DataFrame()<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import json
import os
import pandas as pd
import numpy as np
import subprocess
import sys
import re
import plotly.graph_objects as go
import plotly.figure_factory as ff
def global_explain(request):
try:
selected_use_case = request.session['UseCaseName']
ModelVersion = request.session['ModelVersion']
ModelStatus = request.session['ModelStatus']
updatedConfigFile = request.session['config_json']
f = open(updatedConfigFile, "r")
configSettings = f.read()
f.close()
configSettingsJson = json.loads(configSettings)
problemType = 'classification'
for key in configSettingsJson['basic']['analysisType']:
if configSettingsJson['basic']['analysisType'][key] == 'True':
problemType = key
break
if problemType.lower() != 'classification' and problemType.lower() != 'regression':
return 'Problem Type Error','Explainable AI only available for classification and regression problem','NA','NA','NA','NA',0,0,'NA','NA','NA','NA',0,'NA','NA',0,'NA','NA','NA','NA','NA','NA'
displaypath = os.path.join( request.session['deploypath'],'etc','display.json')
with open(displaypath) as file:
config = json.load(file)
file.close()
inputFeatures = configSettingsJson['basic']['trainingFeatures']
targetFeature = configSettingsJson['basic']['targetFeature']
inputFeatures = inputFeatures.split(',')
if targetFeature in inputFeatures:
inputFeatures.remove(targetFeature)
dataFilePath = str(configSettingsJson['basic']['dataLocation'])
from utils.file_ops import read_df_compressed
status,df = read_df_compressed(config['postprocessedData'],encoding='utf8',nrows=10)
#print(df)
df.rename(columns=lambda x: x.strip(), inplace=True)
df = df[inputFeatures]
#print(df)
singleInstanceData = df.loc[5, inputFeatures]
inputFieldsDict = singleInstanceData.to_dict()
inputFields = []
inputFields.append(inputFieldsDict)
if 'nrows' in config:
nrows = config['nrows']
else:
nrows = 'Not Available'
if 'ncols' in config:
ncols = config['ncols']
else:
ncols = 'Not Available'
if 'targetFeature' in config:
targetFeature = config['targetFeature']
else:
targetFeature = ''
labelMaps = config['labelMaps']
modelfeatures = config['modelFeatures']
mfcount = len(modelfeatures)
df_proprocessed = pd.read_csv(dataFilePath)
if 'targetFeature' != '':
target_classes = df_proprocessed[targetFeature].unique()
numberofclasses = len(target_classes)
else:
target_classes = []
numberofclasses = 'Not Available'
dataPoints = df_proprocessed.shape[0]
df_proprocessed = df_proprocessed.head(5)
df_proprocessed = df_proprocessed.to_json(orient="records")
df_proprocessed = json.loads(df_proprocessed)
expainableAIPath = os.path.join(request.session['deploypath'],'aion_xai.py')
outputStr = subprocess.check_output([sys.executable,expainableAIPath,'global'])
outputStr = outputStr.decode('utf-8')
outputStr = re.search(r'aion_ai_explanation:(.*)',str(outputStr), re.IGNORECASE).group(1)
outputStr = outputStr.strip()
ale_json = json.loads(str(outputStr))
ale_json = ale_json['data']
ale_view = ale_json['data']
sentences = ale_json['sentences']
scoreMessage = ''
feature_importance = ale_json['feature_importance']
dfimp = pd.DataFrame.from_dict(feature_importance)
dfimp = dfimp.sort_values(by=['values'],ascending=False).reset_index()
yaxis_data = dfimp['values'].tolist()
xaxis_data = dfimp['labels'].tolist()
cfig = go.Figure()
cfig.add_trace(go.Bar(x=xaxis_data,y=yaxis_data,name='Feature Importance'))
cfig.update_layout(barmode='stack',xaxis_title='Features')
bargraph = cfig.to_html(full_html=False, default_height=450,default_width=1000)
dftoprecords = dfimp.head(2)
topTwoFeatures = dfimp['labels'].tolist()
topFeaturesMsg = []
for i in range(0,len(dfimp)):
value = round(dfimp.loc[i, "values"],2)*100
value = round(value,2)
tvalue = str(dfimp.loc[i, "labels"])+' contributing to '+ str(value)+'%'
topFeaturesMsg.append(tvalue)
most_influencedfeature = ale_json['most_influencedfeature']
interceppoint = ale_json['interceptionpoint']
anchorjson = ale_json['anchorjson']
return 'Success','Success',ale_view,sentences,bargraph,inputFields,nrows,ncols,targetFeature,dataPoints,target_classes,df_proprocessed,numberofclasses,modelfeatures,problemType,mfcount,topTwoFeatures,topFeaturesMsg,most_influencedfeature,interceppoint,anchorjson,labelMaps
except Exception as Inst:
print(Inst)
return 'Error','Exception: '+str(Inst),'NA','NA','NA','NA',0,0,'NA','NA','NA','NA',0,'NA','NA',0,'NA','NA','NA','NA','NA','NA'<s><s> import json
import os
import sys
import re
import numpy as np
def check_unsupported_col(config): #bugId14444
unsupported_chars = '[]<>#{}@&'
try:
featureList = config['basic']['featureList']
return any([x in y for x in unsupported_chars for y in featureList])
except Exception as e:
print(str(e))
return False
def check_granularity(configSettingsJson,datapath=None):
try:
from AION.appbe.utils import get_true_option
import pandas as pd
from pathlib import Path
seconds_per_unit = {'second':1,'minute':60,'hour':60 * 60,'day':24 * 60 * 60,'week':7 * 24 * 60 * 60,'month':30 * 24 * 60 * 60,'year':365 * 24 * 60 * 60}
if not get_true_option(configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']['aggregation']['type']):
return ''
if isinstance( configSettingsJson['basic']['dateTimeFeature'], list):
datetime_feature = configSettingsJson['basic']['dateTimeFeature'][0]
else:
datetime_feature = configSettingsJson['basic']['dateTimeFeature']
if get_true_option(configSettingsJson['basic']['analysisType']) == 'timeSeriesForecasting' and datetime_feature:
if not datapath:
datapath = configSettingsJson['basic']['dataLocation']
if Path( datapath).exists():
df = pd.read_csv(datapath, nrows=2)
datetime = pd.to_datetime(df[ datetime_feature])
if len(datetime) > 1:
source_time_delta = (datetime[1] - datetime[0]).total_seconds()
granularity_unit = get_true_option(configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']['aggregation']['granularity']['unit'])
size = int(configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']['aggregation']['granularity']['size'])
target_time_delta = size * seconds_per_unit[granularity_unit]
amplify = int(source_time_delta / target_time_delta)
if amplify > 20:
return f'Current Granularity setting will amplify the data approx {amplify} times. Depending on your system configuration, this may cause Memory error'
return ''
except Exception as e:
return ''
def getStatusCount(matched_lines,total_steps):
stepsdone = 0
leaner = True
#print(matched_lines)
for line in matched_lines:
if 'AION feature transformation completed' in line:
stepsdone = stepsdone + 1
elif 'AION feature engineering completed' in line:
stepsdone = stepsdone + 1
elif 'AION Association Rule completed' in line:
stepsdone = stepsdone + 1
elif 'AION Image Classification completed' in line:
stepsdone = stepsdone + 1
elif 'AION Association Rule completed' in line:
stepsdone = stepsdone + 1
elif 'AION State Transition completed' in line:
stepsdone = stepsdone + 1
elif 'AION SurvivalAnalysis completed' in line:
stepsdone = stepsdone + 1
elif 'AION Recommender completed' in line:
stepsdone = stepsdone + 1
elif 'AION Gluon Stop' in line:
stepsdone = stepsdone + 1
elif 'AION Evaluation Stop' in line:
stepsdone = stepsdone + 1
elif 'AION Object Detection completed' in line:
stepsdone = stepsdone + 1
elif ('training completed' in line) and leaner:
stepsdone = stepsdone + 1
leaner = False
elif 'Prediction Service completed' in line:
stepsdone = stepsdone + 1
elif 'AION TimeSeries Forecasting started' in line: #task 11997
stepsdone = stepsdone + 1
elif 'Distributed Learning Completed' in line:
stepsdone = stepsdone + 4
elif 'AION Batch Deployment completed' in line:
stepsdone = stepsdone + 2
match_lines = []
for line in matched_lines:
count = len(line)-len(line.lstrip())
uline = line.split('...')
uline = uline[1]
if count == 0:
uline = '|... <span style="border: 1px solid black; line-height:2; padding: 2px">'+uline+'</span>'
elif count == 8 or count == 1:
uline = ' |... <span style="border: 1px dashed darkblue; line-height:2; padding: 2px">'+uline+'</span>'
elif count == 16 or count == 2:
uline = ' |... <span style="border: 1px dotted darkgray; line-height:2; padding: 2px">'+uline+'</span>'
elif count == 32 or count == 3:
uline = ' |... <span style="border: 1px dotted lightgray ; line-height:2; padding: 2px">'+uline+'</span>'
else:
uline = line
match_lines.append(uline)
stepline = '<b>Stage: ' + str(stepsdone) + '/' + str(total_steps) + ' Complete</b>'
match_lines.insert(0, stepline)
#print(match_lines)
output = "\\n".join([status_text for status_text in match_lines])
output = "<pre>{}</pre>".format(output)
#print(output)
return(output)
def calculate_total_interations(config):
try:
noOfIterations = 0
problemtypes = config['basic']['analysisType']
problem_type = ""
for key in problemtypes:
if config['basic']['analysisType'][key] == 'True':
problem_type = key
break
if problem_type.lower | ||
() in ['classification','regression']:
algorithms = config['basic']['algorithms'][problem_type]
for key in algorithms:
if config['basic']['algorithms'][problem_type][key] == 'True':
if key not in ['Neural Network','Convolutional Neural Network (1D)','Recurrent Neural Network','Recurrent Neural Network (GRU)','Recurrent Neural Network (LSTM)','Deep Q Network','Dueling Deep Q Network']:
if problem_type.lower() == 'classification':
configparam = config['advance']['mllearner_config']['modelParams']['classifierModelParams'][key]
else:
configparam = config['advance']['mllearner_config']['modelParams']['regressorModelParams'][key]
param = paramDefine(configparam,config['advance']['mllearner_config']['optimizationMethod'])
interationsum = 1
for x in param.values():
interationsum = interationsum*len(x)
if config['advance']['mllearner_config']['optimizationMethod'].lower() == 'random':
if interationsum > int(config['advance']['mllearner_config']['optimizationHyperParameter']['iterations']):
interationsum = int(config['advance']['mllearner_config']['optimizationHyperParameter']['iterations'])
noOfIterations = noOfIterations+interationsum
else:
if key in ['Neural Network','Convolutional Neural Network (1D)','Recurrent Neural Network','Recurrent Neural Network (GRU)','Recurrent Neural Network (LSTM)']:
if problem_type.lower() == 'classification':
configparam = config['advance']['dllearner_config']['modelParams']['classifierModelParams'][key]
else:
configparam = config['advance']['dllearner_config']['modelParams']['regressorModelParams'][key]
interationsum = 1
for j in list(configparam.keys()):
if isinstance(configparam[j],(list,dict,tuple,str)):
x = configparam[j].split(',')
interationsum = interationsum*len(x)
noOfIterations = noOfIterations+interationsum
elif key in ['Deep Q Network','Dueling Deep Q Network']:
if problem_type.lower() == 'classification':
configparam = config['advance']['rllearner_config']['modelParams']['classifierModelParams'][key]
interationsum = 1
for j in list(configparam.keys()):
if isinstance(configparam[j],(list,dict,tuple,str)):
x = configparam[j].split(',')
interationsum = interationsum*len(x)
noOfIterations = noOfIterations+interationsum
elif problem_type.lower() in ['llmfinetuning']:
algorithms = config['basic']['algorithms'][problem_type]
for key in algorithms:
if config['basic']['algorithms'][problem_type][key] == 'True':
noOfIterations = configparam = config['advance']['llmFineTuning']['modelParams'][key]['epochs']
break
else:
noOfIterations= 'NA'
except Exception as e:
print(e)
noOfIterations = 'NA'
pass
return(noOfIterations)
def paramDefine(paramSpace, method):
paramDict = {}
for j in list(paramSpace.keys()):
inp = paramSpace[j]
try:
isLog = False
isLin = False
isRan = False
isList = False
isString = False
try:
# check if functions are given as input and reassign paramspace
v = paramSpace[j]
if 'logspace' in paramSpace[j]:
paramSpace[j] = v[v.find("(") + 1:v.find(")")].replace(" ", "")
isLog = True
elif 'linspace' in paramSpace[j]:
paramSpace[j] = v[v.find("(") + 1:v.find(")")].replace(" ", "")
isLin = True
elif 'range' in paramSpace[j]:
paramSpace[j] = v[v.find("(") + 1:v.find(")")].replace(" ", "")
isRan = True
elif 'list' in paramSpace[j]:
paramSpace[j] = v[v.find("(") + 1:v.find(")")].replace(" ", "")
isList = True
elif '[' and ']' in paramSpace[j]:
paramSpace[j] = v.split('[')[1].split(']')[0].replace(" ", "")
isList = True
x = paramSpace[j].split(',')
except:
x = paramSpace[j]
str_arg = paramSpace[j]
# check if arguments are string
try:
test = eval(x[0])
except:
isString = True
if isString:
paramDict.update({j: hp.choice(j, x)} if method == 'bayesopt' else {j: x})
else:
res = eval(str_arg)
if isLin:
y = eval('np.linspace' + str(res))
paramDict.update({j: hp.uniform(j, eval(x[0]), eval(x[1]))} if method == 'bayesopt' else {j: y})
elif isLog:
y = eval('np.logspace' + str(res))
paramDict.update(
{j: hp.uniform(j, 10 ** eval(x[0]), 10 ** eval(x[1]))} if method == 'bayesopt' else {j: y})
elif isRan:
y = eval('np.arange' + str(res))
paramDict.update({j: hp.choice(j, y)} if method == 'bayesopt' else {j: y})
# check datatype of argument
elif isinstance(eval(x[0]), bool):
y = list(map(lambda i: eval(i), x))
paramDict.update({j: hp.choice(j, eval(str(y)))} if method == 'bayesopt' else {j: y})
elif isinstance(eval(x[0]), float):
res = eval(str_arg)
if len(str_arg.split(',')) == 3 and not isList:
y = eval('np.linspace' + str(res))
#print(y)
paramDict.update({j: hp.uniform(j, eval(x[0]), eval(x[1]))} if method == 'bayesopt' else {j: y})
else:
y = list(res) if isinstance(res, tuple) else [res]
paramDict.update({j: hp.choice(j, y)} if method == 'bayesopt' else {j: y})
else:
res = eval(str_arg)
if len(str_arg.split(',')) == 3 and not isList:
y = eval('np.linspace' +str(res)) if eval(x[2]) >= eval(x[1]) else eval('np.arange'+str(res))
else:
y = list(res) if isinstance(res, tuple) else [res]
paramDict.update({j: hp.choice(j, y)} if method == 'bayesopt' else {j: y})
except Exception as inst:
print(inst)
return paramDict
def calculate_total_activities(config):
req_step = 0
problemtypes = config['basic']['analysisType']
problem_type = ""
for key in problemtypes:
if config['basic']['analysisType'][key] == 'True':
problem_type = key
break
Modelproblem = problem_type
if Modelproblem.lower() in ['classification','regression','clustering','anomalydetection','topicmodelling']:
req_step = req_step+4
if Modelproblem.lower() in ['timeseriesforecasting','imageclassification','objectdetection','multilabelprediction','similarityidentification','contextualsearch']: #task 11997
req_step = req_step+2
if Modelproblem.lower() in ['survivalanalysis']:
req_step = req_step+3
if Modelproblem.lower() in ['recommendersystem']:
if config['basic']['algorithms']['recommenderSystem']['ItemRating'] == 'True':
req_step = req_step+3
if config['basic']['algorithms']['recommenderSystem']['AssociationRules-Apriori'] == 'True':
req_step = req_step+1
if Modelproblem.lower() in ['statetransition']:
req_step = req_step+1
return (req_step)
def getModelStatus(Existusecases,modelid):
model = Existusecases.objects.get(id=modelid)
return(model.Status)
def changeModelStatus(Existusecases,modelid,status,problemType,deployPath):
model = Existusecases.objects.get(id=modelid)
model.Status = status
model.ProblemType = problemType
model.DeployPath = deployPath
model.save()
def checkversionrunningstatus(modelid,usecasedetails,Existusecases):
modelx = Existusecases.objects.get(id=modelid)
ConfigPath = str(modelx.ConfigPath)
status = 'Running'
try:
if os.path.exists(ConfigPath):
with open(ConfigPath, 'r') as json_file:
data = json.load(json_file)
json_file.close()
deployPath = str(data['basic']['deployLocation'])
modelName = data['basic']['modelName']
modelVersion = data['basic']['modelVersion']
modelName = modelName.replace(" ", "_")
logfile = os.path.join(deployPath,modelName,str(modelVersion),'log','model_training_logs.log')
print(logfile)
if os.path.exists(logfile):
with open(logfile) as f:
contents = f.read()
f.close()
contents = re.search(r'aion_learner_status:(.*)', str(contents), re.IGNORECASE).group(1)
contents = contents.strip()
print(contents)
if contents != '':
resultJsonObj = json.loads(contents)
odataFile = str(modelx.TrainOuputLocation)
with open(odataFile, 'w') as json_file:
json.dump(resultJsonObj, json_file)
json_file.close()
modelx.Status = resultJsonObj['status']
status = modelx.Status
if resultJsonObj['status'] == 'SUCCESS':
modelx.DeployPath = str(resultJsonObj['data']['deployLocation'])
if resultJsonObj['data']['ModelType'] in ['clustering','anomalydetection']:
modelx.ProblemType = 'unsupervised'
else:
modelx.ProblemType = 'supervised'
modelx.save()
except Exception as e:
pass
return status
def updateLLM_Model_training_logs(deployPath,modelName,modelVersion,model,configPath):
from appbe.prediction import get_instance
hypervisor,instanceid,region,image = get_instance(modelName+'_'+str(modelVersion))
from llm.llm_tuning import llm_logs
cloudconfig = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','config','compute_conf.json'))
llm_logs(configPath,cloudconfig,instanceid,hypervisor,model)
def checkModelUnderTraining(request,usecasedetails,Existusecases):
try:
models = Existusecases.objects.filter(Status='Running')
for model in models:
ConfigPath = str(model.ConfigPath)
try:
if os.path.exists(ConfigPath):
with open(ConfigPath, 'r') as json_file:
data = json.load(json_file)
json_file.close()
deployPath = str(data['basic']['deployLocation'])
modelName = data['basic']['modelName']
modelVersion = data['basic']['modelVersion']
modelName = modelName.replace(" ", "_")
if data['basic']['analysisType']['llmFineTuning'] == 'True':
mlmodels =''
algorihtms = data['basic']['algorithms']['llmFineTuning']
for k in algorihtms.keys():
if data['basic']['algorithms']['llmFineTuning'][k] == 'True':
if mlmodels != '':
mlmodels += ', '
mlmodels += k
updateLLM_Model_training_logs(deployPath,modelName,modelVersion,mlmodels,ConfigPath)
logfile = os.path.join(deployPath,modelName,str(modelVersion),'log','model_training_logs.log')
if os.path.exists(logfile):
with open(logfile,encoding="utf-8") as f:
contents = f.read()
f.close()
contents = re.search(r'aion_learner_status:(.*)', str(contents), re.IGNORECASE).group(1)
contents = contents.strip()
if contents != '':
resultJsonObj = json.loads(contents)
odataFile = str(model.TrainOuputLocation)
with open(odataFile, 'w') as json_file:
json.dump(resultJsonObj, json_file)
json_file.close()
modelx = Existusecases.objects.get(id=model.id)
modelx.Status = resultJsonObj['status']
if resultJsonObj['status'] == 'SUCCESS':
modelx.DeployPath = str(resultJsonObj['data']['deployLocation'])
if resultJsonObj['data']['ModelType'] in ['clustering','anomalydetection']:
modelx.ProblemType = 'unsupervised'
else:
modelx.ProblemType = 'supervised'
modelx.save()
except Exception as e:
print(ConfigPath)
print(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb | ||
.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
pass
except Exception as e:
print(e)
<s> from typing import Union
import numpy as np
import pandas as pd
from sklearn.neighbors import BallTree
def hopkins(data_frame: Union[np.ndarray, pd.DataFrame], sampling_size: int) -> float:
if type(data_frame) == np.ndarray:
data_frame = pd.DataFrame(data_frame)
data_frame_sample = sample_observation_from_dataset(data_frame, sampling_size)
sample_distances_to_nearest_neighbours = get_distance_sample_to_nearest_neighbours(
data_frame, data_frame_sample
)
uniformly_selected_observations_df = simulate_df_with_same_variation(
data_frame, sampling_size
)
df_distances_to_nearest_neighbours = get_nearest_sample(
data_frame, uniformly_selected_observations_df
)
x = sum(sample_distances_to_nearest_neighbours)
y = sum(df_distances_to_nearest_neighbours)
if x + y == 0:
raise Exception("The denominator of the hopkins statistics is null")
return x / (x + y)[0]
def get_nearest_sample(df: pd.DataFrame, uniformly_selected_observations: pd.DataFrame):
tree = BallTree(df, leaf_size=2)
dist, _ = tree.query(uniformly_selected_observations, k=1)
uniformly_df_distances_to_nearest_neighbours = dist
return uniformly_df_distances_to_nearest_neighbours
def simulate_df_with_same_variation(
df: pd.DataFrame, sampling_size: int
) -> pd.DataFrame:
max_data_frame = df.max()
min_data_frame = df.min()
uniformly_selected_values_0 = np.random.uniform(
min_data_frame[0], max_data_frame[0], sampling_size
)
uniformly_selected_values_1 = np.random.uniform(
min_data_frame[1], max_data_frame[1], sampling_size
)
uniformly_selected_observations = np.column_stack(
(uniformly_selected_values_0, uniformly_selected_values_1)
)
if len(max_data_frame) >= 2:
for i in range(2, len(max_data_frame)):
uniformly_selected_values_i = np.random.uniform(
min_data_frame[i], max_data_frame[i], sampling_size
)
to_stack = (uniformly_selected_observations, uniformly_selected_values_i)
uniformly_selected_observations = np.column_stack(to_stack)
uniformly_selected_observations_df = pd.DataFrame(uniformly_selected_observations)
return uniformly_selected_observations_df
def get_distance_sample_to_nearest_neighbours(df: pd.DataFrame, data_frame_sample):
tree = BallTree(df, leaf_size=2)
dist, _ = tree.query(data_frame_sample, k=2)
data_frame_sample_distances_to_nearest_neighbours = dist[:, 1]
return data_frame_sample_distances_to_nearest_neighbours
def sample_observation_from_dataset(df, sampling_size: int):
if sampling_size > df.shape[0]:
raise Exception("The number of sample of sample is bigger than the shape of D")
data_frame_sample = df.sample(n=sampling_size)
return data_frame_sample
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
# def exploratorory_help():
#
#
#
# return (data_overview_tip, feature_importance_tip, correlation_analysis_tip, exploratory_analysis_tip, data_deep_drive_tip, drift_tip)
drift_tip = 'A data distribution represents a list of all of the possible values of each of the variables as provided in the data. Based on how the data values are distributed, it can be mapped to some well-known distribution curves so that the nature of the distribution can be shown.'
data_overview_tip = 'Data Overview give users a quick understanding of the distribution of values across the features and provides summary statistics of the features. It helps to uncover several uncommon and common issues such as unexpected feature values, missing feature values and data skew.'
timeseries_analysis_tip = "Time Series Analysis provides information about the stationarity and seasonality of each of the features in the ingested data."
feature_importance_tip = 'Feature Importance provides a features and grades the features on a scale of relative importance'
correlation_analysis_tip = 'Correlation Analysis provides the strength of relationships among various features. Values range from 0 (least correlation) to 1 (highest correlation). A high correlation means that two or more variables have a strong relationship with each other, while a weak correlation means that the variables are hardly related.'
exploratory_analysis_tip = 'This provides an unsupervised clustering view of the data and provides insights on how the data is distributed. It helps profile the attributes of different clusters and gives insight into underlying patterns of different clusters and find similarities in the data points.'
data_deep_drive_tip = 'Data Deep Dive provides an interactive interface for exploring the relationship between data points across all the different features of a dataset. Each individual item in the visualization represents a data point. Data can be grouped and binned in multiple dimensions based on their feature values.'
pair_graph_tip = 'It is used to present the correlations between two selected features.'
fair_metrics_tip = 'It provides interface to detect the bias in data associated with a sensitive or protected attribute and used for training.'
hopkins_tip =['Since the value is in between (0.0, 0.3), it indicates that the data has a high tendency to cluster.','Since the value is around 0.5, it indicates that the data distriution is random.','Since the value is in between (0.7, 0.99), it indicates that the data is regularly spaced.']
basic_help={'RowFiltering':'You can easily filter rows based on whether the column match a condition or not'}
advance_help = {'NumericFillMethod':'This is used to handle the null values present in the numerical dataset.','NumericFillMethod_Median':'Replace with middle value of the data set. Efficient and not affected by outliers.','NumericFillMethod_Mean':'Replace with average value of the columns. Affected by outliers.','NumericFillMethod_Max':'Replace all nulls with maximum value in the column.','NumericFillMethod_KNN':'This implements KNN algorithm to replace the null','NumericFillMethod_Zero':'Replace the null with 0 value','NumericFillMethod_Drop':'To remove all the null values in the dataset','NumericFillMethod_Min':'Replace all null with minimum value present in the column','CategoricalFillMethod':'This is used to handle the null values present in the categorical dataset.','CategoricalFillMethod_Mode':'Replace with most common values in the dataset. Suggested for categorical columns.','CategoricalFillMethod_Zero':'Replace the null with 0 value.','CategoricalFillMethod_KNN':'This implements KNN algorithm to replace the null','CategoricalFillMethod_Drop':'To remove all the null values in the dataset.','OutlierDetection':'An unusual data point that differs significantly from other data points.','OutlierDetection_IQR':'Identifying the outliers with interquatile range by dividing the data into quartiles.','OutlierDetection_Zscore':'If the z score of a data point is more than 3, it indicates that the data point is an outlier.','OutlierDetection_Isolation':'Randomly sub-sampled data is processed in a tree structure based on randomly selected features.','MissValueRatio':'Permitted Missing Value Ratio i.e., Number of missing values by total number of obervation. If the number of missing value in a columns is more than ratio than the columns will be assumped as empty column','NumericFeatureRatio':'In case column is mix of number and text value. If the number of numeric columns to number of rows ratio is greator than the value mentioned it is assumed as numeric columns and remaining rows which have text values will be removed','NormalStandard':'Standardize features by removing the mean and scaling to unit variance.','NormalMinMax':'This scales and translates each feature individually such that it is in the given range on the training set, e.g. between zero and one.','NormalLogNormal':'When a feature does not follow a linear distributio, that helps minimize skewness and map any distribution to a normal one as close as possible.','RemoveNoise':'Used to remove the noise present in the text data. Noise like special characters, unicode, emojis, hyperlinks,hashtags, html parameters etc.','ExpandContractions':'Contractions are words or combinations of words that are shortened by dropping letters and replacing them by an apostrophe.','Normalize':'Normalization is the process of converting a token into its base form. In the normalization process, the inflectional form of a word is removed so that the base form can be obtained.','Lemmatization':'It is a more effective option than stemming because it converts the word into its root word, rather than just stripping the suffices.','Stemming':'It refers to the removal of suffices, like ing,ly,s etc. by a simple rule-based approach.','NGrams':'The combination of multiple words used together.','PosTags':'The process of classifying words into their parts of speech and labeling them accordingly is known as part-of-speech tagging, or simply POS-tagging.','FeatureSelection':'Feature selection is for filtering irrelevant or redundant features from your dataset. The key difference between feature selection and extraction is that feature selection keeps a subset of the original features while feature extraction creates brand new ones.','FeatureEngineering':'Feature extraction is for creating a new, smaller set of features that stills captures most of the useful information. Again, feature selection keeps a subset of the original features while feature extraction creates new ones.','PCA':'Principle Component Analysis (PCA) is a common feature extraction method in data science. Technically, PCA finds the eigenvectors of a covariance matrix with the highest eigenvalues and then uses those to project the data into a new subspace of equal or less dimensions.','StatisticalBased':'Features are selected on the basis of statistics measures. This method does not depend on the learning algorithm and chooses the features as a pre-processing step. The filter method filters out the irrelevant feature and redundant columns from the model by using different metrics through ranking.','ModelBased':'Different tree-based methods of feature selection help us with feature importance to provide a way of selecting features. Here, feature importance specifies which feature has more importance in model building or has a great impact on the target variable.','CorrelationThreshold':'Correlation Threshold for Statistican Based Feature Selection. Correlation relation analysis done on input features vs target feature and features having correlation value grather then threshold picks for training','PValue':'P Value again for Statistical Based Feature Selection','Variance':'For Feature Selection, features should have higher variance from threshold.','Normalization':'The goal of normalization is to change the values of numeric columns in the dataset to use a common scale , without distoring differences in the ranges of values or losing information.','SVD':'The singular value decomposition (SVD) provides another way to factorize a matrix, into singular vectors and singular values. The SVD allows us to discover some of the same kind of information as the eigendecomposition.','ReplaceAcro':'Replace any abrivations into its full form Eg:{"DM":"DirectMessage"}',
'Factoranalysis':' This algorithm creates factors from the observed variables to represent the common variance i.e. variance due to correlation among the observed variables.','ICA':'ICA stands for Independent Components Analysis and it is a linear dimension reduction method, which transforms the dataset into columns of independent components.','optimizationmethod':'Optimization is the process where we train the model iteratively that results in a maximum and minimum function evaluation.','Random':'Random search is a method in which random combinations of hyperparameters are selected and used to train a model. The best random hyperparameter combinations are used. Random search bears some similarity to grid search.','Grid':'Grid search is essentially an optimization algorithm which lets to select the best parameters for your optimization problemfrom a list of parameter options that provided, hence automating the trial-and-error method.','Bays':'Bayesian optimisation in turn takes into account past evaluations when choosing the hyperparameter set to evaluate next. This approach typically requires less iterations to get to the optimal set of hyperparameter values.','Stopwords':'Stop words are commonly eliminated which are commonly used that they carry very little useful information. They are passed in a list ["Stopword1","Stopword2"]','Tokenization':'It is essentially splitting a phrase, sentence, paragraph, or an entire text document into smaller units, such as individual words or terms. Choose the library for tokenization','Lemma':'In lemmatization, the transformation uses a dictionary to map different variants of a word back to its root format.','Stopwords1':'Stop words are commonly eliminated which are commonly used that they carry very little useful information.Select from the below library to remove them',
'Genetic':'The genetic algorithm repeatedly modifies a population of individual solutions. At each step, the genetic algorithm selects individuals at random from the current population to be parents and uses them to produce the children for the next generation. Over successive generations, the population evolves toward an optimal solution.','CV':'Cross-validation is a resampling procedure used to evaluate machine learning models on a limited data sample. The procedure has a single parameter called k that refers to the number of groups that a given data sample is to be split into.','Ensemble':'Ensemble learning is a general meta approach to machine learning that seeks better predictive performance by combining the predictions from multiple models.','EnsembleStatus':'Enable or disable according to the preference','TargetEncoding':'Target encoding is the process of replacing a categorical value with the mean of the target variable','OneHotEndoding':'Encode categorical features as a one-hot numeric array.','LabelEncoding':'Encode target labels with value between 0 and n_classes-1.','SMCStrategy':'A most_frequent model - The default. In regression the prediction is equal to the mean value, in classification the prediction is equal to the most common value.\\n A uniform model - In regression, selects a random value from the y range. In classification, selects one of the labels by random.\\n A stratified model - Draws the prediction from the distribution of the labels in the train.\\n A tree model - Trains a simple decision tree with a given depth. The depth can be customized using the max_depth parameter.','SMCGain':'The gain is calculated as:\\ngain = (model score - simple score)/(perfect score - simple score)','SMCTreeDepth':'the max depth of the tree (used only if simple model type is tree).','MIcondition':'Measure model average inference time (in seconds) per sample'}<s> from langkit import textstat
from whylogs.experimental.core.udf_schema import udf_schema
import pandas as pd
import whylogs as why
from langkit import light_metrics
from whylogs.experimental.core.udf_schema import udf_schema
from whylogs.experimental.core.udf_schema import register_dataset_udf
import whylogs as why
import json
from sentence_transformers import SentenceTransformer, util
from langkit import lang_config, response_column
def evaluate_prompt_metrics(prompt_msg: any):
""" Evaluate prompt only information."""
text_schema = udf_schema()
llm_schema = light_metrics.init()
df = pd.DataFrame({
"prompt": [
prompt_msg
]})
results = why.log(df, schema=udf_schema()) # .profile()
view = results.view()
automated_readability_index_prompt = view.get_column("prompt.automated_readability_index").to_summary_dict()
automated_readability_index_prompt_mean = automated_readability_index_prompt['distribution/mean']
arip_m = lambda x:1 if x < 1 else (14 if x > 14 else x | ||
)
automated_readability_index_prompt_mean = arip_m(automated_readability_index_prompt_mean)
automated_readability_index_prompt_value = get_readability_index_range_value(automated_readability_index_prompt_mean)
flesch_reading_ease_prompt = view.get_column("prompt.flesch_reading_ease").to_summary_dict()
flesch_reading_ease_prompt_mean = flesch_reading_ease_prompt['distribution/mean']
frep_m = lambda x:1 if x < 1 else (100 if x > 100 else x)
flesch_reading_ease_prompt_mean = frep_m(flesch_reading_ease_prompt_mean)
flesch_reading_ease_prompt_value = get_flesch_reading_ease_prompt_value(flesch_reading_ease_prompt_mean)
prompt_results = {'prompt_readability_score': str(automated_readability_index_prompt_mean),
'prompt_readability_value': automated_readability_index_prompt_value,
'prompt_reading_ease': str(flesch_reading_ease_prompt_mean),
'prompt_reading_ease_value': flesch_reading_ease_prompt_value}
prompt_results_json = json.dumps(prompt_results, indent=4)
return prompt_results_json,prompt_results
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
@register_dataset_udf(["prompt", "response"], "response.relevance_to_prompt")
def similarity_MiniLM_L6_v2(text):
x = text["prompt"]
y = text["response"]
embedding_1 = model.encode(x, convert_to_tensor=True)
embedding_2 = model.encode(y, convert_to_tensor=True)
similarity = util.pytorch_cos_sim(embedding_1, embedding_2)
result = similarity.item()
return result
def get_readability_index_range_value(readability_value):
if readability_value <= 1:
## Grade level Kindergarden to fourth grade
return "Kindergarten"
elif 1 < readability_value <= 2:
## Grade level Kindergarden to fourth grade
return "First Grade"
elif 2 < readability_value <= 3:
## Grade level Fifth grade to Ninth grade
return "Second Grade"
elif 3 < readability_value <= 4:
## Grade level Fifth grade to Ninth grade
return "Third Grade"
elif 4 < readability_value <= 5:
## Grade level Fifth grade to Ninth grade
return "Fourth Grade"
elif 5 < readability_value <= 6:
## Grade level Fifth grade to Ninth grade
return "Fifth Grade"
elif 6 < readability_value <= 7:
## Grade level Fifth grade to Ninth grade
return "Sixth Grade"
elif 7 < readability_value <= 8:
## Grade level Fifth grade to Ninth grade
return "Seventh Grade"
elif 8 < readability_value <= 9:
## Grade level Fifth grade to Ninth grade
return "Eighth Grade"
elif 9 < readability_value <=10:
## Grade level Fifth grade to Ninth grade
return "Ninth Grade"
elif 10 < readability_value <=11:
## Grade level Fifth grade to Ninth grade
return "Tenth Grade"
elif 11 < readability_value <=12:
## Grade level Fifth grade to Ninth grade
return "Eleventh Grade"
elif 12 < readability_value <= 13:
## Grade level Fifth grade to Ninth grade
return "Twelfth Grade"
elif readability_value > 13:
## Grade level Fifth grade to Ninth grade
return "College Grade"
else:
return "College Grade"
def get_flesch_reading_ease_prompt_value(readability_value):
""" Get flesch readability score range approximation"""
if readability_value <= 29:
return "Very Confusing"
elif 29 < readability_value <= 49:
return "Difficult"
elif 49 < readability_value <= 59:
return "Fairly Difficult"
elif 59 < readability_value <= 69:
return "Standard"
elif 69 < readability_value <= 79:
return "Fairly Easy"
elif 79 < readability_value <= 89:
return "Easy"
elif 89 < readability_value <= 100:
return "Very Easy"
else:
return "Very Easy"
def get_relevence_to_response_value(similarity_score):
""" To findout relevence to response results based on similarity score."""
if similarity_score <=0.3:
return "Low"
elif 0.3 < similarity_score <= 0.5:
return "Average"
elif 0.5 < similarity_score <= 0.8:
return "Good"
elif similarity_score > 0.8:
return "High"
def evaluate_prompt_response_inputs (prompt_msg:any, response_msg:any)->str:
""" Predict the text quality, text relevence for both prompt and response messages."""
df = pd.DataFrame({
"prompt": [prompt_msg],
"response": [response_msg]})
results = why.log(df, schema=udf_schema())
view = results.view()
automated_readability_index_prompt = view.get_column("prompt.automated_readability_index").to_summary_dict()
automated_readability_index_prompt_mean = automated_readability_index_prompt['distribution/mean']
arip_m = lambda x:1 if x < 1 else (14 if x > 14 else x)
automated_readability_index_prompt_mean = arip_m(automated_readability_index_prompt_mean)
automated_readability_index_prompt_value = get_readability_index_range_value(automated_readability_index_prompt_mean)
flesch_reading_ease_prompt = view.get_column("prompt.flesch_reading_ease").to_summary_dict()
flesch_reading_ease_prompt_mean = flesch_reading_ease_prompt['distribution/mean']
frep_m = lambda x:1 if x < 1 else (100 if x > 100 else x)
flesch_reading_ease_prompt_mean = frep_m(flesch_reading_ease_prompt_mean)
flesch_reading_ease_prompt_value = get_flesch_reading_ease_prompt_value(flesch_reading_ease_prompt_mean)
automated_readability_index_response = view.get_column("response.automated_readability_index").to_summary_dict()
automated_readability_index_response_mean = automated_readability_index_response['distribution/mean']
arir_m = lambda x:1 if x < 1 else (14 if x > 14 else x)
automated_readability_index_response_mean = arir_m(automated_readability_index_response_mean)
automated_readability_index_response_value = get_readability_index_range_value(automated_readability_index_response_mean)
flesch_reading_ease_response = view.get_column("response.flesch_reading_ease").to_summary_dict()
flesch_reading_ease_response_mean = flesch_reading_ease_response['distribution/mean']
frer_m = lambda x:1 if x < 1 else (100 if x > 100 else x)
flesch_reading_ease_response_mean = frer_m(flesch_reading_ease_response_mean)
flesch_reading_ease_response_value = get_flesch_reading_ease_prompt_value(flesch_reading_ease_response_mean)
relevance_to_response = view.get_column("response.relevance_to_prompt").to_summary_dict()
relevance_to_response_mean = relevance_to_response['distribution/mean']
r2r_m = lambda x:0 if x < 0 else (1 if x > 1 else x)
relevance_to_response_mean = r2r_m(relevance_to_response_mean)
relevance_to_response_value = get_relevence_to_response_value(relevance_to_response_mean)
sentence_count_response = view.get_column("response.sentence_count").to_summary_dict()
sentence_count_response_mean = sentence_count_response['distribution/mean']
word_count_response = view.get_column("response.lexicon_count").to_summary_dict()
word_count_response_mean = word_count_response['distribution/mean']
prompt_response_results = {'prompt_readability_score': str(automated_readability_index_prompt_mean),
'prompt_readability_value': automated_readability_index_prompt_value,
'prompt_reading_ease': str(flesch_reading_ease_prompt_mean),
'prompt_reading_ease_value': flesch_reading_ease_prompt_value,
'response_readability': str(automated_readability_index_response_mean),
'response_readability_value': str(automated_readability_index_response_value),
'response_reading_ease': str(flesch_reading_ease_response_mean),
'response_reading_ease_value': str(flesch_reading_ease_response_value),
'response_sentence_count': str(sentence_count_response_mean),
'response_word_count_response': str(word_count_response_mean),
'relevance_to_response': str(relevance_to_response_mean),
'relevance_to_response_value': relevance_to_response_value
}
final_output_json = json.dumps(prompt_response_results, indent=4)
return final_output_json,prompt_response_results
if __name__ == "__main__":
##Test only prompt message information
option = 'predict'
if option == 'evaluate':
prompt_only_response_msg = "A large language model is an advanced artificial intelligence (AI) system designed to process, understand, and generate human-like text based on massive amounts of data. These models are typically built using deep learning techniques, such as neural networks, and are trained on extensive datasets that include text from a broad range, such as books and websites, for natural language processing.Fine-tuning a large language model involves adjusting and adapting a pre-trained model to perform specific tasks or to cater to a particular domain more effectively. The process usually entails training the model further on a smaller, targeted dataset that is relevant to the desired task or subject matter.Few-shot learning (FSL) can be considered as a meta-learning problem where the model learns how to learn to solve the given problem. In this approach, the model is provided with a very limited number of examples (i.e., “few shots”) from the new task, and it uses this information to adapt and perform well on that task. Adapter Training: Adapter training is a method that involves training lightweight modules that are plugged into the pre-trained model, allowing for fine-tuning on a specific task without affecting the original model’s performance on other tasks.Multi-task Learning: Multi-task learning is a method where the pre-trained model is fine-tuned on multiple tasks simultaneously. This approach enables the model to learn and leverage the shared representations across different tasks, leading to better generalization and performance. Task-specific Fine-tuning: Task-specific fine-tuning is a method where the pre-trained model is fine-tuned on a specific task or domain using a task-specific dataset. This method requires more data and time than transfer learning but can result in higher performance on the specific task. Sequential Fine-tuning: Sequential fine-tuning is a method where a pre-trained model is fine-tuned on multiple related tasks or domains sequentially. This allows the model to learn more nuanced and complex language patterns across different tasks, leading to better generalization and performance.A noteworthy avenue of research within LLM fine-tuning explores strategies to reduce the expenses associated with updating model parameters. This endeavor is the essence of parameter-efficient fine-tuning (PEFT), a collection of techniques aiming to curtail the number of parameters requiring adjustments.Various PEFT techniques exist, and one prominent example is a low-rank adaptation (LoRA), a technique gaining popularity among open-source language models."
prompt_res = evaluate_prompt_metrics(prompt_only_response_msg)
elif option == 'predict':
prompt_msg = "What is AION?"
response_msg = "AION (Artificial Intelligence ONline) is an open -source software platform for building, deploying and operating the entire lifecycle of AI applications. It supports various use cases such as predictive analytics , machine learning and deep learning . Key features: 1. Data Ingestion : Supports multiple data sources like text files, excel sheet, database etc."
evaluation_metrics_json = evaluate_prompt_response_inputs(prompt_msg,response_msg)
print("evaluation_metrics_json: \\n",evaluation_metrics_json)<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import logging
from appbe.dataIngestion import getcommonfields
from appbe.dataIngestion import getusercasestatus
from appbe import service_url
import json
from appbe.dataIngestion import delimitedsetting
import os,sys
import pandas as pd
from django.http import HttpResponse
import time
from appbe.dataPath import LOG_LOCATION
from appbe.log_ut import logg
def get_instance_id(modelID):
from appbe.sqliteUtility import sqlite_db
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
if sqlite_obj.table_exists("LLMTuning"):
data = sqlite_obj.get_data('LLMTuning','usecaseid',modelID)
print(data)
if len(data) > 0:
return (data[3]+' instance '+data[2])
else:
return 'Instance ID not available'
else:
return 'Instance ID not available'
def get_instance(modelID):
from appbe.sqliteUtility import sqlite_db
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
if sqlite_obj.table_exists("LL | ||
MTuning"):
data = sqlite_obj.get_data('LLMTuning','usecaseid',modelID)
if len(data) > 0:
return (data[3],data[2],data[5],data[6])
else:
return '','','',''
else:
return '','','',''
def getprompt(promptfeature,contextFeature,responseFeature,promptFriendlyName,responseFriendlyName,data):
if contextFeature != '':
promptData = data[promptfeature].replace('\\n','')
inputData = data[contextFeature].replace('\\n','')
prompt = (
f"Below is an {promptFriendlyName} that describes a task, paired with an Input that provides further context. "
f"Write a {responseFriendlyName} that appropriately completes the request.\\n\\n"
f"### {promptFriendlyName}:\\n{promptData}\\n\\n### Input:\\n{inputData}\\n\\n### {responseFriendlyName}:\\n")
else:
promptData = data[promptfeature].replace('\\n','')
prompt=(
f"Below is an {promptFriendlyName} that describes a task. "
f"Write a {responseFriendlyName} that appropriately completes the request.\\n\\n"
f"### {promptFriendlyName}:\\n{promptData}\\n\\n### {responseFriendlyName}:\\n")
return prompt
def getDataInstance(problem_type,mlmodels,configSettingsJson):
log = logging.getLogger('log_ux')
delimiters,textqualifier = delimitedsetting(configSettingsJson['basic']['fileSettings']['delimiters'],configSettingsJson['basic']['fileSettings']['textqualifier'])
if problem_type == 'timeSeriesForecasting': #task 11997
inputFieldsDict = {'noofforecasts': 10}
elif problem_type == 'recommenderSystem' and mlmodels =='ItemRating':
inputFieldsDict = {"uid": 1, "iid": 31, "rating": 0}
elif problem_type == 'stateTransition':
inputFeatures = configSettingsJson['basic']['trainingFeatures']
targetFeature = configSettingsJson['basic']['targetFeature']
inputFeaturesList = inputFeatures.split(',')
inputFieldsDict = {inputFeatures:'session',targetFeature:'Activity'}
else:
inputFeatures = configSettingsJson['basic']['trainingFeatures']
targetFeature = configSettingsJson['basic']['targetFeature']
inputFeaturesList = inputFeatures.split(',')
if targetFeature in inputFeaturesList:
inputFeaturesList.remove(targetFeature)
if problem_type == 'survivalAnalysis':
inputFeaturesList.insert(0,configSettingsJson['basic']['dateTimeFeature'])
dataFilePath = str(configSettingsJson['basic']['dataLocation'])
if os.path.isfile(dataFilePath):
df = pd.read_csv(dataFilePath,encoding='utf8',nrows=2,sep=delimiters,quotechar=textqualifier,encoding_errors= 'replace')
try:
singleInstanceData = df.loc[0, inputFeaturesList]
except:
singleInstanceData = pd.Series(0, index =inputFeaturesList)
inputFieldsDict = singleInstanceData.to_dict()
else:
inputFieldsDict = {"File":"EnterFileContent"}
inputFields = []
inputFields.append(inputFieldsDict)
return inputFields
def createInstanceFeatures(configSettingsJson,problem_type,mlmodels,usecaseid,version,ser_url):
delimiters,textqualifier = delimitedsetting(configSettingsJson['basic']['fileSettings']['delimiters'],configSettingsJson['basic']['fileSettings']['textqualifier'])
inputFeatures = configSettingsJson['basic']['trainingFeatures']
targetFeature = configSettingsJson['basic']['targetFeature']
if inputFeatures != '':
inputFeaturesList = inputFeatures.split(',')
else:
inputFeaturesList = []
if targetFeature in inputFeaturesList:
inputFeaturesList.remove(targetFeature)
if configSettingsJson['basic']['contextFeature'] != '':
inputFeaturesList.append(configSettingsJson['basic']['contextFeature'])
if problem_type == 'llmFineTuning':
inputFeaturesList.append('Temperature')
inputFeaturesList.append('Max Tokens')
if problem_type in ['survivalAnalysis','anomalyDetection', 'timeSeriesAnomalyDetection']: #task 11997
if configSettingsJson['basic']['dateTimeFeature'] != '' and configSettingsJson['basic']['dateTimeFeature'] != 'na':
inputFeaturesList.insert(0,configSettingsJson['basic']['dateTimeFeature'])
dataFilePath = str(configSettingsJson['basic']['dataLocation'])
if problem_type == 'timeSeriesForecasting': #task 11997
inputFieldsDict = {'noofforecasts': 10}
elif problem_type == 'recommenderSystem' and mlmodels=='ItemRating':
inputFieldsDict = {"uid": 1, "numberOfRecommendation":10}
elif problem_type == 'stateTransition':
inputFeatures = configSettingsJson['basic']['trainingFeatures']
targetFeature = configSettingsJson['basic']['targetFeature']
if inputFeatures != '':
inputFeaturesList = inputFeatures.split(',')
else:
inputFeaturesList = []
inputFieldsDict = {inputFeatures:'session',targetFeature:'Activity'}
elif problem_type != 'llmFineTuning':
if os.path.isfile(dataFilePath):
df = pd.read_csv(dataFilePath,encoding='utf8',nrows=2,sep=delimiters,quotechar=textqualifier,skipinitialspace = True,encoding_errors= 'replace')
try:
inputFieldsDict = df.to_dict(orient='index')[0]
except:
inputFieldsDict = pd.Series(0, index =inputFeaturesList).to_dict()
else:
inputFieldsDict = {"File":"EnterFileContent"}
else:
inputFieldsDict = pd.Series('', index =inputFeaturesList).to_dict()
inputFieldsDict['Temperature'] = '0.1'
hypervisor,instanceid,region,image = get_instance(usecaseid+'_'+str(version))
if hypervisor.lower() == 'AWS':
inputFieldsDict['Max Tokens'] = '1024'
else:
inputFieldsDict['Max Tokens'] = '4096'
inputFields = []
inputFields.append(inputFieldsDict)
if problem_type == 'llmFineTuning':
ser_url = get_instance_id(usecaseid+'_'+str(version))
elif problem_type == 'stateTransition':
ser_url = ser_url+'pattern_anomaly_predict?usecaseid='+usecaseid+'&version='+str(version)
else:
ser_url = ser_url+'predict?usecaseid='+usecaseid+'&version='+str(version)
return inputFields,ser_url
def singleInstancePredict(request, Existusecases, usecasedetails):
log = logging.getLogger('log_ux')
modelType=''
context = getcommonfields()
submittype = request.POST.get('predictsubmit')
selected_use_case,ModelVersion,ModelStatus = getusercasestatus(request)
t1 = time.time()
try:
try:
model = Existusecases.objects.get(ModelName=request.session['ModelName'],
Version=request.session['ModelVersion'])
output_train_json_filename = str(model.TrainOuputLocation)
f = open(output_train_json_filename, "r+")
training_output = f.read()
f.close()
training_output = json.loads(training_output)
featureused = training_output['data']['featuresused']
except:
featureused = []
from appbe.telemetry import UpdateTelemetry
UpdateTelemetry(request.session['usecaseid']+'-'+str(request.session['ModelVersion']),'Prediction','Yes')
usecasename = request.session['usecaseid'].replace(" ", "_")
context.update({'usecasename':usecasename})
updatedConfigFile = request.session['config_json']
f = open(updatedConfigFile, "r", encoding = "utf-8")
configSettings = f.read()
f.close()
configSettingsJson = json.loads(configSettings)
inputFeatures = configSettingsJson['basic']['trainingFeatures']
targetFeature = configSettingsJson['basic']['targetFeature']
if inputFeatures != '':
inputFeaturesList = inputFeatures.split(',')
else:
inputFeaturesList = []
if targetFeature in inputFeaturesList:
inputFeaturesList.remove(targetFeature)
if configSettingsJson['basic']['contextFeature'] != '':
inputFeaturesList.append(configSettingsJson['basic']['contextFeature'])
problemtypes = configSettingsJson['basic']['analysisType']
problem_type = ''
modelSize = ''
for k in problemtypes.keys():
if configSettingsJson['basic']['analysisType'][k] == 'True':
problem_type = k
break
if problem_type == 'llmFineTuning':
inputFeaturesList.append('Temperature')
inputFeaturesList.append('Max Tokens')
mlmodels =''
algorihtms = configSettingsJson['basic']['algorithms'][problem_type]
for k in algorihtms.keys():
if configSettingsJson['basic']['algorithms'][problem_type][k] == 'True':
if mlmodels != '':
mlmodels += ', '
mlmodels += k
if problem_type == 'llmFineTuning':
ser_url = get_instance_id(usecasename+'_'+str(request.session['ModelVersion']))
if 'modelSize' in configSettingsJson['basic']:
selectedModelSize = configSettingsJson['basic']['modelSize']['llmFineTuning'][mlmodels]
for k in selectedModelSize.keys():
if configSettingsJson['basic']['modelSize']['llmFineTuning'][mlmodels][k] == 'True':
modelSize = k
break
elif problem_type == 'stateTransition':
ser_url = service_url.read_service_url_params(request)
ser_url = ser_url+'pattern_anomaly_predict?usecaseid='+usecasename+'&version='+str(request.session['ModelVersion'])
else:
ser_url = service_url.read_service_url_params(request)
ser_url = ser_url+'predict?usecaseid='+usecasename+'&version='+str(request.session['ModelVersion'])
if submittype.lower() == 'predict':
inputFieldsDict = {}
if problem_type == 'timeSeriesForecasting': #task 11997
inputFieldsDict['noofforecasts'] = int(request.POST.get('noofforecasts'))
elif problem_type == 'stateTransition':
inputFeatures = configSettingsJson['basic']['trainingFeatures']
targetFeature = configSettingsJson['basic']['targetFeature']
sessionid = request.POST.get('SessionID')
activity = request.POST.get(targetFeature)
inputFieldsDict[inputFeatures] = request.POST.get(inputFeatures)
inputFieldsDict[targetFeature] = request.POST.get(targetFeature)
elif problem_type == 'recommenderSystem' and mlmodels == 'ItemRating':
inputFieldsDict['uid'] = request.POST.get('uid')
inputFieldsDict['numberOfRecommendation'] = int(request.POST.get('numberOfRecommendation')) #Task 11190
else:
if problem_type in ['survivalAnalysis','anomalyDetection', 'timeSeriesAnomalyDetection']: #task 11997
if configSettingsJson['basic']['dateTimeFeature'] != '' and configSettingsJson['basic']['dateTimeFeature'] != 'na':
inputFeaturesList.insert(0,configSettingsJson['basic']['dateTimeFeature'])
for feature in inputFeaturesList:
inputFieldsDict[feature] = request.POST.get(feature)
if problem_type.lower() not in ['contextualsearch','similarityidentification']:
for key, value in inputFieldsDict.items():
if value == 'nan':
inputFieldsDict[key] = ''
if value == '':
if key in featureused:
context.update({'tab': 'predict','ser_url':ser_url, 'error': ' Error : Mandatory field(s) are empty', 'selected': 'prediction', 'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,'ModelVersion': ModelVersion})
return context
inputFieldsJson = json.dumps(inputFieldsDict)
if problem_type == 'llmFineTuning':
modelType = request.POST.get('modelTypeforInferencing')
x = inputFieldsDict.keys()
from appbe.dataPath import DATA_DIR
prompt = inputFieldsDict[configSettingsJson['basic']['trainingFeatures']]
promptobj = {'prompt':prompt}
if configSettingsJson['basic']['contextFeature'] != '':
inputData = inputFieldsDict[configSettingsJson['basic']['contextFeature']]
promptobj.update({'input':inputData})
filetimestamp = str(int(time.time()))
file_path = os.path.join(DATA_DIR,'logs',filetimestamp+'.json')
f= open(file_path,"w",encoding="utf-8")
#print(promptobj)
json.dump(promptobj,f)
f.close()
from llm.llm_inference import LLM_predict
cloudconfig = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','config','compute_conf.json'))
hypervisor,instanceid,region,image = get_instance(usecasename+'_'+str(request.session['ModelVersion']))
if hypervisor and instanceid:
if modelSize != '':
mlmodels = mlmodels+'-'+modelSize
cachepath = os.path.join(DATA_DIR,'sqlite','cachePrompt.db')
import sqlite3
conn = sqlite3.connect(cachepath)
from llm.llm_cache import CachePrompt
cachepromptObj = CachePrompt(conn)
searchFlag,result = cachepromptObj.selectFromCache(prompt,usecasename+'_'+str(request.session['ModelVersion']),modelType,temperature=inputFieldsDict['Temperature'],max_token=inputFieldsDict['Max Tokens'])
if searchFlag:
buf = LLM_predict(cloudconfig,instanceid,file_path,hypervisor,mlmodels,usecasename+'_'+str(request.session['ModelVersion']),region,image,inputFieldsDict['Temperature'],inputFieldsDict['Max Tokens'],modelType)
import re
outputStr = buf.split('ModelOutput:')[1]
cachepromptObj.insertRecord(prompt,outputStr,usecasename+'_'+str(request.session['ModelVersion']),modelType,temperature=inputFieldsDict['Temperature'],max_token=inputFieldsDict['Max Tokens'])
else:
outputStr = result
if configSettingsJson['basic']['folderSettings']['fileType'].lower() != 'llm_document':
outputStr = outputStr.split('### '+configSettingsJson['basic']['preprocessing']['llmFineTuning']['friendlyNames']['response']+':')[1]
singlePredictionResults = []
| ||
singlePredictionsummary=""
Results={}
Results['Response'] = outputStr
singlePredictionResults.append(Results)
else:
context.update(
{'tab': 'tabconfigure', 'error': 'Prediction Error: Instance ID not found ', 'selected': 'prediction',
'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,
'ModelVersion': ModelVersion,'mlmodels':mlmodels})
log.info('Predict Instance :' + str(selected_use_case) + ' : ' + str(
ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : Prediction Error, Instance ID not found')
return context
else:
try:
import requests
#response = requests.post(ser_url,auth=(aion_service_username,aion_service_password),data=inputFieldsJson,headers={"Content-Type":"application/json",})
response = requests.post(ser_url,data=inputFieldsJson,headers={"Content-Type":"application/json",})
if response.status_code != 200:
outputStr=response.content
context.update({'tab': 'tabconfigure', 'error': outputStr.decode('utf-8'), 'selected': 'prediction'})
log.info('Predict Instance : '+str(selected_use_case) + ' : ' + str(ModelVersion) + ' : '+'0 '+'sec'+' : '+'Error : '+str(outputStr.decode('utf-8')))
return context
except Exception as inst:
if 'Failed to establish a new connection' in str(inst):
context.update({'tab': 'tabconfigure', 'error': 'AION service need to be started', 'selected': 'prediction', 'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,'ModelVersion': ModelVersion})
log.info('Predict Instance :'+str(selected_use_case) + ' : ' + str(ModelVersion) + ' : '+'0'+' sec'+' : '+'Error : AION service need to be started, '+str(inst))
return context
else:
context.update({'tab': 'tabconfigure', 'error': 'Prediction Error '+str(inst),'selected': 'prediction', 'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,'ModelVersion': ModelVersion})
log.info('Predict Instance :'+str(selected_use_case) + ' : ' + str(ModelVersion) + ' : '+'0 '+'sec'+' : '+'Error : Prediction Error, '+str(inst))
return context
outputStr=response.content
outputStr = outputStr.decode('utf-8','ignore')
outputStr = outputStr.strip()
predict_dict = json.loads(str(outputStr))
#print(predict_dict)
singlePredictionsummary=""
if (predict_dict['status'] == 'SUCCESS'):
data = predict_dict['data']
singlePredictionResults = []
Results = {}
if problem_type == 'multiModalLearning':
data = data[0]
Results['prediction'] = data['predict']
singlePredictionResults.append(Results)
if problem_type == 'textSummarization':
data = data[0]
Results['msg'] = predict_dict['msg']
singlePredictionResults.append(Results)
Results['prediction'] = predict_dict['data']
singlePredictionResults.append(Results)
Results1 = {}
Results1['prediction'] = predict_dict['data']
print("prdata------------",predict_dict['data'])
singlePredictionsummary=predict_dict['data']
print("singlePredictionsummary",singlePredictionsummary)
t2 = time.time()
elif problem_type == 'multiLabelPrediction':
prediction = ''
for x in data:
for y in x:
if 'predict' in y:
if prediction != '':
prediction += ','
prediction += str(y)+':'+str(x[y])
Results['prediction'] = prediction
singlePredictionResults.append(Results)
elif problem_type == 'timeSeriesForecasting': #task 11997
Results['prediction'] = json.dumps(data)
singlePredictionResults.append(Results)
elif problem_type == 'stateTransition':
if str(data['Anomaly']) == 'False':
Results['prediction'] = 'No Anomaly'
else:
Results['prediction'] = str(data['Remarks'])
singlePredictionResults.append(Results)
elif problem_type.lower() in ['similarityidentification','contextualsearch']:
data = data[0]
prediction = data['prediction']
i = 1
for x in prediction:
te = ''
for y in x:
info = (str(x[y])[:50] + '...') if len(str(x[y])) > 50 else str(x[y])
te += y+': '+info+'\\n\\n'
Results[i] = te
i = i+1
singlePredictionResults.append(Results)
else:
data = data[0]
if 'prediction' in data:
Results['prediction'] = data['prediction']
if 'probability' in data:
Results['probability'] = data['probability']
if 'remarks' in data:
Results['remarks'] = json.loads(data['remarks'])
singlePredictionResults.append(Results)
t2 = time.time()
log.info('Predict Instance : '+str(selected_use_case) + ' : ' + str(ModelVersion) + ' : '+str(round(t2-t1))+' sec'+' : '+'Success')
else:
context.update({'tab': 'tabconfigure', 'error': 'Prediction Error '+str(predict_dict['message']), 'selected': 'prediction','selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,'ModelVersion': ModelVersion})
log.info('Predict Instance : '+str(selected_use_case) + ' : ' + str(ModelVersion) + ' : '+'0 '+'sec'+' : '+'Error : Prediction Error')
return context
inputFields = []
inputFields.append(inputFieldsDict)
##Below added by sjayaram for llm langkit evaluation metrics Task:17109
prompt_response_results = ''
if problem_type == 'llmFineTuning':
try:
response_msg = outputStr
prompt_msg = prompt
except:
response_msg = ''
prompt_msg = ''
from appbe.evaluate_prompt import evaluate_prompt_response_inputs
final_output_json,prompt_response_results = evaluate_prompt_response_inputs(prompt_msg,response_msg)
#ser_url = service_url.read_service_url_params(request)
#ser_url = ser_url+'predict?usecaseid='+usecasename+'&version='+str(ModelVersion)
context.update({'tab': 'predict','mlmodels':mlmodels,'fineTunedModelType':modelType,'ser_url':ser_url, 'inputFields': inputFields,'singlePredictionResults': singlePredictionResults,'singlePredictionsummary':singlePredictionsummary,'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,'ModelVersion': ModelVersion, 'selected': 'prediction',
'prompt_response_results':prompt_response_results})
return context
elif submittype.lower() == 'script':
scriptdata="'''\\n"
scriptdata+="* =============================================================================\\n"
scriptdata+="* COPYRIGHT NOTICE\\n"
scriptdata+="* =============================================================================\\n"
scriptdata+="* @ Copyright HCL Technologies Ltd. 2021, 2022, 2023\\n"
scriptdata+="* Proprietary and confidential. All information contained herein is, and\\n"
scriptdata+="* remains the property of HCL Technologies Limited. Copying or reproducing the\\n"
scriptdata+="* contents of this file, via any medium is strictly prohibited unless prior\\n"
scriptdata+="* written permission is obtained from HCL Technologies Limited.\\n"
scriptdata+="'''\\n"
scriptdata+='import sys\\n'
scriptdata+='import json\\n'
scriptdata+='import requests\\n'
scriptdata+='import pandas as pd\\n'
scriptdata+='from pandas import json_normalize\\n'
scriptdata+='ser_url ="'+ser_url+'"\\n\\n'
scriptdata+="def predict(data):\\n"
scriptdata+=" if data.endswith('.tsv'):\\n"
scriptdata+=" df=pd.read_csv(data,encoding='utf-8',encoding_errors= 'replace',sep='\\\\t')\\n"
scriptdata+=" else:\\n"
scriptdata+=" df=pd.read_csv(data,encoding='utf-8',encoding_errors= 'replace')\\n"
scriptdata+=' features = "'+",".join([feature for feature in inputFeaturesList])+'"\\n'
scriptdata+=" features = features.split(',')\\n"
scriptdata+=" df = df[features]\\n"
scriptdata+=" data = df.to_json(orient='records')\\n"
scriptdata+=" try:\\n"
scriptdata+=' response = requests.post(ser_url,data=data,headers={"Content-Type":"application/json",})\\n'
scriptdata+=" if response.status_code == 200:\\n"
scriptdata+=" outputStr=response.content\\n"
scriptdata+=" outputStr = outputStr.decode('utf-8')\\n"
scriptdata+=" outputStr = outputStr.strip()\\n"
scriptdata+=" predict_dict = json.loads(str(outputStr))\\n"
scriptdata+=" print(predict_dict)\\n"
scriptdata+=" except Exception as e:\\n"
scriptdata+=' print(e)\\n'
scriptdata+='\\nif __name__ == "__main__":\\n'
scriptdata+=' predict(sys.argv[1])'
response = HttpResponse()
response['content_type'] = 'text/plain'
response['Content-Disposition'] = 'attachment; filename=prediction.py'
response.write(scriptdata)
return response
except Exception as inst:
print(inst)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type) + ' ' + str(fname) + ' ' + str(exc_tb.tb_lineno))
context.update({'tab': 'tabconfigure', 'error': 'Failed To perform prediction','selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,'ModelVersion': ModelVersion, 'selected': 'prediction'})
log.info('Predict Instance :' + str(selected_use_case) + ' : ' + str(ModelVersion) + ' : ' + ' 0 ' + 'sec' + ' : ' + 'Error : Failed To perform prediction, '+ str(inst))
return context
<s> import os
import openai
from langchain.llms import AzureOpenAI
from sentence_transformers.SentenceTransformer import SentenceTransformer
import time
import datetime
import pandas as pd
import sys
import subprocess
import importlib
from appbe.aion_config import get_llm_data
from appbe.dataPath import DATA_FILE_PATH
remote_data_dir = "/home/aion/data/storage/llm_testing_data"
remote_data_processeddata_dir = '/home/aion/data/storage/processed_data'
remote_config_dir = '/home/aion/data/config'
sh_file_path = '/home/aion/llm/sbin/llm_testing.sh'
prompt_command = '/home/aion/llm/sbin/llm_testing.sh'
PRE_CONTEXT = "Answer the following question in a concise manner.\\n"
DEFAULT_PARAMS = {
'OPENAI_API_TYPE' : "azure",
'OPENAI_API_BASE' : "",
'OPENAI_API_KEY' : "",
'OPENAI_API_VERSION' : "2023-03-15-preview"
}
faq=""
def getAMIDetails(config,selectedAMI):
y = {}
for x in config:
print(x)
if x['id'] == selectedAMI:
return x
return y
class test_LLM():
def __init__(self,
deployment_name='Text-Datvinci-03', params=DEFAULT_PARAMS, transformer=None,
sentence_txfr_model='sentence-transformers/paraphrase-mpnet-base-v2'):
self.deployment_name=deployment_name
self.set_params( params)
self.transformer = transformer
self.sentence_txfr_model = sentence_txfr_model
def fiddlerAuditorCheck(self):
status = importlib.util.find_spec('auditor')
if not status:
subprocess.check_call([sys.executable, "-m", "pip","uninstall", "-q","-y","notebook"])
subprocess.check_call([sys.executable, "-m", "pip", "install","-q", "notebook==6.4.5" ])
subprocess.check_call([sys.executable, "-m", "pip", "install","-q","fiddler-auditor==0.0.2"])
subprocess.check_call([sys.executable, "-m", "pip", "install","-q","notebook==7.0.2"])
status = importlib.util.find_spec('auditor')
return status
def set_params(self, params={}):
valid_params = ['OPENAI_API_TYPE','OPENAI_API_KEY','OPENAI_API_BASE','OPENAI_API_VERSION']
for key, value in params.items():
if 'OPENAI_API_TYPE' == key:
openai.api_type = value
os.environ['OPENAI_API_TYPE'] = openai.api_type
elif 'OPENAI_API_KEY' == key:
openai.api_key = value
os.environ['OPENAI_API_KEY'] = openai.api_key
elif 'OPENAI_API_BASE' == key:
openai.api_base = value
os.environ['OPENAI_API_BASE'] = openai.api_base
elif key in valid_params:
os.environ[key] = value
def run(self,modelName, temperature, similarity_threshold, perturbations_per_sample, prompts, reference_generation,pre_context=PRE_CONTEXT):
if not self.fiddlerAuditorCheck():
raise ValueError('Fiddler-auditor is not instlled "python -m pip install fiddler-auditor==0.0.2"')
openai_llm = AzureOpenAI(deployment_name=self.deployment_name, temperature=temperature, openai_api_key=open | ||
ai.api_key)
from auditor.perturbations import Paraphrase
from auditor.evaluation.expected_behavior import SimilarGeneration
from auditor.evaluation.evaluate import LLMEval
# For Azure OpenAI, it might be the case the api_version for chat completion
# is different from the base model so we need to set that parameter as well.
if self.transformer:
azure_perturber = self.transformer
else:
azure_perturber = Paraphrase(
model="GPT-35-Turbo",
api_version="2023-03-15-preview",
num_perturbations=perturbations_per_sample,
)
sent_xfmer = SentenceTransformer(self.sentence_txfr_model)
similar_generation = SimilarGeneration(
similarity_model=sent_xfmer,
similarity_threshold=similarity_threshold,)
llm_eval = LLMEval(
llm=openai_llm,
expected_behavior=similar_generation,
transformation=azure_perturber,)
test_result = llm_eval.evaluate_prompt_correctness(
prompt=prompts,
pre_context=pre_context,
reference_generation=reference_generation,
perturbations_per_sample=perturbations_per_sample
)
return test_result
def runmultiple(self,modelName, temperature, similarity_threshold, perturbations_per_sample, prompts, reference_generation,pre_context=PRE_CONTEXT,faq=faq):
if not self.fiddlerAuditorCheck():
raise ValueError('Fiddler-auditor is not instlled "python -m pip install fiddler-auditor==0.0.2"')
from auditor.evaluation.expected_behavior import SimilarGeneration
from auditor.evaluation.evaluate import LLMEval
openai_llm = AzureOpenAI(deployment_name=self.deployment_name, temperature=temperature, openai_api_key=openai.api_key)
from auditor.perturbations import Paraphrase
# For Azure OpenAI, it might be the case the api_version for chat completion
# is different from the base model so we need to set that parameter as well.
if self.transformer:
azure_perturber = self.transformer
else:
azure_perturber = Paraphrase(
model="GPT-35-Turbo",
api_version="2023-03-15-preview",
num_perturbations=perturbations_per_sample,
)
sent_xfmer = SentenceTransformer(self.sentence_txfr_model)
similar_generation = SimilarGeneration(
similarity_model=sent_xfmer,
similarity_threshold=similarity_threshold,)
llm_eval = LLMEval(
llm=openai_llm,
expected_behavior=similar_generation,
transformation=azure_perturber,)
rows = faq.shape[0]
prompts = list(faq['Question'])
listofDf = []
for i in range(rows):
test_result = llm_eval.evaluate_prompt_robustness(
prompt=prompts[i],
pre_context=pre_context,
)
try:
now = datetime.datetime.now().strftime("%H%M%S")
name = str(i)+str(now)+'.html'
test_result.save(name)
df_iter=pd.read_html(name)
df_actual = df_iter[0]
listofDf.append(df_actual)
except:
pass
perturbatedDF = pd.concat(listofDf)
return perturbatedDF
def run_offline_model(self, usecasename,modelName, temperature, similarity_threshold, perturbations_per_sample, reference_generation, prompts,isfinetuned):
from appbe.compute import readComputeConfig
from appbe.prediction import get_instance
cloud_infra = readComputeConfig()
dataFile = os.path.join(DATA_FILE_PATH, 'prompt.csv')
remoteFile = os.path.join(remote_data_dir, 'prompt.csv')
if not reference_generation:
reference_generation = ''
prompt = pd.DataFrame([{'prompts':prompts, 'reference_generation':reference_generation}])
prompt.to_csv(dataFile, index=False)
hypervisor, instanceid, region, image = get_instance(usecasename)
key, url, api_type, api_version = get_llm_data()
if hypervisor == 'AWS':
aws_access_key_id = cloud_infra['awsCredentials']['accessKey']
aws_secret_key = cloud_infra['awsCredentials']['secretAccessKey']
currentDirectory = os.path.dirname(os.path.abspath(__file__))
LLM_DIR = os.path.normpath(os.path.join(currentDirectory, '..', 'llm'))
if image != '' and image != 'NA':
amiDetails = getAMIDetails(cloud_infra['AWS_EC2']['amis'], image)
else:
amiDetails = getAMIDetails(cloud_infra['AWS_EC2']['instances'], instanceid)
if region == '' or region == 'NA':
region = amiDetails['regionName']
from llm.aws_instance_api import start_instance
# print(aws_access_key_id, aws_secret_key, instanceid, region)
status, msg, ip = start_instance(aws_access_key_id, aws_secret_key, instanceid, region)
if status.lower() == 'success':
pem_file = os.path.join(LLM_DIR, amiDetails['ssh']['keyFilePath'])
username = amiDetails['ssh']['userName']
# cope file to server for sinfle prompt
from AION.llm.ssh_command import copy_files_to_server
copy_files_to_server(ip,pem_file,dataFile,'',username,'',remote_data_dir,remote_config_dir)
if isfinetuned:
command = prompt_command + ' ' + usecasename + ' ' + str(modelName) \\
+ ' ' + str(temperature) + ' ' + str(similarity_threshold) + ' ' \\
+ str(perturbations_per_sample) + \\
' '+ str(key) + \\
' '+ str(url) + \\
' '+ str(api_type) + \\
' '+ str(api_version)+ \\
' '+ str("single")
else:
command = prompt_command + ' ' + 'BaseModel' + ' ' + str(modelName) \\
+ ' ' + str(temperature) + ' ' + str(similarity_threshold) + ' ' \\
+ str(perturbations_per_sample) + \\
' '+ str(key) + \\
' '+ str(url) + \\
' '+ str(api_type) + \\
' '+ str(api_version)+ \\
' '+ str("single")
from llm.ssh_command import run_ssh_cmd
buf = run_ssh_cmd(ip, pem_file, username, '', '', command)
print(buf)
return buf
def run_multiple_offline_model(self, usecasename,modelName, temperature, similarity_threshold, perturbations_per_sample, faq,isfinetuned):
dataFile = os.path.join(DATA_FILE_PATH, 'prompt.csv')
remoteFile = os.path.join(remote_data_dir, 'prompt.csv')
faq.to_csv(dataFile, index=False)
print("This is done")
from appbe.compute import readComputeConfig
from appbe.prediction import get_instance
cloud_infra = readComputeConfig()
hypervisor, instanceid, region, image = get_instance(usecasename)
key, url, api_type, api_version = get_llm_data()
if hypervisor == 'AWS':
aws_access_key_id = cloud_infra['awsCredentials']['accessKey']
aws_secret_key = cloud_infra['awsCredentials']['secretAccessKey']
currentDirectory = os.path.dirname(os.path.abspath(__file__))
LLM_DIR = os.path.normpath(os.path.join(currentDirectory, '..', 'llm'))
if image != '' and image != 'NA':
amiDetails = getAMIDetails(cloud_infra['AWS_EC2']['amis'], image)
else:
amiDetails = getAMIDetails(cloud_infra['AWS_EC2']['instances'], instanceid)
if region == '' or region == 'NA':
region = amiDetails['regionName']
from llm.aws_instance_api import start_instance
# print(aws_access_key_id, aws_secret_key, instanceid, region)
status, msg, ip = start_instance(aws_access_key_id, aws_secret_key, instanceid, region)
if status.lower() == 'success':
pem_file = os.path.join(LLM_DIR, amiDetails['ssh']['keyFilePath'])
username = amiDetails['ssh']['userName']
#print(ip,pem_file,promptfile,'',username,'',remote_data_dir,remote_config_dir)
from AION.llm.ssh_command import copy_files_to_server
copy_files_to_server(ip,pem_file,dataFile,'',username,'',remote_data_dir,remote_config_dir)
if isfinetuned:
command = prompt_command + ' ' + usecasename + ' ' + str(modelName) \\
+ ' ' + str(temperature) + ' ' + str(similarity_threshold) + ' ' \\
+ str(perturbations_per_sample) + \\
' '+ str(key) + \\
' '+ str(url) + \\
' '+ str(api_type) + \\
' '+ str(api_version)+ \\
' '+ str("multiple")
else:
command = prompt_command + ' ' + 'BaseModel' + ' ' + str(modelName) \\
+ ' ' + str(temperature) + ' ' + str(similarity_threshold) + ' ' \\
+ str(perturbations_per_sample) + \\
' '+ str(key) + \\
' '+ str(url) + \\
' '+ str(api_type) + \\
' '+ str(api_version)+ \\
' '+ str("multiple")
from llm.ssh_command import run_ssh_cmd
buf = run_ssh_cmd(ip, pem_file, username, '', '', command)
print(buf)
return buf
<s> import pandas as pd
import numpy as np
def get_leaderboard(file_content):
matched_lines = [line.replace('Model:-', '') for line in file_content.split('\\n') if "Model:-" in line]
df = pd.DataFrame(columns = ['Model', 'Iterations', 'Score (%)', 'Score Type', 'Best Score (%)'])
import re
try:
for line in matched_lines:
if 'Model Name::' in line:
MODEL = line.split('::')
model = MODEL[1]
if 'ScoringType::' in line:
S = line.split('::')
#SC = ScorTyp[1]
if 'make_scorer'in line:
ST = line.split('make_scorer')
ScorTyp = ST[1]
df['Score Type'] = np.where(df['Model'] == model, ScorTyp,df['Score Type'])
if 'Validation Score::' in line:
BS = line.split('::')
BestSc = round(float(BS[1]), 4)*100
BestSc = abs(BestSc)
df['Best Score (%)'] = np.where(df['Model'] == model, BestSc, df['Best Score (%)'])
if 'Iteration::' in line:
l = line.split('::')
word = re.findall(r'\\[(.*?)\\]', l[1])
if ';, score=' in line:
sc = line.split('score=')
SCR = sc[1].split(' ')
Score = round(float(SCR[0]), 4)*100
Score = abs(Score)
# df = df.concat({'Model': model, 'Iterations': word,'Score (%)': Scor,'Score Type': '', 'Best Score (%)': 0}, ignore_index=True)
newdf = pd.DataFrame([{'Model': model, 'Iterations': word,'Score (%)': Score,'Score Type': '', 'Best Score (%)': 0}])
df = pd.concat([df,newdf],axis=0, ignore_index=True)
LIST = []
for i in range(int(len(df['Score (%)'])/5)):
l = (sum(df['Score (%)'][5*i:5*(i+1)])/5)
#LIST.concat(l)
LIST.append(l)
for i in range(len(LIST)):
df['Score (%)'][5*i:5*(i+1)]=LIST[i]
CL = [line.replace('------->Type of Model :classification', 'Model :classification') for line in file_content.split('\\n') if "------->Type of Model :classification" in line]
for l in CL:
if 'Model :classification' in l:
df = df.sort_values(by = ['Best Score (%)'], ascending=False)
RE = [line.replace('------->Type of Model :regression', 'Model :regression') for line in file_content.split('\\n') if "------->Type of Model :regression" in line]
for l in RE:
if 'Model :regression' in l:
df = df.sort_values(by = ['Best Score (%)'])
except Exception as e:
print(e)
return df
if __name__ == "__main__":
file_path = r"C:\\Users\\richard.mochahari\\AppData\\Local\\Programs\\HCLTech\\AION\\data\\target\\AI0335\\1\\log\\model_training_logs.log"
my_file = open(file_path, 'r')
file_content = my_file.read()
my_file.close()
print(get_leaderboard(file_content))<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import sqlite3
from pathlib import Path
import json
import os
import rsa
import boto3 #usnish
import pandas as pd
import time
import sqlite3
class sqlite_db():
def __init__(self, location, database_file=None):
if not isinstance(location, Path):
location = Path(location)
if database_file:
| ||
self.database_name = database_file
else:
self.database_name = location.stem
db_file = str(location/self.database_name)
self.conn = sqlite3.connect(db_file)
self.cursor = self.conn.cursor()
def table_exists(self, name):
query = f"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}';"
listOfTables = self.cursor.execute(query).fetchall()
return len(listOfTables) > 0
def read_data(self, table_name):
query = f"SELECT * FROM {table_name}"
row = self.cursor.execute(query).fetchall()
return list(row)
#return pd.read_sql_query(f"SELECT * FROM {table_name}", self.conn)
def create_table(self,name, columns, dtypes):
query = f'CREATE TABLE IF NOT EXISTS {name} ('
for column, data_type in zip(columns, dtypes):
query += f"'{column}' TEXT,"
query = query[:-1]
query += ');'
self.conn.execute(query)
return True
def delete_record(self,table_name,col_name, col_value):
try:
query = f"DELETE FROM {table_name} WHERE {col_name}='{col_value}'"
self.conn.execute(query)
self.conn.commit()
return 'success'
except Exception as e :
print(str(e))
print("Deletion Failed")
return 'error'
def get_data(self,table_name,col_name,col_value):
query = f"SELECT * FROM {table_name} WHERE {col_name}='{col_value}'"
row = self.cursor.execute(query).fetchone()
if(row == None):
return []
return list(row)
def write_data(self,data, table_name):
if not self.table_exists(table_name):
self.create_table(table_name, data.columns, data.dtypes)
tuple_data = list(data.itertuples(index=False, name=None))
insert_query = f'INSERT INTO {table_name} VALUES('
for i in range(len(data.columns)):
insert_query += '?,'
insert_query = insert_query[:-1] + ')'
self.cursor.executemany(insert_query, tuple_data)
self.conn.commit()
return True
def close(self):
self.conn.close()
def add_new_azureStorage(request):
try:
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
if request.POST["azurename"] =='' or request.POST["azureaccountkey"] == '' or request.POST["containername"] == '' :
return 'error'
newdata = {}
newdata['azurename'] = [request.POST["azurename"]]
newdata['azureaccountkey'] = [request.POST["azureaccountkey"]]
newdata['containername'] = [request.POST["containername"]]
name = request.POST["azurename"]
if sqlite_obj.table_exists("azurebucket"):
if(len(sqlite_obj.get_data('azurebucket','azurename',name))>0):
return 'error1'
sqlite_obj.write_data(pd.DataFrame.from_dict(newdata),'azurebucket')
except:
return 'error'
def get_azureStorage():
try:
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
temp_data = sqlite_obj.read_data('azurebucket')
data = []
for x in temp_data:
data_dict = {}
data_dict['azurename'] = x[0]
data_dict['azureaccountkey'] = x[1]
data_dict['containername'] = x[2]
data.append(data_dict)
except Exception as e:
print(e)
data = []
return data
def read_azureStorage(name,directoryname,DATA_FILE_PATH):
try:
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
data = sqlite_obj.get_data('azurebucket','azurename',name)
except:
data = []
found = False
if len(data)!=0:
storage_account_name = str(data[0])
storage_account_key = str(data[1])
azure_container_name = data[2]
found = True
try:
if found:
root_dir = str(directoryname)
from azure.storage.filedatalake import DataLakeServiceClient
import io
import pandavro as pdx
from detect_delimiter import detect
try:
service_client = DataLakeServiceClient(account_url="{}://{}.dfs.core.windows.net".format("https", storage_account_name), credential=storage_account_key)
print(azure_container_name)
file_system_client = service_client.get_file_system_client(azure_container_name)
print(root_dir)
file_paths = file_system_client.get_paths(path=root_dir)
main_df = pd.DataFrame()
for path in file_paths:
if not path.is_directory:
file_client = file_system_client.get_file_client(path.name)
file_ext = os.path.basename(path.name).split('.', 1)[1]
if file_ext in ["csv", "tsv"]:
with open(csv_local, "wb") as my_file:
download = file_client.download_file()
download.readinto(my_file)
with open(csv_local, 'r') as file:
data = file.read()
row_delimiter = detect(text=data, default=None, whitelist=[',', ';', ':', '|', '\\t'])
processed_df = pd.read_csv(csv_local, sep=row_delimiter)
if file_ext == "parquet":
download = file_client.download_file()
stream = io.BytesIO()
download.readinto(stream)
processed_df = pd.read_parquet(stream, engine='pyarrow')
if file_ext == "avro":
with open(avro_local, "wb") as my_file:
download = file_client.download_file()
download.readinto(my_file)
processed_df = pdx.read_avro(avro_local)
if not main_df.empty:
main_df = main_df.append(processed_df, ignore_index=True)
else:
main_df = pd.DataFrame(processed_df)
except Exception as e:
msg = str(e).split(".")[0]
print(msg)
return 'Error',str(msg), pd.DataFrame()
return "Success","",main_df
except:
return 'Error',"Please check bucket configuration", pd.DataFrame()
def remove_azure_bucket(name):
from appbe.dataPath import DATA_DIR
file_path = os.path.join(DATA_DIR,'sqlite')
sqlite_obj = sqlite_db(file_path,'config.db')
return sqlite_obj.delete_record('azurebucket','azurename',name)<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import pandas as pd
import json
import os,sys
from appbe import help_Text as ht
def save(request):
from appbe.dataPath import DEFAULT_FILE_PATH
if request.method == 'POST':
submittype = request.POST.get('AdvanceSubmit')
if submittype != 'AdvanceDefault':
configFile = request.session['config_json']
f = open(configFile, "r+")
configSettingsData = f.read()
configSettings = json.loads(configSettingsData)
try:
if configSettings['basic']['analysisType']['llmFineTuning'].lower() == 'false':
numericselectedmethod = request.POST.get('numericfillmethod')
for x in list(configSettings['advance']['profiler']['numericalFillMethod'].keys()):
configSettings['advance']['profiler']['numericalFillMethod'][x] = 'False'
configSettings['advance']['profiler']['numericalFillMethod'][numericselectedmethod] = 'True'
categoricalselectedmethod = request.POST.get('categorialfillmethod')
for x in list(configSettings['advance']['profiler']['categoricalFillMethod'].keys()):
configSettings['advance']['profiler']['categoricalFillMethod'][x] = 'False'
configSettings['advance']['profiler']['categoricalFillMethod'][categoricalselectedmethod] = 'True'
categoryEncodingMethod = request.POST.get('categoryencoding')
for x in list(configSettings['advance']['profiler']['categoryEncoding'].keys()):
configSettings['advance']['profiler']['categoryEncoding'][x] = 'False'
configSettings['advance']['profiler']['categoryEncoding'][categoryEncodingMethod] = 'True'
outlierDetection = request.POST.get('outlierDetection')
for x in list(configSettings['advance']['profiler']['outlierDetection'].keys()):
configSettings['advance']['profiler']['outlierDetection'][x] = 'False'
if outlierDetection != 'Disable':
configSettings['advance']['profiler']['outlierDetection'][outlierDetection] = 'True'
#configSettings['advance']['profiler']['outlierDetectionStatus'] = request.POST.get('AnamolyDetectionStatus')
#configSettings['advance']['profiler']['outlierDetectionMethod'] = request.POST.get('AnaTreatmentMethod')
configSettings['advance']['profiler']['misValueRatio'] = request.POST.get('MisValueRatio')
#configSettings['advance']['profiler']['categoricalToNumeric'] = request.POST.get('CategoricalToNumeric')
configSettings['advance']['profiler']['numericFeatureRatio'] = request.POST.get('NumFeatureRatio')
configSettings['advance']['profiler']['categoryMaxLabel'] = request.POST.get('CatMaxLabels')
configSettings['advance']['selector']['categoryMaxLabel'] = request.POST.get('CatMaxLabels')
normalizationtypes = configSettings['advance']['profiler']['normalization']
for k in normalizationtypes.keys():
configSettings['advance']['profiler']['normalization'][k] = 'False'
if request.POST.get('NormalizationMethod').lower() != 'none':
configSettings['advance']['profiler']['normalization'][request.POST.get('NormalizationMethod')] = 'True'
#configSettings['advance']['profiler']['normalizationMethod'] = request.POST.get('NormalizationMethod')
configSettings['advance']['profiler']['removeDuplicate'] = request.POST.get('removeDuplicate')
# ---------------------------------------------- Debiasing Changes ----------------------------------------------
configSettings['advance']['profiler']['deBiasing']['FeatureName'] = request.POST.get('InputFeature')
configSettings['advance']['profiler']['deBiasing']['ClassName'] = request.POST.get('InputClass')
configSettings['advance']['profiler']['deBiasing']['Algorithm'] = request.POST.get('InputAlgorithm')
configSettings['advance']['profiler']['deBiasing']['TargetFeature'] = configSettings['basic']['targetFeature']
# ---------------------------------------------- ----------------------------------------------
problemtypes = configSettings['basic']['analysisType']
problem_type = ""
for k in problemtypes.keys():
if configSettings['basic']['analysisType'][k] == 'True':
problem_type = k
break
if configSettings['basic']['analysisType']['llmFineTuning'].lower() == 'false' and configSettings['basic']['onlineLearning'].lower() == 'false' and configSettings['basic']['distributedLearning'].lower() == 'false':
configSettings['advance']['profiler']['textCleaning']['removeNoise'] = request.POST.get('noiseStatus')
# -------------------------------- 12301:Remove Noise Config related Changes S T A R T --------------------------------
if request.POST.get('noiseStatus') == 'True':
configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['decodeHTML'] = request.POST.get('DecodeHTML')
configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeHyperLinks'] = request.POST.get('removeHyperlinks')
configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeMentions'] = request.POST.get('RemoveMentions')
configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeHashtags'] = request.POST.get('removeHashtags')
configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeEmoji'] = request.POST.get('removeEmoji')
configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['unicodeToAscii'] = request.POST.get('unicodeToAscii')
configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeNonAscii'] = request.POST.get('removeNonAscii')
else:
configSettings['advance']['profiler']['textCleaning | ||
']['removeNoiseConfig']['decodeHTML'] = "False"
configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeHyperLinks'] = "False"
configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeMentions'] = "False"
configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeHashtags'] = "False"
configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeEmoji'] = "False"
configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['unicodeToAscii'] = "False"
configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeNonAscii'] = "False"
# ---------------------------------------------------------------- E N D ----------------------------------------------------------------
configSettings['advance']['profiler']['textCleaning']['expandContractions'] = request.POST.get(
'expandContractions')
configSettings['advance']['profiler']['textCleaning']['normalize'] = request.POST.get('normalize')
if (request.POST.get('normalizeMethod') == 'Lemmatization'):
configSettings['advance']['profiler']['textCleaning']['normalizeMethod']['lemmatization'] = "True"
configSettings['advance']['profiler']['textCleaning']['normalizeMethod']['stemming'] = "False"
else:
configSettings['advance']['profiler']['textCleaning']['normalizeMethod']['stemming'] = "True"
configSettings['advance']['profiler']['textCleaning']['normalizeMethod']['lemmatization'] = "False"
configSettings['advance']['profiler']['textCleaning']['replaceAcronym'] = request.POST.get('replaceAcronym')
if request.POST.get('acronymDict') != '' and request.POST.get('acronymDict') != 'None':
configSettings['advance']['profiler']['textCleaning']['acronymConfig']['acronymDict'] = eval(request.POST.get(
'acronymDict'))
configSettings['advance']['profiler']['textCleaning']['correctSpelling'] = request.POST.get(
'correctSpelling')
configSettings['advance']['profiler']['textCleaning']['removeStopwords'] = request.POST.get(
'removeStopwords')
if (request.POST.get('ExtendOrReplace') == 'NA'):
configSettings['advance']['profiler']['textCleaning']['stopWordsConfig']['extend'] = "False"
configSettings['advance']['profiler']['textCleaning']['stopWordsConfig']['replace'] = "False"
elif (request.POST.get('ExtendOrReplace') == 'Extend'):
configSettings['advance']['profiler']['textCleaning']['stopWordsConfig']['extend'] = "True"
configSettings['advance']['profiler']['textCleaning']['stopWordsConfig']['replace'] = "False"
else:
configSettings['advance']['profiler']['textCleaning']['stopWordsConfig']['extend'] = "False"
configSettings['advance']['profiler']['textCleaning']['stopWordsConfig']['replace'] = "True"
configSettings['advance']['profiler']['textCleaning']['stopWordsConfig'][
'stopwordsList'] = request.POST.get('stopwordsList')
configSettings['advance']['profiler']['textCleaning']['removePunctuation'] = request.POST.get(
'removePunctuation')
configSettings['advance']['profiler']['textCleaning']['removePunctuationConfig'][
'removePuncWithinTokens'] = request.POST.get('removePuncWithinTokens')
configSettings['advance']['profiler']['textCleaning']['removeNumericTokens'] = request.POST.get(
'removeNumericTokens')
configSettings['advance']['profiler']['textCleaning']['removeNumericConfig'][
'removeNumeric_IncludeSpecialCharacters'] = request.POST.get('removeNumeric_IncludeSpecialCharacters')
if (request.POST.get('tokenizationLib') == 'nltk'):
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['nltk'] = "True"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][
'textblob'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['spacy'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['keras'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][
'gensim'] = "False"
elif (request.POST.get('tokenizationLib') == 'textblob'):
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['nltk'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][
'textblob'] = "True"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['spacy'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['keras'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][
'gensim'] = "False"
elif (request.POST.get('tokenizationLib') == 'spacy'):
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['nltk'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][
'textblob'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['spacy'] = "True"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['keras'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][
'gensim'] = "False"
elif (request.POST.get('tokenizationLib') == 'keras'):
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['nltk'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][
'textblob'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['spacy'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['keras'] = "True"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][
'gensim'] = "False"
else:
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['nltk'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][
'textblob'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['spacy'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['keras'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['gensim'] = "True"
if (request.POST.get('lemmatizationLib') == 'nltk'):
configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib']['nltk'] = "True"
configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib'][
'textblob'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib'][
'spacy'] = "False"
elif (request.POST.get('lemmatizationLib') == 'textblob'):
configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib']['nltk'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib'][
'textblob'] = "True"
configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib'][
'spacy'] = "False"
else:
configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib']['nltk'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib'][
'textblob'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib']['spacy'] = "True"
if (request.POST.get('stopwordsRemovalLib') == 'nltk'):
configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][
'nltk'] = "True"
configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][
'gensim'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][
'spacy'] = "False"
elif (request.POST.get('stopwordsRemovalLib') == 'gensim'):
configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][
'nltk'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][
'gensim'] = "True"
configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][
'spacy'] = "False"
else:
configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][
'nltk'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][
'gensim'] = "False"
configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][
'spacy'] = "True"
configSettings['advance']['profiler']['textFeatureExtraction']['n_grams'] = request.POST.get('n_grams')
configSettings['advance']['profiler']['textFeatureExtraction']['n_grams_config'][
'min_n'] = int(request.POST.get('range_min_n'))
configSettings['advance']['profiler']['textFeatureExtraction']['n_grams_config'][
'max_n'] = int(request.POST.get('range_max_n'))
configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags'] = request.POST.get('pos_tags')
if (request.POST.get('pos_tags_lib') == 'nltk'):
configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['nltk'] = "True"
configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['textblob'] = "False"
configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['spacy'] = "False"
elif (request.POST.get('pos_tags_lib') == 'textblob'):
configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['nltk'] = "False"
configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['textblob'] = "True"
configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['spacy'] = "False"
else:
configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['nltk'] = "False"
configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['textblob'] = "False"
configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['spacy'] = "True"
textconvertionmethods = configSettings['advance']['profiler']['textConversionMethod']
for k in textconvertionmethods.keys():
configSettings['advance']['profiler']['textConversionMethod'][k] = 'False'
if problem_type.lower() not in ['similarityidentification','contextualsearch']:
configSettings['advance']['profiler']['textConversionMethod'][request.POST.get('textConvertionMethod')] = 'True'
if 'embeddingSize' in configSettings['advance']['profiler']:
glove = configSettings['advance']['profiler']['embeddingSize']['Glove']
for k in glove.keys():
configSettings['advance']['profiler']['embeddingSize']['Glove'][k] = 'False'
configSettings['advance']['profiler']['embeddingSize']['Glove'][request.POST.get('txtglovedimensions')] = 'True'
fastText = configSettings['advance']['profiler']['embeddingSize']['FastText']
for k in fastText.keys():
configSettings['advance']['profiler']['embeddingSize']['FastText'][k] = 'False'
configSettings['advance']['profiler']['embeddingSize']['FastText'][request.POST.get('txtFastTextdimensions')] = 'True'
if 'LatentSemanticAnalysis' in configSettings['advance']['profiler']['embeddingSize']:
LatentSemanticAnalysis = configSettings['advance']['profiler']['embeddingSize']['LatentSemanticAnalysis']
for k in LatentSemanticAnalysis.keys():
configSettings['advance']['profiler']['embeddingSize']['LatentSemanticAnalysis'][k] = 'False'
configSettings['advance']['profiler']['embeddingSize']['LatentSemanticAnalysis'][request.POST.get('txttfidfdimensions')] = 'True'
if 'TF_IDF' in configSettings['advance']['profiler']['embeddingSize']:
configSettings['advance']['profiler']['embeddingSize']['TF_IDF']['maxFeatures'] = request.POST.get('tfidfmaxfeatures')
if 'CountVectors' in configSettings['advance']['profiler']['embeddingSize']:
configSettings['advance']['profiler']['embeddingSize']['CountVectors']['maxFeatures'] = request.POST.get('cvmaxfeatures')
if problem_type.lower() == 'imageclassification':
configSettings['advance']['image_config']['img_width'] = int(request.POST.get('img_width'))
configSettings['advance']['image_config']['img_height'] = int(request.POST.get('img_height'))
configSettings['advance']['image_config']['img_channel'] = int(request.POST.get('img_channel'))
configSettings['advance']['image_config']['lr'] = float(request.POST.get('lr'))
configSettings['advance']['image_config']['epochs'] = int(request.POST.get('epoch | ||
s'))
configSettings['advance']['image_config']['test_split_ratio'] = float(request.POST.get('test_split_ratio'))
if problem_type.lower() == "llmfinetuning":
configSettings = llmadvancesettings(configSettings,request)
if problem_type.lower() == 'objectdetection' or problem_type.lower() == 'imageclassification':
configSettings['advance']['ImageAugmentation']['Enable'] = request.POST.get('advance_ImageAugmentation_Enable')
configSettings['advance']['ImageAugmentation']['KeepAugmentedImages'] = request.POST.get('advance_ImageAugmentation_keepAugmentedImages')
configSettings['advance']['ImageAugmentation']['Noise']['Blur'] = request.POST.get('advance_ImageAugmentation_Noise_Blur')
configSettings['advance']['ImageAugmentation']['Noise']['Brightness'] = request.POST.get('advance_ImageAugmentation_Noise_Brightness')
configSettings['advance']['ImageAugmentation']['Noise']['Contrast'] = request.POST.get('advance_ImageAugmentation_Noise_Contrast')
configSettings['advance']['ImageAugmentation']['Transformation']['Flip'] = request.POST.get('advance_ImageAugmentation_Transformation_Flip')
configSettings['advance']['ImageAugmentation']['Transformation']['Rotate'] = request.POST.get('advance_ImageAugmentation_Transformation_Rotate')
configSettings['advance']['ImageAugmentation']['Transformation']['Shift'] = request.POST.get('advance_ImageAugmentation_Transformation_Shift')
configSettings['advance']['ImageAugmentation']['Transformation']['Crop'] = request.POST.get('advance_ImageAugmentation_Transformation_Crop')
configSettings['advance']['ImageAugmentation']['configuration']['Blur']['noOfImages'] = request.POST.get('noofblurimages')
configSettings['advance']['ImageAugmentation']['configuration']['Blur']['limit'] = request.POST.get('limitblurimage')
configSettings['advance']['ImageAugmentation']['configuration']['Brightness']['noOfImages'] = request.POST.get('noofbrightnessimages')
configSettings['advance']['ImageAugmentation']['configuration']['Brightness']['limit'] = request.POST.get('limitbrightnessimage')
configSettings['advance']['ImageAugmentation']['configuration']['Contrast']['noOfImages'] = request.POST.get('noofcontrastimages')
configSettings['advance']['ImageAugmentation']['configuration']['Contrast']['limit'] = request.POST.get('limitcontrastimage')
configSettings['advance']['ImageAugmentation']['configuration']['Flip']['noOfImages'] = request.POST.get('noofflipimages')
configSettings['advance']['ImageAugmentation']['configuration']['Rotate']['noOfImages'] = request.POST.get('noofrotateimages')
configSettings['advance']['ImageAugmentation']['configuration']['Shift']['noOfImages'] = request.POST.get('noofshiftimages')
configSettings['advance']['ImageAugmentation']['configuration']['Crop']['noOfImages'] = request.POST.get('noofcropimages')
configSettings['advance']['selector']['selectionMethod']['featureSelection'] = 'False'
configSettings['advance']['selector']['selectionMethod']['featureEngineering'] = 'False'
configSettings['advance']['selector']['featureSelection']['allFeatures'] = 'False'
configSettings['advance']['selector']['featureSelection']['statisticalBased'] = 'False'
configSettings['advance']['selector']['featureSelection']['modelBased'] = 'False'
if(request.POST.get('selectionMethod') == 'FeatureSelection'):
configSettings['advance']['selector']['selectionMethod']['featureSelection'] = 'True'
else:
configSettings['advance']['selector']['selectionMethod']['featureEngineering'] = 'True'
if request.POST.get('allFeatures'):
configSettings['advance']['selector']['featureSelection']['allFeatures'] = request.POST.get('allFeatures')
if request.POST.get('statisticalBased'):
configSettings['advance']['selector']['featureSelection']['statisticalBased'] = request.POST.get('statisticalBased')
if request.POST.get('modelBased'):
configSettings['advance']['selector']['featureSelection']['modelBased'] = request.POST.get('modelBased')
dimentionalityreductionmethod = request.POST.get('dimentionalityreductionmethod')
for x in list(configSettings['advance']['selector']['featureEngineering'].keys()):
if x != 'numberofComponents':
configSettings['advance']['selector']['featureEngineering'][x] = 'False'
configSettings['advance']['selector']['featureEngineering'][dimentionalityreductionmethod] = 'True'
configSettings['advance']['selector']['featureEngineering']['numberofComponents'] = request.POST.get('numberofComponents')
#configSettings['advance']['selector']['categoricalFeatureRatio'] = request.POST.get('CatFeatureRatio')
configSettings['advance']['selector']['statisticalConfig']['correlationThresholdFeatures'] = request.POST.get('correlationThresholdFeatures')
configSettings['advance']['selector']['statisticalConfig']['correlationThresholdTarget'] = request.POST.get('correlationThresholdTarget')
configSettings['advance']['selector']['statisticalConfig']['pValueThresholdFeatures'] = request.POST.get('pValueThresholdFeatures')
configSettings['advance']['selector']['statisticalConfig']['pValueThresholdTarget'] = request.POST.get('pValueThresholdTarget')
configSettings['advance']['selector']['statisticalConfig']['varianceThreshold'] = request.POST.get('VarianceThreshold')
if problem_type.lower() == 'recommendersystem':
configSettings['advance']['recommenderparam']['svd_params']= eval(request.POST.get('svd_params'))
configSettings['advance']['associationrule']['modelParams']['apriori'] = eval(request.POST.get('apriori'))
configSettings['advance']['textSimilarityConfig'] = eval(request.POST.get('textsimilarity'))
if configSettings['basic']['distributedLearning'].lower() == 'true':
configSettings['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['Distributed Extreme Gradient Boosting (XGBoost)'] = eval(request.POST.get('classDistributedXGBoost'))
configSettings['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['Distributed Light Gradient Boosting (LightGBM)'] = eval(request.POST.get('classDistributedLightGBM'))
configSettings['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['Distributed Extreme Gradient Boosting (XGBoost)'] = eval(request.POST.get('DistributedXGBoostreg'))
configSettings['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['Distributed Light Gradient Boosting (LightGBM)'] = eval(request.POST.get('DistributedLightGBMreg'))
if configSettings['basic']['onlineLearning'].lower() != 'true' and configSettings['basic']['distributedLearning'].lower() != 'true':
if (problem_type.lower() == 'classification') or (problem_type.lower() == 'regression') or (problem_type.lower() == 'clustering') or (problem_type.lower() == 'topicmodelling'):
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Logistic Regression'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Logistic Regression'] = eval(request.POST.get('classification_LogisticRegression'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Naive Bayes'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Naive Bayes'] = eval(request.POST.get('classification_GaussianNB'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Support Vector Machine'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Support Vector Machine'] = eval(request.POST.get('classification_SVC'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['K Nearest Neighbors'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['K Nearest Neighbors'] = eval(request.POST.get('classification_KNeighborsClassifier'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Decision Tree'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Decision Tree'] = eval(request.POST.get('classification_DecisionTreeClassifier'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Random Forest'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Random Forest'] = eval(request.POST.get('classification_RandomForestClassifier'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Gradient Boosting'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Gradient Boosting'] = eval(request.POST.get('classification_GradientBoostingClassifier'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Extreme Gradient Boosting (XGBoost)'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Extreme Gradient Boosting (XGBoost)'] = eval(request.POST.get('classification_ExtremeGradientBoostingClassifier'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Light Gradient Boosting (LightGBM)'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Light Gradient Boosting (LightGBM)'] = eval(request.POST.get('classification_LightGradientBoostingClassifier'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Categorical Boosting (CatBoost)'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Categorical Boosting (CatBoost)'] = eval(request.POST.get('classification_CategoricalBoostingClassifier'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Linear Regression'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Linear Regression'] = eval(request.POST.get('regression_LinearRegression'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Lasso'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Lasso'] = eval(request.POST.get('regression_Lasso'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Ridge'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Ridge'] = eval(request.POST.get('regression_Ridge'))
if problem_type.lower() == 'topicmodelling' and configSettings['basic']['algorithms']['topicModelling']['LDA'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['topicModellingParams']['LDA']= eval(request.POST.get('topicmodeling_lda'))
if problem_type.lower() == 'clustering' and configSettings['basic']['algorithms']['clustering']['KMeans'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['clusteringModelParams']['KMeans']= eval(request.POST.get('cluster_kmeans'))
if problem_type.lower() == 'clustering' and configSettings['basic']['algorithms']['clustering']['DBSCAN'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['clusteringModelParams']['DBSCAN']= eval(request.POST.get('cluster_DBSCAN'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Decision Tree'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Decision Tree'] = eval(request.POST.get('regression_DecisionTreeRegressor'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Random Forest'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Random Forest'] = eval(request.POST.get('regression_RandomForestRegressor'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Extreme Gradient Boosting (XGBoost)'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Extreme Gradient Boosting (XGBoost)'] = eval(request.POST.get('regression_XGBoostRegressor'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Light Gradient Boosting (LightGBM)'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Light Gradient Boosting (LightGBM)'] = eval(request.POST.get('regression_LightGBMRegressor'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Categorical Boosting (CatBoost)'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Categorical Boosting (CatBoost)'] = eval(request.POST.get('regression_CatBoostRegressor'))
configSettings['advance']['mllearner_config']['modelparamsfile'] = request.POST.get('ModelParamFile')
configSettings['advance']['mllearner_config']['optimizationMethod'] = request.POST.get('OptimizationMethod')
configSettings['advance']['mllearner_config']['optimizationHyperParameter'][
'iterations'] = request.POST.get('iterations')
configSettings['advance']['mllearner_config']['optimizationHyperParameter'][
'trainTestCVSplit'] = request.POST.get('trainTestCVSplit')
configSettings['advance']['mllearner_config']['thresholdTunning'] = request.POST.get('thresholdTunning')
configSettings['advance']['mllearner_config']['Stacking (Ensemble)'] = request.POST.get('EnsembleStacking')
configSettings['advance']['mllearner_config']['Voting (Ensemble)'] = request.POST.get('EnsembleVoting')
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Logistic Regression']['enable'] = request.POST.get('ensemple_bagging_ | ||
lr_enable')
if configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Logistic Regression']['enable'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Logistic Regression']['param'] = eval(request.POST.get('classi_ensemple_bagging_lr_param'))
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Naive Bayes']['enable'] = request.POST.get('ensemple_bagging_naivebayes_enable')
if configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Naive Bayes']['enable'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Naive Bayes']['param'] = eval(request.POST.get('classi_ensemple_bagging_naivebayes_param'))
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Support Vector Machine']['enable'] = request.POST.get('ensemple_bagging_svm_enable')
if configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Support Vector Machine']['enable'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Support Vector Machine']['param'] = eval(request.POST.get('classi_ensemple_bagging_svm_param'))
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['K Nearest Neighbors']['enable'] = request.POST.get('ensemple_bagging_knn_enable')
if configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['K Nearest Neighbors']['enable'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['K Nearest Neighbors']['param'] = eval(request.POST.get('classi_ensemple_bagging_knn_param'))
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Decision Tree']['enable'] = request.POST.get('ensemple_bagging_dt_enable')
if configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Decision Tree']['enable'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Decision Tree']['param'] = eval(request.POST.get('classi_ensemple_bagging_dt_param'))
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Random Forest']['enable'] = request.POST.get('ensemple_bagging_rf_enable')
if configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Random Forest']['enable'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Random Forest']['param'] = eval(request.POST.get('classi_ensemple_bagging_rf_param'))
configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Linear Regression']['enable'] = request.POST.get('ensemple_bagging_lir_enable')
if configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Linear Regression']['enable'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Linear Regression']['param'] = eval(request.POST.get('reg_ensemple_bagging_lir_param'))
configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Decision Tree']['enable'] = request.POST.get('ensemple_bagging_dit_enable')
if configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Decision Tree']['enable'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Decision Tree']['param'] = eval(request.POST.get('reg_ensemple_bagging_dit_param'))
configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Ridge']['enable'] = request.POST.get('ensemple_bagging_ridge_enable')
if configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Ridge']['enable'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Ridge']['param'] = eval(request.POST.get('reg_ensemple_bagging_ridge_param'))
if problem_type.lower() == 'classification':
if configSettings['advance']['mllearner_config']['Stacking (Ensemble)'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Stacking (Ensemble)'] = eval(request.POST.get('ensamblestackingClassifierparams'))
if problem_type.lower() == 'regression':
if configSettings['advance']['mllearner_config']['Stacking (Ensemble)'] == 'True':
configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Stacking (Ensemble)'] = eval(request.POST.get('ensamblestackingRegressorparams'))
configSettings['basic']['filterExpression'] = request.POST.get('filterExpression')
#configSettings['advance']['mllearner_config']['trainPercentage'] = request.POST.get('trainPercentage')
if (problem_type.lower() == 'classification') or (problem_type.lower() == 'regression'):
configSettings['advance']['modelEvaluation']['smcStrategy'] = request.POST.get('smcStrategy')
configSettings['advance']['modelEvaluation']['smcMaxDepth'] = request.POST.get('smcMaxDepth')
configSettings['advance']['modelEvaluation']['smcCondition'] = request.POST.get('smcCondition')
configSettings['advance']['modelEvaluation']['miCondition'] = request.POST.get('miCondition')
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Neural Network'] == 'True':
configSettings['advance']['dllearner_config']['modelParams']['classifierModelParams']['Neural Network'] = eval(
request.POST.get('dl_classification_SNN'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Recurrent Neural Network'] == 'True':
configSettings['advance']['dllearner_config']['modelParams']['classifierModelParams']['Recurrent Neural Network'] = eval(
request.POST.get('dl_classification_RNN'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Recurrent Neural Network (GRU)'] == 'True':
configSettings['advance']['dllearner_config']['modelParams']['classifierModelParams']['Recurrent Neural Network (GRU)'] = eval(
request.POST.get('dl_classification_GRURNN'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Recurrent Neural Network (LSTM)'] == 'True':
configSettings['advance']['dllearner_config']['modelParams']['classifierModelParams']['Recurrent Neural Network (LSTM)'] = eval(
request.POST.get('dl_classification_LSTMRNN'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Convolutional Neural Network (1D)'] == 'True':
configSettings['advance']['dllearner_config']['modelParams']['classifierModelParams']['Convolutional Neural Network (1D)'] = eval(
request.POST.get('dl_classification_CNN'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification'].get('Neural Architecture Search') == 'True':
configSettings['advance']['dllearner_config']['modelParams']['classifierModelParams']['Neural Architecture Search'] = eval(
request.POST.get('dl_classification_NAS'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Neural Network'] == 'True':
configSettings['advance']['dllearner_config']['modelParams']['regressorModelParams']['Neural Network'] = eval(
request.POST.get('dl_regression_SNN'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Recurrent Neural Network'] == 'True':
configSettings['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network'] = eval(
request.POST.get('dl_regression_RNN'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Recurrent Neural Network (GRU)'] == 'True':
configSettings['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network (GRU)'] = eval(
request.POST.get('dl_regression_GRURNN'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Recurrent Neural Network (LSTM)'] == 'True':
configSettings['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network (LSTM)'] = eval(
request.POST.get('dl_regression_LSTMRNN'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Convolutional Neural Network (1D)'] == 'True':
configSettings['advance']['dllearner_config']['modelParams']['regressorModelParams']['Convolutional Neural Network (1D)'] = eval(
request.POST.get('dl_regression_CNN'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression'].get('Neural Architecture Search') == 'True':
configSettings['advance']['dllearner_config']['modelParams']['regressorModelParams']['Neural Architecture Search'] = eval(
request.POST.get('dl_regression_NAS'))
#configSettings['advance']['dllearner_config']['optimizationMethod'] = request.POST.get('DLOptimizationMethod')
else:
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Online Logistic Regression'] == 'True':
configSettings['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online Logistic Regression'] = eval(request.POST.get('OnlineLogisticRegression'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Online Decision Tree Classifier'] == 'True':
configSettings['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online Decision Tree Classifier'] = eval(request.POST.get('OnlineDecisionTreeClassifier'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Online Softmax Regression'] == 'True':
configSettings['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online Softmax Regression'] = eval(request.POST.get('OnlineSoftmaxRegression'))
if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Online KNN Classifier'] == 'True':
configSettings['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online KNN Classifier'] = eval(request.POST.get('OnlineKNNClassifier'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Online Linear Regression'] == 'True':
configSettings['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['Online Linear Regression'] = eval(request.POST.get('OnlineLinearRegression'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Online Decision Tree Regressor'] == 'True':
configSettings['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['Online Decision Tree Regressor'] = eval(request.POST.get('OnlineDecisionTreeRegressor'))
if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Online KNN Regressor'] == 'True':
configSettings['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['Online KNN Regressor'] = eval(request.POST.get('OnlineKNNRegressor'))
configSettings['advance']['profiler']['targetEncodingParams'] = eval(request.POST.get('targetEncodingParams'))
configSettings['advance']['profiler']['outlierDetectionParams'] = eval(request.POST.get('outlierDetectionParams'))
if problem_type.lower() == 'objectdetection':
configSettings['advance']['objectDetection']['pretrainedModel']= request.POST.get('objectdetectionpretrainedmodel')
configSettings['advance']['objectDetection']['n_epoch'] = int(request.POST.get('objectDetection_n_epoch'))
configSettings['advance']['objectDetection']['batch_size'] = int(request.POST.get('objectDetection_batch_size'))
if problem_type.lower() == 'timeseriesforecasting': #task 11997 #task 13052
configSettings['advance']['timeSeriesForecasting']['fix_seasonality'] = request.POST.get('seasionality') # task 13052
configSettings['advance']['timeSeriesForecasting']['fix_stationarity'] =request.POST.get('stationarity') # task 13052
configSettings['advance']['timeSeriesForecasting']['modelParams']['ARIMA'] = eval(request.POST.get('ARIMA')) #task 11997
configSettings['advance']['timeSeriesForecasting']['modelParams']['FBPROPHET'] = eval(request.POST.get('FBPROPHET')) #task 11997
configSettings['advance']['timeSeriesForecasting']['modelParams']['LSTM'] = eval(request.POST.get('TSLSTM')) #task 11997
configSettings['advance']['timeSeriesForecasting']['modelParams']['Encoder_Decoder_LSTM_MVI_UVO'] = eval(request.POST.get('TSLSTMencoderdecoder'))
configSettings['advance']['timeSeriesForecasting']['modelParams']['MLP'] = eval(request.POST.get('TSMLP')) #task 11997
if problem_type.lower() == 'timeseriesan | ||
omalydetection':
configSettings['advance']['timeSeriesAnomalyDetection']['modelParams']['AutoEncoder'] = eval(request.POST.get('autoEncoderAD')) #task 11997
configSettings['advance']['timeSeriesAnomalyDetection']['modelParams']['DBScan'] = eval(request.POST.get('dbscanAD')) #task 13316
if problem_type.lower() == 'anomalydetection':
configSettings['advance']['anomalyDetection']['modelParams']['IsolationForest'] = eval(request.POST.get('IsolationForest'))
configSettings['advance']['anomalyDetection']['modelParams']['oneclassSVM'] = eval(request.POST.get('oneclassSVM'))
configSettings['advance']['anomalyDetection']['modelParams']['DBScan'] = eval(request.POST.get('DBScanAD'))
updatedConfigSettingsJson = json.dumps(configSettings)
f.seek(0)
f.write(updatedConfigSettingsJson)
f.truncate()
f.close()
errormsg = 'NA'
request.session['ModelStatus'] = 'Not Trained'
except Exception as e:
import sys
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
errormsg = 'Input value error'
print(e)
if 'NoOfRecords' in request.session:
records = request.session['NoOfRecords']
else:
records = 'NA'
if request.session['datatype'] in ['Video', 'Image','Document']:
folderLocation = str(request.session['datalocation'])
dataFilePath = os.path.join(folderLocation, request.session['csvfullpath'])
else:
dataFilePath = str(request.session['datalocation'])
# dataFilePath = configSettings['basic']['dataLocation']
#df = pd.read_csv(dataFilePath, encoding='latin1')
featuresList = configSettings['basic']['featureList']
config = {}
config['modelName'] = configSettings['basic']['modelName']
config['modelVersion'] = configSettings['basic']['modelVersion']
config['datetimeFeatures'] = configSettings['basic']['dateTimeFeature']
config['sequenceFeatures'] = configSettings['basic']['indexFeature']
config['FeaturesList'] = featuresList
config['unimportantFeatures'] = list(set(featuresList) - set(configSettings['basic']['trainingFeatures']))
config['targetFeature'] = configSettings['basic']['targetFeature']
scoring = configSettings['basic']['scoringCriteria']
scoringCriteria = ""
for k in scoring.keys():
if configSettings['basic']['scoringCriteria'][k] == 'True':
scoringCriteria = k
break
config['scoringCriteria'] = scoringCriteria
temp = {}
temp['ModelName'] = configSettings['basic']['modelName']
temp['Version'] = configSettings['basic']['modelVersion']
selected_use_case = request.session['UseCaseName']
ModelVersion = request.session['ModelVersion']
ModelStatus = request.session['ModelStatus']
context = {'tab': 'advconfig', 'config': config, 'temp': temp, 'advconfig': configSettings,
'noOfRecords': records, 'advance_status_msg': 'Configuration Done',
'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion,'errormsg':errormsg,
'currentstate': request.session['currentstate'], 'finalstate': request.session['finalstate'],
'selected': 'modeltraining'}
return context
elif submittype == 'AdvanceDefault':
try:
MachineLearningModels = []
configFile = os.path.join(DEFAULT_FILE_PATH, 'aion_config.json')
f = open(configFile, "r")
configSettings = f.read()
f.close()
updatedConfigFile = request.session['config_json']
f = open(updatedConfigFile, "r+")
configSettingsData = f.read()
updateconfigSettingsJson = json.loads(configSettingsData)
configSettingsJson = json.loads(configSettings)
temp = {}
temp['ModelName'] = request.session['UseCaseName']
temp['Version'] = request.session['ModelVersion']
config = {}
config['modelName'] = request.session['UseCaseName']
config['modelVersion'] = request.session['ModelVersion']
config['datetimeFeatures'] = updateconfigSettingsJson['basic']['dateTimeFeature']
config['sequenceFeatures'] = updateconfigSettingsJson['basic']['indexFeature']
config['FeaturesList'] = updateconfigSettingsJson['basic']['trainingFeatures']
config['unimportantFeatures'] = ''
config['targetFeature'] = updateconfigSettingsJson['basic']['targetFeature']
problemtypes = updateconfigSettingsJson['basic']['analysisType']
problem_type = ""
for k in problemtypes.keys():
if updateconfigSettingsJson['basic']['analysisType'][k] == 'True':
problem_type = k
break
selectAlgo = ""
if problem_type in ['classification','regression','timeSeriesForecasting',
'timeSeriesAnomalyDetection',
'recommenderSystem','clustering','anomalyDetection','topicModelling','survivalAnalysis','videoForecasting','imageClassification','objectDetection','stateTransition']: #task 11997
for key in updateconfigSettingsJson['basic']['algorithms'][problem_type]:
if updateconfigSettingsJson['basic']['algorithms'][problem_type][key] == 'True':
if selectAlgo != "":
selectAlgo += ','
selectAlgo += key
if problem_type not in ['classification','regression']:
break
for key in updateconfigSettingsJson['basic']['algorithms'][problem_type]:
if updateconfigSettingsJson['basic']['algorithms'][problem_type][key] == 'True':
MachineLearningModels.append(key)
if problem_type == 'objectDetection':
from AION import pretrainedModels
ptmObj = pretrainedModels()
obModels = ptmObj.get_info(selectAlgo)
else:
obModels = {}
problemType = problem_type
selected_use_case = request.session['UseCaseName']
ModelVersion = request.session['ModelVersion']
ModelStatus = request.session['ModelStatus']
request.session['currentstate'] = 2
if request.session['finalstate'] <= 2:
request.session['finalstate'] = 2
outlierDetection = 'False'
updateconfigSettingsJson['advance'] = configSettingsJson['advance']
for x in list(updateconfigSettingsJson['advance']['profiler']['outlierDetection'].keys()):
if updateconfigSettingsJson['advance']['profiler']['outlierDetection'][x] == 'True':
outlierDetection = 'True'
if outlierDetection == 'False':
updateconfigSettingsJson['advance']['profiler']['outlierDetection']['Disable'] = 'True'
else:
updateconfigSettingsJson['advance']['profiler']['outlierDetection']['Disable'] = 'False'
updateconfigSettingsJson = advanceConfigfields(updateconfigSettingsJson)
#print(configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['ExtremeGradientBoostingClassifier'])
updateconfigSettingsJson['advance']['profiler']['normalizationMethod'] = 'None'
normalizationtypes = updateconfigSettingsJson['advance']['profiler']['normalization']
for k in normalizationtypes.keys():
if updateconfigSettingsJson['advance']['profiler']['normalization'][k] == 'True':
updateconfigSettingsJson['advance']['profiler']['normalizationMethod'] = k
break
#---------------- default Hypermarameter changes--- ----------Usnish--------------
hyperparamFile = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','config', 'hyperparam_config.json'))
with open(hyperparamFile) as json_file:
hyperparamConfig = json.load(json_file)
context = {'tab': 'advconfig','temp': temp,'advconfig': updateconfigSettingsJson,
'config': config, 'selected_use_case': selected_use_case,'MachineLearningModels':MachineLearningModels,
'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion,"obModels":obModels,"problemType":problemType,
'currentstate': request.session['currentstate'], 'finalstate': request.session['finalstate'],
'selected': 'modeltraning','advance_help':ht.advance_help,'hyperparamConfig':hyperparamConfig}
return context
except Exception as e:
print(e)
def llmadvancesettings(configSettings,request):
algo = ''
for x in list(configSettings['basic']['algorithms']['llmFineTuning'].keys()):
if configSettings['basic']['algorithms']['llmFineTuning'][x] == 'True':
algo = x
if algo == 'LLaMA-2':
configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2']['fineTuningMethod'] = request.POST.get('llama2fullfinemethod')
configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2']['epochs'] = request.POST.get('llama2epochs')
configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2']['learning_rate'] = request.POST.get('llama2learningrate')
if request.POST.get('llama2fullfinemethod') != 'Full Fine-Tuning':
configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2']['lora_rank'] = request.POST.get('llama2lorarank')
configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2']['lora_alpha'] = request.POST.get('llama2loraalpha')
if algo == 'LLaMA-2-Chat':
configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2-Chat']['fineTuningMethod'] = request.POST.get('llama2chatfullfinemethod')
configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2-Chat']['epochs'] = request.POST.get('llmllama2chatepochs')
configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2-Chat']['learning_rate'] = request.POST.get('llama2chatlearningrate')
if request.POST.get('llama2chatfullfinemethod') != 'Full Fine-Tuning':
configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2-Chat']['lora_rank'] = request.POST.get('llama2chatlorarank')
configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2-Chat']['lora_alpha'] = request.POST.get('llama2chatloraalpha')
if algo == 'CodeLLaMA-2':
configSettings['advance']['llmFineTuning']['modelParams']['CodeLLaMA-2']['fineTuningMethod'] = request.POST.get('CodeLLaMA2fullfinemethod')
configSettings['advance']['llmFineTuning']['modelParams']['CodeLLaMA-2']['epochs'] = request.POST.get('CodeLLaMA2epochs')
configSettings['advance']['llmFineTuning']['modelParams']['CodeLLaMA-2']['learning_rate'] = request.POST.get('CodeLLaMA2learningrate')
if request.POST.get('CodeLLaMA2fullfinemethod') != 'Full Fine-Tuning':
configSettings['advance']['llmFineTuning']['modelParams']['CodeLLaMA-2']['lora_rank'] = request.POST.get('CodeLLaMA2lorarank')
configSettings['advance']['llmFineTuning']['modelParams']['CodeLLaMA-2']['lora_alpha'] = request.POST.get('CodeLLaMA2loraalpha')
if algo == 'Falcon':
configSettings['advance']['llmFineTuning']['modelParams']['Falcon']['fullFineTuning'] = request.POST.get('falconfullfinetuning')
configSettings['advance']['llmFineTuning']['modelParams']['Falcon']['epochs'] = request.POST.get('falconepochs')
configSettings['advance']['llmFineTuning']['modelParams']['Falcon']['learning_rate'] = request.POST.get('falconlearningrate')
configSettings['advance']['llmFineTuning']['modelParams']['Falcon']['lora_rank'] = request.POST.get('falconlorarank')
configSettings['advance']['llmFineTuning']['modelParams']['Falcon']['lora_alpha'] = request.POST.get('falconloraalpha')
return configSettings
def advanceConfigfields(configSettingsJson):
try:
configSettingsJson['advance']['mllearner_config']['EnsembleStacking'] = \\
configSettingsJson['advance']['mllearner_config']['Stacking (Ensemble)']
configSettingsJson['advance']['mllearner_config']['EnsembleVoting'] = \\
configSettingsJson['advance']['mllearner_config']['Voting (Ensemble)']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][
'LogisticRegression'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Logistic Regression']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['GaussianNB'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Naive Bayes']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['SVC'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][
'Support Vector Machine']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][
'KNeighborsClassifier'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['K Nearest Neighbors']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][
'DecisionTreeClassifier'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Decision Tree']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][
'RandomForestClassifier'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Random Forest']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][
'GradientBoostingClassifier'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Gradient Boosting']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][
'ExtremeGradientBoostingClassifier'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][
'Extreme Gradient Boosting (XGBoost)']
configSettingsJson['advance']['mllearner_config'][' | ||
modelParams']['classifierModelParams'][
'LightGradientBoostingClassifier'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][
'Light Gradient Boosting (LightGBM)']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][
'CategoricalBoostingClassifier'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][
'Categorical Boosting (CatBoost)']
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['SNN'] = \\
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['Neural Network']
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['SimpleRNN'] = \\
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams'][
'Recurrent Neural Network']
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['GRURNN'] = \\
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams'][
'Recurrent Neural Network (GRU)']
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['LSTMRNN'] = \\
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams'][
'Recurrent Neural Network (LSTM)']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleStacking'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Stacking (Ensemble)']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][
'LogisticRegression'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][
'Logistic Regression']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][
'NaiveBayes'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][
'Naive Bayes']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][
'SVM'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][
'Support Vector Machine']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][
'KNN'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][
'K Nearest Neighbors']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][
'DecisionTree'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][
'Decision Tree']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][
'RandomForest'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][
'Random Forest']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['SimpleRNN'] = \\
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][
'Recurrent Neural Network']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['GRURNN'] = \\
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][
'Recurrent Neural Network (GRU)']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['LSTMRNN'] = \\
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][
'Recurrent Neural Network (LSTM)']
configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams']['DQN'] = \\
configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams']['Deep Q Network']
configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams']['DDQN'] = \\
configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams'][
'Dueling Deep Q Network']
configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams']['DQN'] = \\
configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams']['Deep Q Network']
configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams']['DDQN'] = \\
configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams'][
'Dueling Deep Q Network']
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['CNN'] = \\
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams'][
'Convolutional Neural Network (1D)']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['LinearRegression'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Linear Regression']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams'][
'DecisionTreeRegressor'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Decision Tree']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams'][
'RandomForestRegressor'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Random Forest']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['XGBoostRegressor'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams'][
'Extreme Gradient Boosting (XGBoost)']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['LightGBMRegressor'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams'][
'Light Gradient Boosting (LightGBM)']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['CatBoostRegressor'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams'][
'Categorical Boosting (CatBoost)']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleStacking'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Stacking (Ensemble)']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging'][
'LinearRegression'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging'][
'Linear Regression']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging'][
'DecisionTree'] = \\
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging'][
'Decision Tree']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['NAS'] = \\
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][
'Neural Architecture Search']
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['NAS'] = \\
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams'][
'Neural Architecture Search']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['SNN'] = \\
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Neural Network']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['SimpleRNN'] = \\
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][
'Recurrent Neural Network']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['GRURNN'] = \\
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][
'Recurrent Neural Network (GRU)']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['LSTMRNN'] = \\
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][
'Recurrent Neural Network (LSTM)']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['CNN'] = \\
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][
'Convolutional Neural Network (1D)']
configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][
'OnlineLogisticRegression'] = \\
configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][
'Online Logistic Regression']
configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][
'OnlineDecisionTreeClassifier'] = \\
configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][
'Online Decision Tree Classifier']
configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][
'OnlineSoftmaxRegression'] = \\
configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][
'Online Softmax Regression']
configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][
'OnlineKNNClassifier'] = \\
configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][
'Online KNN Classifier']
configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams'][
'OnlineLinearRegression'] = \\
configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams'][
'Online Linear Regression']
configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams'][
'OnlineDecisionTreeRegressor'] = \\
configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams'][
'Online Decision Tree Regressor']
configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams'][
'OnlineKNNRegressor'] = \\
configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams'][
'Online KNN Regressor']
configSettingsJson['advance']['profiler']['textConversionMethod']['LatentSemanticAnalysis'] = \\
configSettingsJson['advance']['profiler']['textConversionMethod']['LatentSemanticAnalysis']
configSettingsJson['advance']['profiler']['embeddingSize']['LatentSemanticAnalysis'] = \\
configSettingsJson['advance']['profiler']['embeddingSize']['LatentSemanticAnalysis']
if 'llmFineTuning' in configSettingsJson['advance']:
configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA2'] = \\
configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA-2']
configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA2Chat'] = \\
configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA-2-Chat']
configSettingsJson['basic']['algorithms']['llmFineTuning']['CodeLLaMA2'] = \\
configSettingsJson['basic']['algorithms']['llmFineTuning']['CodeLLaMA-2']
configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA2'] = \\
configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA-2']
configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA2Chat'] = \\
configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA-2-Chat']
configSettingsJson['advance']['llmFineTuning']['modelParams']['CodeLLaMA2'] = \\
configSettingsJson['advance']['llmFineTuning']['modelParams']['CodeLLaMA-2']
configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA2'] = \\
configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA-2']
configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA2Chat'] = \\
configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA-2-Chat']
configSettingsJson['basic']['modelSize']['llmFineTuning']['CodeLLaMA2'] = \\
configSettingsJson['basic']['modelSize']['llmFineTuning']['CodeLLaMA-2']
if 'distributedlearner_config' in configSettingsJson['advance']:
configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams'][
'DistributedXGBoost'] = \\
configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams'][
'Distributed Extreme Gradient Boosting (XGBoost)']
configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams'][
'DistributedLightGBM'] = \\
configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams'][
'Distributed Light Gradient Boosting (LightGBM)']
configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams'][
'DistributedXGBoost'] = \\
configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams'][
'Distributed Extreme Gradient Boosting (XGBoost)']
configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams'][
'DistributedLightGBM'] = \\
configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams'][
'Distributed Light Gradient Boosting (LightGBM)']
problem_type = ""
problemtypes = configSettingsJson['basic'][' | ||
analysisType']
for k in problemtypes.keys():
if configSettingsJson['basic']['analysisType'][k] == 'True':
problem_type = k
break
deepLearning = 'False'
machineLearning = 'False'
reinforcementLearning = 'False'
selectAlgo = ""
if problem_type.lower() in ['classification','regression']:
for key in configSettingsJson['basic']['algorithms'][problem_type]:
if configSettingsJson['basic']['algorithms'][problem_type][key] == 'True':
if key in ['Neural Network','Convolutional Neural Network (1D)','Recurrent Neural Network','Recurrent Neural Network (GRU)','Recurrent Neural Network (LSTM)','Neural Architecture Search']:
deepLearning = 'True'
if key in ['Logistic Regression','Naive Bayes','Decision Tree','Random Forest','Support Vector Machine','K Nearest Neighbors','Gradient Boosting','Extreme Gradient Boosting (XGBoost)','Light Gradient Boosting (LightGBM)','Categorical Boosting (CatBoost)','Linear Regression','Lasso','Ridge','Decision Tree','Random Forest','Bagging (Ensemble)']:
machineLearning = 'True'
if key in ['Deep Q Network','Dueling Deep Q Network']:
reinforcementLearning = 'True'
elif problem_type.lower() in ['clustering','topicmodelling']:#clustering(Bug 12611)
machineLearning = 'True'
configSettingsJson['basic']['deepLearning'] = deepLearning
configSettingsJson['basic']['machineLearning'] = machineLearning
configSettingsJson['basic']['reinforcementLearning'] = reinforcementLearning
except Exception as e:
print(e)
return (configSettingsJson)
def basicconfignex(request):
#pemfilename = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','modelTraining','static','key','AION_GPU.pem'))
try:
updatedConfigFile = request.session['config_json']
f = open(updatedConfigFile, "r+")
configSettingsData = f.read()
configSettingsJson = json.loads(configSettingsData)
#---------------- default Hypermarameter changes-------------Usnish--------------
hyperparamFile = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','config', 'hyperparam_config.json'))
with open(hyperparamFile) as json_file:
hyperparamConfig = json.load(json_file)
#---------------- default Hypermarameter changes end-------------Usnish--------------
# ------------------ Debiasing Changes ------------------
categorical_features = []
class_list = []
MachineLearningModels = []
check_traget = configSettingsJson['basic']['targetFeature']
selectedDebiasingFeature = 'None'
selectedDebiasingClass = 'None'
selectedDebiasingAlgorithm = ''
problemtypes = configSettingsJson['basic']['analysisType']
problem_type = ""
for k in problemtypes.keys():
if configSettingsJson['basic']['analysisType'][k] == 'True':
problem_type = k
break
if request.method == 'GET':
for key in configSettingsJson['basic']['algorithms'][problem_type]:
if configSettingsJson['basic']['algorithms'][problem_type][key] == 'True':
MachineLearningModels.append(key)
else:
MachineLearningModels = request.POST.getlist('MachineLearningModels')
if problem_type.lower() in ['classification','regression']:
if check_traget != '':
try:
if 'deBiasing' in configSettingsJson['advance']['profiler']:
deBiasing = configSettingsJson['advance']['profiler']['deBiasing']
selectedDebiasingFeature = deBiasing.get('FeatureName','None')
selectedDebiasingClass = deBiasing.get('ClassName','None')
selectedDebiasingAlgorithm = deBiasing.get('Algorithm','')
if selectedDebiasingFeature != 'None':
df = pd.read_csv(configSettingsJson['basic']['dataLocation'],encoding='utf8',encoding_errors= 'replace')
classeslist = []
classeslist = df[selectedDebiasingFeature].unique().tolist()
for item in classeslist:
class_list.append(item)
else:
class_list.append('None')
except:
pass
feature_dict = configSettingsJson['advance']['profiler']['featureDict']
for feature_config in feature_dict:
if feature_config.get('type', '') == 'categorical' and feature_config['feature'] != check_traget:
categorical_features.append(feature_config['feature'])
# ------------------ ------------------
#print(categorical_features)
temp = {}
temp['ModelName'] = request.session['UseCaseName']
temp['Version'] = request.session['ModelVersion']
config = {}
config['modelName'] = request.session['UseCaseName']
config['modelVersion'] = request.session['ModelVersion']
config['datetimeFeatures'] = configSettingsJson['basic']['dateTimeFeature']
config['sequenceFeatures'] = configSettingsJson['basic']['indexFeature']
config['FeaturesList'] = configSettingsJson['basic']['trainingFeatures']
config['unimportantFeatures'] = ''
config['targetFeature'] = configSettingsJson['basic']['targetFeature']
deepLearning = 'False'
machineLearning = 'False'
reinforcementLearning = 'False'
selectAlgo = ""
print(problem_type)
if problem_type.lower() in ['classification','regression']:
for key in configSettingsJson['basic']['algorithms'][problem_type]:
if configSettingsJson['basic']['algorithms'][problem_type][key] == 'True':
if key in ['Neural Network','Convolutional Neural Network (1D)','Recurrent Neural Network','Recurrent Neural Network (GRU)','Recurrent Neural Network (LSTM)','Neural Architecture Search']:
deepLearning = 'True'
if key in ['Logistic Regression','Naive Bayes','Decision Tree','Random Forest','Support Vector Machine','K Nearest Neighbors','Gradient Boosting','Extreme Gradient Boosting (XGBoost)','Light Gradient Boosting (LightGBM)','Categorical Boosting (CatBoost)','Linear Regression','Lasso','Ridge','Decision Tree','Random Forest','Bagging (Ensemble)']:
machineLearning = 'True'
if key in ['Deep Q Network','Dueling Deep Q Network']:
reinforcementLearning = 'True'
elif problem_type.lower() in ['clustering','topicmodelling']:#clustering(Bug 12611)
machineLearning = 'True'
configSettingsJson['basic']['deepLearning'] = deepLearning
configSettingsJson['basic']['machineLearning'] = machineLearning
configSettingsJson['basic']['reinforcementLearning'] = reinforcementLearning
if problem_type in ['classification','regression','timeSeriesForecasting',
'timeSeriesAnomalyDetection',
'recommenderSystem','clustering','anomalyDetection','topicModelling','survivalAnalysis','videoForecasting','imageClassification','objectDetection','stateTransition']: #task 11997
for key in configSettingsJson['basic']['algorithms'][problem_type]:
if configSettingsJson['basic']['algorithms'][problem_type][key] == 'True':
if selectAlgo != "":
selectAlgo += ','
selectAlgo += key
if problem_type not in ['classification','regression']:
break
if problem_type == 'objectDetection':
from AION import pretrainedModels
ptmObj = pretrainedModels()
obModels = ptmObj.get_info(selectAlgo)
else:
obModels = {}
problemType = problem_type
selected_use_case = request.session['UseCaseName']
ModelVersion = request.session['ModelVersion']
ModelStatus = request.session['ModelStatus']
request.session['currentstate'] = 2
#configSettingsJson['advance']['remoteTraining']['ssh']['keyFilePath'] = pemfilename
if request.session['finalstate'] <= 2:
request.session['finalstate'] = 2
outlierDetection = 'False'
for x in list(configSettingsJson['advance']['profiler']['outlierDetection'].keys()):
if configSettingsJson['advance']['profiler']['outlierDetection'][x] == 'True':
outlierDetection = 'True'
if outlierDetection == 'False':
configSettingsJson['advance']['profiler']['outlierDetection']['Disable'] = 'True'
else:
configSettingsJson['advance']['profiler']['outlierDetection']['Disable'] = 'False'
if 'distributedLearning' not in configSettingsJson['basic']:
configSettingsJson['basic']['distributedLearning'] = 'False'
configSettingsJson['advance']['mllearner_config']['EnsembleStacking']=configSettingsJson['advance']['mllearner_config']['Stacking (Ensemble)']
configSettingsJson['advance']['mllearner_config']['EnsembleVoting']=configSettingsJson['advance']['mllearner_config']['Voting (Ensemble)']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['LogisticRegression'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Logistic Regression']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['GaussianNB'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Naive Bayes']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['SVC'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Support Vector Machine']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['KNeighborsClassifier'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['K Nearest Neighbors']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['DecisionTreeClassifier'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Decision Tree']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['RandomForestClassifier'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Random Forest']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['GradientBoostingClassifier'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Gradient Boosting']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['ExtremeGradientBoostingClassifier'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Extreme Gradient Boosting (XGBoost)']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['LightGradientBoostingClassifier'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Light Gradient Boosting (LightGBM)']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['CategoricalBoostingClassifier'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Categorical Boosting (CatBoost)']
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['SNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['Neural Network']
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['SimpleRNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['Recurrent Neural Network']
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['GRURNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['Recurrent Neural Network (GRU)']
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['LSTMRNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['Recurrent Neural Network (LSTM)']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']=configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleStacking']=configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Stacking (Ensemble)']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['LogisticRegression'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['Logistic Regression']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['NaiveBayes'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['Naive Bayes']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['SVM'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['Support Vector Machine']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['KNN'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['K Nearest Neighbors']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['DecisionTree'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['Decision Tree']
configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['RandomForest'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['Random Forest']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['SimpleRNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['GRURNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network (GRU)']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['LSTMRNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network (LSTM)']
configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams']['DQN'] = configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams']['Deep | ||
Q Network']
configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams']['DDQN'] = configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams']['Dueling Deep Q Network']
configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams']['DQN'] = configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams']['Deep Q Network']
configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams']['DDQN'] = configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams']['Dueling Deep Q Network']
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['CNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['Convolutional Neural Network (1D)']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['LinearRegression'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Linear Regression']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['DecisionTreeRegressor'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Decision Tree']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['RandomForestRegressor'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Random Forest']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['XGBoostRegressor'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Extreme Gradient Boosting (XGBoost)']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['LightGBMRegressor'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Light Gradient Boosting (LightGBM)']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['CatBoostRegressor'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Categorical Boosting (CatBoost)']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleStacking']=configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Stacking (Ensemble)']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging']=configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging']['LinearRegression'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging']['Linear Regression']
configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging']['DecisionTree'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging']['Decision Tree']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['NAS'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'].get('Neural Architecture Search')
configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['NAS'] = configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams'].get('Neural Architecture Search')
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['SNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Neural Network']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['SimpleRNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['GRURNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network (GRU)']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['LSTMRNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network (LSTM)']
configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['CNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Convolutional Neural Network (1D)']
configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['OnlineLogisticRegression'] = configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online Logistic Regression']
configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['OnlineDecisionTreeClassifier'] = configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online Decision Tree Classifier']
configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['OnlineSoftmaxRegression'] = configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online Softmax Regression']
configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['OnlineKNNClassifier'] = configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online KNN Classifier']
configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['OnlineLinearRegression'] = configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['Online Linear Regression']
configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['OnlineDecisionTreeRegressor'] = configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['Online Decision Tree Regressor']
configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['OnlineKNNRegressor'] = configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['Online KNN Regressor']
configSettingsJson['advance']['profiler']['textConversionMethod']['LatentSemanticAnalysis'] = configSettingsJson['advance']['profiler']['textConversionMethod']['LatentSemanticAnalysis']
configSettingsJson['advance']['profiler']['embeddingSize']['LatentSemanticAnalysis'] = configSettingsJson['advance']['profiler']['embeddingSize']['LatentSemanticAnalysis']
if 'llmFineTuning' in configSettingsJson['advance']:
configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA2'] = configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA-2']
configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA2Chat'] = configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA-2-Chat']
configSettingsJson['basic']['algorithms']['llmFineTuning']['CodeLLaMA2'] = configSettingsJson['basic']['algorithms']['llmFineTuning']['CodeLLaMA-2']
configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA2'] = configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA-2']
configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA2Chat'] = configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA-2-Chat']
configSettingsJson['advance']['llmFineTuning']['modelParams']['CodeLLaMA2'] = configSettingsJson['advance']['llmFineTuning']['modelParams']['CodeLLaMA-2']
configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA2'] = \\
configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA-2']
configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA2Chat'] = \\
configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA-2-Chat']
configSettingsJson['basic']['modelSize']['llmFineTuning']['CodeLLaMA2'] = \\
configSettingsJson['basic']['modelSize']['llmFineTuning']['CodeLLaMA-2']
if 'distributedlearner_config' in configSettingsJson['advance']:
configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['DistributedXGBoost'] = configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['Distributed Extreme Gradient Boosting (XGBoost)']
configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['DistributedLightGBM'] = configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['Distributed Light Gradient Boosting (LightGBM)']
configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams']['DistributedXGBoost'] = configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams']['Distributed Extreme Gradient Boosting (XGBoost)']
configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams']['DistributedLightGBM'] = configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams']['Distributed Light Gradient Boosting (LightGBM)']
configSettingsJson['advance']['profiler']['normalizationMethod'] = 'None'
normalizationtypes = configSettingsJson['advance']['profiler']['normalization']
for k in normalizationtypes.keys():
if configSettingsJson['advance']['profiler']['normalization'][k] == 'True':
configSettingsJson['advance']['profiler']['normalizationMethod'] = k
break
context = {'temp': temp, 'advconfig': configSettingsJson, 'MachineLearningModels':MachineLearningModels,'hyperparamConfig':hyperparamConfig,'config': config, 'selected_use_case': selected_use_case,
'categorical_features': categorical_features, 'selectedDebiasingFeature': selectedDebiasingFeature, 'selectedDebiasingAlgorithm': selectedDebiasingAlgorithm, 'Class_list': class_list, 'selectedDebiasingClass': selectedDebiasingClass, #Debiasing Changes
'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion,"obModels":obModels,"problemType":problemType,
'currentstate': request.session['currentstate'], 'finalstate': request.session['finalstate'],
'selected': 'modeltraning','advance_help':ht.advance_help}
return context
except Exception as e:
print(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
context={'erroradvance':'Fail to load advance config Json file'}
return context
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
def analysis_images(folder_path):
from AIX import image_eda
qualityscore = image_eda.img_MeasureImageQuality(folder_path)
eda_result = image_eda.img_EDA(folder_path)
#Image Duplicate Finder
duplicate_img = image_eda.img_duplicatefinder(folder_path)
color_plt = image_eda.img_plot_colour_hist(folder_path)
return qualityscore,eda_result,duplicate_img,color_plt<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import json
import time
import os
import subprocess
import base64
import sys
import re
from appbe.dataIngestion import getcommonfields
from appbe.dataIngestion import getusercasestatus
def startSummarization(request,DEFAULT_FILE_PATH,CONFIG_PATH,DATA_FILE_PATH):
try:
if request.FILES:
Datapath = request.FILES['summarypath']
ext = str(Datapath).split('.')[-1]
filetimestamp = str(int(time.time()))
if ext.lower() in ['txt','pdf','doc','docs']:
dataFile = os.path.join(DATA_FILE_PATH,'AION_' + filetimestamp+'.'+ext)
else:
dataFile = os.path.join(DATA_FILE_PATH,'AION_' + filetimestamp)
with open(dataFile, 'wb+') as destination:
for chunk in Datapath.chunks():
destination.write(chunk)
destination.close()
configFile = os.path.join(DEFAULT_FILE_PATH,'aion_textSummerization.json')
filetimestamp = str(int(time.time()))
config_json_filename = os.path.join(CONFIG_PATH, 'AION_' + filetimestamp + '.json')
f = open(configFile)
data = json.load(f)
f.close()
data['basic']['dataLocation'] = dataFile
type = request.POST.get('type')
model = request.POST.get('model')
slength = request.POST.get('length')
types = data['basic']['analysisAproach']['textSummarization']
for x in list(types.keys()):
data['basic']['analysisAproach']['textSummarization'][x] = 'False'
data['basic']['analysisAproach']['textSummarization'][type] = 'True'
format = request.POST.get('format')
algorithm = data['basic']['algorithms']['textSummarization']
for x in list(algorithm.keys()):
data['basic']['algorithms']['textSummarization'][x] = 'False'
data['basic']['algorithms']['textSummarization'][model]='True'
length = data['advance']['textSummarization']['summaryLength']
for x in list(types.keys()):
data['advance']['textSummarization']['summaryLength'][x] = 'False'
data['advance']['textSummarization']['summaryLength'][slength] = 'True'
with open(config_json_filename, "w") as outfile:
json.dump(data, outfile)
outfile.close()
from bin.aion_text_summarizer import aion_textsummary
outputStr = aion_textsummary(config_json_filename) | ||
#scriptPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','bin','aion_text_summarizer.py'))
#outputStr = subprocess.check_output([sys.executable, scriptPath, config_json_filename])
#outputStr = outputStr.decode('utf-8')
#outputStr = re.search(r'Summary:(.*)', str(outputStr), re.IGNORECASE).group(1)
predict_dict = json.loads(str(outputStr))
summary = predict_dict['summary']
except Exception as e:
print(e)
summary = str(e)
context = getcommonfields()
selected_use_case,ModelVersion,ModelStatus = getusercasestatus(request)
context.update({'selected_use_case': selected_use_case,'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion})
context.update({'summary':summary})
return context <s> import os
import re
import json
import time
import sys
import tiktoken
import openai
import requests
from appbe.aion_config import get_llm_data
import logging
import pdfplumber
from docx import Document
openai.api_key = ''
openai.api_base = ''
openai.api_type = ''
openai.api_version = ''
deployment_name="GPT-35-Turbo"
model_name='gpt-3.5-turbo'
set_tokens_limit = 500
set_tokens_limit_offline = 400
set_prompt="You are an expert user generating questions and answers. You will be passed a page extracted from a documentation. Generate a numbered list of questions as Q. and equivelant answer as A. for every question based *solely* on the given text."
# QnA Generator using LLM related changes
# --------------------------------------------------------
def ingestDataForQA(request, DATA_FILE_PATH):
log = logging.getLogger('log_ux')
try:
Datapath = request.FILES['DataFileQnA']
from appbe.eda import ux_eda
ext = str(Datapath).split('.')[-1]
request.session['uploadfiletype'] = 'Local'
request.session['datatype'] = 'Normal'
filetimestamp = str(int(time.time()))
if ext.lower() in ['txt','pdf','docx']:
dataFile = os.path.join(DATA_FILE_PATH,'AION_' + filetimestamp+'.'+ext)
else:
dataFile = os.path.join(DATA_FILE_PATH,'AION_' + filetimestamp)
with open(dataFile, 'wb+') as destination:
for chunk in Datapath.chunks():
destination.write(chunk)
destination.close()
dataPath = dataFile
request.session['textdatapathQA'] = dataPath
llm_choice = request.POST.get("llm_choice")
_result = ''
# if llm_choice == 'Haystack':
# _result = generateQA_Haystack(request, DATA_FILE_PATH)
if llm_choice == 'Offline':
_result = generateQA_Offline(request, DATA_FILE_PATH)
else:
_result = generateQA_OpenAI(request, DATA_FILE_PATH)
return _result
except Exception as e:
print(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
context = {'error': 'Failed to read data','emptytxt' : 'emptytxt'}
log.info('Text Data Ingestion -- Error : Failed to read data, '+str(e))
log.info('Details : '+ str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
return context
# ---------------------- E N D ---------------------------
def generateQA_OpenAI(request, DATA_FILE_PATH):
log = logging.getLogger('log_ux')
try:
file_path = request.session['textdatapathQA']
# Read the file content
if file_path.endswith('.pdf'):
pdf_file=pdfplumber.open(file_path)
file_content = " ".join([x.extract_text() for x in pdf_file.pages])
elif file_path.endswith('.docx'):
doc_file=Document(file_path)
file_content = " \\n".join([x.text for x in doc_file.paragraphs])
else:
with open(file_path, "r", encoding="utf-8",errors = "ignore") as file:
file_content = file.read()
text = file_content.strip()
#text = text.strip()
extracted_QnA = []
chunk_counter = 0
num_tokens_text = count_tokens_text(text)
if num_tokens_text > set_tokens_limit:
for sub_text in split_text(text):
chunk_counter = chunk_counter + 1
_result = extract_questions_from_splittedtext(sub_text)
print(f"Currently executed chunk no is - {chunk_counter}.")
extracted_QnA.extend(_result)
else:
_prompt = set_prompt
msg = [ {"role": "system", "content": _prompt},
{"role": "user", "content": text} ]
extracted_QnA = run_model(msg)
quesCount = len(extracted_QnA)
context = {'extracted_QnA':extracted_QnA, 'quesCount':quesCount}
filetimestamp = str(int(time.time()))
output_filepath = os.path.join(DATA_FILE_PATH,'AION_QnA' + filetimestamp+'.txt')
# Save the extracted questions as a JSON file
with open(output_filepath, 'w') as output_file:
json.dump(extracted_QnA, output_file, indent=4)
print(f"QnAs have been saved to {output_filepath}.")
request.session['QnAfilepath'] = output_filepath
return context
except Exception as e:
print(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
errormsg = str(e)
if 'Invalid URL' in errormsg or 'No connection adapters' in errormsg or 'invalid subscription key' in errormsg:
errormsg = 'Access denied due to invalid subscription key or wrong API endpoint. Please go to settings and make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource.'
if 'The API type provided in invalid' in errormsg:
errormsg = "The API type provided is invalid. Please select one of the supported API types:'azure', 'azure_ad' or 'open_ai'"
if 'Max retries exceeded with url' in errormsg:
errormsg = 'Please make sure you have good internet connection and access to API endpoint for your resource.'
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
context = {'error': 'Failed to generate QnA List using openAI','LLM' : 'openAI', 'selected':'DataOperations', 'errormessage':errormsg}
log.info('generateQA_OpenAI -- Error : Failed to generate QnA List using openAI.. '+str(e))
log.info('Details : '+ str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
return context
def run_model(msg):
key,url,api_type,api_version = get_llm_data()
openai.api_key = key
openai.api_base = url
openai.api_type = api_type
openai.api_version = api_version
completions = openai.ChatCompletion.create(engine=deployment_name, temperature=0.0, max_tokens=2000, n=1, stop=None, messages=msg)
# return completions.choices[0].message.content
_questionList = completions.choices[0].message.content
question_pattern = re.compile(r"^Q\\s*\\d+\\.\\s*(.+)$", re.MULTILINE)
questions = question_pattern.findall(_questionList)
answer_pattern = re.compile(r"^A\\s*\\d+\\.\\s*(.+)$", re.MULTILINE)
answers = answer_pattern.findall(_questionList)
if (len(questions) > 0) and (not re.search(r"[.!?)]$", questions[-1].strip())):
print(f"WARNING: Popping incomplete question: '{questions[-1]}'")
questions.pop()
extracted_QnA = []
for question, answer in zip(questions, answers):
extracted_QnA.append({'question': question, 'answer': answer})
return extracted_QnA
def count_tokens_text(text):
import tiktoken
model_type = model_name
encoding = tiktoken.encoding_for_model(model_type)
encoded_text = encoding.encode(text)
return len(encoded_text)
def extract_questions_from_splittedtext(text):
_prompt = set_prompt
msg = [ {"role": "system", "content": _prompt},
{"role": "user", "content": text} ]
_ques_ans_List = run_model(msg)
return _ques_ans_List
def split_text(text):
lines = text.split('\\n')
current_section = ''
sections = []
_lastsection = 0
for line in lines:
num_tokens_text = count_tokens_text(''.join([current_section,line]))
if num_tokens_text < set_tokens_limit:
current_section = ''.join([current_section,line])
else:
sections.append(current_section)
current_section = line
_lastsection = 1
if _lastsection == 1:
sections.append(current_section)
return sections
# --------------------------------------------------------------------------------- #
def generateQA_Haystack(request, DATA_FILE_PATH):
file_path = request.session['textdatapathQA']
# Read the file content
with open(file_path, "r", encoding="utf-8") as file:
file_content = file.read()
text = file_content.strip()
text = text.strip()
docs = []
num_tokens_text = count_tokens_text(text)
if num_tokens_text > set_tokens_limit:
for sub_text in split_text(text):
docs.append({"content": sub_text})
else:
docs = [{"content": text}]
from pprint import pprint
from tqdm.auto import tqdm
from haystack.nodes import QuestionGenerator, BM25Retriever, FARMReader
# from haystack.document_stores import ElasticsearchDocumentStore
from haystack.document_stores import InMemoryDocumentStore
# from haystack.document_stores import PineconeDocumentStore
from haystack.pipelines import (
QuestionGenerationPipeline,
RetrieverQuestionGenerationPipeline,
QuestionAnswerGenerationPipeline,
)
from haystack.utils import print_questions
document_store = InMemoryDocumentStore(use_bm25=True)
document_store.write_documents(docs)
question_generator = QuestionGenerator()
# reader = FARMReader("deepset/roberta-base-squad2")
# reader.save("my_local_roberta_model")
reader_local = FARMReader(model_name_or_path="my_local_roberta_model_1")
qag_pipeline = QuestionAnswerGenerationPipeline(question_generator, reader_local)
extracted_QnA = []
for idx, document in enumerate(tqdm(document_store)):
print(f"\\n * Generating questions and answers for document {idx}: {document.content[:100]}...\\n")
result = qag_pipeline.run(documents=[document])
print_questions(result)
answers = []
questions = result['queries']
answerList = result["answers"]
for _answers in answerList:
for answer in _answers:
ans = answer.answer
answers.append(ans)
for question, answer in zip(questions, answers):
extracted_QnA.append({'question': question, 'answer': answer})
quesCount = len(extracted_QnA)
context = {'extracted_QnA':extracted_QnA, 'quesCount':quesCount}
filetimestamp = str(int(time.time()))
output_filepath = os.path.join(DATA_FILE_PATH,'AION_QnA' + filetimestamp+'.txt')
# Save the extracted questions as a JSON file
with open(output_filepath, 'w') as output_file:
json.dump(extracted_QnA, output_file, indent=4)
print(f"QnAs have been saved to {output_filepath}.")
request.session['QnAfilepath'] = output_filepath
return context
# --------------------------------------------------------------------------------- #
def generateQA_Offline(request, DATA_FILE_PATH):
log = logging.getLogger('log_ux')
try:
file_path = request.session['textdatapathQA']
if file_path.endswith('.pdf'):
pdf_file=pdfplumber.open(file_path)
file_content = " ".join([x.extract_text() for x in pdf_file.pages])
elif file_path.endswith('.docx'):
doc_file=Document(file_path)
file_content = " \\n".join([x.text for x in doc_file.paragraphs])
else:
with open(file_path, "r", encoding="utf-8",errors = "ignore") as file:
file_content = file.read()
# # Read the file content
# with open(file_path, "r", encoding="utf-8") as file:
# file_content = file.read()
text = file_content.strip()
# text = text.strip()
docs = []
# num_tokens_text = count_tokens_text(text)
# if num_tokens_text > set_tokens_limit:
# for sub_text in split_text(text):
# docs.append(sub_text)
# else:
# docs.append(text)
model_name = "valhalla/t5-base-qg-hl"
num_tokens_text = count_tokens_text_offline(text, model_name)
if num_tokens_text > set_tokens_limit_offline:
for sub_text in split_text_for_Off | ||
line(text, model_name):
docs.append(sub_text)
else:
docs.append(text)
from question_generation.pipelines import pipeline
extracted_QnA = []
extracted_QnAList = []
nlp = pipeline("question-generation", model = model_name)
# nlp = pipeline("question-generation", model="valhalla/t5-base-e2e-qg")
# nlp = pipeline("e2e-qg", model="valhalla/t5-base-qg-hl")
# nlp = pipeline("multitask-qa-qg", model="valhalla/t5-base-qa-qg-hl")
for _text in docs:
res = nlp(_text)
print(res)
extracted_QnAList.extend(res)
for _record in extracted_QnAList:
extracted_QnA.append({'question': _record['question'], 'answer': _record['answer'].replace('<pad>', '')})
quesCount = len(extracted_QnA)
context = {'extracted_QnA':extracted_QnA, 'quesCount':quesCount}
filetimestamp = str(int(time.time()))
output_filepath = os.path.join(DATA_FILE_PATH,'AION_QnA' + filetimestamp+'.txt')
# Save the extracted questions as a JSON file
with open(output_filepath, 'w') as output_file:
json.dump(extracted_QnA, output_file, indent=4)
print(f"T5 based QnAs have been saved to {output_filepath}.")
request.session['QnAfilepath'] = output_filepath
return context
except Exception as e:
print(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
errormsg = str(e)
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
context = {'error': 'Failed to generate QnA List using T5','LLM' : 'T5', 'selected':'DataOperations', 'errormessage':errormsg}
log.info('generateQA_Offline -- Error : Failed to generate QnA List using T5.. '+str(e))
log.info('Details : '+ str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
return context
def split_text_for_Offline(text, model_name):
lines = text.split('\\n')
current_section = ''
sections = []
_lastsection = 0
for line in lines:
num_tokens = count_tokens_text_offline(''.join([current_section,line]), model_name)
if num_tokens < set_tokens_limit_offline:
current_section = ''.join([current_section,line])
else:
sections.append(current_section)
current_section = line
_lastsection = 1
if _lastsection == 1:
sections.append(current_section)
return sections
def count_tokens_text_offline(text, model_name):
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(model_name)
inputs = tokenizer(text, return_tensors="pt")
input_ids = inputs["input_ids"]
_token_count = len(input_ids[0])
return _token_count
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os
from pathlib import Path
def label_filename(request):
filename = 'LabeledData.csv'
labelPath = os.path.join(request.session['datalocation'],'AION','Labels')
Path(labelPath).mkdir(parents=True, exist_ok=True)
filePath = os.path.join(labelPath,filename)
return filePath
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import kfp
import kfp.dsl as dsl
import json
from pathlib import Path
class aionpipeline():
containerRegistry = str()
containerLabel = str()
containerSecret = str()
pipelineName = 'AION MLOps Pipeline {0}'
exeCmd = 'python'
codeFile = 'aionCode.py'
mntPoint = '/aion'
inputArg = '-i'
msIP = '0.0.0.0'
port = '8094'
cachingStrategy = 'P0D'
deafultVolume = '1Gi'
volName = 'aion-pvc'
volMode = 'ReadWriteMany'
fileExt = '.tar.gz'
fileName = 'aion_mlops_pipeline_{0}'
containerMM = 'modelmonitoring'
containerDI = 'dataingestion'
containerDT = 'datatransformation'
containerFE = 'featureengineering'
containerMR = 'modelregistry'
containerMS = 'modelserving'
containerImage = '{0}/{1}:{2}'
models = {}
nameSeprator = '-'
modelsLiteral = 'models'
modelNameLiteral = 'modelname'
msTemplate = '{"apiVersion": "v1", "kind": "Pod", "metadata": {"name": "{{workflow.name}}-{0}"}, "spec": {"containers": [{"name": "{0}", "image": "{1}", "command": ["python"], "args": ["aionCode.py", "-ip", "{2}", "-pn", "{3}"],"volumeMounts": [{"name": "aion-pvc", "mountPath": "{4}"}], "ports": [{"name": "http", "containerPort": {3}, "protocol": "TCP"}]}], "imagePullSecrets": [{"name": "{5}"}], "volumes": [{"name": "aion-pvc", "persistentVolumeClaim": {"claimName": "{{workflow.name}}-{6}"}}]}}'
def __init__(self, models, containerRegistry, containerLabel, containerSecret=str()):
self.models = models
self.containerRegistry = containerRegistry
self.containerLabel = containerLabel
self.containerSecret = containerSecret
@dsl.pipeline(
name=pipelineName.format(containerLabel),
description=pipelineName.format(containerLabel),
)
def aion_mlops(self, inputUri=str(), volSize=deafultVolume):
vop = dsl.VolumeOp(
name=self.volName + self.nameSeprator + self.containerLabel,
resource_name=self.volName,
modes=[self.volMode],
size=volSize
)
mm = dsl.ContainerOp(
name=self.containerMM,
image=self.containerImage.format(self.containerRegistry,self.containerMM,self.containerLabel),
command=self.exeCmd,
arguments=[
self.codeFile,
self.inputArg,
inputUri,
],
pvolumes={self.mntPoint: vop.volume}
)
mm.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy
di = dsl.ContainerOp(
name=self.containerDI,
image=self.containerImage.format(self.containerRegistry,self.containerDI,self.containerLabel),
command=self.exeCmd,
arguments=[
self.codeFile,
],
pvolumes={self.mntPoint: mm.pvolume}
)
di.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy
dt = dsl.ContainerOp(
name=self.containerDT,
image=self.containerImage.format(self.containerRegistry,self.containerDT,self.containerLabel),
command=self.exeCmd,
arguments=[
self.codeFile,
],
pvolumes={self.mntPoint: di.pvolume}
)
dt.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy
fe = dsl.ContainerOp(
name=self.containerFE,
image=self.containerImage.format(self.containerRegistry,self.containerFE,self.containerLabel),
command=self.exeCmd,
arguments=[
self.codeFile,
],
pvolumes={self.mntPoint: dt.pvolume}
)
fe.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy
dictMT = {}
listMTOps = []
for model in self.models[self.modelsLiteral]:
modelName = model[self.modelNameLiteral]
mt=dsl.ContainerOp(
name=modelName,
image=self.containerImage.format(self.containerRegistry,modelName,self.containerLabel),
command=self.exeCmd,
arguments=[
self.codeFile,
],
pvolumes={self.mntPoint: fe.pvolume})
mt.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy
listMTOps.append(mt)
dictMT[self.mntPoint]=mt.pvolume
mr = dsl.ContainerOp(
name=self.containerMR,
image=self.containerImage.format(self.containerRegistry,self.containerMR,self.containerLabel),
command=self.exeCmd,
arguments=[
self.codeFile,
],
pvolumes=dictMT
).after(*tuple(listMTOps))
mr.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy
msJson = self.msTemplate.replace(str({0}),self.containerMS).replace(str({1}),self.containerImage.format(self.containerRegistry,self.containerMS,self.containerLabel)).replace(str({2}),self.msIP).replace(str({3}),self.port).replace(str({4}),self.mntPoint).replace(str({5}),self.containerSecret).replace(str({6}),self.volName)
ms = dsl.ResourceOp(
name=self.containerMS + self.nameSeprator + self.containerLabel,
k8s_resource=json.loads(msJson),
)
ms.after(mr)
def compilepl(self, targetPath=str()):
filePath = self.fileName.format(self.containerLabel.lower()) + self.fileExt
if targetPath != str():
filePath = Path(targetPath, filePath)
kfp.compiler.Compiler().compile(self.aion_mlops, str(filePath))
def executepl(self, kfhost=str()):
client = kfp.Client(kfhost)
client.create_run_from_pipeline_func(self.aion_mlops,arguments={})
<s><s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os
import sys
import json
import datetime, time, timeit
import logging
logging.getLogger('tensorflow').disabled = True
import shutil
import warnings
from config_manager.online_pipeline_config import OTAionConfigManager
from records import pushrecords
import logging
import mlflow
from pathlib import Path
from pytz import timezone
def pushRecordForOnlineTraining():
try:
from appbe.pages import getversion
status,msg = pushrecords.enterRecord(AION_VERSION)
except Exception as e:
print("Exception", e)
status = False
msg = str(e)
return status,msg
def mlflowSetPath(path,experimentname):
import mlflow
url = "file:" + str(Path(path).parent.parent) + "/mlruns"
mlflow.set_tracking_uri(url)
mlflow.set_experiment(str(experimentname))
class server():
def __init__(self):
self.response = None
self.dfNumCols=0
self.dfNumRows=0
self.features=[]
self.mFeatures=[]
self.emptyFeatures=[]
self.vectorizerFeatures=[]
self.wordToNumericFeatures=[]
self.profilerAction = []
self.targetType = ''
self.matrix1='{'
self.matrix2='{'
self.matrix='{'
self.trainmatrix='{'
self.numericalFeatures=[]
self.nonNumericFeatures=[]
self.similarGroups=[]
self.method = 'NA'
self.pandasNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
self.modelSelTopFeatures=[]
self.topFeatures=[]
self.allFeatures=[]
def startScriptExecution(self, config_obj):
rowfilterexpression = ''
grouperbyjson = ''
model_tried=''
learner_type = ''
topics = {}
numericContinuousFeatures=''
discreteFeatures=''
threshold=-1
targetColumn = ''
categoricalFeatures=''
dataFolderLocation = ''
original_data_file = ''
profiled_data_file = ''
trained_data_file = ''
predicted_data_file=''
featureReduction = 'False'
reduction_data_file=''
params={}
score = 0
labelMaps={}
featureDataShape=[]
self.riverModels = []
self.riverAlgoNames = ['Online Logistic Regression', 'Online Softmax Regression', 'Online Decision Tree Classifier', 'Online KNN Classifier', 'Online Linear Regression', 'Online Bayesian Linear Regression', 'Online Decision Tree Regressor','Online KNN Regressor']
#ConfigSettings
iterName,iterVersion,dataLocation,deployLocation,delimiter,textqualifier = | ||
config_obj.getAIONLocationSettings()
scoreParam = config_obj.getScoringCreteria()
datetimeFeature,indexFeature,modelFeatures=config_obj.getFeatures()
iterName = iterName.replace(" ", "_")
deployLocation,dataFolderLocation,original_data_file,profiled_data_file,trained_data_file,predicted_data_file,logFileName,outputjsonFile = config_obj.createDeploymentFolders(deployLocation,iterName,iterVersion)
#Mlflow
mlflowSetPath(deployLocation,iterName+'_'+iterVersion)
#Logger
filehandler = logging.FileHandler(logFileName, 'w','utf-8')
formatter = logging.Formatter('%(message)s')
filehandler.setFormatter(formatter)
log = logging.getLogger('eion')
log.propagate = False
for hdlr in log.handlers[:]: # remove the existing file handlers
if isinstance(hdlr,logging.FileHandler):
log.removeHandler(hdlr)
log.addHandler(filehandler)
log.setLevel(logging.INFO)
log.info('************* Version - v2.2.5 *************** \\n')
msg = '-------> Execution Start Time: '+ datetime.datetime.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S' + ' IST')
log.info(msg)
startTime = timeit.default_timer()
try:
output = {'bestModel': '', 'bestScore': 0, 'bestParams': {}}
#ConfigSetting
problemType,targetFeature,profilerStatus,selectorStatus,learnerStatus,visualizationstatus,deployStatus = config_obj.getModulesDetails()
selectorStatus = False
if(problemType.lower() in ['classification','regression']):
if(targetFeature == ''):
output = {"status":"FAIL","message":"Target Feature is Must for Classification and Regression Problem Type"}
return output
#DataReading
from transformations.dataReader import dataReader
objData = dataReader()
if os.path.isfile(dataLocation):
dataFrame = objData.csvTodf(dataLocation,delimiter,textqualifier)
dataFrame.rename(columns=lambda x:x.strip(), inplace=True)
#FilterDataframe
filter = config_obj.getfilter()
if filter != 'NA':
dataFrame,rowfilterexpression = objData.rowsfilter(filter,dataFrame)
#GroupDataframe
timegrouper = config_obj.gettimegrouper()
grouping = config_obj.getgrouper()
if grouping != 'NA':
dataFrame,grouperbyjson = objData.grouping(grouping,dataFrame)
elif timegrouper != 'NA':
dataFrame,grouperbyjson = objData.timeGrouping(timegrouper,dataFrame)
#KeepOnlyModelFtrs
dataFrame = objData.removeFeatures(dataFrame,datetimeFeature,indexFeature,modelFeatures,targetFeature)
log.info('\\n-------> First Ten Rows of Input Data: ')
log.info(dataFrame.head(10))
self.dfNumRows=dataFrame.shape[0]
self.dfNumCols=dataFrame.shape[1]
dataLoadTime = timeit.default_timer() - startTime
log.info('-------> COMPUTING: Total dataLoadTime time(sec) :'+str(dataLoadTime))
if profilerStatus:
log.info('\\n================== Data Profiler has started ==================')
log.info('Status:-|... AION feature transformation started')
dp_mlstart = time.time()
profilerJson = config_obj.getEionProfilerConfigurarion()
log.info('-------> Input dataFrame(5 Rows): ')
log.info(dataFrame.head(5))
log.info('-------> DataFrame Shape (Row,Columns): '+str(dataFrame.shape))
from incremental.incProfiler import incProfiler
incProfilerObj = incProfiler()
dataFrame,targetColumn,self.mFeatures,self.numericalFeatures,self.nonNumericFeatures,labelMaps,self.configDict,self.textFeatures,self.emptyFeatures,self.wordToNumericFeatures = incProfilerObj.startIncProfiler(dataFrame,profilerJson,targetFeature,deployLocation,problemType)
self.features = self.configDict['allFtrs']
log.info('-------> Data Frame Post Data Profiling(5 Rows): ')
log.info(dataFrame.head(5))
log.info('Status:-|... AION feature transformation completed')
dp_mlexecutionTime=time.time() - dp_mlstart
log.info('-------> COMPUTING: Total Data Profiling Execution Time '+str(dp_mlexecutionTime))
log.info('================== Data Profiling completed ==================\\n')
dataFrame.to_csv(profiled_data_file,index=False)
selectorStatus = False
if learnerStatus:
log.info('Status:-|... AION Learner data preparation started')
ldp_mlstart = time.time()
testPercentage = config_obj.getAIONTestTrainPercentage()
balancingMethod = config_obj.getAIONDataBalancingMethod()
from learner.machinelearning import machinelearning
mlobj = machinelearning()
modelType = problemType.lower()
targetColumn = targetFeature
if modelType == "na":
if self.targetType == 'categorical':
modelType = 'classification'
elif self.targetType == 'continuous':
modelType = 'regression'
datacolumns=list(dataFrame.columns)
if targetColumn in datacolumns:
datacolumns.remove(targetColumn)
features =datacolumns
featureData = dataFrame[features]
if targetColumn != '':
targetData = dataFrame[targetColumn]
xtrain,ytrain,xtest,ytest = mlobj.split_into_train_test_data(featureData,targetData,testPercentage,modelType)
categoryCountList = []
if modelType == 'classification':
if(mlobj.checkForClassBalancing(ytrain) >= 1):
xtrain,ytrain = mlobj.ExecuteClassBalancing(xtrain,ytrain,balancingMethod)
valueCount=targetData.value_counts()
categoryCountList=valueCount.tolist()
ldp_mlexecutionTime=time.time() - ldp_mlstart
log.info('-------> COMPUTING: Total Learner data preparation Execution Time '+str(ldp_mlexecutionTime))
log.info('Status:-|... AION Learner data preparation completed')
if learnerStatus:
log.info('\\n================== ML Started ==================')
log.info('Status:-|... AION training started')
log.info('-------> Memory Usage by DataFrame During Learner Status '+str(dataFrame.memory_usage(deep=True).sum()))
mlstart = time.time()
log.info('-------> Target Problem Type:'+ self.targetType)
learner_type = 'ML'
learnerJson = config_obj.getEionLearnerConfiguration()
log.info('-------> Target Model Type:'+ modelType)
modelParams,modelList = config_obj.getEionLearnerModelParams(modelType)
if(modelType == 'regression'):
allowedmatrix = ['mse','r2','rmse','mae']
if(scoreParam.lower() not in allowedmatrix):
scoreParam = 'mse'
if(modelType == 'classification'):
allowedmatrix = ['accuracy','recall','f1_score','precision','roc_auc']
if(scoreParam.lower() not in allowedmatrix):
scoreParam = 'accuracy'
scoreParam = scoreParam.lower()
from incremental.incMachineLearning import incMachineLearning
incMlObj = incMachineLearning(mlobj)
self.configDict['riverModel'] = False
status,model_type,model,saved_model,matrix,trainmatrix,featureDataShape,model_tried,score,filename,self.features,threshold,pscore,rscore,self.method,loaded_model,xtrain1,ytrain1,xtest1,ytest1,topics,params=incMlObj.startLearning(learnerJson,modelType,modelParams,modelList,scoreParam,self.features,targetColumn,dataFrame,xtrain,ytrain,xtest,ytest,categoryCountList,self.targetType,deployLocation,iterName,iterVersion,trained_data_file,predicted_data_file,labelMaps)
if model in self.riverAlgoNames:
self.configDict['riverModel'] = True
if(self.matrix != '{'):
self.matrix += ','
if(self.trainmatrix != '{'):
self.trainmatrix += ','
self.trainmatrix += trainmatrix
self.matrix += matrix
mlexecutionTime=time.time() - mlstart
log.info('-------> Total ML Execution Time '+str(mlexecutionTime))
log.info('Status:-|... AION training completed')
log.info('================== ML Completed ==================\\n')
if visualizationstatus:
visualizationJson = config_obj.getEionVisualizationConfiguration()
log.info('Status:-|... AION Visualizer started')
visualizer_mlstart = time.time()
from visualization.visualization import Visualization
visualizationObj = Visualization(iterName,iterVersion,dataFrame,visualizationJson,datetimeFeature,deployLocation,dataFolderLocation,numericContinuousFeatures,discreteFeatures,categoricalFeatures,self.features,targetFeature,model_type,original_data_file,profiled_data_file,trained_data_file,predicted_data_file,labelMaps,self.vectorizerFeatures,self.textFeatures,self.numericalFeatures,self.nonNumericFeatures,self.emptyFeatures,self.dfNumRows,self.dfNumCols,saved_model,scoreParam,learner_type,model,featureReduction,reduction_data_file)
visualizationObj.visualizationrecommandsystem()
visualizer_mlexecutionTime=time.time() - visualizer_mlstart
log.info('-------> COMPUTING: Total Visualizer Execution Time '+str(visualizer_mlexecutionTime))
log.info('Status:-|... AION Visualizer completed')
try:
os.remove(os.path.join(deployLocation,'aion_xai.py'))
except:
pass
if deployStatus:
if str(model) != 'None':
log.info('\\n================== Deployment Started ==================')
log.info('Status:-|... AION Deployer started')
deployPath = deployLocation
deployer_mlstart = time.time()
src = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','utilities','useCaseFiles')
shutil.copy2(os.path.join(src,'incBatchLearning.py'),deployPath)
os.rename(os.path.join(deployPath,'incBatchLearning.py'),os.path.join(deployPath,'aion_inclearning.py'))
shutil.copy2(os.path.join(src,'incBatchPrediction.py'),deployPath)
os.rename(os.path.join(deployPath,'incBatchPrediction.py'),os.path.join(deployPath,'aion_predict.py'))
self.configDict['modelName'] = str(model)
self.configDict['modelParams'] = params
self.configDict['problemType'] = problemType.lower()
self.configDict['score'] = score
self.configDict['metricList'] = []
self.configDict['metricList'].append(score)
self.configDict['trainRowsList'] = []
self.configDict['trainRowsList'].append(featureDataShape[0])
self.configDict['scoreParam'] = scoreParam
self.configDict['partialFit'] = 0
with open(os.path.join(deployLocation,'production', 'Config.json'), 'w', encoding='utf8') as f:
json.dump(self.configDict, f, ensure_ascii=False)
deployer_mlexecutionTime=time.time() - deployer_mlstart
log.info('-------> COMPUTING: Total Deployer Execution Time '+str(deployer_mlexecutionTime))
log.info('Status:-|... AION Batch Deployment completed')
log.info('================== Deployment Completed ==================')
# self.features = profilerObj.set_features(self.features,self.textFeatures,self.vectorizerFeatures)
self.matrix += '}'
self.trainmatrix += '}'
matrix = eval(self.matrix)
trainmatrix = eval(self.trainmatrix)
model_tried = eval('['+model_tried+']')
try:
json.dumps(params)
output_json = {"status":"SUCCESS","data":{"ModelType":modelType,"deployLocation":deployPath,"BestModel":model,"BestScore":str(score),"ScoreType":str(scoreParam).upper(),"matrix":matrix,"trainmatrix":trainmatrix,"featuresused":str(self.features),"targetFeature":str(targetColumn),"params":params,"EvaluatedModels":model_tried,"LogFile":logFileName}}
except:
output_json = {"status":"SUCCESS","data":{"ModelType":model | ||
Type,"deployLocation":deployPath,"BestModel":model,"BestScore":str(score),"ScoreType":str(scoreParam).upper(),"matrix":matrix,"trainmatrix":trainmatrix,"featuresused":str(self.features),"targetFeature":str(targetColumn),"params":"","EvaluatedModels":model_tried,"LogFile":logFileName}}
print(output_json)
if bool(topics) == True:
output_json['topics'] = topics
with open(outputjsonFile, 'w') as f:
json.dump(output_json, f)
output_json = json.dumps(output_json)
log.info('\\n------------- Summary ------------')
log.info('------->No of rows & columns in data:('+str(self.dfNumRows)+','+str(self.dfNumCols)+')')
log.info('------->No of missing Features :'+str(len(self.mFeatures)))
log.info('------->Missing Features:'+str(self.mFeatures))
log.info('------->Text Features:'+str(self.textFeatures))
log.info('------->No of Nonnumeric Features :'+str(len(self.nonNumericFeatures)))
log.info('------->Non-Numeric Features :' +str(self.nonNumericFeatures))
if threshold == -1:
log.info('------->Threshold: NA')
else:
log.info('------->Threshold: '+str(threshold))
log.info('------->Label Maps of Target Feature for classification :'+str(labelMaps))
if((learner_type != 'TS') & (learner_type != 'AR')):
log.info('------->No of columns and rows used for Modeling :'+str(featureDataShape))
log.info('------->Features Used for Modeling:'+str(self.features))
log.info('------->Target Feature: '+str(targetColumn))
log.info('------->Best Model Score :'+str(score))
log.info('------->Best Parameters:'+str(params))
log.info('------->Type of Model :'+str(modelType))
log.info('------->Best Model :'+str(model))
log.info('------------- Summary ------------\\n')
except Exception as inst:
log.info('server code execution failed !....'+str(inst))
output_json = {"status":"FAIL","message":str(inst).strip('"')}
output_json = json.dumps(output_json)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
executionTime = timeit.default_timer() - startTime
log.info('\\nTotal execution time(sec) :'+str(executionTime))
log.info('\\n------------- Output JSON ------------')
log.info('-------> Output :'+str(output_json))
log.info('------------- Output JSON ------------\\n')
for hdlr in log.handlers[:]: # remove the existing file handlers
if isinstance(hdlr,logging.FileHandler):
hdlr.close()
log.removeHandler(hdlr)
return output_json
def aion_ot_train_model(arg):
warnings.filterwarnings('ignore')
try:
valid, msg = pushRecordForOnlineTraining()
if valid:
serverObj = server()
configObj = OTAionConfigManager()
jsonPath = arg
readConfistatus,msg = configObj.readConfigurationFile(jsonPath)
if(readConfistatus == False):
output = {"status":"FAIL","message":str(msg).strip('"')}
output = json.dumps(output)
print("\\n")
print("aion_learner_status:",output)
print("\\n")
return output
output = serverObj.startScriptExecution(configObj)
else:
output = {"status":"LicenseVerificationFailed","message":str(msg).strip('"')}
output = json.dumps(output)
print("\\n")
print("aion_learner_status:",output)
print("\\n")
return output
except Exception as inst:
output = {"status":"FAIL","message":str(inst).strip('"')}
output = json.dumps(output)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
print("\\n")
print("aion_learner_status:",output)
print("\\n")
return output
if __name__ == "__main__":
aion_ot_train_model(sys.argv[1])
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import joblib
import time
from pandas import json_normalize
import pandas as pd
import numpy as np
import argparse
import json
import os
import pathlib
from pathlib import Path
from sagemaker.aionMlopsService import aionMlopsService
import logging
import os.path
from os.path import expanduser
import platform,sys
from pathlib import Path
from sklearn.model_selection import train_test_split
def getAWSConfiguration(mlops_params,log):
awsId=mlops_params['awsSagemaker']['awsID']
if ((not awsId) or (awsId is None)):
awsId=""
log.info('awsId error. ')
awsAccesskeyid=mlops_params['awsSagemaker']['accesskeyID']
if ((not awsAccesskeyid) or (awsAccesskeyid is None)):
awsAccesskeyid=""
log.info('awsAccesskeyid error. ')
awsSecretaccesskey=mlops_params['awsSagemaker']['secretAccesskey']
if ((not awsSecretaccesskey) or (awsSecretaccesskey is None)):
awsSecretaccesskey=""
log.info('awsSecretaccesskey error. ')
awsSessiontoken=mlops_params['awsSagemaker']['sessionToken']
if ((not awsSessiontoken) or (awsSessiontoken is None)):
awsSessiontoken=""
log.info('awsSessiontoken error. ')
awsRegion=mlops_params['awsSagemaker']['region']
if ((not awsRegion) or (awsRegion is None)):
awsRegion=""
log.info('awsRegion error. ')
IAMSagemakerRoleArn=mlops_params['awsSagemaker']['IAMSagemakerRoleArn']
if ((not IAMSagemakerRoleArn) or (IAMSagemakerRoleArn is None)):
IAMSagemakerRoleArn=""
log.info('IAMSagemakerRoleArn error. ')
return awsId,awsAccesskeyid,awsSecretaccesskey,awsSessiontoken,awsRegion,IAMSagemakerRoleArn
def getMlflowParams(mlops_params,log):
modelInput = mlops_params['modelInput']
data = mlops_params['data']
mlflowtosagemakerDeploy=mlops_params['sagemakerDeploy']
if ((not mlflowtosagemakerDeploy) or (mlflowtosagemakerDeploy is None)):
mlflowtosagemakerDeploy="True"
mlflowtosagemakerPushOnly=mlops_params['deployExistingModel']['status']
if ((not mlflowtosagemakerPushOnly) or (mlflowtosagemakerPushOnly is None)):
mlflowtosagemakerPushOnly="False"
mlflowtosagemakerPushImageName=mlops_params['deployExistingModel']['dockerImageName']
if ((not mlflowtosagemakerPushImageName) or (mlflowtosagemakerPushImageName is None)):
mlflowtosagemakerPushImageName="mlops_image"
mlflowtosagemakerdeployModeluri=mlops_params['deployExistingModel']['deployModeluri']
if ((not mlflowtosagemakerdeployModeluri) or (mlflowtosagemakerdeployModeluri is None)):
mlflowtosagemakerdeployModeluri="None"
log.info('mlflowtosagemakerdeployModeluri error. ')
cloudInfrastructure = mlops_params['modelOutput']['cloudInfrastructure']
if ((not cloudInfrastructure) or (cloudInfrastructure is None)):
cloudInfrastructure="Sagemaker"
endpointName=mlops_params['endpointName']
if ((not endpointName) or (endpointName is None)):
sagemakerAppName="aion-demo-app"
log.info('endpointName not given, setting default one. ')
experimentName=str(endpointName)
mlflowContainerName=str(endpointName)
return modelInput,data,mlflowtosagemakerDeploy,mlflowtosagemakerPushOnly,mlflowtosagemakerPushImageName,mlflowtosagemakerdeployModeluri,cloudInfrastructure,endpointName,experimentName,mlflowContainerName
def getPredictionParams(mlops_params,log):
predictStatus=mlops_params['prediction']['status']
if ((not predictStatus) or (predictStatus is None)):
predictStatus="False"
modelInput = mlops_params['modelInput']
data = mlops_params['data']
if (predictStatus == "True" or predictStatus.lower()== "true"):
if ((not modelInput) or (modelInput is None)):
log.info('prediction model input error.Please check given model file or its path for prediction ')
if ((not data) or (data is None)):
log.info('prediction data input error.Please check given data file or its path for prediction ')
targetFeature=mlops_params['prediction']['target']
return predictStatus,targetFeature
def sagemakerPrediction(mlopsobj,data,log):
df = json_normalize(data)
model=None
predictionStatus=False
try:
endpointPrediction=mlopsobj.predict_sm_app_endpoint(df)
if (endpointPrediction is None):
log.info('Sagemaker endpoint application prediction Issue.')
outputjson = {"status":"Error","msg":"Sagemaker endpoint application prediction Issue"}
outputjson = json.dumps(outputjson)
#print("predictions: "+str(outputjson))
predictionStatus=False
else:
log.info("sagemaker end point Prediction: \\n"+str(endpointPrediction))
df['prediction'] = endpointPrediction
outputjson = df.to_json(orient='records')
outputjson = {"status":"SUCCESS","data":json.loads(outputjson)}
outputjson = json.dumps(outputjson)
#print("predictions: "+str(outputjson))
predictionStatus=True
except Exception as e:
#log.info("sagemaker end point Prediction error: \\n")
outputjson = {"status":"Error","msg":str(e)}
outputjson=None
predictionStatus=False
return outputjson,predictionStatus
## Main aion sagemaker fn call
def sagemaker_exec(mlops_params,log):
#mlops_params = json.loads(config)
mlops_params=mlops_params
modelInput,data,mlflowtosagemakerDeploy,mlflowtosagemakerPushOnly,mlflowtosagemakerPushImageName,mlflowtosagemakerdeployModeluri,cloudInfrastructure,endpointName,experimentName,mlflowContainerName = getMlflowParams(mlops_params,log)
mlflowModelname=None
awsId,awsAccesskeyid,awsSecretaccesskey,awsSessiontoken,awsRegion,IAMSagemakerRoleArn = getAWSConfiguration(mlops_params,log)
predictStatus,targetFeature = getPredictionParams(mlops_params,log)
sagemakerDeployOption='create'
deleteAwsecrRepository='False'
sagemakerAppName=str(endpointName)
ecrRepositoryName='aion-ecr-repo'
#aws ecr model app_name should contain only [[a-zA-Z0-9-]], again rechecking here.
import re
if sagemakerAppName:
pattern = re.compile("[A-Za-z0-9-]+")
# if found match (entire string matches pattern)
if pattern.fullmatch(sagemakerAppName) is not None:
#print("Found match: ")
pass
else:
log.info('wrong sagemaker Application Name, Nmae should contains only [A-Za-z0-9-] .')
app_name = 'aion-demo-app'
else:
app_name = 'aion-demo-app'
#Following 3 aws parameter values are now hard coded , because currently we are not using. If aion using the options, please make sure to get the values from GUI .
sagemakerDeployOption="create"
deleteAwsecrRepository="False"
ecrRepositoryName="aion_test_repo"
log.info('mlops parameter check done.')
# predictionStatus=False
deploystatus = 'SUCCESS'
try:
log.info('cloudInfrastructure: '+str(cloudInfrastructure))
if(cloudInfrastructure.lower() == "sagemaker"):
## sagemaker app prediction call
if (predictStatus.lower() == "true"):
# df = json_normalize(data)
model=None
mlopsobj = aionMlopsService(model,mlflowtosagemakerDeploy,mlflowtosagemakerPushOnly,mlflowtosagemakerPushImageName,mlflowtosagemakerdeployModeluri,experimentName,mlflowModelname,awsAccesskeyid,awsSecretaccesskey,awsSessiontoken,mlflowContainerName,awsRegion,awsId,IAMSagemakerRoleArn,sagemakerAppName,sagemakerDeployOption,deleteAwsecrRepository,ecrRepositoryName)
outputjson,predictionStatus = sagemakerPrediction(mlopsobj,data,log)
print("predictions: "+str(outputjson))
predictionStatus=predictionStatus
return(outputjson)
else:
if Path(modelInput).is_file():
msg = ''
model = joblib.load(modelInput)
ProblemName = model.__class__.__name__
mlflowModelname=str(ProblemName)
log.info('aion mlops Model name: '+str(mlflowModelname))
df=None
mlopsobj = aionMlopsService(model,mlflowtosagemakerDeploy,mlflowtosagemakerPush | ||
Only,mlflowtosagemakerPushImageName,mlflowtosagemakerdeployModeluri,experimentName,mlflowModelname,awsAccesskeyid,awsSecretaccesskey,awsSessiontoken,mlflowContainerName,awsRegion,awsId,IAMSagemakerRoleArn,sagemakerAppName,sagemakerDeployOption,deleteAwsecrRepository,ecrRepositoryName)
mlflow2sm_status,localhost_container_status=mlopsobj.mlflow2sagemaker_deploy()
log.info('mlflow2sm_status: '+str(mlflow2sm_status))
log.info('localhost_container_status: '+str(localhost_container_status))
# Checking deploy status
if (mlflowtosagemakerPushOnly.lower() == "true" ):
if (mlflow2sm_status.lower() == "success"):
deploystatus = 'SUCCESS'
msg = 'Endpoint succesfully deployed in sagemaker'
log.info('Endpoint succesfully deployed in sagemaker (Push eisting model container).\\n ')
elif(mlflow2sm_status.lower() == "failed"):
deploystatus = 'ERROR'
msg = 'Endpoint failed to deploy in sagemaker'
log.info('Endpoint failed to deploy in sagemaker. (Push eisting model container).\\n ')
else:
pass
elif(mlflowtosagemakerDeploy.lower() == "true"):
if (mlflow2sm_status.lower() == "success"):
deploystatus='SUCCESS'
msg = 'Endpoint succesfully deployed in sagemaker'
log.info('Endpoint succesfully deployed in sagemaker')
elif(mlflow2sm_status.lower() == "failed"):
deploystatus = 'ERROR'
msg = 'Endpoint failed to deploy in sagemaker'
log.info('Endpoint failed to deploy in sagemaker.\\n ')
elif (mlflow2sm_status.lower() == "Notdeployed"):
deploystatus= 'ERROR'
msg = 'Sagemaker compatible container created'
log.info('sagemaker endpoint not deployed, check aws connection and credentials. \\n')
elif (mlflowtosagemakerDeploy.lower() == "false"):
if(localhost_container_status.lower() == "success"):
deploystatus = 'SUCCESS'
msg = 'Localhost mlops docker created successfully'
log.info('Localhost mlops docker created successfully. \\n')
elif(localhost_container_status.lower() == "failed"):
deploystatus = 'ERROR'
msg = 'Localhost mlops docker created failed'
log.info('Localhost mlops docker creation failed. \\n')
elif (localhost_container_status.lower() == "Notdeployed"):
deploystatus= 'ERROR'
log.info('Localhost mlops docker not deployed, check local docker status. \\n')
else:
pass
else:
pass
else:
deploystatus = 'ERROR'
msg = 'Model Path not Found'
print('Error: Model Path not Found')
outputjson = {"status":str(deploystatus),"data":str(msg)}
outputjson = json.dumps(outputjson)
print("predictions: "+str(outputjson))
return(outputjson)
except Exception as inst:
outputjson = {"status":str(deploystatus),"data":str(msg)}
outputjson = json.dumps(outputjson)
print("predictions: "+str(outputjson))
return(outputjson)
def aion_sagemaker(config):
try:
mlops_params = config
print(mlops_params)
from appbe.dataPath import LOG_LOCATION
sagemakerLogLocation = LOG_LOCATION
try:
os.makedirs(sagemakerLogLocation)
except OSError as e:
if (os.path.exists(sagemakerLogLocation)):
pass
else:
raise OSError('sagemakerLogLocation error.')
filename_mlops = 'mlopslog_'+str(int(time.time()))
filename_mlops=filename_mlops+'.log'
filepath = os.path.join(sagemakerLogLocation, filename_mlops)
logging.basicConfig(filename=filepath, format='%(message)s',filemode='w')
log = logging.getLogger('aionMLOps')
log.setLevel(logging.DEBUG)
output = sagemaker_exec(mlops_params,log)
return output
except Exception as inst:
print(inst)
deploystatus = 'ERROR'
output = {"status":str(deploystatus),"data":str(inst)}
output = json.dumps(output)
print("predictions: "+str(output))
return(output)
#Sagemaker main fn call
if __name__=='__main__':
json_config = str(sys.argv[1])
output = aion_sagemaker(json.loads(json_config))
<s> """
/**
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* © Copyright HCL Technologies Ltd. 2021, 2022
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*/
"""
import os
from pathlib import Path
os.chdir(Path(__file__).parent)
import json
import shutil
from mlac.timeseries import app as ts_app
from mlac.ml import app as ml_app
import traceback
def create_test_file(config):
code_file = 'aionCode.py'
text = """
from pathlib import Path
import subprocess
import sys
import json
import argparse
def run_pipeline(data_path):
print('Data Location:', data_path)
cwd = Path(__file__).parent
monitor_file = str(cwd/'ModelMonitoring'/'{code_file}')
load_file = str(cwd/'DataIngestion'/'{code_file}')
transformer_file = str(cwd/'DataTransformation'/'{code_file}')
selector_file = str(cwd/'FeatureEngineering'/'{code_file}')
train_folder = cwd
register_file = str(cwd/'ModelRegistry'/'{code_file}')
deploy_file = str(cwd/'ModelServing'/'{code_file}')
print('Running modelMonitoring')
cmd = [sys.executable, monitor_file, '-i', data_path]
result = subprocess.check_output(cmd)
result = result.decode('utf-8')
print(result)
result = json.loads(result[result.find('{search}'):])
if result['Status'] == 'Failure':
exit()
print('Running dataIngestion')
cmd = [sys.executable, load_file]
result = subprocess.check_output(cmd)
result = result.decode('utf-8')
print(result)
result = json.loads(result[result.find('{search}'):])
if result['Status'] == 'Failure':
exit()
print('Running DataTransformation')
cmd = [sys.executable, transformer_file]
result = subprocess.check_output(cmd)
result = result.decode('utf-8')
print(result)
result = json.loads(result[result.find('{search}'):])
if result['Status'] == 'Failure':
exit()
print('Running FeatureEngineering')
cmd = [sys.executable, selector_file]
result = subprocess.check_output(cmd)
result = result.decode('utf-8')
print(result)
result = json.loads(result[result.find('{search}'):])
if result['Status'] == 'Failure':
exit()
train_models = [f for f in train_folder.iterdir() if 'ModelTraining' in f.name]
for model in train_models:
print('Running',model.name)
cmd = [sys.executable, str(model/'{code_file}')]
train_result = subprocess.check_output(cmd)
train_result = train_result.decode('utf-8')
print(train_result)
print('Running ModelRegistry')
cmd = [sys.executable, register_file]
result = subprocess.check_output(cmd)
result = result.decode('utf-8')
print(result)
result = json.loads(result[result.find('{search}'):])
if result['Status'] == 'Failure':
exit()
print('Running ModelServing')
cmd = [sys.executable, deploy_file]
result = subprocess.check_output(cmd)
result = result.decode('utf-8')
print(result)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--inputPath', help='path of the input data')
args = parser.parse_args()
if args.inputPath:
filename = args.inputPath
else:
filename = r"{filename}"
try:
print(run_pipeline(filename))
except Exception as e:
print(e)
""".format(filename=config['dataLocation'],search='{"Status":',code_file=code_file)
deploy_path = Path(config["deploy_path"])/'MLaC'
deploy_path.mkdir(parents=True, exist_ok=True)
py_file = deploy_path/"run_pipeline.py"
with open(py_file, "w") as f:
f.write(text)
def is_module_in_req_file(mod, folder):
status = False
if (Path(folder)/'requirements.txt').is_file():
with open(folder/'requirements.txt', 'r') as f:
status = mod in f.read()
return status
def copy_local_modules(config):
deploy_path = Path(config["deploy_path"])
local_modules_location = config.get("local_modules_location", None)
if local_modules_location:
folder_loc = local_modules_location
else:
folder_loc = Path(__file__).parent/'local_modules'
if not folder_loc.exists():
folder_loc = None
if folder_loc:
file = folder_loc/'config.json'
if file.exists():
with open(file, 'r') as f:
data = json.load(f)
for key, values in data.items():
local_module = folder_loc/key
if local_module.exists():
for folder in values:
target_folder = Path(deploy_path)/'MLaC'/folder
if target_folder.is_dir():
if is_module_in_req_file(key, target_folder):
shutil.copy(local_module, target_folder)
def validate(config):
error = ''
if 'error' in config.keys():
error = config['error']
return error
def generate_mlac_code(config):
with open(config, 'r') as f:
config = json.load(f)
error = validate(config)
if error:
raise ValueError(error)
if config['problem_type'] in ['classification','regression']:
return generate_mlac_ML_code(config)
elif config['problem_type'].lower() == 'timeseriesforecasting': #task 11997
return generate_mlac_TS_code(config)
def generate_mlac_ML_code(config):
try:
ml_app.run_loader(config)
ml_app.run_transformer(config)
ml_app.run_selector(config)
ml_app.run_trainer(config)
ml_app.run_register(config)
ml_app.run_deploy(config)
ml_app.run_drift_analysis(config)
copy_local_modules(config)
create_test_file(config)
status = {'Status':'SUCCESS','MLaC_Location':str(Path(config["deploy_path"])/'MLaC')}
except Exception as Inst:
status = {'Status':'Failure','msg':str(Inst)}
traceback.print_exc()
status = json.dumps(status)
return(status)
def generate_mlac_TS_code(config):
try:
ts_app.run_loader(config)
ts_app.run_transformer(config)
ts_app.run_selector(config)
ts_app.run_trainer(config)
ts_app.run_register(config)
ts_app.run_deploy(config)
ts_app.run_drift_analysis(config)
create_test_file(config)
status = {'Status':'SUCCESS','MLaC_Location':str(Path(config["deploy_path"])/'MLaC')}
except Exception as Inst:
status = {'Status':'Failure','msg':str(Inst)}
traceback.print_exc()
status = json.dumps(status)
return(status)<s> #from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from http.server import BaseHTTPRequestHandler,HTTPServer
#from SocketServer import ThreadingMixIn
from socketserver import ThreadingMixIn
from functools import partial
from http.server import SimpleHTTPRequestHandler, test
import base64
from appbe.dataPath import DEPLOY_LOCATION
'''
from augustus.core.ModelLoader import ModelLoader
from augustus.strict import modelLoader
'''
import pandas as pd
import os,sys
from os.path import expanduser
import platform
import numpy as np
import configparser
import threading
import subprocess
import argparse
from functools import partial
import re
import cgi
from datetime import datetime
import json
import sys
from datetime import datetime
user_records = {}
class LocalModelData(object):
models = {}
class HTTPRequestHandler(BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
username = kwargs.pop("username")
password = kwargs.pop("password")
self._auth = base64.b64encode(f"{username}:{password}".encode()).decode()
super().__init__(*args)
def do_HEAD(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def do_AUTHHEAD(self):
self.send_response(401)
self.send_header("WWW-Authenticate", 'Basic realm="Test"')
self.send_header("Content-type", "text/html")
self.end_headers()
def do_POST(self):
print("PYTHON ######## REQUEST ####### STARTED")
if None != re.search('/AION/', self.path):
ctype, pdict = cgi.parse_header(self.headers.get('content-type'))
if ctype == 'application/json':
if self.headers.get("Authorization") == None:
self.do_AUTHHEAD()
| ||
resp = "Authentication Failed: Auth Header Not Present"
resp=resp.encode()
self.wfile.write(resp)
elif self.headers.get("Authorization") == "Basic " + self._auth:
length = int(self.headers.get('content-length'))
#data = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)
data = self.rfile.read(length)
#print(data)
#keyList = list(data.keys())
#print(keyList[0])
model = self.path.split('/')[-2]
operation = self.path.split('/')[-1]
home = expanduser("~")
#data = json.loads(data)
dataStr = data
model_path = os.path.join(DEPLOY_LOCATION,model)
isdir = os.path.isdir(model_path)
if isdir:
if operation.lower() == 'predict':
predict_path = os.path.join(model_path,'aion_predict.py')
outputStr = subprocess.check_output([sys.executable,predict_path,dataStr])
outputStr = outputStr.decode('utf-8')
outputStr = re.search(r'predictions:(.*)',str(outputStr), re.IGNORECASE).group(1)
outputStr = outputStr.strip()
resp = outputStr
elif operation.lower() == 'spredict':
try:
predict_path = os.path.join(model_path,'aion_spredict.py')
print(predict_path)
outputStr = subprocess.check_output([sys.executable,predict_path,dataStr])
outputStr = outputStr.decode('utf-8')
outputStr = re.search(r'predictions:(.*)',str(outputStr), re.IGNORECASE).group(1)
outputStr = outputStr.strip()
resp = outputStr
except Exception as e:
print(e)
elif operation.lower() == 'features':
predict_path = os.path.join(model_path,'featureslist.py')
outputStr = subprocess.check_output([sys.executable,predict_path,dataStr])
outputStr = outputStr.decode('utf-8')
outputStr = re.search(r'predictions:(.*)',str(outputStr), re.IGNORECASE).group(1)
outputStr = outputStr.strip()
resp = outputStr
elif operation.lower() == 'explain':
predict_path = os.path.join(model_path,'explainable_ai.py')
outputStr = subprocess.check_output([sys.executable,predict_path,'local',dataStr])
outputStr = outputStr.decode('utf-8')
outputStr = re.search(r'aion_ai_explanation:(.*)',str(outputStr), re.IGNORECASE).group(1)
outputStr = outputStr.strip()
elif operation.lower() == 'monitoring':
predict_path = os.path.join(model_path,'aion_ipdrift.py')
outputStr = subprocess.check_output([sys.executable,predict_path,dataStr])
outputStr = outputStr.decode('utf-8')
outputStr = re.search(r'drift:(.*)',str(outputStr), re.IGNORECASE).group(1)
outputStr = outputStr.strip()
elif operation.lower() == 'performance':
predict_path = os.path.join(model_path,'aion_opdrift.py')
outputStr = subprocess.check_output([sys.executable,predict_path,dataStr])
outputStr = outputStr.decode('utf-8')
outputStr = re.search(r'drift:(.*)',str(outputStr), re.IGNORECASE).group(1)
outputStr = outputStr.strip()
elif operation.lower() == 'pattern_anomaly_predict':
data = json.loads(data)
anomaly = False
remarks = ''
clusterid = -1
configfilename = os.path.join(model_path,'datadetails.json')
filename = os.path.join(model_path,'clickstream.json')
clusterfilename = os.path.join(model_path,'stateClustering.csv')
probfilename = os.path.join(model_path,'stateTransitionProbability.csv')
dfclus = pd.read_csv(clusterfilename)
dfprod = pd.read_csv(probfilename)
f = open(configfilename, "r")
configSettings = f.read()
f.close()
configSettingsJson = json.loads(configSettings)
activity = configSettingsJson['activity']
sessionid = configSettingsJson['sessionid']
f = open(filename, "r")
configSettings = f.read()
f.close()
configSettingsJson = json.loads(configSettings)
groupswitching = configSettingsJson['groupswitching']
page_threshold = configSettingsJson['transitionprobability']
chain_count = configSettingsJson['transitionsequence']
chain_probability = configSettingsJson['sequencethreshold']
currentactivity = data[activity]
if bool(user_records):
sessionid = data[sessionid]
if sessionid != user_records['SessionID']:
user_records['SessionID'] = sessionid
prevactivity = ''
user_records['probarry'] = []
user_records['prevclusterid'] = -1
user_records['NoOfClusterHopping'] = 0
user_records['pageclicks'] = 1
else:
prevactivity = user_records['Activity']
user_records['Activity'] = currentactivity
pageswitch = True
if prevactivity == currentactivity or prevactivity == '':
probability = 0
pageswitch = False
remarks = ''
else:
user_records['pageclicks'] += 1
df1 = dfprod[(dfprod['State'] == prevactivity) & (dfprod['NextState'] == currentactivity)]
if df1.empty:
remarks = 'Anomaly Detected - User in unusual state'
anomaly = True
clusterid = -1
probability = 0
user_records['probarry'].append(probability)
n=int(chain_count)
num_list = user_records['probarry'][-n:]
avg = sum(num_list)/len(num_list)
for index, row in dfclus.iterrows():
clusterlist = row["clusterlist"]
if currentactivity in clusterlist:
clusterid = row["clusterid"]
else:
probability = df1['Probability'].iloc[0]
user_records['probarry'].append(probability)
n=int(chain_count)
num_list = user_records['probarry'][-n:]
davg = sum(num_list)/len(num_list)
for index, row in dfclus.iterrows():
clusterlist = row["clusterlist"]
if currentactivity in clusterlist:
clusterid = row["clusterid"]
remarks = ''
if user_records['prevclusterid'] != -1:
if probability == 0 and user_records['prevclusterid'] != clusterid:
user_records['NoOfClusterHopping'] = user_records['NoOfClusterHopping']+1
if user_records['pageclicks'] == 1:
remarks = 'Anomaly Detected - Frequent Cluster Hopping'
anomaly = True
else:
remarks = 'Cluster Hopping Detected'
user_records['pageclicks'] = 0
if user_records['NoOfClusterHopping'] > int(groupswitching) and anomaly == False:
remarks = 'Anomaly Detected - Multiple Cluster Hopping'
anomaly = True
elif probability == 0:
remarks = 'Anomaly Detected - Unusual State Transition Detected'
anomaly = True
elif probability <= float(page_threshold):
remarks = 'Anomaly Detected - In-frequent State Transition Detected'
anomaly = True
else:
if pageswitch == True:
if probability == 0:
remarks = 'Anomaly Detected - Unusual State Transition Detected'
anomaly = True
elif probability <= float(page_threshold):
remarks = 'Anomaly Detected - In-frequent State Transition Detected'
anomaly = True
else:
remarks = ''
if davg < float(chain_probability):
if anomaly == False:
remarks = 'Anomaly Detected - In-frequent Pattern Detected'
anomaly = True
else:
user_records['SessionID'] = data[sessionid]
user_records['Activity'] = data[activity]
user_records['probability'] = 0
user_records['probarry'] = []
user_records['chainprobability'] = 0
user_records['prevclusterid'] = -1
user_records['NoOfClusterHopping'] = 0
user_records['pageclicks'] = 1
for index, row in dfclus.iterrows():
clusterlist = row["clusterlist"]
if currentactivity in clusterlist:
clusterid = row["clusterid"]
user_records['prevclusterid'] = clusterid
outputStr = '{"status":"SUCCESS","data":{"Anomaly":"'+str(anomaly)+'","Remarks":"'+str(remarks)+'"}}'
elif operation.lower() == 'pattern_anomaly_settings':
data = json.loads(data)
groupswitching = data['groupswitching']
transitionprobability = data['transitionprobability']
transitionsequence = data['transitionsequence']
sequencethreshold = data['sequencethreshold']
filename = os.path.join(model_path,'clickstream.json')
data = {}
data['groupswitching'] = groupswitching
data['transitionprobability'] = transitionprobability
data['transitionsequence'] = transitionsequence
data['sequencethreshold'] = sequencethreshold
updatedConfig = json.dumps(data)
with open(filename, "w") as fpWrite:
| ||
fpWrite.write(updatedConfig)
fpWrite.close()
outputStr = '{"Status":"SUCCESS"}'
else:
outputStr = "{'Status':'Error','Msg':'Operation not supported'}"
else:
outputStr = "{'Status':'Error','Msg':'Model Not Present'}"
resp = outputStr
resp=resp+"\\n"
resp=resp.encode()
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(resp)
else:
self.do_AUTHHEAD()
self.wfile.write(self.headers.get("Authorization").encode())
resp = "Authentication Failed"
resp=resp.encode()
self.wfile.write(resp)
else:
print("python ==> else1")
self.send_response(403)
self.send_header('Content-Type', 'application/json')
self.end_headers()
print("PYTHON ######## REQUEST ####### ENDED")
return
def getModelFeatures(self,modelSignature):
datajson = {'Body':'Gives the list of features'}
home = expanduser("~")
if platform.system() == 'Windows':
predict_path = os.path.join(home,'AppData','Local','HCLT','AION','target',modelSignature,'featureslist.py')
else:
predict_path = os.path.join(home,'HCLT','AION','target',modelSignature,'featureslist.py')
if(os.path.isfile(predict_path)):
outputStr = subprocess.check_output([sys.executable,predict_path])
outputStr = outputStr.decode('utf-8')
outputStr = re.search(r'features:(.*)',str(outputStr), re.IGNORECASE).group(1)
outputStr = outputStr.strip()
displaymsg = outputStr
#displaymsg = json.dumps(displaymsg)
return(True,displaymsg)
else:
displaymsg = "{'status':'ERROR','msg':'Unable to fetch featuers'}"
return(False,displaymsg)
def getFeatures(self,modelSignature):
datajson = {'Body':'Gives the list of features'}
urltext = '/AION/UseCase_Version/features'
if modelSignature != '':
status,displaymsg = self.getModelFeatures(modelSignature)
if status:
urltext = '/AION/'+modelSignature+'/features'
else:
displaymsg = json.dumps(datajson)
else:
displaymsg = json.dumps(datajson)
msg="""
URL:{url}
RequestType: POST
Content-Type=application/json
Output: {displaymsg}.
""".format(url=urltext,displaymsg=displaymsg)
return(msg)
def features_help(self,modelSignature):
home = expanduser("~")
if platform.system() == 'Windows':
display_path = os.path.join(home,'AppData','Local','HCLT','AION','target',modelSignature,'display.json')
else:
display_path = os.path.join(home,'HCLT','AION','target',modelSignature,'display.json')
#display_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'target',model,'display.json')
datajson = {'Body':'Data Should be in JSON Format'}
if(os.path.isfile(display_path)):
with open(display_path) as file:
config = json.load(file)
file.close()
datajson={}
for feature in config['numericalFeatures']:
if feature != config['targetFeature']:
datajson[feature] = 'Numeric Value'
for feature in config['nonNumericFeatures']:
if feature != config['targetFeature']:
datajson[feature] = 'Category Value'
for feature in config['textFeatures']:
if feature != config['targetFeature']:
datajson[feature] = 'Category Value'
displaymsg = json.dumps(datajson)
return(displaymsg)
def predict_help(self,modelSignature):
if modelSignature != '':
displaymsg = self.features_help(modelSignature)
urltext = '/AION/'+modelSignature+'/predict'
else:
datajson = {'Body':'Data Should be in JSON Format'}
displaymsg = json.dumps(datajson)
urltext = '/AION/UseCase_Version/predict'
msg="""
URL:{url}
RequestType: POST
Content-Type=application/json
Body: {displaymsg}
Output: prediction,probability(if Applicable),remarks corresponding to each row.
""".format(url=urltext,displaymsg=displaymsg)
return(msg)
def performance_help(self,modelSignature):
if modelSignature != '':
urltext = '/AION/'+modelSignature+'/performance'
else:
urltext = '/AION/UseCase_Version/performance'
datajson = {"trainingDataLocation":"Reference Data File Path","currentDataLocation":"Latest Data File Path"}
displaymsg = json.dumps(datajson)
msg="""
URL:{url}
RequestType: POST
Content-Type=application/json
Body: {displaymsg}
Output: HTML File Path.""".format(url=urltext,displaymsg=displaymsg)
return(msg)
def monitoring_help(self,modelSignature):
if modelSignature != '':
urltext = '/AION/'+modelSignature+'/monitoring'
else:
urltext = '/AION/UseCase_Version/monitoring'
datajson = {"trainingDataLocation":"Reference Data File Path","currentDataLocation":"Latest Data File Path"}
displaymsg = json.dumps(datajson)
msg="""
URL:{url}
RequestType: POST
Content-Type=application/json
Body: {displaymsg}
Output: Affected Columns. HTML File Path.""".format(url=urltext,displaymsg=displaymsg)
return(msg)
def explain_help(self,modelSignature):
if modelSignature != '':
displaymsg = self.features_help(modelSignature)
urltext = '/AION/'+modelSignature+'/explain'
else:
datajson = {'Body':'Data Should be in JSON Format'}
displaymsg = json.dumps(datajson)
urltext = '/AION/UseCase_Version/explain'
msg="""
URL:{url}
RequestType: POST
Content-Type=application/json
Body: {displaymsg}
Output: anchor (Local Explanation),prediction,forceplot,multidecisionplot.""".format(url=urltext,displaymsg=displaymsg)
return(msg)
def help_text(self,modelSignature):
predict_help = self.predict_help(modelSignature)
explain_help = self.explain_help(modelSignature)
features_help = self.getFeatures(modelSignature)
monitoring_help = self.monitoring_help(modelSignature)
performance_help = self.performance_help(modelSignature)
msg="""
Following URL:
Prediction
{predict_help}
Local Explaination
{explain_help}
Features
{features_help}
Monitoring
{monitoring_help}
Performance
{performance_help}
""".format(predict_help=predict_help,explain_help=explain_help,features_help=features_help,monitoring_help=monitoring_help,performance_help=performance_help)
return msg
def do_GET(self):
print("PYTHON ######## REQUEST ####### STARTED")
if None != re.search('/AION/', self.path):
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
helplist = self.path.split('/')[-1]
print(helplist)
if helplist.lower() == 'help':
model = self.path.split('/')[-2]
if model.lower() == 'aion':
model =''
msg = self.help_text(model)
elif helplist.lower() == 'predict':
model = self.path.split('/')[-2]
if model.lower() == 'aion':
model =''
msg = self.predict_help(model)
elif helplist.lower() == 'explain':
model = self.path.split('/')[-2]
if model.lower() == 'aion':
model =''
msg = self.explain_help(model)
elif helplist.lower() == 'monitoring':
model = self.path.split('/')[-2]
if model.lower() == 'aion':
model =''
msg = self.monitoring_help(model)
elif helplist.lower() == 'performance':
model = self.path.split('/')[-2]
if model.lower() == 'aion':
model =''
msg = self.performance_help(model)
elif helplist.lower() == 'features':
model = self.path.split('/')[-2]
if model.lower() == 'aion':
model =''
status,msg = self.getModelFeatures(model)
else:
model = self.path.split('/')[-2]
if model.lower() == 'aion':
model =helplist
msg = self.help_text(model)
self.wfile.write(msg.encode())
else:
self.send_response(403)
self.send_header('Content-Type', 'application/json')
self.end_headers()
return
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
allow_reuse_address = True
def shutdown(self):
self.socket.close()
HTTPServer.shutdown(self)
class SimpleHttpServer():
def __init__(self, ip, port,username,password):
handler_class = partial(HTTPRequestHandler,username=username,password=password,)
self.server = ThreadedHTTPServer((ip,port), handler_class)
def start(self):
self.server_thread = threading.Thread(target=self.server.serve_forever)
self.server_thread.daemon = True
self.server_thread.start()
def waitForThread(self):
self.server_thread.join()
def stop(self):
self.server.shutdown()
self.waitForThread()
def start_server(ip,port,username,password):
server = SimpleHttpServer(ip,int(port),username,password)
print('HTTP Server Running...........')
server.start()
server.waitForThread()
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import joblib
import time
import pandas as pd
import numpy as np
import argparse
import json
import os
import pathlib
from pathlib import Path
from uncertainties.uq_main import aionUQ
import os
from datetime import datetime
from os.path import expanduser
import platform
import logging
class run_uq:
def __init__(self,modelfeatures,modelFile,csvFile,target):
self.modelfeatures=modelfeatures
self.modelFile=modelFile
self.csvFile=csvFile
self.target=target
##UQ classification fn
def getUQclassification(self,model,ProblemName,Params):
df = pd.read_csv(self.csvFile)
# # object_cols = [col for col, col_type in df.dtypes.iteritems() if col_type == 'object'] -- Fix for python 3.8.11 update (in 2.9.0.8)
object_cols = [col for col, col_type in zip(df.columns,df.dtypes) if col_type == 'object']
df = df.drop(object_cols, axis=1)
df = df.dropna(axis=1)
df = df.reset_index(drop=True)
modelfeatures = self.modelfeatures
#tar = args.target
# target = df[tar]
y=df[self.target].values
y = y.flatten()
X = df.drop(self.target, axis=1)
try:
uqObj=aionUQ(df,X,y,ProblemName,Params,model,modelfeatures,self.target)
accuracy,uq_ece,output_jsonobject=uqObj.uqMain_BBMClassification()
except Exception as e:
print("uq error",e)
# print("UQ Classification: \\n",output_jsonobject)
# print(accuracy,uq_ece,output_jsonobject,model_confidence_per,model_uncertaitny_per)
#print(output_jsonobject)
return accuracy,uq_ece,output_jsonobject
##UQ regression fn
def getUQregression(self,model,ProblemName,Params):
df = pd.read_csv(self.csvFile)
modelfeatures = self.modelfeatures
dfp = df[modelfeatures]
tar = self.target
target = df[tar]
uqObj=aionUQ(df,dfp,target,ProblemName,Params,model,modelfeatures,tar)
total_picp_percentage,total_Uncertainty_percentage,uq_medium,uq_best,scoringCriteria,uq_jsonobject=uqObj.uqMain_BB | ||
MRegression()
return total_picp_percentage,total_Uncertainty_percentage,uq_medium,uq_best,scoringCriteria,uq_jsonobject
def uqMain(self,model):
#print("inside uq main.\\n")
reg_status=""
class_status=""
algorithm_status=""
try:
model=model
if Path(self.modelFile).is_file():
ProblemName = model.__class__.__name__
if ProblemName in ['LogisticRegression','SGDClassifier','SVC','DecisionTreeClassifier','RandomForestClassifier','GaussianNB','KNeighborsClassifier','GradientBoostingClassifier']:
Problemtype = 'Classification'
elif ProblemName in ['LinearRegression','Lasso','Ridge','DecisionTreeRegressor','RandomForestRegressor']:
Problemtype = 'Regression'
else:
Problemtype = "None"
if Problemtype.lower() == 'classification':
try:
Params = model.get_params()
accuracy,uq_ece,output = self.getUQclassification(model,ProblemName,Params)
class_status="SUCCESS"
#print(output)
except Exception as e:
print(e)
class_status="FAILED"
output = {'Problem':'None','msg':str(e)}
output = json.dumps(output)
elif Problemtype.lower() == 'regression' :
try:
Params = model.get_params()
total_picp_percentage,total_Uncertainty_percentage,uq_medium,uq_best,scoringCriteria,output = self.getUQregression(model,ProblemName,Params)
#print(uq_jsonobject)
reg_status="SUCCESS"
except Exception as e:
output = {'Problem':'None','msg':str(e)}
output = json.dumps(output)
reg_status="FAILED"
else:
try:
output={}
output['Problem']="None"
output['msg']="Uncertainty Quantification not supported for this algorithm."
output = json.dumps(output)
algorithm_status="FAILED"
except:
algorithm_status="FAILED"
except Exception as e:
print(e)
reg_status="FAILED"
class_status="FAILED"
algorithm_status="FAILED"
output = {'Problem':'None','msg':str(e)}
output = json.dumps(output)
return class_status,reg_status,algorithm_status,output
def aion_uq(modelFile,dataFile,features,targetfeatures):
try:
from appbe.dataPath import DEPLOY_LOCATION
uqLogLocation = os.path.join(DEPLOY_LOCATION,'logs')
try:
os.makedirs(uqLogLocation)
except OSError as e:
if (os.path.exists(uqLogLocation)):
pass
else:
raise OSError('uqLogLocation error.')
filename_uq = 'uqlog_'+str(int(time.time()))
filename_uq=filename_uq+'.log'
filepath = os.path.join(uqLogLocation, filename_uq)
print(filepath)
logging.basicConfig(filename=filepath, format='%(message)s',filemode='w')
log = logging.getLogger('aionUQ')
log.setLevel(logging.INFO)
log.info('************* Version - v1.7.0 *************** \\n')
if isinstance(features, list):
modelfeatures = features
else:
if ',' in features:
modelfeatures = [x.strip() for x in features.split(',')]
else:
modelfeatures = features.split(',')
model = joblib.load(modelFile)
uqobj = run_uq(modelfeatures,modelFile,dataFile,targetfeatures)
class_status,reg_status,algorithm_status,output=uqobj.uqMain(model)
if (class_status.lower() == 'failed'):
log.info('uq classifiction failed./n')
elif (class_status.lower() == 'success'):
log.info('uq classifiction success./n')
else:
log.info('uq classifiction not used../n')
if (reg_status.lower() == 'failed'):
log.info('uq regression failed./n')
elif (reg_status.lower() == 'success'):
log.info('uq regression success./n')
else:
log.info('uq regression not used./n')
if (algorithm_status.lower() == 'failed'):
log.info('Problem type issue, UQ only support classification and regression. May be selected algorithm not supported by Uncertainty Quantification currently./n')
except Exception as e:
log.info('uq test failed.n'+str(e))
#print(e)
output = {'Problem':'None','msg':str(e)}
output = json.dumps(output)
return(output)
#Sagemaker main fn call
if __name__=='__main__':
try:
parser = argparse.ArgumentParser()
parser.add_argument('savFile')
parser.add_argument('csvFile')
parser.add_argument('features')
parser.add_argument('target')
args = parser.parse_args()
home = expanduser("~")
if platform.system() == 'Windows':
uqLogLocation = os.path.join(home,'AppData','Local','HCLT','AION','uqLogs')
else:
uqLogLocation = os.path.join(home,'HCLT','AION','uqLogs')
try:
os.makedirs(uqLogLocation)
except OSError as e:
if (os.path.exists(uqLogLocation)):
pass
else:
raise OSError('uqLogLocation error.')
# self.sagemakerLogLocation=str(sagemakerLogLocation)
filename_uq = 'uqlog_'+str(int(time.time()))
filename_uq=filename_uq+'.log'
# filename = 'mlopsLog_'+Time()
filepath = os.path.join(uqLogLocation, filename_uq)
logging.basicConfig(filename=filepath, format='%(message)s',filemode='w')
log = logging.getLogger('aionUQ')
log.setLevel(logging.DEBUG)
if ',' in args.features:
args.features = [x.strip() for x in args.features.split(',')]
else:
args.features = args.features.split(',')
modelFile = args.savFile
modelfeatures = args.features
csvFile = args.csvFile
target=args.target
model = joblib.load(args.savFile)
##Main uq function call
uqobj = run_uq(modelfeatures,modelFile,csvFile,target)
class_status,reg_status,algorithm_status,output=uqobj.uqMain(model)
if (class_status.lower() == 'failed'):
log.info('uq classifiction failed./n')
elif (class_status.lower() == 'success'):
log.info('uq classifiction success./n')
else:
log.info('uq classifiction not used../n')
if (reg_status.lower() == 'failed'):
log.info('uq regression failed./n')
elif (reg_status.lower() == 'success'):
log.info('uq regression success./n')
else:
log.info('uq regression not used./n')
if (algorithm_status.lower() == 'failed'):
msg = 'Uncertainty Quantification not supported for this algorithm'
log.info('Algorithm not supported by Uncertainty Quantification./n')
output = {'Problem':'None','msg':str(msg)}
output = json.dumps(output)
except Exception as e:
log.info('uq test failed.n'+str(e))
output = {'Problem':'None','msg':str(e)}
output = json.dumps(output)
#print(e)
print(output)<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import logging
logging.getLogger('tensorflow').disabled = True
#from autogluon.tabular import TabularDataset, TabularPredictor
#from autogluon.core.utils.utils import setup_outputdir
#from autogluon.core.utils.loaders import load_pkl
#from autogluon.core.utils.savers import save_pkl
import datetime, time, timeit
from datetime import datetime as dt
import os.path
import json
import io
import shutil
import sys
#from Gluon_MultilabelPredictor import MultilabelPredictor
class MultilabelPredictor():
""" Tabular Predictor for predicting multiple columns in table.
Creates multiple TabularPredictor objects which you can also use individually.
You can access the TabularPredictor for a particular label via: `multilabel_predictor.get_predictor(label_i)`
Parameters
----------
labels : List[str]
The ith element of this list is the column (i.e. `label`) predicted by the ith TabularPredictor stored in this object.
path : str
Path to directory where models and intermediate outputs should be saved.
If unspecified, a time-stamped folder called "AutogluonModels/ag-[TIMESTAMP]" will be created in the working directory to store all models.
Note: To call `fit()` twice and save all results of each fit, you must specify different `path` locations or don't specify `path` at all.
Otherwise files from first `fit()` will be overwritten by second `fit()`.
Caution: when predicting many labels, this directory may grow large as it needs to store many TabularPredictors.
problem_types : List[str]
The ith element is the `problem_type` for the ith TabularPredictor stored in this object.
eval_metrics : List[str]
The ith element is the `eval_metric` for the ith TabularPredictor stored in this object.
consider_labels_correlation : bool
Whether the predictions of multiple labels should account for label correlations or predict each label independently of the others.
If True, the ordering of `labels` may affect resulting accuracy as each label is predicted conditional on the previous labels appearing earlier in this list (i.e. in an auto-regressive fashion).
Set to False if during inference you may want to individually use just the ith TabularPredictor without predicting all the other labels.
kwargs :
Arguments passed into the initialization of each TabularPredictor.
"""
multi_predictor_file = 'multilabel_predictor.pkl'
def __init__(self, labels, path, problem_types=None, eval_metrics=None, consider_labels_correlation=True, **kwargs):
if len(labels) < 2:
raise ValueError("MultilabelPredictor is only intended for predicting MULTIPLE labels (columns), use TabularPredictor for predicting one label (column).")
self.path = setup_outputdir(path, warn_if_exist=False)
self.labels = labels
#print(self.labels)
self.consider_labels_correlation = consider_labels_correlation
self.predictors = {} # key = label, value = TabularPredictor or str path to the TabularPredictor for this label
if eval_metrics is None:
self.eval_metrics = {}
else:
self.eval_metrics = {labels[i] : eval_metrics[i] for i in range(len(labels))}
problem_type = None
eval_metric = None
for i in range(len(labels)):
label = labels[i]
path_i = self.path + "Predictor_" + label
if problem_types is not None:
problem_type = problem_types[i]
if eval_metrics is not None:
eval_metric = self.eval_metrics[i]
self.predictors[label] = TabularPredictor(label=label, problem_type=problem_type, eval_metric=eval_metric, path=path_i, **kwargs)
def fit(self, train_data, tuning_data=None, **kwargs):
""" Fits a separate TabularPredictor to predict each of the labels.
Parameters
----------
train_data, tuning_data : str or autogluon.tabular.TabularDataset or pd.DataFrame
See documentation for `TabularPredictor.fit()`.
kwargs :
Arguments passed into the `fit()` call for each TabularPredictor.
"""
if isinstance(train_data, str):
train_data = TabularDataset(train_data)
if tuning_data is not None and isinstance(tuning_data, str):
tuning_data = TabularDataset(tuning_data)
train_data_og = train_data.copy()
if tuning_data is not None:
tuning_data_og = tuning_data.copy()
save_metrics = len(self.eval_metrics) == 0
for i in range(len(self.labels)):
label = self.labels[i]
predictor = self.get_predictor(label)
if not self.consider_labels_correlation:
labels_to_drop = [l for l in self.labels if l!=label]
else:
labels_to_drop = [self.labels[j] for j in range(i+1,len(self.labels))]
train_data = train_data_og.drop(labels_to_drop, axis=1)
if tuning_data is not None:
tuning_data = tuning_data_og.drop(labels_to_drop, axis=1)
print(f"Fitting TabularPredictor for label: {label} ...")
predictor.fit(train_data=train_data, tuning_data=tuning_data, **kwargs)
self.predictors[label] = predictor.path
if save_metrics:
self.eval_metrics[label] = predictor.eval_metric
self.save()
def eval_metrics(self):
return(self.eval_metrics)
def predict(self, data, **kwargs):
""" Returns DataFrame with label columns containing predictions for each label.
Parameters
----------
data : str or autogluon.tabular.TabularDataset or pd.DataFrame
Data to make predictions for. If label columns are present in this data, they will be ignored. See documentation for `TabularPredictor.predict()`.
kwargs :
Arguments passed into the predict() call for each TabularPredictor.
"""
return self._predict(data, as_proba=False, **kwargs)
def predict_proba(self, data, **kwargs):
""" Returns dict where each key is a label and the corresponding value is the `predict_proba()` output for just that label.
Parameters
----------
data : str or autogluon.tabular.TabularDataset or pd. | ||
DataFrame
Data to make predictions for. See documentation for `TabularPredictor.predict()` and `TabularPredictor.predict_proba()`.
kwargs :
Arguments passed into the `predict_proba()` call for each TabularPredictor (also passed into a `predict()` call).
"""
return self._predict(data, as_proba=True, **kwargs)
def evaluate(self, data, **kwargs):
""" Returns dict where each key is a label and the corresponding value is the `evaluate()` output for just that label.
Parameters
----------
data : str or autogluon.tabular.TabularDataset or pd.DataFrame
Data to evalate predictions of all labels for, must contain all labels as columns. See documentation for `TabularPredictor.evaluate()`.
kwargs :
Arguments passed into the `evaluate()` call for each TabularPredictor (also passed into the `predict()` call).
"""
data = self._get_data(data)
eval_dict = {}
for label in self.labels:
print(f"Evaluating TabularPredictor for label: {label} ...")
predictor = self.get_predictor(label)
eval_dict[label] = predictor.evaluate(data, **kwargs)
if self.consider_labels_correlation:
data[label] = predictor.predict(data, **kwargs)
return eval_dict
def save(self):
""" Save MultilabelPredictor to disk. """
for label in self.labels:
if not isinstance(self.predictors[label], str):
self.predictors[label] = self.predictors[label].path
save_pkl.save(path=self.path+self.multi_predictor_file, object=self)
print(f"MultilabelPredictor saved to disk. Load with: MultilabelPredictor.load('{self.path}')")
@classmethod
def load(cls, path):
""" Load MultilabelPredictor from disk `path` previously specified when creating this MultilabelPredictor. """
path = os.path.expanduser(path)
if path[-1] != os.path.sep:
path = path + os.path.sep
return load_pkl.load(path=path+cls.multi_predictor_file)
def get_predictor(self, label):
""" Returns TabularPredictor which is used to predict this label. """
predictor = self.predictors[label]
if isinstance(predictor, str):
return TabularPredictor.load(path=predictor)
return predictor
def _get_data(self, data):
if isinstance(data, str):
return TabularDataset(data)
return data.copy()
def _predict(self, data, as_proba=False, **kwargs):
data = self._get_data(data)
if as_proba:
predproba_dict = {}
for label in self.labels:
print(f"Predicting with TabularPredictor for label: {label} ...")
predictor = self.get_predictor(label)
if as_proba:
predproba_dict[label] = predictor.predict_proba(data, as_multiclass=True, **kwargs)
data[label] = predictor.predict(data, **kwargs)
if not as_proba:
return data[self.labels]
else:
return predproba_dict
def aion_train_gluon(arg):
configFile = arg
with open(configFile, 'rb') as cfile:
data = json.load(cfile)
cfile.close()
rootElement = data['basic']
modelname = rootElement['modelName']
version = rootElement['modelVersion']
dataLocation = rootElement['dataLocation']
deployFolder = rootElement['deployLocation']
analysisType = rootElement['analysisType']
testPercentage = data['advance']['testPercentage']
deployLocation = os.path.join(deployFolder,modelname+'_'+version)
try:
os.makedirs(deployLocation)
except OSError as e:
shutil.rmtree(deployLocation)
os.makedirs(deployLocation)
logLocation = os.path.join(deployLocation,'log')
try:
os.makedirs(logLocation)
except OSError as e:
pass
etcLocation = os.path.join(deployLocation,'etc')
try:
os.makedirs(etcLocation)
except OSError as e:
pass
logFileName=os.path.join(deployLocation,'log','model_training_logs.log')
filehandler = logging.FileHandler(logFileName, 'w','utf-8')
formatter = logging.Formatter('%(message)s')
filehandler.setFormatter(formatter)
log = logging.getLogger('eion')
log.propagate = False
for hdlr in log.handlers[:]: # remove the existing file handlers
if isinstance(hdlr,logging.FileHandler):
log.removeHandler(hdlr)
log.addHandler(filehandler)
log.setLevel(logging.INFO)
log.info('************* Version - v1.2.0 *************** \\n')
msg = '-------> Execution Start Time: '+ dt.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
log.info(msg)
dataLabels = rootElement['targetFeature'].split(',')
# Create and Write the config file used in Prediction
# ----------------------------------------------------------------------------#
tdata = TabularDataset(dataLocation)
#train_data = tdata
train_data = tdata.sample(frac = 0.8)
test_data = tdata.drop(train_data.index)
if rootElement['trainingFeatures'] != '':
trainingFeatures = rootElement['trainingFeatures'].split(',')
else:
trainingFeatures = list(train_data.columns)
features = trainingFeatures
for x in dataLabels:
if x not in features:
features.append(x)
indexFeature = rootElement['indexFeature']
if indexFeature != '':
indexFeature = indexFeature.split(',')
for x in indexFeature:
if x in features:
features.remove(x)
dateTimeFeature = rootElement['dateTimeFeature']
if dateTimeFeature != '':
dateTimeFeature = dateTimeFeature.split(',')
for x in dateTimeFeature:
if x in features:
features.remove(x)
train_data = train_data[features]
test_data = test_data[features]
configJsonFile = {"targetFeature":dataLabels,"features":",".join([feature for feature in features])}
configJsonFilePath = os.path.join(deployLocation,'etc','predictionConfig.json')
if len(dataLabels) == 1 and analysisType['multiLabelPrediction'] == "False":
dataLabels = rootElement['targetFeature']
with io.open(configJsonFilePath, 'w', encoding='utf8') as outfile:
str_ = json.dumps(configJsonFile, ensure_ascii=False)
outfile.write(str_)
# ----------------------------------------------------------------------------#
if analysisType['multiLabelPrediction'] == "True":
# Copy and Write the Predictiion script file into deployment location
# ----------------------------------------------------------------------------#
srcFile = os.path.join(os.path.dirname(__file__),'gluon','AION_Gluon_MultiLabelPrediction.py')
dstFile = os.path.join(deployLocation,'aion_predict.py')
shutil.copy(srcFile,dstFile)
# ----------------------------------------------------------------------------#
labels = dataLabels # which columns to predict based on the others
#problem_types = dataProblem_types # type of each prediction problem
save_path = os.path.join(deployLocation,'ModelPath') # specifies folder to store trained models
time_limit = 5 # how many seconds to train the TabularPredictor for each label
log.info('Status:-|... AION Gluon Start')
try:
if len(labels) < 2:
log.info('Status:-|... AION Evaluation Error: Target should be multiple column')
# ----------------------------------------------------------------------------#
output = {'status':'FAIL','message':'Number of target variable should be 2 or more than 2'}
else:
multi_predictor = MultilabelPredictor(labels=labels, path=save_path)
multi_predictor.fit(train_data, time_limit=time_limit)
log.info('Status:-|... AION Gluon Stop')
log.info('Status:-|... AION Evaluation Start')
trainevaluations = multi_predictor.evaluate(train_data)
testevaluations = multi_predictor.evaluate(test_data)
best_model = {}
for label in labels:
predictor_class = multi_predictor.get_predictor(label)
predictor_class.get_model_best()
best_model[label] = predictor_class.get_model_best()
log.info('Status:-|... AION Evaluation Stop')
# ----------------------------------------------------------------------------#
output = {'status':'SUCCESS','data':{'ModelType':'MultiLabelPrediction','EvaluatedModels':'','featuresused':'','BestModel':'AutoGluon','BestScore': '0', 'ScoreType': 'ACCURACY','deployLocation':deployLocation,'matrix':trainevaluations,'testmatrix':testevaluations,'BestModel':best_model, 'LogFile':logFileName}}
except Exception as inst:
log.info('Status:-|... AION Gluon Error')
output = {"status":"FAIL","message":str(inst).strip('"')}
if analysisType['multiModalLearning'] == "True":
from autogluon.core.utils.utils import get_cpu_count, get_gpu_count
from autogluon.text import TextPredictor
# check the system and then set the equivelent flag
# ----------------------------------------------------------------------------#
os.environ["AUTOGLUON_TEXT_TRAIN_WITHOUT_GPU"] = "0"
if get_gpu_count() == 0:
os.environ["AUTOGLUON_TEXT_TRAIN_WITHOUT_GPU"] = "1"
# ----------------------------------------------------------------------------#
# Copy and Write the Predictiion script file into deployment location
# ----------------------------------------------------------------------------#
srcFile = os.path.join(os.path.dirname(__file__),'gluon','AION_Gluon_MultiModalPrediction.py')
dstFile = os.path.join(deployLocation,'aion_predict.py')
shutil.copy(srcFile,dstFile)
time_limit = None # set to larger value in your applications
save_path = os.path.join(deployLocation,'text_prediction')
predictor = TextPredictor(label=dataLabels, path=save_path)
predictor.fit(train_data, time_limit=time_limit)
log.info('Status:-|... AION Gluon Stop')
log.info('Status:-|... AION Evaluation Start')
trainevaluations = predictor.evaluate(train_data)
log.info('Status:-|... AION Evaluation Stop')
# ----------------------------------------------------------------------------#
output = {'status':'SUCCESS','data':{'ModelType':'MultiModelLearning','EvaluatedModels':'','featuresused':'','BestModel':'AutoGluon','BestScore': '0', 'ScoreType': 'SCORE','deployLocation':deployLocation,'matrix':trainevaluations,'LogFile':logFileName}}
output = json.dumps(output)
print("\\n")
print("aion_learner_status:",output)
print("\\n")
log.info('\\n------------- Output JSON ------------')
log.info('-------> Output :'+str(output))
log.info('------------- Output JSON ------------\\n')
for hdlr in log.handlers[:]: # remove the existing file handlers
if isinstance(hdlr,logging.FileHandler):
hdlr.close()
log.removeHandler(hdlr)
return(output)
if __name__ == "__main__":
aion_train_gluon(sys.argv[1])<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os
import platform
import shutil
import subprocess
import sys
import glob
import json
def publish(data):
if os.path.splitext(data)[1] == ".json":
with open(data,'r',encoding='utf-8') as f:
jsonData = json.load(f)
else:
jsonData = json.loads(data)
model = jsonData['modelName']
version = jsonData['modelVersion']
deployFolder = jsonData['deployLocation']
model = model.replace(" ", "_")
deployedPath = os.path.join(deployFolder,model+'_'+version)
deployedPath = os.path.join(deployedPath,'WHEELfile')
whlfilename='na'
if os.path.isdir(deployedPath):
for file in os.listdir(deployedPath):
if file.endswith(".whl"):
whlfilename = os.path.join(deployedPath,file)
if whlfilename != 'na':
subprocess.check_call([sys.executable, "-m", "pip", "uninstall","-y",model])
subprocess.check_call([sys.executable, "-m", "pip", "install", whlfilename])
status,pid,ip,port = check_service_running(jsonData['modelName'],jsonData['serviceFolder'])
if status == 'Running':
service_stop(json.dumps(jsonData))
service_start(json.dumps(jsonData))
output_json = {'status':"SUCCESS"}
output_json = json.dumps(output_json)
else:
output_json = {'status':'Error','Msg':'Installation Package not Found'}
output_json = json.dumps(output_json)
return(output_json)
def check_service_running(model,serviceFolder):
model = model.replace(" ", "_")
filename = model+'_service.py'
modelservicefile = os.path.join(serviceFolder,filename)
status = 'File Not Exist'
ip = ''
port = ''
pid = ''
if os.path.exists(modelservicefile):
status = 'File Exist'
import psutil
for proc in psutil.process_iter():
pinfo = proc.as_dict(attrs=['pid', 'name', 'cmdline','connections'])
if 'python' in pinfo['name']:
if filename in pinfo['cmdline'][1]:
status = 'Running'
pid = pinfo['pid']
for x in pinfo['connections']:
ip = x.laddr.ip
port = x.laddr.port
return(status,pid,ip,port)
def service_stop(data):
if os.path.splitext(data)[1] == ".json":
with open(data,'r',encoding='utf-8') as f:
jsonData = json | ||
.load(f)
else:
jsonData = json.loads(data)
status,pid,ip,port = check_service_running(jsonData['modelName'],jsonData['serviceFolder'])
if status == 'Running':
import psutil
p = psutil.Process(int(pid))
p.terminate()
time.sleep(2)
output_json = {'status':'SUCCESS'}
output_json = json.dumps(output_json)
return(output_json)
def service_start(data):
if os.path.splitext(data)[1] == ".json":
with open(data,'r',encoding='utf-8') as f:
jsonData = json.load(f)
else:
jsonData = json.loads(data)
model = jsonData['modelName']
version = jsonData['modelVersion']
ip = jsonData['ip']
port = jsonData['port']
deployFolder = jsonData['deployLocation']
serviceFolder = jsonData['serviceFolder']
model = model.replace(" ", "_")
deployLocation = os.path.join(deployFolder,model+'_'+version)
org_service_file = os.path.abspath(os.path.join(os.path.dirname(__file__),'model_service.py'))
filename = model+'_service.py'
modelservicefile = os.path.join(serviceFolder,filename)
status = 'File Not Exist'
if os.path.exists(modelservicefile):
status = 'File Exist'
r = ([line.split() for line in subprocess.check_output("tasklist").splitlines()])
for i in range(len(r)):
if filename in r[i]:
status = 'Running'
if status == 'File Not Exist':
shutil.copy(org_service_file,modelservicefile)
with open(modelservicefile, 'r+') as file:
content = file.read()
file.seek(0, 0)
line = 'from '+model+' import aion_performance'
file.write(line+"\\n")
line = 'from '+model+' import aion_drift'
file.write(line+ "\\n")
line = 'from '+model+' import featureslist'
file.write(line+ "\\n")
line = 'from '+model+' import aion_prediction'
file.write(line+ "\\n")
file.write(content)
file.close()
status = 'File Exist'
if status == 'File Exist':
status,pid,ipold,portold = check_service_running(jsonData['modelName'],jsonData['serviceFolder'])
if status != 'Running':
command = "python "+modelservicefile+' '+str(port)+' '+str(ip)
os.system('start cmd /c "'+command+'"')
time.sleep(2)
status = 'Running'
output_json = {'status':'SUCCESS','Msg':status}
output_json = json.dumps(output_json)
return(output_json)
if __name__ == "__main__":
aion_publish(sys.argv[1])
<s> import json
import logging
import os
import shutil
import time
import sys
from sys import platform
from distutils.util import strtobool
from config_manager.pipeline_config import AionConfigManager
from summarizer import Summarizer
# Base class for EION configuration Manager which read the needed f params from eion.json, initialize the parameterlist, read the respective params, store in variables and return back to caller function or external modules.
class AionTextManager:
def __init__(self):
self.log = logging.getLogger('eion')
self.data = ''
self.problemType = ''
self.basic = []
self.advance=[]
def readTextfile(self,dataPath):
#dataPath=self.[baisc][]
file = open(dataPath, "r")
data = file.read()
return data
#print(data)
def generateSummary(self,data,algo,stype):
bert_model = Summarizer()
if stype == "large":
bert_summary = ''.join(bert_model(data, min_length=300))
return(bert_summary)
elif stype == "medium":
bert_summary = ''.join(bert_model(data, min_length=150))
return(bert_summary)
elif stype == "small":
bert_summary = ''.join(bert_model(data, min_length=60))
return(bert_summary)
def aion_textsummary(arg):
Obj = AionTextManager()
configObj = AionConfigManager()
readConfistatus,msg = configObj.readConfigurationFile(arg)
dataPath = configObj.getTextlocation()
text_data = Obj.readTextfile(dataPath)
getAlgo, getMethod = configObj.getTextSummarize()
summarize = Obj.generateSummary(text_data, getAlgo, getMethod)
output = {'status':'Success','summary':summarize}
output_json = json.dumps(output)
return(output_json)
if __name__ == "__main__":
aion_textsummary(sys.argv[1])
<s> import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__))))
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import requests
import json
import os
from datetime import datetime
import socket
import getmac
def telemetry_data(operation,Usecase,data):
now = datetime.now()
ID = datetime.timestamp(now)
record_date = now.strftime("%y-%m-%d %H:%M:%S")
try:
user = os.getlogin()
except:
user = 'NA'
computername = socket.getfqdn()
macaddress = getmac.get_mac_address()
item = {}
item['ID'] = str(int(ID))
item['record_date'] = record_date
item['UseCase'] = Usecase
item['user'] = str(user)
item['operation'] = operation
item['remarks'] = data
item['hostname'] = computername
item['macaddress'] = macaddress
url = 'https://l5m119j6v9.execute-api.ap-south-1.amazonaws.com/default/aion_telemetry'
record = {}
record['TableName'] = 'AION_OPERATION'
record['Item'] = item
record = json.dumps(record)
try:
response = requests.post(url, data=record,headers={"x-api-key":"Obzt8ijfOT3dgBYma9JCt1tE3W6tzHaV8rVuQdMK","Content-Type":"application/json",})
check_telemetry_file()
except Exception as inst:
filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),'telemetry.txt')
f=open(filename, "a+")
f.write(record+'\\n')
f.close()
def check_telemetry_file():
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'telemetry.txt')
if(os.path.isfile(file_path)):
f = open(file_path, 'r')
file_content = f.read()
f.close()
matched_lines = file_content.split('\\n')
write_lines = []
url = 'https://l5m119j6v9.execute-api.ap-south-1.amazonaws.com/default/aion_telemetry'
for record in matched_lines:
try:
response = requests.post(url, data=record,headers={"x-api-key":"Obzt8ijfOT3dgBYma9JCt1tE3W6tzHaV8rVuQdMK","Content-Type":"application/json",})
except:
write_lines.append(record)
f = open(file_path, "a")
f.seek(0)
f.truncate()
for record in write_lines:
f.write(record+'\\n')
f.close()
return True
else:
return True<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import os
import sys
import json
import datetime, time, timeit
import argparse
import logging
logging.getLogger('tensorflow').disabled = True
import math
import shutil
import re
from datetime import datetime as dt
import warnings
from config_manager.pipeline_config import AionConfigManager
import pandas as pd
import numpy as np
import sklearn
import string
from records import pushrecords
import logging
from pathlib import Path
from pytz import timezone
from config_manager.config_gen import code_configure
import joblib
from sklearn.model_selection import train_test_split
from config_manager.check_config import config_validate
from utils.file_ops import save_csv_compressed,save_csv,save_chromadb
LOG_FILE_NAME = 'model_training_logs.log'
if 'AION' in sys.modules:
try:
from appbe.app_config import DEBUG_ENABLED
except:
DEBUG_ENABLED = False
else:
DEBUG_ENABLED = True
def getversion():
configFolder = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','config')
version = 'NA'
for file in os.listdir(configFolder):
if file.endswith(".var"):
version = file.rsplit('.', 1)
version = version[0]
break
return version
AION_VERSION = getversion()
def pushRecordForTraining():
try:
status,msg = pushrecords.enterRecord(AION_VERSION)
except Exception as e:
print("Exception", e)
status = False
msg = str(e)
return status,msg
def mlflowSetPath(path,experimentname):
import mlflow
url = "file:" + str(Path(path).parent.parent) + "/mlruns"
mlflow.set_tracking_uri(url)
mlflow.set_experiment(str(experimentname))
def set_log_handler( basic, mode='w'):
deploy_loc = Path(basic.get('deployLocation'))
log_file_parent = deploy_loc/basic['modelName']/basic['modelVersion']/'log'
log_file_parent.mkdir(parents=True, exist_ok=True)
log_file = log_file_parent/LOG_FILE_NAME
filehandler = logging.FileHandler(log_file, mode,'utf-8')
formatter = logging.Formatter('%(message)s')
filehandler.setFormatter(formatter)
log = logging.getLogger('eion')
log.propagate = False
for hdlr in log.handlers[:]: # remove the existing file handlers
if isinstance(hdlr,logging.FileHandler):
log.removeHandler(hdlr)
log.addHandler(filehandler)
log.setLevel(logging.INFO)
return log
class server():
def __init__(self):
self.response = None
self.features=[]
self.mFeatures=[]
self.emptyFeatures=[]
self.textFeatures=[]
self.vectorizerFeatures=[]
self.wordToNumericFeatures=[]
self.profilerAction = []
self.targetType = ''
self.matrix1='{'
self.matrix2='{'
self.matrix='{'
self.trainmatrix='{'
self.numericalFeatures=[]
self.nonNumericFeatures=[]
self.similarGroups=[]
self.dfcols=0
self.dfrows=0
self.method = 'NA'
self.pandasNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
self.modelSelTopFeatures=[]
self.topFeatures=[]
self.allFeatures=[]
def startScriptExecution(self, config_obj, codeConfigure, log):
oldStdout = sys.stdout
model_training_details = ''
model_tried=''
learner_type = ''
topics = {}
pred_filename = ''
numericContinuousFeatures=''
discreteFeatures=''
sessonal_freq = ''
additional_regressors = ''
threshold=-1
targetColumn = ''
numericalFeatures =''
nonNumericFeatures=''
categoricalFeatures=''
dataFolderLocation = ''
featureReduction = 'False'
original_data_file = ''
normalizer_pickle_file = ''
pcaModel_pickle_file = ''
bpca_features= []
apca_features = []
lag_order = 1
profiled_data_file = ''
trained_data_file = ''
predicted_data_file=''
dictDiffCount={}
cleaning_kwargs = {}
grouperbyjson = ''
rowfilterexpression=''
featureEngineeringSelector = 'false'
conversion_method = ''
params={}
loss_matrix='binary_crossentropy'
optimizer='Nadam'
numericToLabel_json='[]'
preprocessing_pipe=''
firstDocFeature = ''
secondDocFeature = ''
padding_length = 30
pipe = None
scalertransformationFile=None
column_merge_flag = False
merge_columns = []
score = 0
profilerObj = None
imageconfig=''
labelMaps={}
featureDataShape=[]
normFeatures = []
preprocess_out_columns = []
preprocess_pipe = None
label_encoder = None
unpreprocessed_columns = []
import pickle
iterName,iterVersion,dataLocation,deployLocation,delimiter,textqualifier = config_obj.getAIONLocationSettings()
inlierLabels=config_obj.getEionInliers()
scoreParam = config_obj.getScoringCreteria()
noofforecasts = config_obj.getNumberofForecasts()
datetimeFeature,indexFeature,modelFeatures=config_obj.getFeatures()
filter_expression = config_obj.getFilterExpression()
refined_filter_expression = ""
sa_images = []
model_tried = ''
deploy_config = {}
iterName = iterName.replace(" ", "_")
deployFolder = deployLocation
usecaseLocation,deployLocation,dataFolderLocation,imageFolderLocation,original_data_file,profiled | ||
_data_file,trained_data_file,predicted_data_file,logFileName,outputjsonFile,reduction_data_file = config_obj.createDeploymentFolders(deployFolder,iterName,iterVersion)
outputLocation=deployLocation
mlflowSetPath(deployLocation,iterName+'_'+iterVersion)
# mlflowSetPath shut down the logger, so set again
set_log_handler( config_obj.basic, mode='a')
xtrain=pd.DataFrame()
xtest=pd.DataFrame()
log.info('Status:-|... AION Training Configuration started')
startTime = timeit.default_timer()
try:
output = {'bestModel': '', 'bestScore': 0, 'bestParams': {}}
problem_type,targetFeature,profiler_status,selector_status,learner_status,deeplearner_status,timeseriesStatus,textsummarizationStatus,survival_analysis_status,textSimilarityStatus,inputDriftStatus,outputDriftStatus,recommenderStatus,visualizationstatus,deploy_status,associationRuleStatus,imageClassificationStatus,forecastingStatus, objectDetectionStatus,stateTransitionStatus, similarityIdentificationStatus,contextualSearchStatus,anomalyDetectionStatus = config_obj.getModulesDetails()
status, error_id, msg = config_obj.validate_config()
if not status:
if error_id == 'fasttext':
raise ValueError(msg)
VideoProcessing = False
if(problem_type.lower() in ['classification','regression']):
if(targetFeature == ''):
output = {"status":"FAIL","message":"Target Feature is Must for Classification and Regression Problem Type"}
return output
from transformations.dataReader import dataReader
objData = dataReader()
DataIsFolder = False
folderdetails = config_obj.getFolderSettings()
if os.path.isfile(dataLocation):
log.info('Status:-|... AION Loading Data')
dataFrame = objData.csvTodf(dataLocation,delimiter,textqualifier)
status,msg = save_csv_compressed(dataFrame,original_data_file)
if not status:
log.info('CSV File Error: '+str(msg))
elif os.path.isdir(dataLocation):
if problem_type.lower() == 'summarization':
from document_summarizer import summarize
keywords, pretrained_type, embedding_sz = summarize.get_params()
dataFrame = summarize.to_dataframe(dataLocation,keywords, deploy_loc, pretrained_type, embedding_sz)
problem_type = 'classification'
targetFeature = 'label'
scoreParam = 'Accuracy'
elif folderdetails['fileType'].lower() == 'document':
dataFrame, error = objData.documentsTodf(dataLocation, folderdetails['labelDataFile'])
if error:
log.info(error)
elif folderdetails['fileType'].lower() == 'object':
testPercentage = config_obj.getAIONTestTrainPercentage() #Unnati
intermediateLocation = os.path.join(deployLocation,'intermediate')
os.mkdir(intermediateLocation)
AugEnabled,keepAugImages,operations,augConf = config_obj.getEionImageAugmentationConfiguration()
dataFrame, n_class = objData.createTFRecord(dataLocation, intermediateLocation, folderdetails['labelDataFile'], testPercentage,AugEnabled,keepAugImages,operations, "objectdetection",augConf) #Unnati
DataIsFolder = True
else:
datafilelocation = os.path.join(dataLocation,folderdetails['labelDataFile'])
dataFrame = objData.csvTodf(datafilelocation,delimiter,textqualifier)
DataIsFolder = True
if textSimilarityStatus or similarityIdentificationStatus or contextualSearchStatus:
similaritydf = dataFrame
filter = config_obj.getfilter()
if filter != 'NA':
dataFrame,rowfilterexpression = objData.rowsfilter(filter,dataFrame)
timegrouper = config_obj.gettimegrouper()
grouping = config_obj.getgrouper()
if grouping != 'NA':
dataFrame,grouperbyjson = objData.grouping(grouping,dataFrame)
elif timegrouper != 'NA':
dataFrame,grouperbyjson = objData.timeGrouping(timegrouper,dataFrame)
if timeseriesStatus or anomalyDetectionStatus:
from utils.validate_inputs import dataGarbageValue
status,msg = dataGarbageValue(dataFrame,datetimeFeature)
if status.lower() == 'error':
raise ValueError(msg)
if not DataIsFolder:
if timeseriesStatus:
if(modelFeatures != 'NA' and datetimeFeature != ''):
if datetimeFeature:
if isinstance(datetimeFeature, list): #to handle if time series having multiple time column
unpreprocessed_columns = unpreprocessed_columns + datetimeFeature
else:
unpreprocessed_columns = unpreprocessed_columns + datetimeFeature.split(',')
if datetimeFeature not in modelFeatures:
modelFeatures = modelFeatures+','+datetimeFeature
dataFrame = objData.removeFeatures(dataFrame,'NA',indexFeature,modelFeatures,targetFeature)
elif survival_analysis_status or anomalyDetectionStatus:
if(modelFeatures != 'NA'):
if datetimeFeature != 'NA' and datetimeFeature != '':
unpreprocessed_columns = unpreprocessed_columns + datetimeFeature.split(',')
if datetimeFeature not in modelFeatures:
modelFeatures = modelFeatures+','+datetimeFeature
dataFrame = objData.removeFeatures(dataFrame,'NA',indexFeature,modelFeatures,targetFeature)
else:
dataFrame = objData.removeFeatures(dataFrame,datetimeFeature,indexFeature,modelFeatures,targetFeature)
log.info('\\n-------> First Ten Rows of Input Data: ')
log.info(dataFrame.head(10))
self.dfrows=dataFrame.shape[0]
self.dfcols=dataFrame.shape[1]
log.info('\\n-------> Rows: '+str(self.dfrows))
log.info('\\n-------> Columns: '+str(self.dfcols))
topFeatures=[]
profilerObj = None
normalizer=None
dataLoadTime = timeit.default_timer() - startTime
log.info('-------> COMPUTING: Total dataLoadTime time(sec) :'+str(dataLoadTime))
if timeseriesStatus:
if datetimeFeature != 'NA' and datetimeFeature != '':
preproces_config = config_obj.basic.get('preprocessing',{}).get('timeSeriesForecasting',{})
if preproces_config:
from transformations.preprocess import timeSeries as ts_preprocess
preprocess_obj = ts_preprocess( preproces_config,datetimeFeature, log)
dataFrame = preprocess_obj.run( dataFrame)
log.info('-------> Input dataFrame(5 Rows) after preprocessing: ')
log.info(dataFrame.head(5))
deploy_config['preprocess'] = {}
deploy_config['preprocess']['code'] = preprocess_obj.get_code()
if profiler_status:
log.info('\\n================== Data Profiler has started ==================')
log.info('Status:-|... AION feature transformation started')
from transformations.dataProfiler import profiler as dataProfiler
dp_mlstart = time.time()
profilerJson = config_obj.getEionProfilerConfigurarion()
log.info('-------> Input dataFrame(5 Rows): ')
log.info(dataFrame.head(5))
log.info('-------> DataFrame Shape (Row,Columns): '+str(dataFrame.shape))
testPercentage = config_obj.getAIONTestTrainPercentage() #Unnati
if DataIsFolder:
if folderdetails['type'].lower() != 'objectdetection':
profilerObj = dataProfiler(dataFrame)
topFeatures,VideoProcessing,tfrecord_directory = profilerObj.folderPreprocessing(dataLocation,folderdetails,deployLocation)
elif textSimilarityStatus:
firstDocFeature = config_obj.getFirstDocumentFeature()
secondDocFeature = config_obj.getSecondDocumentFeature()
profilerObj = dataProfiler(dataFrame,targetFeature, data_path=dataFolderLocation)
dataFrame,pipe,targetColumn,topFeatures = profilerObj.textSimilarityStartProfiler(firstDocFeature,secondDocFeature)
elif recommenderStatus:
profilerObj = dataProfiler(dataFrame)
dataFrame = profilerObj.recommenderStartProfiler(modelFeatures)
else:
if deeplearner_status or learner_status:
if (problem_type.lower() != 'clustering') and (problem_type.lower() != 'topicmodelling'):
if targetFeature != '':
try:
biasingDetail = config_obj.getDebiasingDetail()
if len(biasingDetail) > 0:
if biasingDetail['FeatureName'] != 'None':
protected_feature = biasingDetail['FeatureName']
privileged_className = biasingDetail['ClassName']
target_feature = biasingDetail['TargetFeature']
algorithm = biasingDetail['Algorithm']
from debiasing.DebiasingManager import DebiasingManager
mgrObj = DebiasingManager()
log.info('Status:-|... Debiasing transformation started')
transf_dataFrame = mgrObj.Bias_Mitigate(dataFrame, protected_feature, privileged_className, target_feature, algorithm)
log.info('Status:-|... Debiasing transformation completed')
dataFrame = transf_dataFrame
except Exception as e:
print(e)
pass
# ---------------------------------------------- ----------------------------------------------
targetData = dataFrame[targetFeature]
featureData = dataFrame[dataFrame.columns.difference([targetFeature])]
testPercentage = config_obj.getAIONTestTrainPercentage() #Unnati
xtrain,ytrain,xtest,ytest = self.split_into_train_test_data(featureData,targetData,testPercentage,log,problem_type.lower())
xtrain.reset_index(drop=True,inplace=True)
ytrain.reset_index(drop=True,inplace=True)
xtest.reset_index(drop=True,inplace=True)
ytest.reset_index(drop=True,inplace=True)
dataFrame = xtrain
dataFrame[targetFeature] = ytrain
encode_target_problems = ['classification','anomalyDetection', 'timeSeriesAnomalyDetection'] #task 11997
if problem_type == 'survivalAnalysis' and dataFrame[targetFeature].nunique() > 1:
encode_target_problems.append('survivalAnalysis')
if timeseriesStatus: #task 12627 calling data profiler without target feature specified separately (i.e) profiling is done for model features along with target features
profilerObj = dataProfiler(dataFrame, config=profilerJson, keep_unprocessed = unpreprocessed_columns.copy(), data_path=dataFolderLocation)
else:
profilerObj = dataProfiler(dataFrame, target=targetFeature, encode_target= problem_type in encode_target_problems, config=profilerJson, keep_unprocessed = unpreprocessed_columns.copy(), data_path=dataFolderLocation) #task 12627
dataFrame, preprocess_pipe, label_encoder = profilerObj.transform()
preprocess_out_columns = dataFrame.columns.tolist()
if not timeseriesStatus: #task 12627 preprocess_out_columns goes as output_columns in target folder script/input_profiler.py, It should contain the target feature also as it is what is used for forecasting
if targetFeature in preprocess_out_columns:
preprocess_out_columns.remove(targetFeature)
for x in unpreprocessed_columns:
preprocess_out_columns.remove(x)
if label_encoder:
joblib.dump(label_encoder, Path(deployLocation)/'model'/'label_encoder.pkl')
labelMaps = dict(zip(label_encoder.classes_, label_encoder.transform(label_encoder.classes_)))
codeConfigure.update_config('train_features',list(profilerObj.train_features_type.keys()))
codeConfigure.update_config('text_features',profilerObj.text_feature)
self.textFeatures = profilerObj.text_feature
deploy_config['profiler'] = {}
deploy_config['profiler']['input_features'] = list(profilerObj.train_features_type.keys())
deploy_config['profiler']['output_features'] = preprocess_out_columns
deploy_config['profiler']['input_features_type'] = profilerObj.train_features_type
deploy_config['profiler']['word2num_features'] = profilerObj.wordToNumericFeatures
deploy_config['profiler']['unpreprocessed_columns'] = unpreprocessed_columns
deploy_config['profiler']['force_numeric_conv'] = profilerObj.force_numeric_conv
if self.textFeatures:
deploy_config['profiler']['conversion_method'] = config_obj.get_conversion_method()
if anomalyDetectionStatus and datetimeFeature != 'NA' and datetimeFeature != '':
if unpreprocessed_columns:
dataFrame.set_index( unpreprocessed_columns[0], inplace=True)
log.info('-------> Data Frame Post Data Profiling(5 Rows): ')
log.info(dataFrame.head(5))
if not xtest.empty:
if targetFeature != '':
non_null_index = ytest.notna()
ytest = ytest[non_null_index]
xtest = xtest[non_null_index]
if profilerObj.force_numeric_conv:
xtest[ profilerObj.force_numeric_conv] = xtest[profilerObj.force_numeric_conv].apply(pd.to_numeric,errors='coerce')
xtest.astype(profilerObj.train_features_type)
if unpreprocessed_columns:
xtest_unprocessed = xtest[unpreprocessed_columns]
xtest = preprocess_pipe.transform(xtest)
if not isinstance(xtest, np.ndarray):
xtest = xtest.toarray()
xtest = pd.DataFrame(xtest, columns=preprocess_out_columns)
if unpreprocessed_columns:
xtest[unpreprocessed_columns] = xtest_unprocessed
if survival_analysis_status:
xtest.astype({x:'float' for x in unpreprocessed_columns})
xtrain.astype({x:'float' for x in unpreprocessed_columns})
#task 11997 removed setting datetime column as index of dataframe code as it is already done before
if label_encoder:
ytest = label_encoder | ||
.transform(ytest)
if preprocess_pipe:
if self.textFeatures:
from text.textProfiler import reset_pretrained_model
reset_pretrained_model(preprocess_pipe) # pickle is not possible for fasttext model ( binary)
joblib.dump(preprocess_pipe, Path(deployLocation)/'model'/'preprocess_pipe.pkl')
self.features=topFeatures
if targetColumn in topFeatures:
topFeatures.remove(targetColumn)
self.topFeatures=topFeatures
if normalizer != None:
normalizer_file_path = os.path.join(deployLocation,'model','normalizer_pipe.sav')
normalizer_pickle_file = 'normalizer_pipe.sav'
pickle.dump(normalizer, open(normalizer_file_path,'wb'))
log.info('Status:-|... AION feature transformation completed')
dp_mlexecutionTime=time.time() - dp_mlstart
log.info('-------> COMPUTING: Total Data Profiling Execution Time '+str(dp_mlexecutionTime))
log.info('================== Data Profiling completed ==================\\n')
else:
datacolumns=list(dataFrame.columns)
if targetFeature in datacolumns:
datacolumns.remove(targetFeature)
if not timeseriesStatus and not anomalyDetectionStatus and not inputDriftStatus and not outputDriftStatus and not imageClassificationStatus and not associationRuleStatus and not objectDetectionStatus and not stateTransitionStatus and not textsummarizationStatus:
self.textFeatures,self.vectorizerFeatures,pipe,column_merge_flag,merge_columns = profilerObj.checkForTextClassification(dataFrame)
self.topFeatures =datacolumns
if(pipe is not None):
preprocessing_pipe = 'pppipe'+iterName+'_'+iterVersion+'.sav'
ppfilename = os.path.join(deployLocation,'model','pppipe'+iterName+'_'+iterVersion+'.sav')
pickle.dump(pipe, open(ppfilename, 'wb'))
status, msg = save_csv_compressed(dataFrame,profiled_data_file)
if not status:
log.info('CSV File Error: ' + str(msg))
if selector_status:
log.info("\\n================== Feature Selector has started ==================")
log.info("Status:-|... AION feature engineering started")
fs_mlstart = time.time()
selectorJson = config_obj.getEionSelectorConfiguration()
if self.textFeatures:
config_obj.updateFeatureSelection(selectorJson, codeConfigure, self.textFeatures)
log.info("-------> For vectorizer 'feature selection' is disabled and all the features will be used for training")
from feature_engineering.featureSelector import featureSelector
selectorObj = featureSelector()
dataFrame,targetColumn,self.topFeatures,self.modelSelTopFeatures,self.allFeatures,self.targetType,self.similarGroups,numericContinuousFeatures,discreteFeatures,nonNumericFeatures,categoricalFeatures,pcaModel,bpca_features,apca_features,featureEngineeringSelector = selectorObj.startSelector(dataFrame, selectorJson,self.textFeatures,targetFeature,problem_type)
if(str(pcaModel) != 'None'):
featureReduction = 'True'
status, msg = save_csv(dataFrame,reduction_data_file)
if not status:
log.info('CSV File Error: ' + str(msg))
pcaFileName = os.path.join(deployLocation,'model','pca'+iterName+'_'+iterVersion+'.sav')
pcaModel_pickle_file = 'pca'+iterName+'_'+iterVersion+'.sav'
pickle.dump(pcaModel, open(pcaFileName, 'wb'))
if not xtest.empty:
xtest = pd.DataFrame(pcaModel.transform(xtest),columns= apca_features)
if targetColumn in self.topFeatures:
self.topFeatures.remove(targetColumn)
fs_mlexecutionTime=time.time() - fs_mlstart
log.info('-------> COMPUTING: Total Feature Selection Execution Time '+str(fs_mlexecutionTime))
log.info('================== Feature Selection completed ==================\\n')
log.info("Status:-|... AION feature engineering completed")
if deeplearner_status or learner_status:
log.info('Status:-|... AION training started')
ldp_mlstart = time.time()
balancingMethod = config_obj.getAIONDataBalancingMethod()
from learner.machinelearning import machinelearning
mlobj = machinelearning()
modelType = problem_type.lower()
targetColumn = targetFeature
if modelType == "na":
if self.targetType == 'categorical':
modelType = 'classification'
elif self.targetType == 'continuous':
modelType = 'regression'
else:
modelType='clustering'
datacolumns=list(dataFrame.columns)
if targetColumn in datacolumns:
datacolumns.remove(targetColumn)
features =datacolumns
featureData = dataFrame[features]
if(modelType == 'clustering') or (modelType == 'topicmodelling'):
xtrain = featureData
ytrain = pd.DataFrame()
xtest = featureData
ytest = pd.DataFrame()
elif (targetColumn!=''):
xtrain = dataFrame[features]
ytrain = dataFrame[targetColumn]
else:
pass
categoryCountList = []
if modelType == 'classification':
if(mlobj.checkForClassBalancing(ytrain) >= 1):
xtrain,ytrain = mlobj.ExecuteClassBalancing(xtrain,ytrain,balancingMethod)
valueCount=targetData.value_counts()
categoryCountList=valueCount.tolist()
ldp_mlexecutionTime=time.time() - ldp_mlstart
log.info('-------> COMPUTING: Total Learner data preparation Execution Time '+str(ldp_mlexecutionTime))
if learner_status:
base_model_score=0
log.info('\\n================== ML Started ==================')
log.info('-------> Memory Usage by DataFrame During Learner Status '+str(dataFrame.memory_usage(deep=True).sum()))
mlstart = time.time()
log.info('-------> Target Problem Type:'+ self.targetType)
learner_type = 'ML'
learnerJson = config_obj.getEionLearnerConfiguration()
from learner.machinelearning import machinelearning
mlobj = machinelearning()
anomalyDetectionStatus = False
anomalyMethod =config_obj.getEionanomalyModels()
if modelType.lower() == "anomalydetection" or modelType.lower() == "timeseriesanomalydetection": #task 11997
anomalyDetectionStatus = True
if anomalyDetectionStatus == True :
datacolumns=list(dataFrame.columns)
if targetColumn in datacolumns:
datacolumns.remove(targetColumn)
if datetimeFeature in datacolumns:
datacolumns.remove(datetimeFeature)
self.features = datacolumns
from learner.anomalyDetector import anomalyDetector
anomalyDetectorObj=anomalyDetector()
model_type ="anomaly_detection"
saved_model = model_type+'_'+iterName+'_'+iterVersion+'.sav'
if problem_type.lower() == "timeseriesanomalydetection": #task 11997
anomalyconfig = config_obj.getAIONTSAnomalyDetectionConfiguration()
modelType = "TimeSeriesAnomalyDetection"
else:
anomalyconfig = config_obj.getAIONAnomalyDetectionConfiguration()
testPercentage = config_obj.getAIONTestTrainPercentage()
##Multivariate feature based anomaly detection status from gui (true/false)
mv_featurebased_selection = config_obj.getMVFeaturebasedAD()
mv_featurebased_ad_status=str(mv_featurebased_selection['uniVariate'])
model,estimator,matrix,trainmatrix,score,labelMaps=anomalyDetectorObj.startanomalydetector(dataFrame,targetColumn,labelMaps,inlierLabels,learnerJson,model_type,saved_model,anomalyMethod,deployLocation,predicted_data_file,testPercentage,anomalyconfig,datetimeFeature,mv_featurebased_ad_status) #Unnati
score = 'NA'
if(self.matrix != '{'):
self.matrix += ','
self.matrix += matrix
if(self.trainmatrix != '{'):
self.trainmatrix += ','
self.trainmatrix += trainmatrix
scoreParam = 'NA'
scoredetails = f'{{"Model":"{model}","Score":"{score}"}}'
if model_tried != '':
model_tried += ','
model_tried += scoredetails
model = anomalyMethod
else:
log.info('-------> Target Problem Type:'+ self.targetType)
log.info('-------> Target Model Type:'+ modelType)
if(modelType == 'regression'):
allowedmatrix = ['mse','r2','rmse','mae']
if(scoreParam.lower() not in allowedmatrix):
scoreParam = 'mse'
if(modelType == 'classification'):
allowedmatrix = ['accuracy','recall','f1_score','precision','roc_auc']
if(scoreParam.lower() not in allowedmatrix):
scoreParam = 'accuracy'
scoreParam = scoreParam.lower()
codeConfigure.update_config('scoring_criteria',scoreParam)
modelParams,modelList = config_obj.getEionLearnerModelParams(modelType)
status,model_type,model,saved_model,matrix,trainmatrix,featureDataShape,model_tried,score,filename,self.features,threshold,pscore,rscore,self.method,loaded_model,xtrain1,ytrain1,xtest1,ytest1,topics,params=mlobj.startLearning(learnerJson,modelType,modelParams,modelList,scoreParam,targetColumn,dataFrame,xtrain,ytrain,xtest,ytest,categoryCountList,self.topFeatures,self.modelSelTopFeatures,self.allFeatures,self.targetType,deployLocation,iterName,iterVersion,trained_data_file,predicted_data_file,labelMaps,'MB',codeConfigure,featureEngineeringSelector,config_obj.getModelEvaluationConfig(),imageFolderLocation)
#Getting model,data for ensemble calculation
e_model=loaded_model
base_model_score=score
if(self.matrix != '{'):
self.matrix += ','
if(self.trainmatrix != '{'):
self.trainmatrix += ','
self.trainmatrix += trainmatrix
self.matrix += matrix
mlexecutionTime=time.time() - mlstart
log.info('-------> Total ML Execution Time '+str(mlexecutionTime))
log.info('================== ML Completed ==================\\n')
if deeplearner_status:
learner_type = 'DL'
log.info('Status:- |... AION DL training started')
from dlearning.deeplearning import deeplearning
dlobj = deeplearning()
from learner.machinelearning import machinelearning
mlobj = machinelearning()
log.info('\\n================== DL Started ==================')
dlstart = time.time()
deeplearnerJson = config_obj.getEionDeepLearnerConfiguration()
targetColumn = targetFeature
method = deeplearnerJson['optimizationMethod']
optimizationHyperParameter = deeplearnerJson['optimizationHyperParameter']
cvSplit = optimizationHyperParameter['trainTestCVSplit']
roundLimit=optimizationHyperParameter['roundLimit']
if 'randomMethod' in optimizationHyperParameter:
randomMethod = optimizationHyperParameter['randomMethod']
else:
randomMethod = 'Quantum'
modelType = problem_type.lower()
modelParams = deeplearnerJson['modelParams']
modelParamsFile=deeplearnerJson['modelparamsfile']
if roundLimit =="":
roundLimit=None
else:
roundLimit=int(roundLimit)
if len(self.modelSelTopFeatures) !=0:
dl_features=self.modelSelTopFeatures
best_feature_model = 'ModelBased'
elif len(self.topFeatures) != 0:
dl_features=self.topFeatures
if featureEngineeringSelector.lower() == 'true':
best_feature_model = 'DimensionalityReduction'
else:
best_feature_model = 'StatisticalBased'
elif len(self.allFeatures) != 0:
dl_features=self.allFeatures
best_feature_model = 'AllFeatures'
else:
datacolumns=list(dataFrame.columns)
datacolumns.remove(targetColumn)
dl_features =datacolumns
best_feature_model = 'AllFeatures'
log.info('-------> Features Used For Modeling: '+(str(dl_features))[:500])
if cvSplit == "":
cvSplit =None
else:
cvSplit =int(cvSplit)
xtrain = xtrain[dl_features]
xtest = xtest[dl_features]
df_test = xtest.copy()
df_test['actual'] = ytest
modelParams,modelList = config_obj.getEionDeepLearnerModelParams(modelType)
if modelType.lower() == 'classification':
scoreParam = dlobj.setScoreParams(scoreParam,modelType)
featureDataShape = xtrain.shape
model_type = 'Classification'
log.info('\\n------ Training DL: Classification ----')
elif modelType.lower() == 'regression':
model_type = "Regression"
if scoreParam == 'None':
scoreParam = None
log.info('\\n------ Training DL: Regression ----')
featureDataShape = xtrain.shape
model_dl,score_dl,best_model_dl,params_dl,X1,XSNN,model_tried_dl,loss_matrix,optimizer,saved_model_dl,filename_dl,dftrain,df_test,performancematrix,trainingperformancematrix = dlobj.startLearning(model_type,modelList, modelParams, scoreParam, cvSplit, xtrain,ytrain,xtest,ytest,method,randomMethod,roundLimit,labelMaps,df_test,deployLocation,iterName,iterVersion,best_feature_model)
if model_tried != '':
model_tried += ','
model_tried += model_tried_dl
bestDL = True
if learner_status:
if score_dl <= score:
bestDL = False
log.info("\\n----------- Machine Learning is Good ---")
log.info("-------> Model: "+str(model) +" Score | ||
: "+str(score))
log.info("---------------------------------------\\n")
else:
os.remove(filename)
os.remove(predicted_data_file)
log.info("\\n------------ Deep Learning is Good---")
log.info("-------> Model: "+str(model_dl)+" Score: "+str(score_dl))
log.info("---------------------------------------\\n")
if bestDL:
model = model_dl
score = score_dl
best_model = best_model_dl
params = params_dl
filename = filename_dl
status, msg = save_csv(df_test,predicted_data_file)
if not status:
log.info('CSV File Error: ' + str(msg))
saved_model = saved_model_dl
self.matrix = '{'+performancematrix
self.trainmatrix = '{'+trainingperformancematrix
self.features = dl_features
else:
learner_type = 'ML'
shutil.rmtree(filename_dl)
dlexecutionTime=time.time() - dlstart
log.info('-------> DL Execution Time '+str(dlexecutionTime))
log.info('Status:- |... AION DL training completed')
log.info('================== Deep Completed ==================\\n')
if deeplearner_status or learner_status:
log.info('Status:-|... AION training completed')
if stateTransitionStatus:
log.info('Status:-|... AION State Transition start')
learner_type = modelType = model_type = 'StateTransition'
model = 'MarkovClustering'
scoreParam = 'NA'
score = 0
from state_transition.pattern import pattern
patternobj = pattern(modelFeatures,targetFeature)
model_tried,probabilityfile,clusteringfile = patternobj.training(dataFrame,outputLocation)
deploy_status = False
visualizationstatus = False
log.info('Status:-|... AION State Transition completed')
if associationRuleStatus:
log.info('\\n================== Association Rule Started ==================')
log.info('Status:-|... AION Association Rule start')
learner_type = 'AR'
modelType = 'Association Rule'
model = 'apriori'
scoreParam = 'NA'
score = 'NA'
model_type = modelType
associationRuleJson = config_obj.getEionAssociationRuleConfiguration()
modelparams,modelList = config_obj.getEionAssociationRuleModelParams()
invoiceNoFeature,itemFeature = config_obj.getAssociationRuleFeatures()
if model in modelparams:
modelparam = modelparams[model]
log.info('\\n-------- Assciation Rule Start -----')
from association_rules.associationrules import associationrules
associationrulesobj = associationrules(dataFrame,associationRuleJson,modelparam,invoiceNoFeature,itemFeature)
model_tried = associationrulesobj.apply_associationRules(outputLocation)
log.info('-------- Association Rule End -----\\n')
log.info('<--------Association Rule Completed----->')
log.info('Status:-|... AION Association Rule completed')
deploy_status = False
if textSimilarityStatus:
log.info('================ Text Similarity Started ====================')
log.info('Status:-|... AION Text Similarity started')
learner_type = 'Text Similarity'
model_type = 'Text Similarity'
scoreParam = 'Accuracy'
modelType = model_type
firstDocFeature = config_obj.getFirstDocumentFeature()
secondDocFeature = config_obj.getSecondDocumentFeature()
textSimilarityCongig = config_obj.getEionTextSimilarityConfig()
testPercentage = config_obj.getAIONTestTrainPercentage() #Unnati
from recommender.text_similarity import eion_similarity_siamese
objTextSimilarity = eion_similarity_siamese()
model,score,matrix,trainmatrix,modeltried,saved_model,filename,padding_length,threshold = objTextSimilarity.siamese_model(dataFrame,firstDocFeature,secondDocFeature,targetFeature,textSimilarityCongig,pipe,deployLocation,iterName,iterVersion,testPercentage,predicted_data_file)
if(self.matrix != '{'):
self.matrix += ','
self.matrix += matrix
if model_tried != '':
model_tried += ','
model_tried += modeltried
if(self.trainmatrix != '{'):
self.trainmatrix += ','
self.trainmatrix += trainmatrix
log.info('Status:-|... AION Text Similarity completed')
log.info('================ Text Similarity Started End====================')
if timeseriesStatus:
log.info('================ Time Series Forecasting Started ====================') #task 11997
log.info('Status:-|... AION TimeSeries Forecasting started') #task 11997
modelType = 'TimeSeriesForecasting' #task 11997
model_type = 'TimeSeriesForecasting' #task 11997
learner_type = 'TS'
modelName='ARIMA'
numericContinuousFeatures = targetFeature.split(",")
profilerJson = config_obj.getEionTimeSeriesConfiguration()
modelParams,modelList = config_obj.getEionTimeSeriesModelParams()
modelName = modelList
testPercentage = config_obj.getAIONTestTrainPercentage() #Unnati
from time_series.timeseries import timeseries
allowedmatrix = ['mse','r2','rmse','mae']
if(scoreParam.lower() not in allowedmatrix):
scoreParam = 'rmse'
objTS = timeseries(profilerJson,modelParams,modelList,dataFrame,targetFeature,datetimeFeature,modelName,testPercentage,iterName,iterVersion,deployLocation,scoreParam)
modelName,model,scoreParam,score,best_model,sfeatures,errormatrix,model_tried,dictDiffCount,pred_freq,additional_regressors,filename,saved_model,lag_order,scalertransformationFile = objTS.timeseries_learning(trained_data_file,predicted_data_file,deployLocation)
xtrain = dataFrame
self.matrix += errormatrix
log.info("Best model to deploy: \\n"+str(model))
## Below part is for var,arima,fbprophet
try:
with open(filename, 'rb') as f:
loaded_model = pickle.load(f)
f.close()
except:
loaded_model=best_model
pass
df_l=len(dataFrame)
pred_threshold=0.1
max_pred_by_user= round((df_l)*pred_threshold)
#prediction for 24 steps or next 24 hours
if noofforecasts == -1:
noofforecasts = max_pred_by_user
no_of_prediction=noofforecasts
if (no_of_prediction > max_pred_by_user):
log.info("-------> Forecast beyond the threshold.So, Reset to Maximum:" +str(max_pred_by_user))
no_of_prediction=max_pred_by_user
noofforecasts = no_of_prediction
log.info("-------> Number of Forecast Records: "+str(no_of_prediction))
log.info("\\n------ Forecast Prediction Start -------------")
if(model.lower() == 'var'):
sfeatures.remove(datetimeFeature)
self.features = sfeatures
originalPredictions=objTS.var_prediction(no_of_prediction)
log.info("-------> Predictions")
log.info(originalPredictions)
predictions=originalPredictions
forecast_output = predictions.to_json(orient='records')
else:
if (model.lower() == 'fbprophet'):
self.features = sfeatures
if not pred_freq:
sessonal_freq = 'H'
else:
sessonal_freq=pred_freq
ts_prophet_future = best_model.make_future_dataframe(periods=no_of_prediction,freq=sessonal_freq,include_history = False)
#If additional regressor given by user.
if (additional_regressors):
log.info("------->Prophet additional regressor given by user: "+str(additional_regressors))
ts_prophet_future[additional_regressors] = dataFrame[additional_regressors]
ts_prophet_future.reset_index(drop=True)
ts_prophet_future=ts_prophet_future.dropna()
else:
pass
train_forecast = best_model.predict(ts_prophet_future)
train_forecast = train_forecast.round(2)
prophet_forecast_tail=train_forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']]
prophet_forecast_tail['ds'] = prophet_forecast_tail['ds'].dt.strftime('%Y-%m-%d %H:%i:%s')
log.info("------->Prophet Predictions")
log.info(prophet_forecast_tail)
forecast_output = prophet_forecast_tail.to_json(orient='records')
elif (model.lower() == 'arima'):
predictions = loaded_model.predict(n_periods=no_of_prediction)
predictions = predictions.round(2)
self.features = sfeatures
col = targetFeature.split(",")
pred = pd.DataFrame(predictions,columns=col)
predictionsdf = pred
log.info("-------> Predictions")
log.info(predictionsdf)
forecast_output = predictionsdf.to_json(orient='records')
elif (model.lower() == 'encoder_decoder_lstm_mvi_uvo'):
log.info(datetimeFeature)
log.info(sfeatures)
self.features = sfeatures
if len(sfeatures) == 1:
xt = xtrain[self.features].values
else:
xt = xtrain[self.features].values
with open(scalertransformationFile, 'rb') as f:
loaded_scaler_model = pickle.load(f)
f.close()
xt = xt.astype('float32')
xt = loaded_scaler_model.transform(xt)
pred_data = xt
y_future = []
featuerlen = len(sfeatures)
targetColIndx = (xtrain.columns.get_loc(targetFeature))
#in case of lstm multivariate input and univariate out prediction only one sequence can be predicted
#consider the last xtrain window as input sequence
pdata = pred_data[-lag_order:]
pdata = pdata.reshape((1,lag_order, featuerlen))
pred = loaded_model.predict(pdata)
pred_1d = pred.ravel()
#pred_1d = pred_1d.reshape(len(pred_1d),1)
pdata_2d = pdata.ravel().reshape(len(pdata) * lag_order, featuerlen)
pdata_2d[:,targetColIndx] = pred_1d
pred_2d_inv = loaded_scaler_model.inverse_transform(pdata_2d)
predout = pred_2d_inv[:, targetColIndx]
predout = predout.reshape(len(pred_1d),1)
#y_future.append(predout)
col = targetFeature.split(",")
pred = pd.DataFrame(index=range(0,len(predout)),columns=col)
for i in range(0, len(predout)):
pred.iloc[i] = predout[i]
predictions = pred
log.info("-------> Predictions")
log.info(predictions)
forecast_output = predictions.to_json(orient='records')
elif (model.lower() == 'mlp' or model.lower() == 'lstm'):
sfeatures.remove(datetimeFeature)
self.features = sfeatures
if len(sfeatures) == 1:
xt = xtrain[self.features].values
else:
xt = xtrain[self.features].values
with open(scalertransformationFile, 'rb') as f:
loaded_scaler_model = pickle.load(f)
f.close()
xt = xt.astype('float32')
xt = loaded_scaler_model.transform(xt)
pred_data = xt
y_future = []
for i in range(no_of_prediction):
pdata = pred_data[-lag_order:]
if model.lower() == 'mlp':
pdata = pdata.reshape((1,lag_order))
else:
pdata = pdata.reshape((1,lag_order, len(sfeatures)))
if (len(sfeatures) > 1):
pred = loaded_model.predict(pdata)
predout = loaded_scaler_model.inverse_transform(pred)
y_future.append(predout)
pred_data=np.append(pred_data,pred,axis=0)
else:
pred = loaded_model.predict(pdata)
predout = loaded_scaler_model.inverse_transform(pred)
y_future.append(predout.flatten()[-1])
pred_data = np.append(pred_data,pred)
col = targetFeature.split(",")
pred = pd.DataFrame(index=range(0,len(y_future)),columns=col)
for i in range(0, len(y_future)):
pred.iloc[i] = y_future[i]
predictions = pred
log.info("-------> Predictions")
log.info(predictions)
forecast_output = predictions.to_json(orient='records')
else:
pass
log.info('Status:-|... AION TimeSeries Forecasting completed') #task 11997
log.info("------ Forecast Prediction End -------------\\n")
log.info('================ Time Series Forecasting Completed ================\\n') #task 11997
if recommenderStatus:
log.info('\\n================ Recommender Started ================ ')
log.info('Status:-|... AION Recommender started')
learner_type = 'RecommenderSystem'
model_type = 'RecommenderSystem'
modelType = model_type
model = model_type
targetColumn=''
datacolumns=list(dataFrame.columns)
self.features=datacolumns
svd_params = config_obj.getEionRecommenderConfiguration()
from recommender.item_rating import recommendersystem
recommendersystemObj = recommendersystem(modelFeatures,svd_params)
testPercentage = config_obj.getAION | ||
TestTrainPercentage() #Unnati
saved_model,rmatrix,score,trainingperformancematrix,model_tried = recommendersystemObj.recommender_model(dataFrame,outputLocation)
scoreParam = 'NA' #Task 11190
log.info('Status:-|... AION Recommender completed')
log.info('================ Recommender Completed ================\\n')
if textsummarizationStatus:
log.info('\\n================ text Summarization Started ================ ')
log.info('Status:-|... AION text Summarization started')
modelType = 'textsummarization'
model_type = 'textsummarization'
learner_type = 'Text Summarization'
modelName='TextSummarization'
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from scipy import spatial
model = model_type
dataLocationTS,deployLocationTS,KeyWordsTS,pathForKeywordFileTS = config_obj.getEionTextSummarizationConfig()
#print("dataLocationTS",dataLocationTS)
#print("deployLocationTS",deployLocationTS)
#print("KeyWordsTS",KeyWordsTS)
#print("pathForKeywordFileTS",pathForKeywordFileTS)
#PreTrained Model Download starts-------------------------
from appbe.dataPath import DATA_DIR
preTrainedModellocation = Path(DATA_DIR)/'PreTrainedModels'/'TextSummarization'
preTrainedModellocation = Path(DATA_DIR)/'PreTrainedModels'/'TextSummarization'
models = {'glove':{50:'glove.6B.50d.w2vformat.txt'}}
supported_models = [x for y in models.values() for x in y.values()]
modelsPath = Path(DATA_DIR)/'PreTrainedModels'/'TextSummarization'
Path(modelsPath).mkdir(parents=True, exist_ok=True)
p = Path(modelsPath).glob('**/*')
modelsDownloaded = [x.name for x in p if x.name in supported_models]
selected_model="glove.6B.50d.w2vformat.txt"
if selected_model not in modelsDownloaded:
print("Model not in folder, downloading")
import urllib.request
location = Path(modelsPath)
local_file_path = location/f"glove.6B.50d.w2vformat.txt"
urllib.request.urlretrieve(f'https://aion-pretrained-models.s3.ap-south-1.amazonaws.com/text/glove.6B.50d.w2vformat.txt', local_file_path)
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
tokenizer = AutoTokenizer.from_pretrained("sshleifer/distilbart-cnn-12-6")
model = AutoModelForSeq2SeqLM.from_pretrained("sshleifer/distilbart-cnn-12-6")
tokenizer.save_pretrained(preTrainedModellocation)
model.save_pretrained(preTrainedModellocation)
#PreTrained Model Download ends-----------------------
deployLocationData=deployLocation+"\\\\data\\\\"
modelLocation=Path(DATA_DIR)/'PreTrainedModels'/'TextSummarization'/'glove.6B.50d.w2vformat.txt'
KeyWordsTS=KeyWordsTS.replace(",", " ")
noOfKeyword = len(KeyWordsTS.split())
keywords = KeyWordsTS.split()
embeddings = {}
word = ''
with open(modelLocation, 'r', encoding="utf8") as f:
header = f.readline()
header = header.split(' ')
vocab_size = int(header[0])
embed_size = int(header[1])
for i in range(vocab_size):
data = f.readline().strip().split(' ')
word = data[0]
embeddings[word] = [float(x) for x in data[1:]]
readData=pd.read_csv(pathForKeywordFileTS,encoding='utf-8',encoding_errors= 'replace')
for i in range(noOfKeyword):
terms=(sorted(embeddings.keys(), key=lambda word: spatial.distance.euclidean(embeddings[word], embeddings[keywords[i]])) )[1:6]
readData = readData.append({'Keyword': keywords[i]}, ignore_index=True)
for j in range(len(terms)):
readData = readData.append({'Keyword': terms[j]}, ignore_index=True)
deployLocationDataKwDbFile=deployLocationData+"keywordDataBase.csv"
readData.to_csv(deployLocationDataKwDbFile,encoding='utf-8',index=False)
datalocation_path=dataLocationTS
path=Path(datalocation_path)
fileList=os.listdir(path)
textExtraction = pd.DataFrame()
textExtraction['Sentences']=""
rowIndex=0
for i in range(len(fileList)):
fileName=str(datalocation_path)+"\\\\"+str(fileList[i])
if fileName.endswith(".pdf"):
print("\\n files ",fileList[i])
from pypdf import PdfReader
reader = PdfReader(fileName)
number_of_pages = len(reader.pages)
text=""
textOutputForFile=""
OrgTextOutputForFile=""
for i in range(number_of_pages) :
page = reader.pages[i]
text1 = page.extract_text()
text=text+text1
import nltk
tokens = nltk.sent_tokenize(text)
for sentence in tokens:
sentence=sentence.replace("\\n", " ")
if (len(sentence.split()) < 4 ) or (len(str(sentence.split(',')).split()) < 8)or (any(chr.isdigit() for chr in sentence)) :
continue
textExtraction.at[rowIndex,'Sentences']=str(sentence.strip())
rowIndex=rowIndex+1
if fileName.endswith(".txt"):
print("\\n txt files",fileList[i])
data=[]
with open(fileName, "r",encoding="utf-8") as f:
data.append(f.read())
str1 = ""
for ele in data:
str1 += ele
sentences=str1.split(".")
count=0
for sentence in sentences:
count += 1
textExtraction.at[rowIndex+i,'Sentences']=str(sentence.strip())
rowIndex=rowIndex+1
df=textExtraction
#print("textExtraction",textExtraction)
deployLocationDataPreProcessData=deployLocationData+"preprocesseddata.csv"
save_csv_compressed(deployLocationDataPreProcessData, df, encoding='utf-8')
df['Label']=0
kw=pd.read_csv(deployLocationDataKwDbFile,encoding='utf-8',encoding_errors= 'replace')
Keyword_list = kw['Keyword'].tolist()
for i in df.index:
for x in Keyword_list:
if (str(df["Sentences"][i])).find(x) != -1:
df['Label'][i]=1
break
deployLocationDataPostProcessData=deployLocationData+"postprocesseddata.csv"
#df.to_csv(deployLocationDataPostProcessData,encoding='utf-8')
save_csv_compressed(deployLocationDataPostProcessData, df, encoding='utf-8')
labelledData=df
train_df=labelledData
labelencoder = LabelEncoder()
train_df['Sentences'] = labelencoder.fit_transform(train_df['Sentences'])
X = train_df.drop('Label',axis=1)
y = train_df['Label']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
Classifier = RandomForestClassifier(n_estimators = 10, random_state = 42)
modelTs=Classifier.fit(X, y)
import pickle
deployLocationTS=deployLocation+"\\\\model\\\\"+iterName+'_'+iterVersion+'.sav'
deployLocationTS2=deployLocation+"\\\\model\\\\"+"classificationModel.sav"
pickle.dump(modelTs, open(deployLocationTS, 'wb'))
pickle.dump(modelTs, open(deployLocationTS2, 'wb'))
print("\\n trainModel Ends")
saved_model = 'textsummarization_'+iterName+'_'+iterVersion
log.info('Status:-|... AION text summarization completed')
model = learner_type
log.info('================ text summarization Completed ================\\n')
if survival_analysis_status:
sa_method = config_obj.getEionanomalyModels()
labeldict = {}
log.info('\\n================ SurvivalAnalysis Started ================ ')
log.info('Status:-|... AION SurvivalAnalysis started')
log.info('\\n================ SurvivalAnalysis DataFrame ================ ')
log.info(dataFrame)
from survival import survival_analysis
from learner.machinelearning import machinelearning
sa_obj = survival_analysis.SurvivalAnalysis(dataFrame, preprocess_pipe, sa_method, targetFeature, datetimeFeature, filter_expression, profilerObj.train_features_type)
if sa_obj != None:
predict_json = sa_obj.learn()
if sa_method.lower() in ['kaplanmeierfitter','kaplanmeier','kaplan-meier','kaplan meier','kaplan','km','kmf']:
predicted = sa_obj.models[0].predict(dataFrame[datetimeFeature])
status, msg = save_csv(predicted,predicted_data_file)
if not status:
log.info('CSV File Error: ' + str(msg))
self.features = [datetimeFeature]
elif sa_method.lower() in ['coxphfitter','coxregression','cox-regression','cox regression','coxproportionalhazard','coxph','cox','cph']:
predicted = sa_obj.models[0].predict_cumulative_hazard(dataFrame)
datacolumns = list(dataFrame.columns)
targetColumn = targetFeature
if targetColumn in datacolumns:
datacolumns.remove(targetColumn)
self.features = datacolumns
score = sa_obj.score
scoreParam = 'Concordance_Index'
status,msg = save_csv(predicted,predicted_data_file)
if not status:
log.info('CSV File Error: ' + str(msg))
model = sa_method
modelType = "SurvivalAnalysis"
model_type = "SurvivalAnalysis"
modelName = sa_method
i = 1
for mdl in sa_obj.models:
saved_model = "%s_%s_%s_%d.sav"%(model_type,sa_method,iterVersion,i)
pickle.dump(mdl, open(os.path.join(deployLocation,'model',saved_model), 'wb')),
i+=1
p = 1
for plot in sa_obj.plots:
img_name = "%s_%d.png"%(sa_method,p)
img_location = os.path.join(imageFolderLocation,img_name)
plot.savefig(img_location,bbox_inches='tight')
sa_images.append(img_location)
p+=1
log.info('Status:-|... AION SurvivalAnalysis completed')
log.info('\\n================ SurvivalAnalysis Completed ================ ')
if visualizationstatus:
visualizationJson = config_obj.getEionVisualizationConfiguration()
log.info('\\n================== Visualization Recommendation Started ==================')
visualizer_mlstart = time.time()
from visualization.visualization import Visualization
visualizationObj = Visualization(iterName,iterVersion,dataFrame,visualizationJson,datetimeFeature,deployLocation,dataFolderLocation,numericContinuousFeatures,discreteFeatures,categoricalFeatures,self.features,targetFeature,model_type,original_data_file,profiled_data_file,trained_data_file,predicted_data_file,labelMaps,self.vectorizerFeatures,self.textFeatures,self.numericalFeatures,self.nonNumericFeatures,self.emptyFeatures,self.dfrows,self.dfcols,saved_model,scoreParam,learner_type,model,featureReduction,reduction_data_file)
visualizationObj.visualizationrecommandsystem()
visualizer_mlexecutionTime=time.time() - visualizer_mlstart
log.info('-------> COMPUTING: Total Visualizer Execution Time '+str(visualizer_mlexecutionTime))
log.info('================== Visualization Recommendation Started ==================\\n')
if similarityIdentificationStatus or contextualSearchStatus:
datacolumns=list(dataFrame.columns)
features = modelFeatures.split(",")
if indexFeature != '' and indexFeature != 'NA':
iFeature = indexFeature.split(",")
for ifea in iFeature:
if ifea not in features:
features.append(ifea)
for x in features:
dataFrame[x] = similaritydf[x]
#get vectordb(chromadb) status selected
if similarityIdentificationStatus:
learner_type = 'similarityIdentification'
else:
learner_type = 'contextualSearch'
vecDBCosSearchStatus = config_obj.getVectorDBCosSearchStatus(learner_type)
if vecDBCosSearchStatus:
status, msg = save_chromadb(dataFrame, config_obj, trained_data_file, modelFeatures)
if not status:
log.info('Vector DB File Error: '+str(msg))
else:
status, msg = save_csv(dataFrame,trained_data_file)
if not status:
log.info('CSV File Error: '+str(msg))
self.features = datacolumns
model_type = config_obj.getAlgoName(problem_type)
model = model_type #bug 12833
model_tried = '{"Model":"'+model_type+'","FeatureEngineering":"NA","Score":"NA","ModelUncertainty":"NA"}'
modelType = learner_type
saved_model = learner_type
score = 'NA'
if deploy_status:
if str(model) != 'None':
log.info('\\n================== Deployment Started ==================')
log.info('Status:-|... AION Creating Prediction Service Start')
deployer_mlstart = time.time()
deployJson = config_obj.getEionDeployerConfiguration()
deploy_name = iterName+'_'+iterVersion
from prediction_package.model_deploy import DeploymentManager
if textsummarizationStatus :
deploy = DeploymentManager()
deploy.deployTSum(deployLocation,preTrainedModellocation)
codeConfigure.save_config(deployLocation | ||
)
deployer_mlexecutionTime=time.time() - deployer_mlstart
log.info('-------> COMPUTING: Total Deployer Execution Time '+str(deployer_mlexecutionTime))
log.info('Status:-|... AION Deployer completed')
log.info('================== Deployment Completed ==================')
else:
deploy = DeploymentManager()
deploy.deploy_model(deploy_name,deployJson,learner_type,model_type,model,scoreParam,saved_model,deployLocation,self.features,self.profilerAction,dataLocation,labelMaps,column_merge_flag,self.textFeatures,self.numericalFeatures,self.nonNumericFeatures,preprocessing_pipe,numericToLabel_json,threshold,loss_matrix,optimizer,firstDocFeature,secondDocFeature,padding_length,trained_data_file,dictDiffCount,targetFeature,normalizer_pickle_file,normFeatures,pcaModel_pickle_file,bpca_features,apca_features,self.method,deployFolder,iterName,iterVersion,self.wordToNumericFeatures,imageconfig,sessonal_freq,additional_regressors,grouperbyjson,rowfilterexpression,xtrain,profiled_data_file,conversion_method,modelFeatures,indexFeature,lag_order,scalertransformationFile,noofforecasts,preprocess_pipe,preprocess_out_columns, label_encoder,datetimeFeature,usecaseLocation,deploy_config)
codeConfigure.update_config('deploy_path',os.path.join(deployLocation,'publish'))
codeConfigure.save_config(deployLocation)
deployer_mlexecutionTime=time.time() - deployer_mlstart
log.info('-------> COMPUTING: Total Deployer Execution Time '+str(deployer_mlexecutionTime))
log.info('Status:-|... AION Creating Prediction Service completed')
log.info('================== Deployment Completed ==================')
if not outputDriftStatus and not inputDriftStatus:
from transformations.dataProfiler import set_features
self.features = set_features(self.features,profilerObj)
self.matrix += '}'
self.trainmatrix += '}'
print(model_tried)
model_tried = eval('['+model_tried+']')
matrix = eval(self.matrix)
trainmatrix = eval(self.trainmatrix)
deployPath = deployLocation.replace(os.sep, '/')
if survival_analysis_status:
output_json = {"status":"SUCCESS","data":{"ModelType":modelType,"deployLocation":deployPath,"BestModel":model,"BestScore":str(score),"ScoreType":str(scoreParam).upper(),"matrix":matrix,"survivalProbability":json.loads(predict_json),"featuresused":str(self.features),"targetFeature":str(targetColumn),"EvaluatedModels":model_tried,"imageLocation":str(sa_images),"LogFile":logFileName}}
elif not timeseriesStatus:
try:
json.dumps(params)
output_json = {"status":"SUCCESS","data":{"ModelType":modelType,"deployLocation":deployPath,"BestModel":model,"BestScore":str(score),"ScoreType":str(scoreParam).upper(),"matrix":matrix,"trainmatrix":trainmatrix,"featuresused":str(self.features),"targetFeature":str(targetColumn),"params":params,"EvaluatedModels":model_tried,"LogFile":logFileName}}
except:
output_json = {"status":"SUCCESS","data":{"ModelType":modelType,"deployLocation":deployPath,"BestModel":model,"BestScore":str(score),"ScoreType":str(scoreParam).upper(),"matrix":matrix,"trainmatrix":trainmatrix,"featuresused":str(self.features),"targetFeature":str(targetColumn),"params":"","EvaluatedModels":model_tried,"LogFile":logFileName}}
else:
if config_obj.summarize:
modelType = 'Summarization'
output_json = {"status":"SUCCESS","data":{"ModelType":modelType,"deployLocation":deployPath,"BestModel":model,"BestScore":str(score),"ScoreType":str(scoreParam).upper(),"matrix":matrix,"featuresused":str(self.features),"targetFeature":str(targetColumn),"EvaluatedModels":model_tried,'forecasts':json.loads(forecast_output),"LogFile":logFileName}}
if bool(topics) == True:
output_json['topics'] = topics
with open(outputjsonFile, 'w',encoding='utf-8') as f:
json.dump(output_json, f)
f.close()
output_json = json.dumps(output_json)
log.info('\\n------------- Summary ------------')
log.info('------->No of rows & columns in data:('+str(self.dfrows)+','+str(self.dfcols)+')')
log.info('------->No of missing Features :'+str(len(self.mFeatures)))
log.info('------->Missing Features:'+str(self.mFeatures))
log.info('------->Text Features:'+str(self.textFeatures))
log.info('------->No of Nonnumeric Features :'+str(len(self.nonNumericFeatures)))
log.info('------->Non-Numeric Features :' +str(self.nonNumericFeatures))
if threshold == -1:
log.info('------->Threshold: NA')
else:
log.info('------->Threshold: '+str(threshold))
log.info('------->Label Maps of Target Feature for classification :'+str(labelMaps))
for i in range(0,len(self.similarGroups)):
log.info('------->Similar Groups '+str(i+1)+' '+str(self.similarGroups[i]))
if((learner_type != 'TS') & (learner_type != 'AR')):
log.info('------->No of columns and rows used for Modeling :'+str(featureDataShape))
log.info('------->Features Used for Modeling:'+str(self.features))
log.info('------->Target Feature: '+str(targetColumn))
log.info('------->Best Model Score :'+str(score))
log.info('------->Best Parameters:'+str(params))
log.info('------->Type of Model :'+str(modelType))
log.info('------->Best Model :'+str(model))
log.info('------------- Summary ------------\\n')
log.info('Status:-|... AION Model Training Successfully Done')
except Exception as inst:
log.info('server code execution failed !....'+str(inst))
log.error(inst, exc_info = True)
output_json = {"status":"FAIL","message":str(inst).strip('"'),"LogFile":logFileName}
output_json = json.dumps(output_json)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
executionTime = timeit.default_timer() - startTime
log.info('\\nTotal execution time(sec) :'+str(executionTime))
log.info('\\n------------- Output JSON ------------')
log.info('aion_learner_status:'+str(output_json))
log.info('------------- Output JSON ------------\\n')
for hdlr in log.handlers[:]: # remove the existing file handlers
if isinstance(hdlr,logging.FileHandler):
hdlr.close()
log.removeHandler(hdlr)
return output_json
def split_into_train_test_data(self,featureData,targetData,testPercentage,log,modelType='classification'): #Unnati
log.info('\\n-------------- Test Train Split ----------------')
if testPercentage == 0 or testPercentage == 100: #Unnati
xtrain=featureData
ytrain=targetData
xtest=pd.DataFrame()
ytest=pd.DataFrame()
else:
testSize= testPercentage/100 #Unnati
if modelType == 'regression':
log.info('-------> Split Type: Random Split')
xtrain,xtest,ytrain,ytest=train_test_split(featureData,targetData,test_size=testSize,shuffle=True,random_state=42)
else:
try:
log.info('-------> Split Type: Stratify Split')
xtrain,xtest,ytrain,ytest=train_test_split(featureData,targetData,stratify=targetData,test_size=testSize,random_state=42)
except Exception as ValueError:
count_unique = targetData.value_counts()
feature_with_single_count = count_unique[ count_unique == 1].index.tolist()
error = f"The least populated class in {feature_with_single_count} has only 1 member, which is too few. The minimum number of groups for any class cannot be less than 2"
raise Exception(error) from ValueError
except:
log.info('-------> Split Type: Random Split')
xtrain,xtest,ytrain,ytest=train_test_split(featureData,targetData,test_size=testSize,shuffle=True,random_state=42)
log.info('Status:- !... Train / test split done: '+str(100-testPercentage)+'% train,'+str(testPercentage)+'% test') #Unnati
log.info('-------> Train Data Shape: '+str(xtrain.shape)+' ---------->')
log.info('-------> Test Data Shape: '+str(xtest.shape)+' ---------->')
log.info('-------------- Test Train Split End ----------------\\n')
return(xtrain,ytrain,xtest,ytest)
def aion_train_model(arg):
warnings.filterwarnings('ignore')
config_path = Path( arg)
with open( config_path, 'r') as f:
config = json.load( f)
log = set_log_handler(config['basic'])
log.info('************* Version - v'+AION_VERSION+' *************** \\n')
msg = '-------> Execution Start Time: '+ datetime.datetime.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S' + ' IST')
log.info(msg)
try:
config_validate(arg)
valid, msg = pushRecordForTraining()
if valid:
serverObj = server()
configObj = AionConfigManager()
codeConfigure = code_configure()
codeConfigure.create_config(config)
readConfistatus,msg = configObj.readConfigurationFile(config)
if(readConfistatus == False):
raise ValueError( msg)
output = serverObj.startScriptExecution(configObj, codeConfigure, log)
else:
output = {"status":"LicenseVerificationFailed","message":str(msg).strip('"')}
output = json.dumps(output)
print( f"\\naion_learner_status:{output}\\n")
log.info( f"\\naion_learner_status:{output}\\n")
except Exception as inst:
output = {"status":"FAIL","message":str(inst).strip('"')}
output = json.dumps(output)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
print(f"\\naion_learner_status:{output}\\n")
log.info( f"\\naion_learner_status:{output}\\n")
return output
if __name__ == "__main__":
aion_train_model( sys.argv[1])
<s>
'''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import time
import os
import sys
import numpy as np
from sklearn.metrics import confusion_matrix
from sklearn.metrics import recall_score
from sklearn.metrics import precision_score
from sklearn.preprocessing import binarize
from learner.optimizetechnique import OptimizationTq
from learner.parameters import parametersDefine
import logging
from learner.aion_matrix import aion_matrix
# apply threshold to positive probabilities to create labels
def to_labels(pos_probs, threshold):
return (pos_probs >= threshold).astype('int')
class incClassifierModel():
def __init__(self,noOfClasses,modelList,params,scoreParam,cvSplit,numIter,geneticParam,trainX,trainY,testX,testY,method,modelType,MakeFP0,MakeFN0,deployLocation):
self.noOfClasses = noOfClasses
self.modelList =modelList
self.params =params
self.trainX =trainX
self.X =trainX
self.trainY =trainY
self.testX = testX
self.testY = testY
self.method =method
self.scoreParam=scoreParam
self.cvSplit=cvSplit
self.numIter=numIter
self.geneticParam=geneticParam
self.MakeFP0= MakeFP0
self.MakeFN0=MakeFN0
self.log = logging.getLogger('eion')
self.modelType = modelType
self.deployLocation = deployLocation
self.isRiverModel = False
self.AlgorithmNames={'Online Logistic Regression':'Online Logistic Regression', 'Online Softmax Regression':'Online Softmax Regression', 'Online Decision Tree Classifier':'Online Decision Tree Classifier', 'Online KNN Classifier':'Online KNN Classifier'}
self.modelToAlgoNames = {value: key for key, value in self.AlgorithmNames.items()}
def check_threshold(self,estimator,testX,testY,threshold_range,checkParameter,modelName):
thresholdx = -1
for threshold in threshold_range:
predictedData = estimator.predict_proba(testX)
predictedData = binarize(predictedData[:,1].reshape(-1, 1),threshold=threshold)#bug 12437
p_score = precision_score(testY, predictedData)
r_score = recall_score(testY, predictedData)
tn, fp, fn, tp = confusion_matrix(testY, predictedData).ravel()
if(checkParameter.lower() == 'fp'):
if fp == 0:
if(p_score == 1):
thresholdx = threshold
self.log.info('---------------> Best Threshold:'+str(threshold))
self.log.info('---------------> Best Precision:'+str(p_score))
self.log. | ||
info('---------------> Best Recall:'+str(r_score))
self.log.info('---------------> TN:'+str(tn))
self.log.info('---------------> FP:'+str(fp))
self.log.info('---------------> FN:'+str(fn))
self.log.info('---------------> TP:'+str(tp))
break
if(checkParameter.lower() == 'fn'):
if fn == 0:
if(r_score == 1):
thresholdx = threshold
self.log.info('---------------> Best Threshold:'+str(threshold))
self.log.info('---------------> Best Precision:'+str(p_score))
self.log.info('---------------> Best Recall:'+str(r_score))
self.log.info('---------------> TN:'+str(tn))
self.log.info('---------------> FP:'+str(fp))
self.log.info('---------------> FN:'+str(fn))
self.log.info('---------------> TP:'+str(tp))
break
return(thresholdx,p_score,r_score)
def getBestModel(self,fp0,fn0,threshold,bestthreshold,rscore,brscore,pscore,bpscore,tscore,btscore):
cmodel = False
if(threshold != -1):
if(bestthreshold == -1):
cmodel = True
bestthreshold = threshold
brscore = rscore
bpscore = pscore
btscore = tscore
elif fp0:
if rscore > brscore:
cmodel = True
bestthreshold = threshold
brscore = rscore
bpscore = pscore
btscore = tscore
elif rscore == brscore:
if tscore > btscore or btscore == -0xFFFF:
cmodel = True
bestthreshold = threshold
brscore = rscore
bpscore = pscore
btscore = tscore
elif fn0:
if pscore > bpscore:
cmodel = True
bestthreshold = threshold
brscore = rscore
bpscore = pscore
btscore = tscore
elif pscore == bpscore:
if tscore > btscore or btscore == -0xFFFF:
cmodel = True
bestthreshold = threshold
brscore = rscore
bpscore = pscore
btscore = tscore
else:
if tscore > btscore or btscore == -0xFFFF:
cmodel = True
btscore = tscore
else:
if(bestthreshold == -1):
if tscore > btscore or btscore == -0xFFFF:
cmodel = True
btscore = tscore
return cmodel,btscore,bestthreshold,brscore,bpscore
def firstFit(self):
bestModel='None'
bestParams={}
bestScore=-0xFFFF
bestEstimator = 'None'
scoredetails = ''
threshold = -1
bestthreshold = -1
precisionscore =-1
bestprecisionscore=-1
recallscore = -1
bestrecallscore=-1
self.bestTrainPredictedData = None
self.bestPredictedData = None
self.log.info('\\n---------- ClassifierModel has started ----------')
objClf = aion_matrix()
try:
for modelName in self.modelList:
paramSpace=self.params[modelName]
algoName = self.AlgorithmNames[modelName]
from incremental.riverML import riverML
riverMLObj = riverML()
self.log.info("-------> Model Name: "+str(modelName))
start = time.time()
model, modelParams, estimator, trainPredictedData = riverMLObj.startLearn('classification',algoName,paramSpace,self.trainX, self.trainY, self.noOfClasses)
modelParams = str(modelParams)
predictedData = riverMLObj.getPrediction(estimator,self.testX)
executionTime=time.time() - start
self.testY.reset_index(inplace=True, drop=True)
score = objClf.get_score(self.scoreParam,self.testY.values.flatten(),predictedData.values.flatten())
self.log.info(str(score))
metrices = {}
metrices["score"] = score
threshold = -1
precisionscore = precision_score(self.testY, predictedData, average='macro')
recallscore = recall_score(self.testY, predictedData, average='macro')
self.log.info('---------> Total Execution: '+str(executionTime))
if(scoredetails != ''):
scoredetails += ','
scoredetails += '{"Model":"'+self.modelToAlgoNames[model]+'","Score":'+str(score)+'}'
status,bscore,bthres,brscore,bpscore = self.getBestModel(self.MakeFP0,self.MakeFN0,threshold,bestthreshold,recallscore,bestrecallscore,precisionscore,bestprecisionscore,score,bestScore)
if status:
bestScore =bscore
bestModel =model
bestParams=modelParams
bestEstimator=estimator
bestthreshold = threshold
bestrecallscore = recallscore
bestprecisionscore = precisionscore
self.bestTrainPredictedData = trainPredictedData
self.bestPredictedData = predictedData
self.log.info('Status:- |... ML Algorithm applied: '+modelName)
self.log.info("Status:- |... Testing Score: "+str(score))
self.log.info('---------- ClassifierModel End ---------- \\n')
self.log.info('\\n------- Best Model and its parameters -------------')
self.log.info('Status:- |... Best Algorithm selected: '+str(self.modelToAlgoNames[bestModel])+' Score='+str(round(bestScore,2)))
self.log.info("-------> Best Name: "+str(bestModel))
self.log.info("-------> Best Score: "+str(bestScore))
return self.modelToAlgoNames[bestModel],bestParams,bestScore,bestEstimator,scoredetails,bestthreshold,bestprecisionscore,bestrecallscore
except Exception as inst:
self.log.info( '\\n-----> ClassifierModel failed!!!.'+str(inst))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
self.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import warnings
warnings.filterwarnings('ignore')
import logging
import sklearn
from random import sample
from numpy.random import uniform
import numpy as np
import math
import pickle
import os
import json
from math import isnan
from sklearn.preprocessing import binarize
from sklearn.preprocessing import LabelEncoder
import pandas as pd
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from incremental.incClassificationModel import incClassifierModel
from incremental.incRegressionModel import incRegressionModel
class incMachineLearning(object):
def __init__(self,mlobj):
self.features=[]
self.mlobj=mlobj
self.log = logging.getLogger('eion')
def startLearning(self,mlconfig,modelType,modelParams,modelList,scoreParam,features,targetColumn,dataFrame,xtrain,ytrain,xtest,ytest,categoryCountList,targetType,deployLocation,iterName,iterVersion,trained_data_file,predicted_data_file,labelMaps):
model = 'None'
params = 'None'
score = 0xFFFF
estimator = None
model_tried = ''
threshold = -1
pscore = -1
rscore = -1
topics = {}
if(targetColumn != ''):
targetData = dataFrame[targetColumn]
datacolumns=list(dataFrame.columns)
if targetColumn in datacolumns:
datacolumns.remove(targetColumn)
scoreParam = self.mlobj.setScoreParams(scoreParam,modelType,categoryCountList)
self.log.info('\\n-------------- Training ML: Start --------------')
model_type,model,params, score, estimator,model_tried,xtrain,ytrain,xtest,ytest,threshold,pscore,rscore,method,incObj=self.startLearnerModule(mlconfig,modelType,modelParams,modelList,scoreParam,targetColumn,dataFrame,xtrain,ytrain,xtest,ytest,categoryCountList,targetType,deployLocation,iterName,iterVersion,trained_data_file,labelMaps)
self.log.info('-------------- Training ML: End --------------\\n')
filename = os.path.join(deployLocation,'production','model',model+'.pkl')
saved_model = model+'.pkl'
pickle.dump(estimator, open(filename, 'wb'))
df_test = xtest.copy()
df_test.reset_index(inplace = True,drop=True)
trainPredictedData = incObj.bestTrainPredictedData
predictedData = incObj.bestPredictedData
try:
if(model_type == 'Classification'):
self.log.info('\\n--------- Performance Matrix with Train Data ---------')
train_matrix = self.mlobj.getClassificationPerformaceMatrix(ytrain,trainPredictedData,labelMaps)
self.log.info('--------- Performance Matrix with Train Data End ---------\\n')
self.log.info('\\n--------- Performance Matrix with Test Data ---------')
performancematrix = self.mlobj.getClassificationPerformaceMatrix(ytest,predictedData,labelMaps)
ytest.reset_index(inplace=True,drop=True)
df_test['actual'] = ytest
df_test['predict'] = predictedData
self.log.info('--------- Performance Matrix with Test Data End ---------\\n')
matrix = performancematrix
elif(model_type == 'Regression'):
self.log.info('\\n--------- Performance Matrix with Train Data ---------')
train_matrix = self.mlobj.get_regression_matrix(ytrain, trainPredictedData)
self.log.info('--------- Performance Matrix with Train Data End ---------\\n')
self.log.info('\\n--------- Performance Matrix with Test Data ---------')
matrix = self.mlobj.get_regression_matrix(ytest, predictedData)
ytest.reset_index(inplace=True, drop=True)
df_test['actual'] = ytest
df_test['predict'] = predictedData
self.log.info('--------- Performance Matrix with Test Data End ---------\\n')
except Exception as Inst:
self.log.info('--------- Error Performance Matrix ---------\\n')
self.log.info(str(Inst))
df_test['predict'] = predictedData
matrix = ""
train_matrix = ""
self.log.info('--------- Performance Matrix with Test Data End ---------\\n')
df_test.to_csv(predicted_data_file)
return 'Success',model_type,model,saved_model,matrix,train_matrix,xtrain.shape,model_tried,score,filename,self.features,threshold,pscore,rscore,method,estimator,xtrain,ytrain,xtest,ytest,topics,params
def startLearnerModule(self,mlconfig,modelType,modelParams,modelList,scoreParam,targetColumn,dataFrame,xtrain,ytrain,xtest,ytest,categoryCountList,targetType,deployLocation,iterName,iterVersion,trained_data_file,labelMaps):
matrix = ''
threshold = -1
pscore = -1
rscore = -1
datacolumns=list(xtrain.columns)
if targetColumn in datacolumns:
datacolumns.remove(targetColumn)
self.features =datacolumns
self.log.info('-------> Features Used For Training the Model: '+(str(self.features))[:500])
xtrain = xtrain[self.features]
xtest = xtest[self.features]
method = mlconfig['optimizationMethod']
method = method.lower()
geneticParam = ''
optimizationHyperParameter = mlconfig['optimizationHyperParameter']
cvSplit = optimizationHyperParameter['trainTestCVSplit']
nIter = int(optimizationHyperParameter['iterations'])
if(method.lower() == 'genetic'):
geneticParam = optimizationHyperParameter['geneticparams']
scoreParam = scoreParam
if 'thresholdTunning' in mlconfig:
thresholdTunning = mlconfig['thresholdTunning'] | ||
else:
thresholdTunning = 'NA'
if cvSplit == "":
cvSplit =None
else:
cvSplit =int(cvSplit)
if modelType == 'classification':
model_type = "Classification"
MakeFP0 = False
MakeFN0 = False
if(len(categoryCountList) == 2):
if(thresholdTunning.lower() == 'fp0'):
MakeFP0 = True
elif(thresholdTunning.lower() == 'fn0'):
MakeFN0 = True
noOfClasses= len(labelMaps)
incObjClf = incClassifierModel(noOfClasses,modelList, modelParams, scoreParam, cvSplit, nIter,geneticParam, xtrain,ytrain,xtest,ytest,method,modelType,MakeFP0,MakeFN0,deployLocation)
model, params, score, estimator,model_tried,threshold,pscore,rscore = incObjClf.firstFit()
incObj = incObjClf
elif modelType == 'regression':
model_type = "Regression"
incObjReg = incRegressionModel(modelList, modelParams, scoreParam, cvSplit, nIter,geneticParam, xtrain,ytrain,xtest,ytest,method,deployLocation)
model,params,score,estimator,model_tried = incObjReg.firstFit()
incObj = incObjReg
return model_type,model,params, score, estimator,model_tried,xtrain,ytrain,xtest,ytest,threshold,pscore,rscore,method, incObj<s>
import logging
import pickle
import os
import sys
import pandas as pd
from river import stream
from river.linear_model import LogisticRegression, SoftmaxRegression, LinearRegression
from river.tree import ExtremelyFastDecisionTreeClassifier, HoeffdingAdaptiveTreeRegressor
# from river.ensemble import AdaptiveRandomForestRegressor, AdaptiveRandomForestClassifier
from river.neighbors import KNNClassifier, KNNRegressor
from river.multiclass import OneVsRestClassifier
from river.optim import SGD, Adam, AdaDelta, NesterovMomentum, RMSProp
# from river.optim.losses import CrossEntropy, Log, MultiClassLoss, Poisson, RegressionLoss, BinaryLoss, Huber
# from river.optim.initializers import Normal
class riverML(object):
def __init__(self):
self.algoDict={'Online Logistic Regression':LogisticRegression, 'Online Softmax Regression':SoftmaxRegression, 'Online Decision Tree Classifier':ExtremelyFastDecisionTreeClassifier, 'Online KNN Classifier':KNNClassifier,'Online Linear Regression':LinearRegression, 'Online Decision Tree Regressor':HoeffdingAdaptiveTreeRegressor, 'Online KNN Regressor':KNNRegressor}
self.optDict={'sgd': SGD, 'adam':Adam, 'adadelta':AdaDelta, 'nesterovmomentum':NesterovMomentum, 'rmsprop':RMSProp}
self.log = logging.getLogger('eion')
def getPrediction(self, model,X):
testStream = stream.iter_pandas(X)
preds = []
for (xi,yi) in testStream:
pred = model.predict_one(xi)
preds.append(pred)
return pd.DataFrame(preds)
def startLearn(self,problemType,algoName,params,xtrain,ytrain,noOfClasses=None):
try:
model = self.algoDict[algoName]
params = self.parseParams(params, algoName)
if problemType == 'classification':
if noOfClasses>2:
model = OneVsRestClassifier(classifier=model(**params))
else:
model = model(**params)
else:
model = model(**params)
trainStream = stream.iter_pandas(xtrain, ytrain)
#head start
for i, (xi, yi) in enumerate(trainStream):
if i>100:
break
if yi!=None:
model.learn_one(xi, yi)
trainPredictedData = []
trainStream = stream.iter_pandas(xtrain, ytrain)
for i, (xi, yi) in enumerate(trainStream):
if yi!=None:
trainPredictedData.append(model.predict_one(xi))
model.learn_one(xi, yi)
trainPredictedData = pd.DataFrame(trainPredictedData)
return algoName, params, model, trainPredictedData
except Exception as inst:
self.log.info( '\\n-----> '+algoName+' failed!!!.'+str(inst))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
self.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
def parseParams(self, params, algoName):
try:
from learner.parameters import parametersDefine
paramsObj = parametersDefine()
paramDict =paramsObj.paramDefine(params,method=None)
paramDict = {k:v[0] for k,v in paramDict.items()}
if algoName=='Online Logistic Regression' or algoName=='Online Softmax Regression' or algoName=='Online Linear Regression':
opt = self.optDict[paramDict.pop('optimizer').lower()]
lr = float(paramDict.pop('optimizer_lr'))
paramDict['optimizer'] = opt(lr)
return paramDict
except Exception as inst:
self.log.info( '\\n-----> Parameter parsing failed!!!.'+str(inst))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
self.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
#System imports
import logging
import os
import sys
import pickle
#Sci-Tools imports
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from scipy import stats
from word2number import w2n
#river imports
from river.preprocessing import StatImputer
from river import stats, compose, anomaly
class incProfiler():
def __init__(self):
self.DtypesDic={}
self.pandasNumericDtypes=['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
self.allNumberTypeCols = [] #all number type columns
self.allNumCols = [] #only numerical columns which includes num features and target if it is numerical
self.allCatCols = []
self.numFtrs = []
self.catFtrs = []
self.textFtrs = []
self.textVectorFtrs = []
self.numDiscreteCols = []
self.numContinuousCols = []
self.wordToNumericFeatures=[]
self.emptyCols=[]
self.missingCols = []
self.targetColumn = ""
self.le_dict = {}
self.configDict = {}
self.incFill = None
self.incLabelMapping = None
self.incCatEncoder = None
self.incScaler = None
self.incOutlierRem = None
self.log = logging.getLogger('eion')
def pickleDump(self, model, path):
if model is not None:
with open(path, 'wb') as f:
pickle.dump(model, f)
def saveProfilerModels(self, deployLocation):
if isinstance(self.incFill['num_fill'], StatImputer) or isinstance(self.incFill['cat_fill'], StatImputer):
self.pickleDump(self.incFill, os.path.join(deployLocation,'production','profiler','incFill.pkl'))
self.pickleDump(self.incLabelMapping, os.path.join(deployLocation,'production','profiler','incLabelMapping.pkl'))
self.pickleDump(self.incCatEncoder, os.path.join(deployLocation,'production','profiler','incCatEncoder.pkl'))
self.pickleDump(self.incScaler, os.path.join(deployLocation,'production','profiler','incScaler.pkl'))
self.pickleDump(self.incOutlierRem, os.path.join(deployLocation,'production','profiler','incOutlierRem.pkl'))
def featureAnalysis(self, df, conf_json, targetFeature):
try:
self.log.info('-------> Remove Duplicate Rows')
noofdplicaterows = df.duplicated(keep='first').sum()
df = df.drop_duplicates(keep="first")
df = df.reset_index(drop=True)
self.log.info('Status:- |... Duplicate row treatment done: '+str(noofdplicaterows))
self.log.info(df.head(5))
self.log.info( '\\n----------- Inspecting Features -----------')
ctn_count = 0
df = df.replace('-', np.nan)
df = df.replace('?', np.nan)
dataFDtypes=self.dataFramecolType(df)
numerical_ratio = float(conf_json['numericFeatureRatio'])
categoricalMaxLabel = int(conf_json['categoryMaxLabel'])
indexFeatures = []
numOfRows = df.shape[0]
dataCols = df.columns
for item in dataFDtypes:
if(item[1] == 'object'):
filteredDf,checkFlag = self.smartFilter(item[0],df,numerical_ratio)
if(checkFlag):
self.wordToNumericFeatures.append(item[0])
self.log.info('----------> Data Type Converting to numeric :Yes')
try:
df[item[0]]=filteredDf[item[0]].astype(float)
except:
pass
ctn_count = ctn_count+1
else:
count = (df[item[0]] - df[item[0]].shift() == 1).sum()
if((numOfRows - count) == 1):
self.log.info( '-------> Feature :'+str(item[0]))
self.log.info('----------> Sequence Feature')
indexFeatures.append(item[0])
self.configDict['wordToNumCols'] = self.wordToNumericFeatures
self.configDict['emptyFtrs'] = indexFeatures
self.log.info('Status:- |... Feature inspection done for numeric data: '+str(ctn_count)+' feature(s) converted to numeric')
self.log.info('Status:- |... Feature word to numeric treatment done: '+str(self.wordToNumericFeatures))
self.log.info( '----------- Inspecting Features End -----------\\n')
except Exception as inst:
self.log.info("Error in Feature inspection: "+str(inst))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
self.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
try:
self.log.info('\\n---------- Dropping Index features ----------')
self.log.info('Index Features to remove '+str(indexFeatures))
if len(indexFeatures) > 0:
dataCols = list(set(dataCols) - set(indexFeatures))
for empCol in indexFeatures:
self.log.info('-------> Drop Feature: '+empCol)
df = df.drop(columns=[empCol])
self.log.info('---------- Dropping Index features End----------\\n')
dataFDtypes=self.dataFramecolType(df)
categoricalMaxLabel = int(conf_json['categoryMaxLabel'])
for item in dataFDtypes:
self.DtypesDic[item[0]] = item[1]
nUnique=len(df[item[0]].unique().tolist())
if item[1] in self.pandasNumericDtypes:
self.allNumberTypeCols.append(item[0])
if nUnique >= categoricalMaxLabel:
self.allNumCols.append(item[0]) #pure numerical
if item[1] in ['int16', 'int32', 'int64']:
self.numDiscreteCols.append(item[0])
elif item[1] in ['float16', 'float32', 'float64']:
self.numContinuousCols.append(item[0])
else:
self.allCatCols.append(item[0])
elif item[1] != 'bool':
if (nUnique >= categoricalMaxLabel) and targetFeature != item[0]:
self.textFtrs.append(item[0])
else:
col = item[0]
if (max(df[col |