[ { "input": " import os\nimport sys\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__))))\nfrom .bin.aion_pipeline import aion_train_model\n import argparse\nimport sys\nimport os\nimport subprocess\n\nINSTALL = 'install'\nLINUXINSTALL = 'linuxinstall'\nFE_MIGRATE = 'migrateappfe'\nLAUNCH_KAFKA = 'launchkafkaconsumer'\nRUN_LOCAL_MLAC_PIPELINE = 'runpipelinelocal'\nBUILD_MLAC_CONTAINER = 'buildmlaccontainerlocal'\nCONVERT_MODEL = 'convertmodel'\nSTART_MLFLOW = 'mlflow'\nCOMMON_SERVICE = 'service'\nTRAINING = 'training'\nTRAINING_AWS = 'trainingonaws'\nTRAINING_DISTRIBUTED = 'distributedtraining'\nSTART_APPF = 'appfe'\nONLINE_TRAINING = 'onlinetraining'\nTEXT_SUMMARIZATION = 'textsummarization'\nGENERATE_MLAC = 'generatemlac'\nAWS_TRAINING = 'awstraining'\nLLAMA_7B_TUNING = 'llama7btuning'\nLLM_PROMPT = 'llmprompt'\nLLM_TUNING = 'llmtuning'\nLLM_PUBLISH = 'llmpublish'\nLLM_BENCHMARKING = 'llmbenchmarking'\nTELEMETRY_PUSH = 'pushtelemetry'\ndef aion_aws_training(confFile):\n from hyperscalers.aion_aws_training import awsTraining\n status = awsTraining(confFile)\n print(status)\n \ndef aion_training(confFile):\n from bin.aion_pipeline import aion_train_model\n status = aion_train_model(confFile)\n print(status) \n\ndef aion_awstraining(config_file):\n from hyperscalers import aws_instance\n print(config_file)\n aws_instance.training(config_file)\n \ndef aion_generatemlac(ConfFile):\n from bin.aion_mlac import generate_mlac_code\n status = generate_mlac_code(ConfFile)\n print(status)\n \ndef aion_textsummarization(confFile):\n from bin.aion_text_summarizer import aion_textsummary\n status = aion_textsummary(confFile) \n \ndef aion_oltraining(confFile):\n from bin.aion_online_pipeline import aion_ot_train_model\n status = aion_ot_train_model(confFile)\n print(status)\n\ndef do_telemetry_sync():\n from appbe.telemetry import SyncTelemetry\n SyncTelemetry()\n \ndef aion_llm_publish(cloudconfig,instanceid,hypervisor,model,usecaseid,region,image):\n from llm.llm_inference import LLM_publish\n LLM_publish(cloudconfig,instanceid,hypervisor,model,usecaseid,region,image)\n \ndef aion_migratefe(operation):\n import os\n import sys\n os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'appfe.ux.settings')\n try:\n from django.core.management import execute_from_command_line\n except ImportError as exc:\n raise ImportError(\n \"Couldn't import Django. Are you sure it's installed and \"\n \"available on your PYTHONPATH environment variable? Did you \"\n \"forget to activate a virtual environment?\"\n ) from exc\n argi=[]\n argi.append(os.path.abspath(__file__))\n argi.append(operation)\n execute_from_command_line(argi) \ndef aion_appfe(url,port):\n #manage_location = os.path.join(os.path.dirname(os.path.abspath(__file__)),'manage.py')\n #subprocess.check_call([sys.executable,manage_location, \"runserver\",\"%s:%s\"%(url,port)])\n import os\n import sys\n os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'appfe.ux.settings')\n try:\n from django.core.management import execute_from_command_line\n except ImportError as exc:\n raise ImportError(\n \"Couldn't import Django. Are you sure it's installed and \"\n \"available on your PYTHONPATH environment variable? Did you \"\n \"forget to activate a virtual environment?\"\n ) from exc\n argi=[]\n argi.append(os.path.abspath(__file__))\n argi.append('runaion')\n argi.append(\"%s:%s\"%(url,port)) \n execute_from_command_line(argi)\n\ndef aion_linux_install(version):\n from install import linux_dependencies\n linux_dependencies.process(version) \n \ndef aion_install(version):\n from install import dependencies\n dependencies.process(version)\n \ndef aion_service(ip,port,username,password):\n from bin.aion_service import start_server\n start_server(ip,port,username,password) \n \ndef aion_distributedLearning(confFile):\n from distributed_learning import learning \n learning.training(confFile)\n \ndef aion_launchkafkaconsumer():\n from mlops import kafka_consumer\n kafka_consumer.launch_kafka_consumer()\n \ndef aion_start_mlflow():\n from appbe.dataPath import DEPLOY_LOCATION \n import platform\n import shutil\n from os.path import expanduser \n mlflowpath = os.path.normpath(os.path.join(os.path.dirname(__file__),'..','..','..','Scripts','mlflow.exe'))\n print(mlflowpath)\n home = expanduser(\"~\")\n if platform.system() == 'Windows':\n DEPLOY_LOCATION = os.path.join(DEPLOY_LOCATION,'mlruns')\n outputStr = subprocess.Popen([sys.executable, mlflowpath,\"ui\", \"--backend-store-uri\",\"file:///\"+DEPLOY_LOCATION])\n else:\n DEPLOY_LOCATION = os.path.join(DEPLOY_LOCATION,'mlruns')\n subprocess.check_call(['mlflow',\"ui\",\"-h\",\"0.0.0.0\",\"--backend-store-uri\",\"file:///\"+DEPLOY_LOCATION])\n\ndef aion_model_conversion(config_file):\n from conversions import model_convertions\n model_convertions.convert(config_file) \n \ndef aion_model_buildMLaCContainer(config):\n from mlops import build_container\n build_container.local_docker_build(config)\n \ndef aion_model_runpipelinelocal(config):\n from mlops import local_pipeline\n local_pipeline.run_pipeline(config)\n\ndef aion_llm_tuning(config):\n from llm.llm_tuning import run\n run(config)\n \ndef aion_llm_prompt(cloudconfig,instanceid,prompt):\n from llm.aws_instance_api import LLM_predict\n LLM_predict(cloudconfig,instanceid,prompt)\n \ndef llm_bench_marking(hypervisor,instanceid,model,usecaseid,eval):\n print(eval)\n from llm.bench_marking import bench_mark\n bench_mark(hypervisor,instanceid,model,usecaseid,eval)\n \nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', '--configPath', help='Config File Path')\n parser.add_argument('-i', '--instanceid', help='instanceid')\n parser.add_argument('-hv', '--hypervisor', help='hypervisor')\n parser.add_argument('-md', '--model', help='model')\n parser.add_argument('-uc', '--usecase', help='usecase')\n parser.add_argument('-cc', '--cloudConfigPath', help='Cloud Config File Path')\n parser.add_argument('-m', '--module', help='MODULE=TRAINING, APPFE, ONLINETRAINING,DISTRIBUTEDTRAINING')\n parser.add_argument('-ip', '--ipaddress', help='URL applicable only for APPFE method ') \n parser.add_argument('-p', '--port', help='APP Front End Port applicable only for APPFE method ') \n parser.add_argument('-ac', '--appfecommand', help='APP Front End Command ') \n parser.add_argument('-un','--username', help=\"USERNAME\")\n parser.add_argument('-passw','--password', help=\"PASSWORD\")\n parser.add_argument('-j', '--jsoninput', help='JSON Input') \n parser.add_argument('-v', '--version', help='Installer Version') \n parser.add_argument('-pf', '--prompt', help='Prompt File')\n parser.add_argument('-r', '--region', help='REGION NAME')\n parser.add_argument('-im', '--image', help='IMAGE NAME')\n parser.add_argument('-e', '--eval', help='evaluation for code or doc', default='doc')\n args = parser.parse_args() \n if args.module.lower() == TRAINING:\n aion_training(args.configPath)\n elif args.module.lower() == TRAINING_AWS:\n aion_awstraining(args.configPath) \n elif args.module.lower() == TRAINING_DISTRIBUTED:\n aion_distributedLearning(args.configPath) \n elif args.module.lower() == START_APPF:\n aion_appfe(args.ipaddress,args.port) \n elif args.module.lower() == ONLINE_TRAINING:\n aion_oltraining(args.configPath) \n elif args.module.lower() == TEXT_SUMMARIZATION:\n aion_textsummarization(args.configPath) \n elif args.module.lower() == GENERATE_MLAC:\n aion_generatemlac(args.configPath) \n elif args.module.lower() == COMMON_SERVICE:\n aion_service(args.ipaddress,args.port,args.username,args.password) \n elif args.module.lower() == START_MLFLOW:\n aion_mlflow() \n elif args.module.lower() == CONVERT_MODEL: \n aion_model_conversion(args.configPath) \n elif args.module.lower() == BUILD_MLAC_CONTAINER:\n aion_model_buildMLaCContainer(args.jsoninput) \n elif args.module.lower() == RUN_LOCAL_MLAC_PIPELINE:\n aion_model_runpipelinelocal(args.jsoninput)\n elif args.module.lower() == LAUNCH_KAFKA: \n aion_launchkafkaconsumer() \n elif args.module.lower() == INSTALL: \n aion_install(args.version)\n elif args.module.lower() == LINUXINSTALL: \n aion_linux_install(args.version) \n elif args.module.lower() == FE_MIGRATE: \n aion_migratefe('makemigrations') \n aion_migratefe('migrate')\n elif args.module.lower() == AWS_TRAINING:\n aion_aws_training(args.configPath)\n elif args.module.lower() == LLAMA_7B_TUNING:\n aion_llm_tuning(args.configPath)\n elif args.module.lower() == LLM_TUNING:\n aion_llm_tuning(args.configPath)\n elif args.module.lower() == LLM_PROMPT:\n aion_llm_prompt(args.cloudConfigPath,args.instanceid,args.prompt)\n elif args.module.lower() == LLM_PUBLISH:\n aion_llm_publish(args.cloudConfigPath,args.instanceid,args.hypervisor,args.model,args.usecase,args.region,args.image)\n elif args.module.lower() == LLM_BENCHMARKING:\n llm_bench_marking(args.hypervisor,args.instanceid,args.model,args.usecase, args.eval)\n elif args.module.lower() == TELEMETRY_PUSH:\n do_telemetry_sync() import numpy as np\nfrom scipy.stats import norm\nfrom sklearn.metrics import mean_squared_error, r2_score\n\nfrom ..utils.misc import fitted_ucc_w_nullref\n\n\ndef picp(y_true, y_lower, y_upper):\n \"\"\"\n Prediction Interval Coverage Probability (PICP). Computes the fraction of samples for which the grounds truth lies\n within predicted interval. Measures the prediction interval calibration for regression.\n\n Args:\n y_true: Ground truth\n y_lower: predicted lower bound\n y_upper: predicted upper bound\n\n Returns:\n float: the fraction of samples for which the grounds truth lies within predicted interval.\n \"\"\"\n satisfies_upper_bound = y_true <= y_upper\n satisfies_lower_bound = y_true >= y_lower\n return np.mean(satisfies_upper_bound * satisfies_lower_bound)\n\n\ndef mpiw(y_lower, y_upper):\n \"\"\"\n Mean Prediction Interval Width (MPIW). Computes the average width of the the prediction intervals. Measures the\n sharpness of intervals.\n\n Args:\n y_lower: predicted lower bound\n y_upper: predicted upper bound\n\n Returns:\n float: the average width the prediction interval across samples.\n \"\"\"\n return np.mean(np.abs(y_lower - y_upper))\n\n\ndef auucc_gain(y_true, y_mean, y_lower, y_upper):\n \"\"\" Computes the Area Under the Uncertainty Characteristics Curve (AUUCC) gain wrt to a null reference\n with constant band.\n\n Args:\n y_true: Ground truth\n y_mean: predicted mean\n y_lower: predicted lower bound\n y_upper: predicted upper bound\n\n Returns:\n float: AUUCC gain\n\n \"\"\"\n u = fitted_ucc_w_nullref(y_true, y_mean, y_lower, y_upper)\n auucc = u.get_AUUCC()\n assert(isinstance(auucc, list) and len(auucc) == 2), \"Failed to calculate auucc gain\"\n assert (not np.isclose(auucc[1], 0.)), \"Failed to calculate auucc gain\"\n auucc_gain = (auucc[1]-auucc[0])/auucc[0]\n return auucc_gain\n\n\ndef negative_log_likelihood_Gaussian(y_true, y_mean, y_lower, y_upper):\n \"\"\" Computes Gaussian negative_log_likelihood assuming symmetric band around the mean.\n\n Args:\n y_true: Ground truth\n y_mean: predicted mean\n y_lower: predicted lower bound\n y_upper: predicted upper bound\n\n Returns:\n float: nll\n\n \"\"\"\n y_std = (y_upper - y_lower) / 4.0\n nll = np.mean(-norm.logpdf(y_true.squeeze(), loc=y_mean.squeeze(), scale=y_std.squeeze()))\n return nll\n\n\ndef compute_regression_metrics(y_true, y_mean,", "instruction": "", "output": "" }, { "input": "y_lower, y_upper, option=\"all\", nll_fn=None):\n \"\"\"\n Computes the metrics specified in the option which can be string or a list of strings. Default option `all` computes\n the [\"rmse\", \"nll\", \"auucc_gain\", \"picp\", \"mpiw\", \"r2\"] metrics.\n\n Args:\n y_true: Ground truth\n y_mean: predicted mean\n y_lower: predicted lower bound\n y_upper: predicted upper bound\n option: string or list of string contained the name of the metrics to be computed.\n nll_fn: function that evaluates NLL, if None, then computes Gaussian NLL using y_mean and y_lower.\n\n Returns:\n dict: dictionary containing the computed metrics.\n \"\"\"\n\n assert y_true.shape == y_mean.shape, \"y_true shape: {}, y_mean shape: {}\".format(y_true.shape, y_mean.shape)\n assert y_true.shape == y_lower.shape, \"y_true shape: {}, y_mean shape: {}\".format(y_true.shape, y_lower.shape)\n assert y_true.shape == y_upper.shape, \"y_true shape: {}, y_mean shape: {}\".format(y_true.shape, y_upper.shape)\n\n results = {}\n if not isinstance(option, list):\n if option == \"all\":\n option_list = [\"rmse\", \"nll\", \"auucc_gain\", \"picp\", \"mpiw\", \"r2\"]\n else:\n option_list = [option]\n\n if \"rmse\" in option_list:\n results[\"rmse\"] = mean_squared_error(y_true, y_mean, squared=False)\n if \"nll\" in option_list:\n if nll_fn is None:\n nll = negative_log_likelihood_Gaussian(y_true, y_mean, y_lower, y_upper)\n results[\"nll\"] = nll\n else:\n results[\"nll\"] = np.mean(nll_fn(y_true))\n if \"auucc_gain\" in option_list:\n gain = auucc_gain(y_true, y_mean, y_lower, y_upper)\n results[\"auucc_gain\"] = gain\n if \"picp\" in option_list:\n results[\"picp\"] = picp(y_true, y_lower, y_upper)\n if \"mpiw\" in option_list:\n results[\"mpiw\"] = mpiw(y_lower, y_upper)\n if \"r2\" in option_list:\n results[\"r2\"] = r2_score(y_true, y_mean)\n\n return results\n\n\ndef _check_not_tuple_of_2_elements(obj, obj_name='obj'):\n \"\"\"Check object is not tuple or does not have 2 elements.\"\"\"\n if not isinstance(obj, tuple) or len(obj) != 2:\n raise TypeError('%s must be a tuple of 2 elements.' % obj_name)\n\n\ndef plot_uncertainty_distribution(dist, show_quantile_dots=False, qd_sample=20, qd_bins=7,\n ax=None, figsize=None, dpi=None,\n title='Predicted Distribution', xlims=None, xlabel='Prediction', ylabel='Density', **kwargs):\n \"\"\"\n Plot the uncertainty distribution for a single distribution.\n\n Args:\n dist: scipy.stats._continuous_distns.\n A scipy distribution object.\n show_quantile_dots: boolean.\n Whether to show quantil dots on top of the density plot.\n qd_sample: int.\n Number of dots for the quantile dot plot.\n qd_bins: int.\n Number of bins for the quantile dot plot.\n ax: matplotlib.axes.Axes or None, optional (default=None).\n Target axes instance. If None, new figure and axes will be created.\n figsize: tuple of 2 elements or None, optional (default=None).\n Figure size.\n dpi : int or None, optional (default=None).\n Resolution of the figure.\n title : string or None, optional (default=Prediction Distribution)\n Axes title.\n If None, title is disabled.\n xlims : tuple of 2 elements or None, optional (default=None). Tuple passed to ``ax.xlim()``.\n xlabel : string or None, optional (default=Prediction)\n X-axis title label.\n If None, title is disabled.\n ylabel : string or None, optional (default=Density)\n Y-axis title label.\n If None, title is disabled.\n\n Returns:\n matplotlib.axes.Axes: ax : The plot with prediction distribution.\n \"\"\"\n\n import matplotlib.pyplot as plt\n\n if ax is None:\n if figsize is not None:\n _check_not_tuple_of_2_elements(figsize, 'figsize')\n _, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)\n\n x = np.linspace(dist.ppf(0.01), dist.ppf(0.99), 100)\n ax.plot(x, dist.pdf(x), **kwargs)\n\n if show_quantile_dots:\n from matplotlib.patches import Circle\n from matplotlib.collections import PatchCollection\n import matplotlib.ticker as ticker\n\n data = dist.rvs(size=10000)\n p_less_than_x = np.linspace(1 / qd_sample / 2, 1 - (1 / qd_sample / 2), qd_sample)\n x_ = np.percentile(data, p_less_than_x * 100) # Inverce CDF (ppf)\n # Create bins\n hist = np.histogram(x_, bins=qd_bins)\n bins, edges = hist\n radius = (edges[1] - edges[0]) / 2\n\n ax2 = ax.twinx()\n patches = []\n max_y = 0\n for i in range(qd_bins):\n x_bin = (edges[i + 1] + edges[i]) / 2\n y_bins = [(i + 1) * (radius * 2) for i in range(bins[i])]\n\n max_y = max(y_bins) if max(y_bins) > max_y else max_y\n\n for _, y_bin in enumerate(y_bins):\n circle = Circle((x_bin, y_bin), radius)\n patches.append(circle)\n\n p = PatchCollection(patches, alpha=0.4)\n ax2.add_collection(p)\n\n # Axis tweek\n y_scale = (max_y + radius) / max(dist.pdf(x))\n ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x_ / y_scale))\n ax2.yaxis.set_major_formatter(ticks_y)\n ax2.set_yticklabels([])\n if xlims is not None:\n ax2.set_xlim(left=xlims[0], right=xlims[1])\n else:\n ax2.set_xlim([min(x_) - radius, max(x) + radius])\n ax2.set_ylim([0, max_y + radius])\n ax2.set_aspect(1)\n\n if title is not None:\n ax.set_title(title)\n if xlabel is not None:\n ax.set_xlabel(xlabel)\n if ylabel is not None:\n ax.set_ylabel(ylabel)\n \n return ax\n\n\ndef plot_picp_by_feature(x_test, y_test, y_test_pred_lower_total, y_test_pred_upper_total, num_bins=10,\n ax=None, figsize=None, dpi=None, xlims=None, ylims=None, xscale=\"linear\",\n title=None, xlabel=None, ylabel=None):\n \"\"\"\n Plot how prediction uncertainty varies across the entire range of a feature.\n\n Args:\n x_test: One dimensional ndarray.\n Feature column of the test dataset.\n y_test: One dimensional ndarray.\n Ground truth label of the test dataset.\n y_test_pred_lower_total: One dimensional ndarray.\n Lower bound of the total uncertainty range.\n y_test_pred_upper_total: One dimensional ndarray.\n Upper bound of the total uncertainty range.\n num_bins: int.\n Number of bins used to discritize x_test into equal-sample-sized bins.\n ax: matplotlib.axes.Axes or None, optional (default=None). Target axes instance. If None, new figure and axes will be created.\n figsize: tuple of 2 elements or None, optional (default=None). Figure size.\n dpi : int or None, optional (default=None). Resolution of the figure.\n xlims : tuple of 2 elements or None, optional (default=None). Tuple passed to ``ax.xlim()``.\n ylims: tuple of 2 elements or None, optional (default=None). Tuple passed to ``ax.ylim()``.\n xscale: Passed to ``ax.set_xscale()``.\n title : string or None, optional\n Axes title.\n If None, title is disabled.\n xlabel : string or None, optional\n X-axis title label.\n If None, title is disabled.\n ylabel : string or None, optional\n Y-axis title label.\n If None, title is disabled.\n\n Returns:\n matplotlib.axes.Axes: ax : The plot with PICP scores binned by a feature.\n\n \"\"\"\n from scipy.stats.mstats import mquantiles\n import matplotlib.pyplot as plt\n\n if ax is None:\n if figsize is not None:\n _check_not_tuple_of_2_elements(figsize, 'figsize')\n _, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)\n \n x_uniques_sorted = np.sort(np.unique(x_test))\n\n num_unique = len(x_uniques_sorted)\n sample_bin_ids = np.searchsorted(x_uniques_sorted, x_test)\n if len(x_uniques_sorted) > 10: # bin the values\n q_bins = mquantiles(x_test, np.histogram_bin_edges([], bins=num_bins-1, range=(0.0, 1.0))[1:])\n q_sample_bin_ids = np.digitize(x_test, q_bins)\n picps = np.array([picp(y_test[q_sample_bin_ids==bin], y_test_pred_lower_total[q_sample_bin_ids==bin],\n y_test_pred_upper_total[q_sample_bin_ids==bin]) for bin in range(num_bins)])\n unique_sample_bin_ids = np.digitize(x_uniques_sorted, q_bins)\n picp_replicated = [len(x_uniques_sorted[unique_sample_bin_ids == bin]) * [picps[bin]] for bin in range(num_bins)]\n picp_replicated = np.array([item for sublist in picp_replicated for item in sublist])\n else:\n picps = np.array([picp(y_test[sample_bin_ids == bin], y_test_pred_lower_total[sample_bin_ids == bin],\n y_test_pred_upper_total[sample_bin_ids == bin]) for bin in range(num_unique)])\n picp_replicated = picps\n\n ax.plot(x_uniques_sorted, picp_replicated, label='PICP')\n ax.axhline(0.95, linestyle='--', label='95%')\n ax.set_ylabel('PICP')\n\n ax.legend(loc='best')\n\n if title is None:\n title = 'Test data overall PICP: {:.2f} MPIW: {:.2f}'.format(\n picp(y_test, \n y_test_pred_lower_total, \n y_test_pred_upper_total),\n mpiw(y_test_pred_lower_total, \n y_test_pred_upper_total)) \n\n if xlims is not None:\n ax.set_xlim(left=xlims[0], right=xlims[1])\n\n if ylims is not None:\n ax.set_ylim(bottom=ylims[0], top=ylims[1])\n \n ax.set_title(title)\n if xlabel is not None:\n ax.set_xlabel(xlabel)\n if ylabel is not None:\n ax.set_ylabel(ylabel)\n if xscale is not None:\n ax.set_xscale(xscale)\n\n return ax\n\n\ndef plot_uncertainty_by_feature(x_test, y_test_pred_mean, y_test_pred_lower_total, y_test_pred_upper_total,\n y_test_pred_lower_epistemic=None, y_test_pred_upper_epistemic=None,\n ax=None, figsize=None, dpi=None, xlims=None, xscale=\"linear\",\n title=None, xlabel=None, ylabel=None):\n \"\"\"\n Plot how prediction uncertainty varies across the entire range of a feature.\n\n Args:\n x_test: one dimensional ndarray.\n Feature column of the test dataset.\n y_test_pred_mean: One dimensional ndarray.\n Model prediction for the test dataset.\n y_test_pred_lower_total: One dimensional ndarray.\n Lower bound of the total uncertainty range.\n y_test_pred_upper_total: One dimensional ndarray.\n Upper bound of the total uncertainty range.\n y_test_pred_lower_epistemic: One dimensional ndarray.\n Lower bound of the epistemic uncertainty range.\n y_test_pred_upper_epistemic: One dimensional ndarray.\n Upper bound of the epistemic uncertainty range.\n ax: matplotlib.axes.Axes or None, optional (default=None). Target axes instance. If None, new figure and axes will be created.\n figsize: tuple of 2 elements or None, optional (default=None). Figure size.\n dpi : int or None, optional (default=None). Resolution of the figure.\n xlims : tuple of 2 elements or None, optional (default=None). Tuple passed to ``ax.xlim()``.\n xscale: Passed to ``ax.set_xscale()``.\n title : string or None, optional\n Axes title.\n If None, title is disabled.\n xlabel : string or None, optional\n X-axis title label.\n If None, title is disabled.\n ylabel : string or None, optional\n Y-axis title label.\n If None, title is disabled.\n\n Returns:\n matplotlib.axes.Axes: ax : The plot with model's uncertainty binned by a feature.\n\n \"\"\"\n import matplotlib.pyplot as plt\n\n if ax is None:\n if figsize is not None:\n _check_not_tuple_of_2_elements(figsize, 'figsize')\n _, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)\n\n x_uniques_sorted = np.sort(np.unique(x_test))\n\n y_pred_var = ((y_test_pred_upper_total - y_test_pred_lower_total) / 4.0)**2\n agg_y_std = np.array([np.sqrt(np.mean(y_pred_var[x_test==x])) for x in x_uniques_sorted])\n agg_y_mean =", "instruction": "", "output": "" }, { "input": "np.array([np.mean(y_test_pred_mean[x_test==x]) for x in x_uniques_sorted])\n\n ax.plot(x_uniques_sorted, agg_y_mean, '-b', lw=2, label='mean prediction')\n ax.fill_between(x_uniques_sorted,\n agg_y_mean - 2.0 * agg_y_std,\n agg_y_mean + 2.0 * agg_y_std,\n alpha=0.3, label='total uncertainty')\n\n if y_test_pred_lower_epistemic is not None:\n y_pred_var_epistemic = ((y_test_pred_upper_epistemic - y_test_pred_lower_epistemic) / 4.0)**2\n agg_y_std_epistemic = np.array([np.sqrt(np.mean(y_pred_var_epistemic[x_test==x])) for x in x_uniques_sorted])\n ax.fill_between(x_uniques_sorted,\n agg_y_mean - 2.0 * agg_y_std_epistemic,\n agg_y_mean + 2.0 * agg_y_std_epistemic,\n alpha=0.3, label='model uncertainty')\n\n ax.legend(loc='best')\n \n if xlims is not None:\n ax.set_xlim(left=xlims[0], right=xlims[1]) \n\n if title is not None:\n ax.set_title(title)\n if xlabel is not None:\n ax.set_xlabel(xlabel)\n if ylabel is not None:\n ax.set_ylabel(ylabel)\n if xscale is not None:\n ax.set_xscale(xscale)\n\n return ax\n import numpy as np\nimport pandas as pd\nfrom scipy.stats import entropy\nfrom sklearn.metrics import roc_auc_score, log_loss, accuracy_score\n\n\ndef entropy_based_uncertainty_decomposition(y_prob_samples):\n \"\"\" Entropy based decomposition [2]_ of predictive uncertainty into aleatoric and epistemic components.\n\n References:\n .. [2] Depeweg, S., Hernandez-Lobato, J. M., Doshi-Velez, F., & Udluft, S. (2018, July). Decomposition of\n uncertainty in Bayesian deep learning for efficient and risk-sensitive learning. In International Conference\n on Machine Learning (pp. 1184-1193). PMLR.\n\n Args:\n y_prob_samples: list of array-like of shape (n_samples, n_classes) containing class prediction probabilities\n corresponding to samples from the model posterior.\n\n Returns:\n tuple:\n - total_uncertainty: entropy of the predictive distribution.\n - aleatoric_uncertainty: aleatoric component of the total_uncertainty.\n - epistemic_uncertainty: epistemic component of the total_uncertainty.\n\n \"\"\"\n y_preds_samples_stacked = np.stack(y_prob_samples)\n preds_mean = np.mean(y_preds_samples_stacked, 0)\n\n total_uncertainty = entropy(preds_mean, axis=1)\n aleatoric_uncertainty = np.mean(\n np.concatenate([entropy(y_pred, axis=1).reshape(-1, 1) for y_pred in y_prob_samples], axis=1),\n axis=1)\n epistemic_uncertainty = total_uncertainty - aleatoric_uncertainty\n\n return total_uncertainty, aleatoric_uncertainty, epistemic_uncertainty\n\n\ndef multiclass_brier_score(y_true, y_prob):\n \"\"\"Brier score for multi-class.\n\n Args:\n y_true: array-like of shape (n_samples,)\n ground truth labels.\n y_prob: array-like of shape (n_samples, n_classes).\n Probability scores from the base model.\n\n Returns:\n float: Brier score.\n\n \"\"\"\n assert len(y_prob.shape) > 1, \"y_prob should be array-like of shape (n_samples, n_classes)\"\n\n y_target = np.zeros_like(y_prob)\n y_target[:, y_true] = 1.0\n return np.mean(np.sum((y_target - y_prob) ** 2, axis=1))\n\n\ndef area_under_risk_rejection_rate_curve(y_true, y_prob, y_pred=None, selection_scores=None, risk_func=accuracy_score,\n attributes=None, num_bins=10, subgroup_ids=None,\n return_counts=False):\n \"\"\" Computes risk vs rejection rate curve and the area under this curve. Similar to risk-coverage curves [3]_ where\n coverage instead of rejection rate is used.\n\n References:\n .. [3] Franc, Vojtech, and Daniel Prusa. \"On discriminative learning of prediction uncertainty.\"\n In International Conference on Machine Learning, pp. 1963-1971. 2019.\n\n Args:\n y_true: array-like of shape (n_samples,)\n ground truth labels.\n y_prob: array-like of shape (n_samples, n_classes).\n Probability scores from the base model.\n y_pred: array-like of shape (n_samples,)\n predicted labels.\n selection_scores: scores corresponding to certainty in the predicted labels.\n risk_func: risk function under consideration.\n attributes: (optional) if risk function is a fairness metric also pass the protected attribute name.\n num_bins: number of bins.\n subgroup_ids: (optional) selectively compute risk on a subgroup of the samples specified by subgroup_ids.\n return_counts: set to True to return counts also.\n\n Returns:\n float or tuple:\n - aurrrc (float): area under risk rejection rate curve.\n - rejection_rates (list): rejection rates for each bin (returned only if return_counts is True).\n - selection_thresholds (list): selection threshold for each bin (returned only if return_counts is True).\n - risks (list): risk in each bin (returned only if return_counts is True).\n\n \"\"\"\n\n if selection_scores is None:\n assert len(y_prob.shape) > 1, \"y_prob should be array-like of shape (n_samples, n_classes)\"\n selection_scores = y_prob[np.arange(y_prob.shape[0]), np.argmax(y_prob, axis=1)]\n\n if y_pred is None:\n assert len(y_prob.shape) > 1, \"y_prob should be array-like of shape (n_samples, n_classes)\"\n y_pred = np.argmax(y_prob, axis=1)\n\n order = np.argsort(selection_scores)[::-1]\n\n rejection_rates = []\n selection_thresholds = []\n risks = []\n for bin_id in range(num_bins):\n samples_in_bin = len(y_true) // num_bins\n selection_threshold = selection_scores[order[samples_in_bin * (bin_id+1)-1]]\n selection_thresholds.append(selection_threshold)\n ids = selection_scores >= selection_threshold\n if sum(ids) > 0:\n if attributes is None:\n if isinstance(y_true, pd.Series):\n y_true_numpy = y_true.values\n else:\n y_true_numpy = y_true\n if subgroup_ids is None:\n risk_value = 1.0 - risk_func(y_true_numpy[ids], y_pred[ids])\n else:\n if sum(subgroup_ids & ids) > 0:\n risk_value = 1.0 - risk_func(y_true_numpy[subgroup_ids & ids], y_pred[subgroup_ids & ids])\n else:\n risk_value = 0.0\n else:\n risk_value = risk_func(y_true.iloc[ids], y_pred[ids], prot_attr=attributes)\n else:\n risk_value = 0.0\n risks.append(risk_value)\n rejection_rates.append(1.0 - 1.0 * sum(ids) / len(y_true))\n\n aurrrc = np.nanmean(risks)\n\n if not return_counts:\n return aurrrc\n else:\n return aurrrc, rejection_rates, selection_thresholds, risks\n\n\ndef expected_calibration_error(y_true, y_prob, y_pred=None, num_bins=10, return_counts=False):\n \"\"\" Computes the reliability curve and the expected calibration error [1]_ .\n\n References:\n .. [1] Chuan Guo, Geoff Pleiss, Yu Sun, Kilian Q. Weinberger; Proceedings of the 34th International Conference\n on Machine Learning, PMLR 70:1321-1330, 2017.\n\n Args:\n y_true: array-like of shape (n_samples,)\n ground truth labels.\n y_prob: array-like of shape (n_samples, n_classes).\n Probability scores from the base model.\n y_pred: array-like of shape (n_samples,)\n predicted labels.\n num_bins: number of bins.\n return_counts: set to True to return counts also.\n\n Returns:\n float or tuple:\n - ece (float): expected calibration error.\n - confidences_in_bins: average confidence in each bin (returned only if return_counts is True).\n - accuracies_in_bins: accuracy in each bin (returned only if return_counts is True).\n - frac_samples_in_bins: fraction of samples in each bin (returned only if return_counts is True).\n\n \"\"\"\n\n assert len(y_prob.shape) > 1, \"y_prob should be array-like of shape (n_samples, n_classes)\"\n num_samples, num_classes = y_prob.shape\n top_scores = np.max(y_prob, axis=1)\n\n if y_pred is None:\n y_pred = np.argmax(y_prob, axis=1)\n\n if num_classes == 2:\n bins_edges = np.histogram_bin_edges([], bins=num_bins, range=(0.5, 1.0))\n else:\n bins_edges = np.histogram_bin_edges([], bins=num_bins, range=(0.0, 1.0))\n\n non_boundary_bin_edges = bins_edges[1:-1]\n bin_centers = (bins_edges[1:] + bins_edges[:-1])/2\n\n sample_bin_ids = np.digitize(top_scores, non_boundary_bin_edges)\n\n num_samples_in_bins = np.zeros(num_bins)\n accuracies_in_bins = np.zeros(num_bins)\n confidences_in_bins = np.zeros(num_bins)\n\n for bin in range(num_bins):\n num_samples_in_bins[bin] = len(y_pred[sample_bin_ids == bin])\n if num_samples_in_bins[bin] > 0:\n accuracies_in_bins[bin] = np.sum(y_true[sample_bin_ids == bin] == y_pred[sample_bin_ids == bin]) / num_samples_in_bins[bin]\n confidences_in_bins[bin] = np.sum(top_scores[sample_bin_ids == bin]) / num_samples_in_bins[bin]\n\n ece = np.sum(\n num_samples_in_bins * np.abs(accuracies_in_bins - confidences_in_bins) / num_samples\n )\n frac_samples_in_bins = num_samples_in_bins / num_samples\n\n if not return_counts:\n return ece\n else:\n return ece, confidences_in_bins, accuracies_in_bins, frac_samples_in_bins, bin_centers\n\n\ndef compute_classification_metrics(y_true, y_prob, option='all'):\n \"\"\"\n Computes the metrics specified in the option which can be string or a list of strings. Default option `all` computes\n the [aurrrc, ece, auroc, nll, brier, accuracy] metrics.\n\n Args:\n y_true: array-like of shape (n_samples,)\n ground truth labels.\n y_prob: array-like of shape (n_samples, n_classes).\n Probability scores from the base model.\n option: string or list of string contained the name of the metrics to be computed.\n\n Returns:\n dict: a dictionary containing the computed metrics.\n \"\"\"\n results = {}\n if not isinstance(option, list):\n if option == \"all\":\n option_list = [\"aurrrc\", \"ece\", \"auroc\", \"nll\", \"brier\", \"accuracy\"]\n else:\n option_list = [option]\n\n if \"aurrrc\" in option_list:\n results[\"aurrrc\"] = area_under_risk_rejection_rate_curve(y_true=y_true, y_prob=y_prob)\n if \"ece\" in option_list:\n results[\"ece\"] = expected_calibration_error(y_true=y_true, y_prob=y_prob)\n if \"auroc\" in option_list:\n results[\"auroc\"], _ = roc_auc_score(y_true=y_true, y_score=y_prob)\n if \"nll\" in option_list:\n results[\"nll\"] = log_loss(y_true=y_true, y_pred=np.argmax(y_prob, axis=1))\n if \"brier\" in option_list:\n results[\"brier\"] = multiclass_brier_score(y_true=y_true, y_prob=y_prob)\n if \"accuracy\" in option_list:\n results[\"accuracy\"] = accuracy_score(y_true=y_true, y_pred=np.argmax(y_prob, axis=1))\n\n return results\n\n\ndef plot_reliability_diagram(y_true, y_prob, y_pred, plot_label=[\"\"], num_bins=10):\n \"\"\"\n Plots the reliability diagram showing the calibration error for different confidence scores. Multiple curves\n can be plot by passing data as lists.\n\n Args:\n y_true: array-like or or a list of array-like of shape (n_samples,)\n ground truth labels.\n y_prob: array-like or or a list of array-like of shape (n_samples, n_classes).\n Probability scores from the base model.\n y_pred: array-like or or a list of array-like of shape (n_samples,)\n predicted labels.\n plot_label: (optional) list of names identifying each curve.\n num_bins: number of bins.\n\n Returns:\n tuple:\n - ece_list: ece: list containing expected calibration error for each curve.\n - accuracies_in_bins_list: list containing binned average accuracies for each curve.\n - frac_samples_in_bins_list: list containing binned sample frequencies for each curve.\n - confidences_in_bins_list: list containing binned average confidence for each curve.\n \"\"\"\n import matplotlib.", "instruction": "", "output": "" }, { "input": "pyplot as plt\n\n if not isinstance(y_true, list):\n y_true, y_prob, y_pred = [y_true], [y_prob], [y_pred]\n if len(plot_label) != len(y_true):\n raise ValueError('y_true and plot_label should be of same length.')\n\n ece_list = []\n accuracies_in_bins_list = []\n frac_samples_in_bins_list = []\n confidences_in_bins_list = []\n\n for idx in range(len(plot_label)):\n ece, confidences_in_bins, accuracies_in_bins, frac_samples_in_bins, bins = expected_calibration_error(y_true[idx],\n y_prob[idx],\n y_pred[idx],\n num_bins=num_bins,\n return_counts=True)\n ece_list.append(ece)\n accuracies_in_bins_list.append(accuracies_in_bins)\n frac_samples_in_bins_list.append(frac_samples_in_bins)\n confidences_in_bins_list.append(confidences_in_bins)\n\n fig = plt.figure(figsize=(12, 5))\n\n plt.subplot(1, 2, 1)\n for idx in range(len(plot_label)):\n plt.plot(bins, frac_samples_in_bins_list[idx], 'o-', label=plot_label[idx])\n plt.title(\"Confidence Histogram\")\n plt.xlabel(\"Confidence\")\n plt.ylabel(\"Fraction of Samples\")\n plt.grid()\n plt.ylim([0.0, 1.0])\n plt.legend()\n\n plt.subplot(1, 2, 2)\n for idx in range(len(plot_label)):\n plt.plot(bins, accuracies_in_bins_list[idx], 'o-',\n label=\"{} ECE = {:.2f}\".format(plot_label[idx], ece_list[idx]))\n plt.plot(np.linspace(0, 1, 50), np.linspace(0, 1, 50), 'b.', label=\"Perfect Calibration\")\n plt.title(\"Reliability Plot\")\n plt.xlabel(\"Confidence\")\n plt.ylabel(\"Accuracy\")\n plt.grid()\n plt.legend()\n\n plt.show()\n\n return ece_list, accuracies_in_bins_list, frac_samples_in_bins_list, confidences_in_bins_list\n\n\ndef plot_risk_vs_rejection_rate(y_true, y_prob, y_pred, selection_scores=None, plot_label=[\"\"], risk_func=None,\n attributes=None, num_bins=10, subgroup_ids=None):\n \"\"\"\n Plots the risk vs rejection rate curve showing the risk for different rejection rates. Multiple curves\n can be plot by passing data as lists.\n\n Args:\n y_true: array-like or or a list of array-like of shape (n_samples,)\n ground truth labels.\n y_prob: array-like or or a list of array-like of shape (n_samples, n_classes).\n Probability scores from the base model.\n y_pred: array-like or or a list of array-like of shape (n_samples,)\n predicted labels.\n selection_scores: ndarray or a list of ndarray containing scores corresponding to certainty in the predicted labels.\n risk_func: risk function under consideration.\n attributes: (optional) if risk function is a fairness metric also pass the protected attribute name.\n num_bins: number of bins.\n subgroup_ids: (optional) ndarray or a list of ndarray containing subgroup_ids to selectively compute risk on a\n subgroup of the samples specified by subgroup_ids.\n\n Returns:\n tuple:\n - aurrrc_list: list containing the area under risk rejection rate curves.\n - rejection_rate_list: list containing the binned rejection rates.\n - selection_thresholds_list: list containing the binned selection thresholds.\n - risk_list: list containing the binned risks.\n \"\"\"\n import matplotlib.pyplot as plt\n\n if not isinstance(y_true, list):\n y_true, y_prob, y_pred, selection_scores, subgroup_ids = [y_true], [y_prob], [y_pred], [selection_scores], [subgroup_ids]\n if len(plot_label) != len(y_true):\n raise ValueError('y_true and plot_label should be of same length.')\n\n aurrrc_list = []\n rejection_rate_list = []\n risk_list = []\n selection_thresholds_list = []\n\n for idx in range(len(plot_label)):\n aursrc, rejection_rates, selection_thresholds, risks = area_under_risk_rejection_rate_curve(\n y_true[idx],\n y_prob[idx],\n y_pred[idx],\n selection_scores=selection_scores[idx],\n risk_func=risk_func,\n attributes=attributes,\n num_bins=num_bins,\n subgroup_ids=subgroup_ids[idx],\n return_counts=True\n )\n\n aurrrc_list.append(aursrc)\n rejection_rate_list.append(rejection_rates)\n risk_list.append(risks)\n selection_thresholds_list.append(selection_thresholds)\n\n plt.figure(figsize=(12, 5))\n\n plt.subplot(1, 2, 1)\n for idx in range(len(plot_label)):\n plt.plot(rejection_rate_list[idx], risk_list[idx], label=\"{} AURRRC={:.5f}\".format(plot_label[idx], aurrrc_list[idx]))\n\n plt.legend(loc=\"best\")\n plt.xlabel(\"Rejection Rate\")\n if risk_func is None:\n ylabel = \"Prediction Error Rate\"\n else:\n if 'accuracy' in risk_func.__name__:\n ylabel = \"1.0 - \" + risk_func.__name__\n else:\n ylabel = risk_func.__name__\n\n plt.ylabel(ylabel)\n plt.title(\"Risk vs Rejection Rate Plot\")\n plt.grid()\n\n plt.subplot(1, 2, 2)\n for idx in range(len(plot_label)):\n plt.plot(selection_thresholds_list[idx], risk_list[idx], label=\"{}\".format(plot_label[idx]))\n\n plt.legend(loc=\"best\")\n plt.xlabel(\"Selection Threshold\")\n if risk_func is None:\n ylabel = \"Prediction Error Rate\"\n else:\n if 'accuracy' in risk_func.__name__:\n ylabel = \"1.0 - \" + risk_func.__name__\n else:\n ylabel = risk_func.__name__\n\n plt.ylabel(ylabel)\n plt.title(\"Risk vs Selection Threshold Plot\")\n plt.grid()\n\n plt.show()\n\n return aurrrc_list, rejection_rate_list, selection_thresholds_list, risk_list\n from .classification_metrics import expected_calibration_error, area_under_risk_rejection_rate_curve, \\\\\n compute_classification_metrics, entropy_based_uncertainty_decomposition\nfrom .regression_metrics import picp, mpiw, compute_regression_metrics, plot_uncertainty_distribution, \\\\\n plot_uncertainty_by_feature, plot_picp_by_feature\nfrom .uncertainty_characteristics_curve import UncertaintyCharacteristicsCurve\n from copy import deepcopy\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.integrate import simps, trapz\nfrom sklearn.isotonic import IsotonicRegression\n\nDEFAULT_X_AXIS_NAME = 'excess'\nDEFAULT_Y_AXIS_NAME = 'missrate'\n\n\nclass UncertaintyCharacteristicsCurve:\n \"\"\"\n Class with main functions of the Uncertainty Characteristics Curve (UCC).\n\n \"\"\"\n\n def __init__(self, normalize=True, precompute_bias_data=True):\n \"\"\"\n :param normalize: set initial axes normalization flag (can be changed via set_coordinates())\n :param precompute_bias_data: if True, fit() will compute statistics necessary to generate bias-based\n UCCs (in addition to the scale-based ones). Skipping this precomputation may speed up the fit() call\n if bias-based UCC is not needed.\n\n \"\"\"\n self.axes_name2idx = {\"missrate\": 1, \"bandwidth\": 2, \"excess\": 3, \"deficit\": 4}\n self.axes_idx2descr = {1: \"Missrate\", 2: \"Bandwidth\", 3: \"Excess\", 4: \"Deficit\"}\n self.x_axis_idx = None\n self.y_axis_idx = None\n self.norm_x_axis = False\n self.norm_y_axis = False\n self.std_unit = None\n self.normalize = normalize\n self.d = None\n self.gt = None\n self.lb = None\n self.ub = None\n self.precompute_bias_data = precompute_bias_data\n self.set_coordinates(x_axis_name=DEFAULT_X_AXIS_NAME, y_axis_name=DEFAULT_Y_AXIS_NAME, normalize=normalize)\n\n def set_coordinates(self, x_axis_name=None, y_axis_name=None, normalize=None):\n \"\"\"\n Assigns user-specified type to the axes and normalization behavior (sticky).\n\n :param x_axis_name: None-> unchanged, or name from self.axes_name2idx \n :param y_axis_name: ditto\n :param normalize: True/False will activate/deactivate norming for specified axes. Behavior for\n Axes_name that are None will not be changed.\n Value None will leave norm status unchanged.\n Note, axis=='missrate' will never get normalized, even with normalize == True\n :return: none\n \"\"\"\n normalize = self.normalize if normalize is None else normalize\n if x_axis_name is None and self.x_axis_idx is None:\n raise ValueError(\"ERROR(UCC): x-axis has not been defined.\")\n if y_axis_name is None and self.y_axis_idx is None:\n raise ValueError(\"ERROR(UCC): y-axis has not been defined.\")\n if x_axis_name is None and y_axis_name is None and normalize is not None:\n # just set normalization on/off for both axes and return\n self.norm_x_axis = False if x_axis_name == 'missrate' else normalize\n self.norm_y_axis = False if y_axis_name == 'missrate' else normalize\n return\n if x_axis_name is not None:\n self.x_axis_idx = self.axes_name2idx[x_axis_name]\n self.norm_x_axis = False if x_axis_name == 'missrate' else normalize\n if y_axis_name is not None:\n self.y_axis_idx = self.axes_name2idx[y_axis_name]\n self.norm_y_axis = False if y_axis_name == 'missrate' else normalize\n\n def set_std_unit(self, std_unit=None):\n \"\"\"\n Sets the UCC's unit to be used when displaying normalized axes.\n\n :param std_unit: if None, the unit will be calculated as stddev of the ground truth data \n (ValueError raised if data has not been set at this point)\n or set to the user-specified value.\n :return: \n \"\"\"\n if std_unit is None: # set it to stddev of data\n if self.gt is None:\n raise ValueError(\"ERROR(UCC): No data specified - cannot set stddev unit.\")\n self.std_unit = np.std(self.gt)\n\n if np.isclose(self.std_unit, 0.):\n print(\"WARN(UCC): data-based stddev is zero - resetting axes unit to 1.\")\n self.std_unit = 1.\n else:\n self.std_unit = float(std_unit)\n\n def fit(self, X, gt):\n \"\"\"\n Calculates internal arrays necessary for other methods (plotting, auc, cost minimization).\n Re-entrant.\n\n :param X: [numsamples, 3] numpy matrix, or list of numpy matrices.\n Col 1: predicted values\n Col 2: lower band (deviate) wrt predicted value (always positive)\n Col 3: upper band wrt predicted value (always positive)\n If list is provided, all methods will output corresponding metrics as lists as well!\n :param gt: Ground truth array (i.e.,the 'actual' values corresponding to predictions in X\n :return: self\n\n \"\"\"\n if not isinstance(X, list):\n X = [X]\n newX = []\n for x in X:\n assert (isinstance(x, np.ndarray) and len(x.shape) == 2 and x.shape[1] == 3 and x.shape[0] == len(gt))\n newX.append(self._sanitize_input(x))\n self.d = [gt - x[:, 0] for x in newX]\n self.lb = [x[:, 1] for x in newX]\n self.ub = [x[:, 2] for x in newX]\n self.gt = gt\n self.set_std_unit()\n self.plotdata_for_scale = []\n self.plotdata_for_bias = []\n # precompute plotdata:\n for i in range(len(self.d)):\n self.plotdata_for_scale.append(self._calc_plotdata(self.d[i], self.lb[i], self.ub[i], vary_bias=False))\n if self.precompute_bias_data:\n self.plotdata_for_bias.append(self._calc_plotdata(self.d[i], self.lb[i], self.ub[i], vary_bias=True))\n\n return self\n\n def minimize_cost(self, x_axis_cost=.5, y_axis_cost=.5, augment_cost_by_normfactor=True,\n search=('scale', 'bias')):\n \"\"\"\n Find minima of a linear cost function for each component.\n Cost function C = x_axis_cost * x_axis_value + y_axis_cost * y_axis_value.\n A minimum can occur in the scale-based or bias-based UCC (this can be constrained by the 'search' arg).\n The function returns a 'recipe' how to achieve the corresponding minimum, for each component.\n\n :param x_axis_cost: weight of one unit on x_axis\n :param y_axis_cost: weight of one unit on y_axis\n :param augment_cost_by_normfactor: when False, the cost multipliers will apply as is. If True, they will be\n pre-normed by the corresponding axis norm (where applicable), to account for range differences between axes.\n :param search: list of types over which minimization is to be performed, valid elements are 'scale' and 'bias'.\n\n :return: list of dicts - one per component, or a single dict, if there is only one component. Dict keys are -\n 'operation': can be 'bias' (additive) or 'scale' (multiplicative), 'modvalue': value to multiply by or to\n add to error bars to achieve", "instruction": "", "output": "" }, { "input": "the minimum, 'new_x'/'new_y': new coordinates (operating point) with that\n minimum, 'cost': new cost at minimum point, 'original_cost': original cost (original operating point).\n\n \"\"\"\n if self.d is None:\n raise ValueError(\"ERROR(UCC): call fit() prior to using this method.\")\n if augment_cost_by_normfactor:\n if self.norm_x_axis:\n x_axis_cost /= self.std_unit\n if self.norm_y_axis:\n y_axis_cost /= self.std_unit\n print(\"INFO(UCC): Pre-norming costs by corresp. std deviation: new x_axis_cost = %.4f, y_axis_cost = %.4f\" %\n (x_axis_cost, y_axis_cost))\n if isinstance(search, tuple):\n search = list(search)\n if not isinstance(search, list):\n search = [search]\n\n min_costs = []\n for d in range(len(self.d)):\n # original OP cost\n m, b, e, df = self._calc_missrate_bandwidth_excess_deficit(self.d[d], self.lb[d], self.ub[d])\n original_cost = x_axis_cost * [0., m, b, e, df][self.x_axis_idx] + y_axis_cost * [0., m, b, e, df][\n self.y_axis_idx]\n\n plotdata = self.plotdata_for_scale[d]\n cost_scale, minidx_scale = self._find_min_cost_in_component(plotdata, self.x_axis_idx, self.y_axis_idx,\n x_axis_cost, y_axis_cost)\n mcf_scale_multiplier = plotdata[minidx_scale][0]\n mcf_scale_x = plotdata[minidx_scale][self.x_axis_idx]\n mcf_scale_y = plotdata[minidx_scale][self.y_axis_idx]\n\n if 'bias' in search:\n if not self.precompute_bias_data:\n raise ValueError(\n \"ERROR(UCC): Cannot perform minimization - instantiated without bias data computation\")\n plotdata = self.plotdata_for_bias[d]\n cost_bias, minidx_bias = self._find_min_cost_in_component(plotdata, self.x_axis_idx, self.y_axis_idx,\n x_axis_cost, y_axis_cost)\n mcf_bias_add = plotdata[minidx_bias][0]\n mcf_bias_x = plotdata[minidx_bias][self.x_axis_idx]\n mcf_bias_y = plotdata[minidx_bias][self.y_axis_idx]\n\n if 'bias' in search and 'scale' in search:\n if cost_bias < cost_scale:\n min_costs.append({'operation': 'bias', 'cost': cost_bias, 'modvalue': mcf_bias_add,\n 'new_x': mcf_bias_x, 'new_y': mcf_bias_y, 'original_cost': original_cost})\n else:\n min_costs.append({'operation': 'scale', 'cost': cost_scale, 'modvalue': mcf_scale_multiplier,\n 'new_x': mcf_scale_x, 'new_y': mcf_scale_y, 'original_cost': original_cost})\n elif 'scale' in search:\n min_costs.append({'operation': 'scale', 'cost': cost_scale, 'modvalue': mcf_scale_multiplier,\n 'new_x': mcf_scale_x, 'new_y': mcf_scale_y, 'original_cost': original_cost})\n elif 'bias' in search:\n min_costs.append({'operation': 'bias', 'cost': cost_bias, 'modvalue': mcf_bias_add,\n 'new_x': mcf_bias_x, 'new_y': mcf_bias_y, 'original_cost': original_cost})\n else:\n raise ValueError(\"(ERROR): Unknown search element (%s) requested.\" % \",\".join(search))\n\n if len(min_costs) < 2:\n return min_costs[0]\n else:\n return min_costs\n\n def get_specific_operating_point(self, req_x_axis_value=None, req_y_axis_value=None,\n req_critical_value=None, vary_bias=False):\n \"\"\"\n Finds corresponding operating point on the current UCC, given a point on either x or y axis. Returns\n a list of recipes how to achieve the point (x,y), for each component. If there is only one component,\n returns a single recipe dict.\n\n :param req_x_axis_value: requested x value on UCC (normalization status is taken from current display)\n :param req_y_axis_value: requested y value on UCC (normalization status is taken from current display)\n :param vary_bias: set to True when referring to bias-induced UCC (scale UCC default)\n :return: list of dicts (recipes), or a single dict\n \"\"\"\n if self.d is None:\n raise ValueError(\"ERROR(UCC): call fit() prior to using this method.\")\n if np.sum([req_x_axis_value is not None, req_y_axis_value is not None, req_critical_value is not None]) != 1:\n raise ValueError(\"ERROR(UCC): exactly one axis value must be requested at a time.\")\n if vary_bias and not self.precompute_bias_data:\n raise ValueError(\"ERROR(UCC): Cannot vary bias - instantiated without bias data computation\")\n xnorm = self.std_unit if self.norm_x_axis else 1.\n ynorm = self.std_unit if self.norm_y_axis else 1.\n recipe = []\n for dc in range(len(self.d)):\n plotdata = self.plotdata_for_bias[dc] if vary_bias else self.plotdata_for_scale[dc]\n if req_x_axis_value is not None:\n tgtidx = self.x_axis_idx\n req_value = req_x_axis_value * xnorm\n elif req_y_axis_value is not None:\n tgtidx = self.y_axis_idx\n req_value = req_y_axis_value * ynorm\n elif req_critical_value is not None:\n req_value = req_critical_value\n tgtidx = 0 # first element in plotdata is always the critical value (scale of bias)\n else:\n raise RuntimeError(\"Unhandled case\")\n closestidx = np.argmin(np.asarray([np.abs(p[tgtidx] - req_value) for p in plotdata]))\n recipe.append({'operation': ('bias' if vary_bias else 'scale'),\n 'modvalue': plotdata[closestidx][0],\n 'new_x': plotdata[closestidx][self.x_axis_idx] / xnorm,\n 'new_y': plotdata[closestidx][self.y_axis_idx] / ynorm})\n if len(recipe) < 2:\n return recipe[0]\n else:\n return recipe\n\n\n def _find_min_cost_in_component(self, plotdata, idx1, idx2, cost1, cost2):\n \"\"\"\n Find s minimum cost function value and corresp. position index in plotdata\n\n :param plotdata: liste of tuples\n :param idx1: idx of x-axis item within the tuple\n :param idx2: idx of y-axis item within the tuple\n :param cost1: cost factor for x-axis unit\n :param cost2: cost factor for y-axis unit\n :return: min cost value, index within plotdata where minimum occurs\n \"\"\"\n raw = [cost1 * i[idx1] + cost2 * i[idx2] for i in plotdata]\n minidx = np.argmin(raw)\n return raw[minidx], minidx\n\n def _sanitize_input(self, x):\n \"\"\"\n Replaces problematic values in input data (e.g, zero error bars)\n\n :param x: single matrix of input data [n, 3]\n :return: sanitized version of x\n \"\"\"\n if np.isclose(np.sum(x[:, 1]), 0.):\n raise ValueError(\"ERROR(UCC): Provided lower bands are all zero.\")\n if np.isclose(np.sum(x[:, 2]), 0.):\n raise ValueError(\"ERROR(UCC): Provided upper bands are all zero.\")\n for i in [1, 2]:\n if any(np.isclose(x[:, i], 0.)):\n print(\"WARN(UCC): some band values are 0. - REPLACING with positive minimum\")\n m = np.min(x[x[:, i] > 0, i])\n x = np.where(np.isclose(x, 0.), m, x)\n return x\n\n def _calc_avg_excess(self, d, lb, ub):\n \"\"\"\n Excess is amount an error bar overshoots actual\n\n :param d: pred-actual array\n :param lb: lower band\n :param ub: upper band\n :return: average excess over array\n \"\"\"\n excess = np.zeros(d.shape)\n posidx = np.where(d >= 0)[0]\n excess[posidx] = np.where(ub[posidx] - d[posidx] < 0., 0., ub[posidx] - d[posidx])\n negidx = np.where(d < 0)[0]\n excess[negidx] = np.where(lb[negidx] + d[negidx] < 0., 0., lb[negidx] + d[negidx])\n return np.mean(excess)\n\n def _calc_avg_deficit(self, d, lb, ub):\n \"\"\"\n Deficit is error bar insufficiency: bar falls short of actual\n\n :param d: pred-actual array\n :param lb: lower band\n :param ub: upper band\n :return: average deficit over array\n \"\"\"\n deficit = np.zeros(d.shape)\n posidx = np.where(d >= 0)[0]\n deficit[posidx] = np.where(- ub[posidx] + d[posidx] < 0., 0., - ub[posidx] + d[posidx])\n negidx = np.where(d < 0)[0]\n deficit[negidx] = np.where(- lb[negidx] - d[negidx] < 0., 0., - lb[negidx] - d[negidx])\n return np.mean(deficit)\n\n def _calc_missrate_bandwidth_excess_deficit(self, d, lb, ub, scale=1.0, bias=0.0):\n \"\"\"\n Calculates recall at a given scale/bias, average bandwidth and average excess\n\n :param d: delta\n :param lb: lower band\n :param ub: upper band\n :param scale: scale * (x + bias)\n :param bias:\n :return: miss rate, average bandwidth, avg excess, avg deficit\n \"\"\"\n abslband = scale * np.where((lb + bias) < 0., 0., lb + bias)\n absuband = scale * np.where((ub + bias) < 0., 0., ub + bias)\n recall = np.sum((d >= - abslband) & (d <= absuband)) / len(d)\n avgbandwidth = np.mean([absuband, abslband])\n avgexcess = self._calc_avg_excess(d, abslband, absuband)\n avgdeficit = self._calc_avg_deficit(d, abslband, absuband)\n return 1 - recall, avgbandwidth, avgexcess, avgdeficit\n\n def _calc_plotdata(self, d, lb, ub, vary_bias=False):\n \"\"\"\n Generates data necessary for various UCC metrics.\n\n :param d: delta (predicted - actual) vector\n :param ub: upper uncertainty bandwidth (above predicted)\n :param lb: lower uncertainty bandwidth (below predicted) - all positive (bandwidth)\n :param vary_bias: True will switch to additive bias instead of scale\n :return: list. Elements are tuples (varyvalue, missrate, bandwidth, excess, deficit)\n \"\"\"\n\n # step 1: collect critical scale or bias values\n critval = []\n for i in range(len(d)):\n if not vary_bias:\n if d[i] >= 0:\n critval.append(d[i] / ub[i])\n else:\n critval.append(-d[i] / lb[i])\n else:\n if d[i] >= 0:\n critval.append(d[i] - ub[i])\n else:\n critval.append(-lb[i] - d[i])\n critval = sorted(critval)\n plotdata = []\n for i in range(len(critval)):\n if not vary_bias:\n missrate, bandwidth, excess, deficit = self._calc_missrate_bandwidth_excess_deficit(d, lb, ub,\n scale=critval[i])\n else:\n missrate, bandwidth, excess, deficit = self._calc_missrate_bandwidth_excess_deficit(d, lb, ub,\n bias=critval[i])\n plotdata.append((critval[i], missrate, bandwidth, excess, deficit))\n\n return plotdata\n\n def get_AUUCC(self, vary_bias=False, aucfct=\"trapz\", partial_x=None, partial_y=None):\n \"\"\"\n returns approximate area under the curve on current coordinates, for each component.\n\n :param vary_bias: False == varies scale, True == varies bias\n :param aucfct: specifies AUC integrator (can be \"trapz\", \"simps\")\n :param partial_x: tuple (x_min, x_max) defining interval on x to calc a a partial AUC.\n The interval bounds refer to axes as visualized (ie. potentially normed)\n :param partial_y: tuple (y_min, y_max) defining interval on y to calc a a partial AUC. partial_x must be None.\n :return: list of floats with AUUCCs for each input component, or a single float, if there is only 1 component.\n \"\"\"\n if self.d is None:\n raise ValueError(\"ERROR(UCC): call fit() prior to using this method.\")\n if vary_bias and not self.precompute_bias_data:\n raise ValueError(\"ERROR(UCC): Cannot vary bias - instantiated without bias data computation\")\n if partial_x is not None and partial_y is not None:\n raise ValueError(\"ERROR(UCC): partial_x and partial_y can not be specified at the same time.\")\n assert(partial_x is None or (isinstance(partial_x, tuple) and len(partial_x)==2))\n assert(partial_y is None or (isinstance(partial_y, tuple) and len(partial_y)==2))\n\n # find starting point (where the x axis value starts to actually change)\n rv = []\n # do this for individual streams \n xind = self.x_axis_idx\n aucfct = simps if aucfct == \"simps\" else trapz\n for s in range(len(self.d)):\n plotdata = self.plotdata_for_bias[s] if vary_bias else self.plotdata_for_scale[s]\n prev = plotdata[0][xind]\n t = 1\n cval = plotdata[t", "instruction": "", "output": "" }, { "input": "][xind]\n while cval == prev and t < len(plotdata) - 1:\n t += 1\n prev = cval\n cval = plotdata[t][xind]\n startt = t - 1 # from here, it's a valid function\n endtt = len(plotdata)\n\n if startt >= endtt - 2:\n rvs = 0. # no area\n else:\n xnorm = self.std_unit if self.norm_x_axis else 1.\n ynorm = self.std_unit if self.norm_y_axis else 1.\n y=[(plotdata[i][self.y_axis_idx]) / ynorm for i in range(startt, endtt)]\n x=[(plotdata[i][self.x_axis_idx]) / xnorm for i in range(startt, endtt)]\n if partial_x is not None:\n from_i = self._find_closest_index(partial_x[0], x)\n to_i = self._find_closest_index(partial_x[1], x) + 1\n elif partial_y is not None:\n from_i = self._find_closest_index(partial_y[0], y)\n to_i = self._find_closest_index(partial_y[1], y)\n if from_i > to_i: # y is in reverse order\n from_i, to_i = to_i, from_i\n to_i += 1 # as upper bound in array indexing\n else:\n from_i = 0\n to_i = len(x)\n to_i = min(to_i, len(x))\n if to_i < from_i:\n raise ValueError(\"ERROR(UCC): Failed to find an appropriate partial-AUC interval in the data.\")\n if to_i - from_i < 2:\n raise RuntimeError(\"ERROR(UCC): There are too few samples (1) in the partial-AUC interval specified\")\n rvs = aucfct(x=x[from_i:to_i], y=y[from_i:to_i])\n rv.append(rvs)\n if len(rv) < 2:\n return rv[0]\n else:\n return rv\n\n @ staticmethod\n def _find_closest_index(value, array):\n \"\"\"\n Returns an index of the 'array' element closest in value to 'value'\n\n :param value:\n :param array:\n :return:\n \"\"\"\n return np.argmin(np.abs(np.asarray(array)-value))\n\n def _get_single_OP(self, d, lb, ub, scale=1., bias=0.):\n \"\"\"\n Returns Operating Point for original input data, on coordinates currently set up, given a scale/bias.\n\n :param scale:\n :param bias: \n :return: single tuple (x point, y point, unit of x, unit of y)\n \"\"\"\n xnorm = self.std_unit if self.norm_x_axis else 1.\n ynorm = self.std_unit if self.norm_y_axis else 1.\n auxop = self._calc_missrate_bandwidth_excess_deficit(d, lb, ub, scale=scale, bias=bias)\n op = [0.] + [i for i in auxop] # mimic plotdata (first element ignored here)\n return (op[self.x_axis_idx] / xnorm, op[self.y_axis_idx] / ynorm, xnorm, ynorm)\n\n def get_OP(self, scale=1., bias=0.):\n \"\"\"\n Returns all Operating Points for original input data, on coordinates currently set up, given a scale/bias.\n\n :param scale:\n :param bias:\n :return: list of tuples (x point, y point, unit of x, unit of y) or a single tuple if there is only\n 1 component.\n \"\"\"\n if self.d is None:\n raise ValueError(\"ERROR(UCC): call fit() prior to using this method.\")\n op = []\n for dc in range(len(self.d)):\n op.append(self._get_single_OP(self.d[dc], self.lb[dc], self.ub[dc], scale=scale, bias=bias))\n if len(op) < 2:\n return op[0]\n else:\n return op\n\n def plot_UCC(self, titlestr='', syslabel='model', outfn=None, vary_bias=False, markers=None,\n xlim=None, ylim=None, **kwargs):\n \"\"\" Will plot/display the UCC based on current data and coordinates. Multiple curves will be shown\n if there are multiple data components (via fit())\n\n :param titlestr: Plot title string\n :param syslabel: list is label strings to appear in the plot legend. Can be single, if one component.\n :param outfn: base name of an image file to be created (will append .png before creating)\n :param vary_bias: True will switch to varying additive bias (default is multiplicative scale)\n :param markers: None or a list of marker styles to be used for each curve.\n List must be same or longer than number of components.\n Markers can be one among these ['o', 's', 'v', 'D', '+'].\n :param xlim: tuples or lists of specifying the range for the x axis, or None (auto)\n :param ylim: tuples or lists of specifying the range for the y axis, or None (auto)\n :param `**kwargs`: Additional arguments passed to the main plot call.\n\n :return: list of areas under the curve (or single area, if one data component)\n list of operating points (or single op): format of an op is tuple (xaxis value, yaxis value, xunit, yunit)\n \"\"\"\n if self.d is None:\n raise ValueError(\"ERROR(UCC): call fit() prior to using this method.\")\n if vary_bias and not self.precompute_bias_data:\n raise ValueError(\"ERROR(UCC): Cannot vary bias - instantiated without bias data computation\")\n if not isinstance(syslabel, list):\n syslabel = [syslabel]\n assert (len(syslabel) == len(self.d))\n assert (markers is None or (isinstance(markers, list) and len(markers) >= len(self.d)))\n # main plot of (possibly multiple) datasets\n plt.figure()\n xnorm = self.std_unit if self.norm_x_axis else 1.\n ynorm = self.std_unit if self.norm_y_axis else 1.\n op_info = []\n auucc = self.get_AUUCC(vary_bias=vary_bias)\n auucc = [auucc] if not isinstance(auucc, list) else auucc\n for s in range(len(self.d)):\n # original operating point\n x_op, y_op, x_unit, y_unit = self._get_single_OP(self.d[s], self.lb[s], self.ub[s])\n op_info.append((x_op, y_op, x_unit, y_unit))\n # display chart\n plotdata = self.plotdata_for_scale[s] if not vary_bias else self.plotdata_for_bias[s]\n axisX_data = [i[self.x_axis_idx] / xnorm for i in plotdata]\n axisY_data = [i[self.y_axis_idx] / ynorm for i in plotdata]\n marker = None\n if markers is not None: marker = markers[s]\n p = plt.plot(axisX_data, axisY_data, label=syslabel[s] + (\" (AUC=%.3f)\" % auucc[s]), marker=marker, **kwargs)\n if s + 1 == len(self.d):\n oplab = 'OP'\n else:\n oplab = None\n plt.plot(x_op, y_op, marker='o', color=p[0].get_color(), label=oplab, markerfacecolor='w',\n markeredgewidth=1.5, markeredgecolor=p[0].get_color())\n axisX_label = self.axes_idx2descr[self.x_axis_idx]\n axisY_label = self.axes_idx2descr[self.y_axis_idx]\n axisX_units = \"(raw)\" if np.isclose(xnorm, 1.0) else \"[in std deviations]\"\n axisY_units = \"(raw)\" if np.isclose(ynorm, 1.0) else \"[in std deviations]\"\n axisX_label += ' ' + axisX_units\n axisY_label += ' ' + axisY_units\n if ylim is not None:\n plt.ylim(ylim)\n if xlim is not None:\n plt.xlim(xlim)\n plt.xlabel(axisX_label)\n plt.ylabel(axisY_label)\n plt.legend()\n plt.title(titlestr)\n plt.grid()\n if outfn is None:\n plt.show()\n else:\n plt.savefig(outfn)\n if len(auucc) < 2:\n auucc = auucc[0]\n op_info = op_info[0]\n return auucc, op_info\n from .uncertainty_characteristics_curve import UncertaintyCharacteristicsCurve\n import abc\nimport sys\n\n# Ensure compatibility with Python 2/3\nif sys.version_info >= (3, 4):\n ABC = abc.ABC\nelse:\n ABC = abc.ABCMeta(str('ABC'), (), {})\n\n\nclass BuiltinUQ(ABC):\n \"\"\" BuiltinUQ is the base class for any algorithm that has UQ built into it.\n \"\"\"\n\n def __init__(self, *argv, **kwargs):\n \"\"\" Initialize a BuiltinUQ object.\n \"\"\"\n\n @abc.abstractmethod\n def fit(self, *argv, **kwargs):\n \"\"\" Learn the UQ related parameters..\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def predict(self, *argv, **kwargs):\n \"\"\" Method to obtain the predicitve uncertainty, this can return the total, epistemic and/or aleatoric\n uncertainty in the predictions.\n \"\"\"\n raise NotImplementedError\n\n def set_params(self, **parameters):\n for parameter, value in parameters.items():\n setattr(self, parameter, value)\n return self\n\n\n import abc\nimport sys\n\n# Ensure compatibility with Python 2/3\nif sys.version_info >= (3, 4):\n ABC = abc.ABC\nelse:\n ABC = abc.ABCMeta(str('ABC'), (), {})\n\n\nclass PostHocUQ(ABC):\n \"\"\" PostHocUQ is the base class for any algorithm that quantifies uncertainty of a pre-trained model.\n \"\"\"\n\n def __init__(self, *argv, **kwargs):\n \"\"\" Initialize a BuiltinUQ object.\n \"\"\"\n\n @abc.abstractmethod\n def _process_pretrained_model(self, *argv, **kwargs):\n \"\"\" Method to process the pretrained model that requires UQ.\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def predict(self, *argv, **kwargs):\n \"\"\" Method to obtain the predicitve uncertainty, this can return the total, epistemic and/or aleatoric\n uncertainty in the predictions.\n \"\"\"\n raise NotImplementedError\n\n def set_params(self, **parameters):\n for parameter, value in parameters.items():\n setattr(self, parameter, value)\n return self\n\n def get_params(self):\n \"\"\"\n This method should not take any arguments and returns a dict of the __init__ parameters.\n\n \"\"\"\n raise NotImplementedError\n from collections import namedtuple\n\nimport numpy as np\nimport torch\nfrom scipy.stats import norm\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import TensorDataset\nfrom uq360.algorithms.builtinuq import BuiltinUQ\nfrom uq360.models.heteroscedastic_mlp import GaussianNoiseMLPNet as _MLPNet\n\nnp.random.seed(42)\ntorch.manual_seed(42)\n\nclass HeteroscedasticRegression(BuiltinUQ):\n \"\"\" Wrapper for heteroscedastic regression. We learn to predict targets given features, \n assuming that the targets are noisy and that the amount of noise varies between data points. \n https://en.wikipedia.org/wiki/Heteroscedasticity\n \"\"\"\n\n def __init__(self, model_type=None, model=None, config=None, device=None, verbose=True):\n \"\"\"\n Args:\n model_type: The base model architecture. Currently supported values are [mlp].\n mlp modeltype learns a multi-layer perceptron with a heteroscedastic Gaussian likelihood. Both the\n mean and variance of the Gaussian are functions of the data point ->git N(y_n | mlp_mu(x_n), mlp_var(x_n))\n model: (optional) The prediction model. Currently support pytorch models that returns mean and log variance.\n config: dictionary containing the config parameters for the model.\n device: device used for pytorch models ignored otherwise.\n verbose: if True, print statements with the progress are enabled.\n \"\"\"\n\n super(HeteroscedasticRegression).__init__()\n self.config = config\n self.device = device\n self.verbose = verbose\n if model_type == \"mlp\":\n self.model_type = model_type\n self.model = _MLPNet(\n num_features=self.config[\"num_features\"],\n num_outputs=self.config[\"num_outputs\"],\n num_hidden=self.config[\"num_hidden\"],\n )\n\n elif model_type == \"custom\":\n self.model_type = model_type\n self.model = model\n\n else:\n raise NotImplementedError\n\n def get_params(self, deep=True):\n return {\"model_type\": self.model_type, \"config\": self.config, \"model\": self.model,\n \"device\": self.device, \"verbose\": self.verbose}\n\n def _loss(self, y_true, y_pred_mu, y_pred_log_var):\n return torch.mean(0.5 * torch.exp(-y_pred_log_var) * torch.abs(y_true - y_pred_mu) ** 2 +\n 0.5 * y_pred_log_var)\n\n def fit(self, X, y):\n \"\"\" Fit the Heteroscedastic Regression model.\n\n Args:\n X: array-like of shape (n_samples, n_features).\n Features vectors of the training data.\n y: array-like of shape (n_samples,) or (n_samples, n_targets)\n Target values\n\n Returns:\n self\n\n \"\"\"\n X = torch.from_numpy(X).float().to(self.device)\n y = torch.from_numpy(y).float().to(self.device)\n\n dataset_loader = DataLoader(\n TensorDataset(X,y),\n batch_size=self.config[\"batch_size\"]\n )\n optimizer = torch.optim.Adam(self.model.parameters(), lr=self.config[\"lr\"])\n\n for epoch in range(self.config[\"num_epochs\"]):\n avg_loss = 0.0\n for batch_x, batch_y in dataset_loader:\n self.model.train()\n batch_y_pred_mu, batch_y_pred_log_var = self.model(batch_x)\n loss = self.model.loss(batch_y, batch_y_pred_mu, batch_y_pred_log_var)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n avg_loss += loss.item()/len(dataset_loader)\n\n ", "instruction": "", "output": "" }, { "input": "if self.verbose:\n print(\"Epoch: {}, loss = {}\".format(epoch, avg_loss))\n\n return self\n\n def predict(self, X, return_dists=False):\n \"\"\"\n Obtain predictions for the test points.\n\n In addition to the mean and lower/upper bounds, also returns epistemic uncertainty (return_epistemic=True)\n and full predictive distribution (return_dists=True).\n\n Args:\n X: array-like of shape (n_samples, n_features).\n Features vectors of the test points.\n return_dists: If True, the predictive distribution for each instance using scipy distributions is returned.\n\n Returns:\n namedtuple: A namedtupe that holds\n\n y_mean: ndarray of shape (n_samples, [n_output_dims])\n Mean of predictive distribution of the test points.\n y_lower: ndarray of shape (n_samples, [n_output_dims])\n Lower quantile of predictive distribution of the test points.\n y_upper: ndarray of shape (n_samples, [n_output_dims])\n Upper quantile of predictive distribution of the test points.\n dists: list of predictive distribution as `scipy.stats` objects with length n_samples.\n Only returned when `return_dists` is True.\n \"\"\"\n\n self.model.eval()\n\n X = torch.from_numpy(X).float().to(self.device)\n dataset_loader = DataLoader(\n X,\n batch_size=self.config[\"batch_size\"]\n )\n\n y_mean_list = []\n y_log_var_list = []\n for batch_x in dataset_loader:\n batch_y_pred_mu, batch_y_pred_log_var = self.model(batch_x)\n y_mean_list.append(batch_y_pred_mu.data.cpu().numpy())\n y_log_var_list.append(batch_y_pred_log_var.data.cpu().numpy())\n\n y_mean = np.concatenate(y_mean_list)\n y_log_var = np.concatenate(y_log_var_list)\n y_std = np.sqrt(np.exp(y_log_var))\n y_lower = y_mean - 2.0*y_std\n y_upper = y_mean + 2.0*y_std\n\n Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])\n res = Result(y_mean, y_lower, y_upper)\n\n if return_dists:\n dists = [norm(loc=y_mean[i], scale=y_std[i]) for i in range(y_mean.shape[0])]\n Result = namedtuple('res', Result._fields + ('y_dists',))\n res = Result(*res, y_dists=dists)\n\n return res\n from .heteroscedastic_regression import HeteroscedasticRegression from collections import namedtuple\n\nimport numpy as np\n\nfrom sklearn.calibration import CalibratedClassifierCV\nfrom sklearn.preprocessing import LabelEncoder\n\nfrom uq360.utils.misc import DummySklearnEstimator\nfrom uq360.algorithms.posthocuq import PostHocUQ\n\n\nclass ClassificationCalibration(PostHocUQ):\n \"\"\"Post hoc calibration of classification models. Currently wraps `CalibratedClassifierCV` from sklearn and allows\n non-sklearn models to be calibrated.\n\n \"\"\"\n def __init__(self, num_classes, fit_mode=\"features\", method='isotonic', base_model_prediction_func=None):\n \"\"\"\n\n Args:\n num_classes: number of classes.\n fit_mode: features or probs. If probs the `fit` and `predict` operate on the base models probability scores,\n useful when these are precomputed.\n method: isotonic or sigmoid.\n base_model_prediction_func: the function that takes in the input features and produces base model's\n probability scores. This is ignored when operating in `probs` mode.\n \"\"\"\n super(ClassificationCalibration).__init__()\n if fit_mode == \"probs\":\n # In this case, the fit assumes that it receives the probability scores of the base model.\n # create a dummy estimator\n self.base_model = DummySklearnEstimator(num_classes, lambda x: x)\n else:\n self.base_model = DummySklearnEstimator(num_classes, base_model_prediction_func)\n self.method = method\n\n def get_params(self, deep=True):\n return {\"num_classes\": self.num_classes, \"fit_mode\": self.fit_mode, \"method\": self.method,\n \"base_model_prediction_func\": self.base_model_prediction_func}\n\n def _process_pretrained_model(self, base_model):\n return base_model\n\n def fit(self, X, y):\n \"\"\" Fits calibration model using the provided calibration set.\n\n Args:\n X: array-like of shape (n_samples, n_features) or (n_samples, n_classes).\n Features vectors of the training data or the probability scores from the base model.\n y: array-like of shape (n_samples,) or (n_samples, n_targets)\n Target values\n\n Returns:\n self\n\n \"\"\"\n\n self.base_model.label_encoder_ = LabelEncoder().fit(y)\n self.calib_model = CalibratedClassifierCV(base_estimator=self.base_model,\n cv=\"prefit\",\n method=self.method)\n self.calib_model.fit(X, y)\n\n return self\n\n def predict(self, X):\n \"\"\"\n Obtain calibrated predictions for the test points.\n\n Args:\n X: array-like of shape (n_samples, n_features) or (n_samples, n_classes).\n Features vectors of the training data or the probability scores from the base model.\n\n Returns:\n namedtuple: A namedtupe that holds\n\n y_pred: ndarray of shape (n_samples,)\n Predicted labels of the test points.\n y_prob: ndarray of shape (n_samples, n_classes)\n Predicted probability scores of the classes.\n\n \"\"\"\n y_prob = self.calib_model.predict_proba(X)\n if len(np.shape(y_prob)) == 1:\n y_pred_labels = y_prob > 0.5\n\n else:\n y_pred_labels = np.argmax(y_prob, axis=1)\n\n Result = namedtuple('res', ['y_pred', 'y_prob'])\n res = Result(y_pred_labels, y_prob)\n\n return res\n from .classification_calibration import ClassificationCalibration\n from collections import namedtuple\n\nimport botorch\nimport gpytorch\nimport numpy as np\nimport torch\nfrom botorch.models import SingleTaskGP\nfrom botorch.utils.transforms import normalize\nfrom gpytorch.constraints import GreaterThan\nfrom scipy.stats import norm\nfrom sklearn.preprocessing import StandardScaler\n\nfrom uq360.algorithms.builtinuq import BuiltinUQ\n\nnp.random.seed(42)\ntorch.manual_seed(42)\n\n\nclass HomoscedasticGPRegression(BuiltinUQ):\n \"\"\" A wrapper around Botorch SingleTask Gaussian Process Regression [1]_ with homoscedastic noise.\n\n References:\n .. [1] https://botorch.org/api/models.html#singletaskgp\n\n \"\"\"\n\n def __init__(self,\n kernel=gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel()),\n likelihood=None,\n config=None):\n \"\"\"\n Args:\n kernel: gpytorch kernel function with default set to `RBFKernel` with output scale.\n likelihood: gpytorch likelihood function with default set to `GaussianLikelihood`.\n config: dictionary containing the config parameters for the model.\n \"\"\"\n\n super(HomoscedasticGPRegression).__init__()\n self.config = config\n self.kernel = kernel\n self.likelihood = likelihood\n self.model = None\n self.scaler = StandardScaler()\n self.X_bounds = None\n\n def get_params(self, deep=True):\n return {\"kernel\": self.kernel, \"likelihood\": self.likelihood, \"config\": self.config}\n\n def fit(self, X, y, **kwargs):\n \"\"\"\n Fit the GP Regression model.\n\n Additional arguments relevant for SingleTaskGP fitting can be passed to this function.\n\n Args:\n X: array-like of shape (n_samples, n_features).\n Features vectors of the training data.\n y: array-like of shape (n_samples,) or (n_samples, n_targets)\n Target values\n **kwargs: Additional arguments relevant for SingleTaskGP fitting.\n\n Returns:\n self\n\n \"\"\"\n y = self.scaler.fit_transform(y)\n X, y = torch.tensor(X), torch.tensor(y)\n self.X_bounds = X_bounds = torch.stack([X.min() * torch.ones(X.shape[1]),\n X.max() * torch.ones(X.shape[1])])\n\n X = normalize(X, X_bounds)\n\n model_homo = SingleTaskGP(train_X=X, train_Y=y, covar_module=self.kernel, likelihood=self.likelihood, **kwargs)\n model_homo.likelihood.noise_covar.register_constraint(\"raw_noise\", GreaterThan(1e-5))\n model_homo_marginal_log_lik = gpytorch.mlls.ExactMarginalLogLikelihood(model_homo.likelihood, model_homo)\n botorch.fit.fit_gpytorch_model(model_homo_marginal_log_lik)\n\n model_homo_marginal_log_lik.eval()\n\n self.model = model_homo_marginal_log_lik\n self.inferred_observation_noise = self.scaler.inverse_transform(self.model.likelihood.noise.detach().numpy()[0].reshape(1,1)).squeeze()\n\n return self\n\n def predict(self, X, return_dists=False, return_epistemic=False, return_epistemic_dists=False):\n \"\"\"\n Obtain predictions for the test points.\n\n In addition to the mean and lower/upper bounds, also returns epistemic uncertainty (return_epistemic=True)\n and full predictive distribution (return_dists=True).\n\n Args:\n X: array-like of shape (n_samples, n_features).\n Features vectors of the test points.\n return_dists: If True, the predictive distribution for each instance using scipy distributions is returned.\n return_epistemic: if True, the epistemic upper and lower bounds are returned.\n return_epistemic_dists: If True, the epistemic distribution for each instance using scipy distributions\n is returned.\n\n Returns:\n namedtuple: A namedtuple that holds\n\n y_mean: ndarray of shape (n_samples, [n_output_dims])\n Mean of predictive distribution of the test points.\n y_lower: ndarray of shape (n_samples, [n_output_dims])\n Lower quantile of predictive distribution of the test points.\n y_upper: ndarray of shape (n_samples, [n_output_dims])\n Upper quantile of predictive distribution of the test points.\n y_lower_epistemic: ndarray of shape (n_samples, [n_output_dims])\n Lower quantile of epistemic component of the predictive distribution of the test points.\n Only returned when `return_epistemic` is True.\n y_upper_epistemic: ndarray of shape (n_samples, [n_output_dims])\n Upper quantile of epistemic component of the predictive distribution of the test points.\n Only returned when `return_epistemic` is True.\n dists: list of predictive distribution as `scipy.stats` objects with length n_samples.\n Only returned when `return_dists` is True.\n \"\"\"\n X = torch.tensor(X)\n\n X_test_norm = normalize(X, self.X_bounds)\n\n self.model.eval()\n with torch.no_grad():\n posterior = self.model.model.posterior(X_test_norm)\n y_mean = posterior.mean\n #y_epi_std = torch.sqrt(posterior.variance)\n y_lower_epistemic, y_upper_epistemic = posterior.mvn.confidence_region()\n\n predictive_posterior = self.model.model.posterior(X_test_norm, observation_noise=True)\n #y_std = torch.sqrt(predictive_posterior.variance)\n y_lower_total, y_upper_total = predictive_posterior.mvn.confidence_region()\n\n y_mean, y_lower, y_upper, y_lower_epistemic, y_upper_epistemic = self.scaler.inverse_transform(y_mean.numpy()).squeeze(), \\\\\n self.scaler.inverse_transform(y_lower_total.numpy()).squeeze(),\\\\\n self.scaler.inverse_transform(y_upper_total.numpy()).squeeze(),\\\\\n self.scaler.inverse_transform(y_lower_epistemic.numpy()).squeeze(),\\\\\n self.scaler.inverse_transform(y_upper_epistemic.numpy()).squeeze()\n\n y_epi_std = (y_upper_epistemic - y_lower_epistemic) / 4.0\n y_std = (y_upper_total - y_lower_total) / 4.0\n\n Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])\n res = Result(y_mean, y_lower, y_upper)\n\n if return_epistemic:\n Result = namedtuple('res', Result._fields + ('y_lower_epistemic', 'y_upper_epistemic',))\n res = Result(*res, y_lower_epistemic=y_lower_epistemic, y_upper_epistemic=y_upper_epistemic)\n\n if return_dists:\n dists = [norm(loc=y_mean[i], scale=y_std[i]) for i in range(y_mean.shape[0])]\n Result = namedtuple('res', Result._fields + ('y_dists',))\n res = Result(*res, y_dists=dists)\n\n if return_epistemic_dists:\n epi_dists = [norm(loc=y_mean[i], scale=y_epi_std[i]) for i in range(y_mean.shape[0])]\n Result = namedtuple('res', Result._fields + ('y_epistemic_dists',))\n res = Result(*res, y_epistemic_dists=epi_dists)\n\n return res\n\n from .homoscedastic_gaussian_process_regression import HomoscedasticGPRegression from collections import namedtuple\n\nfrom sklearn.ensemble import GradientBoostingRegressor\n\nfrom uq360.algorithms.builtinuq import BuiltinUQ\n\n\nclass QuantileRegression(BuiltinUQ):\n \"\"\"Quantile Regression uses quantile loss and learns two separate models for the upper and lower quantile\n to obtain the prediction intervals.\n \"\"\"\n\n def __init__(self, model_type=\"gbr", "instruction": "", "output": "" }, { "input": "\", config=None):\n \"\"\"\n Args:\n model_type: The base model used for predicting a quantile. Currently supported values are [gbr].\n gbr is sklearn GradientBoostingRegressor.\n config: dictionary containing the config parameters for the model.\n \"\"\"\n\n super(QuantileRegression).__init__()\n if config is not None:\n self.config = config\n else:\n self.config = {}\n if \"alpha\" not in self.config:\n self.config[\"alpha\"] = 0.95\n if model_type == \"gbr\":\n self.model_type = model_type\n self.model_mean = GradientBoostingRegressor(\n loss='ls',\n n_estimators=self.config[\"n_estimators\"],\n max_depth=self.config[\"max_depth\"],\n learning_rate=self.config[\"learning_rate\"],\n min_samples_leaf=self.config[\"min_samples_leaf\"],\n min_samples_split=self.config[\"min_samples_split\"]\n )\n self.model_upper = GradientBoostingRegressor(\n loss='quantile',\n alpha=self.config[\"alpha\"],\n n_estimators=self.config[\"n_estimators\"],\n max_depth=self.config[\"max_depth\"],\n learning_rate=self.config[\"learning_rate\"],\n min_samples_leaf=self.config[\"min_samples_leaf\"],\n min_samples_split=self.config[\"min_samples_split\"]\n )\n self.model_lower = GradientBoostingRegressor(\n loss='quantile',\n alpha=1.0 - self.config[\"alpha\"],\n n_estimators=self.config[\"n_estimators\"],\n max_depth=self.config[\"max_depth\"],\n learning_rate=self.config[\"learning_rate\"],\n min_samples_leaf=self.config[\"min_samples_leaf\"],\n min_samples_split=self.config[\"min_samples_split\"])\n\n else:\n raise NotImplementedError\n\n def get_params(self, deep=True):\n return {\"model_type\": self.model_type, \"config\": self.config}\n\n def fit(self, X, y):\n \"\"\" Fit the Quantile Regression model.\n\n Args:\n X: array-like of shape (n_samples, n_features).\n Features vectors of the training data.\n y: array-like of shape (n_samples,) or (n_samples, n_targets)\n Target values\n\n Returns:\n self\n\n \"\"\"\n\n self.model_mean.fit(X, y)\n self.model_lower.fit(X, y)\n self.model_upper.fit(X, y)\n\n return self\n\n def predict(self, X):\n \"\"\"\n Obtain predictions for the test points.\n\n In addition to the mean and lower/upper bounds, also returns epistemic uncertainty (return_epistemic=True)\n and full predictive distribution (return_dists=True).\n\n Args:\n X: array-like of shape (n_samples, n_features).\n Features vectors of the test points.\n\n Returns:\n namedtuple: A namedtupe that holds\n\n y_mean: ndarray of shape (n_samples, [n_output_dims])\n Mean of predictive distribution of the test points.\n y_lower: ndarray of shape (n_samples, [n_output_dims])\n Lower quantile of predictive distribution of the test points.\n y_upper: ndarray of shape (n_samples, [n_output_dims])\n Upper quantile of predictive distribution of the test points.\n \"\"\"\n\n y_mean = self.model_mean.predict(X)\n y_lower = self.model_lower.predict(X)\n y_upper = self.model_upper.predict(X)\n\n Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])\n res = Result(y_mean, y_lower, y_upper)\n\n return res\n from .quantile_regression import QuantileRegression\n import inspect\nfrom collections import namedtuple\n\nimport numpy as np\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.exceptions import NotFittedError\nfrom uq360.algorithms.posthocuq import PostHocUQ\n\n\nclass BlackboxMetamodelRegression(PostHocUQ):\n \"\"\" Extracts confidence scores from black-box regression models using a meta-model [2]_ .\n\n References:\n .. [2] Chen, Tongfei, et al. Confidence scoring using whitebox meta-models with linear classifier probes.\n The 22nd International Conference on Artificial Intelligence and Statistics. PMLR, 2019.\n\n \"\"\"\n\n def _create_named_model(self, mdltype, config):\n \"\"\"\n Instantiates a model by name passed in 'mdltype'\n\n :param mdltype: string with name (must be supprted)\n :param config: dict with args passed in the instantiation call\n :return: mdl instance\n \"\"\"\n assert (isinstance(mdltype, str))\n if mdltype == 'gbr':\n mdl = GradientBoostingRegressor(**config)\n else:\n raise NotImplementedError(\"ERROR: Requested model type unknown: \\\\\"%s\\\\\"\" % mdltype)\n return mdl\n\n def _get_model_instance(self, model, config):\n \"\"\"\n Returns an instance of a model based on (a) a desired name or (b) passed in class, or\n (c) passed in instance\n\n :param model: string, class, or instance. Class and instance must have certain methods callable.\n :param config: dict with args passed in during the instantiation\n :return: model instance\n \"\"\"\n assert (model is not None and config is not None)\n if isinstance(model, str): # 'model' is a name, create it\n mdl = self._create_named_model(model, config)\n elif inspect.isclass(model): # 'model' is a class, instantiate it\n mdl = model(**config)\n else: # 'model' is an instance, register it\n mdl = model\n if not all([hasattr(mdl, key) and callable(getattr(mdl, key)) for key in self.callable_keys]):\n raise ValueError(\"ERROR: Passed model/method failed the interface test. Methods required: %s\" %\n ','.join(self.callable_keys))\n return mdl\n\n def __init__(self, base_model=None, meta_model=None, base_config=None, meta_config=None, random_seed=42):\n \"\"\"\n\n :param base_model: Base model. Can be:\n (1) None (default mdl will be set up),\n (2) Named model (e.g., 'gbr'),\n (3) Base model class declaration (e.g., sklearn.linear_model.LinearRegressor). Will instantiate.\n (4) Model instance (instantiated outside). Will be re-used. Must have required callable methods.\n Note: user-supplied classes and models must have certain callable methods ('predict', 'fit')\n and be capable of raising NotFittedError.\n :param meta_model: Meta model. Same values possible as with 'base_model'\n :param base_config: None or a params dict to be passed to 'base_model' at instantiation\n :param meta_config: None or a params dict to be passed to 'meta_model' at instantiation\n :param random_seed: seed used in the various pipeline steps\n \"\"\"\n super(BlackboxMetamodelRegression).__init__()\n self.random_seed = random_seed\n self.callable_keys = ['predict', 'fit'] # required methods - must be present in models passed in\n self.base_model_default = 'gbr'\n self.meta_model_default = 'gbr'\n self.base_config_default = {'loss': 'ls', 'n_estimators': 300, 'max_depth': 10, 'learning_rate': 0.001,\n 'min_samples_leaf': 10, 'min_samples_split': 10, 'random_state': self.random_seed}\n self.meta_config_default = {'loss': 'quantile', 'alpha': 0.95, 'n_estimators': 300, 'max_depth': 10,\n 'learning_rate': 0.001, 'min_samples_leaf': 10, 'min_samples_split': 10,\n 'random_state': self.random_seed}\n self.base_config = base_config if base_config is not None else self.base_config_default\n self.meta_config = meta_config if meta_config is not None else self.meta_config_default\n self.base_model = None\n self.meta_model = None\n self.base_model = self._get_model_instance(base_model if base_model is not None else self.base_model_default,\n self.base_config)\n self.meta_model = self._get_model_instance(meta_model if meta_model is not None else self.meta_model_default,\n self.meta_config)\n\n def get_params(self, deep=True):\n return {\"base_model\": self.base_model, \"meta_model\": self.meta_model, \"base_config\": self.base_config,\n \"meta_config\": self.meta_config, \"random_seed\": self.random_seed}\n\n def fit(self, X, y, meta_fraction=0.2, randomize_samples=True, base_is_prefitted=False,\n meta_train_data=(None, None)):\n \"\"\"\n Fit base and meta models.\n\n :param X: input to the base model\n :param y: ground truth for the base model\n :param meta_fraction: float in [0,1] - a fractional size of the partition carved out to train the meta model\n (complement will be used to train the base model)\n :param randomize_samples: use shuffling when creating partitions\n :param base_is_prefitted: Setting True will skip fitting the base model (useful for base models that have been\n instantiated outside/by the user and are already fitted.\n :param meta_train_data: User supplied data to train the meta model. Note that this option should only be used\n with 'base_is_prefitted'==True. Pass a tuple meta_train_data=(X_meta, y_meta) to activate.\n Note that (X,y,meta_fraction, randomize_samples) will be ignored in this mode.\n :return: self\n \"\"\"\n X = np.asarray(X)\n y = np.asarray(y)\n assert(len(meta_train_data)==2)\n if meta_train_data[0] is None:\n X_base, X_meta, y_base, y_meta = train_test_split(X, y, shuffle=randomize_samples, test_size=meta_fraction,\n random_state=self.random_seed)\n else:\n if not base_is_prefitted:\n raise ValueError(\"ERROR: fit(): base model must be pre-fitted to use the 'meta_train_data' option\")\n X_base = y_base = None\n X_meta = meta_train_data[0]\n y_meta = meta_train_data[1]\n # fit the base model\n if not base_is_prefitted:\n self.base_model.fit(X_base, y_base)\n # get input for the meta model from the base\n try:\n y_hat_meta = self.base_model.predict(X_meta)\n except NotFittedError as e:\n raise RuntimeError(\"ERROR: fit(): The base model appears not pre-fitted (%s)\" % repr(e))\n # used base input and output as meta input\n X_meta_in = self._process_pretrained_model(X_meta, y_hat_meta)\n # train meta model to predict abs diff\n self.meta_model.fit(X_meta_in, np.abs(y_hat_meta - y_meta))\n return self\n\n def _process_pretrained_model(self, X, y_hat):\n \"\"\"\n Given the original input features and the base output probabilities, generate input features\n to train a meta model. Current implementation copies all input features and appends.\n\n :param X: numpy [nsamples, dim]\n :param y_hat: [nsamples,]\n :return: array with new features [nsamples, newdim]\n \"\"\"\n y_hat_meta_prime = np.expand_dims(y_hat, -1) if len(y_hat.shape) < 2 else y_hat\n X_meta_in = np.hstack([X, y_hat_meta_prime])\n return X_meta_in\n\n def predict(self, X):\n \"\"\"\n Generate prediction and uncertainty bounds for data X.\n\n :param X: input features\n :return: namedtuple: A namedtuple that holds\n\n y_mean: ndarray of shape (n_samples, [n_output_dims])\n Mean of predictive distribution of the test points.\n y_lower: ndarray of shape (n_samples, [n_output_dims])\n Lower quantile of predictive distribution of the test points.\n y_upper: ndarray of shape (n_samples, [n_output_dims])\n Upper quantile of predictive distribution of the test points.\n\n \"\"\"\n y_hat = self.base_model.predict(X)\n y_hat_prime = np.expand_dims(y_hat, -1) if len(y_hat.shape) < 2 else y_hat\n X_meta_in = np.hstack([X, y_hat_prime])\n z_hat = self.meta_model.predict(X_meta_in)\n\n Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])\n res = Result(y_hat, y_hat - z_hat, y_hat + z_hat)\n\n return res\n import inspect\nfrom collections import namedtuple\n\nimport numpy as np\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.exceptions import NotFittedError\nfrom uq360.algorithms.posthocuq import PostHocUQ\n\n\nclass BlackboxMetamodelClassification(PostHocUQ):\n \"\"\" Extracts confidence scores from black-box classification models using a meta-model [4]_ .\n\n References:\n .. [4] Chen, Tongfei, et al. \"Confidence scoring using whitebox meta-models with linear classifier probes.\"\n The 22nd International Conference on Artificial Intelligence and Statistics. PMLR, 2019.\n \"\"\"\n\n def _create_named_model(self, mdltype, config):\n \"\"\" Instantiates a model by name passed in 'mdltype'.\n\n Args:\n mdltype: string with name (must be supported)\n config: dict with args passed in the instantiation call\n Returns:\n mdl instance\n \"\"\"\n assert (isinstance(mdltype, str))\n if mdltype == 'lr':\n mdl = LogisticRegression(**config)\n elif mdltype == 'gbm':\n mdl = GradientBoostingClassifier(**config)\n else:\n raise NotImplementedError(\"ERROR: Requested model type unknown: \\\\\"%s\\\\\"\" % mdltype)\n return mdl\n\n def _get_model_instance(self, model, config):\n \"\"\" Returns an instance of a model based on (a) a desired name or (b) passed in class, or\n (c) passed in instance.\n\n :param model: string, class, or instance. Class and instance must have certain methods callable.\n :", "instruction": "", "output": "" }, { "input": "param config: dict with args passed in during the instantiation\n :return: model instance\n \"\"\"\n assert (model is not None and config is not None)\n if isinstance(model, str): # 'model' is a name, create it\n mdl = self._create_named_model(model, config)\n elif inspect.isclass(model): # 'model' is a class, instantiate it\n mdl = model(**config)\n else: # 'model' is an instance, register it\n mdl = model\n if not all([hasattr(mdl, key) and callable(getattr(mdl, key)) for key in self.callable_keys]):\n raise ValueError(\"ERROR: Passed model/method failed the interface test. Methods required: %s\" %\n ','.join(self.callable_keys))\n return mdl\n\n def __init__(self, base_model=None, meta_model=None, base_config=None, meta_config=None, random_seed=42):\n \"\"\"\n\n :param base_model: Base model. Can be:\n (1) None (default mdl will be set up),\n (2) Named model (e.g., logistic regression 'lr' or gradient boosting machine 'gbm'),\n (3) Base model class declaration (e.g., sklearn.linear_model.LogisticRegression). Will instantiate.\n (4) Model instance (instantiated outside). Will be re-used. Must have certain callable methods.\n Note: user-supplied classes and models must have certain callable methods ('predict', 'fit')\n and be capable of raising NotFittedError.\n :param meta_model: Meta model. Same values possible as with 'base_model'\n :param base_config: None or a params dict to be passed to 'base_model' at instantiation\n :param meta_config: None or a params dict to be passed to 'meta_model' at instantiation\n :param random_seed: seed used in the various pipeline steps\n \"\"\"\n super(BlackboxMetamodelClassification).__init__()\n self.random_seed = random_seed\n self.callable_keys = ['predict', 'fit'] # required methods - must be present in models passed in\n self.base_model_default = 'gbm'\n self.meta_model_default = 'lr'\n self.base_config_default = {'n_estimators': 300, 'max_depth': 10,\n 'learning_rate': 0.001, 'min_samples_leaf': 10, 'min_samples_split': 10,\n 'random_state': self.random_seed}\n self.meta_config_default = {'penalty': 'l1', 'C': 1, 'solver': 'liblinear', 'random_state': self.random_seed}\n self.base_config = base_config if base_config is not None else self.base_config_default\n self.meta_config = meta_config if meta_config is not None else self.meta_config_default\n self.base_model = None\n self.meta_model = None\n self.base_model = self._get_model_instance(base_model if base_model is not None else self.base_model_default,\n self.base_config)\n self.meta_model = self._get_model_instance(meta_model if meta_model is not None else self.meta_model_default,\n self.meta_config)\n\n def get_params(self, deep=True):\n return {\"base_model\": self.base_model, \"meta_model\": self.meta_model, \"base_config\": self.base_config,\n \"meta_config\": self.meta_config, \"random_seed\": self.random_seed}\n\n def _process_pretrained_model(self, X, y_hat_proba):\n \"\"\"\n Given the original input features and the base output probabilities, generate input features\n to train a meta model. Current implementation copies all input features and appends.\n\n :param X: numpy [nsamples, dim]\n :param y_hat_proba: [nsamples, nclasses]\n :return: array with new features [nsamples, newdim]\n \"\"\"\n assert (len(y_hat_proba.shape) == 2)\n assert (X.shape[0] == y_hat_proba.shape[0])\n # sort the probs sample by sample\n faux1 = np.sort(y_hat_proba, axis=-1)\n # add delta between top and second candidate\n faux2 = np.expand_dims(faux1[:, -1] - faux1[:, -2], axis=-1)\n return np.hstack([X, faux1, faux2])\n\n def fit(self, X, y, meta_fraction=0.2, randomize_samples=True, base_is_prefitted=False,\n meta_train_data=(None, None)):\n \"\"\"\n Fit base and meta models.\n\n :param X: input to the base model,\n array-like of shape (n_samples, n_features).\n Features vectors of the training data.\n :param y: ground truth for the base model,\n array-like of shape (n_samples,)\n :param meta_fraction: float in [0,1] - a fractional size of the partition carved out to train the meta model\n (complement will be used to train the base model)\n :param randomize_samples: use shuffling when creating partitions\n :param base_is_prefitted: Setting True will skip fitting the base model (useful for base models that have been\n instantiated outside/by the user and are already fitted.\n :param meta_train_data: User supplied data to train the meta model. Note that this option should only be used\n with 'base_is_prefitted'==True. Pass a tuple meta_train_data=(X_meta, y_meta) to activate.\n Note that (X,y,meta_fraction, randomize_samples) will be ignored in this mode.\n :return: self\n \"\"\"\n X = np.asarray(X)\n y = np.asarray(y)\n assert (len(meta_train_data) == 2)\n if meta_train_data[0] is None:\n X_base, X_meta, y_base, y_meta = train_test_split(X, y, shuffle=randomize_samples, test_size=meta_fraction,\n random_state=self.random_seed)\n else:\n if not base_is_prefitted:\n raise ValueError(\"ERROR: fit(): base model must be pre-fitted to use the 'meta_train_data' option\")\n X_base = y_base = None\n X_meta = meta_train_data[0]\n y_meta = meta_train_data[1]\n # fit the base model\n if not base_is_prefitted:\n self.base_model.fit(X_base, y_base)\n # get input for the meta model from the base\n try:\n y_hat_meta_proba = self.base_model.predict_proba(X_meta)\n # determine correct-incorrect outcome - these are targets for the meta model trainer\n \n # 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)\n y_hat_meta_targets = np.asarray((y_meta == np.argmax(y_hat_meta_proba, axis=-1)), dtype=int)\n \n except NotFittedError as e:\n raise RuntimeError(\"ERROR: fit(): The base model appears not pre-fitted (%s)\" % repr(e))\n # get input features for meta training\n X_meta_in = self._process_pretrained_model(X_meta, y_hat_meta_proba)\n # train meta model to predict 'correct' vs. 'incorrect' of the base\n self.meta_model.fit(X_meta_in, y_hat_meta_targets)\n return self\n\n def predict(self, X):\n \"\"\"\n Generate a base prediction along with uncertainty/confidence for data X.\n\n :param X: array-like of shape (n_samples, n_features).\n Features vectors of the test points.\n :return: namedtuple: A namedtuple that holds\n\n y_pred: ndarray of shape (n_samples,)\n Predicted labels of the test points.\n y_score: ndarray of shape (n_samples,)\n Confidence score the test points.\n\n \"\"\"\n y_hat_proba = self.base_model.predict_proba(X)\n y_hat = np.argmax(y_hat_proba, axis=-1)\n X_meta_in = self._process_pretrained_model(X, y_hat_proba)\n z_hat = self.meta_model.predict_proba(X_meta_in)\n index_of_class_1 = np.where(self.meta_model.classes_ == 1)[0][0] # class 1 corresponds to probab of positive/correct outcome\n Result = namedtuple('res', ['y_pred', 'y_score'])\n res = Result(y_hat, z_hat[:, index_of_class_1])\n\n return res\n from .blackbox_metamodel_regression import BlackboxMetamodelRegression\nfrom .blackbox_metamodel_classification import BlackboxMetamodelClassification\n from collections import namedtuple\n\nfrom uq360.algorithms.posthocuq import PostHocUQ\nfrom uq360.utils.misc import form_D_for_auucc\nfrom uq360.metrics.uncertainty_characteristics_curve.uncertainty_characteristics_curve import UncertaintyCharacteristicsCurve\n\n\nclass UCCRecalibration(PostHocUQ):\n \"\"\" Recalibration a regression model to specified operating point using Uncertainty Characteristics Curve.\n \"\"\"\n\n def __init__(self, base_model):\n \"\"\"\n Args:\n base_model: pretrained model to be recalibrated.\n \"\"\"\n super(UCCRecalibration).__init__()\n self.base_model = self._process_pretrained_model(base_model)\n self.ucc = None\n\n def get_params(self, deep=True):\n return {\"base_model\": self.base_model}\n\n def _process_pretrained_model(self, base_model):\n return base_model\n\n def fit(self, X, y):\n \"\"\"\n Fit the Uncertainty Characteristics Curve.\n\n Args:\n X: array-like of shape (n_samples, n_features).\n Features vectors of the test points.\n y: array-like of shape (n_samples,) or (n_samples, n_targets)\n Target values\n\n Returns:\n self\n\n \"\"\"\n y_pred_mean, y_pred_lower, y_pred_upper = self.base_model.predict(X)[:3]\n bwu = y_pred_upper - y_pred_mean\n bwl = y_pred_mean - y_pred_lower\n self.ucc = UncertaintyCharacteristicsCurve()\n self.ucc.fit(form_D_for_auucc(y_pred_mean, bwl, bwu), y.squeeze())\n\n return self\n\n def predict(self, X, missrate=0.05):\n \"\"\"\n Generate prediction and uncertainty bounds for data X.\n\n Args:\n X: array-like of shape (n_samples, n_features).\n Features vectors of the test points.\n missrate: desired missrate of the new operating point, set to 0.05 by default.\n\n Returns:\n namedtuple: A namedtupe that holds\n\n y_mean: ndarray of shape (n_samples, [n_output_dims])\n Mean of predictive distribution of the test points.\n y_lower: ndarray of shape (n_samples, [n_output_dims])\n Lower quantile of predictive distribution of the test points.\n y_upper: ndarray of shape (n_samples, [n_output_dims])\n Upper quantile of predictive distribution of the test points.\n \"\"\"\n C = self.ucc.get_specific_operating_point(req_y_axis_value=missrate, vary_bias=False)\n new_scale = C['modvalue']\n\n y_pred_mean, y_pred_lower, y_pred_upper = self.base_model.predict(X)[:3]\n bwu = y_pred_upper - y_pred_mean\n bwl = y_pred_mean - y_pred_lower\n\n if C['operation'] == 'bias':\n calib_y_pred_upper = y_pred_mean + (new_scale + bwu) # lower bound width\n calib_y_pred_lower = y_pred_mean - (new_scale + bwl) # Upper bound width\n else:\n calib_y_pred_upper = y_pred_mean + (new_scale * bwu) # lower bound width\n calib_y_pred_lower = y_pred_mean - (new_scale * bwl) # Upper bound width\n\n Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])\n res = Result(y_pred_mean, calib_y_pred_lower, calib_y_pred_upper)\n\n return res\n from .ucc_recalibration import UCCRecalibration\n from collections import namedtuple\n\nimport numpy as np\n\nfrom uq360.algorithms.posthocuq import PostHocUQ\n\n\nclass InfinitesimalJackknife(PostHocUQ):\n \"\"\"\n Performs a first order Taylor series expansion around MLE / MAP fit.\n Requires the model being probed to be twice differentiable.\n \"\"\"\n def __init__(self, params, gradients, hessian, config):\n \"\"\" Initialize IJ.\n Args:\n params: MLE / MAP fit around which uncertainty is sought. d*1\n gradients: Per data point gradients, estimated at the MLE / MAP fit. d*n\n hessian: Hessian evaluated at the MLE / MAP fit. d*d\n \"\"\"\n\n super(InfinitesimalJackknife).__init__()\n self.params_one = params\n self.gradients = gradients\n self.hessian = hessian\n self.d, self.n = gradients.shape\n self.dParams_dWeights = -np.linalg.solve(self.hessian, self.gradients)\n self.approx_dParams_dWeights = -np.linalg.solve(np.diag(np.diag(self.hessian)), self.gradients)\n self.w_one = np.ones([self.n])\n self.config = config\n\n def get_params(self, deep=True):\n return {\"params\": self.params, \"config\": self.config, \"gradients\": self.gradients,\n \"hessian\": self.hessian}\n\n def _process_pretrained_model(self, *argv, **kwargs):\n pass\n\n def get_parameter_uncertainty(self):\n if (self.config['resampling_strategy'] == \"jackknife\") or (self.config['resampling_strategy'] == \"jackknife+\"):\n w_query = np.ones_like(self.w_one)\n resampled_params = np.zeros([self.n, self.d])\n for i in np.arange(self.n):\n w_query[i] = 0\n resampled_params[i] = self.ij(w_query)\n w_query[i] = 1\n return np.cov(resampled_params), resampled_params\n elif self.config['resampling_strategy'] == \"bootstrap\":\n pass\n else:\n raise NotImplemented", "instruction": "", "output": "" }, { "input": "Error(\"Only jackknife, jackknife+, and bootstrap resampling strategies are supported\")\n\n def predict(self, X, model):\n \"\"\"\n Args:\n X: array-like of shape (n_samples, n_features).\n Features vectors of the test points.\n model: model object, must implement a set_parameters function\n\n Returns:\n namedtuple: A namedtupe that holds\n\n y_mean: ndarray of shape (n_samples, [n_output_dims])\n Mean of predictive distribution of the test points.\n y_lower: ndarray of shape (n_samples, [n_output_dims])\n Lower quantile of predictive distribution of the test points.\n y_upper: ndarray of shape (n_samples, [n_output_dims])\n Upper quantile of predictive distribution of the test points.\n\n \"\"\"\n n, _ = X.shape\n y_all = model.predict(X)\n _, d_out = y_all.shape\n params_cov, params = self.get_parameter_uncertainty()\n if d_out > 1:\n print(\"Quantiles are computed independently for each dimension. May not be accurate.\")\n y = np.zeros([params.shape[0], n, d_out])\n for i in np.arange(params.shape[0]):\n model.set_parameters(params[i])\n y[i] = model.predict(X)\n y_lower = np.quantile(y, q=0.5 * self.config['alpha'], axis=0)\n y_upper = np.quantile(y, q=(1. - 0.5 * self.config['alpha']), axis=0)\n y_mean = y.mean(axis=0)\n\n Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])\n res = Result(y_mean, y_lower, y_upper)\n\n return res\n\n def ij(self, w_query):\n \"\"\"\n Args:\n w_query: A n*1 vector to query parameters at.\n Return:\n new parameters at w_query\n \"\"\"\n assert w_query.shape[0] == self.n\n return self.params_one + self.dParams_dWeights @ (w_query-self.w_one).T\n\n def approx_ij(self, w_query):\n \"\"\"\n Args:\n w_query: A n*1 vector to query parameters at.\n Return:\n new parameters at w_query\n \"\"\"\n assert w_query.shape[0] == self.n\n return self.params_one + self.approx_dParams_dWeights @ (w_query-self.w_one).T from .infinitesimal_jackknife import InfinitesimalJackknife\n import copy\nfrom collections import namedtuple\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nimport torch.utils.data as data_utils\nfrom scipy.stats import norm\nfrom sklearn.preprocessing import StandardScaler\n\nfrom uq360.algorithms.builtinuq import BuiltinUQ\nfrom uq360.models.bayesian_neural_networks.bnn_models import horseshoe_mlp, bayesian_mlp\n\n\nclass BnnRegression(BuiltinUQ):\n \"\"\"\n Variationally trained BNNs with Gaussian and Horseshoe [6]_ priors for regression.\n\n References:\n .. [6] Ghosh, Soumya, Jiayu Yao, and Finale Doshi-Velez. \"Structured variational learning of Bayesian neural\n networks with horseshoe priors.\" International Conference on Machine Learning. PMLR, 2018.\n \"\"\"\n def __init__(self, config, prior=\"Gaussian\"):\n \"\"\"\n\n Args:\n config: a dictionary specifying network and learning hyperparameters.\n prior: BNN priors specified as a string. Supported priors are Gaussian, Hshoe, RegHshoe\n \"\"\"\n super(BnnRegression, self).__init__()\n self.config = config\n if prior == \"Gaussian\":\n self.net = bayesian_mlp.BayesianRegressionNet(ip_dim=config['ip_dim'], op_dim=config['op_dim'],\n num_nodes=config['num_nodes'], num_layers=config['num_layers'])\n self.config['use_reg_hshoe'] = None\n elif prior == \"Hshoe\":\n self.net = horseshoe_mlp.HshoeRegressionNet(ip_dim=config['ip_dim'], op_dim=config['op_dim'],\n num_nodes=config['num_nodes'], num_layers=config['num_layers'],\n hshoe_scale=config['hshoe_scale'])\n self.config['use_reg_hshoe'] = False\n elif prior == \"RegHshoe\":\n self.net = horseshoe_mlp.HshoeRegressionNet(ip_dim=config['ip_dim'], op_dim=config['op_dim'],\n num_nodes=config['num_nodes'], num_layers=config['num_layers'],\n hshoe_scale=config['hshoe_scale'],\n use_reg_hshoe=config['use_reg_hshoe'])\n self.config['use_reg_hshoe'] = True\n else:\n raise NotImplementedError(\"'prior' must be a string. It can be one of Gaussian, Hshoe, RegHshoe\")\n\n def get_params(self, deep=True):\n return {\"prior\": self.prior, \"config\": self.config}\n\n def fit(self, X, y):\n \"\"\" Fit the BNN regression model.\n\n Args:\n X: array-like of shape (n_samples, n_features).\n Features vectors of the training data.\n y: array-like of shape (n_samples,) or (n_samples, n_targets)\n Target values\n\n Returns:\n self\n\n \"\"\"\n torch.manual_seed(1234)\n optimizer = torch.optim.Adam(self.net.parameters(), lr=self.config['step_size'])\n neg_elbo = torch.zeros([self.config['num_epochs'], 1])\n params_store = {}\n for epoch in range(self.config['num_epochs']):\n loss = self.net.neg_elbo(num_batches=1, x=X, y=y.float().unsqueeze(dim=1)) / X.shape[0]\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n if hasattr(self.net, 'fixed_point_updates'):\n # for hshoe or regularized hshoe nets\n self.net.fixed_point_updates()\n neg_elbo[epoch] = loss.item()\n if (epoch + 1) % 10 == 0:\n # print ((net.noise_layer.bhat/net.noise_layer.ahat).data.numpy()[0])\n print('Epoch[{}/{}], neg elbo: {:.6f}, noise var: {:.6f}'\n .format(epoch + 1, self.config['num_epochs'], neg_elbo[epoch].item() / X.shape[0],\n self.net.get_noise_var()))\n params_store[epoch] = copy.deepcopy(self.net.state_dict()) # for small nets we can just store all.\n best_model_id = neg_elbo.argmin() # loss_val_store.argmin() #\n self.net.load_state_dict(params_store[best_model_id.item()])\n\n return self\n\n def predict(self, X, mc_samples=100, return_dists=False, return_epistemic=True, return_epistemic_dists=False):\n \"\"\"\n Obtain predictions for the test points.\n\n In addition to the mean and lower/upper bounds, also returns epistemic uncertainty (return_epistemic=True)\n and full predictive distribution (return_dists=True).\n\n Args:\n X: array-like of shape (n_samples, n_features).\n Features vectors of the test points.\n mc_samples: Number of Monte-Carlo samples.\n return_dists: If True, the predictive distribution for each instance using scipy distributions is returned.\n return_epistemic: if True, the epistemic upper and lower bounds are returned.\n return_epistemic_dists: If True, the epistemic distribution for each instance using scipy distributions\n is returned.\n\n Returns:\n namedtuple: A namedtupe that holds\n\n y_mean: ndarray of shape (n_samples, [n_output_dims])\n Mean of predictive distribution of the test points.\n y_lower: ndarray of shape (n_samples, [n_output_dims])\n Lower quantile of predictive distribution of the test points.\n y_upper: ndarray of shape (n_samples, [n_output_dims])\n Upper quantile of predictive distribution of the test points.\n y_lower_epistemic: ndarray of shape (n_samples, [n_output_dims])\n Lower quantile of epistemic component of the predictive distribution of the test points.\n Only returned when `return_epistemic` is True.\n y_upper_epistemic: ndarray of shape (n_samples, [n_output_dims])\n Upper quantile of epistemic component of the predictive distribution of the test points.\n Only returned when `return_epistemic` is True.\n dists: list of predictive distribution as `scipy.stats` objects with length n_samples.\n Only returned when `return_dists` is True.\n \"\"\"\n epistemic_out = np.zeros([mc_samples, X.shape[0]])\n total_out = np.zeros([mc_samples, X.shape[0]])\n for s in np.arange(mc_samples):\n pred = self.net(X).data.numpy().ravel()\n epistemic_out[s] = pred\n total_out[s] = pred + np.sqrt(self.net.get_noise_var()) * np.random.randn(pred.shape[0])\n y_total_std = np.std(total_out, axis=0)\n y_epi_std = np.std(epistemic_out, axis=0)\n y_mean = np.mean(total_out, axis=0)\n y_lower = y_mean - 2 * y_total_std\n y_upper = y_mean + 2 * y_total_std\n y_epi_lower = y_mean - 2 * y_epi_std\n y_epi_upper = y_mean + 2 * y_epi_std\n\n Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])\n res = Result(y_mean, y_lower, y_upper)\n\n if return_epistemic:\n Result = namedtuple('res', Result._fields + ('lower_epistemic', 'upper_epistemic',))\n res = Result(*res, lower_epistemic=y_epi_lower, upper_epistemic=y_epi_upper)\n\n if return_dists:\n dists = [norm(loc=y_mean[i], scale=y_total_std[i]) for i in range(y_mean.shape[0])]\n Result = namedtuple('res', Result._fields + ('y_dists',))\n res = Result(*res, y_dists=dists)\n\n if return_epistemic_dists:\n epi_dists = [norm(loc=y_mean[i], scale=y_epi_std[i]) for i in range(y_mean.shape[0])]\n Result = namedtuple('res', Result._fields + ('y_epistemic_dists',))\n res = Result(*res, y_epistemic_dists=epi_dists)\n\n return res\n\n\nclass BnnClassification(BuiltinUQ):\n \"\"\"\n Variationally trained BNNs with Gaussian and Horseshoe [6]_ priors for classification.\n \"\"\"\n def __init__(self, config, prior=\"Gaussian\", device=None):\n \"\"\"\n\n Args:\n config: a dictionary specifying network and learning hyperparameters.\n prior: BNN priors specified as a string. Supported priors are Gaussian, Hshoe, RegHshoe\n \"\"\"\n super(BnnClassification, self).__init__()\n self.config = config\n self.device = device\n if prior == \"Gaussian\":\n self.net = bayesian_mlp.BayesianClassificationNet(ip_dim=config['ip_dim'], op_dim=config['op_dim'],\n num_nodes=config['num_nodes'], num_layers=config['num_layers'])\n self.config['use_reg_hshoe'] = None\n elif prior == \"Hshoe\":\n self.net = horseshoe_mlp.HshoeClassificationNet(ip_dim=config['ip_dim'], op_dim=config['op_dim'],\n num_nodes=config['num_nodes'], num_layers=config['num_layers'],\n hshoe_scale=config['hshoe_scale'])\n self.config['use_reg_hshoe'] = False\n elif prior == \"RegHshoe\":\n self.net = horseshoe_mlp.HshoeClassificationNet(ip_dim=config['ip_dim'], op_dim=config['op_dim'],\n num_nodes=config['num_nodes'], num_layers=config['num_layers'],\n hshoe_scale=config['hshoe_scale'],\n use_reg_hshoe=config['use_reg_hshoe'])\n self.config['use_reg_hshoe'] = True\n else:\n raise NotImplementedError(\"'prior' must be a string. It can be one of Gaussian, Hshoe, RegHshoe\")\n if \"batch_size\" not in self.config:\n self.config[\"batch_size\"] = 50\n self.net = self.net.to(device)\n\n def get_params(self, deep=True):\n return {\"prior\": self.prior, \"config\": self.config, \"device\": self.device}\n\n def fit(self, X=None, y=None, train_loader=None):\n \"\"\" Fits BNN regression model.\n\n Args:\n X: array-like of shape (n_samples, n_features) or (n_samples, n_classes).\n Features vectors of the training data or the probability scores from the base model.\n Ignored if train_loader is not None.\n y: array-like of shape (n_samples,) or (n_samples, n_targets)\n Target values\n Ignored if train_loader is not None.\n train_loader: pytorch train_loader object.\n\n Returns:\n self\n\n \"\"\"\n if train_loader is None:\n train = data_utils.TensorDataset(torch.Tensor(X), torch.Tensor(y.values).long())\n train_loader = data_utils.DataLoader(train, batch_size=self.config['batch_size'], shuffle=True)\n\n torch.manual_seed(1234)\n optimizer = torch.optim.Adam(self.net.parameters(), lr=self.config['step_size'])\n neg_elbo = torch.zeros([self.config['num_epochs'], 1])\n params_store = {}\n for epoch in range(self.config['num_epochs']):\n avg_loss = 0.0\n for batch_x, batch_y in train_loader:\n loss = self.net.neg_elbo(num_batches=len(train_", "instruction": "", "output": "" }, { "input": "loader), x=batch_x, y=batch_y) / batch_x.size(0)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if hasattr(self.net, 'fixed_point_updates'):\n # for hshoe or regularized hshoe nets\n self.net.fixed_point_updates()\n\n avg_loss += loss.item()\n\n neg_elbo[epoch] = avg_loss / len(train_loader)\n\n if (epoch + 1) % 10 == 0:\n # print ((net.noise_layer.bhat/net.noise_layer.ahat).data.numpy()[0])\n print('Epoch[{}/{}], neg elbo: {:.6f}'\n .format(epoch + 1, self.config['num_epochs'], neg_elbo[epoch].item()))\n params_store[epoch] = copy.deepcopy(self.net.state_dict()) # for small nets we can just store all.\n best_model_id = neg_elbo.argmin() # loss_val_store.argmin() #\n self.net.load_state_dict(params_store[best_model_id.item()])\n\n return self\n\n def predict(self, X, mc_samples=100):\n \"\"\"\n Obtain calibrated predictions for the test points.\n\n Args:\n X: array-like of shape (n_samples, n_features) or (n_samples, n_classes).\n Features vectors of the training data or the probability scores from the base model.\n mc_samples: Number of Monte-Carlo samples.\n\n Returns:\n namedtuple: A namedtupe that holds\n\n y_pred: ndarray of shape (n_samples,)\n Predicted labels of the test points.\n y_prob: ndarray of shape (n_samples, n_classes)\n Predicted probability scores of the classes.\n y_prob_var: ndarray of shape (n_samples,)\n Variance of the prediction on the test points.\n y_prob_samples: ndarray of shape (mc_samples, n_samples, n_classes)\n Samples from the predictive distribution.\n\n \"\"\"\n\n X = torch.Tensor(X)\n y_prob_samples = [F.softmax(self.net(X), dim=1).detach().numpy() for _ in np.arange(mc_samples)]\n\n y_prob_samples_stacked = np.stack(y_prob_samples)\n prob_mean = np.mean(y_prob_samples_stacked, 0)\n prob_var = np.std(y_prob_samples_stacked, 0) ** 2\n\n if len(np.shape(prob_mean)) == 1:\n y_pred_labels = prob_mean > 0.5\n\n else:\n y_pred_labels = np.argmax(prob_mean, axis=1)\n\n Result = namedtuple('res', ['y_pred', 'y_prob', 'y_prob_var', 'y_prob_samples'])\n res = Result(y_pred_labels, prob_mean, prob_var, y_prob_samples)\n\n return res\n from collections import namedtuple\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom scipy.stats import norm\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import TensorDataset\n\nfrom uq360.algorithms.builtinuq import BuiltinUQ\n\nnp.random.seed(42)\ntorch.manual_seed(42)\n\n\nclass _MLPNet_Main(torch.nn.Module):\n def __init__(self, num_features, num_outputs, num_hidden):\n super(_MLPNet_Main, self).__init__()\n self.fc = torch.nn.Linear(num_features, num_hidden)\n self.fc_mu = torch.nn.Linear(num_hidden, num_outputs)\n self.fc_log_var = torch.nn.Linear(num_hidden, num_outputs)\n\n def forward(self, x):\n x = F.relu(self.fc(x))\n mu = self.fc_mu(x)\n log_var = self.fc_log_var(x)\n return mu, log_var\n\n\nclass _MLPNet_Aux(torch.nn.Module):\n def __init__(self, num_features, num_outputs, num_hidden):\n super(_MLPNet_Aux, self).__init__()\n self.fc = torch.nn.Linear(num_features, num_hidden)\n self.fc_log_var = torch.nn.Linear(num_hidden, num_outputs)\n\n def forward(self, x):\n x = F.relu(self.fc(x))\n log_var = self.fc_log_var(x)\n return log_var\n\n\nclass AuxiliaryIntervalPredictor(BuiltinUQ):\n \"\"\" Auxiliary Interval Predictor [1]_ uses an auxiliary model to encourage calibration of the main model.\n\n References:\n .. [1] Thiagarajan, J. J., Venkatesh, B., Sattigeri, P., & Bremer, P. T. (2020, April). Building calibrated deep\n models via uncertainty matching with auxiliary interval predictors. In Proceedings of the AAAI Conference on\n Artificial Intelligence (Vol. 34, No. 04, pp. 6005-6012). https://arxiv.org/abs/1909.04079\n \"\"\"\n\n def __init__(self, model_type=None, main_model=None, aux_model=None, config=None, device=None, verbose=True):\n \"\"\"\n Args:\n model_type: The model type used to build the main model and the auxiliary model. Currently supported values\n are [mlp, custom]. `mlp` modeltype learns a mlp neural network using pytorch framework. For `custom` the user\n provide `main_model` and `aux_model`.\n main_model: (optional) The main prediction model. Currently support pytorch models that return mean and log variance.\n aux_model: (optional) The auxiliary prediction model. Currently support pytorch models that return calibrated log variance.\n config: dictionary containing the config parameters for the model.\n device: device used for pytorch models ignored otherwise.\n verbose: if True, print statements with the progress are enabled.\n \"\"\"\n\n super(AuxiliaryIntervalPredictor).__init__()\n self.config = config\n self.device = device\n self.verbose = verbose\n if model_type == \"mlp\":\n self.model_type = model_type\n self.main_model = _MLPNet_Main(\n num_features=self.config[\"num_features\"],\n num_outputs=self.config[\"num_outputs\"],\n num_hidden=self.config[\"num_hidden\"],\n )\n self.aux_model = _MLPNet_Aux(\n num_features=self.config[\"num_features\"],\n num_outputs=self.config[\"num_outputs\"],\n num_hidden=self.config[\"num_hidden\"],\n )\n elif model_type == \"custom\":\n self.model_type = model_type\n self.main_model = main_model\n self.aux_model = aux_model\n\n else:\n raise NotImplementedError\n\n def get_params(self, deep=True):\n return {\"model_type\": self.model_type, \"config\": self.config, \"main_model\": self.main_model,\n \"aux_model\": self.aux_model, \"device\": self.device, \"verbose\": self.verbose}\n\n def _main_model_loss(self, y_true, y_pred_mu, y_pred_log_var, y_pred_log_var_aux):\n r = torch.abs(y_true - y_pred_mu)\n # + 0.5 * y_pred_log_var +\n loss = torch.mean(0.5 * torch.exp(-y_pred_log_var) * r ** 2) + \\\\\n 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)))\n return loss\n\n def _aux_model_loss(self, y_true, y_pred_mu, y_pred_log_var_aux):\n deltal = deltau = 2.0 * torch.exp(0.5 * y_pred_log_var_aux)\n upper = y_pred_mu + deltau\n lower = y_pred_mu - deltal\n width = upper - lower\n r = torch.abs(y_true - y_pred_mu)\n\n emce = torch.mean(torch.sigmoid((y_true - lower) * (upper - y_true) * 100000))\n\n loss_emce = torch.abs(self.config[\"calibration_alpha\"]-emce)\n loss_noise = torch.mean(torch.abs(0.5 * width - r))\n loss_sharpness = torch.mean(torch.abs(upper - y_true)) + torch.mean(torch.abs(lower - y_true))\n\n #print(emce)\n return loss_emce + self.config[\"lambda_noise\"] * loss_noise + self.config[\"lambda_sharpness\"] * loss_sharpness\n\n def fit(self, X, y):\n \"\"\" Fit the Auxiliary Interval Predictor model.\n\n Args:\n X: array-like of shape (n_samples, n_features).\n Features vectors of the training data.\n y: array-like of shape (n_samples,) or (n_samples, n_targets)\n Target values\n\n Returns:\n self\n\n \"\"\"\n\n X = torch.from_numpy(X).float().to(self.device)\n y = torch.from_numpy(y).float().to(self.device)\n\n dataset_loader = DataLoader(\n TensorDataset(X,y),\n batch_size=self.config[\"batch_size\"]\n )\n optimizer_main_model = torch.optim.Adam(self.main_model.parameters(), lr=self.config[\"lr\"])\n optimizer_aux_model = torch.optim.Adam(self.aux_model.parameters(), lr=self.config[\"lr\"])\n\n for it in range(self.config[\"num_outer_iters\"]):\n\n # Train the main model\n for epoch in range(self.config[\"num_main_iters\"]):\n avg_mean_model_loss = 0.0\n for batch_x, batch_y in dataset_loader:\n self.main_model.train()\n self.aux_model.eval()\n batch_y_pred_log_var_aux = self.aux_model(batch_x)\n batch_y_pred_mu, batch_y_pred_log_var = self.main_model(batch_x)\n main_loss = self._main_model_loss(batch_y, batch_y_pred_mu, batch_y_pred_log_var, batch_y_pred_log_var_aux)\n optimizer_main_model.zero_grad()\n main_loss.backward()\n optimizer_main_model.step()\n\n avg_mean_model_loss += main_loss.item()/len(dataset_loader)\n\n if self.verbose:\n print(\"Iter: {}, Epoch: {}, main_model_loss = {}\".format(it, epoch, avg_mean_model_loss))\n\n # Train the auxiliary model\n for epoch in range(self.config[\"num_aux_iters\"]):\n avg_aux_model_loss = 0.0\n for batch_x, batch_y in dataset_loader:\n self.aux_model.train()\n self.main_model.eval()\n batch_y_pred_log_var_aux = self.aux_model(batch_x)\n batch_y_pred_mu, batch_y_pred_log_var = self.main_model(batch_x)\n aux_loss = self._aux_model_loss(batch_y, batch_y_pred_mu, batch_y_pred_log_var_aux)\n optimizer_aux_model.zero_grad()\n aux_loss.backward()\n optimizer_aux_model.step()\n\n avg_aux_model_loss += aux_loss.item() / len(dataset_loader)\n\n if self.verbose:\n print(\"Iter: {}, Epoch: {}, aux_model_loss = {}\".format(it, epoch, avg_aux_model_loss))\n\n return self\n\n def predict(self, X, return_dists=False):\n \"\"\"\n Obtain predictions for the test points.\n\n In addition to the mean and lower/upper bounds, also returns full predictive distribution (return_dists=True).\n\n Args:\n X: array-like of shape (n_samples, n_features).\n Features vectors of the test points.\n return_dists: If True, the predictive distribution for each instance using scipy distributions is returned.\n\n Returns:\n namedtuple: A namedtupe that holds\n\n y_mean: ndarray of shape (n_samples, [n_output_dims])\n Mean of predictive distribution of the test points.\n y_lower: ndarray of shape (n_samples, [n_output_dims])\n Lower quantile of predictive distribution of the test points.\n y_upper: ndarray of shape (n_samples, [n_output_dims])\n Upper quantile of predictive distribution of the test points.\n dists: list of predictive distribution as `scipy.stats` objects with length n_samples.\n Only returned when `return_dists` is True.\n \"\"\"\n\n self.main_model.eval()\n\n X = torch.from_numpy(X).float().to(self.device)\n dataset_loader = DataLoader(\n X,\n batch_size=self.config[\"batch_size\"]\n )\n\n y_mean_list = []\n y_log_var_list = []\n for batch_x in dataset_loader:\n batch_y_pred_mu, batch_y_pred_log_var = self.main_model(batch_x)\n y_mean_list.append(batch_y_pred_mu.data.cpu().numpy())\n y_log_var_list.append(batch_y_pred_log_var.data.cpu().numpy())\n\n y_mean = np.concatenate(y_mean_list)\n y_log_var = np.concatenate(y_log_var_list)\n y_std = np.sqrt(np.exp(y_log_var))\n y_lower = y_mean - 2.0*y_std\n y_upper = y_mean + 2.0*y_std\n\n Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])\n res = Result(y_mean, y_lower, y_upper)\n\n if return_dists:\n dists = [norm(loc=y_mean[i], scale=y_std[i]) for i in range(y_mean.shape[0])]\n Result = namedtuple('res', Result._fields + ('y_dists',))\n res = Result(*res, y_dists=dists)\n\n return res\n from .auxiliary_interval_predictor import AuxiliaryIntervalPredictor\n import torch\nimport torch.nn.functional as F\nfrom uq360.models.noise_models.heteroscedastic_noise_models import GaussianNoise\n\nclass GaussianNoiseMLPNet(torch.nn.Module):\n\n def __init__(self, num", "instruction": "", "output": "" }, { "input": "_features, num_outputs, num_hidden):\n super(GaussianNoiseMLPNet, self).__init__()\n self.fc = torch.nn.Linear(num_features, num_hidden)\n self.fc_mu = torch.nn.Linear(num_hidden, num_outputs)\n self.fc_log_var = torch.nn.Linear(num_hidden, num_outputs)\n self.noise_layer = GaussianNoise()\n\n def forward(self, x):\n x = F.relu(self.fc(x))\n mu = self.fc_mu(x)\n log_var = self.fc_log_var(x)\n return mu, log_var\n\n def loss(self, y_true=None, mu_pred=None, log_var_pred=None):\n return self.noise_layer.loss(y_true, mu_pred, log_var_pred, reduce_mean=True) \"\"\"\n Contains implementations of various Bayesian layers\n\"\"\"\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch.nn import Parameter\n\nfrom uq360.models.bayesian_neural_networks.layer_utils import InvGammaHalfCauchyLayer, InvGammaLayer\n\ntd = torch.distributions\n\n\ndef reparam(mu, logvar, do_sample=True, mc_samples=1):\n if do_sample:\n std = torch.exp(0.5 * logvar)\n eps = torch.FloatTensor(std.size()).normal_()\n sample = mu + eps * std\n for _ in np.arange(1, mc_samples):\n sample += mu + eps * std\n return sample / mc_samples\n else:\n return mu\n\n\nclass BayesianLinearLayer(torch.nn.Module):\n \"\"\"\n Affine layer with N(0, v/H) or N(0, user specified v) priors on weights and\n fully factorized variational Gaussian approximation\n \"\"\"\n\n def __init__(self, in_features, out_features, cuda=False, init_weight=None, init_bias=None, prior_stdv=None):\n super(BayesianLinearLayer, self).__init__()\n self.cuda = cuda\n self.in_features = in_features\n self.out_features = out_features\n\n # weight mean params\n self.weights = Parameter(torch.Tensor(out_features, in_features))\n self.bias = Parameter(torch.Tensor(out_features))\n # weight variance params\n self.weights_logvar = Parameter(torch.Tensor(out_features, in_features))\n self.bias_logvar = Parameter(torch.Tensor(out_features))\n\n # numerical stability\n self.fudge_factor = 1e-8\n if not prior_stdv:\n # We will use a N(0, 1/num_inputs) prior over weights\n self.prior_stdv = torch.FloatTensor([1. / np.sqrt(self.weights.size(1))])\n else:\n self.prior_stdv = torch.FloatTensor([prior_stdv])\n # self.prior_stdv = torch.Tensor([1. / np.sqrt(1e+3)])\n self.prior_mean = torch.FloatTensor([0.])\n # for Bias use a prior of N(0, 1)\n self.prior_bias_stdv = torch.FloatTensor([1.])\n self.prior_bias_mean = torch.FloatTensor([0.])\n\n # init params either random or with pretrained net\n self.init_parameters(init_weight, init_bias)\n\n def init_parameters(self, init_weight, init_bias):\n # init means\n if init_weight is not None:\n self.weights.data = torch.Tensor(init_weight)\n else:\n self.weights.data.normal_(0, np.float(self.prior_stdv.numpy()[0]))\n\n if init_bias is not None:\n self.bias.data = torch.Tensor(init_bias)\n else:\n self.bias.data.normal_(0, 1)\n\n # init variances\n self.weights_logvar.data.normal_(-9, 1e-2)\n self.bias_logvar.data.normal_(-9, 1e-2)\n\n def forward(self, x, do_sample=True, scale_variances=False):\n # local reparameterization trick\n mu_activations = F.linear(x, self.weights, self.bias)\n var_activations = F.linear(x.pow(2), self.weights_logvar.exp(), self.bias_logvar.exp())\n if scale_variances:\n activ = reparam(mu_activations, var_activations.log() - np.log(self.in_features), do_sample=do_sample)\n else:\n activ = reparam(mu_activations, var_activations.log(), do_sample=do_sample)\n return activ\n\n def kl(self):\n \"\"\"\n KL divergence (q(W) || p(W))\n :return:\n \"\"\"\n weights_logvar = self.weights_logvar\n kld_weights = self.prior_stdv.log() - weights_logvar.mul(0.5) + \\\\\n (weights_logvar.exp() + (self.weights.pow(2) - self.prior_mean)) / (\n 2 * self.prior_stdv.pow(2)) - 0.5\n kld_bias = self.prior_bias_stdv.log() - self.bias_logvar.mul(0.5) + \\\\\n (self.bias_logvar.exp() + (self.bias.pow(2) - self.prior_bias_mean)) / (\n 2 * self.prior_bias_stdv.pow(2)) \\\\\n - 0.5\n return kld_weights.sum() + kld_bias.sum()\n\n\nclass HorseshoeLayer(BayesianLinearLayer):\n \"\"\"\n Uses non-centered parametrization. w_k = v*tau_k*beta_k where k indexes an output unit and w_k and beta_k\n are vectors of all weights incident into the unit\n \"\"\"\n def __init__(self, in_features, out_features, cuda=False, scale=1.):\n super(HorseshoeLayer, self).__init__(in_features, out_features)\n self.cuda = cuda\n self.in_features = in_features\n self.out_features = out_features\n self.nodescales = InvGammaHalfCauchyLayer(out_features=out_features, b=1.)\n self.layerscale = InvGammaHalfCauchyLayer(out_features=1, b=scale)\n # prior on beta is N(0, I) when employing non centered parameterization\n self.prior_stdv = torch.Tensor([1])\n self.prior_mean = torch.Tensor([0.])\n\n def forward(self, x, do_sample=True, debug=False, eps_scale=None, eps_w=None):\n # At a particular unit k, preactivation_sample = scale_sample * pre_activation_sample\n # sample scales\n scale_mean = 0.5 * (self.nodescales.mu + self.layerscale.mu)\n scale_var = 0.25 * (self.nodescales.log_sigma.exp() ** 2 + self.layerscale.log_sigma.exp() ** 2)\n scale_sample = reparam(scale_mean, scale_var.log(), do_sample=do_sample).exp()\n # sample preactivations\n mu_activations = F.linear(x, self.weights, self.bias)\n var_activations = F.linear(x.pow(2), self.weights_logvar.exp(), self.bias_logvar.exp())\n activ_sample = reparam(mu_activations, var_activations.log(), do_sample=do_sample)\n return scale_sample * activ_sample\n\n def kl(self):\n return super(HorseshoeLayer, self).kl() + self.nodescales.kl() + self.layerscale.kl()\n\n def fixed_point_updates(self):\n self.nodescales.fixed_point_updates()\n self.layerscale.fixed_point_updates()\n\n\nclass RegularizedHorseshoeLayer(HorseshoeLayer):\n \"\"\"\n Uses the regularized Horseshoe distribution. The regularized Horseshoe soft thresholds the tails of the Horseshoe.\n For all weights w_k incident upon node k in the layer we have:\n w_k ~ N(0, (tau_k * v)^2 I) N(0, c^2 I), c^2 ~ InverseGamma(c_a, b).\n c^2 controls the scale of the thresholding. As c^2 -> infinity, the regularized Horseshoe -> Horseshoe.\n \"\"\"\n\n def __init__(self, in_features, out_features, cuda=False, scale=1., c_a=2., c_b=6.):\n super(RegularizedHorseshoeLayer, self).__init__(in_features, out_features, cuda=cuda, scale=scale)\n self.c = InvGammaLayer(a=c_a, b=c_b)\n\n def forward(self, x, do_sample=True, **kwargs):\n # At a particular unit k, preactivation_sample = scale_sample * pre_activation_sample\n # sample regularized scales\n scale_mean = self.nodescales.mu + self.layerscale.mu\n scale_var = self.nodescales.log_sigma.exp() ** 2 + self.layerscale.log_sigma.exp() ** 2\n scale_sample = reparam(scale_mean, scale_var.log(), do_sample=do_sample).exp()\n c_sample = reparam(self.c.mu, 2 * self.c.log_sigma, do_sample=do_sample).exp()\n regularized_scale_sample = (c_sample * scale_sample) / (c_sample + scale_sample)\n # sample preactivations\n mu_activations = F.linear(x, self.weights, self.bias)\n var_activations = F.linear(x.pow(2), self.weights_logvar.exp(), self.bias_logvar.exp())\n activ_sample = reparam(mu_activations, var_activations.log(), do_sample=do_sample)\n return torch.sqrt(regularized_scale_sample) * activ_sample\n\n def kl(self):\n return super(RegularizedHorseshoeLayer, self).kl() + self.c.kl()\n\n\nclass NodeSpecificRegularizedHorseshoeLayer(RegularizedHorseshoeLayer):\n \"\"\"\n Uses the regularized Horseshoe distribution. The regularized Horseshoe soft thresholds the tails of the Horseshoe.\n For all weights w_k incident upon node k in the layer we have:\n w_k ~ N(0, (tau_k * v)^2 I) N(0, c_k^2 I), c_k^2 ~ InverseGamma(a, b).\n c_k^2 controls the scale of the thresholding. As c_k^2 -> infinity, the regularized Horseshoe -> Horseshoe\n Note that we now have a per-node c_k.\n \"\"\"\n\n def __init__(self, in_features, out_features, cuda=False, scale=1., c_a=2., c_b=6.):\n super(NodeSpecificRegularizedHorseshoeLayer, self).__init__(in_features, out_features, cuda=cuda, scale=scale)\n self.c = InvGammaLayer(a=c_a, b=c_b, out_features=out_features)\n\n\n\n\n \"\"\"\n Contains implementations of various utilities used by Horseshoe Bayesian layers\n\"\"\"\nimport numpy as np\nimport torch\nfrom torch.nn import Parameter\n\ntd = torch.distributions\ngammaln = torch.lgamma\n\n\ndef diag_gaussian_entropy(log_std, D):\n return 0.5 * D * (1.0 + torch.log(2 * np.pi)) + torch.sum(log_std)\n\n\ndef inv_gamma_entropy(a, b):\n return torch.sum(a + torch.log(b) + torch.lgamma(a) - (1 + a) * torch.digamma(a))\n\n\ndef log_normal_entropy(log_std, mu, D):\n return torch.sum(log_std + mu + 0.5) + (D / 2) * np.log(2 * np.pi)\n\n\nclass InvGammaHalfCauchyLayer(torch.nn.Module):\n \"\"\"\n Uses the inverse Gamma parameterization of the half-Cauchy distribution.\n a ~ C^+(0, b) <==> a^2 ~ IGamma(0.5, 1/lambda), lambda ~ IGamma(0.5, 1/b^2), where lambda is an\n auxiliary latent variable.\n Uses a factorized variational approximation q(ln a^2)q(lambda) = N(mu, sigma^2) IGamma(ahat, bhat).\n This layer places a half Cauchy prior on the scales of each output node of the layer.\n \"\"\"\n def __init__(self, out_features, b):\n \"\"\"\n :param out_fatures: number of output nodes in the layer.\n :param b: scale of the half Cauchy\n \"\"\"\n super(InvGammaHalfCauchyLayer, self).__init__()\n self.b = b\n self.out_features = out_features\n # variational parameters for q(ln a^2)\n self.mu = Parameter(torch.FloatTensor(out_features))\n self.log_sigma = Parameter(torch.FloatTensor(out_features))\n # self.log_sigma = torch.FloatTensor(out_features)\n # variational parameters for q(lambda). These will be updated via fixed point updates, hence not parameters.\n self.ahat = torch.FloatTensor([1.]) # The posterior parameter is always 1.\n self.bhat = torch.ones(out_features) * (1.0 / self.b ** 2)\n self.const = torch.FloatTensor([0.5])\n self.initialize_from_prior()\n\n def initialize_from_prior(self):\n \"\"\"\n Initializes variational parameters by sampling from the prior.\n \"\"\"\n # sample from half cauchy and log to initialize the mean of the log normal\n sample = np.abs(self.b * (np.random.randn(self.out_features) / np.random.randn(self.out_features)))\n self.mu.data = torch.FloatTensor(np.log(sample))\n self.log_sigma.data = torch.FloatTensor(np.random.randn(self.out_features) - 10.)\n\n def expectation_wrt_prior(self):\n \"\"\"\n Computes E[ln p(a^2 | lambda)] + E[ln p(lambda)]\n \"\"\"\n expected_a_given_lambda = -gammaln(self.const) - 0.5 * (torch.log(self.bhat) - torch.digamma(self.ahat)) + (\n -0.5 - 1.) * self.mu - torch.exp(-self.mu + 0.5 * self.log_sigma.exp() ** 2) * (self.ahat / self.bhat)\n expected_lambda = -gammaln(self.const) - 2 * 0.5 * np.log(", "instruction": "", "output": "" }, { "input": "self.b) + (-self.const - 1.) * (\n torch.log(self.bhat) - torch.digamma(self.ahat)) - (1. / self.b ** 2) * (self.ahat / self.bhat)\n return torch.sum(expected_a_given_lambda) + torch.sum(expected_lambda)\n\n def entropy(self):\n \"\"\"\n Computes entropy of q(ln a^2) and q(lambda)\n \"\"\"\n return self.entropy_lambda() + self.entropy_a2()\n\n def entropy_lambda(self):\n return inv_gamma_entropy(self.ahat, self.bhat)\n\n def entropy_a2(self):\n return log_normal_entropy(self.log_sigma, self.mu, self.out_features)\n\n def kl(self):\n \"\"\"\n Computes KL(q(ln(a^2)q(lambda) || IG(a^2 | 0.5, 1/lambda) IG(lambda | 0.5, 1/b^2))\n \"\"\"\n return -self.expectation_wrt_prior() - self.entropy()\n\n def fixed_point_updates(self):\n # update lambda moments\n self.bhat = torch.exp(-self.mu + 0.5 * self.log_sigma.exp() ** 2) + (1. / self.b ** 2)\n\n\nclass InvGammaLayer(torch.nn.Module):\n \"\"\"\n Approximates the posterior of c^2 with prior IGamma(c^2 | a , b)\n using a log Normal approximation q(ln c^2) = N(mu, sigma^2)\n \"\"\"\n\n def __init__(self, a, b, out_features=1):\n super(InvGammaLayer, self).__init__()\n self.a = torch.FloatTensor([a])\n self.b = torch.FloatTensor([b])\n # variational parameters for q(ln c^2)\n self.mu = Parameter(torch.FloatTensor(out_features))\n self.log_sigma = Parameter(torch.FloatTensor(out_features))\n self.out_features = out_features\n self.initialize_from_prior()\n\n def initialize_from_prior(self):\n \"\"\"\n Initializes variational parameters by sampling from the prior.\n \"\"\"\n self.mu.data = torch.log(self.b / (self.a + 1) * torch.ones(self.out_features)) # initialize at the mode\n self.log_sigma.data = torch.FloatTensor(np.random.randn(self.out_features) - 10.)\n\n def expectation_wrt_prior(self):\n \"\"\"\n Computes E[ln p(c^2 | a, b)]\n \"\"\"\n # return self.c_a * np.log(self.c_b) - gammaln(self.c_a) + (\n # - self.c_a - 1) * c_mu - self.c_b * Ecinv\n return self.a * torch.log(self.b) - gammaln(self.a) + (- self.a - 1) \\\\\n * self.mu - self.b * torch.exp(-self.mu + 0.5 * self.log_sigma.exp() ** 2)\n\n def entropy(self):\n return log_normal_entropy(self.log_sigma, self.mu, 1)\n\n def kl(self):\n \"\"\"\n Computes KL(q(ln(c^2) || IG(c^2 | a, b))\n \"\"\"\n return -self.expectation_wrt_prior().sum() - self.entropy()\n import numpy as np\nimport torch\nfrom uq360.models.noise_models.homoscedastic_noise_models import GaussianNoiseFixedPrecision\n\ndef compute_test_ll(y_test, y_pred_samples, std_y=1.):\n \"\"\"\n Computes test log likelihoods = (1 / Ntest) * \\\\sum_n p(y_n | x_n, D_train)\n :param y_test: True y\n :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\n q(w) is either a trained variational posterior or an MCMC approximation to p(w | D_train)\n :param std_y: True std of y (assumed known)\n \"\"\"\n S, _ = y_pred_samples.shape\n noise = GaussianNoiseFixedPrecision(std_y=std_y)\n ll = noise.loss(y_pred=y_pred_samples, y_true=y_test.unsqueeze(dim=0), reduce_sum=False)\n ll = torch.logsumexp(ll, dim=0) - np.log(S) # mean over num samples\n return torch.mean(ll) # mean over test points\n\n\n from abc import ABC\n\nimport numpy as np\nimport torch\nfrom torch import nn\n\nfrom uq360.models.bayesian_neural_networks.layers import HorseshoeLayer, BayesianLinearLayer, RegularizedHorseshoeLayer\nfrom uq360.models.noise_models.homoscedastic_noise_models import GaussianNoiseGammaPrecision\nimport numpy as np\ntd = torch.distributions\n\n\nclass HshoeBNN(nn.Module, ABC):\n \"\"\"\n Bayesian neural network with Horseshoe layers.\n \"\"\"\n def __init__(self, ip_dim=1, op_dim=1, num_nodes=50, activation_type='relu', num_layers=1,\n hshoe_scale=1e-1, use_reg_hshoe=False):\n if use_reg_hshoe:\n layer = RegularizedHorseshoeLayer\n else:\n layer = HorseshoeLayer\n super(HshoeBNN, self).__init__()\n self.num_layers = num_layers\n if activation_type == 'relu':\n # activation\n self.activation = nn.ReLU()\n elif activation_type == 'tanh':\n self.activation = nn.Tanh()\n else:\n print(\"Activation Type not supported\")\n self.fc_hidden = []\n self.fc1 = layer(ip_dim, num_nodes, scale=hshoe_scale)\n for _ in np.arange(self.num_layers - 1):\n self.fc_hidden.append(layer(num_nodes, num_nodes))\n self.fc_out = BayesianLinearLayer(num_nodes, op_dim)\n self.noise_layer = None\n\n def forward(self, x, do_sample=True):\n x = self.fc1(x, do_sample=do_sample)\n x = self.activation(x)\n for layer in self.fc_hidden:\n x = layer(x, do_sample=do_sample)\n x = self.activation(x)\n return self.fc_out(x, do_sample=do_sample, scale_variances=True)\n\n def kl_divergence_w(self):\n kld = self.fc1.kl() + self.fc_out.kl()\n for layer in self.fc_hidden:\n kld += layer.kl()\n return kld\n\n def fixed_point_updates(self):\n if hasattr(self.fc1, 'fixed_point_updates'):\n self.fc1.fixed_point_updates()\n if hasattr(self.fc_out, 'fixed_point_updates'):\n self.fc_out.fixed_point_updates()\n for layer in self.fc_hidden:\n if hasattr(layer, 'fixed_point_updates'):\n layer.fixed_point_updates()\n\n def prior_predictive_samples(self, n_sample=100):\n n_eval = 1000\n x = torch.linspace(-2, 2, n_eval)[:, np.newaxis]\n y = np.zeros([n_sample, n_eval])\n for i in np.arange(n_sample):\n y[i] = self.forward(x).data.numpy().ravel()\n return x.data.numpy(), y\n\n ### get and set weights ###\n def get_weights(self):\n assert len(self.fc_hidden) == 0 # only works for one layer networks.\n weight_dict = {}\n weight_dict['layerip_means'] = torch.cat([self.fc1.weights, self.fc1.bias.unsqueeze(1)], dim=1).data.numpy()\n weight_dict['layerip_logvar'] = torch.cat([self.fc1.weights_logvar, self.fc1.bias_logvar.unsqueeze(1)], dim=1).data.numpy()\n weight_dict['layerop_means'] = torch.cat([self.fc_out.weights, self.fc_out.bias.unsqueeze(1)], dim=1).data.numpy()\n weight_dict['layerop_logvar'] = torch.cat([self.fc_out.weights_logvar, self.fc_out.bias_logvar.unsqueeze(1)], dim=1).data.numpy()\n return weight_dict\n\n def set_weights(self, weight_dict):\n assert len(self.fc_hidden) == 0 # only works for one layer networks.\n to_param = lambda x: nn.Parameter(torch.Tensor(x))\n self.fc1.weights = to_param(weight_dict['layerip_means'][:, :-1])\n self.fc1.weights = to_param(weight_dict['layerip_logvar'][:, :-1])\n self.fc1.bias = to_param(weight_dict['layerip_means'][:, -1])\n self.fc1.bias_logvar = to_param(weight_dict['layerip_logvar'][:, -1])\n\n self.fc_out.weights = to_param(weight_dict['layerop_means'][:, :-1])\n self.fc_out.weights = to_param(weight_dict['layerop_logvar'][:, :-1])\n self.fc_out.bias = to_param(weight_dict['layerop_means'][:, -1])\n self.fc_out.bias_logvar = to_param(weight_dict['layerop_logvar'][:, -1])\n\n\nclass HshoeRegressionNet(HshoeBNN, ABC):\n \"\"\"\n Horseshoe net with N(y_true | f(x, w), \\\\lambda^-1); \\\\lambda ~ Gamma(a, b) likelihoods.\n \"\"\"\n def __init__(self, ip_dim=1, op_dim=1, num_nodes=50, activation_type='relu',\n num_layers=1, hshoe_scale=1e-5, use_reg_hshoe=False):\n super(HshoeRegressionNet, self).__init__(ip_dim=ip_dim, op_dim=op_dim,\n num_nodes=num_nodes, activation_type=activation_type,\n num_layers=num_layers,\n hshoe_scale=hshoe_scale,\n use_reg_hshoe=use_reg_hshoe)\n self.noise_layer = GaussianNoiseGammaPrecision(a0=6., b0=6.)\n\n def likelihood(self, x=None, y=None):\n out = self.forward(x)\n return -self.noise_layer.loss(y_pred=out, y_true=y)\n\n def neg_elbo(self, num_batches, x=None, y=None):\n # scale the KL terms by number of batches so that the minibatch elbo is an unbiased estiamte of the true elbo.\n Elik = self.likelihood(x, y)\n neg_elbo = (self.kl_divergence_w() + self.noise_layer.kl()) / num_batches - Elik\n return neg_elbo\n\n def mse(self, x, y):\n \"\"\"\n scaled rmse (scaled by 1 / std_y**2)\n \"\"\"\n E_noise_precision = 1. / self.noise_layer.get_noise_var()\n return (0.5 * E_noise_precision * (self.forward(x, do_sample=False) - y)**2).sum()\n\n def get_noise_var(self):\n return self.noise_layer.get_noise_var()\n\n\nclass HshoeClassificationNet(HshoeBNN, ABC):\n \"\"\"\n Horseshoe net with Categorical(y_true | f(x, w)) likelihoods. Use for classification.\n \"\"\"\n def __init__(self, ip_dim=1, op_dim=1, num_nodes=50, activation_type='relu',\n num_layers=1, hshoe_scale=1e-5, use_reg_hshoe=False):\n super(HshoeClassificationNet, self).__init__(ip_dim=ip_dim, op_dim=op_dim,\n num_nodes=num_nodes, activation_type=activation_type,\n num_layers=num_layers,\n hshoe_scale=hshoe_scale,\n use_reg_hshoe=use_reg_hshoe)\n self.noise_layer = torch.nn.CrossEntropyLoss(reduction='sum')\n\n def likelihood(self, x=None, y=None):\n out = self.forward(x)\n return -self.noise_layer(out, y)\n\n def neg_elbo(self, num_batches, x=None, y=None):\n # scale the KL terms by number of batches so that the minibatch elbo is an unbiased estiamte of the true elbo.\n Elik = self.likelihood(x, y)\n neg_elbo = (self.kl_divergence_w()) / num_batches - Elik\n return neg_elbo\n\n\n\n\n from abc import ABC\nimport torch\nfrom torch import nn\nfrom uq360.models.bayesian_neural_networks.layers import BayesianLinearLayer\nfrom uq360.models.noise_models.homoscedastic_noise_models import GaussianNoiseGammaPrecision\nimport numpy as np\ntd = torch.distributions\n\n\nclass BayesianNN(nn.Module, ABC):\n \"\"\"\n Bayesian neural network with zero mean Gaussian priors over weights.\n \"\"\"\n def __init__(self, layer=BayesianLinearLayer, ip_dim=1, op_dim=1, num_nodes=50,\n activation_type='relu', num_layers=1):\n super(BayesianNN, self).__init__()\n self.num_layers = num_layers\n if activation_type == 'relu':\n # activation\n self.activation = nn.ReLU()\n elif activation_type == 'tanh':\n self.activation = nn.Tanh()\n else:\n print(\"Activation Type not supported\")\n self.fc_hidden = []\n self.fc1 = layer(ip_dim, num_nodes,)\n for _ in np.arange(self.num_layers - 1):\n self.fc_hidden.append(layer(num_nodes, num_nodes, ))\n self.fc_out = layer(num_nodes, op_dim, )\n self.noise_layer = None\n\n def forward(self, x, do_sample=True):\n x = self.fc1(x, do_sample=do_sample)\n x = self.activation(x)\n for layer in self.fc_hidden:\n x = layer(x, do_", "instruction": "", "output": "" }, { "input": "sample=do_sample)\n x = self.activation(x)\n return self.fc_out(x, do_sample=do_sample, scale_variances=True)\n\n def kl_divergence_w(self):\n kld = self.fc1.kl() + self.fc_out.kl()\n for layer in self.fc_hidden:\n kld += layer.kl()\n return kld\n\n def prior_predictive_samples(self, n_sample=100):\n n_eval = 1000\n x = torch.linspace(-2, 2, n_eval)[:, np.newaxis]\n y = np.zeros([n_sample, n_eval])\n for i in np.arange(n_sample):\n y[i] = self.forward(x).data.numpy().ravel()\n return x.data.numpy(), y\n\n ### get and set weights ###\n def get_weights(self):\n assert len(self.fc_hidden) == 0 # only works for one layer networks.\n weight_dict = {}\n weight_dict['layerip_means'] = torch.cat([self.fc1.weights, self.fc1.bias.unsqueeze(1)], dim=1).data.numpy()\n weight_dict['layerip_logvar'] = torch.cat([self.fc1.weights_logvar, self.fc1.bias_logvar.unsqueeze(1)], dim=1).data.numpy()\n weight_dict['layerop_means'] = torch.cat([self.fc_out.weights, self.fc_out.bias.unsqueeze(1)], dim=1).data.numpy()\n weight_dict['layerop_logvar'] = torch.cat([self.fc_out.weights_logvar, self.fc_out.bias_logvar.unsqueeze(1)], dim=1).data.numpy()\n return weight_dict\n\n def set_weights(self, weight_dict):\n assert len(self.fc_hidden) == 0 # only works for one layer networks.\n to_param = lambda x: nn.Parameter(torch.Tensor(x))\n self.fc1.weights = to_param(weight_dict['layerip_means'][:, :-1])\n self.fc1.weights = to_param(weight_dict['layerip_logvar'][:, :-1])\n self.fc1.bias = to_param(weight_dict['layerip_means'][:, -1])\n self.fc1.bias_logvar = to_param(weight_dict['layerip_logvar'][:, -1])\n\n self.fc_out.weights = to_param(weight_dict['layerop_means'][:, :-1])\n self.fc_out.weights = to_param(weight_dict['layerop_logvar'][:, :-1])\n self.fc_out.bias = to_param(weight_dict['layerop_means'][:, -1])\n self.fc_out.bias_logvar = to_param(weight_dict['layerop_logvar'][:, -1])\n\n\nclass BayesianRegressionNet(BayesianNN, ABC):\n \"\"\"\n Bayesian neural net with N(y_true | f(x, w), \\\\lambda^-1); \\\\lambda ~ Gamma(a, b) likelihoods.\n \"\"\"\n def __init__(self, layer=BayesianLinearLayer, ip_dim=1, op_dim=1, num_nodes=50, activation_type='relu',\n num_layers=1):\n super(BayesianRegressionNet, self).__init__(layer=layer, ip_dim=ip_dim, op_dim=op_dim,\n num_nodes=num_nodes, activation_type=activation_type,\n num_layers=num_layers,\n )\n self.noise_layer = GaussianNoiseGammaPrecision(a0=6., b0=6.)\n\n def likelihood(self, x=None, y=None):\n out = self.forward(x)\n return -self.noise_layer.loss(y_pred=out, y_true=y)\n\n def neg_elbo(self, num_batches, x=None, y=None):\n # scale the KL terms by number of batches so that the minibatch elbo is an unbiased estiamte of the true elbo.\n Elik = self.likelihood(x, y)\n neg_elbo = (self.kl_divergence_w() + self.noise_layer.kl()) / num_batches - Elik\n return neg_elbo\n\n def mse(self, x, y):\n \"\"\"\n scaled rmse (scaled by 1 / std_y**2)\n \"\"\"\n E_noise_precision = 1. / self.noise_layer.get_noise_var()\n return (0.5 * E_noise_precision * (self.forward(x, do_sample=False) - y)**2).sum()\n\n def get_noise_var(self):\n return self.noise_layer.get_noise_var()\n\n\nclass BayesianClassificationNet(BayesianNN, ABC):\n \"\"\"\n Bayesian neural net with Categorical(y_true | f(x, w)) likelihoods. Use for classification.\n \"\"\"\n def __init__(self, layer=BayesianLinearLayer, ip_dim=1, op_dim=1, num_nodes=50, activation_type='relu',\n num_layers=1):\n super(BayesianClassificationNet, self).__init__(layer=layer, ip_dim=ip_dim, op_dim=op_dim,\n num_nodes=num_nodes, activation_type=activation_type,\n num_layers=num_layers)\n self.noise_layer = torch.nn.CrossEntropyLoss(reduction='sum')\n\n def likelihood(self, x=None, y=None):\n out = self.forward(x)\n return -self.noise_layer(out, y)\n\n def neg_elbo(self, num_batches, x=None, y=None):\n # scale the KL terms by number of batches so that the minibatch elbo is an unbiased estiamte of the true elbo.\n Elik = self.likelihood(x, y)\n neg_elbo = self.kl_divergence_w() / num_batches - Elik\n return neg_elbo\n\n\n\n\n import math\n\nimport numpy as np\nimport torch\nfrom scipy.special import gammaln\nfrom uq360.models.noise_models.noisemodel import AbstractNoiseModel\nfrom torch.nn import Parameter\n\ntd = torch.distributions\n\n\ndef transform(a):\n return torch.log(1 + torch.exp(a))\n\n\nclass GaussianNoise(torch.nn.Module, AbstractNoiseModel):\n \"\"\"\n N(y_true | f_\\\\mu(x, w), f_\\\\sigma^2(x, w))\n \"\"\"\n\n def __init__(self, cuda=False):\n super(GaussianNoise, self).__init__()\n self.cuda = cuda\n self.const = torch.log(torch.FloatTensor([2 * math.pi]))\n\n def loss(self, y_true=None, mu_pred=None, log_var_pred=None, reduce_mean=True):\n \"\"\"\n computes -1 * ln N (y_true | mu_pred, softplus(log_var_pred))\n :param y_true:\n :param mu_pred:\n :param log_var_pred:\n\n :return:\n \"\"\"\n var_pred = transform(log_var_pred)\n ll = -0.5 * self.const - 0.5 * torch.log(var_pred) - 0.5 * (1. / var_pred) * ((mu_pred - y_true) ** 2)\n if reduce_mean:\n return -ll.mean(dim=0)\n else:\n return -ll.sum(dim=0)\n\n def get_noise_var(self, log_var_pred):\n return transform(log_var_pred)\n\n\n import math\n\nimport numpy as np\nimport torch\nfrom scipy.special import gammaln\nfrom uq360.models.noise_models.noisemodel import AbstractNoiseModel\nfrom torch.nn import Parameter\n\ntd = torch.distributions\n\n\ndef transform(a):\n return torch.log(1 + torch.exp(a))\n\n\nclass GaussianNoiseGammaPrecision(torch.nn.Module, AbstractNoiseModel):\n \"\"\"\n N(y_true | f(x, w), \\\\lambda^-1); \\\\lambda ~ Gamma(a, b).\n Uses a variational approximation; q(lambda) = Gamma(ahat, bhat)\n \"\"\"\n\n def __init__(self, a0=6, b0=6, cuda=False):\n super(GaussianNoiseGammaPrecision, self).__init__()\n self.cuda = cuda\n self.a0 = a0\n self.b0 = b0\n self.const = torch.log(torch.FloatTensor([2 * math.pi]))\n # variational parameters\n self.ahat = Parameter(torch.FloatTensor([10.]))\n self.bhat = Parameter(torch.FloatTensor([3.]))\n\n def loss(self, y_pred=None, y_true=None):\n \"\"\"\n computes -1 * E_q(\\\\lambda)[ln N (y_pred | y_true, \\\\lambda^-1)], where q(lambda) = Gamma(ahat, bhat)\n :param y_pred:\n :param y_true:\n :return:\n \"\"\"\n n = y_pred.shape[0]\n ahat = transform(self.ahat)\n bhat = transform(self.bhat)\n return -1 * (-0.5 * n * self.const + 0.5 * n * (torch.digamma(ahat) - torch.log(bhat)) \\\\\n - 0.5 * (ahat/bhat) * ((y_pred - y_true) ** 2).sum())\n\n def kl(self):\n ahat = transform(self.ahat)\n bhat = transform(self.bhat)\n return (ahat - self.a0) * torch.digamma(ahat) - torch.lgamma(ahat) + gammaln(self.a0) + \\\\\n self.a0 * (torch.log(bhat) - np.log(self.b0)) + ahat * (self.b0 - bhat) / bhat\n\n def get_noise_var(self):\n ahat = transform(self.ahat)\n bhat = transform(self.bhat)\n return (bhat / ahat).data.numpy()[0]\n\n\nclass GaussianNoiseFixedPrecision(torch.nn.Module, AbstractNoiseModel):\n \"\"\"\n N(y_true | f(x, w), sigma_y**2); known sigma_y\n \"\"\"\n\n def __init__(self, std_y=1., cuda=False):\n super(GaussianNoiseFixedPrecision, self).__init__()\n self.cuda = cuda\n self.const = torch.log(torch.FloatTensor([2 * math.pi]))\n self.sigma_y = std_y\n\n def loss(self, y_pred=None, y_true=None):\n \"\"\"\n computes -1 * ln N (y_pred | y_true, sigma_y**2)\n :param y_pred:\n :param y_true:\n :return:\n \"\"\"\n ll = -0.5 * self.const - np.log(self.sigma_y) - 0.5 * (1. / self.sigma_y ** 2) * ((y_pred - y_true) ** 2)\n return -ll.sum(dim=0)\n\n def get_noise_var(self):\n return self.sigma_y ** 2 import abc\nimport sys\n\n# Ensure compatibility with Python 2/3\nif sys.version_info >= (3, 4):\n ABC = abc.ABC\nelse:\n ABC = abc.ABCMeta(str('ABC'), (), {})\n\n\nclass AbstractNoiseModel(ABC):\n \"\"\" Abstract class. All noise models inherit from here.\n \"\"\"\n\n def __init__(self, *argv, **kwargs):\n \"\"\" Initialize an AbstractNoiseModel object.\n \"\"\"\n\n @abc.abstractmethod\n def loss(self, *argv, **kwargs):\n \"\"\" Compute loss given predictions and groundtruth labels\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def get_noise_var(self, *argv, **kwargs):\n \"\"\"\n Return the current estimate of noise variance\n \"\"\"\n raise NotImplementedError\n import autograd\nimport autograd.numpy as np\nimport scipy.optimize\nfrom autograd import grad\nfrom autograd.scipy.special import logsumexp\nfrom sklearn.cluster import KMeans\n\n\nclass HMM:\n \"\"\"\n A Hidden Markov Model with Gaussian observations with\n unknown means and known precisions.\n \"\"\"\n def __init__(self, X, config_dict=None):\n self.N, self.T, self.D = X.shape\n self.K = config_dict['K'] # number of HMM states\n self.I = np.eye(self.K)\n self.Precision = np.zeros([self.D, self.D, self.K])\n self.X = X\n if config_dict['precision'] is None:\n for k in np.arange(self.K):\n self.Precision[:, :, k] = np.eye(self.D)\n else:\n self.Precision = config_dict['precision']\n self.dParams_dWeights = None\n self.alphaT = None # Store the final beliefs.\n self.beta1 = None # store the first timestep beliefs from the beta recursion.\n self.forward_trellis = {} # stores \\\\alpha\n self.backward_trellis = {} # stores \\\\beta\n\n def initialize_params(self, seed=1234):\n np.random.seed(seed)\n param_dict = {}\n A = np.random.randn(self.K, self.K)\n # use k-means to initialize the mean parameters\n X = self.X.reshape([-1, self.D])\n kmeans = KMeans(n_clusters=self.K, random_state=seed,\n n_init=15).fit(X)\n labels = kmeans.labels_\n _, counts = np.unique(labels, return_counts=True)\n pi = counts\n phi = kmeans.cluster_centers_\n\n param_dict['A'] = np.exp(A)\n param_dict['pi0'] = pi\n param_dict['phi'] = phi\n return self.pack_params(param_dict)\n\n def unpack_params(self, params):\n param_dict = dict()\n K = self.K\n # For unpacking simplex parameters: have packed them as\n # log(pi[:-1]) - log(pi[-1]).\n unnorm_A = np.exp(np.append(params[:K**2-K].reshape(K, K-1),\n np.zeros((K, 1)),\n axis=1)\n )\n Z = np.sum(unnorm_A[:, :-1], axis=1)\n unnorm_A /= Z[:, np.newaxis]\n norm_A = unnorm_A / unnorm_A.sum(axis=1, keepdims=True)\n param_dict['A'] = norm_A\n\n unnorm_pi = np.exp(np.append(params[K**2-K:K**2-1],", "instruction": "", "output": "" }, { "input": "0.0))\n Z = np.sum(unnorm_pi[:-1])\n unnorm_pi /= Z\n param_dict['pi0'] = unnorm_pi / unnorm_pi.sum()\n param_dict['phi'] = params[K**2-K+K-1:].reshape(self.D, K)\n return param_dict\n\n def weighted_alpha_recursion(self, xseq, pi, phi, Sigma, A, wseq, store_belief=False):\n \"\"\"\n Computes the weighted marginal probability of the sequence xseq given parameters;\n weights wseq turn on or off the emissions p(x_t | z_t) (weighting scheme B)\n :param xseq: T * D\n :param pi: K * 1\n :param phi: D * K\n :param wseq: T * 1\n :param A:\n :return:\n \"\"\"\n ll = self.log_obs_lik(xseq[:, :, np.newaxis], phi[np.newaxis, :, :], Sigma)\n alpha = np.log(pi.ravel()) + wseq[0] * ll[0]\n if wseq[0] == 0:\n self.forward_trellis[0] = alpha[:, np.newaxis]\n for t in np.arange(1, self.T):\n alpha = logsumexp(alpha[:, np.newaxis] + np.log(A), axis=0) + wseq[t] * ll[t]\n if wseq[t] == 0:\n # store the trellis, would be used to compute the posterior z_t | x_1...x_t-1, x_t+1, ...x_T\n self.forward_trellis[t] = alpha[:, np.newaxis]\n if store_belief:\n # store the final belief\n self.alphaT = alpha\n return logsumexp(alpha)\n\n def weighted_beta_recursion(self, xseq, pi, phi, Sigma, A, wseq, store_belief=False):\n \"\"\"\n Runs beta recursion;\n weights wseq turn on or off the emissions p(x_t | z_t) (weighting scheme B)\n :param xseq: T * D\n :param pi: K * 1\n :param phi: D * K\n :param wseq: T * 1\n :param A:\n :return:\n \"\"\"\n ll = self.log_obs_lik(xseq[:, :, np.newaxis], phi[np.newaxis, :, :], Sigma)\n beta = np.zeros_like(pi.ravel()) # log(\\\\beta) of all ones.\n max_t = ll.shape[0]\n if wseq[max_t - 1] == 0:\n # store the trellis, would be used to compute the posterior z_t | x_1...x_t-1, x_t+1, ...x_T\n self.backward_trellis[max_t - 1] = beta[:, np.newaxis]\n for i in np.arange(1, max_t):\n t = max_t - i - 1\n beta = logsumexp((beta + wseq[t + 1] * ll[t + 1])[np.newaxis, :] + np.log(A), axis=1)\n if wseq[t] == 0:\n # store the trellis, would be used to compute the posterior z_t | x_1...x_t-1, x_t+1, ...x_T\n self.backward_trellis[t] = beta[:, np.newaxis]\n # account for the init prob\n beta = (beta + wseq[0] * ll[0]) + np.log(pi.ravel())\n if store_belief:\n # store the final belief\n self.beta1 = beta\n return logsumexp(beta)\n\n def weighted_loss(self, params, weights):\n \"\"\"\n For LOOCV / IF computation within a single sequence. Uses weighted alpha recursion\n :param params:\n :param weights:\n :return:\n \"\"\"\n param_dict = self.unpack_params(params)\n logp = self.get_prior_contrib(param_dict)\n logp = logp + self.weighted_alpha_recursion(self.X[0], param_dict['pi0'],\n param_dict['phi'],\n self.Precision,\n param_dict['A'],\n weights)\n return -logp\n\n def loss_at_missing_timesteps(self, weights, params):\n \"\"\"\n :param weights: zeroed out weights indicate missing values\n :param params: packed parameters\n :return:\n \"\"\"\n # empty forward and backward trellis\n self.clear_trellis()\n param_dict = self.unpack_params(params)\n # populate forward and backward trellis\n lpx = self.weighted_alpha_recursion(self.X[0], param_dict['pi0'],\n param_dict['phi'],\n self.Precision,\n param_dict['A'],\n weights,\n store_belief=True )\n lpx_alt = self.weighted_beta_recursion(self.X[0], param_dict['pi0'],\n param_dict['phi'],\n self.Precision,\n param_dict['A'],\n weights,\n store_belief=True)\n assert np.allclose(lpx, lpx_alt) # sanity check\n test_ll = []\n # compute loo likelihood\n ll = self.log_obs_lik(self.X[0][:, :, np.newaxis], param_dict['phi'], self.Precision)\n # compute posterior p(z_t | x_1,...t-1, t+1,...T) \\\\forall missing t\n tsteps = []\n for t in self.forward_trellis.keys():\n lpz_given_x = self.forward_trellis[t] + self.backward_trellis[t] - lpx\n test_ll.append(logsumexp(ll[t] + lpz_given_x.ravel()))\n tsteps.append(t)\n # empty forward and backward trellis\n self.clear_trellis()\n return -np.array(test_ll)\n\n def fit(self, weights, init_params=None, num_random_restarts=1, verbose=False, maxiter=None):\n if maxiter:\n options_dict = {'disp': verbose, 'gtol': 1e-10, 'maxiter': maxiter}\n else:\n options_dict = {'disp': verbose, 'gtol': 1e-10}\n\n # Define a function that returns gradients of training loss using Autograd.\n training_loss_fun = lambda params: self.weighted_loss(params, weights)\n training_gradient_fun = grad(training_loss_fun, 0)\n if init_params is None:\n init_params = self.initialize_params()\n if verbose:\n print(\"Initial loss: \", training_loss_fun(init_params))\n res = scipy.optimize.minimize(fun=training_loss_fun,\n jac=training_gradient_fun,\n x0=init_params,\n tol=1e-10,\n options=options_dict)\n if verbose:\n print('grad norm =', np.linalg.norm(res.jac))\n return res.x\n\n def clear_trellis(self):\n self.forward_trellis = {}\n self.backward_trellis = {}\n\n #### Required for IJ computation ###\n def compute_hessian(self, params_one, weights_one):\n return autograd.hessian(self.weighted_loss, argnum=0)(params_one, weights_one)\n\n def compute_jacobian(self, params_one, weights_one):\n return autograd.jacobian(autograd.jacobian(self.weighted_loss, argnum=0), argnum=1)\\\\\n (params_one, weights_one).squeeze()\n ###################################################\n\n @staticmethod\n def log_obs_lik(x, phi, Sigma):\n \"\"\"\n :param x: T*D*1\n :param phi: 1*D*K\n :param Sigma: D*D*K --- precision matrices per state\n :return: ll\n \"\"\"\n centered_x = x - phi\n ll = -0.5 * np.einsum('tdk, tdk, ddk -> tk', centered_x, centered_x, Sigma )\n return ll\n\n @staticmethod\n def pack_params(params_dict):\n param_list = [(np.log(params_dict['A'][:, :-1]) -\n np.log(params_dict['A'][:, -1])[:, np.newaxis]).ravel(),\n np.log(params_dict['pi0'][:-1]) - np.log(params_dict['pi0'][-1]),\n params_dict['phi'].ravel()]\n return np.concatenate(param_list)\n\n @staticmethod\n def get_prior_contrib(param_dict):\n logp = 0.0\n # Prior\n logp += -0.5 * (np.linalg.norm(param_dict['phi'], axis=0) ** 2).sum()\n logp += (1.1 - 1) * np.log(param_dict['A']).sum()\n logp += (1.1 - 1) * np.log(param_dict['pi0']).sum()\n return logp\n\n @staticmethod\n def get_indices_in_held_out_fold(T, pct_to_drop, contiguous=False):\n \"\"\"\n :param T: length of the sequence\n :param pct_to_drop: % of T in the held out fold\n :param contiguous: if True generate a block of indices to drop else generate indices by iid sampling\n :return: o (the set of indices in the fold)\n \"\"\"\n if contiguous:\n l = np.floor(pct_to_drop / 100. * T)\n anchor = np.random.choice(np.arange(l + 1, T))\n o = np.arange(anchor - l, anchor).astype(int)\n else:\n # i.i.d LWCV\n o = np.random.choice(T - 2, size=np.int(pct_to_drop / 100. * T), replace=False) + 1\n return o\n\n @staticmethod\n def synthetic_hmm_data(K, T, D, sigma0=None, seed=1234, varainces_of_mean=1.0,\n diagonal_upweight=False):\n \"\"\"\n :param K: Number of HMM states\n :param T: length of the sequence\n \"\"\"\n N = 1 # For structured IJ we will remove data / time steps from a single sequence\n np.random.seed(seed)\n if sigma0 is None:\n sigma0 = np.eye(D)\n\n A = np.random.dirichlet(alpha=np.ones(K), size=K)\n if diagonal_upweight:\n A = A + 3 * np.eye(K) # add 3 to the diagonal and renormalize to encourage self transitions\n A = A / A.sum(axis=1)\n\n pi0 = np.random.dirichlet(alpha=np.ones(K))\n mus = np.random.normal(size=(K, D), scale=np.sqrt(varainces_of_mean))\n zs = np.empty((N, T), dtype=np.int)\n X = np.empty((N, T, D))\n\n for n in range(N):\n zs[n, 0] = int(np.random.choice(np.arange(K), p=pi0))\n X[n, 0] = np.random.multivariate_normal(mean=mus[zs[n, 0]], cov=sigma0)\n for t in range(1, T):\n zs[n, t] = int(np.random.choice(np.arange(K), p=A[zs[n, t - 1], :]))\n X[n, t] = np.random.multivariate_normal(mean=mus[zs[n, t]], cov=sigma0)\n\n return {'X': X, 'state_assignments': zs, 'A': A, 'initial_state_assignment': pi0, 'means': mus}\n from builtins import range\n\nimport autograd.numpy as np\n\n\ndef adam(grad, x, callback=None, num_iters=100, step_size=0.001, b1=0.9, b2=0.999, eps=10**-8, polyak=False):\n \"\"\"Adapted from autograd.misc.optimizers\"\"\"\n m = np.zeros(len(x))\n v = np.zeros(len(x))\n for i in range(num_iters):\n g = grad(x, i)\n if callback: callback(x, i, g, polyak)\n m = (1 - b1) * g + b1 * m # First moment estimate.\n v = (1 - b2) * (g**2) + b2 * v # Second moment estimate.\n mhat = m / (1 - b1**(i + 1)) # Bias correction.\n vhat = v / (1 - b2**(i + 1))\n x = x - step_size*mhat/(np.sqrt(vhat) + eps)\n return x import matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.random as npr\nimport torch as torch\n\n\ndef make_data_gap(seed, data_count=100):\n import GPy\n npr.seed(0)\n x = np.hstack([np.linspace(-5, -2, int(data_count/2)), np.linspace(2, 5, int(data_count/2))])\n x = x[:, np.newaxis]\n k = GPy.kern.RBF(input_dim=1, variance=1., lengthscale=1.)\n K = k.K(x)\n L = np.linalg.cholesky(K + 1e-5 * np.eye(data_count))\n\n # draw a noise free random function from a GP\n eps = np.random.randn(data_count)\n f = L @ eps\n\n\n # use a homoskedastic Gaussian noise model N(f(x)_i, \\\\sigma^2). \\\\sigma^2 = 0.1\n eps_noise = np.sqrt(0.1) * np.random.randn(data_count)\n y = f + eps_noise\n y = y[:, np.newaxis]\n\n plt.plot(x, f, 'ko', ms=2)\n plt.plot(x, y, 'ro')\n plt.title(\"GP generated Data\")\n plt.pause(1)\n return torch.FloatTensor(x), torch.FloatTensor(y), torch.FloatTensor(x), torch.FloatTensor(y)\n\n\ndef make_data_sine(seed, data_count=450):\n # fix the random seed\n np.random.seed(seed)\n noise_var = 0.1\n\n X = np.linspace(-4, 4, data_count)\n y = 1*np.sin(X) + np.sqrt(noise_var)*npr.randn(data_count)\n\n train_count = int (0.2 * data_count)\n idx = npr.permutation(range(data_", "instruction": "", "output": "" }, { "input": "count))\n X_train = X[idx[:train_count], np.newaxis ]\n X_test = X[ idx[train_count:], np.newaxis ]\n y_train = y[ idx[:train_count] ]\n y_test = y[ idx[train_count:] ]\n\n mu = np.mean(X_train, 0)\n std = np.std(X_train, 0)\n X_train = (X_train - mu) / std\n X_test = (X_test - mu) / std\n mu = np.mean(y_train, 0)\n std = np.std(y_train, 0)\n # mu = 0\n # std = 1\n y_train = (y_train - mu) / std\n y_test = (y_test -mu) / std\n train_stats = dict()\n train_stats['mu'] = torch.FloatTensor([mu])\n train_stats['sigma'] = torch.FloatTensor([std])\n return torch.FloatTensor(X_train), torch.FloatTensor(y_train), torch.FloatTensor(X_test), torch.FloatTensor(y_test),\\\\\n train_stats import autograd\nimport autograd.numpy as np\nimport numpy.random as npr\nimport scipy.optimize\n\nsigmoid = lambda x: 0.5 * (np.tanh(x / 2.) + 1)\nget_num_train = lambda inputs: inputs.shape[0]\nlogistic_predictions = lambda params, inputs: sigmoid(np.dot(inputs, params))\n\n\nclass LogisticRegression:\n def __init__(self):\n self.params = None\n\n def set_parameters(self, params):\n self.params = params\n\n def predict(self, X):\n if self.params is not None:\n # Outputs probability of a label being true according to logistic model\n return np.atleast_2d(sigmoid(np.dot(X, self.params))).T\n else:\n raise RuntimeError(\"Params need to be fit before predictions can be made.\")\n\n def loss(self, params, weights, inputs, targets):\n # Training loss is the negative log-likelihood of the training labels.\n preds = logistic_predictions(params, inputs)\n label_probabilities = preds * targets + (1 - preds) * (1 - targets)\n return -np.sum(weights * np.log(label_probabilities + 1e-16))\n\n def fit(self, weights, init_params, inputs, targets, verbose=True):\n training_loss_fun = lambda params: self.loss(params, weights, inputs, targets)\n # Define a function that returns gradients of training loss using Autograd.\n training_gradient_fun = autograd.grad(training_loss_fun, 0)\n # optimize params\n if verbose:\n print(\"Initial loss:\", self.loss(init_params, weights, inputs, targets))\n # opt_params = sgd(training_gradient_fun, params, hyper=1, num_iters=5000, step_size=0.1)\n res = scipy.optimize.minimize(fun=training_loss_fun,\n jac=training_gradient_fun,\n x0=init_params,\n tol=1e-10,\n options={'disp': verbose})\n opt_params = res.x\n if verbose:\n print(\"Trained loss:\", self.loss(opt_params, weights, inputs, targets))\n self.params = opt_params\n return opt_params\n\n def get_test_acc(self, params, test_targets, test_inputs):\n preds = np.round(self.predict(test_inputs).T).astype(np.int)\n err = np.abs(test_targets - preds).sum()\n return 1 - err/ test_targets.shape[1]\n\n #### Required for IJ computation ###\n def compute_hessian(self, params_one, weights_one, inputs, targets):\n return autograd.hessian(self.loss, argnum=0)(params_one, weights_one, inputs, targets)\n\n def compute_jacobian(self, params_one, weights_one, inputs, targets):\n return autograd.jacobian(autograd.jacobian(self.loss, argnum=0), argnum=1)\\\\\n (params_one, weights_one, inputs, targets).squeeze()\n ###################################################\n\n @staticmethod\n def synthetic_lr_data(N=10000, D=10):\n x = 1. * npr.randn(N, D)\n x_test = 1. * npr.randn(int(0.3 * N), D)\n w = npr.randn(D, 1)\n y = sigmoid((x @ w)).ravel()\n y = npr.binomial(n=1, p=y) # corrupt labels\n y_test = sigmoid(x_test @ w).ravel()\n # y_test = np.round(y_test)\n y_test = npr.binomial(n=1, p=y_test)\n return x, np.atleast_2d(y), x_test, np.atleast_2d(y_test)\n import abc\nimport sys\n\n# Ensure compatibility with Python 2/3\nif sys.version_info >= (3, 4):\n ABC = abc.ABC\nelse:\n ABC = abc.ABCMeta(str('ABC'), (), {})\n\nfrom copy import deepcopy\n\nimport numpy as np\nimport numpy.random as npr\n\n\ndef make_batches(n_data, batch_size):\n return [slice(i, min(i+batch_size, n_data)) for i in range(0, n_data, batch_size)]\n\n\ndef generate_regression_data(seed, data_count=500):\n \"\"\"\n Generate data from a noisy sine wave.\n :param seed: random number seed\n :param data_count: number of data points.\n :return:\n \"\"\"\n np.random.seed(seed)\n noise_var = 0.1\n\n x = np.linspace(-4, 4, data_count)\n y = 1*np.sin(x) + np.sqrt(noise_var)*npr.randn(data_count)\n\n train_count = int (0.2 * data_count)\n idx = npr.permutation(range(data_count))\n x_train = x[idx[:train_count], np.newaxis ]\n x_test = x[ idx[train_count:], np.newaxis ]\n y_train = y[ idx[:train_count] ]\n y_test = y[ idx[train_count:] ]\n\n mu = np.mean(x_train, 0)\n std = np.std(x_train, 0)\n x_train = (x_train - mu) / std\n x_test = (x_test - mu) / std\n mu = np.mean(y_train, 0)\n std = np.std(y_train, 0)\n y_train = (y_train - mu) / std\n train_stats = dict()\n train_stats['mu'] = mu\n train_stats['sigma'] = std\n\n return x_train, y_train, x_test, y_test, train_stats\n\n\ndef form_D_for_auucc(yhat, zhatl, zhatu):\n # a handy routine to format data as needed by the UCC fit() method\n D = np.zeros([yhat.shape[0], 3])\n D[:, 0] = yhat.squeeze()\n D[:, 1] = zhatl.squeeze()\n D[:, 2] = zhatu.squeeze()\n return D\n\n\ndef fitted_ucc_w_nullref(y_true, y_pred_mean, y_pred_lower, y_pred_upper):\n \"\"\"\n Instantiates an UCC object for the target predictor plus a 'null' (constant band) reference\n :param y_pred_lower:\n :param y_pred_mean:\n :param y_pred_upper:\n :param y_true:\n :return: ucc object fitted for two systems: target + null reference\n \"\"\"\n # form matrix for ucc:\n X_for_ucc = form_D_for_auucc(y_pred_mean.squeeze(),\n y_pred_mean.squeeze() - y_pred_lower.squeeze(),\n y_pred_upper.squeeze() - y_pred_mean.squeeze())\n # form matrix for a 'null' system (constant band)\n X_null = deepcopy(X_for_ucc)\n X_null[:,1:] = np.std(y_pred_mean) # can be set to any other constant (no effect on AUUCC)\n # create an instance of ucc and fit data\n from uq360.metrics.uncertainty_characteristics_curve import UncertaintyCharacteristicsCurve as ucc\n u = ucc()\n u.fit([X_for_ucc, X_null], y_true.squeeze())\n return u\n\n\ndef make_sklearn_compatible_scorer(task_type, metric, greater_is_better=True, **kwargs):\n \"\"\"\n\n Args:\n task_type: (str) regression or classification.\n metric: (str): choice of metric can be one of these - [aurrrc, ece, auroc, nll, brier, accuracy] for\n classification and [\"rmse\", \"nll\", \"auucc_gain\", \"picp\", \"mpiw\", \"r2\"] for regression.\n greater_is_better: is False the scores are negated before returning.\n **kwargs: additional arguments specific to some metrics.\n\n Returns:\n sklearn compatible scorer function.\n\n \"\"\"\n\n from uq360.metrics.classification_metrics import compute_classification_metrics\n from uq360.metrics.regression_metrics import compute_regression_metrics\n\n def sklearn_compatible_score(model, X, y_true):\n \"\"\"\n\n Args:\n model: The model being scored. Currently uq360 and sklearn models are supported.\n X: Input features.\n y_true: ground truth values for the target.\n\n Returns:\n Computed score of the model.\n\n \"\"\"\n\n from uq360.algorithms.builtinuq import BuiltinUQ\n from uq360.algorithms.posthocuq import PostHocUQ\n if isinstance(model, BuiltinUQ) or isinstance(model, PostHocUQ):\n # uq360 models\n if task_type == \"classification\":\n score = compute_classification_metrics(\n y_true=y_true,\n y_prob=model.predict(X).y_prob,\n option=metric,\n **kwargs\n )[metric]\n elif task_type == \"regression\":\n y_mean, y_lower, y_upper = model.predict(X)\n score = compute_regression_metrics(\n y_true=y_true,\n y_mean=y_mean,\n y_lower=y_lower,\n y_upper=y_upper,\n option=metric,\n **kwargs\n )[metric]\n else:\n raise NotImplementedError\n\n else:\n # sklearn models\n if task_type == \"classification\":\n score = compute_classification_metrics(\n y_true=y_true,\n y_prob=model.predict_proba(X),\n option=metric,\n **kwargs\n )[metric]\n else:\n if metric in [\"rmse\", \"r2\"]:\n score = compute_regression_metrics(\n y_true=y_true,\n y_mean=model.predict(X),\n y_lower=None,\n y_upper=None,\n option=metric,\n **kwargs\n )[metric]\n else:\n raise NotImplementedError(\"{} is not supported for sklearn regression models\".format(metric))\n\n if not greater_is_better:\n score = -score\n return score\n return sklearn_compatible_score\n\n\nclass DummySklearnEstimator(ABC):\n def __init__(self, num_classes, base_model_prediction_fn):\n self.base_model_prediction_fn = base_model_prediction_fn\n self.classes_ = [i for i in range(num_classes)]\n\n def fit(self):\n pass\n\n def predict_proba(self, X):\n return self.base_model_prediction_fn(X)\n from .meps_dataset import MEPSDataset\n # Adapted from https://github.com/Trusted-AI/AIX360/blob/master/aix360/datasets/meps_dataset.py\n# Utilization target is kept as a continuous target.\nimport os\n\nimport pandas as pd\n\n\ndef default_preprocessing(df):\n \"\"\"\n 1.Create a new column, RACE that is 'White' if RACEV2X = 1 and HISPANX = 2 i.e. non Hispanic White\n and 'non-White' otherwise\n 2. Restrict to Panel 19\n 3. RENAME all columns that are PANEL/ROUND SPECIFIC\n 4. Drop rows based on certain values of individual features that correspond to missing/unknown - generally < -1\n 5. Compute UTILIZATION.\n \"\"\"\n def race(row):\n if ((row['HISPANX'] == 2) and (row['RACEV2X'] == 1)): #non-Hispanic Whites are marked as WHITE; all others as NON-WHITE\n return 'White'\n return 'Non-White'\n\n df['RACEV2X'] = df.apply(lambda row: race(row), axis=1)\n df = df.rename(columns = {'RACEV2X' : 'RACE'})\n\n df = df[df['PANEL'] == 19]\n\n # RENAME COLUMNS\n df = df.rename(columns = {'FTSTU53X' : 'FTSTU', 'ACTDTY53' : 'ACTDTY', 'HONRDC53' : 'HONRDC', 'RTHLTH53' : 'RTHLTH',\n 'MNHLTH53' : 'MNHLTH', 'CHBRON53' : 'CHBRON', 'JTPAIN53' : 'JTPAIN', 'PREGNT53' : 'PREGNT',\n 'WLKLIM53' : 'WLKLIM', 'ACTLIM53' : 'ACTLIM', 'SOCLIM53' : 'SOCLIM', 'COGLIM53' : 'COGLIM',\n 'EMPST53' : 'EMPST', 'REGION53' : 'REGION', 'MARRY53X' : 'MARRY', 'AGE53X' : 'AGE',\n 'POVCAT15' : 'POVCAT', 'INSCOV15' : 'INSCOV'})\n\n df = df[df['REGION'] >= 0] # remove values -1\n df = df[df['AGE'] >= 0] # remove values -1\n\n df = df[df['MARRY'] >= 0] # remove values -1, -7, -8, -9\n\n df = df[df['ASTHDX'] >= 0] # remove values -1, -7, -8, -9\n\n df = df[(df[['FTSTU','ACTDTY','HONRDC','RTHLTH','MNHLTH','HIBPDX','CHDDX','ANGIDX','EDUCYR','HIDEG',\n", "instruction": "", "output": "" }, { "input": " 'MIDX','OHRTDX','STRKDX','EMPHDX','CHBRON','CHOLDX','CANCERDX','DIABDX',\n 'JTPAIN','ARTHDX','ARTHTYPE','ASTHDX','ADHDADDX','PREGNT','WLKLIM',\n 'ACTLIM','SOCLIM','COGLIM','DFHEAR42','DFSEE42','ADSMOK42',\n 'PHQ242','EMPST','POVCAT','INSCOV']] >= -1).all(1)] #for all other categorical features, remove values < -1\n\n def utilization(row):\n return row['OBTOTV15'] + row['OPTOTV15'] + row['ERTOT15'] + row['IPNGTD15'] + row['HHTOTD15']\n\n df['TOTEXP15'] = df.apply(lambda row: utilization(row), axis=1)\n\n df = df.rename(columns = {'TOTEXP15' : 'UTILIZATION'})\n\n df = df[['REGION','AGE','SEX','RACE','MARRY',\n 'FTSTU','ACTDTY','HONRDC','RTHLTH','MNHLTH','HIBPDX','CHDDX','ANGIDX',\n 'MIDX','OHRTDX','STRKDX','EMPHDX','CHBRON','CHOLDX','CANCERDX','DIABDX',\n 'JTPAIN','ARTHDX','ARTHTYPE','ASTHDX','ADHDADDX','PREGNT','WLKLIM',\n 'ACTLIM','SOCLIM','COGLIM','DFHEAR42','DFSEE42','ADSMOK42','PCS42',\n 'MCS42','K6SUM42','PHQ242','EMPST','POVCAT','INSCOV','UTILIZATION','PERWT15F']]\n\n return df\n\n\nclass MEPSDataset():\n \"\"\"\n The Medical Expenditure Panel Survey (MEPS) [#]_ data consists of large scale surveys of families and individuals,\n medical providers, and employers, and collects data on health services used, costs & frequency of services,\n demographics, health status and conditions, etc., of the respondents.\n This specific dataset contains MEPS survey data for calendar year 2015 obtained in rounds 3, 4, and 5 of Panel 19,\n and rounds 1, 2, and 3 of Panel 20.\n See :file:`uq360/datasets/data/meps_data/README.md` for more details on the dataset and instructions on downloading/processing the data.\n References:\n .. [#] `Medical Expenditure Panel Survey data `_\n \"\"\"\n\n def __init__(self, custom_preprocessing=default_preprocessing, dirpath=None):\n self._dirpath = dirpath\n if not self._dirpath:\n self._dirpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'meps_data')\n\n self._filepath = os.path.join(self._dirpath, 'h181.csv')\n try:\n df = pd.read_csv(self._filepath, sep=',', na_values=[])\n except IOError as err:\n print(\"IOError: {}\".format(err))\n print(\"To use this class, please place the heloc_dataset.csv:\")\n print(\"file, as-is, in the folder:\")\n print(\"\\\\n\\\\t{}\\\\n\".format(os.path.abspath(os.path.join(\n os.path.abspath(__file__), 'data', 'meps_data'))))\n import sys\n sys.exit(1)\n\n if custom_preprocessing:\n self._data = custom_preprocessing(df)\n\n def data(self):\n return self._data # Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Base class for generating the feature_statistics proto from TensorFlow data.\n\nThe proto is used as input for the Overview visualization.\n\"\"\"\n\nfrom functools import partial\nfrom facets_overview.base_generic_feature_statistics_generator import BaseGenericFeatureStatisticsGenerator\nimport tensorflow as tf\n\n\n# The feature name used to track sequence length when analyzing\n# tf.SequenceExamples.\nSEQUENCE_LENGTH_FEATURE_NAME = 'sequence length (derived feature)'\n\n\nclass BaseFeatureStatisticsGenerator(BaseGenericFeatureStatisticsGenerator):\n \"\"\"Base class for generator of stats proto from TF data.\"\"\"\n\n def __init__(self, fs_proto, datasets_proto, histogram_proto):\n BaseGenericFeatureStatisticsGenerator.__init__(\n self, fs_proto, datasets_proto, histogram_proto)\n\n def ProtoFromTfRecordFiles(self,\n files,\n max_entries=10000,\n features=None,\n is_sequence=False,\n iterator_options=None,\n histogram_categorical_levels_count=None):\n \"\"\"Creates a feature statistics proto from a set of TFRecord files.\n\n Args:\n files: A list of dicts describing files for each dataset for the proto.\n Each\n entry contains a 'path' field with the path to the TFRecord file on\n disk\n and a 'name' field to identify the dataset in the proto.\n max_entries: The maximum number of examples to load from each dataset\n in order to create the proto. Defaults to 10000.\n features: A list of strings that is a whitelist of feature names to create\n feature statistics for. If set to None then all features in the\n dataset\n are analyzed. Defaults to None.\n is_sequence: True if the input data from 'tables' are tf.SequenceExamples,\n False if tf.Examples. Defaults to false.\n iterator_options: Options to pass to the iterator that reads the examples.\n Defaults to None.\n histogram_categorical_levels_count: int, controls the maximum number of\n levels to display in histograms for categorical features.\n Useful to prevent codes/IDs features from bloating the stats object.\n Defaults to None.\n\n Returns:\n The feature statistics proto for the provided files.\n \"\"\"\n datasets = []\n for entry in files:\n entries, size = self._GetTfRecordEntries(entry['path'], max_entries,\n is_sequence, iterator_options)\n datasets.append({'entries': entries, 'size': size, 'name': entry['name']})\n return self.GetDatasetsProto(\n datasets,\n features,\n histogram_categorical_levels_count)\n\n def _ParseExample(self, example_features, example_feature_lists, entries,\n index):\n \"\"\"Parses data from an example, populating a dictionary of feature values.\n\n Args:\n example_features: A map of strings to tf.Features from the example.\n example_feature_lists: A map of strings to tf.FeatureLists from the\n example.\n entries: A dictionary of all features parsed thus far and arrays of their\n values. This is mutated by the function.\n index: The index of the example to parse from a list of examples.\n Raises:\n TypeError: Raises an exception when a feature has inconsistent types\n across\n examples.\n \"\"\"\n features_seen = set()\n\n for feature_list, is_feature in zip(\n [example_features, example_feature_lists], [True, False]):\n sequence_length = None\n for feature_name in feature_list:\n # If this feature has not been seen in previous examples, then\n # initialize its entry into the entries dictionary.\n if feature_name not in entries:\n entries[feature_name] = {\n 'vals': [],\n 'counts': [],\n 'feat_lens': [],\n 'missing': index\n }\n\n feature_entry = entries[feature_name]\n feature = feature_list[feature_name]\n\n value_type = None\n value_list = []\n if is_feature:\n # If parsing a tf.Feature, extract the type and values simply.\n if feature.HasField('float_list'):\n value_list = feature.float_list.value\n value_type = self.fs_proto.FLOAT\n elif feature.HasField('bytes_list'):\n value_list = feature.bytes_list.value\n value_type = self.fs_proto.STRING\n elif feature.HasField('int64_list'):\n value_list = feature.int64_list.value\n value_type = self.fs_proto.INT\n else:\n # If parsing a tf.FeatureList, get the type and values by iterating\n # over all Features in the FeatureList.\n sequence_length = len(feature.feature)\n if sequence_length != 0 and feature.feature[0].HasField('float_list'):\n for feat in feature.feature:\n for value in feat.float_list.value:\n value_list.append(value)\n value_type = self.fs_proto.FLOAT\n elif sequence_length != 0 and feature.feature[0].HasField(\n 'bytes_list'):\n for feat in feature.feature:\n for value in feat.bytes_list.value:\n value_list.append(value)\n value_type = self.fs_proto.STRING\n elif sequence_length != 0 and feature.feature[0].HasField(\n 'int64_list'):\n for feat in feature.feature:\n for value in feat.int64_list.value:\n value_list.append(value)\n value_type = self.fs_proto.INT\n if value_type is not None:\n if 'type' not in feature_entry:\n feature_entry['type'] = value_type\n elif feature_entry['type'] != value_type:\n raise TypeError('type mismatch for feature ' + feature_name)\n feature_entry['counts'].append(len(value_list))\n feature_entry['vals'].extend(value_list)\n if sequence_length is not None:\n feature_entry['feat_lens'].append(sequence_length)\n if value_list:\n features_seen.add(feature_name)\n\n # For all previously-seen features not found in this example, update the\n # feature's missing value.\n for f in entries:\n fv = entries[f]\n if f not in features_seen:\n fv['missing'] += 1\n\n def _GetEntries(self,\n paths,\n max_entries,\n iterator_from_file,\n is_sequence=False):\n \"\"\"Extracts examples into a dictionary of feature values.\n\n Args:\n paths: A list of the paths to the files to parse.\n max_entries: The maximum number of examples to load.\n iterator_from_file: A method that takes a file path string and returns an\n iterator to the examples in that file.\n is_sequence: True if the input data from 'iterator_from_file' are\n tf.SequenceExamples, False if tf.Examples. Defaults to false.\n\n Returns:\n A tuple with two elements:\n - A dictionary of all features parsed thus far and arrays of their\n values.\n - The number of examples parsed.\n \"\"\"\n entries = {}\n index = 0\n for filepath in paths:\n reader = iterator_from_file(filepath)\n for record in reader:\n if is_sequence:\n sequence_example = tf.train.SequenceExample.FromString(record)\n self._ParseExample(sequence_example.context.feature,\n sequence_example.feature_lists.feature_list,\n entries, index)\n else:\n self._ParseExample(\n tf.train.Example.FromString(record).features.feature, [], entries,\n index)\n index += 1\n if index == max_entries:\n return entries, index\n return entries, index\n\n def _GetTfRecordEntries(self, path, max_entries, is_sequence,\n iterator_options):\n \"\"\"Extracts TFRecord examples into a dictionary of feature values.\n\n Args:\n path: The path to the TFRecord file(s).\n max_entries: The maximum number of examples to load.\n is_sequence: True if the input data from 'path' are tf.SequenceExamples,\n False if tf.Examples. Defaults to false.\n iterator_options: Options to pass to the iterator that reads the examples.\n Defaults to None.\n\n Returns:\n A tuple with two elements:\n - A dictionary of all features parsed thus far and arrays of their\n values.\n - The number of examples parsed.\n \"\"\"\n return self._GetEntries([path], max_entries,\n partial(\n tf.compat.v1.io.tf_record_iterator,\n options=iterator_options), is_sequence)\n # Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nfrom facets_overview.generic_feature_statistics_generator import GenericFeatureStatisticsGenerator\nimport numpy as np\nimport pandas as pd\nfrom tensorflow.python.platform import googletest\n\n\nclass GenericFeatureStatisticsGeneratorTest(googletest.TestCase):\n\n def setUp(self):\n self.gfsg = GenericFeatureStatisticsGenerator()\n\n def testProtoFromDataFrames(self):\n data = [[1, 'hi'], [2, 'hello'], [3, 'hi']]\n df = pd.DataFrame(data, columns=['testFeatureInt', 'testFeatureString'])\n dataframes = [{'table': df, 'name': 'testDataset'}]\n p = self.gfsg.ProtoFromDataFrames(dataframes)\n\n self.assertEqual(1, len(p.datasets))\n test_data = p.datasets[0]\n self.assertEqual('testDataset', test_data.name)\n self.assertEqual(3, test_data.num_examples)\n self.assertEqual(2, len(test_data.features))\n\n if test_data.features[0].name == 'testFeatureInt':\n numfeat = test_data.features[0]\n stringfeat = test_data.features[1]\n else:\n numfeat = test_data.features[1]\n stringfeat = test_data.features[0]\n\n self.assertEqual('testFeatureInt', numfeat.name)\n self.assertEqual(self.gfsg.fs_proto.INT, numfeat.type)\n self.assertEqual(1, numfeat.num_stats.min)\n self.assertEqual(3, numfeat.num_stats.max)\n self.assertEqual('testFeatureString', stringfeat.name)", "instruction": "", "output": "" }, { "input": "\n self.assertEqual(self.gfsg.fs_proto.STRING, stringfeat.type)\n self.assertEqual(2, stringfeat.string_stats.unique)\n\n def testNdarrayToEntry(self):\n arr = np.array([1.0, 2.0, None, float('nan'), 3.0], dtype=float)\n\n entry = self.gfsg.NdarrayToEntry(arr)\n self.assertEqual(2, entry['missing'])\n\n arr = np.array(['a', 'b', float('nan'), 'c'], dtype=str)\n entry = self.gfsg.NdarrayToEntry(arr)\n self.assertEqual(1, entry['missing'])\n\n def testNdarrayToEntryTimeTypes(self):\n arr = np.array(\n [np.datetime64('2005-02-25'),\n np.datetime64('2006-02-25')],\n dtype=np.datetime64)\n entry = self.gfsg.NdarrayToEntry(arr)\n self.assertEqual([1109289600000000000, 1140825600000000000], entry['vals'])\n\n arr = np.array(\n [np.datetime64('2009-01-01') - np.datetime64('2008-01-01')],\n dtype=np.timedelta64)\n entry = self.gfsg.NdarrayToEntry(arr)\n self.assertEqual([31622400000000000], entry['vals'])\n\n def testDTypeToType(self):\n self.assertEqual(self.gfsg.fs_proto.INT,\n self.gfsg.DtypeToType(np.dtype(np.int32)))\n # Boolean and time types treated as int\n self.assertEqual(self.gfsg.fs_proto.INT,\n self.gfsg.DtypeToType(np.dtype(np.bool)))\n self.assertEqual(self.gfsg.fs_proto.INT,\n self.gfsg.DtypeToType(np.dtype(np.datetime64)))\n self.assertEqual(self.gfsg.fs_proto.INT,\n self.gfsg.DtypeToType(np.dtype(np.timedelta64)))\n self.assertEqual(self.gfsg.fs_proto.FLOAT,\n self.gfsg.DtypeToType(np.dtype(np.float32)))\n self.assertEqual(self.gfsg.fs_proto.STRING,\n self.gfsg.DtypeToType(np.dtype(np.str)))\n # Unsupported types treated as string for now\n self.assertEqual(self.gfsg.fs_proto.STRING,\n self.gfsg.DtypeToType(np.dtype(np.void)))\n\n def testGetDatasetsProtoFromEntriesLists(self):\n entries = {}\n entries['testFeature'] = {\n 'vals': [1, 2, 3],\n 'counts': [1, 1, 1],\n 'missing': 0,\n 'type': self.gfsg.fs_proto.INT\n }\n datasets = [{'entries': entries, 'size': 3, 'name': 'testDataset'}]\n p = self.gfsg.GetDatasetsProto(datasets)\n\n self.assertEqual(1, len(p.datasets))\n test_data = p.datasets[0]\n self.assertEqual('testDataset', test_data.name)\n self.assertEqual(3, test_data.num_examples)\n self.assertEqual(1, len(test_data.features))\n numfeat = test_data.features[0]\n self.assertEqual('testFeature', numfeat.name)\n self.assertEqual(self.gfsg.fs_proto.INT, numfeat.type)\n self.assertEqual(1, numfeat.num_stats.min)\n self.assertEqual(3, numfeat.num_stats.max)\n hist = numfeat.num_stats.common_stats.num_values_histogram\n buckets = hist.buckets\n self.assertEqual(self.gfsg.histogram_proto.QUANTILES, hist.type)\n self.assertEqual(10, len(buckets))\n self.assertEqual(1, buckets[0].low_value)\n self.assertEqual(1, buckets[0].high_value)\n self.assertEqual(.3, buckets[0].sample_count)\n self.assertEqual(1, buckets[9].low_value)\n self.assertEqual(1, buckets[9].high_value)\n self.assertEqual(.3, buckets[9].sample_count)\n\n def testGetDatasetsProtoSequenceExampleHistogram(self):\n entries = {}\n entries['testFeature'] = {\n 'vals': [1, 2, 2, 3],\n 'counts': [1, 2, 1],\n 'feat_lens': [1, 2, 1],\n 'missing': 0,\n 'type': self.gfsg.fs_proto.INT\n }\n datasets = [{'entries': entries, 'size': 3, 'name': 'testDataset'}]\n p = self.gfsg.GetDatasetsProto(datasets)\n hist = p.datasets[0].features[\n 0].num_stats.common_stats.feature_list_length_histogram\n buckets = hist.buckets\n self.assertEqual(self.gfsg.histogram_proto.QUANTILES, hist.type)\n self.assertEqual(10, len(buckets))\n self.assertEqual(1, buckets[0].low_value)\n self.assertEqual(1, buckets[0].high_value)\n self.assertEqual(.3, buckets[0].sample_count)\n self.assertEqual(1.8, buckets[9].low_value)\n self.assertEqual(2, buckets[9].high_value)\n self.assertEqual(.3, buckets[9].sample_count)\n\n def testGetDatasetsProtoWithWhitelist(self):\n entries = {}\n entries['testFeature'] = {\n 'vals': [1, 2, 3],\n 'counts': [1, 1, 1],\n 'missing': 0,\n 'type': self.gfsg.fs_proto.INT\n }\n entries['ignoreFeature'] = {\n 'vals': [5, 6],\n 'counts': [1, 1],\n 'missing': 1,\n 'type': self.gfsg.fs_proto.INT\n }\n datasets = [{'entries': entries, 'size': 3, 'name': 'testDataset'}]\n p = self.gfsg.GetDatasetsProto(datasets, features=['testFeature'])\n\n self.assertEqual(1, len(p.datasets))\n test_data = p.datasets[0]\n self.assertEqual('testDataset', test_data.name)\n self.assertEqual(3, test_data.num_examples)\n self.assertEqual(1, len(test_data.features))\n numfeat = test_data.features[0]\n self.assertEqual('testFeature', numfeat.name)\n self.assertEqual(1, numfeat.num_stats.min)\n\n def testGetDatasetsProtoWithMaxHistigramLevelsCount(self):\n # Selected entries' lengths make it easy to compute average length\n data = [['hi'], ['good'], ['hi'], ['hi'], ['a'], ['a']]\n df = pd.DataFrame(data, columns=['testFeatureString'])\n dataframes = [{'table': df, 'name': 'testDataset'}]\n # Getting proto from ProtoFromDataFrames instead of GetDatasetsProto\n # directly to avoid any hand written values ex: size of dataset.\n p = self.gfsg.ProtoFromDataFrames(dataframes,\n histogram_categorical_levels_count=2)\n\n self.assertEqual(1, len(p.datasets))\n test_data = p.datasets[0]\n self.assertEqual('testDataset', test_data.name)\n self.assertEqual(6, test_data.num_examples)\n self.assertEqual(1, len(test_data.features))\n numfeat = test_data.features[0]\n self.assertEqual('testFeatureString', numfeat.name)\n\n top_values = numfeat.string_stats.top_values\n self.assertEqual(3, top_values[0].frequency)\n self.assertEqual('hi', top_values[0].value)\n\n self.assertEqual(3, numfeat.string_stats.unique)\n self.assertEqual(2, numfeat.string_stats.avg_length)\n\n rank_hist = numfeat.string_stats.rank_histogram\n buckets = rank_hist.buckets\n self.assertEqual(2, len(buckets))\n self.assertEqual('hi', buckets[0].label)\n self.assertEqual(3, buckets[0].sample_count)\n self.assertEqual('a', buckets[1].label)\n self.assertEqual(2, buckets[1].sample_count)\n\nif __name__ == '__main__':\n googletest.main()\n # Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Code for generating the feature_statistics proto from generic data.\n\nThe proto is used as input for the Overview visualization.\n\"\"\"\n\nfrom facets_overview.base_generic_feature_statistics_generator import BaseGenericFeatureStatisticsGenerator\nimport facets_overview.feature_statistics_pb2 as fs\n\n\nclass GenericFeatureStatisticsGenerator(BaseGenericFeatureStatisticsGenerator):\n \"\"\"Generator of stats proto from generic data.\"\"\"\n\n def __init__(self):\n BaseGenericFeatureStatisticsGenerator.__init__(\n self, fs.FeatureNameStatistics, fs.DatasetFeatureStatisticsList,\n fs.Histogram)\n # Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nfrom facets_overview.feature_statistics_generator import FeatureStatisticsGenerator\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.platform import googletest\n\n\nclass FeatureStatisticsGeneratorTest(googletest.TestCase):\n\n def setUp(self):\n self.fs = FeatureStatisticsGenerator()\n\n def testParseExampleInt(self):\n # Tests parsing examples of integers\n examples = []\n for i in range(50):\n example = tf.train.Example()\n example.features.feature['num'].int64_list.value.append(i)\n examples.append(example)\n\n entries = {}\n for i, example in enumerate(examples):\n self.fs._ParseExample(example.features.feature, [], entries, i)\n\n self.assertEqual(1, len(entries))\n self.assertIn('num', entries)\n info = entries['num']\n self.assertEqual(0, info['missing'])\n self.assertEqual(self.fs.fs_proto.INT, info['type'])\n for i in range(len(examples)):\n self.assertEqual(1, info['counts'][i])\n self.assertEqual(i, info['vals'][i])\n\n def testParseExampleMissingValueList(self):\n # Tests parsing examples of integers\n examples = []\n example = tf.train.Example()\n # pylint: disable=pointless-statement\n example.features.feature['str']\n # pylint: enable=pointless-statement\n examples.append(example)\n example = tf.train.Example()\n example.features.feature['str'].bytes_list.value.append(b'test')\n examples.append(example)\n\n entries = {}\n for i, example in enumerate(examples):\n self.fs._ParseExample(example.features.feature, [], entries, i)\n\n self.assertEqual(1, len(entries))\n self.assertIn('str', entries)\n info = entries['str']\n self.assertEqual(1, info['missing'])\n self.assertEqual(self.fs.fs_proto.STRING, info['type'])\n self.assertEqual(0, info['counts'][0])\n self.assertEqual(1, info['counts'][1])\n\n def _check_sequence_example_entries(self,\n entries,\n n_examples,\n n_features,\n feat_len=None):\n self.assertIn('num', entries)\n info = entries['num']\n self.assertEqual(0, info['missing'])\n self.assertEqual(self.fs.fs_proto.INT, info['type'])\n for i in range(n_examples):\n self.assertEqual(n_features, info['counts'][i])\n if feat_len is not None:\n self.assertEqual(feat_len, info['feat_lens'][i])\n for i in range(n_examples * n_features):\n self.assertEqual(i, info['vals'][i])\n if feat_len is None:\n self.assertEqual(0, len(info['feat_lens']))\n\n def testParseExampleSequenceContext(self):\n # Tests parsing examples of integers in context field\n examples = []\n for i in range(50):\n example = tf.train.SequenceExample()\n example.context.feature['num'].int64_list.value.append(i)\n examples.append(example)\n\n entries = {}\n for i, example in enumerate(examples):\n self.fs._ParseExample(example.context.feature,\n example.feature_lists.feature_list, entries, i)\n self._check_sequence_example_entries(entries, 50, 1)\n self.assertEqual(1, len(entries))\n\n def testParseExampleSequenceFeatureList(self):\n examples = []\n for i in range(50):\n example = tf.train.SequenceExample()\n feat = example.feature_lists.feature_list['num'].feature.add()\n feat.int64_list.value.append(i)\n examples.append(example)\n\n entries = {}\n for i, example in enumerate(examples):\n self.fs._ParseExample(example.context.feature,\n example.feature_lists.feature_list, entries, i)\n self._check_sequence_example_entries(entries, 50, 1, 1)\n\n def testParseExampleSequenceFeature", "instruction": "", "output": "" }, { "input": "ListMultipleEntriesInner(self):\n examples = []\n for i in range(2):\n example = tf.train.SequenceExample()\n feat = example.feature_lists.feature_list['num'].feature.add()\n for j in range(25):\n feat.int64_list.value.append(i * 25 + j)\n examples.append(example)\n\n entries = {}\n for i, example in enumerate(examples):\n self.fs._ParseExample(example.context.feature,\n example.feature_lists.feature_list, entries, i)\n\n self._check_sequence_example_entries(entries, 2, 25, 1)\n\n def testParseExampleSequenceFeatureListMultipleEntriesOuter(self):\n # Tests parsing examples of integers in context field\n examples = []\n for i in range(2):\n example = tf.train.SequenceExample()\n for j in range(25):\n feat = example.feature_lists.feature_list['num'].feature.add()\n feat.int64_list.value.append(i * 25 + j)\n examples.append(example)\n\n entries = {}\n for i, example in enumerate(examples):\n self.fs._ParseExample(example.context.feature,\n example.feature_lists.feature_list, entries, i)\n self._check_sequence_example_entries(entries, 2, 25, 25)\n\n def testVaryingCountsAndMissing(self):\n # Tests parsing examples of when some examples have missing features\n examples = []\n for i in range(5):\n example = tf.train.Example()\n example.features.feature['other'].int64_list.value.append(0)\n for _ in range(i):\n example.features.feature['num'].int64_list.value.append(i)\n examples.append(example)\n example = tf.train.Example()\n example.features.feature['other'].int64_list.value.append(0)\n examples.append(example)\n\n entries = {}\n for i, example in enumerate(examples):\n self.fs._ParseExample(example.features.feature, [], entries, i)\n\n info = entries['num']\n self.assertEqual(2, info['missing'])\n self.assertEqual(4, len(info['counts']))\n for i in range(4):\n self.assertEqual(i + 1, info['counts'][i])\n self.assertEqual(10, len(info['vals']))\n\n def testParseExampleStringsAndFloats(self):\n # Tests parsing examples of string and float features\n examples = []\n for i in range(50):\n example = tf.train.Example()\n example.features.feature['str'].bytes_list.value.append(b'hi')\n example.features.feature['float'].float_list.value.append(i)\n examples.append(example)\n\n entries = {}\n for i, example in enumerate(examples):\n self.fs._ParseExample(example.features.feature, [], entries, i)\n\n self.assertEqual(2, len(entries))\n self.assertEqual(self.fs.fs_proto.FLOAT, entries['float']['type'])\n self.assertEqual(self.fs.fs_proto.STRING, entries['str']['type'])\n for i in range(len(examples)):\n self.assertEqual(1, entries['str']['counts'][i])\n self.assertEqual(1, entries['float']['counts'][i])\n self.assertEqual(i, entries['float']['vals'][i])\n self.assertEqual('hi', entries['str']['vals'][i].decode(\n 'UTF-8', 'strict'))\n\n def testParseExamplesTypeMismatch(self):\n examples = []\n example = tf.train.Example()\n example.features.feature['feat'].int64_list.value.append(0)\n examples.append(example)\n example = tf.train.Example()\n example.features.feature['feat'].bytes_list.value.append(b'str')\n examples.append(example)\n\n entries = {}\n self.fs._ParseExample(examples[0].features.feature, [], entries, 0)\n\n with self.assertRaises(TypeError):\n self.fs._ParseExample(examples[1].features.feature, [], entries, 1)\n\n def testGetDatasetsProtoFromEntriesLists(self):\n entries = {}\n entries['testFeature'] = {\n 'vals': [1, 2, 3],\n 'counts': [1, 1, 1],\n 'missing': 0,\n 'type': self.fs.fs_proto.INT\n }\n datasets = [{'entries': entries, 'size': 3, 'name': 'testDataset'}]\n p = self.fs.GetDatasetsProto(datasets)\n\n self.assertEqual(1, len(p.datasets))\n test_data = p.datasets[0]\n self.assertEqual('testDataset', test_data.name)\n self.assertEqual(3, test_data.num_examples)\n self.assertEqual(1, len(test_data.features))\n numfeat = test_data.features[0]\n self.assertEqual('testFeature', numfeat.name)\n self.assertEqual(self.fs.fs_proto.INT, numfeat.type)\n self.assertEqual(1, numfeat.num_stats.min)\n self.assertEqual(3, numfeat.num_stats.max)\n\n def testGetProtoNums(self):\n # Tests converting int examples into the feature stats proto\n examples = []\n for i in range(50):\n example = tf.train.Example()\n example.features.feature['num'].int64_list.value.append(i)\n examples.append(example)\n example = tf.train.Example()\n example.features.feature['other'].int64_list.value.append(0)\n examples.append(example)\n\n entries = {}\n for i, example in enumerate(examples):\n self.fs._ParseExample(example.features.feature, [], entries, i)\n\n datasets = [{'entries': entries, 'size': len(examples), 'name': 'test'}]\n p = self.fs.GetDatasetsProto(datasets)\n\n self.assertEqual(1, len(p.datasets))\n test_data = p.datasets[0]\n self.assertEqual('test', test_data.name)\n self.assertEqual(51, test_data.num_examples)\n\n numfeat = test_data.features[0] if (\n test_data.features[0].name == 'num') else test_data.features[1]\n self.assertEqual('num', numfeat.name)\n self.assertEqual(self.fs.fs_proto.INT, numfeat.type)\n self.assertEqual(0, numfeat.num_stats.min)\n self.assertEqual(49, numfeat.num_stats.max)\n self.assertEqual(24.5, numfeat.num_stats.mean)\n self.assertEqual(24.5, numfeat.num_stats.median)\n self.assertEqual(1, numfeat.num_stats.num_zeros)\n self.assertAlmostEqual(14.430869689, numfeat.num_stats.std_dev, 4)\n self.assertEqual(1, numfeat.num_stats.common_stats.num_missing)\n self.assertEqual(50, numfeat.num_stats.common_stats.num_non_missing)\n self.assertEqual(1, numfeat.num_stats.common_stats.min_num_values)\n self.assertEqual(1, numfeat.num_stats.common_stats.max_num_values)\n self.assertAlmostEqual(1, numfeat.num_stats.common_stats.avg_num_values, 4)\n hist = numfeat.num_stats.common_stats.num_values_histogram\n buckets = hist.buckets\n self.assertEqual(self.fs.histogram_proto.QUANTILES, hist.type)\n self.assertEqual(10, len(buckets))\n self.assertEqual(1, buckets[0].low_value)\n self.assertEqual(1, buckets[0].high_value)\n self.assertEqual(5, buckets[0].sample_count)\n self.assertEqual(1, buckets[9].low_value)\n self.assertEqual(1, buckets[9].high_value)\n self.assertEqual(5, buckets[9].sample_count)\n\n self.assertEqual(2, len(numfeat.num_stats.histograms))\n buckets = numfeat.num_stats.histograms[0].buckets\n self.assertEqual(self.fs.histogram_proto.STANDARD,\n numfeat.num_stats.histograms[0].type)\n self.assertEqual(10, len(buckets))\n self.assertEqual(0, buckets[0].low_value)\n self.assertEqual(4.9, buckets[0].high_value)\n self.assertEqual(5, buckets[0].sample_count)\n self.assertAlmostEqual(44.1, buckets[9].low_value)\n self.assertEqual(49, buckets[9].high_value)\n self.assertEqual(5, buckets[9].sample_count)\n\n buckets = numfeat.num_stats.histograms[1].buckets\n self.assertEqual(self.fs.histogram_proto.QUANTILES,\n numfeat.num_stats.histograms[1].type)\n self.assertEqual(10, len(buckets))\n self.assertEqual(0, buckets[0].low_value)\n self.assertEqual(4.9, buckets[0].high_value)\n self.assertEqual(5, buckets[0].sample_count)\n self.assertAlmostEqual(44.1, buckets[9].low_value)\n self.assertEqual(49, buckets[9].high_value)\n self.assertEqual(5, buckets[9].sample_count)\n\n def testQuantiles(self):\n examples = []\n for i in range(50):\n example = tf.train.Example()\n example.features.feature['num'].int64_list.value.append(i)\n examples.append(example)\n for i in range(50):\n example = tf.train.Example()\n example.features.feature['num'].int64_list.value.append(100)\n examples.append(example)\n\n entries = {}\n for i, example in enumerate(examples):\n self.fs._ParseExample(example.features.feature, [], entries, i)\n\n datasets = [{'entries': entries, 'size': len(examples), 'name': 'test'}]\n p = self.fs.GetDatasetsProto(datasets)\n\n numfeat = p.datasets[0].features[0]\n self.assertEqual(2, len(numfeat.num_stats.histograms))\n self.assertEqual(self.fs.histogram_proto.QUANTILES,\n numfeat.num_stats.histograms[1].type)\n buckets = numfeat.num_stats.histograms[1].buckets\n self.assertEqual(10, len(buckets))\n self.assertEqual(0, buckets[0].low_value)\n self.assertEqual(9.9, buckets[0].high_value)\n self.assertEqual(10, buckets[0].sample_count)\n self.assertEqual(100, buckets[9].low_value)\n self.assertEqual(100, buckets[9].high_value)\n self.assertEqual(10, buckets[9].sample_count)\n\n def testInfinityAndNan(self):\n examples = []\n for i in range(50):\n example = tf.train.Example()\n example.features.feature['num'].float_list.value.append(i)\n examples.append(example)\n example = tf.train.Example()\n example.features.feature['num'].float_list.value.append(float('inf'))\n examples.append(example)\n example = tf.train.Example()\n example.features.feature['num'].float_list.value.append(float('-inf'))\n examples.append(example)\n example = tf.train.Example()\n example.features.feature['num'].float_list.value.append(float('nan'))\n examples.append(example)\n\n entries = {}\n for i, example in enumerate(examples):\n self.fs._ParseExample(example.features.feature, [], entries, i)\n\n datasets = [{'entries': entries, 'size': len(examples), 'name': 'test'}]\n p = self.fs.GetDatasetsProto(datasets)\n\n numfeat = p.datasets[0].features[0]\n\n self.assertEqual('num', numfeat.name)\n self.assertEqual(self.fs.fs_proto.FLOAT, numfeat.type)\n self.assertTrue(np.isnan(numfeat.num_stats.min))\n self.assertTrue(np.isnan(numfeat.num_stats.max))\n self.assertTrue(np.isnan(numfeat.num_stats.mean))\n self.assertTrue(np.isnan(numfeat.num_stats.median))\n self.assertEqual(1, numfeat.num_stats.num_zeros)\n self.assertTrue(np.isnan(numfeat.num_stats.std_dev))\n self.assertEqual(53, numfeat.num_stats.common_stats.num_non_missing)\n hist = buckets = numfeat.num_stats.histograms[0]\n buckets = hist.buckets\n self.assertEqual(self.fs.histogram_proto.STANDARD, hist.type)\n self.assertEqual(1, hist.num_nan)\n self.assertEqual(10, len(buckets))\n self.assertEqual(float('-inf'), buckets[0].low_value)\n self.assertEqual(4.9, buckets[0].high_value)\n self.assertEqual(6, buckets[0].sample_count)\n self.assertEqual(44.1, buckets[9].low_value)\n self.assertEqual(float('inf'), buckets[9].high_value)\n self.assertEqual(6, buckets[9].sample_count)\n\n def testInfinitysOnly(self):\n examples = []\n example = tf.train.Example()\n example.features.feature['num'].float_list.value.append(float('inf'))\n examples.append(example)\n example = tf.train.Example()\n example.features.feature['num'].float_list.value.append(float('-inf'))\n examples.append(example)\n\n entries = {}\n for i, example in enumerate(examples):\n self.fs._ParseExample(example.features.feature, [], entries, i)\n\n datasets = [{'entries': entries, 'size': len(examples), 'name': 'test'}]\n p = self.fs.GetDatasetsProto(datasets)\n\n numfeat = p.datasets[0].features[0]\n hist = buckets = numfeat.num_stats.histograms[0]\n buckets = hist.buckets\n self.assertEqual(self.fs.histogram_proto.STANDARD, hist.type)\n self.assertEqual(10, len(buckets))\n self.assertEqual(float('-inf'), buckets[0].low_value)\n self.assertEqual(0.1, buckets[0].high_value)\n self.assertEqual(1, buckets[0].sample_count)\n self.assertEqual(0.", "instruction": "", "output": "" }, { "input": "9, buckets[9].low_value)\n self.assertEqual(float('inf'), buckets[9].high_value)\n self.assertEqual(1, buckets[9].sample_count)\n\n def testGetProtoStrings(self):\n # Tests converting string examples into the feature stats proto\n examples = []\n for i in range(2):\n example = tf.train.Example()\n example.features.feature['str'].bytes_list.value.append(b'hello')\n examples.append(example)\n for i in range(3):\n example = tf.train.Example()\n example.features.feature['str'].bytes_list.value.append(b'hi')\n examples.append(example)\n example = tf.train.Example()\n example.features.feature['str'].bytes_list.value.append(b'hey')\n examples.append(example)\n\n entries = {}\n for i, example in enumerate(examples):\n self.fs._ParseExample(example.features.feature, [], entries, i)\n\n datasets = [{'entries': entries, 'size': len(examples), 'name': 'test'}]\n p = self.fs.GetDatasetsProto(datasets)\n\n self.assertEqual(1, len(p.datasets))\n test_data = p.datasets[0]\n self.assertEqual('test', test_data.name)\n self.assertEqual(6, test_data.num_examples)\n\n strfeat = test_data.features[0]\n self.assertEqual('str', strfeat.name)\n self.assertEqual(self.fs.fs_proto.STRING, strfeat.type)\n self.assertEqual(3, strfeat.string_stats.unique)\n self.assertAlmostEqual(19 / 6.0, strfeat.string_stats.avg_length, 4)\n self.assertEqual(0, strfeat.string_stats.common_stats.num_missing)\n self.assertEqual(6, strfeat.string_stats.common_stats.num_non_missing)\n self.assertEqual(1, strfeat.string_stats.common_stats.min_num_values)\n self.assertEqual(1, strfeat.string_stats.common_stats.max_num_values)\n self.assertEqual(1, strfeat.string_stats.common_stats.avg_num_values)\n hist = strfeat.string_stats.common_stats.num_values_histogram\n buckets = hist.buckets\n self.assertEqual(self.fs.histogram_proto.QUANTILES, hist.type)\n self.assertEqual(10, len(buckets))\n self.assertEqual(1, buckets[0].low_value)\n self.assertEqual(1, buckets[0].high_value)\n self.assertEqual(.6, buckets[0].sample_count)\n self.assertEqual(1, buckets[9].low_value)\n self.assertEqual(1, buckets[9].high_value)\n self.assertEqual(.6, buckets[9].sample_count)\n\n self.assertEqual(2, len(strfeat.string_stats.top_values))\n self.assertEqual(3, strfeat.string_stats.top_values[0].frequency)\n self.assertEqual('hi', strfeat.string_stats.top_values[0].value)\n self.assertEqual(2, strfeat.string_stats.top_values[1].frequency)\n self.assertEqual('hello', strfeat.string_stats.top_values[1].value)\n\n buckets = strfeat.string_stats.rank_histogram.buckets\n self.assertEqual(3, len(buckets))\n self.assertEqual(0, buckets[0].low_rank)\n self.assertEqual(0, buckets[0].high_rank)\n self.assertEqual(3, buckets[0].sample_count)\n self.assertEqual('hi', buckets[0].label)\n self.assertEqual(2, buckets[2].low_rank)\n self.assertEqual(2, buckets[2].high_rank)\n self.assertEqual(1, buckets[2].sample_count)\n self.assertEqual('hey', buckets[2].label)\n\n def testGetProtoMultipleDatasets(self):\n # Tests converting multiple datsets into the feature stats proto\n # including ensuring feature order is consistent in the protos.\n examples1 = []\n for i in range(2):\n example = tf.train.Example()\n example.features.feature['str'].bytes_list.value.append(b'one')\n example.features.feature['num'].int64_list.value.append(0)\n examples1.append(example)\n examples2 = []\n example = tf.train.Example()\n example.features.feature['num'].int64_list.value.append(1)\n example.features.feature['str'].bytes_list.value.append(b'two')\n examples2.append(example)\n\n entries1 = {}\n for i, example1 in enumerate(examples1):\n self.fs._ParseExample(example1.features.feature, [], entries1, i)\n entries2 = {}\n for i, example2 in enumerate(examples2):\n self.fs._ParseExample(example2.features.feature, [], entries2, i)\n\n datasets = [{\n 'entries': entries1,\n 'size': len(examples1),\n 'name': 'test1'\n }, {\n 'entries': entries2,\n 'size': len(examples2),\n 'name': 'test2'\n }]\n p = self.fs.GetDatasetsProto(datasets)\n\n self.assertEqual(2, len(p.datasets))\n test_data_1 = p.datasets[0]\n self.assertEqual('test1', test_data_1.name)\n self.assertEqual(2, test_data_1.num_examples)\n num_feat_index = 0 if test_data_1.features[0].name == 'num' else 1\n self.assertEqual(0, test_data_1.features[num_feat_index].num_stats.max)\n test_data_2 = p.datasets[1]\n self.assertEqual('test2', test_data_2.name)\n self.assertEqual(1, test_data_2.num_examples)\n self.assertEqual(1, test_data_2.features[num_feat_index].num_stats.max)\n\n def testGetEntriesNoFiles(self):\n features, num_examples = self.fs._GetEntries(['test'], 10,\n lambda unused_path: [])\n self.assertEqual(0, num_examples)\n self.assertEqual({}, features)\n\n @staticmethod\n def get_example_iter():\n\n def ex_iter(unused_filename):\n examples = []\n for i in range(50):\n example = tf.train.Example()\n example.features.feature['num'].int64_list.value.append(i)\n examples.append(example.SerializeToString())\n return examples\n\n return ex_iter\n\n def testGetEntries_one(self):\n features, num_examples = self.fs._GetEntries(['test'], 1,\n self.get_example_iter())\n self.assertEqual(1, num_examples)\n self.assertTrue('num' in features)\n\n def testGetEntries_oneFile(self):\n unused_features, num_examples = self.fs._GetEntries(['test'], 1000,\n self.get_example_iter())\n self.assertEqual(50, num_examples)\n\n def testGetEntries_twoFiles(self):\n unused_features, num_examples = self.fs._GetEntries(['test0', 'test1'],\n 1000,\n self.get_example_iter())\n self.assertEqual(100, num_examples)\n\n def testGetEntries_stopInSecondFile(self):\n unused_features, num_examples = self.fs._GetEntries([\n 'test@0', 'test@1', 'test@2', 'test@3', 'test@4', 'test@5', 'test@6',\n 'test@7', 'test@8', 'test@9'\n ], 75, self.get_example_iter())\n self.assertEqual(75, num_examples)\n\n\nif __name__ == '__main__':\n googletest.main()\n # Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n# Generated by the protocol buffer compiler. DO NOT EDIT!\n# source: feature_statistics.proto\n\nimport sys\n_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import message as _message\nfrom google.protobuf import reflection as _reflection\nfrom google.protobuf import symbol_database as _symbol_database\nfrom google.protobuf import descriptor_pb2\n# @@protoc_insertion_point(imports)\n\n_sym_db = _symbol_database.Default()\n\n\n\n\nDESCRIPTOR = _descriptor.FileDescriptor(\n name='feature_statistics.proto',\n package='featureStatistics',\n syntax='proto3',\n 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", "instruction": "", "output": "" }, { "input": "\\\\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')\n)\n\n\n\n_FEATURENAMESTATISTICS_TYPE = _descriptor.EnumDescriptor(\n name='Type',\n full_name='featureStatistics.FeatureNameStatistics.Type',\n filename=None,\n file=DESCRIPTOR,\n values=[\n _descriptor.EnumValueDescriptor(\n name='INT', index=0, number=0,\n options=None,\n type=None),\n _descriptor.EnumValueDescriptor(\n name='FLOAT', index=1, number=1,\n options=None,\n type=None),\n _descriptor.EnumValueDescriptor(\n name='STRING', index=2, number=2,\n options=None,\n type=None),\n _descriptor.EnumValueDescriptor(\n name='BYTES', index=3, number=3,\n options=None,\n type=None),\n ],\n containing_type=None,\n options=None,\n serialized_start=636,\n serialized_end=685,\n)\n_sym_db.RegisterEnumDescriptor(_FEATURENAMESTATISTICS_TYPE)\n\n_HISTOGRAM_HISTOGRAMTYPE = _descriptor.EnumDescriptor(\n name='HistogramType',\n full_name='featureStatistics.Histogram.HistogramType',\n filename=None,\n file=DESCRIPTOR,\n values=[\n _descriptor.EnumValueDescriptor(\n name='STANDARD', index=0, number=0,\n options=None,\n type=None),\n _descriptor.EnumValueDescriptor(\n name='QUANTILES', index=1, number=1,\n options=None,\n type=None),\n ],\n containing_type=None,\n options=None,\n serialized_start=2735,\n serialized_end=2779,\n)\n_sym_db.RegisterEnumDescriptor(_HISTOGRAM_HISTOGRAMTYPE)\n\n\n_DATASETFEATURESTATISTICSLIST = _descriptor.Descriptor(\n name='DatasetFeatureStatisticsList',\n full_name='featureStatistics.DatasetFeatureStatisticsList',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='datasets', full_name='featureStatistics.DatasetFeatureStatisticsList.datasets', index=0,\n number=1, type=11, cpp_type=10, label=3,\n has_default_value=False, default_value=[],\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[],\n enum_types=[\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n ],\n serialized_start=47,\n serialized_end=140,\n)\n\n\n_DATASETFEATURESTATISTICS = _descriptor.Descriptor(\n name='DatasetFeatureStatistics',\n full_name='featureStatistics.DatasetFeatureStatistics',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='name', full_name='featureStatistics.DatasetFeatureStatistics.name', index=0,\n number=1, type=9, cpp_type=9, label=1,\n has_default_value=False, default_value=_b(\"\").decode('utf-8'),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='num_examples', full_name='featureStatistics.DatasetFeatureStatistics.num_examples', index=1,\n number=2, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='weighted_num_examples', full_name='featureStatistics.DatasetFeatureStatistics.weighted_num_examples', index=2,\n number=4, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='features', full_name='featureStatistics.DatasetFeatureStatistics.features', index=3,\n number=3, type=11, cpp_type=10, label=3,\n has_default_value=False, default_value=[],\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[],\n enum_types=[\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n ],\n serialized_start=143,\n serialized_end=296,\n)\n\n\n_FEATURENAMESTATISTICS = _descriptor.Descriptor(\n name='FeatureNameStatistics',\n full_name='featureStatistics.FeatureNameStatistics',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='name', full_name='featureStatistics.FeatureNameStatistics.name', index=0,\n number=1, type=9, cpp_type=9, label=1,\n has_default_value=False, default_value=_b(\"\").decode('utf-8'),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='type', full_name='featureStatistics.FeatureNameStatistics.type', index=1,\n number=2, type=14, cpp_type=8, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='num_stats', full_name='featureStatistics.FeatureNameStatistics.num_stats', index=2,\n number=3, type=11, cpp_type=10, label=1,\n has_default_value=False, default_value=None,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='string_stats', full_name='featureStatistics.FeatureNameStatistics.string_stats', index=3,\n number=4, type=11, cpp_type=10, label=1,\n has_default_value=False, default_value=None,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='bytes_stats', full_name='featureStatistics.FeatureNameStatistics.bytes_stats', index=4,\n number=5, type=11, cpp_type=10, label=1,\n has_default_value=False, default_value=None,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='custom_stats', full_name='featureStatistics.FeatureNameStatistics.custom_stats', index=5,\n number=6, type=11, cpp_type=10, label=3,\n has_default_value=False, default_value=[],\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=", "instruction": "", "output": "" }, { "input": "None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[],\n enum_types=[\n _FEATURENAMESTATISTICS_TYPE,\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n _descriptor.OneofDescriptor(\n name='stats', full_name='featureStatistics.FeatureNameStatistics.stats',\n index=0, containing_type=None, fields=[]),\n ],\n serialized_start=299,\n serialized_end=694,\n)\n\n\n_WEIGHTEDCOMMONSTATISTICS = _descriptor.Descriptor(\n name='WeightedCommonStatistics',\n full_name='featureStatistics.WeightedCommonStatistics',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='num_non_missing', full_name='featureStatistics.WeightedCommonStatistics.num_non_missing', index=0,\n number=1, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='num_missing', full_name='featureStatistics.WeightedCommonStatistics.num_missing', index=1,\n number=2, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='avg_num_values', full_name='featureStatistics.WeightedCommonStatistics.avg_num_values', index=2,\n number=3, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='tot_num_values', full_name='featureStatistics.WeightedCommonStatistics.tot_num_values', index=3,\n number=4, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[],\n enum_types=[\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n ],\n serialized_start=696,\n serialized_end=816,\n)\n\n\n_CUSTOMSTATISTIC = _descriptor.Descriptor(\n name='CustomStatistic',\n full_name='featureStatistics.CustomStatistic',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='name', full_name='featureStatistics.CustomStatistic.name', index=0,\n number=1, type=9, cpp_type=9, label=1,\n has_default_value=False, default_value=_b(\"\").decode('utf-8'),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='num', full_name='featureStatistics.CustomStatistic.num', index=1,\n number=2, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='str', full_name='featureStatistics.CustomStatistic.str', index=2,\n number=3, type=9, cpp_type=9, label=1,\n has_default_value=False, default_value=_b(\"\").decode('utf-8'),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='histogram', full_name='featureStatistics.CustomStatistic.histogram', index=3,\n number=4, type=11, cpp_type=10, label=1,\n has_default_value=False, default_value=None,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[],\n enum_types=[\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n _descriptor.OneofDescriptor(\n name='val', full_name='featureStatistics.CustomStatistic.val',\n index=0, containing_type=None, fields=[]),\n ],\n serialized_start=818,\n serialized_end=937,\n)\n\n\n_NUMERICSTATISTICS = _descriptor.Descriptor(\n name='NumericStatistics',\n full_name='featureStatistics.NumericStatistics',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='common_stats', full_name='featureStatistics.NumericStatistics.common_stats', index=0,\n number=1, type=11, cpp_type=10, label=1,\n has_default_value=False, default_value=None,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='mean', full_name='featureStatistics.NumericStatistics.mean', index=1,\n number=2, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='std_dev', full_name='featureStatistics.NumericStatistics.std_dev', index=2,\n number=3, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='num_zeros', full_name='featureStatistics.NumericStatistics.num_zeros', index=3,\n number=4, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='min', full_name='featureStatistics.NumericStatistics.min', index=4,\n number=5, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='median', full_name='featureStatistics.NumericStatistics.median', index=5,\n number=6, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='max', full_name='featureStatistics.NumericStatistics.max', index=6,\n number=7, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='histograms', full_name='featureStatistics.NumericStatistics.histograms', index=7,\n number=8, type=11, cpp_type=10, label=3,\n has_default_value=False, default_value=[],\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='weighted_numeric_stats', full_name='featureStatistics.NumericStatistics.weighted_numeric_stats', index=8,\n number=9, type=11, cpp_type=10, label=1,\n has_default_value=False, default_value=None,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[],\n enum_types=[\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n ],\n serialized_start=940,\n serialized_end=1238,\n)\n\n\n_STRINGSTATISTICS_FREQANDVALUE = _descriptor.Descriptor(\n name='FreqAndValue',\n full_name='featureStatistics.StringStatistics.FreqAndValue',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='deprecated_freq', full_name='featureStatistics.StringStatistics.FreqAndValue.deprecated_freq', index=0,\n number=1, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\\\\030\\\\001'))),\n _descriptor.FieldDescriptor(\n name='value', full_name='featureStatistics.StringStatistics.FreqAndValue.value', index=1,\n number=2, type=9, cpp_type=9, label=1,\n has_default_value=False, default_value=_b(\"\").decode('utf-8'),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='frequency', full_name='featureStatistics.StringStatistics.FreqAndValue.frequency', index=2,\n number=3, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[],\n enum_types=[\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n ],\n serialized_start=1560,\n serialized_end=1637,\n)\n\n_STRINGSTATISTICS = _descriptor.Descriptor(\n name='StringStatistics',\n full_name='featureStatistics.StringStatistics',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='common_stats', full_name='featureStatistics.StringStatistics.common_stats', index=0,\n number=1, type=11, cpp_type=10, label=1,\n has_default_value=False, default_value=None,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='unique', full_name='featureStatistics.StringStatistics.unique', index=1,\n number=2, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='top_values', full_name='featureStatistics.StringStatistics.top_values', index=2,\n number=3, type=11, cpp_type=10, label=3,\n has_default_value=False, default_value=[],\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='avg_length', full_name='featureStatistics.StringStatistics.avg_length', index=3,\n number=4, type=2, cpp_type=6, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='rank_histogram', full_name='featureStatistics.StringStatistics.rank_histogram', index=4,\n number=5, type=11, cpp_type=10, label=1,\n has_default_value=False, default_value=None,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='weighted_string_stats', full_name='featureStatistics.StringStatistics.weighted_string_stats', index=5,\n number=6, type=11, cpp_type=10, label=1,\n has_default_value=False, default_value=None,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[_STRINGSTATISTICS_FREQANDVALUE, ],\n enum_types=[\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n ],\n serialized_start=1241,\n ", "instruction": "", "output": "" }, { "input": "serialized_end=1637,\n)\n\n\n_WEIGHTEDNUMERICSTATISTICS = _descriptor.Descriptor(\n name='WeightedNumericStatistics',\n full_name='featureStatistics.WeightedNumericStatistics',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='mean', full_name='featureStatistics.WeightedNumericStatistics.mean', index=0,\n number=1, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='std_dev', full_name='featureStatistics.WeightedNumericStatistics.std_dev', index=1,\n number=2, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='median', full_name='featureStatistics.WeightedNumericStatistics.median', index=2,\n number=3, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='histograms', full_name='featureStatistics.WeightedNumericStatistics.histograms', index=3,\n number=4, type=11, cpp_type=10, label=3,\n has_default_value=False, default_value=[],\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[],\n enum_types=[\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n ],\n serialized_start=1639,\n serialized_end=1763,\n)\n\n\n_WEIGHTEDSTRINGSTATISTICS = _descriptor.Descriptor(\n name='WeightedStringStatistics',\n full_name='featureStatistics.WeightedStringStatistics',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='top_values', full_name='featureStatistics.WeightedStringStatistics.top_values', index=0,\n number=1, type=11, cpp_type=10, label=3,\n has_default_value=False, default_value=[],\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='rank_histogram', full_name='featureStatistics.WeightedStringStatistics.rank_histogram', index=1,\n number=2, type=11, cpp_type=10, label=1,\n has_default_value=False, default_value=None,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[],\n enum_types=[\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n ],\n serialized_start=1766,\n serialized_end=1920,\n)\n\n\n_BYTESSTATISTICS = _descriptor.Descriptor(\n name='BytesStatistics',\n full_name='featureStatistics.BytesStatistics',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='common_stats', full_name='featureStatistics.BytesStatistics.common_stats', index=0,\n number=1, type=11, cpp_type=10, label=1,\n has_default_value=False, default_value=None,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='unique', full_name='featureStatistics.BytesStatistics.unique', index=1,\n number=2, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='avg_num_bytes', full_name='featureStatistics.BytesStatistics.avg_num_bytes', index=2,\n number=3, type=2, cpp_type=6, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='min_num_bytes', full_name='featureStatistics.BytesStatistics.min_num_bytes', index=3,\n number=4, type=2, cpp_type=6, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='max_num_bytes', full_name='featureStatistics.BytesStatistics.max_num_bytes', index=4,\n number=5, type=2, cpp_type=6, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[],\n enum_types=[\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n ],\n serialized_start=1923,\n serialized_end=2084,\n)\n\n\n_COMMONSTATISTICS = _descriptor.Descriptor(\n name='CommonStatistics',\n full_name='featureStatistics.CommonStatistics',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='num_non_missing', full_name='featureStatistics.CommonStatistics.num_non_missing', index=0,\n number=1, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='num_missing', full_name='featureStatistics.CommonStatistics.num_missing', index=1,\n number=2, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='min_num_values', full_name='featureStatistics.CommonStatistics.min_num_values', index=2,\n number=3, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='max_num_values', full_name='featureStatistics.CommonStatistics.max_num_values', index=3,\n number=4, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='avg_num_values', full_name='featureStatistics.CommonStatistics.avg_num_values', index=4,\n number=5, type=2, cpp_type=6, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='tot_num_values', full_name='featureStatistics.CommonStatistics.tot_num_values', index=5,\n number=8, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='num_values_histogram', full_name='featureStatistics.CommonStatistics.num_values_histogram', index=6,\n number=6, type=11, cpp_type=10, label=1,\n has_default_value=False, default_value=None,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='weighted_common_stats', full_name='featureStatistics.CommonStatistics.weighted_common_stats', index=7,\n number=7, type=11, cpp_type=10, label=1,\n has_default_value=False, default_value=None,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='feature_list_length_histogram', full_name='featureStatistics.CommonStatistics.feature_list_length_histogram', index=8,\n number=9, type=11, cpp_type=10, label=1,\n has_default_value=False, default_value=None,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[],\n enum_types=[\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n ],\n serialized_start=2087,\n serialized_end=2452,\n)\n\n\n_HISTOGRAM_BUCKET = _descriptor.Descriptor(\n name='Bucket',\n full_name='featureStatistics.Histogram.Bucket',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='low_value', full_name='featureStatistics.Histogram.Bucket.low_value', index=0,\n number=1, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='high_value', full_name='featureStatistics.Histogram.Bucket.high_value', index=1,\n number=2, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='deprecated_count', full_name='featureStatistics.Histogram.Bucket.deprecated_count', index=2,\n number=3, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\\\\030\\\\001'))),\n _descriptor.FieldDescriptor(\n name='sample_count', full_name='featureStatistics.Histogram.Bucket.sample_count', index=3,\n number=4, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[],\n enum_types=[\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n ],\n serialized_start=2634,\n serialized_end=2733,\n)\n\n_HISTOGRAM = _descriptor.Descriptor(\n name='Histogram',\n full_name='featureStatistics.Histogram',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='num_nan', full_name='featureStatistics.Histogram.num_nan', index=0,\n number=1, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='num_undefined', full_name='featureStatistics.Histogram.num_undefined', index=1,\n number=2, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='buckets', full_name='featureStatistics.Histogram.buckets', index=2,\n number=3, type=11, cpp_type=10, label=3,\n has_default_value=False, default_value=[],\n message_type=None, enum_type=None, containing_type=None,\n", "instruction": "", "output": "" }, { "input": " is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='type', full_name='featureStatistics.Histogram.type', index=3,\n number=4, type=14, cpp_type=8, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='name', full_name='featureStatistics.Histogram.name', index=4,\n number=5, type=9, cpp_type=9, label=1,\n has_default_value=False, default_value=_b(\"\").decode('utf-8'),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[_HISTOGRAM_BUCKET, ],\n enum_types=[\n _HISTOGRAM_HISTOGRAMTYPE,\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n ],\n serialized_start=2455,\n serialized_end=2779,\n)\n\n\n_RANKHISTOGRAM_BUCKET = _descriptor.Descriptor(\n name='Bucket',\n full_name='featureStatistics.RankHistogram.Bucket',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='low_rank', full_name='featureStatistics.RankHistogram.Bucket.low_rank', index=0,\n number=1, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='high_rank', full_name='featureStatistics.RankHistogram.Bucket.high_rank', index=1,\n number=2, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='deprecated_count', full_name='featureStatistics.RankHistogram.Bucket.deprecated_count', index=2,\n number=3, type=4, cpp_type=4, label=1,\n has_default_value=False, default_value=0,\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\\\\030\\\\001'))),\n _descriptor.FieldDescriptor(\n name='label', full_name='featureStatistics.RankHistogram.Bucket.label', index=3,\n number=4, type=9, cpp_type=9, label=1,\n has_default_value=False, default_value=_b(\"\").decode('utf-8'),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='sample_count', full_name='featureStatistics.RankHistogram.Bucket.sample_count', index=4,\n number=5, type=1, cpp_type=5, label=1,\n has_default_value=False, default_value=float(0),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[],\n enum_types=[\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n ],\n serialized_start=2871,\n serialized_end=2983,\n)\n\n_RANKHISTOGRAM = _descriptor.Descriptor(\n name='RankHistogram',\n full_name='featureStatistics.RankHistogram',\n filename=None,\n file=DESCRIPTOR,\n containing_type=None,\n fields=[\n _descriptor.FieldDescriptor(\n name='buckets', full_name='featureStatistics.RankHistogram.buckets', index=0,\n number=1, type=11, cpp_type=10, label=3,\n has_default_value=False, default_value=[],\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n _descriptor.FieldDescriptor(\n name='name', full_name='featureStatistics.RankHistogram.name', index=1,\n number=2, type=9, cpp_type=9, label=1,\n has_default_value=False, default_value=_b(\"\").decode('utf-8'),\n message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None,\n options=None),\n ],\n extensions=[\n ],\n nested_types=[_RANKHISTOGRAM_BUCKET, ],\n enum_types=[\n ],\n options=None,\n is_extendable=False,\n syntax='proto3',\n extension_ranges=[],\n oneofs=[\n ],\n serialized_start=2782,\n serialized_end=2983,\n)\n\n_DATASETFEATURESTATISTICSLIST.fields_by_name['datasets'].message_type = _DATASETFEATURESTATISTICS\n_DATASETFEATURESTATISTICS.fields_by_name['features'].message_type = _FEATURENAMESTATISTICS\n_FEATURENAMESTATISTICS.fields_by_name['type'].enum_type = _FEATURENAMESTATISTICS_TYPE\n_FEATURENAMESTATISTICS.fields_by_name['num_stats'].message_type = _NUMERICSTATISTICS\n_FEATURENAMESTATISTICS.fields_by_name['string_stats'].message_type = _STRINGSTATISTICS\n_FEATURENAMESTATISTICS.fields_by_name['bytes_stats'].message_type = _BYTESSTATISTICS\n_FEATURENAMESTATISTICS.fields_by_name['custom_stats'].message_type = _CUSTOMSTATISTIC\n_FEATURENAMESTATISTICS_TYPE.containing_type = _FEATURENAMESTATISTICS\n_FEATURENAMESTATISTICS.oneofs_by_name['stats'].fields.append(\n _FEATURENAMESTATISTICS.fields_by_name['num_stats'])\n_FEATURENAMESTATISTICS.fields_by_name['num_stats'].containing_oneof = _FEATURENAMESTATISTICS.oneofs_by_name['stats']\n_FEATURENAMESTATISTICS.oneofs_by_name['stats'].fields.append(\n _FEATURENAMESTATISTICS.fields_by_name['string_stats'])\n_FEATURENAMESTATISTICS.fields_by_name['string_stats'].containing_oneof = _FEATURENAMESTATISTICS.oneofs_by_name['stats']\n_FEATURENAMESTATISTICS.oneofs_by_name['stats'].fields.append(\n _FEATURENAMESTATISTICS.fields_by_name['bytes_stats'])\n_FEATURENAMESTATISTICS.fields_by_name['bytes_stats'].containing_oneof = _FEATURENAMESTATISTICS.oneofs_by_name['stats']\n_CUSTOMSTATISTIC.fields_by_name['histogram'].message_type = _HISTOGRAM\n_CUSTOMSTATISTIC.oneofs_by_name['val'].fields.append(\n _CUSTOMSTATISTIC.fields_by_name['num'])\n_CUSTOMSTATISTIC.fields_by_name['num'].containing_oneof = _CUSTOMSTATISTIC.oneofs_by_name['val']\n_CUSTOMSTATISTIC.oneofs_by_name['val'].fields.append(\n _CUSTOMSTATISTIC.fields_by_name['str'])\n_CUSTOMSTATISTIC.fields_by_name['str'].containing_oneof = _CUSTOMSTATISTIC.oneofs_by_name['val']\n_CUSTOMSTATISTIC.oneofs_by_name['val'].fields.append(\n _CUSTOMSTATISTIC.fields_by_name['histogram'])\n_CUSTOMSTATISTIC.fields_by_name['histogram'].containing_oneof = _CUSTOMSTATISTIC.oneofs_by_name['val']\n_NUMERICSTATISTICS.fields_by_name['common_stats'].message_type = _COMMONSTATISTICS\n_NUMERICSTATISTICS.fields_by_name['histograms'].message_type = _HISTOGRAM\n_NUMERICSTATISTICS.fields_by_name['weighted_numeric_stats'].message_type = _WEIGHTEDNUMERICSTATISTICS\n_STRINGSTATISTICS_FREQANDVALUE.containing_type = _STRINGSTATISTICS\n_STRINGSTATISTICS.fields_by_name['common_stats'].message_type = _COMMONSTATISTICS\n_STRINGSTATISTICS.fields_by_name['top_values'].message_type = _STRINGSTATISTICS_FREQANDVALUE\n_STRINGSTATISTICS.fields_by_name['rank_histogram'].message_type = _RANKHISTOGRAM\n_STRINGSTATISTICS.fields_by_name['weighted_string_stats'].message_type = _WEIGHTEDSTRINGSTATISTICS\n_WEIGHTEDNUMERICSTATISTICS.fields_by_name['histograms'].message_type = _HISTOGRAM\n_WEIGHTEDSTRINGSTATISTICS.fields_by_name['top_values'].message_type = _STRINGSTATISTICS_FREQANDVALUE\n_WEIGHTEDSTRINGSTATISTICS.fields_by_name['rank_histogram'].message_type = _RANKHISTOGRAM\n_BYTESSTATISTICS.fields_by_name['common_stats'].message_type = _COMMONSTATISTICS\n_COMMONSTATISTICS.fields_by_name['num_values_histogram'].message_type = _HISTOGRAM\n_COMMONSTATISTICS.fields_by_name['weighted_common_stats'].message_type = _WEIGHTEDCOMMONSTATISTICS\n_COMMONSTATISTICS.fields_by_name['feature_list_length_histogram'].message_type = _HISTOGRAM\n_HISTOGRAM_BUCKET.containing_type = _HISTOGRAM\n_HISTOGRAM.fields_by_name['buckets'].message_type = _HISTOGRAM_BUCKET\n_HISTOGRAM.fields_by_name['type'].enum_type = _HISTOGRAM_HISTOGRAMTYPE\n_HISTOGRAM_HISTOGRAMTYPE.containing_type = _HISTOGRAM\n_RANKHISTOGRAM_BUCKET.containing_type = _RANKHISTOGRAM\n_RANKHISTOGRAM.fields_by_name['buckets'].message_type = _RANKHISTOGRAM_BUCKET\nDESCRIPTOR.message_types_by_name['DatasetFeatureStatisticsList'] = _DATASETFEATURESTATISTICSLIST\nDESCRIPTOR.message_types_by_name['DatasetFeatureStatistics'] = _DATASETFEATURESTATISTICS\nDESCRIPTOR.message_types_by_name['FeatureNameStatistics'] = _FEATURENAMESTATISTICS\nDESCRIPTOR.message_types_by_name['WeightedCommonStatistics'] = _WEIGHTEDCOMMONSTATISTICS\nDESCRIPTOR.message_types_by_name['CustomStatistic'] = _CUSTOMSTATISTIC\nDESCRIPTOR.message_types_by_name['NumericStatistics'] = _NUMERICSTATISTICS\nDESCRIPTOR.message_types_by_name['StringStatistics'] = _STRINGSTATISTICS\nDESCRIPTOR.message_types_by_name['WeightedNumericStatistics'] = _WEIGHTEDNUMERICSTATISTICS\nDESCRIPTOR.message_types_by_name['WeightedStringStatistics'] = _WEIGHTEDSTRINGSTATISTICS\nDESCRIPTOR.message_types_by_name['BytesStatistics'] = _BYTESSTATISTICS\nDESCRIPTOR.message_types_by_name['CommonStatistics'] = _COMMONSTATISTICS\nDESCRIPTOR.message_types_by_name['Histogram'] = _HISTOGRAM\nDESCRIPTOR.message_types_by_name['RankHistogram'] = _RANKHISTOGRAM\n_sym_db.RegisterFileDescriptor(DESCRIPTOR)\n\nDatasetFeatureStatisticsList = _reflection.GeneratedProtocolMessageType('DatasetFeatureStatisticsList', (_message.Message,), dict(\n DESCRIPTOR = _DATASETFEATURESTATISTICSLIST,\n __module__ = 'feature_statistics_pb2'\n # @@protoc_insertion_point(class_scope:featureStatistics.DatasetFeatureStatisticsList)\n ))\n_sym_db.RegisterMessage(DatasetFeatureStatisticsList)\n\nDatasetFeatureStatistics = _reflection.GeneratedProtocolMessageType('DatasetFeatureStatistics', (_message.Message,), dict(\n DESCRIPTOR = _DATASETFEATURESTATISTICS,\n __module__ = 'feature_statistics_pb2'\n # @@protoc_insertion_point(class_scope:featureStatistics.DatasetFeatureStatistics)\n ))\n_sym_db.RegisterMessage(DatasetFeatureStatistics)\n\nFeatureNameStatistics = _reflection.GeneratedProtocolMessageType('FeatureNameStatistics', (_message.Message,), dict(\n DESCRIPTOR = _FEATURENAMESTATISTICS,\n __module__ = 'feature_statistics_pb2'\n # @@protoc_insertion_point(class_scope:featureStatistics.FeatureNameStatistics)\n ))\n_sym_db.RegisterMessage(FeatureNameStatistics)\n\nWeightedCommonStatistics = _reflection.GeneratedProtocolMessageType('WeightedCommonStatistics', (_message.Message,), dict(\n DESCRIPTOR = _WEIGHTEDCOMMONSTATISTICS,\n __module__ = 'feature_statistics_pb2'\n # @@protoc_insertion_point(class_scope:featureStatistics.WeightedCommonStatistics)\n ))\n_sym_db.RegisterMessage(WeightedCommonStatistics)\n\nCustomStatistic = _reflection.GeneratedProtocolMessageType('CustomStatistic', (_message.Message,), dict(\n DESCRIPTOR = _CUSTOMSTATISTIC,\n __module__ = 'feature_statistics_pb2'\n # @@protoc_insertion_point(class_scope:featureStatistics.CustomStatistic)\n ))\n_sym_db.RegisterMessage(CustomStatistic)\n\nNumericStatistics = _reflection.GeneratedProtocolMessageType('NumericStatistics', (_message.Message,), dict(\n DESCRIPTOR = _NUMERICSTATISTICS,\n __module__ = 'feature_statistics_pb2'", "instruction": "", "output": "" }, { "input": "\n # @@protoc_insertion_point(class_scope:featureStatistics.NumericStatistics)\n ))\n_sym_db.RegisterMessage(NumericStatistics)\n\nStringStatistics = _reflection.GeneratedProtocolMessageType('StringStatistics', (_message.Message,), dict(\n\n FreqAndValue = _reflection.GeneratedProtocolMessageType('FreqAndValue', (_message.Message,), dict(\n DESCRIPTOR = _STRINGSTATISTICS_FREQANDVALUE,\n __module__ = 'feature_statistics_pb2'\n # @@protoc_insertion_point(class_scope:featureStatistics.StringStatistics.FreqAndValue)\n ))\n ,\n DESCRIPTOR = _STRINGSTATISTICS,\n __module__ = 'feature_statistics_pb2'\n # @@protoc_insertion_point(class_scope:featureStatistics.StringStatistics)\n ))\n_sym_db.RegisterMessage(StringStatistics)\n_sym_db.RegisterMessage(StringStatistics.FreqAndValue)\n\nWeightedNumericStatistics = _reflection.GeneratedProtocolMessageType('WeightedNumericStatistics', (_message.Message,), dict(\n DESCRIPTOR = _WEIGHTEDNUMERICSTATISTICS,\n __module__ = 'feature_statistics_pb2'\n # @@protoc_insertion_point(class_scope:featureStatistics.WeightedNumericStatistics)\n ))\n_sym_db.RegisterMessage(WeightedNumericStatistics)\n\nWeightedStringStatistics = _reflection.GeneratedProtocolMessageType('WeightedStringStatistics', (_message.Message,), dict(\n DESCRIPTOR = _WEIGHTEDSTRINGSTATISTICS,\n __module__ = 'feature_statistics_pb2'\n # @@protoc_insertion_point(class_scope:featureStatistics.WeightedStringStatistics)\n ))\n_sym_db.RegisterMessage(WeightedStringStatistics)\n\nBytesStatistics = _reflection.GeneratedProtocolMessageType('BytesStatistics', (_message.Message,), dict(\n DESCRIPTOR = _BYTESSTATISTICS,\n __module__ = 'feature_statistics_pb2'\n # @@protoc_insertion_point(class_scope:featureStatistics.BytesStatistics)\n ))\n_sym_db.RegisterMessage(BytesStatistics)\n\nCommonStatistics = _reflection.GeneratedProtocolMessageType('CommonStatistics', (_message.Message,), dict(\n DESCRIPTOR = _COMMONSTATISTICS,\n __module__ = 'feature_statistics_pb2'\n # @@protoc_insertion_point(class_scope:featureStatistics.CommonStatistics)\n ))\n_sym_db.RegisterMessage(CommonStatistics)\n\nHistogram = _reflection.GeneratedProtocolMessageType('Histogram', (_message.Message,), dict(\n\n Bucket = _reflection.GeneratedProtocolMessageType('Bucket', (_message.Message,), dict(\n DESCRIPTOR = _HISTOGRAM_BUCKET,\n __module__ = 'feature_statistics_pb2'\n # @@protoc_insertion_point(class_scope:featureStatistics.Histogram.Bucket)\n ))\n ,\n DESCRIPTOR = _HISTOGRAM,\n __module__ = 'feature_statistics_pb2'\n # @@protoc_insertion_point(class_scope:featureStatistics.Histogram)\n ))\n_sym_db.RegisterMessage(Histogram)\n_sym_db.RegisterMessage(Histogram.Bucket)\n\nRankHistogram = _reflection.GeneratedProtocolMessageType('RankHistogram', (_message.Message,), dict(\n\n Bucket = _reflection.GeneratedProtocolMessageType('Bucket', (_message.Message,), dict(\n DESCRIPTOR = _RANKHISTOGRAM_BUCKET,\n __module__ = 'feature_statistics_pb2'\n # @@protoc_insertion_point(class_scope:featureStatistics.RankHistogram.Bucket)\n ))\n ,\n DESCRIPTOR = _RANKHISTOGRAM,\n __module__ = 'feature_statistics_pb2'\n # @@protoc_insertion_point(class_scope:featureStatistics.RankHistogram)\n ))\n_sym_db.RegisterMessage(RankHistogram)\n_sym_db.RegisterMessage(RankHistogram.Bucket)\n\n\n_STRINGSTATISTICS_FREQANDVALUE.fields_by_name['deprecated_freq'].has_options = True\n_STRINGSTATISTICS_FREQANDVALUE.fields_by_name['deprecated_freq']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\\\\030\\\\001'))\n_HISTOGRAM_BUCKET.fields_by_name['deprecated_count'].has_options = True\n_HISTOGRAM_BUCKET.fields_by_name['deprecated_count']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\\\\030\\\\001'))\n_RANKHISTOGRAM_BUCKET.fields_by_name['deprecated_count'].has_options = True\n_RANKHISTOGRAM_BUCKET.fields_by_name['deprecated_count']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\\\\030\\\\001'))\n# @@protoc_insertion_point(module_scope)\n # Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n # Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Class for generating the feature_statistics proto.\n\nThe proto is used as input for the Overview visualization.\n\"\"\"\n\nfrom facets_overview.base_feature_statistics_generator import BaseFeatureStatisticsGenerator\nimport facets_overview.feature_statistics_pb2 as fs\n\n\nclass FeatureStatisticsGenerator(BaseFeatureStatisticsGenerator):\n \"\"\"Generator of stats proto from TF data.\"\"\"\n\n def __init__(self):\n BaseFeatureStatisticsGenerator.__init__(self, fs.FeatureNameStatistics,\n fs.DatasetFeatureStatisticsList,\n fs.Histogram)\n # Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Base class for generating the feature_statistics proto from generic data.\n\nThe proto is used as input for the Overview visualization.\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport sys\n\n\nclass BaseGenericFeatureStatisticsGenerator(object):\n \"\"\"Base class for generator of stats proto from generic data.\"\"\"\n\n def __init__(self, fs_proto, datasets_proto, histogram_proto):\n self.fs_proto = fs_proto\n self.datasets_proto = datasets_proto\n self.histogram_proto = histogram_proto\n\n def ProtoFromDataFrames(self, dataframes,\n histogram_categorical_levels_count=None):\n \"\"\"Creates a feature statistics proto from a set of pandas dataframes.\n\n Args:\n dataframes: A list of dicts describing tables for each dataset for the\n proto. Each entry contains a 'table' field of the dataframe of the\n data\n and a 'name' field to identify the dataset in the proto.\n histogram_categorical_levels_count: int, controls the maximum number of\n levels to display in histograms for categorical features.\n Useful to prevent codes/IDs features from bloating the stats object.\n Defaults to None.\n Returns:\n The feature statistics proto for the provided tables.\n \"\"\"\n datasets = []\n for dataframe in dataframes:\n table = dataframe['table']\n table_entries = {}\n for col in table:\n table_entries[col] = self.NdarrayToEntry(table[col])\n datasets.append({\n 'entries': table_entries,\n 'size': len(table),\n 'name': dataframe['name']\n })\n return self.GetDatasetsProto(\n datasets,\n histogram_categorical_levels_count=histogram_categorical_levels_count)\n\n def DtypeToType(self, dtype):\n \"\"\"Converts a Numpy dtype to the FeatureNameStatistics.Type proto enum.\"\"\"\n if dtype.char in np.typecodes['AllFloat']:\n return self.fs_proto.FLOAT\n elif (dtype.char in np.typecodes['AllInteger'] or dtype == bool or\n np.issubdtype(dtype, np.datetime64) or\n np.issubdtype(dtype, np.timedelta64)):\n return self.fs_proto.INT\n else:\n return self.fs_proto.STRING\n\n def DtypeToNumberConverter(self, dtype):\n \"\"\"Converts a Numpy dtype to a converter method if applicable.\n\n The converter method takes in a numpy array of objects of the provided\n dtype\n and returns a numpy array of the numbers backing that object for\n statistical\n analysis. Returns None if no converter is necessary.\n\n Args:\n dtype: The numpy dtype to make a converter for.\n\n Returns:\n The converter method or None.\n \"\"\"\n if np.issubdtype(dtype, np.datetime64):\n\n def DatetimesToNumbers(dt_list):\n return np.array([pd.Timestamp(dt).value for dt in dt_list])\n\n return DatetimesToNumbers\n elif np.issubdtype(dtype, np.timedelta64):\n\n def TimedetlasToNumbers(td_list):\n return np.array([pd.Timedelta(td).value for td in td_list])\n\n return TimedetlasToNumbers\n else:\n return None\n\n def NdarrayToEntry(self, x):\n \"\"\"Converts an ndarray to the Entry format.\"\"\"\n row_counts = []\n for row in x:\n try:\n rc = np.count_nonzero(~np.isnan(row))\n if rc != 0:\n row_counts.append(rc)\n except TypeError:\n try:\n row_counts.append(row.size)\n except AttributeError:\n row_counts.append(1)\n\n data_type = self.DtypeToType(x.dtype)\n converter = self.DtypeToNumberConverter(x.dtype)\n flattened = x.ravel()\n orig_size = len(flattened)\n\n # Remove all None and nan values and count how many were removed.\n flattened = flattened[flattened != np.array(None)]\n if converter:\n flattened = converter(flattened)\n if data_type == self.fs_proto.STRING:\n flattened_temp = []\n for x in flattened:\n try:\n if str(x) != 'nan':\n flattened_temp.append(x)\n except UnicodeEncodeError:\n if x.encode('utf-8') != 'nan':\n flattened_temp.append(x)\n flattened = flattened_temp\n else:\n flattened = flattened[~np.isnan(flattened)].tolist()\n missing = orig_size - len(flattened)\n return {\n 'vals': flattened,\n 'counts': row_counts,\n 'missing': missing,\n 'type': data_type\n }\n\n def GetDatasetsProto(self, datasets, features=None,\n histogram_categorical_levels_count=None):\n \"\"\"Generates the feature stats proto from dictionaries of feature values.\n\n Args:\n datasets: An array of dictionaries, one per dataset, each one containing:\n - 'entries': The dictionary of features in the dataset from the parsed\n examples.\n - 'size': The number of examples parsed for the dataset.\n - 'name': The name of the dataset.\n features: A list of strings that is a whitelist of feature names to create\n feature statistics for. If set to None then all features in the\n dataset\n are analyzed. Defaults to None.\n histogram_categorical_levels_count: int, controls the maximum number of\n levels to display in histograms for categorical features.\n Useful to prevent codes/IDs features from bloating the stats object.\n Defaults to None.\n\n Returns:\n The feature statistics proto for the provided datasets.\n \"\"\"\n features_seen = set()\n whitelist_features = set(features) if features else None\n all_datasets = self.datasets_proto()\n\n # TODO(jwexler): Add ability to generate weighted feature stats\n # if there is a specified weight feature in the dataset.\n\n # Initialize each dataset\n for dataset in datasets:\n all_datasets.datasets.add(\n name=dataset['name'], num_examples=dataset['size'])\n # This outer loop ensures that for each feature seen in any of the provided\n # datasets, we check the feature once against all datasets.\n for outer_dataset in datasets:\n for key, value in outer_dataset['entries'].items():\n \n # If we have a feature whitelist and this feature is not in the\n # whitelist then do not process it.\n # If we have processed this feature already, no need to do it again.\n if ((whitelist_features and key not in whitelist_features) or\n key in features_seen):\n continue\n features_seen.add(key)\n # Default to type int if no type is found, so that the fact that all\n # values are missing from this feature can be displayed.\n feature_type = value['type'] if 'type' in value else self.fs_proto.INT\n # Process the found feature for each dataset.\n for j, dataset in enumerate(datasets):\n feat = all_datasets.datasets[j].features.add(\n type=feature_type, name=key.encode('utf-8'))\n value = dataset['entries'].get(key)\n has_data = value is not None and (value['vals'].size != 0\n if isinstance(\n value['vals'], np.ndarray) else\n value['vals'])\n commonstats = None\n # For numeric features, calculate numeric statistics.\n if feat.type in (self.fs_proto", "instruction": "", "output": "" }, { "input": ".INT, self.fs_proto.FLOAT):\n featstats = feat.num_stats\n commonstats = featstats.common_stats\n if has_data:\n nums = value['vals']\n \n featstats.std_dev = np.std(nums).item()\n \n featstats.mean = np.mean(nums).item()\n \n featstats.min = np.min(nums).item()\n\n featstats.max = np.max(nums).item()\n\n featstats.median = np.median(nums).item()\n\n featstats.num_zeros = len(nums) - np.count_nonzero(nums)\n\n nums = np.array(nums)\n num_nan = len(nums[np.isnan(nums)])\n num_posinf = len(nums[np.isposinf(nums)])\n num_neginf = len(nums[np.isneginf(nums)])\n\n # Remove all non-finite (including NaN) values from the numeric\n # values in order to calculate histogram buckets/counts. The\n # inf values will be added back to the first and last buckets.\n nums = nums[np.isfinite(nums)]\n counts, buckets = np.histogram(nums)\n hist = featstats.histograms.add()\n hist.type = self.histogram_proto.STANDARD\n hist.num_nan = num_nan \n for bucket_count in range(len(counts)):\n bucket = hist.buckets.add(\n low_value=buckets[bucket_count],\n high_value=buckets[bucket_count + 1],\n sample_count=counts[bucket_count].item())\n # Add any negative or positive infinities to the first and last\n # buckets in the histogram.\n if bucket_count == 0 and num_neginf > 0:\n bucket.low_value = float('-inf')\n bucket.sample_count += num_neginf\n elif bucket_count == len(counts) - 1 and num_posinf > 0:\n bucket.high_value = float('inf')\n bucket.sample_count += num_posinf\n if not hist.buckets:\n if num_neginf:\n hist.buckets.add(\n low_value=float('-inf'),\n high_value=float('-inf'),\n sample_count=num_neginf)\n if num_posinf:\n hist.buckets.add(\n low_value=float('inf'),\n high_value=float('inf'),\n sample_count=num_posinf) \n self._PopulateQuantilesHistogram(featstats.histograms.add(),nums.tolist())\n elif feat.type == self.fs_proto.STRING:\n featstats = feat.string_stats\n commonstats = featstats.common_stats\n if has_data:\n strs = []\n for item in value['vals']:\n strs.append(item if hasattr(item, '__len__') else\n item.encode('utf-8') if hasattr(item, 'encode') else str(\n item))\n\n featstats.avg_length = np.mean(np.vectorize(len)(strs))\n vals, counts = np.unique(strs, return_counts=True)\n featstats.unique = len(vals)\n sorted_vals = sorted(zip(counts, vals), reverse=True)\n sorted_vals = sorted_vals[:histogram_categorical_levels_count]\n for val_index, val in enumerate(sorted_vals):\n try:\n if (sys.version_info.major < 3 or\n isinstance(val[1], (bytes, bytearray))):\n printable_val = val[1].decode('UTF-8', 'strict')\n else:\n printable_val = val[1]\n except (UnicodeDecodeError, UnicodeEncodeError):\n printable_val = '__BYTES_VALUE__'\n bucket = featstats.rank_histogram.buckets.add(\n low_rank=val_index,\n high_rank=val_index,\n sample_count=(val[0].item()),\n label=printable_val)\n if val_index < 2:\n featstats.top_values.add(\n value=bucket.label, frequency=bucket.sample_count)\n # Add the common stats regardless of the feature type.\n if has_data:\n commonstats.num_missing = value['missing']\n commonstats.num_non_missing = (all_datasets.datasets[j].num_examples\n - featstats.common_stats.num_missing)\n commonstats.min_num_values = int(np.min(value['counts']).astype(int))\n commonstats.max_num_values = int(np.max(value['counts']).astype(int))\n commonstats.avg_num_values = np.mean(value['counts'])\n if 'feat_lens' in value and value['feat_lens']:\n self._PopulateQuantilesHistogram(\n commonstats.feature_list_length_histogram, value['feat_lens'])\n self._PopulateQuantilesHistogram(commonstats.num_values_histogram,\n value['counts'])\n else:\n commonstats.num_non_missing = 0\n commonstats.num_missing = all_datasets.datasets[j].num_examples\n\n return all_datasets\n\n def _PopulateQuantilesHistogram(self, hist, nums):\n \"\"\"Fills in the histogram with quantile information from the provided array.\n\n Args:\n hist: A Histogram proto message to fill in.\n nums: A list of numbers to create a quantiles histogram from.\n \"\"\"\n if not nums:\n return\n num_quantile_buckets = 10\n quantiles_to_get = [\n x * 100 / num_quantile_buckets for x in range(num_quantile_buckets + 1)\n ]\n try:\n quantiles = np.percentile(nums, quantiles_to_get)\n except:\n quantiles = [0.0]\n hist.type = self.histogram_proto.QUANTILES\n quantiles_sample_count = float(len(nums)) / num_quantile_buckets\n for low, high in zip(quantiles, quantiles[1:]):\n hist.buckets.add(\n low_value=low, high_value=high, sample_count=quantiles_sample_count)\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport pandas as pd \nimport numpy as np\nimport sys\nimport math\nimport markov_clustering as mc\nimport os\nimport networkx as nx\nimport logging\nimport json\n## How far you'd like your random-walkers to go (bigger number -> more walking)\nEXPANSION_POWER = 2\n## How tightly clustered you'd like your final picture to be (bigger number -> more clusters)\nINFLATION_POWER = 2\n## If you can manage 100 iterations then do so - otherwise, check you've hit a stable end-point.\nITERATION_COUNT = 100\ndef normalize(matrix):\n\treturn matrix/np.sum(matrix, axis=0)\n\ndef expand(matrix, power):\n\treturn np.linalg.matrix_power(matrix, power)\n\ndef inflate(matrix, power):\n\tfor entry in np.nditer(matrix, op_flags=['readwrite']):\n\t\tentry[...] = math.pow(entry, power)\n\treturn matrix\nclass pattern:\n\n\tdef __init__(self,modelFeatures,targetFeature):\n\t\tself.modelFeatures = modelFeatures.split(',')\n\t\tself.targetFeature = targetFeature\n\t\tself.log = logging.getLogger('eion')\n \n\tdef training(self,df,outputLocation):\n\t\tdf[\"code\"] = df[self.targetFeature].astype(\"category\")\n\t\tdf['code'] = df.code.cat.codes\n\t\tdf2 = df[[self.targetFeature,'code']]\n\t\tdf2 = df2.drop_duplicates()\n\t\tcode_book = df2.to_dict('records')\n\t\tsize = len(code_book)\t\t\n\t\tif self.targetFeature in self.modelFeatures:\n\t\t\tself.modelFeatures.remove(self.targetFeature)\n\t\tdf['prev_code'] = df.groupby(self.modelFeatures)['code'].shift()\n\t\tdf['prev_activity'] = df.groupby(self.modelFeatures)[self.targetFeature].shift()\n\t\tprint(self.modelFeatures)\n\t\tdf = df.dropna(axis=0, subset=['prev_code'])\n\t\tdf['prev_code'] = df['prev_code'].astype('int32')\n\t\tmatrix = np.zeros((size, size),float)\n\t\tnp.set_printoptions(suppress=True)\n\t\tfor index, row in df.iterrows():\n\t\t\tmatrix[int(row['prev_code'])][int(row['code'])] += 1\n\t\tnp.fill_diagonal(matrix, 1)\n\t\tmatrix = normalize(matrix)\n\t\tpmatrix = matrix\n\t\ti = 0\n\t\trecords = []\n\t\tfor row in matrix:\n\t\t\tj = 0\n\t\t\tfor val in row:\n\t\t\t\tfor event in code_book:\n\t\t\t\t\tif event['code'] == i:\n\t\t\t\t\t\tpage = event[self.targetFeature]\n\t\t\t\t\tif event['code'] == j:\n\t\t\t\t\t\tnextpage = event[self.targetFeature]\n\t\t\t\trecord = {}\n\t\t\t\trecord['State'] = page\n\t\t\t\trecord['NextState'] = nextpage\n\t\t\t\trecord['Probability'] = round(val,2)\n\t\t\t\trecords.append(record)\n\t\t\t\tj = j+1\n\t\t\ti = i+1\n\t\tdf_probability = pd.DataFrame(records)\n\t\tself.log.info('Status:- |... StateTransition Probability Matrix')\n\t\tfor _ in range(ITERATION_COUNT):\n\t\t\tmatrix = normalize(inflate(expand(matrix, EXPANSION_POWER), INFLATION_POWER))\n\t\tresult = mc.run_mcl(matrix) # run MCL with default parameters\n\t\tc = 0\n\t\tclusters = mc.get_clusters(matrix) # get clusters\n\t\tself.log.info('Status:- |... StateTransition Algorithm applied: MarkovClustering')\n\t\tclusterrecords = []\n\t\tfor cluster in clusters:\n\t\t\tclusterid = c\n\t\t\tclusterlist = ''\n\t\t\tfor pageid in cluster:\n\t\t\t\tfor event in code_book:\n\t\t\t\t\tif event['code'] == pageid:\n\t\t\t\t\t\tpage = event[self.targetFeature]\n\t\t\t\tif clusterlist != '':\n\t\t\t\t\tclusterlist = clusterlist+','\n\t\t\t\tclusterlist = clusterlist+page\n\t\t\trecord = {}\n\t\t\trecord['clusterid'] = c\n\t\t\trecord['clusterlist'] = clusterlist\n\t\t\tclusterrecords.append(record)\n\t\t\tc = c+1\n\t\tdf_cluster = pd.DataFrame(clusterrecords)\n\t\tprobabilityoutputfile = os.path.join(outputLocation, 'stateTransitionProbability.csv')\n\t\tself.log.info('-------> State Transition Probability Matrix:' + probabilityoutputfile)\n\t\tdf_probability.to_csv(probabilityoutputfile,index=False)\n\t\tclusteringoutputfile = os.path.join(outputLocation, 'stateClustering.csv')\n\t\tself.log.info('-------> State Transition Probability Grouping:' + clusteringoutputfile)\n\t\tdf_cluster.to_csv(clusteringoutputfile,index=False)\n\t\tdatadetailsfile = os.path.join(outputLocation, 'datadetails.json') \n\t\tdataanalytics = {}\n\t\tdataanalytics['activity'] = self.targetFeature\n\t\tdataanalytics['sessionid'] = self.modelFeatures[0]\n\t\tupdatedConfig = json.dumps(dataanalytics)\n\t\twith open(datadetailsfile, \"w\") as fpWrite:\n\t\t\tfpWrite.write(updatedConfig) \n\t\tfpWrite.close()\n\t\tevaulatemodel = '{\"Model\":\"MarkovClustering\",\"Score\":0}'\n\t\treturn(evaulatemodel,probabilityoutputfile,clusteringoutputfile)\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n''' '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport json\nimport os\nimport sys\nimport pandas as pd\nfrom pandas import json_normalize\n\n#from selector import selector\n#from inputprofiler import inputprofiler\n#from trained_model import trained_model\n#from output_format import output_format\n\nfrom autogluon.tabular import TabularDataset, TabularPredictor\nfrom autogluon.core.utils.utils import setup_outputdir\nfrom autogluon.core.utils.loaders import load_pkl\nfrom autogluon.core.utils.savers import save_pkl\nimport os.path\n\n\n\nclass MultilabelPredictor():\n\n \"\"\" Tabular Predictor for predicting multiple columns in table.\n Creates multiple TabularPredictor objects which you can also use individually.\n You can access the TabularPredictor for a particular label via: `multilabel_predictor.get_predictor(label_i)`\n\n Parameters\n ----------\n labels : List[str]\n The ith element of this list is the column (i.e. `label`) predicted by the ith TabularPredictor stored in this object.\n path : str\n Path to directory where models and intermediate outputs should be saved.\n If unspecified, a time-stamped folder called \"AutogluonModels/ag-[TIMESTAMP]\" will be created in the working directory to store all models.\n 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.\n Otherwise files from first `fit()` will be overwritten by second `fit()`.\n Caution: when predicting many labels, this directory may grow large as it needs to store many TabularPredictors.\n problem_types : List[str]\n The ith element is the `problem_type` for the", "instruction": "", "output": "" }, { "input": "ith TabularPredictor stored in this object.\n eval_metrics : List[str]\n The ith element is the `eval_metric` for the ith TabularPredictor stored in this object.\n consider_labels_correlation : bool\n Whether the predictions of multiple labels should account for label correlations or predict each label independently of the others.\n 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).\n Set to False if during inference you may want to individually use just the ith TabularPredictor without predicting all the other labels.\n kwargs :\n Arguments passed into the initialization of each TabularPredictor.\n\n \"\"\"\n\n multi_predictor_file = 'multilabel_predictor.pkl'\n\n def __init__(self, labels, path, problem_types=None, eval_metrics=None, consider_labels_correlation=True, **kwargs):\n if len(labels) < 2:\n raise ValueError(\"MultilabelPredictor is only intended for predicting MULTIPLE labels (columns), use TabularPredictor for predicting one label (column).\")\n self.path = setup_outputdir(path, warn_if_exist=False)\n self.labels = labels\n self.consider_labels_correlation = consider_labels_correlation\n self.predictors = {} # key = label, value = TabularPredictor or str path to the TabularPredictor for this label\n if eval_metrics is None:\n self.eval_metrics = {}\n else:\n self.eval_metrics = {labels[i] : eval_metrics[i] for i in range(len(labels))}\n problem_type = None\n eval_metric = None\n for i in range(len(labels)):\n label = labels[i]\n path_i = self.path + \"Predictor_\" + label\n if problem_types is not None:\n problem_type = problem_types[i]\n if eval_metrics is not None:\n eval_metric = self.eval_metrics[i]\n self.predictors[label] = TabularPredictor(label=label, problem_type=problem_type, eval_metric=eval_metric, path=path_i, **kwargs)\n\n def fit(self, train_data, tuning_data=None, **kwargs):\n \"\"\" Fits a separate TabularPredictor to predict each of the labels.\n\n Parameters\n ----------\n train_data, tuning_data : str or autogluon.tabular.TabularDataset or pd.DataFrame\n See documentation for `TabularPredictor.fit()`.\n kwargs :\n Arguments passed into the `fit()` call for each TabularPredictor.\n \"\"\"\n if isinstance(train_data, str):\n train_data = TabularDataset(train_data)\n if tuning_data is not None and isinstance(tuning_data, str):\n tuning_data = TabularDataset(tuning_data)\n train_data_og = train_data.copy()\n if tuning_data is not None:\n tuning_data_og = tuning_data.copy()\n save_metrics = len(self.eval_metrics) == 0\n for i in range(len(self.labels)):\n label = self.labels[i]\n predictor = self.get_predictor(label)\n if not self.consider_labels_correlation:\n labels_to_drop = [l for l in self.labels if l!=label]\n else:\n labels_to_drop = [labels[j] for j in range(i+1,len(self.labels))]\n train_data = train_data_og.drop(labels_to_drop, axis=1)\n if tuning_data is not None:\n tuning_data = tuning_data_og.drop(labels_to_drop, axis=1)\n print(f\"Fitting TabularPredictor for label: {label} ...\")\n predictor.fit(train_data=train_data, tuning_data=tuning_data, **kwargs)\n self.predictors[label] = predictor.path\n if save_metrics:\n self.eval_metrics[label] = predictor.eval_metric\n self.save()\n\n def predict(self, data, **kwargs):\n \"\"\" Returns DataFrame with label columns containing predictions for each label.\n\n Parameters\n ----------\n data : str or autogluon.tabular.TabularDataset or pd.DataFrame\n Data to make predictions for. If label columns are present in this data, they will be ignored. See documentation for `TabularPredictor.predict()`.\n kwargs :\n Arguments passed into the predict() call for each TabularPredictor.\n \"\"\"\n return self._predict(data, as_proba=False, **kwargs)\n\n def predict_proba(self, data, **kwargs):\n \"\"\" Returns dict where each key is a label and the corresponding value is the `predict_proba()` output for just that label.\n\n Parameters\n ----------\n data : str or autogluon.tabular.TabularDataset or pd.DataFrame\n Data to make predictions for. See documentation for `TabularPredictor.predict()` and `TabularPredictor.predict_proba()`.\n kwargs :\n Arguments passed into the `predict_proba()` call for each TabularPredictor (also passed into a `predict()` call).\n \"\"\"\n return self._predict(data, as_proba=True, **kwargs)\n\n def evaluate(self, data, **kwargs):\n \"\"\" Returns dict where each key is a label and the corresponding value is the `evaluate()` output for just that label.\n\n Parameters\n ----------\n data : str or autogluon.tabular.TabularDataset or pd.DataFrame\n Data to evalate predictions of all labels for, must contain all labels as columns. See documentation for `TabularPredictor.evaluate()`.\n kwargs :\n Arguments passed into the `evaluate()` call for each TabularPredictor (also passed into the `predict()` call).\n \"\"\"\n data = self._get_data(data)\n eval_dict = {}\n for label in self.labels:\n print(f\"Evaluating TabularPredictor for label: {label} ...\")\n predictor = self.get_predictor(label)\n eval_dict[label] = predictor.evaluate(data, **kwargs)\n if self.consider_labels_correlation:\n data[label] = predictor.predict(data, **kwargs)\n return eval_dict\n\n def save(self):\n \"\"\" Save MultilabelPredictor to disk. \"\"\"\n for label in self.labels:\n if not isinstance(self.predictors[label], str):\n self.predictors[label] = self.predictors[label].path\n save_pkl.save(path=self.path+self.multi_predictor_file, object=self)\n print(f\"MultilabelPredictor saved to disk. Load with: MultilabelPredictor.load('{self.path}')\")\n\n @classmethod\n def load(cls, path):\n \"\"\" Load MultilabelPredictor from disk `path` previously specified when creating this MultilabelPredictor. \"\"\"\n path = os.path.expanduser(path)\n if path[-1] != os.path.sep:\n path = path + os.path.sep\n return load_pkl.load(path=path+cls.multi_predictor_file)\n\n def get_predictor(self, label):\n \"\"\" Returns TabularPredictor which is used to predict this label. \"\"\"\n predictor = self.predictors[label]\n if isinstance(predictor, str):\n return TabularPredictor.load(path=predictor)\n return predictor\n\n def _get_data(self, data):\n if isinstance(data, str):\n return TabularDataset(data)\n return data.copy()\n\n def _predict(self, data, as_proba=False, **kwargs):\n data = self._get_data(data)\n if as_proba:\n predproba_dict = {}\n for label in self.labels:\n print(f\"Predicting with TabularPredictor for label: {label} ...\")\n predictor = self.get_predictor(label)\n if as_proba:\n predproba_dict[label] = predictor.predict_proba(data, as_multiclass=True, **kwargs)\n data[label] = predictor.predict(data, **kwargs)\n if not as_proba:\n return data[self.labels]\n else:\n return predproba_dict\n\n\n\ndef predict(data):\n try:\n if os.path.splitext(data)[1] == \".tsv\":\n df=pd.read_csv(data,encoding='utf-8',sep='\\\\t')\n elif os.path.splitext(data)[1] == \".csv\":\n df=pd.read_csv(data,encoding='utf-8')\n else:\n if os.path.splitext(data)[1] == \".json\":\n with open(data,'r',encoding='utf-8') as f:\n jsonData = json.load(f)\n else:\n jsonData = json.loads(data)\n df = json_normalize(jsonData)\n #df0 = df.copy()\n\t\t\n\t\t\n #profilerobj = inputprofiler()\n #df = profilerobj.apply_profiler(df)\n #selectobj = selector()\n #df = selectobj.apply_selector(df)\n \n\t\t\n\t\t#modelobj = trained_model()\n #output = modelobj.predict(df,\"\")\n \n # Load the Test data for Prediction\n # ----------------------------------------------------------------------------#\n test_data = df#TabularDataset(data) #'testingDataset.csv'\n #subsample_size = 2\n # ----------------------------------------------------------------------------#\n \n \n # Specify the corresponding target features to be used\n # ----------------------------------------------------------------------------#\n #labels = ['education-num','education','class']\n configFile = os.path.join(os.path.dirname(os.path.abspath(__file__)),'etc','predictionConfig.json')\n with open(configFile, 'rb') as cfile:\n data = json.load(cfile) \n labels = data['targetFeature']\n # ----------------------------------------------------------------------------# \n \n for x in labels:\n if x in list(test_data.columns):\n test_data.drop(x,axis='columns', inplace=True)\n # ----------------------------------------------------------------------------#\n #test_data = test_data.sample(n=subsample_size, random_state=0)\n #print(test_data)\n #test_data_nolab = test_data.drop(columns=labels)\n #test_data_nolab.head()\n test_data_nolab = test_data\n # ----------------------------------------------------------------------------#\n \n \n # Load the trained model from where it's stored\n # ----------------------------------------------------------------------------#\n model_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'ModelPath')\n multi_predictor = MultilabelPredictor.load(model_path) \n # ----------------------------------------------------------------------------#\n \n \n # Start the prediction and perform the evaluation \n # ----------------------------------------------------------------------------#\n predictions = multi_predictor.predict(test_data_nolab)\n \n for label in labels:\n df[label+'_predict'] = predictions[label]\n \n #evaluations = multi_predictor.evaluate(test_data)\n #print(evaluations)\n #print(\"Evaluated using metrics:\", multi_predictor.eval_metrics)\n # ----------------------------------------------------------------------------#\n \n \n # ----------------------------------------------------------------------------#\n #outputobj = output_format()\n #output = outputobj.apply_output_format(df0,output) \n outputjson = df.to_json(orient='records')\n outputjson = {\"status\":\"SUCCESS\",\"data\":json.loads(outputjson)}\n output = json.dumps(outputjson)\n print(\"predictions:\",output)\n return(output)\n # ----------------------------------------------------------------------------#\n \n except KeyError as e:\n output = {\"status\":\"FAIL\",\"message\":str(e).strip('\"')}\n print(\"predictions:\",json.dumps(output))\n return (json.dumps(output))\n except Exception as e:\n output = {\"status\":\"FAIL\",\"message\":str(e).strip('\"')}\n print(\"predictions:\",json.dumps(output))\n return (json.dumps(output))\n \n \nif __name__ == \"__main__\":\n\toutput = predict(sys.argv[1])\n\t\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport json\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\n\nfrom pandas import json_normalize\nfrom autogluon.text import TextPredictor\nimport os.path\n\n\n\ndef predict(data):\n try:\n \n if os.path.splitext(data)[1] == \".tsv\":\n df=pd.read_csv(data,encoding='utf-8',sep='\\\\t')\n elif os.path.splitext(data)[1] == \".csv\":\n df=pd.read_csv(data,encoding='utf-8')\n else:\n if os.path.splitext(data)[1] == \".json\":\n with open(data,'r',encoding='utf-8') as f:\n jsonData = json.load(f)\n else:\n jsonData = json.loads(data)\n df = json_normalize(jsonData)\n \n model_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'text_prediction')\n \n predictor = TextPredictor.load(model_path) \n predictions = predictor.predict(df)\n df['predict'] = predictions\n outputjson = df.to_json(orient='records')\n outputjson = {\"status\":\"SUCCESS\",\"data\":json.loads(outputjson)}\n output = json.dumps(outputjson)\n print(\"predictions:\",output)\n return(output)\n\n except KeyError as e:\n output = {\"status\":\"FAIL\",\"message\":str(e).strip('\"')}\n print(\"predictions:\",json.dumps(output))\n return (json.dumps(output))\n except Exception as e:\n output = {\"status\":\"FAIL\",\"message\":str(e).strip('\"')}\n print(\"predictions:\",json.dumps(output))\n return (json.dumps(output))\n \n \nif __name__ == \"__main__\":\n\toutput = predict(sys.argv[1])\n\t\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n''' '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,20", "instruction": "", "output": "" }, { "input": "23\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os.path\nimport time\nimport subprocess\nimport sys\nfrom appbe.aion_config import kafka_setting\nfrom appbe.aion_config import running_setting\nfrom appbe import installPackage\nfrom appbe import compute\nfrom appbe.models import getusercasestatus\nimport json\nimport pandas as pd\nfrom os.path import expanduser\nimport ntpath\nimport shutil\nimport platform\nfrom pathlib import Path\nhome = expanduser(\"~\")\nif platform.system() == 'Windows':\n LOG_FILE_PATH = os.path.join(home,'AppData','Local','HCLT','AION','logs')\nelse:\n LOG_FILE_PATH = os.path.join(home,'HCLT','AION','logs')\n\ndef convert(obj):\n if isinstance(obj, bool):\n return str(obj).capitalize()\n if isinstance(obj, (list, tuple)):\n return [convert(item) for item in obj]\n if isinstance(obj, dict):\n return {convert(key):convert(value) for key, value in obj.items()}\n return obj\n\t\ndef fl_command(request,Existusecases,usecasedetails):\n command = request.POST.get('flsubmit')\n print(command)\n #kafkaSetting = kafka_setting()\n ruuningSetting = running_setting()\n computeinfrastructure = compute.readComputeConfig()\n modelID = request.POST.get('modelID')\n p = Existusecases.objects.get(id=modelID)\n usecasename = p.ModelName.UsecaseName\n runningStatus,pid,ip,port = installPackage.checkModelServiceRunning(usecasename)\n installationStatus,modelName,modelVersion=installPackage.checkInstalledPackge(usecasename)\n usecasedetail = usecasedetails.objects.get(id=p.ModelName.id)\n usecase = usecasedetails.objects.all()\n models = Existusecases.objects.filter(ModelName=usecasedetail,Status='SUCCESS')\n for model in models:\n model.scoringCreteria = 'NA'\n model.score = 'NA'\n model.deploymodel = 'NA'\n if os.path.isdir(str(model.DeployPath)):\n modelPath = os.path.join(str(model.DeployPath),'etc','output.json')\n try:\t\n with open(modelPath) as file:\n outputconfig = json.load(file)\n file.close()\n if outputconfig['status'] == 'SUCCESS':\n model.scoringCreteria = outputconfig['data']['ScoreType']\n model.score = outputconfig['data']['BestScore']\n model.deploymodel = outputconfig['data']['BestModel']\n model.modelType = outputconfig['data']['ModelType']\n model.featuresused = eval(outputconfig['data']['featuresused'])\n model.targetFeature = outputconfig['data']['targetFeature']\n model.modelParams = outputconfig['data']['params']\n model.dataPath = os.path.join(str(model.DeployPath),'data', 'postprocesseddata.csv.gz')\t\t\t\t\t\n model.maacsupport = 'True'\n model.flserversupport = 'False'\n supportedmodels = [\"Logistic Regression\",\"Neural Network\",\"Linear Regression\"]\n if model.deploymodel in supportedmodels:\n model.flserversupport = 'True'\n else:\n model.flserversupport = 'False'\n supportedmodels = [\"Logistic Regression\",\n \"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)\"]\n if model.deploymodel in supportedmodels:\n model.maacsupport = 'True'\n else:\n model.maacsupport = 'False' \n supportedmodels = [\"Extreme Gradient Boosting (XGBoost)\"]\n if model.deploymodel in supportedmodels:\n model.encryptionsupport = 'True'\n else:\n model.encryptionsupport = 'False'\t \n except Exception as e: \n pass\t\n flserver = os.path.join(str(p.DeployPath),'publish','FedLearning')\n if command == 'startServer':\n flservicefile = os.path.join(flserver,'fedServer','aionfls.py')\n confilefile = \tos.path.join(flserver,'fedServer','config.json')\n if platform.system() == 'Windows':\n outputStr = subprocess.Popen([sys.executable, flservicefile,confilefile],creationflags = subprocess.CREATE_NEW_CONSOLE)\n else:\n outputStr = subprocess.Popen([sys.executable, flservicefile,confilefile]) \n Status = 'SUCCESS'\n Msg = 'Federated Learning Server Started'\t\t\t\n if command == 'saveflconfig':\t\n #print(command)\n fedserverPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','utilities','fedServer'))\n shutil.rmtree(flserver, ignore_errors=True)\t\t\n Path(flserver).mkdir(parents=True, exist_ok=True)\t\n flcopypath = os.path.join(flserver,'fedServer')\t\t\n shutil.copytree(fedserverPath,flcopypath)\n fedserverDataPath = os.path.join(flcopypath,'data')\n shutil.copy2(request.POST.get('flserver_datalocation'),fedserverDataPath) \t\t\n flcon = {}\n AlgorithmNames={'Logistic Regression':'LogisticRegression','Neural Network':'deeplearning','Linear Regression':'LinearRegression'}\t\t \n flcon['server_IP'] = request.POST.get('flserver_ipaddress')\n flcon['server_port'] = request.POST.get('flserver_port')\n flcon['model_name'] = AlgorithmNames[request.POST.get('flserver_model')]\n flcon['version'] = request.POST.get('flserver_Version')\n flcon['model_hyperparams'] = convert(eval(request.POST.get('flserver_params')))\n dataLocation = request.POST.get('flserver_datalocation')\n dataPath,datafile = ntpath.split(dataLocation)\n flcon['data_location'] = 'data/'+datafile\n flcon['selected_feature'] = \",\".join([model for model in eval(request.POST.get('flserver_trainingfeatures'))])\n flcon['target_feature'] = request.POST.get('flserver_targetfeature')\t\n flcon['problem_type'] = request.POST.get('flserver_modelType')\t\t\n flcon['min_available_clients'] = request.POST.get('flserver_noofclient')\n flcon['min_fit_clients'] = 2\n flcon['fl_round'] = request.POST.get('flserver_trainround')\n flcon['evaluation_required'] = request.POST.get('flserver_evaluation')\n flcon['model_store'] = \"\"\n flconfigfile = os.path.join(flcopypath,'config.json')\n flconjson = json.dumps(flcon)\n f = open(flconfigfile, \"w+\")\n f.seek(0)\n f.write(flconjson)\n f.truncate()\n f.close()\n nouc = 0\n Status = 'Success'\n Msg = 'Federated Learning Server Configured'\t\n if command =='startClient':\n flconfigfile = os.path.join(str(model.DeployPath),'publish','FedLearning','fedServer','config.json')\n if os.path.isfile(flconfigfile):\n with open(flconfigfile) as file:\n flconfig = json.load(file)\n file.close()\t\t\t\n numberofclient = flconfig['min_available_clients']\n for x in range(int(numberofclient)): \n flclientdirectory = os.path.join(str(model.DeployPath),'publish','FedLearning','fedClient_'+str(x+1))\t\t \n flclientpath = os.path.join(str(model.DeployPath),'publish','FedLearning','fedClient_'+str(x+1),'fedClient.bat')\n if platform.system() == 'Windows':\n outputStr = subprocess.Popen([flclientpath],creationflags = subprocess.CREATE_NEW_CONSOLE,cwd=flclientdirectory)\n else:\n outputStr = subprocess.Popen([flclientpath],cwd=flclientdirectory) \n Status = 'SUCCESS'\n Msg = 'Federated Learning Client Started' \n if command == 'generateClient':\n flconfigfile = os.path.join(str(model.DeployPath),'publish','FedLearning','fedServer','config.json')\n if os.path.isfile(flconfigfile):\n with open(flconfigfile) as file:\n flconfig = json.load(file)\n file.close()\t\t\t\n numberofclient = flconfig['min_available_clients']\n trainingDataLocation = os.path.join(str(p.DeployPath),'data','postprocesseddata.csv.gz')\t\n from utils.file_ops import read_df_compressed\n status,df = read_df_compressed(trainingDataLocation,encoding='utf8')\n for x in range(int(numberofclient)):\n flclientpath = os.path.join(str(model.DeployPath),'publish','FedLearning','fedClient_'+str(x+1))\n logPath = os.path.join(flclientpath,'logs')\n modelsPath = os.path.join(flclientpath,'models')\n Path(flclientpath).mkdir(parents=True, exist_ok=True)\t\t\t\n Path(logPath).mkdir(parents=True, exist_ok=True)\t\t\t\n Path(modelsPath).mkdir(parents=True, exist_ok=True)\t\n flclientor = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','utilities','fedClient','aionflc.py'))\n shutil.copy2(flclientor,flclientpath)\n flclientor = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','utilities','fedClient','utils.py')) \n shutil.copy2(flclientor,flclientpath)\n flclientor = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','utilities','fedClient','dl_model.py')) \n shutil.copy2(flclientor,flclientpath)\n subset = df.sample(frac=0.8)\n dataPath = os.path.join(flclientpath,'data')\n Path(dataPath).mkdir(parents=True, exist_ok=True)\t\t\t\n datafile = os.path.join(dataPath,'data.dat')\n subset.to_csv(datafile, index=False)\t\n flclient = {}\n flclient['server_IP'] = flconfig['server_IP']\n flclient['server_port'] = flconfig['server_port']\n flclient['model_name'] = flconfig['model_name']\n flclient['problem_type'] = flconfig['problem_type']\n flclient['version'] = flconfig['version']\n flclient['model_hyperparams'] = flconfig['model_hyperparams']\n flclient['data_location'] = 'data\\\\data.dat'\n flclient['selected_feature'] = flconfig['selected_feature']\n flclient['target_feature'] = flconfig['target_feature']\n flclient['train_size'] = 80\n #flclient['deploy_location'] = flconfig['deploy_location']\n flclient['num_records_per_round'] = request.POST.get('flserver_recordperround')\n flclient['wait_time'] = request.POST.get('flserver_roundtime')\n flclient['model_overwrite'] = request.POST.get('model_overwritelabel')\t\t\t\n configPath = os.path.join(flclientpath,'config')\n Path(configPath).mkdir(parents=True, exist_ok=True)\t\t\t\n configFile = os.path.join(configPath,'config.json')\n flconjson = json.dumps(flclient)\n f = open(configFile, \"w+\")\n f.seek(0)\n f.write(flconjson)\n f.truncate()\n f.close()\n locate_python = sys.exec_prefix\n bathfilePath = os.path.join(flclientpath,'fedClient.bat')\t\t\t\n batfilecontent='''\n@ECHO OFF\n\nGOTO weiter\n:setenv\nSET \"Path={python_path}\\\\;%Path%;\"\nGOTO :EOF\n\n:weiter\nIF \"%1\" EQU \"setenv\" (\n ECHO.\n ECHO Setting environment for AION Federated Learning Client.\n\tCALL :setenv\n\tpython %CD%\\\\\\\\aionflc.py %CD%\\\\config\\\\config.json\n\t\n) ELSE (\n SETLOCAL EnableDelayedExpansion\n\t\n\tTITLE ION Federated Learning Client\n\t\n PROMPT %username%@%computername%$S$P$_#$S\n\t\n\tIF EXIST aion.config (FOR /F \"delims=\" %%A IN (aion.config) DO SET \"%%A\")\n\tSTART \"\" /B %COMSPEC% /K \"%~f0\" setenv\n)\n'''.format(python_path=str(locate_python))\n f = open(bathfilePath, \"w\",encoding=\"utf-8\")\n f.write(str(batfilecontent))\n f.close()\n\t\t\t\n Status = 'Success'\n Msg = 'Federated Learning Client Code Generated'\t\n nouc = 0\n #selected_use_case,ModelVersion,ModelStatus = getusercasestatus(request)\n from appbe.pages import get_usecase_page \n status,context,action = get_usecase_page(request,usecasedetails,Existusecases) \n context['Status'] = Status \n context['Msg'] = Msg\n return(context) \t '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport csv\nimport logging\nimport pandas as pd\n\n\nclass csv_validator:\n\n def __init__(self):\n self.log = logging.getLogger('eion')\n\n def __text_header(self, filename, threshold=0.75):\n df = pd.read_csv(filename, header=None,nrows=1000)\n numeric_columns = df.dtypes[df.dtypes != object]\n if not len(numeric_columns):\n first_row_len = df.iloc[0].str.len()\n index = 0\n for c in df", "instruction": "", "output": "" }, { "input": ":\n if (df[c].map(len).mean() * threshold <= first_row_len[index]):\n return False\n index += 1\n return True\n return False\n\n def validate_header(self, filename,delimiter,textqualifier,threshold=0.75):\n with open(filename, 'rt',encoding='utf-8') as csvfile:\n has_header = csv.Sniffer().has_header(csvfile.read(8192))\n csvfile.seek(0)\n if not has_header:\n has_header = self.__text_header(filename, threshold)\n reader = csv.reader(csvfile, delimiter=delimiter,quotechar=textqualifier)\n good_csv = True\n col_len = len(next(reader))\n bad_lines = []\n offset = 2 # +1 for first read and +1 for python index start at 0\n for index, row in enumerate(reader):\n if len(row) != col_len:\n good_csv = False\n if(index == 1 and has_header):\n offset += 1\n bad_lines.append(index + offset)\n return has_header, good_csv, bad_lines\n\n\nif __name__ == '__main__':\n import sys\n val = csv_validator()\n print(val.validate_header(sys.argv[1]))\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nfrom typing import Tuple, Union, List\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom flwr.common.logger import log\nfrom logging import INFO\n\nTRUE_FALSE_MAPPING = {'True':'False','true':'false',True:False,'y':'n','Y':'N','Yes':'No','yes':'no','YES':'NO'}\nXY = Tuple[np.ndarray, np.ndarray]\nDataset = Tuple[XY, XY]\nLogRegParams = Union[XY, Tuple[np.ndarray]]\nXYList = List[XY]\nmodelUsed=None\nmodelname=None\ndef setmodelName(modelselected):\n\ttry:\n\t\tmodelname=str(modelselected)\n\t\tprint(\"setmodelName ,given modelname: \\\\n\",modelname)\n\t\tif (modelname.lower() == 'logisticregression'):\n\t\t\tmodelUsed=LogisticRegression()\t\t\t\n\t\t\treturn True\n\t\telif (modelname.lower() == \"naivebayes\"): \n\t\t\tmodelUsed = GaussianNB()\n\t\t\treturn True\n\t\telif (modelname.lower() == \"sgdclassifier\"):\n\t\t\t#from sklearn.linear_model import SGDClassifier\n\t\t\tmodelUsed=SGDClassifier()\n\t\t\treturn True\t\t\n\t\telif (modelname.lower() == \"knn\"):\n\t\t\tmodelUsed = KNeighborsClassifier()\n\t\t\treturn True\n\t\telif (modelname.lower() == \"decisiontreeclassifier\"):\n\t\t\tmodelUsed = DecisionTreeClassifier()\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\texcept Exception as e:\n\t\tlog(INFO, \"set fl model name fn issue: \",e)\n\ndef get_model_parameters(model:modelUsed) -> LogRegParams:\n \"\"\"Returns the paramters of a sklearn LogisticRegression model.\"\"\" \n model_name=model.__class__.__name__\n if model.fit_intercept: \n params = (model.coef_, model.intercept_)\n else:\n params = (model.coef_,)\n \n return params\n\n\ndef set_model_params(\n model:modelUsed, params: LogRegParams\n) -> modelUsed:\n \"\"\"Sets the parameters of a sklean LogisticRegression model.\"\"\" \n model.coef_ = params[0]\n model_name=model.__class__.__name__\n try:\n if model.fit_intercept:\n model.intercept_ = params[1]\n except Exception as e:\n log(INFO, \"set_model_params fn issue: \",e)\n pass\n \n return model\n\n\ndef set_initial_params(model,no_classes,no_features):\n \"\"\"Sets initial parameters as zeros Required since model params are\n uninitialized until model.fit is called.\n\n But server asks for initial parameters from clients at launch. Refer\n to sklearn.linear_model.LogisticRegression documentation for more\n information.\n \"\"\"\n \n n_classes = no_classes \n n_features = no_features\n model.classes_ = np.array([i for i in range(n_classes)])\n model.coef_ = np.zeros((n_classes, n_features))\n model_name=model.__class__.__name__\n try:\n if model.fit_intercept:\n model.intercept_ = np.zeros((n_classes,))\n except Exception as e:\n log(INFO, \"set_initial_params fn issue: \",e)\n pass\n\n\n\ndef shuffle(X: np.ndarray, y: np.ndarray) -> XY:\n \"\"\"Shuffle X and y.\"\"\"\n rng = np.random.default_rng()\n idx = rng.permutation(len(X))\n return X[idx], y[idx]\n\n\ndef partition(X: np.ndarray, y: np.ndarray, num_partitions: int) -> XYList:\n \"\"\"Split X and y into a number of partitions.\"\"\"\n return list(\n zip(np.array_split(X, num_partitions), np.array_split(y, num_partitions))\n )\n\ndef get_true_option(d, default_value=None):\n if isinstance(d, dict):\n for k,v in d.items():\n if v in TRUE_FALSE_MAPPING.keys():\n return k\n return default_value\n\ndef get_true_options( d):\n options = []\n if isinstance(d, dict):\n for k,v in d.items():\n if v in TRUE_FALSE_MAPPING.keys():\n options.append(k)\n return options\n\ndef set_true_option(d, key=None, value='True'):\n if key in d.keys():\n if value in TRUE_FALSE_MAPPING.keys():\n for k in d.keys():\n d[ k] = TRUE_FALSE_MAPPING[ value]\n d[key] = value\n return d\n \n\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport pandas as pd\nimport requests\nfrom io import StringIO\n\nimport json\nimport time\nimport shutil\nimport sys\nfrom appbe import compute\nfrom appbe.aion_config import kafka_setting\nfrom appbe.aion_config import running_setting\nfrom appbe.s3bucketsDB import get_s3_bucket\nfrom appbe.gcsbucketsDB import get_gcs_bucket\nfrom appbe.azureStorageDB import get_azureStorage\nfrom appbe.aion_config import eda_setting\nfrom appbe.s3bucketsDB import read_s3_bucket\nfrom appbe.gcsbucketsDB import read_gcs_bucket\nfrom appbe.azureStorageDB import read_azureStorage\nfrom appbe.validatecsv import csv_validator\n\nimport time\n\nfrom appbe.dataPath import LOG_LOCATION\nfrom appbe.dataPath import DATA_FILE_PATH\nfrom appbe.log_ut import logg\nimport logging\n\ndef langchain_splittext(filename):\n try:\n from langchain.document_loaders import PyPDFLoader\n from langchain.text_splitter import RecursiveCharacterTextSplitter \n loader = PyPDFLoader(filename)\n pages = loader.load() \n text_splitter = RecursiveCharacterTextSplitter(chunk_size=500,chunk_overlap=50)\n texts = text_splitter.split_documents(pages) \n return(texts)\n except Exception as e:\n print(e)\n \ndef pd_lanfchain_textsplitter(datalocation,data):\n try:\n document=[]\n for i in range(len(data)):\n filename = os.path.join(datalocation,data.loc[i,\"File\"])\n out = langchain_splittext(filename)\n for doc in out:\n print(doc.page_content)\n document.append(doc.page_content)\n my_data = pd.DataFrame({'instruction': document}) \n n = 1\n my_data[\"response\"] = my_data[\"instruction\"].tolist()[n:] + my_data[\"instruction\"].tolist()[:n]\n filetimestamp = str(int(time.time()))\n filename = os.path.join(DATA_FILE_PATH, 'LLMTuning_' + filetimestamp+'.csv')\n my_data.to_csv(filename,index=False)\n return(filename)\n except Exception as e:\n print(e)\ndef getimpfeatures(dataFile, numberoffeatures,delimiter,textqualifier):\n imp_features = []\n if numberoffeatures > 20:\n try:\n from appbe.eda import ux_eda\n eda_obj = ux_eda(dataFile,delimiter,textqualifier,optimize=1) \n if eda_obj.getNumericFeatureCount() >= 2:\n pca_map = eda_obj.getPCATop10Features()\n imp_features = pca_map.index.values.tolist()\n except Exception as e:\n print(e)\n pass\n return imp_features\n\ndef pdf2text(inpFileName):\n try:\n from pypdf import PdfReader\n reader = PdfReader(inpFileName)\n number_of_pages = len(reader.pages)\n text=\"\"\n OrgTextOutputForFile=\"\" \n for i in range(number_of_pages) :\n page = reader.pages[i]\n text1 = page.extract_text()\n text=text+text1\n import nltk\n tokens = nltk.sent_tokenize(text)\n for sentence in tokens:\n sentence=sentence.replace(\"\\\\n\", \" \") \n if len(sentence.split()) < 4 :\n continue\n if len(str(sentence.split(',')).split()) < 8 :\n continue\n if any(chr.isdigit() for chr in sentence) :\n continue\n OrgTextOutputForFile= OrgTextOutputForFile+str(sentence.strip())\n #print(\"\\\\n\\\\n\\\\n\\\\nOrgTextOutputForFile------------->\\\\n\\\\n\\\\n\",OrgTextOutputForFile)\n return (OrgTextOutputForFile) \n except Exception as e:\n print(\"Encountered exception. {0}\".format(e))\n \ndef getcommonfields():\n computeinfrastructure = compute.readComputeConfig()\n from appbe.aion_config import settings\n usecasetab = settings() \n kafkaSetting = kafka_setting()\n ruuningSetting = running_setting()\n context = {'s3buckets':get_s3_bucket(),'gcsbuckets':get_gcs_bucket(),'computeinfrastructure':computeinfrastructure,'kafkaSetting':kafkaSetting,'ruuningSetting':ruuningSetting,'usecasetab':usecasetab,'azurestorage':get_azureStorage()}\n return context\n\ndef getusercasestatus(request):\n if 'UseCaseName' in request.session:\n selected_use_case = request.session['UseCaseName']\n else:\n selected_use_case = 'Not Defined'\n\n if 'ModelVersion' in request.session:\n ModelVersion = request.session['ModelVersion']\n else:\n ModelVersion = 0\n\n if 'ModelStatus' in request.session:\n ModelStatus = request.session['ModelStatus']\n else:\n ModelStatus = 'Not Trained'\n return selected_use_case,ModelVersion,ModelStatus\n \ndef delimitedsetting(delimiter='',textqualifier='',other=''):\n if delimiter != '':\n if delimiter.lower() == 'tab' or delimiter.lower() == '\\\\t':\n delimiter = '\\\\t'\n elif delimiter.lower() == 'semicolon' or delimiter.lower() == ';':\n delimiter = ';'\n elif delimiter.lower() == 'comma' or delimiter.lower() == ',':\n delimiter = ','\n elif delimiter.lower() == 'space' or delimiter.lower() == ' ':\n delimiter = ' '\n elif delimiter.lower() == 'other' or other.lower() != '':\n if other != '':\n delimiter = other\n else:\n delimiter = ','\n elif delimiter != '':\n delimiter = delimiter\n else:\n delimiter = ','\n else:\n delimiter = ','\n if textqualifier == '':\n textqualifier = '\"'\n return delimiter,textqualifier\n\ndef multipleZipExtraction(data,DATA_FILE_PATH):\n from zipfile import ZipFile\n try:\n import glob\n filetimestamp = str(int(time.time()))\n extracted_data = os.path.join(DATA_FILE_PATH, 'extracted_' + filetimestamp)\n os.mkdir(extracted_data)\n with ZipFile(data, 'r') as zObject:\n zObject.extractall(extracted_data)\n csv_files = glob.glob(r'{}\\\\*.{}'.format(extracted_data,'csv'))\n df_csv_append = pd.DataFrame()\n for file in csv_files:\n df = pd.read_csv(file)\n df_csv_append = df_csv_append.append(df, ignore_index=True)\n for f in os.listdir(extracted_data):\n os.remove(os.path.join(extracted_data, f))\n #os.mkdir(extracted_data)\n combined_data = os.path.join(extracted_data,filetimestamp+'.csv')\n df_csv_append.to_csv(combined_data)\n return combined_data\n except Exception as e:\n if os.path.exists(extracted_data):\n shutil.rmtree(extracted_data)\n #print (e)\n return ''\n\n\n\ndef tarFileExtraction(data,DATA_FILE_PATH):\n try:\n import tarfile\n filetimestamp = str(int(time.time()))\n extracted_data = os.path.join(DATA_FILE_PATH, 'extracted_' + filetimestamp)\n os.mkdir(extracted_data)\n if data.endswith('tar'):\n file = tarfile.open(data)\n file.extractall(extracted_data)\n file.close()\n\t \n for f in os.listdir(extracted_data):\n if f.endswith('csv') or f.endswith('tsv'):\n dataFile = os.path.join(extracted_data,f)\n return dataFile\n except Exception as e:\n if os.path.exists(extracted_data):\n shutil.rmtree(extracted_data)\n print (e)\n return ''\n# ------ changes for the bug 1", "instruction": "", "output": "" }, { "input": "0379 starts---------------- By Usnish ------\ndef checkRamAfterLoading(dataPath):\n import psutil\n availableRam = psutil.virtual_memory()[1]/1e9\n filesize = os.path.getsize(dataPath)/1e9\n return availableRam < 2*filesize\ndef checkRamBeforeLoading(dataPath):\n import psutil\n filesize = os.path.getsize(dataPath)/1e9\n totalRam = psutil.virtual_memory()[0] / 1e9\n if( filesize > 0.8 * totalRam):\n return \"File size is larger than the 80% of Total RAM.\"\n return \"\"\n# ------ changes for the bug 10379 ends---------------- By Usnish ------\n\n\n# ---------- 10012:Decision Threshold related Changes S T A R T ----------\n# This method is used to check If -> \n# 80% of available RAM size is greater than ingested data (or not). \ndef checkRAMThreshold(dataPath):\n import psutil\n availableRam = psutil.virtual_memory()[1]/1e9\n filesize = os.path.getsize(dataPath)/1e9\n return (0.8 * availableRam) > filesize\n# ---------------------- E N D ----------------------\n\n\n# Text Data Labelling using LLM related changes\n# --------------------------------------------------------\ndef ingestTextData(request, DATA_FILE_PATH):\n log = logging.getLogger('log_ux')\n try:\n Datapath = request.FILES['DataFilePath']\n from appbe.eda import ux_eda\n \n ext = str(Datapath).split('.')[-1]\n request.session['uploadfiletype'] = 'Local'\n request.session['datatype'] = 'Normal'\n filetimestamp = str(int(time.time()))\n if ext.lower() in ['csv','tsv','tar','zip','avro','parquet']:\n dataFile = os.path.join(DATA_FILE_PATH,'AION_' + filetimestamp+'.'+ext)\n else:\n dataFile = os.path.join(DATA_FILE_PATH,'AION_' + filetimestamp)\n with open(dataFile, 'wb+') as destination:\n for chunk in Datapath.chunks():\n destination.write(chunk)\n destination.close()\n dataPath = dataFile\n \n request.session['textdatapath'] = dataPath\n \n # import pdb\n # pdb.set_trace()\n \n # check_df = pd.read_csv(dataPath)\n eda_obj = ux_eda(dataPath)\n check_df = eda_obj.getdata()\n \n df_top = check_df.head(10)\n df_json = df_top.to_json(orient=\"records\")\n df_json = json.loads(df_json)\n \n # featuresList = check_df.columns.tolist()\n features,dateFeature,seqFeature,constantFeature,textFeature,targetFeature,numericCatFeatures,numericFeature,catfeatures = eda_obj.getFeatures()\n \n noTextFeature = False\n if len(textFeature) == 0: \n noTextFeature = True\n \n context = {'raw_data':df_json, 'featuresList':textFeature, 'selected':'DataOperations', 'noTextFeature':noTextFeature}\n \n return context\n \n except Exception as e:\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n \n context = {'error': 'Failed to read data','emptycsv' : 'emptycsv'}\n log.info('Text Data Ingestion -- Error : Failed to read data, '+str(e))\n log.info('Details : '+ str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n return context\n# ---------------------- E N D ---------------------------\n\n\n\ndef ingestDataFromFile(request,DATA_FILE_PATH):\n log = logging.getLogger('log_ux')\n delimiter,textqualifier = delimitedsetting(request.POST.get('delimiters'),request.POST.get('qualifier'),request.POST.get('delimiters_custom_value'))\n request.session['delimiter'] = delimiter\n request.session['textqualifier'] = textqualifier\n context = getcommonfields()\n selected_use_case,ModelVersion,ModelStatus = getusercasestatus(request)\n context.update({'selected_use_case': selected_use_case,'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion,})\n try:\n t1 = time.time()\n request.session['uploadfiletype'] = ''\n request.session['uploadLocation'] = ''\n data_is_large = False\n check_df = pd.DataFrame()\n if request.method == 'POST':\n if 'ModelVersion' in request.session:\n ModelVersion = request.session['ModelVersion']\n else:\n ModelVersion = 0\n if 'ModelName' not in request.session:\n movenext = False\n request.session['currentstate'] = 0\n context.update({'tab': 'tabconfigure', 'error': 'Please Create/Select the Use Case First', 'movenext': movenext,'currentstate': request.session['currentstate']})\n log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(\n ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : Please Create/Select the Use Case First')\n return context\n else:\n type = request.POST.get(\"optradio\") \n if type == \"s3Bucket\":\n try:\n request.session['uploadfiletype'] = 'S3Bucket'\t\t\t\t\t\t\n bucketname = request.POST.get('s3bucketname')\n fileName = request.POST.get('s3file')\n if fileName != '':\n status,msg,check_df = read_s3_bucket(bucketname,fileName,DATA_FILE_PATH)\n if status == 'Success':\n filetimestamp = str(int(time.time()))\n dataFile = os.path.join(DATA_FILE_PATH, 'AION_' + filetimestamp+'.csv')\n check_df.to_csv(dataFile, index=False)\n request.session['datalocation'] = dataFile\n \n else :\n request.session['currentstate'] = 0 #usnish\n context.update({'error': str(msg),'ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})\n log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(\n ModelVersion) + ' : ' + '0' + 'sec' + ' : ' + 'Error : ' + str(msg))\n return context\n \n else: #usnish\n request.session['currentstate'] = 0\n context.update({'error': 'Please provide a file name','ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})\n log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(\n ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : Please provide a file name')\n return context\n except Exception as e:\n request.session['currentstate'] = 0\n context.update({'error': str(e),'ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})\n log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(\n ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : '+ str(e))\n return context\n '''request.session['datalocation'] = \"S3\"'''\n \n \n # -------------------------------- Graviton-Integration Changes S T A R T -------------------------------- \n elif type == \"graviton\":\n try:\n dataServiceId = request.POST.get('dataservice')\n metadataId = request.POST.get('metadata')\n data = []\n from appbe.aion_config import get_graviton_data\n graviton_url,graviton_userid = get_graviton_data()\n gravitonURL = graviton_url\n gravitonUserId = graviton_userid\n \n # url = 'https://xenius.azurewebsites.net/api/getdata?userid=1&dataserviceid='+str(dataserviceId) +'&metadataid=' +str(metadataId)\n url = gravitonURL + 'getdata?userid=' + gravitonUserId +'&dataserviceid='+str(dataServiceId) +'&metadataid=' +str(metadataId)\n print(url)\n response = requests.get(url)\n statuscode = response.status_code\n if statuscode == 200:\n json_dictionary = json.loads(response.content)\n data = json_dictionary['result']\n \n firstElement = next(iter(data[0].keys()))\n check_df = pd.DataFrame.from_dict(data[0][firstElement])\n \n filetimestamp = str(int(time.time()))\n dataFile = os.path.join(DATA_FILE_PATH, 'AION_' + filetimestamp+'.csv')\n check_df.to_csv(dataFile, index=False)\n \n request.session['uploadfiletype'] = 'Graviton'\n request.session['datalocation'] = str(dataFile)\n except Exception as e:\n print(e)\n request.session['currentstate'] = 0\n context.update({'error':'Check log file for more details','ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})\n log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error :'+str(e))\n return context\n # ------------------------------------------------ E N D -------------------------------------------------\n \n elif type == \"azurestorage\":\t\t\t\t\t\t\t\n try:\t\t\n request.session['uploadfiletype'] = 'AzureStorage'\t\t\t\t\t\t\n azurename = request.POST.get('azurename')\n directoryname = request.POST.get('azuredirectory')\n if directoryname != '':\n \n status,msg,check_df = read_azureStorage(azurename,directoryname,DATA_FILE_PATH)\n if status == 'Success':\n filetimestamp = str(int(time.time()))\n dataFile = os.path.join(DATA_FILE_PATH, 'AION_' + filetimestamp+'.csv')\n check_df.to_csv(dataFile, index=False)\n '''request.session['datalocation'] = \"S3\"'''\n request.session['datalocation'] = dataFile\n else :\n request.session['currentstate'] = 0 #usnish\n context.update({'error': str(msg),'ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})\n log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(\n ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : ' +str(msg))\n\n return context \n \n else: #usnish\n request.session['currentstate'] = 0\n context.update({'error': 'Please provide a file name','ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})\n log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(\n ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : Please provide a file name')\n return context\n except Exception as e:\n print(e)\n request.session['currentstate'] = 0\n context.update({'error': 'File does not exist','ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})\n log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(\n ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : File does not exist, '+str(e))\n return context\n elif type == \"googleBucket\":\n try:\t\t\n request.session['uploadfiletype'] = 'GCPBucket'\t\t\t\t\t\t\n bucketname = request.POST.get('gcpbucketname')\n fileName = request.POST.get('file1')\n if fileName != '':\n \n status,msg,check_df = read_gcs_bucket(bucketname,fileName,DATA_FILE_PATH)\n if status == 'Success':\n filetimestamp = str(int(time.time()))\n dataFile = os.path.join(DATA_FILE_PATH, 'AION_' + filetimestamp+'.csv')\n check_df.to_csv(dataFile, index=False)\n '''request.session['datalocation'] = \"S3\"'''\n request.session['datalocation'] = dataFile\n else :\n request.session['currentstate'] = 0 #usnish\n context.update({'error': str(msg),'ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})\n log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(\n ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : '+str(msg))\n return context \n else: #usnish\n request.session['currentstate'] = 0\n context.update({'error': 'Please provide a file name','ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})\n log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(\n ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : Please provide a file name')\n return context\n except Exception as e:\n request.session['currentstate'] = 0\n context.update({'error': 'File does not exist','ModelVersion': ModelVersion,'emptycsv' : 'emptycsv'})\n log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(\n ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : File does not exist, ' + str(e))\n return context\n elif type == \"url\":\n try:\n request.session['uploadfiletype'] = 'URL' \t\t\t\t\t\t\n url_text = request.POST.get('urlpathinput')\n log.info('Data ingesttion from URL..')\n request.session['uploadLocation'] = url_text\n url = url_text\n check_df = pd.read_csv(url)\n filetimestamp = str(int(time.time()))\n dataFile = os.path.join(DATA_FILE_PATH, 'AION_' + filetimestamp+'.csv')\n check_df.to_csv(dataFile,index=False)\t\n request.session['datalocation'] = dataFile \n except Exception as e:\n request.session['currentstate'] = 0\n e = str(e)\n print(e)\n if e.find(\"tokenizing\")!=-1:\n error", "instruction": "", "output": "" }, { "input": "= \"This is not an open source URL to access data\"\n context.update({'error': error, 'ModelVersion': ModelVersion, 'emptycsv': 'emptycsv'})\n elif e.find(\"connection\")!=-1:\n error =", "instruction": "", "output": "" }, { "input": "(selected_use_case) + ' : ' + str(ModelVersion) + ' : ' + str(\n round(t2 - t1)) + ' sec' + ' : ' + 'Success')\n # EDA Subsampling changes\n context.update({'range':range(1,101),'samplePercentage':samplePercentage, 'samplePercentval':samplePercentval, 'showRecommended':showRecommended,'featuresList': featuresList,'tab': 'tabconfigure', 'data': df_json, 'status_msg': statusmsg,\n 'selected': 'modeltraning','imp_features':imp_features,'numberoffeatures':numberoffeatures,\n 'currentstate': request.session['currentstate'], 'finalstate': request.session['finalstate'],\n 'exploratory': False})\n if msg!=\"\":\n context.update({'data_size_alert': msg})\n return context\n except Exception as e:\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n request.session['currentstate'] = 0\n context.update({'error': 'Failed to read data','emptycsv' : 'emptycsv'})\n log.info('Data Ingestion : ' + str(selected_use_case) + ' : ' + str(ModelVersion) + ' : ' + '0' + ' sec' + ' : ' + 'Error : Failed to read data, '+str(e))\n log.info('Details : '+ str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n return context\n\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nfrom pathlib import Path\nimport sqlite3\nclass sqlite_db():\n\n def __init__(self, location, database_file=None):\n if not isinstance(location, Path):\n location = Path(location)\n if database_file:\n self.database_name = database_file\n else:\n self.database_name = location.stem\n db_file = str(location / self.database_name)\n self.conn = sqlite3.connect(db_file)\n self.cursor = self.conn.cursor()\n\n def table_exists(self, name):\n query = f\"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}';\"\n listOfTables = self.cursor.execute(query).fetchall()\n return len(listOfTables) > 0\n\n def read_data(self, table_name, condition = None):\n if condition:\n query = f\"SELECT * FROM {table_name} WHERE \"+condition\n else:\n query = f\"SELECT * FROM {table_name}\"\n row = self.cursor.execute(query).fetchall()\n return list(row)\n \n def column_names(self, table_name):\n query = f\"SELECT * FROM {table_name}\"\n row = self.cursor.execute(query).fetchall()\n column_names = list(map(lambda x:x[0],self.cursor.description))\n return column_names\n # return pd.read_sql_query(f\"SELECT * FROM {table_name}\", self.conn)\n\n def create_table(self, name, columns, dtypes):\n query = f'CREATE TABLE IF NOT EXISTS {name} ('\n\n for column, data_type in zip(columns, dtypes):\n query += f\"'{column}'\tTEXT,\"\n query = query[:-1]\n query += ');'\n self.conn.execute(query)\n return True\n\n def delete_record(self, table_name, col_name, col_value):\n try:\n query = f\"DELETE FROM {table_name} WHERE {col_name}='{col_value}'\"\n self.conn.execute(query)\n self.conn.commit()\n return 'success'\n except Exception as e:\n print(str(e))\n print(\"Deletion Failed\")\n return 'error'\n def drop_table(self,table_name):\n query = f\"DROP TABLE {table_name}\"\n self.cursor.execute(query)\n print(\"Table dropped... \")\n\n # Commit your changes in the database\n self.conn.commit()\n def get_data(self, table_name, col_name, col_value):\n query = f\"SELECT * FROM {table_name} WHERE {col_name}='{col_value}'\"\n row = self.cursor.execute(query).fetchone()\n if (row == None):\n return []\n return list(row)\n\n def execute_query(self,query):\n self.cursor.execute(query)\n self.conn.commit()\n\n def write_data(self, data, table_name):\n if not self.table_exists(table_name):\n self.create_table(table_name, data.columns, data.dtypes)\n tuple_data = list(data.itertuples(index=False, name=None))\n insert_query = f'INSERT INTO {table_name} VALUES('\n for i in range(len(data.columns)):\n insert_query += '?,'\n insert_query = insert_query[:-1] + ')'\n self.cursor.executemany(insert_query, tuple_data)\n self.conn.commit()\n return True\n \n def update_dict_data(self,data:dict,condition,table_name):\n if not data:\n return\n if not table_name:\n raise ValueError('Database table name is not provided')\n updates = ''\n #TODO validation of keys\n for i,kv in enumerate(data.items()):\n if i:\n updates += ','\n updates += f'\"{kv[0]}\"=\"{kv[1]}\"'\n if condition == '':\n update_query = f'UPDATE {table_name} SET {updates}'\n else:\n update_query = f'UPDATE {table_name} SET {updates} WHERE {condition}'\n self.cursor.execute(update_query)\n self.conn.commit()\n \n def update_data(self,updates,condition,table_name):\n if condition == '':\n update_query = f'UPDATE {table_name} SET {updates}'\n else:\n update_query = f'UPDATE {table_name} SET {updates} WHERE {condition}'\n self.cursor.execute(update_query)\n self.conn.commit()\n\n def close(self):\n self.conn.close() '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport platform\nimport shutil\nimport subprocess\nimport sys\nimport time\nimport glob\nimport re\nfrom appbe.pages import get_usecase_page\nimport json\nfrom django.http import FileResponse\ndef startIncrementallearning(request,usecasedetails,Existusecases,DATA_FILE_PATH):\n try:\n modelid = request.POST.get('modelid')\n #incfilepath = request.POST.get('incfilepath')\n Datapath = request.FILES['incfilepath']\n filetimestamp = str(int(time.time()))\n dataFile = os.path.join(DATA_FILE_PATH,'AION_' + filetimestamp+'.csv')\n with open(dataFile, 'wb+') as destination:\n for chunk in Datapath.chunks():\n destination.write(chunk)\n # destination.close()#bugfix 11656\n incfilepath = dataFile\n p = Existusecases.objects.get(id=modelid)\n deployPath = str(p.DeployPath)\n scriptPath = os.path.abspath(os.path.join(deployPath,'aion_inclearning.py'))\n request.session['IsRetraining'] = 'No' \n if not os.path.exists(scriptPath):\n status,context,action = get_usecase_page(request,usecasedetails,Existusecases)\n context['Msg'] = 'Incremental/Online learning not supported for this model.For online training select Online Training in basic configuration page and provide with training'\n else:\n \n outputStr = subprocess.check_output([sys.executable, scriptPath, incfilepath]) \n outputStr = outputStr.decode('utf-8')\n outputStr = re.search(r'aion_learner_status:(.*)', str(outputStr), re.IGNORECASE).group(1)\n outputStr = outputStr.strip()\n decoded_data = json.loads(outputStr)\n status,context,action = get_usecase_page(request,usecasedetails,Existusecases) \n if decoded_data['status'] == 'SUCCESS':\n msg = decoded_data['Msg']\n context['Status'] = 'SUCCESS'\n context['Msg'] = msg\n else:\n msg = decoded_data['Msg']\n context['Status'] = 'SUCCESS'\n context['Msg'] = msg\n except Exception as e:\n print(e)\n try:\n status,context,action = get_usecase_page(request,usecasedetails,Existusecases)\n except Exception as msg:\n context['errorMsg'] = msg\n return action,context\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport sqlite3\nfrom pathlib import Path\nimport json\nimport os\nimport rsa\nimport boto3 #usnish\nimport pandas as pd\nimport time\nimport sqlite3\n\nclass sqlite_db():\n\n\tdef __init__(self, location, database_file=None):\n\t\tif not isinstance(location, Path):\n\t\t\tlocation = Path(location)\n\t\tif database_file:\n\t\t\tself.database_name = database_file\n\t\telse:\n\t\t\tself.database_name = location.stem\n\t\tdb_file = str(location/self.database_name)\n\t\tself.conn = sqlite3.connect(db_file)\n\t\tself.cursor = self.conn.cursor()\n\n\tdef table_exists(self, name):\n\t\tquery = f\"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}';\"\n\t\tlistOfTables = self.cursor.execute(query).fetchall()\n\t\treturn len(listOfTables) > 0\n\n\tdef read_data(self, table_name):\n\t\tquery = f\"SELECT * FROM {table_name}\"\n\t\trow = self.cursor.execute(query).fetchall()\n\t\treturn list(row)\n\t\t#return pd.read_sql_query(f\"SELECT * FROM {table_name}\", self.conn)\n\n\tdef create_table(self,name, columns, dtypes):\n\t\tquery = f'CREATE TABLE IF NOT EXISTS {name} ('\n\t\t\n\t\tfor column, data_type in zip(columns, dtypes):\n\t\t\tquery += f\"'{column}'\tTEXT,\"\n\t\tquery = query[:-1]\n\t\tquery += ');'\n\t\tself.conn.execute(query)\n\t\treturn True\n\tdef delete_record(self,table_name,col_name, col_value):\n\t\ttry:\n\t\t\tquery = f\"DELETE FROM {table_name} WHERE {col_name}='{col_value}'\"\n\t\t\tself.conn.execute(query)\n\t\t\tself.conn.commit()\n\t\t\treturn 'success'\n\t\texcept Exception as e :\n\t\t\tprint(str(e))\n\t\t\tprint(\"Deletion Failed\")\n\t\t\treturn 'error'\n\t\n\tdef get_data(self,table_name,col_name,col_value):\n\t\tquery = f\"SELECT * FROM {table_name} WHERE {col_name}='{col_value}'\"\n\t\trow = self.cursor.execute(query).fetchone()\n\t\tif(row == None):\n\t\t\treturn []\n\t\treturn list(row)\n\t\n\tdef write_data(self,data, table_name):\n\t\tif not self.table_exists(table_name):\n\t\t\tself.create_table(table_name, data.columns, data.dtypes)\n\t\ttuple_data = list(data.itertuples(index=False, name=None))\n\t\tinsert_query = f'INSERT INTO {table_name} VALUES('\n\t\tfor i in range(len(data.columns)):\n\t\t\tinsert_query += '?,'\n\t\tinsert_query = insert_query[:-1] + ')'\n\t\tself.cursor.executemany(insert_query, tuple_data)\n\t\tself.conn.commit()\n\t\treturn True\n\t\t\n\tdef close(self):\n\t\tself.conn.close()\n\ndef add_new_GCSBucket(request):\n\ttry:\n\t\tfrom appbe.dataPath import DATA_DIR\n\t\tfile_path = os.path.join(DATA_DIR,'sqlite')\n\t\tsqlite_obj = sqlite_db(file_path,'config.db')\n\t\t\n\t\tprint(request.POST[\"aionreferencename\"])\t\t\n\t\tprint(request.POST[\"serviceaccountkey\"])\n\t\tprint(request.POST[\"bucketname\"])\n\t\tif request.POST[\"aionreferencename\"] =='' or request.POST[\"serviceaccountkey\"] == '' or request.POST[\"bucketname\"] == '' :\n\t\t\t\n\t\t\treturn 'error'\n\t\tnewdata = {}\t \n\t\tnewdata['Name'] = [request.POST[\"aionreferencename\"]]\n\t\tnewdata['GCSServiceAccountKey'] = [request.POST[\"serviceaccountkey\"]]\n\t\tnewdata['GCSbucketname'] = [request.POST[\"bucketname\"]]\n\t\tname = request.POST[\"aionreferencename\"]\n\t\tif sqlite_obj.table_exists(\"gcsbucket\"): \n\t\t\tif(len(sqlite_obj.get_data(\"gcsbucket\",'Name',name))>0):\n\t\t\t\treturn 'error1' \n\t\tsqlite_obj.write_data(pd.DataFrame.from_dict(newdata),'gcsbucket')\n\texcept:\n\t\treturn 'error'\n\ndef get_gcs_bucket():\n\ttry:\n\t\tfrom appbe.dataPath import DATA_DIR\n\t\tfile_path = os.path.join(DATA_DIR,'sqlite')\n\t\tsqlite_obj = sqlite_db(file_path,'config.db')\n\t\ttemp_data = sqlite_obj.read_data('gcsbucket')\n\t\tdata = []\n\t\tfor x in temp_data:\n\t\t\tdata_dict = {}\n\t\t\tdata_dict['Name'] = x[0]\n\t\t\tdata_dict['GCSServiceAccountKey'] = x[1]\n\t\t\tdata_dict['GCSbucketname'] = x[2]\n\t\t\tdata.append(data_dict)\t\n\texcept Exception as e:\n\t\tprint(e)\n\t\tdata = []\n\treturn data\n\ndef read_gcs_", "instruction": "", "output": "" }, { "input": "bucket(name,filename,DATA_FILE_PATH):\n\ttry:\n\t\tfrom appbe.dataPath import DATA_DIR\n\t\tfile_path = os.path.join(DATA_DIR,'sqlite')\n\t\tsqlite_obj = sqlite_db(file_path,'config.db')\n\t\tdata = sqlite_obj.get_data(\"gcsbucket\",'Name',name)\n\texcept:\n\t\tdata = []\n\tfound = False\n\tif len(data)!=0:\n\t\tGCSServiceAccountKey = data[1]\n\t\tGCSbucketname = data[2]\n\t\tfound = True\t\t\n\t#print(found)\n\t#print(name)\n\ttry:\n\t\tif found:\n\t\t\timport io \n\t\t\tfrom google.cloud import storage\t\n\t\t\t\n\t\t\t#print(GCSServiceAccountKey)\n\t\t\t#print(GCSbucketname)\n\t\t\ttry:\n\t\t\t\tstorage_client = storage.Client.from_service_account_json(GCSServiceAccountKey)\n\t\t\t\tbucket = storage_client.get_bucket(GCSbucketname)\n\t\t\t\tblob = bucket.blob(filename)\t\t\n\t\t\t\tdata = blob.download_as_string()\n\t\t\t\tdf = pd.read_csv(io.BytesIO(data), encoding = 'utf-8', sep = ',',encoding_errors= 'replace')\n\t\t\texcept Exception as e:\n\t\t\t\treturn \"Error\",str(e), pd.DataFrame()\n\t\t\treturn 'Success',\"\",df\n\texcept Exception as e:\n\t\tprint(e)\n\t\treturn 'Error',\"Please check bucket configuration\",pd.DataFrame()\n\ndef remove_gcs_bucket(name):\n\tfrom appbe.dataPath import DATA_DIR\n\tfile_path = os.path.join(DATA_DIR,'sqlite')\n\tsqlite_obj = sqlite_db(file_path,'config.db')\n\treturn sqlite_obj.delete_record('gcsbucket','Name',name)\n\t\t\n\t '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport sqlite3\nfrom pathlib import Path\nimport json\nimport os\nimport rsa\nimport boto3 #usnish\nimport pandas as pd\nimport time\nclass sqlite_db():\n\n\tdef __init__(self, location, database_file=None):\n\t\tif not isinstance(location, Path):\n\t\t\tlocation = Path(location)\n\t\tif database_file:\n\t\t\tself.database_name = database_file\n\t\telse:\n\t\t\tself.database_name = location.stem\n\t\tdb_file = str(location/self.database_name)\n\t\tself.conn = sqlite3.connect(db_file)\n\t\tself.cursor = self.conn.cursor()\n\n\tdef table_exists(self, name):\n\t\tquery = f\"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}';\"\n\t\tlistOfTables = self.cursor.execute(query).fetchall()\n\t\treturn len(listOfTables) > 0\n\n\tdef read_data(self, table_name):\n\t\tquery = f\"SELECT * FROM {table_name}\"\n\t\trow = self.cursor.execute(query).fetchall()\n\t\treturn list(row)\n\t\t#return pd.read_sql_query(f\"SELECT * FROM {table_name}\", self.conn)\n\n\tdef create_table(self,name, columns, dtypes):\n\t\tquery = f'CREATE TABLE IF NOT EXISTS {name} ('\n\t\t\n\t\tfor column, data_type in zip(columns, dtypes):\n\t\t\tquery += f\"'{column}'\tTEXT,\"\n\t\tquery = query[:-1]\n\t\tquery += ');'\n\t\tself.conn.execute(query)\n\t\treturn True\n\tdef delete_record(self,table_name,col_name, col_value):\n\t\ttry:\n\t\t\tquery = f\"DELETE FROM {table_name} WHERE {col_name}='{col_value}'\"\n\t\t\tself.conn.execute(query)\n\t\t\tself.conn.commit()\n\t\t\treturn 'success'\n\t\texcept Exception as e :\n\t\t\tprint(str(e))\n\t\t\tprint(\"Deletion Failed\")\n\t\t\treturn 'error'\n\t\t\t\n\t\n\tdef get_data(self,table_name,col_name,col_value):\n\t\t\n\t\tquery = f\"SELECT * FROM {table_name} WHERE {col_name}='{col_value}'\"\n\t\trow = self.cursor.execute(query).fetchone()\n\t\tif(row == None):\n\t\t\treturn []\n\t\treturn list(row)\n\t\n\tdef write_data(self,data, table_name):\n\t\tif not self.table_exists(table_name):\n\t\t\tself.create_table(table_name, data.columns, data.dtypes)\n\t\ttuple_data = list(data.itertuples(index=False, name=None))\n\t\tinsert_query = f'INSERT INTO {table_name} VALUES('\n\t\tfor i in range(len(data.columns)):\n\t\t\tinsert_query += '?,'\n\t\tinsert_query = insert_query[:-1] + ')'\n\t\tself.cursor.executemany(insert_query, tuple_data)\n\t\tself.conn.commit()\n\t\treturn True\n\t\t\n\tdef close(self):\n\t\tself.conn.close()\n\ndef add_new_s3bucket(request):\n\n\ttry:\n\t\tfrom appbe.dataPath import DATA_DIR\n\t\tfile_path = os.path.join(DATA_DIR,'sqlite')\n\t\tsqlite_obj = sqlite_db(file_path,'config.db')\n\t\t\n\t\tif request.POST[\"aionreferencename\"] =='' or request.POST[\"s3bucketname\"] == '' or request.POST[\"awsaccesskey\"] == '' :\n\t\t\treturn 'error' \n\t\tpkeydata='''-----BEGIN RSA PUBLIC KEY-----\n\tMIIBCgKCAQEAxIHM1FphEMMwViUrG0b2Bqf8tOxbhUWlnmjgFt5A25qbY1AfnrMv\n\tfVx8+7iCcZ/3TY9Jv2I584SOc1tvsgESCke/t6+o/u2esPBsnDFzV62l3Zvw0m4e\n\twQeKlFC8EoOblyIXRbZdelSJinzlr9lOiKuid/xPvXHou6jxF1A2W7a89A2PM4Re\n\tn0W9YkjB7dRGW1sSrpruHdVJvgHhGZFZ7sCTue0jVOnc5sT3Tq5saLfEDqHyKxlq\n\ti/mcThmcTfisRIYFH5pyt/Ysr4VVP924QlcoqPOyg3RMCS3G0VjstSoVwNhxWrs/\n\tlujDuCnpxvWzNpq21OWmF66GXxwiq+6W0wIDAQAB\n\t-----END RSA PUBLIC KEY-----'''\n\n\t\tpubkey = rsa.PublicKey.load_pkcs1(pkeydata)\n\t\tawssecretaccesskey = rsa.encrypt(request.POST[\"awssecretaccesskey\"].encode(), pubkey)\n\t\tnewdata = {}\n\t\tnewdata['Name'] = [request.POST[\"aionreferencename\"]]\n\t\tnewdata['AWSAccessKeyID'] = [request.POST[\"awsaccesskey\"]]\n\t\tnewdata['AWSSecretAccessKey'] = [str(awssecretaccesskey)]\n\t\tnewdata['S3BucketName'] = [request.POST[\"s3bucketname\"]]\n\t\tname = request.POST[\"aionreferencename\"]\n\t\t\n\t\tif sqlite_obj.table_exists(\"s3bucket\"):\n\t\t\tif(len(sqlite_obj.get_data(\"s3bucket\",\"Name\",name)) > 0):\n\t\t\t\treturn 'error1'\n\t\tsqlite_obj.write_data(pd.DataFrame.from_dict(newdata),'s3bucket')\n\t\t\n\texcept Exception as e:\n\t\tprint(e)\n\t\treturn 'error'\n\ndef get_s3_bucket():\n\ttry:\n\t\tfrom appbe.dataPath import DATA_DIR\n\t\tfile_path = os.path.join(DATA_DIR,'sqlite')\n\t\tsqlite_obj = sqlite_db(file_path,'config.db')\n\t\ttemp_data = sqlite_obj.read_data('s3bucket')\n\t\t\n\t\tdata = []\n\t\tfor x in temp_data:\n\t\t\tdata_dict = {}\n\t\t\tdata_dict['Name'] = x[0]\n\t\t\tdata_dict['AWSAccessKeyID'] = x[1]\n\t\t\tdata_dict['AWSSecretAccessKey'] = x[2]\n\t\t\tdata_dict['S3BucketName'] = x[3]\n\t\t\tdata.append(data_dict)\n\texcept Exception as e:\n\t\tprint(e)\n\t\tdata = []\n\treturn data\ndef remove_s3_bucket(name):\n\tfrom appbe.dataPath import DATA_DIR\n\tfile_path = os.path.join(DATA_DIR,'sqlite')\n\tsqlite_obj = sqlite_db(file_path,'config.db')\n\treturn sqlite_obj.delete_record('s3bucket','Name',name)\n\t\n\ndef read_s3_bucket(name,filename,DATA_FILE_PATH):\n\tprivkey = '''-----BEGIN RSA PRIVATE KEY-----\nMIIEqQIBAAKCAQEAxIHM1FphEMMwViUrG0b2Bqf8tOxbhUWlnmjgFt5A25qbY1Af\nnrMvfVx8+7iCcZ/3TY9Jv2I584SOc1tvsgESCke/t6+o/u2esPBsnDFzV62l3Zvw\n0m4ewQeKlFC8EoOblyIXRbZdelSJinzlr9lOiKuid/xPvXHou6jxF1A2W7a89A2P\nM4Ren0W9YkjB7dRGW1sSrpruHdVJvgHhGZFZ7sCTue0jVOnc5sT3Tq5saLfEDqHy\nKxlqi/mcThmcTfisRIYFH5pyt/Ysr4VVP924QlcoqPOyg3RMCS3G0VjstSoVwNhx\nWrs/lujDuCnpxvWzNpq21OWmF66GXxwiq+6W0wIDAQABAoIBAC/VbNfQPEqJSO3f\nVFPqfR73q2MbGdgiMQOTgeDvLxiF1QdizJ+j/I5mgiIAMviXuOpPU+NbdMHbZZWd\nD15kNlD8UCXVg6yyiOuHStjmjK4uHe8I86E1nxTb0hbyZCWZlbk/WizlDHInu+dT\nKdIZcq2AIidU6tAxtwA0ingHaRSoXDlSGwOTEigNqmWOKnDTVg0SMscoHOD7siXF\nDHm1/lkvD3uvcZk6c7fGxC8SgNX2dj6n/Nbuy0Em+bJ0Ya5wq4HFdLJn3EHZYORF\nODUDYoGaSxeXqYsGg/KHJBc8J7xW9FdN9fGbHfw1YplrmiGL3daATtArjMmAh0EQ\nH8Sj7+ECgYkA3oWMCHi+4t8txRPkg1Fwt8dcqYhGtqpAus3NESVurAdi0ZPqEJcQ\n4cUbflwQPhX0TOaBlkgzdP8DMdcW/4RalxHsAh5N8ezx/97PQMb3Bht0WsQUBeYJ\nxLV7T2astjTRWactGCG7dwTaUYRtU3FqL6//3CysmA12B5EMX0udNBOTKwmaYKww\nAwJ5AOISS7f12Q0fgTEVY0H8Zu5hHXNOA7DN92BUzf99iPx+H+codLet4Ut4Eh0C\ncFmjA3TC78oirp5mOOQmYxwaFaxlZ7Rs60dlPFrhz0rsHYPK1yUOWRr3RcXWSR13\nr+kn+f+8k7nItfGi7shdcQW+adm/EqPfwTHM8QKBiQCIPEMrvKFBzVn8Wt2A+I+G\nNOyqbuC8XSgcNnvij4RelncN0P1xAsw3LbJTfpIDMPXNTyLvm2zFqIuQLBvMfH/q\nFfLkqSEXiPXwrb0975K1joGCQKHxqpE4edPxHO+I7nVt6khVifF4QORZHDbC66ET\naTHA3ykcPsGQiGGGxoiMpZ9orgxyO3l5Anh92jmU26RNjfBZ5tIu9dhHdID0o8Wi\nM8c3NX7IcJZGGeCgywDPEFmPrfRHeggZnopaAfuDx/L182pQeJ5MEqlmI72rz8bb\nJByJa5P+3ZtAtzc2RdqNDIMnM7fYU7z2S279U3nZv0aqkk3j9UDqNaqvsZMq73GZ\ny8ECgYgoeJDi+YyVtqgzXyDTLv6MNWKna9LQZlbkRLcpg6ELRnb5F/dL/eB/D0Sx\nQpUFi8ZqBWL+A/TvgrCrTSIrfk71CKv6h1CGAS02dXorYro86KBLbJ0yp1T/WJUj\nrHrGHczglvoB+5stY/EpquNpyca03GcutgIi9P2IsTIuFdnUgjc7t96WEQwL\n-----END RSA PRIVATE KEY-----'''\n\ttry:\n\t\tfrom appbe.dataPath import DATA_DIR\n\t\tfile_path = os.path.join(DATA_DIR,'sqlite') \n\t\tsqlite_obj = sqlite_db(file_path,'config.db')\n\t\tdata = sqlite_obj.get_data(\"s3bucket\",'Name',name)\n\texcept:\n\t\tdata = []\n\tawssecretaccesskey = ''\n\tfound = False\n\t\n\tif len(data)!=0:\n\t\taws_access_key_id = data[1]\n\t\tawssecretaccesskey = data[2]\n\t\tbucketName = data[3]\n\t\tfound = True\n\t\t\t\n\tif found:\n\t\tprivkey = rsa.PrivateKey.load_pkcs1(privkey,'PEM')\n\t\tawssecretaccesskey = eval(awssecretaccesskey)\n\t\tawssecretaccesskey = rsa.decrypt(aws", "instruction": "", "output": "" }, { "input": "secretaccesskey, privkey)\n\t\tawssecretaccesskey = awssecretaccesskey.decode('utf-8')\n\t\t#awssecretaccesskey = 'SGcyJavYEQPwTbOg1ikqThT+Op/ZNsk7UkRCpt9g'#rsa.decrypt(awssecretaccesskey, privkey)\n\t\tclient_s3 = boto3.client('s3', aws_access_key_id=aws_access_key_id, aws_secret_access_key=str(awssecretaccesskey))\n\t\t#print(bucketName,filename)\n\t\ttry:\t\t\n\t\t\tresponse = client_s3.get_object(Bucket=bucketName, Key=filename)\n\t\t\tdf = pd.read_csv(response['Body'])\n\t\texcept Exception as e:\n\t\t\tprint(str(e))#usnish\n\t\t\treturn 'Error',str(e), pd.DataFrame()\n\t\t\t\n\t\t\t#return 'Error', pd.DataFrame()\n\t\treturn 'Success','',df\n\treturn 'Error',\"Please check bucket configuration\", pd.DataFrame() '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\n\nimport plotly.figure_factory as ff\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\nfrom wordcloud import WordCloud, STOPWORDS\nimport pandas as pd\nimport numpy as np\nfrom appbe import distribution\nimport io\nimport urllib\nimport os\nimport sys\nimport base64\nfrom appbe import help_Text as ht\nimport math\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom natsort import natsorted\nfrom sklearn.cluster import KMeans\nimport json\nfrom facets_overview.generic_feature_statistics_generator import GenericFeatureStatisticsGenerator\n\nfrom appbe.aion_config import eda_setting\nfrom dython.nominal import associations\ndef calculateNumberofCluster(featureData):\n Sum_of_squared_distances = []\n K = range(1, 15)\n for k in K:\n km = KMeans(n_clusters=k)\n km = km.fit(featureData)\n Sum_of_squared_distances.append(km.inertia_)\n x1, y1 = 1, Sum_of_squared_distances[0]\n x2, y2 = 15, Sum_of_squared_distances[len(Sum_of_squared_distances) - 1]\n distances = []\n for inertia in range(len(Sum_of_squared_distances)):\n x0 = inertia + 2\n y0 = Sum_of_squared_distances[inertia]\n numerator = abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1)\n denominator = math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)\n distances.append(numerator / denominator)\n n_clusters = distances.index(max(distances)) + 2\n #print(n_clusters)\n return (n_clusters)\n\ndef get_eda(request):\n hopkins_val = ''\n hopkins_tip = ''\n if request.session['datatype'] == 'Normal': \n from appbe.eda import ux_eda\n \n # EDA Subsampling changes\n # ---------------------------- \n edasampleSize = request.POST.get('SubsampleSize')\n edasampleSize = str(int(edasampleSize)/100)\n \n sampleFile = str(request.session['datalocation'])\n repText = sampleFile[sampleFile.find('sub_'):sampleFile.find('_sampled_') + 9]\n if len(repText) == 30:\n dataLocation = sampleFile.replace(repText,\"\")\n else:\n dataLocation = sampleFile\n \n eda_obj = ux_eda(dataLocation,request.session['delimiter'],request.session['textqualifier'])\n \n df0 = eda_obj.getdata()\n \n if os.path.isfile(dataLocation):\n if(len(edasampleSize) > 0): \n df0 = df0.sample(frac = float(edasampleSize)) \n \n #EDA Performance change\n # ----------------------------\n dflength = len(df0) \n # sample_size = int(eda_setting())\n # if dflength >= sample_size:\n # eda_obj.subsampleData(sample_size)\n # else:\n eda_obj.subsampleData(dflength)\n # ----------------------------\n \n TrainSampleSelected = request.POST.get('TrainSampleSize')\n if(TrainSampleSelected == 'EDASize'):\n from pathlib import Path\n filePath = Path(dataLocation)\n \n import datetime\n timestamp = datetime.datetime.now().replace(microsecond=0).isoformat()\n timestamp = str(timestamp.replace(\":\",\"\"))\n \n sub_sampledFile = filePath.parent/(\"sub_\" + timestamp + \"_sampled_\"+filePath.name)\n # sub_sampledFile = filePath.parent/(usename + \"_sub_sampled_\"+filePath.name)\n \n df0.to_csv(sub_sampledFile,index=False,)\n request.session['datalocation'] = str(sub_sampledFile)\n records = df0.shape[0]\n request.session['NoOfRecords'] = records\n \n edaFeatures = request.POST.getlist('InputFeatures')\n request.session['edaFeatures'] = edaFeatures\n\n if(len(edaFeatures) > 0):\n eda_obj.subsetFeatures(edaFeatures)\n # ---------------------------- \n \n features,dateFeature,seqFeature,constantFeature,textFeature,targetFeature,numericCatFeatures,numericFeature,catfeatures = eda_obj.getFeatures()\n \n request.session['edanumericCatFeatures'] = numericCatFeatures\n request.session['edatextFeature'] = textFeature\n \n categoricalfeatures = catfeatures\n numericfeaturecount = eda_obj.getNumericFeatureCount()\n cluster_details = []\n dataCharts = []\n # correlated_features=[]\n pca_details = []\n \n if numericfeaturecount > 1:\n try:\n\n cluster_details,hopkins_val = eda_obj.getClusterDetails()\n if hopkins_val!='':\n if float(hopkins_val) <0.3:\n hopkins_tip = ht.hopkins_tip[0]\n elif float(hopkins_val)>0.7:\n hopkins_tip = ht.hopkins_tip[2]\n else:\n hopkins_tip = ht.hopkins_tip[1]\n else:\n hopkins_tip = ''\n except Exception as e:\n print(\"========================\"+str(e))\n pass\n \n try:\n pca_map = eda_obj.getPCATop10Features()\n pca_details = pca_map\n yaxis_data = pca_map.tolist()\n xaxis_data = pca_map.index.values.tolist()\n import plotly.graph_objects as go\n cfig = go.Figure()\n cfig.add_trace(go.Bar(x=xaxis_data, y=yaxis_data, name='Feature Importance'))\n cfig.update_layout(barmode='stack', xaxis_title='Features',yaxis_title='Explained Variance Ratio')\n bargraph = cfig.to_html(full_html=False, default_height=450, default_width=1000)\n dataCharts.append(bargraph)\n except:\n pass\n df = eda_obj.getdata()\n\n # try:\n # top5highcorr = eda_obj.getHighlyCorrelatedFeatures(5)\n # correlated_features = getHighlyCorrelatedFeatureCharts(df,top5highcorr) \n # except:\n # pass\n \n else:\n df = eda_obj.getdata()\n \n # # EDA Subsampling changes\n # # ----------------------------\n # if os.path.isfile(dataLocation):\n # if dflength < 10000:\n # if(len(edasampleSize) > 0):\n # df = df.sample(frac = float(edasampleSize))\n # ----------------------------\n \n if len(textFeature) > 0:\n commonfeatures = eda_obj.getTopTextFeatures(10)\n # comment_words = eda_obj.word_token()\n del eda_obj\n \n wordcloudpic = ''\n showtextFeature = False\n if len(textFeature) > 0:\n showtextFeature = True\n # try: \n # stopwords = set(STOPWORDS)\n # wordcloud = WordCloud(width=800, height=800, background_color='white', stopwords=stopwords,\n # min_font_size=10).generate(comment_words)\n # try:\n # plt.clf()\n # except:\n # pass\n # plt.imshow(wordcloud, interpolation='bilinear')\n # plt.axis(\"off\")\n # plt.tight_layout(pad=0)\n # image = io.BytesIO()\n # plt.savefig(image, format='png')\n # image.seek(0)\n # string = base64.b64encode(image.read())\n # wordcloudpic = 'data:image/png;base64,' + urllib.parse.quote(string) \n # except:\n # pass \n \n xaxis_data = commonfeatures['most_common_words'].tolist()\n yaxis_data = commonfeatures['freq'].tolist()\n import plotly.graph_objects as go\n cfig = go.Figure()\n cfig.add_trace(go.Bar(x=xaxis_data, y=yaxis_data, name='Feature Importance'))\n cfig.update_layout(barmode='stack', xaxis_title='Features',yaxis_title='Count')\n bargraph = cfig.to_html(full_html=False, default_height=450, default_width=1000)\n dataCharts.append(bargraph)\n \n df_top = df.head(10) \n df_json = df_top.to_json(orient=\"records\")\n \n df_json = json.loads(df_json) \n # if len(df) > 10000:\n # df1 = df.sample(n=10000, random_state=1)\n # else:\n # df1 = df\n df1 = df \n \n data_deep_json = df_top.to_json(orient='records') #df1.to_json(orient='records')\n \n try:\n gfsg = GenericFeatureStatisticsGenerator()\n proto = gfsg.ProtoFromDataFrames([{'name': 'train', 'table': df1}]) \n protostr = base64.b64encode(proto.SerializeToString()).decode(\"utf-8\") \n except Exception as e:\n protostr=''\n print('protostr '+str(e))\n try: \n correlationgraph = getCorrelationMatrix(df) \n except Exception as e:\n print(e)\n try:\n dataDrift = 'onRequest' #getDriftDistribution(numericCatFeatures, df[numericCatFeatures])\n \n except Exception as e:\n dataDrift = '' \n print(e) \n \n selected_use_case = request.session['UseCaseName']\n ModelVersion = request.session['ModelVersion']\n ModelStatus = request.session['ModelStatus']\n statusmsg = 'Successfully Done'\n \n DF_list = list()\n \n des1 = df.describe(include='all').T\n des1['missing count %'] = df.isnull().mean() * 100\n des1['zero count %'] = df.isin([0]).mean() * 100\n data = list(df.columns.values)\n des1.insert(0, 'Features', data)\n \n des1 = des1.to_json(orient=\"records\")\n pca_df=pd.DataFrame()\n #print(pca_details) \n \n # if pca_details.empty:\n if len(pca_details) > 0:\n pca_df = pd.DataFrame({'Feature':pca_details.index, 'Explained Variance Ratio':pca_details.values}).round(4)\n\n pca_df = pca_df.to_json(orient=\"records\")\n if len(df.columns) > 25:\n df3 = df[df.columns[0:24]]\n else:\n df3 = df.copy()\n #cor_mat = abs(df3.corr())\n #cor_mat = cor_mat.round(2)\n try:\n if len(df3.columns) > 25:\n df3 = df3[df3.columns[0:24]]\n cor_mat= associations(df3,compute_only=True)\n cor_mat=cor_mat['corr'] \n #cor_mat = df3.corr()\n cor_mat = cor_mat.astype(float).round(2)\n except Exception as e:\n print(\"creating correlation mat issue: \\\\n\",e)\n pass\n\n data = list(cor_mat.index)\n cor_mat.insert(0, 'Features', data)\n cor_mat = cor_mat.to_json(orient=\"records\") \n cluster_df = pd.DataFrame.from_dict(cluster_details) \n cluster_df = cluster_df.to_json(orient=\"records\")\n #textFeature = json.dumps(textFeature)\n # 2.2 patch changes\n #-------------------------------------------------\n request.session['edaRecords'] = df.shape[0]\n print(textFeature)\n context = {'data_deep_json': data_deep_json, 'sampleFile':sampleFile,'protostr': protostr, 'data': df_json, 'oneda': True, \n 'dataCharts': dataCharts,'dataDrift': dataDrift, 'drift_tip': ht.drift_tip,'des1':des1,'cluster_df':cluster_df,'hopkins_val':hopkins_val,\n 'pca_df':pca_df,'cor_mat':cor_mat,'correlationgraph': correlationgraph, 'centroids':cluster_details, 'wordcloudpic': wordcloudpic, 'showtextFeature': showtextFeature, 'textFeature': textFeature,\n # 'featurepairgraph': correlated_features,\n '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,\n 'correlation_analysis_tip': ht.correlation_analysis_tip,\n '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,\n 'pair", "instruction": "", "output": "" }, { "input": "_graph_tip':ht.pair_graph_tip, 'fair_metrics_tip':ht.fair_metrics_tip, 'categoricalfeatures':categoricalfeatures, 'numericCatFeatures':numericCatFeatures,\n 'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion,'selected': 'modeltraning',\n 'currentstate': request.session['currentstate'], 'finalstate': request.session['finalstate'],'exploratory':True,'NumericFeatureList':numericFeature,'dateFeature':dateFeature,'targetFeature':targetFeature}\n return(context)\n\n\n\n\n\n# EDA Visualization changes\n# ----------------------------\ndef get_edaGraph(request):\n if request.session['datatype'] == 'Normal':\n from appbe.eda import ux_eda\n \n df_temp = dict(request.GET).get('features[]')\n graphType = request.GET.get('graphType') \n d3_url = request.GET.get('d3_url')\n mpld3_url = request.GET.get('mpld3_url')\n \n dataLocation = request.session['datalocation']\n eda_obj = ux_eda(dataLocation) \n \n \n # 2.2 patch changes\n #-------------------------------------------------\n edaRecords = request.session['edaRecords']\n #df = df.sample(n=int(edaRecords), random_state=1)\n eda_obj.subsampleData(edaRecords)\n \n \n eda_obj.subsetFeatures(df_temp) \n features,dateFeature,seqFeature,constantFeature,textFeature,targetFeature,numericCatFeatures,numericFeature, catfeatures = eda_obj.getFeatures() \n numericfeaturecount = eda_obj.getNumericFeatureCount() \n correlated_features=[] \n \n df = eda_obj.getdata()\n if numericfeaturecount > 1:\n try:\n if graphType == 'Default':\n top5highcorr = eda_obj.getHighlyCorrelatedFeatures(5)\n correlated_features = getHighlyCorrelatedFeatureCharts(df,top5highcorr)\n \n else:\n correlated_features = getFeatureCharts(df,graphType,d3_url,mpld3_url)\n except:\n pass\n \n return correlated_features\n# ----------------------------\n\n\n# ---------------------- 12686:Data Distribution related Changes S T A R T ----------------------\ndef get_DataDistribution(request):\n selectedFeature = request.GET.get('selected_feature')\n \n _featureItem = []\n _featureItem.append(selectedFeature)\n \n from appbe.eda import ux_eda\n dataLocation = request.session['datalocation']\n eda_obj = ux_eda(dataLocation)\n df = eda_obj.getdata()\n \n numericCatFeatures = request.session['edanumericCatFeatures']\n textFeature = request.session['edatextFeature']\n # features,dateFeature,seqFeature,constantFeature,textFeature,targetFeature,numericCatFeatures,numericFeature,catfeatures = eda_obj.getFeatures()\n dataDrift = ''\n \n if selectedFeature in numericCatFeatures:\n dataDrift = getDriftDistribution(_featureItem, df[numericCatFeatures])\n \n elif selectedFeature in textFeature:\n try:\n comment_words = eda_obj.word_token_for_feature(selectedFeature, df[_featureItem])\n stopwords = set(STOPWORDS)\n wordcloud = WordCloud(width=800, height=800, background_color='white', stopwords=stopwords,\n min_font_size=10).generate(comment_words)\n try:\n plt.clf()\n except:\n pass\n plt.imshow(wordcloud, interpolation='bilinear')\n plt.axis(\"off\")\n plt.tight_layout(pad=0)\n image = io.BytesIO()\n plt.savefig(image, format='png')\n image.seek(0)\n string = base64.b64encode(image.read())\n # wordcloudpic = 'data:image/png;base64,' + urllib.parse.quote(string)\n dataDrift = urllib.parse.quote(string)\n \n except:\n dataDrift = ''\n \n del eda_obj \n return dataDrift\n# -------------------------------------------- E N D --------------------------------------------\n \n\ndef get_DeepDiveData(request):\n if request.session['datatype'] == 'Normal':\n from appbe.eda import ux_eda\n dataLocation = request.session['datalocation']\n eda_obj = ux_eda(dataLocation)\n \n edaRecords = request.session['edaRecords']\n edaFeatures = request.session['edaFeatures']\n \n eda_obj.subsampleData(edaRecords)\n eda_obj.subsetFeatures(edaFeatures) \n \n df = eda_obj.getdata()\n data_deep_json = df.to_json(orient='records')\n \n return (data_deep_json) \n\n\n\n# Fairness Metrics changes\n# ----------------------------\ndef get_fairmetrics(request):\n import mpld3 \n if request.session['datatype'] == 'Normal':\n from appbe.eda import ux_eda \n \n df_temp = dict(request.GET).get('features[]')\n \n d3_url = request.GET.get('d3_url')\n mpld3_url = request.GET.get('mpld3_url')\n global metricvalue\n metricvalue = request.GET.get('metricvalue')\n \n dataLocation = request.session['datalocation']\n # dataLocation = 'C:\\\\\\\\MyFolder\\\\\\\\AION\\\\\\\\AION Datasets\\\\\\\\AIF360\\\\\\\\database.csv'\n \n eda_obj = ux_eda(dataLocation, optimize=1) \n features,dateFeature,seqFeature,constantFeature,textFeature,targetFeature,numericCatFeatures,numericFeature,catfeatures = eda_obj.getFeatures()\n \n # data = eda_obj.getdata()\n data = pd.read_csv(dataLocation, na_values=['Unknown', ' ']) \n features_toEncode = features\n \n from sklearn.preprocessing import MinMaxScaler, LabelEncoder\n data_encoded = data.copy()\n categorical_names = {}\n encoders = {}\n \n # Use Label Encoder for categorical columns (including target column)\n for feature in features_toEncode:\n le = LabelEncoder()\n le.fit(data_encoded[feature]) \n data_encoded[feature] = le.transform(data_encoded[feature]) \n categorical_names[feature] = le.classes_\n encoders[feature] = le\n \n data_perp = data_encoded\n \n protected_feature = df_temp[0] #'Victim Race' \n target_feature = df_temp[1] #'Perpetrator Sex'\n\n # ------Theil index----- Task->13843\n from aif360.sklearn.metrics import generalized_entropy_index\n Ti_List = []\n for items in categorical_names[protected_feature]:\n df = data[data[protected_feature]==items]\n le = LabelEncoder()\n le.fit(df[target_feature]) \n df[target_feature] = le.transform(df[target_feature])\n tf = generalized_entropy_index(df[target_feature], alpha = 1)\n tf = round(tf, 4)\n Ti_List.append(tf) \n global Thi_idx\n Thi_idx = Ti_List\n \n #claas_size = categorical_names[protected_feature].size\n new_list = [item for item in categorical_names[protected_feature] if not(pd.isnull(item)) == True]\n claas_size = len(new_list)\n \n if claas_size > 10:\n return 'HeavyFeature'\n \n metrics = fair_metrics(categorical_names, data_perp, protected_feature, target_feature, claas_size) \n figure = plot_fair_metrics(metrics) \n html_graph = mpld3.fig_to_html(figure,d3_url=d3_url,mpld3_url=mpld3_url) \n \n return html_graph\n\n\ndef fair_metrics(categorical_names, data_perp, protected_feature, target_feature, claas_size):\n import aif360\n from aif360.datasets import StandardDataset\n from aif360.metrics import BinaryLabelDatasetMetric\n cols = [metricvalue]\n obj_fairness = [[0]] \n fair_metrics = pd.DataFrame(data=obj_fairness, index=['objective'], columns=cols)\n \n for indx in range(claas_size):\n priv_group = categorical_names[protected_feature][indx]\n privileged_class = np.where(categorical_names[protected_feature] == priv_group)[0]\n\n data_orig = StandardDataset(data_perp, \n label_name=target_feature, \n favorable_classes=[1], \n protected_attribute_names=[protected_feature], \n privileged_classes=[privileged_class])\n\n dataset_pred = data_orig\n attr = dataset_pred.protected_attribute_names[0]\n idx = dataset_pred.protected_attribute_names.index(attr)\n privileged_groups = [{attr:dataset_pred.privileged_protected_attributes[idx][0]}] \n\n unprivileged_size = dataset_pred.unprivileged_protected_attributes[0].size\n unprivileged_groups = []\n for idx2 in range(unprivileged_size): \n unprivileged_groups.extend([{attr:dataset_pred.unprivileged_protected_attributes[idx][idx2]}])\n\n metric_pred = BinaryLabelDatasetMetric(dataset_pred,\n unprivileged_groups=unprivileged_groups,\n privileged_groups=privileged_groups)\n if metricvalue == \"Theil Index\":\n row = pd.DataFrame([Thi_idx[indx]],\n columns = cols ,\n index = [priv_group])\n elif metricvalue == \"Disparate Impact\":\n row = pd.DataFrame([[metric_pred.disparate_impact()]],\n columns = cols ,\n index = [priv_group])\n elif metricvalue == \"Statistical Parity Difference\":\n row = pd.DataFrame([[metric_pred.mean_difference()]],\n columns = cols ,\n index = [priv_group]) \n #fair_metrics = fair_metrics.append(row)\n fair_metrics = pd.concat([fair_metrics,row])\n\n return fair_metrics\n \n \n\ndef plot_fair_metrics(fair_metrics):\n import matplotlib.patches as patches\n plt.style.use('default')\n \n import seaborn as sns \n fig, ax = plt.subplots(figsize=(10,4), ncols=1, nrows=1)\n\n plt.subplots_adjust(\n left = 0.125, \n bottom = 0.1, \n right = 0.9, \n top = 0.9, \n wspace = .5, \n hspace = 1.1\n )\n\n y_title_margin = 1.2\n\n plt.suptitle(\"Fairness metrics\", y = 1.09, fontsize=20)\n sns.set(style=\"dark\")\n\n cols = fair_metrics.columns.values\n obj = fair_metrics.loc['objective']\n if metricvalue == \"Theil Index\":\n size_rect = [0.5]\n rect = [-0.1]\n bottom = [-0.1]\n top = [2]\n bound = [[-0.1,0.1]]\n elif metricvalue == \"Disparate Impact\":\n size_rect = [0.4]\n rect = [0.8]\n bottom = [0]\n top = [2]\n bound = [[-0.1,0.1]]\n elif metricvalue == \"Statistical Parity Difference\":\n size_rect = [0.2]\n rect = [-0.1]\n bottom = [-1]\n top = [1]\n bound = [[-0.1,0.1]]\n \n #display(Markdown(\"### Check bias metrics :\"))\n #display(Markdown(\"A model can be considered bias if just one of these five metrics show that this model is biased.\"))\n \n for attr in fair_metrics.index[0:len(fair_metrics)].values:\n #display(Markdown(\"#### For the %s attribute :\"%attr))\n check = [bound[i][0] < fair_metrics.loc[attr][i] < bound[i][1] for i in range(0,1)] \n #display(Markdown(\"With default thresholds, bias against unprivileged group detected in **%d** out of 5 metrics\"%(5 - sum(check)))) \n for i in range(0,1):\n plt.subplot(1, 1, i+1) \n xx = fair_metrics.index[1:len(fair_metrics)].values.tolist()\n yy = fair_metrics.iloc[1:len(fair_metrics)][cols[i]].values.tolist()\n \n palette = sns.color_palette('husl', len(xx)) \n ax = sns.pointplot(x=fair_metrics.index[1:len(fair_metrics)], y=yy, palette=palette, hue=xx)\n \n index = 0\n for p in zip(ax.get_xticks(), yy):\n if (p[1] > 2.0):\n _color = palette.as_hex()[index] \n _val = 'Outlier(' + str(round(p[1],3)) + ')'\n ax.text(p[0]-0.5, 0.02, _val, color=_color)\n else:\n ax.text(p[0], p[1]+0.05, round(p[1],3), color='k') \n index = index + 1\n \n plt.ylim(bottom[i], top[i])\n plt.setp(ax.patches, linewidth=0) \n ax.get_xaxis().set_visible(False)\n \n ax.legend(loc='right', bbox_to_anchor=(1, 0.8), ncol=1) \n ax.add_patch(patches.Rectangle((-5,rect[i]), 10, size_rect[i], alpha=0.3, facecolor=\"green\", linewidth=1, linestyle='solid'))\n # plt.axhline(obj[i], color='black', alpha=0.3) \n \n plt.title(cols[i], fontname=\"Times New Roman\", size=20,fontweight=\"bold\")\n ax.set_ylabel('') \n ax.set_xlabel('') \n \n return fig\n# ----------------------------\n\n\ndef getDriftDistribution(feature, dataframe, newdataframe=pd.DataFrame()):\n try:\n import numpy as np\n import pandas as pd\n import seaborn as sns\n import matplotlib.pyplot as plt\n import scipy\n from scipy import stats\n from scipy.stats import norm\n import matplotlib.gridspec as gridspec\n import math\n import io, base64, urllib\n np.seterr(divide='ignore', invalid='ignore')\n from appbe.eda import ux_eda\n ", "instruction": "", "output": "" }, { "input": "eda_obj = ux_eda()\n try: \n plt.clf()\n except:\n pass\n plt.rcParams.update({'figure.max_open_warning': 0})\n sns.set(color_codes=True)\n pandasNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n if len(feature) > 4:\n numneroffeatures = len(feature)\n plt.figure(figsize=(10, numneroffeatures*2))\n else:\n plt.figure(figsize=(10,5))\n \n for i in enumerate(feature):\n \n dataType = dataframe[i[1]].dtypes\n if dataType not in pandasNumericDtypes:\n dataframe[i[1]] = pd.Categorical(dataframe[i[1]])\n dataframe[i[1]] = dataframe[i[1]].cat.codes\n dataframe[i[1]] = dataframe[i[1]].astype(int)\n dataframe[i[1]] = dataframe[i[1]].fillna(dataframe[i[1]].mode()[0])\n else:\n dataframe[i[1]] = dataframe[i[1]].fillna(dataframe[i[1]].mean())\n \n plt.subplots_adjust(hspace=0.5, wspace=0.7, top=1)\n plt.subplot(math.ceil((len(feature) / 2)), 2, i[0] + 1)\n \n distname, sse = eda_obj.DistributionFinder(dataframe[i[1]])\n try:\n ax = sns.distplot(dataframe[i[1]], label=distname)\n \n ax.legend(loc='best')\n if newdataframe.empty == False:\n dataType = newdataframe[i[1]].dtypes\n if dataType not in pandasNumericDtypes:\n newdataframe[i[1]] = pd.Categorical(newdataframe[i[1]])\n newdataframe[i[1]] = newdataframe[i[1]].cat.codes\n newdataframe[i[1]] = newdataframe[i[1]].astype(int)\n newdataframe[i[1]] = newdataframe[i[1]].fillna(newdataframe[i[1]].mode()[0])\n else:\n newdataframe[i[1]] = newdataframe[i[1]].fillna(newdataframe[i[1]].mean())\n distname, sse = distribution.DistributionFinder(newdataframe[i[1]])\n ax = sns.distplot(newdataframe[i[1]], label=distname)\n ax.legend(loc='best')\n except Exception as e:\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type) + ' ' + str(fname) + ' ' + str(exc_tb.tb_lineno))\n pass\n buf = io.BytesIO()\n plt.savefig(buf, format='png')\n buf.seek(0)\n string = base64.b64encode(buf.read())\n uri = urllib.parse.quote(string)\n return uri\n except Exception as e:\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n \ndef getCategoryWordCloud(df):\n labels = df.Label.unique()\n df_output = pd.DataFrame()\n tcolumns=['text'] \n for label in labels:\n df2 = df[df['Label'] == label] \n df2 = df2.reset_index()\n \n wordcloud,df_text = getWordCloud(df2,tcolumns)\n newrow = {'Label':label,'wordCloud':wordcloud} \n df_output = df_output.append(newrow,ignore_index=True)\n return(df_output) \ndef getHighlyCorrelatedFeatureCharts(df, df_top):\n numOfRows = df.shape[0]\n cratio = 0.01\n if (numOfRows < 1000):\n cratio = 0.2\n elif (numOfRows < 10000):\n cratio = 0.1\n elif (numOfRows < 100000):\n cratio = 0.01\n barcolor = [\"red\", \"green\", \"blue\", \"goldenrod\", \"magenta\"]\n ffig = make_subplots(rows=2, cols=3)\n height = 800\n rowno = 1\n colno = 1\n featureCharts = []\n try:\n for index, row in df_top.iterrows():\n feature1 = row['FEATURE_1']\n feature2 = row['FEATURE_2']\n df_temp = df[[feature1, feature2]]\n feature1data = df_temp[feature1]\n feature2data = df_temp[feature2]\n nUnique = len(feature1data.unique().tolist())\n if nUnique / numOfRows >= cratio:\n feature1type = 'Continous'\n else:\n feature1type = 'Category'\n nUnique = len(feature2data.unique().tolist())\n if nUnique / numOfRows >= cratio:\n feature2type = 'Continous'\n else:\n feature2type = 'Category'\n\n charttype = 0\n if feature1type == 'Continous' and feature2type == 'Continous':\n df_temp[feature1] = pd.qcut(df_temp[feature1], q=8, duplicates='drop',precision=0)\n df_temp[feature1] = df_temp[feature1].astype(str).str.strip('()[]')\n feature1type = 'Category'\n xaxis = feature1\n yaxis = feature2\n charttype = 1\n if feature1type == 'Category' and feature2type == 'Continous':\n xaxis = feature1\n yaxis = feature2\n charttype = 1\n\n \n if feature1type == 'Continous' and feature2type == 'Category':\n xaxis = feature1 #xaxis = feature2\n yaxis = feature2 #yaxis = feature1\n charttype = 1\n\n if feature1type == 'Category' and feature2type == 'Category':\n if (len(feature1data.unique().tolist()) < len(feature2data.unique().tolist())):\n xaxis = feature1 #xaxis = feature2\n yaxis = feature2 #yaxis = feature1\n else:\n xaxis = feature1\n yaxis = feature2\n\n if (len(df_temp[xaxis].unique().tolist()) > 5):\n df_temp[xaxis] = pd.qcut(df_temp[xaxis], q=5, duplicates='drop',precision=0)\n df_temp[xaxis] = df_temp[xaxis].astype(str).str.strip('()[]')\n\n if (len(df_temp[yaxis].unique().tolist()) > 5):\n df_temp[yaxis] = pd.qcut(df_temp[yaxis], q=3, duplicates='drop',precision=0)\n df_temp[yaxis] = df_temp[yaxis].astype(str).str.strip('()[]')\n charttype = 2\n # if feature1type == 'Category' and feature2type == 'Category':\n if charttype == 2:\n uniqueclasses = df_temp[yaxis].unique().tolist()\n cfig = go.Figure()\n i = 1\n for x in uniqueclasses:\n df_temp3 = df_temp.loc[df_temp[yaxis] == x]\n df_temp2 = df_temp3.groupby(xaxis, as_index=False)[yaxis].count()\n if df_temp2[xaxis].dtypes == \"object\":\n df_temp2 = df_temp2.set_index(xaxis).reindex(\n natsorted(df_temp2[xaxis].tolist(), key=lambda y: y.lower())).reset_index()\n\n xaxis_data = df_temp2[xaxis].tolist()\n \n yaxis_data = df_temp2[yaxis].tolist()\n \n cfig.add_trace(go.Bar(x=xaxis_data, y=yaxis_data, name=x, marker_color=barcolor[i]))\n i = i + 1\n if i == 5:\n break\n cfig.update_layout(barmode='stack', xaxis_title=xaxis, yaxis_title=yaxis)\n bargraph = cfig.to_html(full_html=False, default_height=450, default_width=400)\n featureCharts.append(bargraph)\n\n if charttype == 1:\n df_temp2 = df_temp.groupby(xaxis, as_index=False)[yaxis].mean()\n if df_temp2[xaxis].dtypes == \"object\":\n df_temp2 = df_temp2.set_index(xaxis).reindex(\n natsorted(df_temp2[xaxis].tolist(), key=lambda y: y.lower())).reset_index()\n\n xaxis_data = df_temp2[xaxis].tolist()\n yaxis_data = df_temp2[yaxis].tolist()\n \n cfig = go.Figure()\n cfig.add_trace(go.Bar(x=xaxis_data, y=yaxis_data, name='Primary Product', marker_color='blue'))\n cfig.update_layout(xaxis_title=xaxis, yaxis_title=yaxis)\n bargraph = cfig.to_html(full_html=False, default_height=450, default_width=400)\n featureCharts.append(bargraph)\n colno += 1\n if colno > 3:\n colno = 1\n rowno += 1\n except Exception as e:\n print(e)\n return (featureCharts)\n\n\n# EDA Visualization changes\n# ----------------------------\ndef getFeatureCharts(df, graphType, d3_url,mpld3_url): \n featureCharts = []\n feature1 = df.columns[0]\n feature2 = df.columns[1]\n\n import seaborn as sns\n import mpld3\n fig, ax = plt.subplots(figsize=[10,5])\n \n if graphType == 'marker':\n df.plot(ax=ax, marker='o')\n # df[['age','education-num']].plot(ax=ax, marker='o') \n\n if graphType == 'area':\n df.plot(ax=ax, kind =\"area\")\n # df[['education-num','age']].plot(ax=ax, kind =\"area\") # UIprb\n\n if graphType == 'hexbin':\n df.plot.hexbin(ax=ax, x=feature1, y=feature2, gridsize=2)\n\n if graphType == 'boxplot':\n plt.boxplot(df)\n\n if graphType == 'scatter':\n ax.scatter(df[feature1], df[feature2]) \n \n if graphType == 'regplot':\n ax = sns.regplot(x= feature1, y=feature2, data= df, fit_reg = False, scatter_kws={\"alpha\": 0.5})\n \n if graphType == 'lineplot':\n ax = sns.lineplot(x= feature1, y=feature2, data= df) \n \n if graphType == 'barplot':\n ax = sns.barplot(x= feature1, y=feature2, data= df)\n # ax = sns.barplot(x= 'age', y='fnlwgt', data= df) #Start_prb \n \n ax.legend()\n ax.set_xlabel(feature1)\n ax.set_ylabel(feature2)\n #print(d3_url)\n #print(mpld3_url)\n html_graph = mpld3.fig_to_html(fig,d3_url=d3_url,mpld3_url=mpld3_url) \n \n if graphType == 'kde':\n ax = sns.pairplot(df, kind=\"kde\", height=4, x_vars=feature1,y_vars = feature2)\n # ax = sns.pairplot(df[['age','fnlwgt']], kind=\"kde\")\n html_graph = mpld3.fig_to_html(ax.fig)\n \n if graphType == 'relplot':\n sns.set(style =\"darkgrid\")\n ax = sns.relplot(x =feature1, y =feature2, data = df)\n html_graph = mpld3.fig_to_html(ax.fig)\n \n \n \n featureCharts.append(html_graph) \n return (featureCharts)\n# ----------------------------\n\n\n\n\ndef MostCommonWords(stopwords, inputCorpus, num_of_words=10):\n try:\n from collections import Counter\n new = inputCorpus.str.split()\n new = new.values.tolist()\n corpus = [word for i in new for word in i if word not in stopwords]\n counter = Counter(corpus)\n most = counter.most_common()\n x, y = [], []\n for word, count in most[: num_of_words + 1]:\n x.append(word)\n y.append(count)\n return pd.DataFrame([x, y], index=['most_common_words', 'freq']).T\n except:\n print(\"exception\", sys.exc_info())\n return False\n\ndef removeFeature(df):\n featuresList = df.columns.values.tolist()\n modelFeatures = featuresList.copy()\n datetimeFeatures = []\n sequenceFeatures = []\n unimportantFeatures = []\n featuresRatio = {}\n for i in featuresList:\n check = match_date_format(df[i])\n if check == True:\n modelFeatures.remove(i)\n continue \n seq_check = check_seq_feature(df[i])\n if seq_check == True:\n modelFeatures.remove(i)\n continue\n ratio = check_category(df[i])\n if ratio != 0:\n featuresRatio[i] = ratio\n else:\n modelFeatures.remove(i)\n return featuresList, modelFeatures\n\ndef check_category(data):\n total_record = len(data)\n nUnique = len(data.unique().tolist())\n if nUnique == 1:\n return 0\n ratio = nUnique / total_record\n return (ratio)\n\ndef check_seq_feature(data):\n if data.dtypes in ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']:\n total_record = data.count()\n count = (data - data.shift() == 1).sum()\n if ((total_record - count) == 1):\n return True\n return False\n\ndef match_date_format(data):\n data = data.astype(str)\n beforecheckcount = (data.count()*80)/100\n #####YYYY-MM-DD HH:MM:SS####\n check1 = data[data.str.match(\n r'(^\\\\d\\\\d\\\\d\\\\d-(0?[1-9]|1[0-2", "instruction": "", "output": "" }, { "input": "])-(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]\n aftercheckcount = check1.count()\n if (beforecheckcount <= aftercheckcount):\n return True\n #####MM/DD/YYYY HH:MM####\n check2 = data[data.str.match(\n 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]\n aftercheckcount = check2.count()\n if (beforecheckcount <= aftercheckcount):\n return True\n\n #####DD-MM-YYYY HH:MM####\n check2 = data[data.str.match(\n 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]\n aftercheckcount = check2.count()\n if (beforecheckcount <= aftercheckcount):\n return True\n\n #####YYYY/MM/DD####\n 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]\n aftercheckcount = check2.count()\n if (beforecheckcount <= aftercheckcount):\n return True\n #####MM/DD/YYYY####\n 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]\n aftercheckcount = check2.count()\n if (beforecheckcount <= aftercheckcount):\n return True\n return False\n\ndef check_text_features(df, modelFeatures):\n aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n textFeature = []\n for i in enumerate(modelFeatures):\n dataType = df[i[1]].dtypes\n numOfRows = df.shape[0]\n if dataType not in aionNumericDtypes:\n if dataType != 'bool':\n nUnique = len(df[i[1]].unique().tolist())\n textnumbericratio = 0.01\n if (numOfRows < 1000):\n textnumbericratio = 0.2\n elif (numOfRows < 10000):\n textnumbericratio = 0.1\n elif (numOfRows < 100000):\n textnumbericratio = 0.01\n if nUnique / numOfRows >= textnumbericratio:\n textFeature.append(i[1])\n return (textFeature)\n\ndef getWordCloud(df, text_columns):\n df_text = pd.DataFrame()\n stopwords = set(STOPWORDS)\n if (len(text_columns) > 1):\n df_text['combined'] = df[text_columns].apply(lambda row: ' '.join(row.values.astype(str)), axis=1)\n features = ['combined']\n else:\n df_text[['combined']] = df[text_columns]\n features = ['combined']\n df_text[features[0]] = df_text[features[0]].fillna(\"NA\")\n textCorpus = df_text[features[0]]\n from text import TextProcessing\n tp = TextProcessing.TextProcessing()\n preprocessed_text = tp.transform(textCorpus)\n df_text['combined'] = preprocessed_text\n df_text_list = df_text.values.tolist()\n comment_words = \"\"\n for val in df_text_list:\n val = str(val)\n tokens = val.split()\n for i in range(len(tokens)):\n tokens[i] = tokens[i].lower()\n\n comment_words += \" \".join(tokens) + \" \"\n wordcloud = WordCloud(stopwords=stopwords).generate(comment_words)\n try:\n plt.clf()\n except:\n pass\n try:\n plt.imshow(wordcloud, interpolation='bilinear')\n plt.axis(\"off\")\n plt.tight_layout(pad=0)\n image = io.BytesIO()\n plt.savefig(image, format='png')\n image.seek(0)\n string = base64.b64encode(image.read())\n image_64 = 'data:image/png;base64,' + urllib.parse.quote(string)\n except Exception as inst:\n print(inst)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n image_64=''\n return (image_64, df_text)\n\ndef getTopTextFeatures(df_text):\n stopwords = set(STOPWORDS)\n commonfeatures = MostCommonWords(stopwords, df_text['combined'])\n xaxis_data = commonfeatures['most_common_words'].tolist()\n yaxis_data = commonfeatures['freq'].tolist()\n import plotly.graph_objects as go\n cfig = go.Figure()\n cfig.add_trace(go.Bar(x=xaxis_data, y=yaxis_data, name='Feature Importance'))\n cfig.update_layout(barmode='stack', xaxis_title='Features')\n bargraph = cfig.to_html(full_html=False, default_height=450, default_width=1000)\n return (bargraph)\n\n\n\ndef getPCATop10Features(df, modelFeatures):\n aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n categorial_features = []\n for i in enumerate(modelFeatures):\n dataType = df[i[1]].dtypes\n if dataType not in aionNumericDtypes:\n categorial_features.append(i[1])\n df[i[1]] = pd.Categorical(df[i[1]])\n df[i[1]] = df[i[1]].cat.codes\n df[i[1]] = df[i[1]].astype(int)\n df[i[1]] = df[i[1]].fillna(df[i[1]].mode()[0])\n else:\n df[i[1]] = df[i[1]].fillna(df[i[1]].mean())\n from sklearn.decomposition import PCA\n pca = PCA(n_components=2).fit(df)\n map = pd.DataFrame(pca.components_, columns=modelFeatures)\n map = map.diff(axis=0).abs()\n map = map.iloc[1]\n map = map.sort_values(ascending=False).head(10)\n yaxis_data = map.tolist()\n xaxis_data = map.index.values.tolist()\n import plotly.graph_objects as go\n cfig = go.Figure()\n cfig.add_trace(go.Bar(x=xaxis_data, y=yaxis_data, name='Feature Importance'))\n cfig.update_layout(barmode='stack', xaxis_title='Features')\n bargraph = cfig.to_html(full_html=False, default_height=450, default_width=1000)\n \n \n return (bargraph)\n\ndef getCorrelationMatrix(df):\n try:\n #from dython.nominal import associations\n if len(df.columns) > 25:\n df3 = df[df.columns[0:24]]\n else:\n df3 = df.copy()\n cor_mat= associations(df3,compute_only=True)\n cor_mat=cor_mat['corr'] \n #cor_mat = df3.corr()\n cor_mat = cor_mat.astype(float).round(2)\n #print(cor_mat)\n z = cor_mat.values.tolist()\n fig = ff.create_annotated_heatmap(z, x=cor_mat.columns.tolist(), y=cor_mat.index.tolist(), annotation_text=z,\n colorscale='Blues')\n fig.layout.yaxis.automargin = True\n correlationgraph = fig.to_html(full_html=True, default_height=450, default_width=1000)\n except Exception as e:\n print(e)\n correlationgraph = ''\n return (correlationgraph)\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nfrom appbe import exploratory_Analysis as ea\nimport pandas as pd\nfrom appbe.checkConfiguration import start_check\nimport json\nimport os\nimport ast\nimport time\nimport numpy as np\nfrom appfe.modelTraining.models import usecasedetails\nfrom appfe.modelTraining.models import Existusecases\n# from modelTraining.models import view\nfrom appbe.aion_config import kafka_setting\nfrom appbe.aion_config import running_setting\nfrom appbe.s3buckets import get_s3_bucket\nfrom appbe.gcsbuckets import get_gcs_bucket\nfrom appbe import help_Text as ht\n\ndef is_value_na( value):\n if isinstance( value, str):\n return value.strip().lower() in ['','na','none']\n return not value\n\ndef set_ts_preprocessing(request,configSettingsJson): #Task 13052 Timeseries Preprocessing\n\n interpolationType = request.POST.get('interpolationType')\n ts_config = configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']\n for key in ts_config['interpolation']:\n configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']['interpolation'][\n key] = 'False'\n if interpolationType != 'na':\n configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']['interpolation'][\n interpolationType] = 'True'\n ts_config['rollingWindow'] = request.POST.get('rollingWindow')\n if ts_config['rollingWindow'] == 'True':\n ts_config['rollingWindowSize'] = request.POST.get('rollWindowsize')\n\n aggregation = request.POST.get('aaggregationType')\n for key in ts_config['aggregation']['type']:\n ts_config['aggregation']['type'][key]='False'\n if is_value_na(aggregation) == False:\n ts_config['aggregation']['type'][aggregation] = 'True'\n granularityType = request.POST.get('unitType')\n granularitySize = request.POST.get('garnularitysize')\n for key in ts_config['aggregation']['granularity']['unit']:\n ts_config['aggregation']['granularity']['unit'][key] = 'False'\n ts_config['aggregation']['granularity']['unit'][granularityType]='True'\n ts_config['aggregation']['granularity']['size'] = granularitySize\n configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']= ts_config\n return configSettingsJson\n\ndef update_granularity(configSettingsJson,datapath=None):\n try:\n from AION.appbe.utils import set_true_option\n import pandas as pd\n from pathlib import Path\n MINUTES = 60\n if not is_value_na(configSettingsJson['basic']['dateTimeFeature']):\n if not datapath:\n datapath = configSettingsJson['basic']['dataLocation']\n if Path( datapath).exists():\n df = pd.read_csv(datapath, nrows=2)\n if isinstance( configSettingsJson['basic']['dateTimeFeature'], list):\n datetime_feature = configSettingsJson['basic']['dateTimeFeature'][0]\n else:\n datetime_feature = configSettingsJson['basic']['dateTimeFeature']\n datetime = pd.to_datetime(df[ datetime_feature])\n if len(datetime) > 1:\n time_delta = (datetime[1] - datetime[0]).total_seconds()\n granularity_unit = configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']['aggregation']['granularity']['unit']\n if time_delta < (1 * MINUTES):\n set_true_option(granularity_unit, key='second')\n elif time_delta < (60 * MINUTES):\n set_true_option(granularity_unit, key='minute')\n elif time_delta < (24 * 60 * MINUTES):\n set_true_option(granularity_unit, key='hour')\n elif time_delta < (7 * 24 * 60 * MINUTES):\n set_true_option(granularity_unit, key='day')\n elif time_delta < (30 * 24 * 60 * MINUTES):\n set_true_option(granularity_unit, key='week')\n elif time_delta < (365 * 24 * 60 * MINUTES):\n set_true_option(granularity_unit, key='month')\n else:\n set_true_option(granularity_unit, key='year')\n return configSettingsJson\n except Exception as e:\n print(f'\\\\nIgnoring error during granularity unit conversion\\\\n:{str(e)}')\n return configSettingsJson\n\ndef save(request):\n\n try:\n status = 'pass'\n msg = \"\"\n DEPLOY_LOCATION = request.session['deploylocation']\n if request.method == 'POST':\n submittype = request.POST.get('BasicSubmit')\n if submittype != 'BasicDefault':\n filterjson = 'NA'\n timegroupingjson = 'NA'\n groupingjson = 'NA'\n if request.POST.get('filters') != '':\n filterjson = str(json.loads(request.POST.get('filters')))\n if request.POST.get('timegroup') != '':\n timegroupingjson = str(json.loads(request.POST.get('timegroup')))\n if request.POST.get('idgroup') != '':\n groupingjson = str(json.loads(request.POST.get('idgroup')))\n \n configFile = request.session['config_json']\n f = open(configFile, \"r\")\n configSettings = f.read()\n f.close()\n configSettings", "instruction": "", "output": "" }, { "input": "Json = json.loads(configSettings)\n temp = {} \n # Retraing settings changes\n # -------- S T A R T --------\n prbType = request.POST.get('ProblemType')\n if prbType is None:\n prbType = request.POST.get('tempProblemType')\n # temp['ProblemType'] = request.POST.get('ProblemType')\n # request.session['Problem'] = request.POST.get('ProblemType')\n temp['ProblemType'] = prbType\n request.session['Problem'] = request.POST.get('ProblemType')\n # ---------------------------\n \n \n temp['ModelName'] = request.session['usecaseid']\n temp['Version'] = str(request.session['ModelVersion'])\n temp['InputFeatures'] = request.POST.getlist('IncInputFeatures')\n temp['dataLocation'] = str(request.session['datalocation'])\n onlinelearning=request.POST.get('onlineLearning',None) \n if (onlinelearning is not None): \n if onlinelearning.lower() == 'onlinelearning':\n configSettingsJson['basic']['onlineLearning'] = 'True'\n if onlinelearning.lower() == 'distributedlearning':\n configSettingsJson['basic']['distributedLearning'] = 'True' \n temp['InputFeatures'] = request.POST.getlist('IncInputFeatures')\n temp['TargetFeatures'] = request.POST.getlist('TargetFeatures')\n temp['DateTimeFeatures'] = ''\n temp['IndexFeatures'] = ''\n for x in configSettingsJson['advance']['profiler']['normalization'].keys():\n configSettingsJson['advance']['profiler']['normalization'][x] = 'False'\n configSettingsJson['advance']['profiler']['normalization']['standardScaler'] = 'True'\n for x in configSettingsJson['advance']['profiler']['numericalFillMethod'].keys():\n configSettingsJson['advance']['profiler']['numericalFillMethod'][x] = 'False' \n configSettingsJson['advance']['profiler']['numericalFillMethod']['Mean'] = 'True'\n if onlinelearning.lower() == 'distributedlearning':\n for x in configSettingsJson['advance']['profiler']['categoricalFillMethod'].keys():\n configSettingsJson['advance']['profiler']['categoricalFillMethod'][x] = 'False' \n configSettingsJson['advance']['profiler']['categoricalFillMethod']['MostFrequent'] = 'True'\n for x in configSettingsJson['advance']['profiler']['categoryEncoding'].keys():\n configSettingsJson['advance']['profiler']['categoryEncoding'][x] = 'False' \n configSettingsJson['advance']['profiler']['categoryEncoding']['OneHotEncoding'] = 'True'\n configSettingsJson['advance']['profiler']['normalization']['standardScaler'] = 'False'\n for x in configSettingsJson['advance']['selector']['featureEngineering'].keys():\n if x != 'numberofComponents':\n configSettingsJson['advance']['selector']['featureEngineering'][x] = 'False'\n elif prbType == 'llmFineTuning':\n if configSettingsJson['basic']['preprocessing']['llmFineTuning']['unstructuredData'] == 'False':\n temp['InputFeatures'] = request.POST.getlist('IncInputFeatures')\n temp['TargetFeatures'] = request.POST.getlist('TargetFeatures')\n contextFeatures = request.POST.getlist('contextFeatures')\n configSettingsJson['basic']['contextFeature'] = \",\".join([model for model in contextFeatures])\n temp['DateTimeFeatures'] = ''\n temp['IndexFeatures'] = '' \n if request.POST.get('promptfriendlyname') != '':\n configSettingsJson['basic']['preprocessing']['llmFineTuning']['friendlyNames']['prompt'] = request.POST.get('promptfriendlyname')\n else:\n configSettingsJson['basic']['preprocessing']['llmFineTuning']['friendlyNames']['prompt'] = 'Instruction'\n if request.POST.get('responsefriendlyname') != '':\n configSettingsJson['basic']['preprocessing']['llmFineTuning']['friendlyNames']['response'] = request.POST.get('responsefriendlyname')\n else:\n configSettingsJson['basic']['preprocessing']['llmFineTuning']['friendlyNames']['response'] = ''\n else:\n if request.session['datatype'] == 'LLM_Document':\n for x in configSettingsJson['basic']['preprocessing']['llmFineTuning']['document'].keys(): \n configSettingsJson['basic']['preprocessing']['llmFineTuning']['document'][x] = 'False'\n configSettingsJson['basic']['preprocessing']['llmFineTuning']['document'][request.POST.get('dataPreprocessing')] = 'True'\n if request.session['datatype'] == 'LLM_Code':\n for x in configSettingsJson['basic']['preprocessing']['llmFineTuning']['objective'].keys():\n configSettingsJson['basic']['preprocessing']['llmFineTuning']['objective'][x] = 'False'\n configSettingsJson['basic']['preprocessing']['llmFineTuning']['objective'][request.POST.get('llmObjective')] = 'True'\n \n for x in configSettingsJson['basic']['preprocessing']['llmFineTuning']['code'].keys():\n configSettingsJson['basic']['preprocessing']['llmFineTuning']['code'][x] = 'False'\n configSettingsJson['basic']['preprocessing']['llmFineTuning']['code'][request.POST.get('dataPreprocessing')] = 'True'\n \n else:\n configSettingsJson['basic']['onlineLearning'] = 'False'\n configSettingsJson['basic']['distributedLearning'] = 'False'\n temp['InputFeatures'] = request.POST.getlist('InputFeatures')\n temp['TargetFeatures'] = request.POST.getlist('TargetFeatures')\n temp['DateTimeFeatures'] = request.POST.getlist('DateTimeFeatures')\n temp['IndexFeatures'] = request.POST.getlist('IndexFeatures')\n if (configSettingsJson['basic']['algorithms']['timeSeriesAnomalyDetection']['AutoEncoder'] == 'True'):#task 11997\n \n if (request.POST.get('analysis') == 'MultiVariate'):\n configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['multiVariate'] = 'True' #task 11997\n \n configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['uniVariate'] = 'False' #task 11997\n else:\n #print(configSettingsJson)\n configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['uniVariate'] = 'True' \n configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['multiVariate'] = 'False' #task 11997\n\n \n temp['UserID'] = ''\n temp['ItemID'] = ''\n temp['rating'] = ''\n \n temp['secondDocFeature'] = ''\n temp['firstDocFeature'] = ''\n temp['invoiceNoFeature'] = ''\n temp['itemFeature'] = ''\n model = ''\n \n if temp['ProblemType'].lower() == 'recommendersystem':\n model = request.POST.get('MachineLearningModels')\n \n if model == 'ItemRating':\n temp['ProblemType'] = 'RecommenderSystem'\n temp['MachineLearningModels'] = ['ItemRating']\n temp['DeepLearningModels'] = ''\n temp['UserID'] = request.POST.get('UserID')\n temp['ItemID'] = request.POST.get('ItemID')\n temp['rating'] = request.POST.get('rating')\n temp['InputFeatures'] = []\n temp['InputFeatures'].append(temp['UserID'])\n temp['InputFeatures'].append(temp['ItemID'])\n temp['InputFeatures'].append(temp['rating'])\n if model == 'TextSimilarity-Siamese':\n temp['ProblemType'] = 'recommenderSystem'\n temp['MachineLearningModels'] = ['TextSimilarity-Siamese']\n temp['secondDocFeature'] = request.POST.get('secondDocFeature')\n temp['firstDocFeature'] = request.POST.get('firstDocFeature')\n temp['InputFeatures'] = []\n temp['InputFeatures'].append(temp['secondDocFeature'])\n temp['InputFeatures'].append(temp['firstDocFeature'])\n if model == 'AssociationRules-Apriori':\n temp['ProblemType'] = 'recommenderSystem'\n temp['DeepLearningModels'] = ''\n temp['MachineLearningModels'] = ['AssociationRules-Apriori']\n temp['invoiceNoFeature'] = request.POST.get('associationRuleInvoiceNo')\n temp['itemFeature'] = request.POST.get('associationRuleItem')\n temp['InputFeatures'] = []\n temp['InputFeatures'].append(temp['invoiceNoFeature'])\n temp['InputFeatures'].append(temp['itemFeature']) \n \n temp['ScoringCriteria'] = request.POST.get('ScoringCriteria')\n\n if temp['ProblemType'].lower() not in ['recommendersystem','textsimilarity','associationrules','llmfinetuning']:\n temp['MachineLearningModels'] = request.POST.getlist('MachineLearningModels')\n temp['DeepLearningModels'] = request.POST.getlist('SelectDeepLearningModels')\n elif temp['ProblemType'].lower() == 'llmfinetuning':\n temp['MachineLearningModels'] = request.POST.getlist('MachineLearningModels')\n model = temp['MachineLearningModels'][0]\n supportedModelsSize = configSettingsJson['basic']['modelSize'][temp['ProblemType']][model]\n selectedModelSize = request.POST.get('modelSize')\n for x in supportedModelsSize.keys():\n configSettingsJson['basic']['modelSize'][temp['ProblemType']][model][x] = 'False'\n configSettingsJson['basic']['modelSize'][temp['ProblemType']][model][selectedModelSize] = 'True'\n\n temp['noofforecasts'] = request.POST.get('noofforecasts')\n temp['inlierLabels'] = request.POST.get('inlierLabels')\n #temp['filterExpression'] = request.POST.get('filterExpression')\n if temp['ProblemType'].lower() in ['clustering','topicmodelling','similarityidentification','contextualsearch']:\n temp['TargetFeatures'] = ''\n configSettingsJson['basic']['modelName'] = temp['ModelName']\n configSettingsJson['basic']['modelVersion'] = temp['Version']\n configSettingsJson['basic']['dataLocation'] = str(temp['dataLocation'])\n configSettingsJson['basic']['deployLocation'] = DEPLOY_LOCATION \n if configSettingsJson['basic']['preprocessing']['llmFineTuning']['unstructuredData'] == 'False':\n configSettingsJson['basic']['trainingFeatures'] = \",\".join([model for model in temp['InputFeatures']])\n configSettingsJson['basic']['dateTimeFeature'] = \",\".join([model for model in temp['DateTimeFeatures']])\n configSettingsJson['basic']['targetFeature'] = \",\".join([model for model in temp['TargetFeatures']])\n configSettingsJson['basic']['indexFeature'] = \",\".join([model for model in temp['IndexFeatures']])\n\n if filterjson == 'NA':\n configSettingsJson['basic']['filter'] = 'NA'\n else:\n configSettingsJson['basic']['filter'] = eval(filterjson)\n \n if timegroupingjson == 'NA':\n configSettingsJson['basic']['timegrouper'] = 'NA'\n else:\n configSettingsJson['basic']['timegrouper'] = eval(timegroupingjson)\n \n if groupingjson == 'NA':\n configSettingsJson['basic']['group'] = 'NA'\n else:\n configSettingsJson['basic']['group'] = eval(groupingjson)\n\n problemtyp = configSettingsJson['basic']['analysisType']\n \n for i in list(problemtyp.keys()):\n configSettingsJson['basic']['analysisType'][i]='False'\n \n algorithm = configSettingsJson['basic']['algorithms']\n for i in list(algorithm.keys()):\n for x in list(configSettingsJson['basic']['algorithms'][i].keys()):\n if x not in ['textSimilarityConfig','itemRatingConfig','associationRulesConfig','textSummarization']:\n configSettingsJson['basic']['algorithms'][i][x] = 'False'\n \n configSettingsJson['basic']['analysisType'][temp['ProblemType'][0].lower() + temp['ProblemType'][1:]] = 'True'\n \n # configSettingsJson['basic']['problem_type'] = temp['ProblemType']\n scoring = configSettingsJson['basic']['scoringCriteria']\n for i in list(scoring.keys()):\n for x in list(configSettingsJson['basic']['scoringCriteria'][i].keys()):\n configSettingsJson['basic']['scoringCriteria'][i][x] = 'False'\n if temp['ProblemType'].lower() in [\"classification\",\"regression\",\"survivalanalysis\",\"similarityidentification\",\"timeseriesforecasting\",\"contextualsearch\"]: #task 11997\n configSettingsJson['basic']['scoringCriteria'][temp['ProblemType'][0].lower() + temp['ProblemType'][1:]][temp['ScoringCriteria']] = 'True' \n # configSettingsJson['basic']['problem_type'] = temp['ProblemType']\n # configSettingsJson['basic']['scoringCriteria'] = temp['ScoringCriteria']\n configSettingsJson['basic']['noofforecasts'] = temp['noofforecasts']\n configSettingsJson['basic']['inlierLabels'] = temp['inlierLabels']\n #configSettingsJson['basic']['filterExpression'] = temp['filterExpression']\n configSettingsJson['basic']['algorithms']['recommenderSystem']['itemRatingConfig']['userID'] = temp['UserID']\n configSettingsJson['basic']['algorithms']['recommenderSystem']['itemRatingConfig']['itemID'] = temp['ItemID']\n configSettingsJson['basic']['algorithms']['recommenderSystem']['itemRatingConfig']['rating'] = temp['rating']\n configSettingsJson['basic']['algorithms']['recommenderSystem']['textSimilarityConfig']['baseFeature'] = temp['firstDocFeature']\n configSettingsJson['basic']['algorithms']['recommenderSystem']['textSimilarityConfig']['comparisonFeature'] = temp['secondDocFeature']\n configSettingsJson['basic']['algorithms']['recommenderSystem']['associationRulesConfig']['invoiceNoFeature'] = temp['invoiceNoFeature']\n configSettingsJson['basic']['algorithms']['recommenderSystem']['associationRulesConfig']['itemFeature'] = temp['itemFeature'] \n for x in temp['MachineLearningModels']:\n \n if temp['ProblemType'].lower() =='associationrules' or temp['ProblemType'].lower() == 'textsimilarity':\n temp['ProblemType'] = 'recommenderSystem'\n if request.POST.get('SearchType') != 'NAS' and request.POST.get('SearchType') != 'GoogleModelSearch'and request.POST.get('SearchType') != 'AutoGluon':\n configSettingsJson['basic']['algorithms'][temp['ProblemType'][0].lower() + temp['ProblemType'][1:]][x] = 'True' \n \n #for y in temp['DeepLearningModels']:\n # configSettingsJson['basic']['algorithms'][temp['ProblemType'][0].lower() + temp['ProblemType'][1:]][y] = 'True'\n \n configSettingsJson['basic']['output']['profilerStage'] = 'True'\n config", "instruction": "", "output": "" }, { "input": "SettingsJson['basic']['output']['selectorStage'] = 'True'\n for key in configSettingsJson['advance']['profiler']['textConversionMethod']: \n configSettingsJson['advance']['profiler']['textConversionMethod'][key] = 'False'\n if temp['ProblemType'].lower() != 'topicmodelling': \n configSettingsJson['advance']['profiler']['textConversionMethod']['TF_IDF'] ='True'\n else:\n configSettingsJson['advance']['profiler']['textConversionMethod']['CountVectors'] ='True'\n #print('============================')\n #print(temp['ProblemType'].lower()) \n #print('============================')\n if temp['ProblemType'].lower() == 'textsummarization':\n configSettingsJson['basic']['algorithms']['textSummarization']['Text Summarization'] = 'True'\n configSettingsJson['basic']['textSummarization']['KeyWords'] = str(request.POST.get('addKeywordsForSummarization'))\n configSettingsJson['basic']['textSummarization']['pathForKeywordFile'] = str(request.POST.get('DataFilePath'))\n \n if temp['ProblemType'].lower() not in ['recommendersystem','textsummarization','llmfinetuning']:\n\n if configSettingsJson['basic']['onlineLearning'] != 'True' and configSettingsJson['basic']['distributedLearning'] != 'True':\n jsonarr =request.POST.get('jsonarr')\n \n res = ast.literal_eval(jsonarr)\n for x in res:\n if x['type'].lower() == 'text':\n configSettingsJson['advance']['selector']['featureSelection']['allFeatures'] = 'False'\n configSettingsJson['advance']['selector']['featureSelection']['statisticalBased'] = 'True'\n configSettingsJson['advance']['selector']['featureSelection']['modelBased'] = 'False'\n if len(request.POST.get('traindfeatures').split(',')) > 30:\n configSettingsJson['advance']['selector']['featureSelection']['allFeatures'] = 'False'\n configSettingsJson['advance']['selector']['featureSelection']['statisticalBased'] = 'True'\n configSettingsJson['advance']['selector']['featureSelection']['modelBased'] = 'False'\n \n configSettingsJson['advance']['profiler']['featureDict'] = res\n \n configSettingsJson['basic']['indexFeature'] = request.POST.get('indexfeatures')\n configSettingsJson['basic']['trainingFeatures'] = request.POST.get('traindfeatures')\n configSettingsJson['basic']['dateTimeFeature'] = request.POST.get('datefeatures')\t\t\t\t\n \n if request.POST.get('SearchType') == 'GoogleModelSearch':\n configSettingsJson['basic']['algorithms'][temp['ProblemType'][0].lower() + temp['ProblemType'][1:]]['GoogleModelSearch_DNN'] = 'True'\n configSettingsJson['basic']['output']['profilerStage']= 'True'\n \n #---------- Time series Changes Task 13052 -----------------\n\n if temp['ProblemType'].lower() == 'timeseriesforecasting':\n configSettingsJson = set_ts_preprocessing(request,configSettingsJson)\n status,msg= start_check(configSettingsJson)\n updatedConfigSettings = json.dumps(configSettingsJson)\n updatedConfigFile = request.session['config_json']\n with open(updatedConfigFile, \"w\") as fpWrite:\n fpWrite.write(updatedConfigSettings)\n fpWrite.close()\n request.session['ModelStatus'] = 'Not Trained'\n selected_use_case = request.session['UseCaseName']\n ModelVersion = request.session['ModelVersion']\n ModelStatus = request.session['ModelStatus']\n request.session['currentstate'] = 1\n from appbe.telemetry import UpdateTelemetry\n UpdateTelemetry(request.session['usecaseid']+'-'+str(request.session['ModelVersion']),'ProblemType',prbType) \n UpdateTelemetry(request.session['usecaseid']+'-'+str(request.session['ModelVersion']),'Operation','Configured') \n context = {'tab': 'configure', 'temp': temp,'advconfig': configSettingsJson,\n 'basic_status_msg': 'Configuration Done',\n 'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion,\n 'currentstate': request.session['currentstate'], 'selected': 'modeltraning','training':True,'basic_help':ht.basic_help}\n \n # return render(request, 'basicconfig.html', context)\n if submittype == 'BasicDefault':\n \n temp = {}\n temp['ModelName'] = request.session['UseCaseName']\n temp['Version'] = request.session['ModelVersion']\n\n dataLocation = str(request.session['datalocation'])\n df = pd.read_csv(dataLocation, encoding='latin1')\n featuresList = df.columns.values.tolist()\n datetimeFeatures = []\n sequenceFeatures = []\n unimportantFeatures = []\n featuresRatio = {}\n for i in featuresList:\n check = ea.match_date_format(df[i])\n if check == True:\n datetimeFeatures.append(i)\n unimportantFeatures.append(i)\n seq_check = ea.check_seq_feature(df[i])\n if seq_check == True:\n sequenceFeatures.append(i)\n unimportantFeatures.append(i)\n ratio = ea.check_category(df[i])\n if ratio != 0:\n featuresRatio[i] = ratio\n else:\n unimportantFeatures.append(i)\n\n targetFeature = min(featuresRatio, key=featuresRatio.get)\n unimportantFeatures.append(targetFeature)\n config = {}\n config['modelName'] = request.session['UseCaseName']\n config['modelVersion'] = request.session['ModelVersion']\n config['datetimeFeatures'] = datetimeFeatures\n config['sequenceFeatures'] = sequenceFeatures\n config['FeaturesList'] = featuresList\n config['unimportantFeatures'] = unimportantFeatures\n config['targetFeature'] = targetFeature\n request.session['currentstate'] = 1\n context = {'tab': 'configure', 'temp': temp, 'config': config,\n 'currentstate': request.session['currentstate'], 'selected': 'modeltraning'}\n except Exception as e:\n print(e)\n import sys\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n return status,msg,context\n\ndef openbasicconf(request):\n # 10012:Decision Threshold related Changes\n data_is_under_RAM_threshold = True\n\n updatedConfigFile = request.session['config_json']\n f = open(updatedConfigFile, \"r+\")\n configSettingsData = f.read()\n configSettingsJson = json.loads(configSettingsData)\n temp = {}\n # temp['ModelName'] = request.session['UseCaseName']\n # temp['Version'] = request.session['ModelVersion']\n if request.session['datatype'] == 'Video' or request.session['datatype'] == 'Image' or request.session['datatype'] == 'Document':\n folderLocation = str(request.session['datalocation'])\n dataFile = os.path.join(folderLocation, request.session['csvfullpath'])\n else:\n dataFile = str(request.session['datalocation'])\n # -------------------------------- 10012:Decision Threshold related Changes S T A R T -------------------------------\n from appbe.dataIngestion import checkRAMThreshold\n data_is_under_RAM_threshold = checkRAMThreshold(request.session['datalocation'])\n # ------------------------------------------------------ E N D ------------------------------------------------------\n\n # Retraing settings changes\n # -------- S T A R T --------\n IsReTrainingCase = False\n if request.session['IsRetraining'] == 'Yes':\n IsReTrainingCase = True\n IsSameFeatures = True\n # ---------------------------\n \n \n featuresList = configSettingsJson['basic']['featureList']\n unimportantFeatures = []\n modelfeatures = configSettingsJson['basic']['trainingFeatures']\n for x in featuresList:\n if x not in modelfeatures:\n unimportantFeatures.append(x)\n config = {}\n config['ModelName'] = request.session['usecaseid']\n config['Version'] = request.session['ModelVersion']\n config['datetimeFeatures'] = configSettingsJson['basic']['dateTimeFeature'] # .split(\",\")\n if configSettingsJson['basic']['indexFeature']:\n config['sequenceFeatures'] = configSettingsJson['basic']['indexFeature'] # .split(\",\")\n config['FeaturesList'] = featuresList\n config['unimportantFeatures'] = unimportantFeatures\n config['targetFeature'] = configSettingsJson['basic']['targetFeature'].split(\",\")\n problemtypes = configSettingsJson['basic']['analysisType'] \n onlineLearning = configSettingsJson['basic']['onlineLearning'] \n problem_type = \"\"\n for k in problemtypes.keys():\n if configSettingsJson['basic']['analysisType'][k] == 'True':\n problem_type = k\n break\n #print('123',problem_type)\n config['ProblemType'] = problem_type\n # config['ProblemType'] = configSettingsJson['basic']['problem_type']\n \n scoring = configSettingsJson['basic']['scoringCriteria'] \n scoringCriteria = \"\"\n for k in scoring.keys():\n if configSettingsJson['basic']['scoringCriteria'][k] == 'True':\n scoringCriteria = k\n break\n config['ScoringCriteria'] = scoringCriteria\n\n # config['ProblemType'] = configSettingsJson['basic']['problem_type']\n # config['ScoringCriteria'] = configSettingsJson['basic']['scoringCriteria']\n\n selected_use_case = request.session['UseCaseName']\n ModelVersion = request.session['ModelVersion']\n ModelStatus = request.session['ModelStatus']\n if 'NoOfRecords' in request.session:\n records = request.session['NoOfRecords']\n else:\n records = 'NA'\n if request.session['finalstate'] <= 1:\n request.session['finalstate'] = 1\n request.session['currentstate'] = 1\n # dataFile = str(request.session['datalocation'])\n # df = pd.read_csv(dataFile,encoding='utf8')\n if 'NoOfRecords' in request.session:\n noofforecast = 20\n else:\n noofforecast = 20\n config['noofforecasts'] = noofforecast\n if 'numericFeature' in request.session:\n numericFeature = request.session['numericFeature']\n else:\n numericFeature = ''\n\n problemType = 'classification'\n for key in configSettingsJson['basic']['analysisType']:\n if configSettingsJson['basic']['analysisType'][key] == 'True':\n problemType = key\n break\n scoringCreteria = 'NA'\n if problemType in ['classification','regression','survivalAnalysis','timeSeriesForecasting']: #task 11997\n for key in configSettingsJson['basic']['scoringCriteria'][problemType]:\n if configSettingsJson['basic']['scoringCriteria'][problemType][key] == 'True':\n scoringCreteria = key\n break\n selectAlgo = \"\"\n if problemType in ['classification','regression','timeSeriesForecasting',\n 'timeSeriesAnomalyDetection',\n 'recommenderSystem','clustering','anomalyDetection','topicModelling','survivalAnalysis','videoForecasting','imageClassification','objectDetection','stateTransition','llmFineTuning']: #task 11997\n for key in configSettingsJson['basic']['algorithms'][problemType]:\n if configSettingsJson['basic']['algorithms'][problemType][key] == 'True':\n if selectAlgo != \"\":\n selectAlgo += ','\n selectAlgo += key \n modelSize = ''\n if problemType == 'llmFineTuning':\n for key in configSettingsJson['basic']['modelSize']['llmFineTuning'][selectAlgo].keys():\n if configSettingsJson['basic']['modelSize']['llmFineTuning'][selectAlgo][key] == 'True':\n modelSize = key\n break\n \n \n featuresdict = [feature['feature'] for feature in configSettingsJson['advance']['profiler']['featureDict']]\n context = {'tab': 'tabconfigure','modelSize':modelSize,'featuresdict':featuresdict, 'configsettings': configSettingsJson, 'temp': temp, 'config': config,'numericFeature':numericFeature,'onlineLearning':onlineLearning,\n 'noOfRecords': records, 'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,'problemType':problemType,'scoringCreteria':scoringCreteria,'selectAlgo':selectAlgo,\n 'ModelVersion': ModelVersion, 'currentstate': request.session['currentstate'],\n 'finalstate': request.session['finalstate'], 'selected': 'modeltraning','IsSameFeatures':IsSameFeatures,'IsReTrainingCase':IsReTrainingCase,'basic_help':ht.basic_help\n \n # 10012:Decision Threshold related changes\n , 'DLCheckpoint':data_is_under_RAM_threshold}\n return context\n\ndef gotoconf(request):\n selected_use_case = request.session['UseCaseName']\n ModelVersion = request.session['ModelVersion']\n ModelStatus = request.session['ModelStatus']\n try:\n # 10012:Decision Threshold related Changes\n data_is_under_RAM_threshold = True\n \n ModelName = usecasedetails.objects.get(id=request.session['ModelName'])\n Version = request.session['ModelVersion']\n import os\n\n if request.session['datatype'] in ['Video', 'Image','Document','Object']:\n folderLocation = str(request.session['datalocation'])\n dataFile = os.path.join(folderLocation, request.session['csvfullpath'])\n else:\n dataFile = str(request.session['datalocation'])\n # -------------------------------- 10012:Decision Threshold related Changes S T A R T -------------------------------\n from appbe.dataIngestion import checkRAMThreshold\n data_is_under_RAM_threshold = checkRAMThreshold(request.session['datalocation'])\n # ------------------------------------------------------ E N D ------------------------------------------------------\n if request.session['datatype'] not in ['LLM_Document','LLM_Code']: \n from appbe.eda import ux_eda\n if 'delimiter' not in request.session:\n request.session['delimiter'] = ','\n if 'textqualifier' not in request.session:\n request.session['textqualifier'] = '\"'\n eda_obj = ux_eda(dataFile,request.session['delimiter'],request.session['textqualifier'],optimize=1)\n featuresList,datetimeFeatures,sequenceFeatures,constantFeature,textFeature,targetFeature,numericCatFeatures,numericFeature,catFeatures = eda_obj.getFeatures() \n else:\n featuresList = []\n featuresList.append('Instruction')\n datetimeFeatures=[]\n sequenceFeatures=[]\n constantFeature=[]\n textFeature=[]\n targetFeature='Response'\n numericCatFeatures = []\n numericFeature=[]\n catFeatures=[]\n featuresListJson = []\n for x in featuresList:\n featureOperation={} \n featureOperation['feature'] = x\n if x in datetimeFeatures:\n featureOperation['type'] = 'date'\n featureOperation['fillMethod'] = 'na'", "instruction": "", "output": "" }, { "input": "\n featureOperation['categoryEncoding'] = 'na' \n elif x in textFeature:\n featureOperation['type'] = 'text'\n featureOperation['fillMethod'] = 'na' \n featureOperation['categoryEncoding'] = 'na'\n elif x in sequenceFeatures:\n featureOperation['type'] = 'index'\n featureOperation['fillMethod'] = 'median'\n featureOperation['categoryEncoding'] = 'na'\n elif (x in catFeatures) or (x in constantFeature):\n featureOperation['type'] = 'categorical'\n featureOperation['fillMethod'] = 'mode'\n featureOperation['categoryEncoding'] = 'targetEncoding'\n else:\n featureOperation['type'] = 'numerical'\n featureOperation['fillMethod'] = 'medium'\n featureOperation['categoryEncoding'] = 'na' \n featureOperation['outlierDetection'] = 'disable' \n featureOperation['outlierOperation'] = 'nochange'\n featureOperation['normalizer'] = 'none'\n featuresListJson.append(featureOperation) \n \n request.session['numericFeature'] = numericFeature\n records = 0\n import os\n if os.path.isfile(dataFile):\n for chunk in pd.read_csv(dataFile, chunksize=20000,encoding=\"utf-8\",encoding_errors= 'replace'):\n records = records+len(chunk)\n request.session['NoOfRecords'] = records\n \n filetimestamp = str(int(time.time()))\n CONFIG_FILE_PATH = request.session['configfilepath']\n config_json_filename = os.path.join(CONFIG_FILE_PATH, 'AION_' + filetimestamp + '.json')\n outputfile = os.path.join(CONFIG_FILE_PATH, 'AION_OUTPUT_' + filetimestamp + '.json')\n request.session['outputfilepath'] = str(outputfile)\n modelname = request.session['usecaseid']\n modelname = modelname.replace(\" \", \"_\")\n DEPLOY_LOCATION = request.session['deploylocation']\n request.session['logfilepath'] = os.path.join(DEPLOY_LOCATION, modelname,str(Version),'log','model_training_logs.log')\n request.session['config_json'] = config_json_filename\n #request.session['ModelVersion'] = Version\n request.session['ModelStatus'] = 'Not Trained'\n\n \n \n # p = Existusecases(DataFilePath=dataFile, DeployPath=DEPLOY_LOCATION, Status='Not Trained',\n # ConfigPath=config_json_filename, Version=Version, ModelName=ModelName,\n # TrainOuputLocation=outputfile)\n # p.save()\n \n # from AION_UX import telemetry\n # telemetry.telemetry_data('UseCaseCreated',modelname+'_'+str(Version),'UseCaseCreated')\n # request.session['modelid'] = p.id\n \n \n temp = {}\n temp['ModelName'] = request.session['usecaseid']\n temp['Version'] = request.session['ModelVersion']\n '''\n featuresList = features #df.columns.values.tolist()\n datetimeFeatures = \n \n datetimeFeatures = []\n sequenceFeatures = []\n unimportantFeatures = []\n featuresRatio = {}\n for i in featuresList:\n check = ea.match_date_format(df[i])\n if check == True:\n datetimeFeatures.append(i)\n unimportantFeatures.append(i)\n seq_check = ea.check_seq_feature(df[i])\n if seq_check == True:\n sequenceFeatures.append(i)\n unimportantFeatures.append(i)\n ratio = ea.check_category(df[i])\n if ratio != 0:\n featuresRatio[i] = ratio\n else:\n unimportantFeatures.append(i)\n targetFeature = min(featuresRatio, key=featuresRatio.get)\n unimportantFeatures.append(targetFeature)\n '''\n unimportantFeatures = list(datetimeFeatures)\n unimportantFeatures.extend(sequenceFeatures)\n #unimportantFeatures = list(set(unimportantFeatures) + set(sequenceFeatures))\n unimportantFeatures.append(targetFeature)\n \n config = {}\n noofforecast = 20\n config['ModelName'] = request.session['usecaseid']\n config['Version'] = request.session['ModelVersion']\n config['datetimeFeatures'] = datetimeFeatures\n config['sequenceFeatures'] = sequenceFeatures\n config['FeaturesList'] = featuresList\n config['unimportantFeatures'] = unimportantFeatures\n config['targetFeature'] = targetFeature\n config['noofforecasts'] = noofforecast\n DEFAULT_FILE_PATH = request.session['defaultfilepath']\n \n # Retraing settings changes\n # -------- S T A R T --------\n \n IsReTrainingCase = False\n if request.session['IsRetraining'] == 'Yes':\n id = request.session['ModelName']\n p = usecasedetails.objects.get(id=id)\n model = Existusecases.objects.filter(ModelName=p)\n \n indexVal = model.count() - 1\n configFile = str(model[indexVal].ConfigPath)\n # configFile = str(model[0].ConfigPath)\n \n # request.session['IsRetraining'] = 'No'\n IsReTrainingCase = True\n # ---------------------------\n \n else:\n configFile = os.path.join(DEFAULT_FILE_PATH, 'aion_config.json')\n \n f = open(configFile, \"r\")\n configSettings = f.read()\n f.close()\n configSettingsJson = json.loads(configSettings)\n\n # Retraing settings changes\n # -------- S T A R T --------\n pickDefaultSettings = False\n IsSameFeatures = False\n if 'featureList' not in configSettingsJson['basic']:\n pickDefaultSettings = True\n IsSameFeatures = True\n else:\n if configSettingsJson['basic']['featureList'] == featuresList:\n pickDefaultSettings = False\n IsSameFeatures = True\n else:\n pickDefaultSettings = True\n\n if pickDefaultSettings:\n # ---------------------------\n \n configSettingsJson['basic']['featureList'] = featuresList\n configSettingsJson['basic']['dateTimeFeature'] = \",\".join([feature for feature in datetimeFeatures])\n configSettingsJson['basic']['indexFeature'] = sequenceFeatures\n trainingFeatures = list(set(featuresList) - set(unimportantFeatures))\n configSettingsJson['basic']['trainingFeatures'] = \",\".join([feature for feature in trainingFeatures])\n configSettingsJson['basic']['targetFeature'] = targetFeature\n \n if request.session['datatype'].lower() in ['video','image','object','document','llm_document','llm_code']:\n for x in configSettingsJson['basic']['analysisType'].keys():\n configSettingsJson['basic']['analysisType'][x] = 'False'\n configSettingsJson['basic']['folderSettings']['fileType'] = request.session['datatype']\n configSettingsJson['basic']['folderSettings']['labelDataFile'] = request.session['csvfullpath']\n configSettingsJson['basic']['folderSettings']['fileExtension'] = request.session['fileExtension']\n if request.session['datatype'] in ['LLM_Document','LLM_Code']:\n configSettingsJson['basic']['analysisType']['llmFineTuning'] = 'True'\n configSettingsJson['basic']['preprocessing']['llmFineTuning']['friendlyNames']['prompt']='Instruction'\n configSettingsJson['basic']['preprocessing']['llmFineTuning']['friendlyNames']['response']='Response'\n configSettingsJson['basic']['preprocessing']['llmFineTuning']['unstructuredData'] = 'True'\n \n elif request.session['datatype'] == 'Video':\n configSettingsJson['basic']['analysisType']['videoForecasting'] = 'True'\n elif request.session['datatype'] == 'Image':\n configSettingsJson['basic']['analysisType']['imageClassification'] = 'True'\n elif request.session['datatype'] == 'Object':\n configSettingsJson['basic']['analysisType']['objectDetection'] = 'True'\n elif request.session['datatype'].lower() == 'document':\n df = pd.read_csv(dataFile, encoding='utf8',sep=request.session['delimiter'],quotechar=request.session['textqualifier'],nrows=100)\n noOfEmotyLevels = 0\n shape = df.shape\n if shape[1] == 2:\n noOfEmotyLevels = df['Label'].isnull().sum()\n #print(noOfEmotyLevels)\n if noOfEmotyLevels == 100:\n configSettingsJson['basic']['analysisType']['topicModelling'] = 'True'\t\t\n else:\n configSettingsJson['basic']['analysisType']['classification'] = 'True'\n else: \n if 'uploadfiletype' in request.session:\n configSettingsJson['basic']['folderSettings']['fileType'] = request.session['uploadfiletype'] \t\n configSettingsJson['basic']['folderSettings']['labelDataFile'] = request.session['uploadLocation']\t\n try:\n if isinstance(datetimeFeatures, list):\n if len(datetimeFeatures) != 0:\n configSettingsJson = update_granularity(configSettingsJson,datapath=dataFile)\n elif isinstance(datetimeFeatures, str):\n if datetimeFeatures != '':\n configSettingsJson = update_granularity(configSettingsJson,datapath=dataFile)\n except:\n pass\n # Retraing settings changes\n # -------- S T A R T --------\n\n tot_count=len(numericCatFeatures)\n #task 11997\n if (tot_count > 1):\n configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['multiVariate'] = 'True'\n configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['uniVariate'] = 'False'\n else:\n configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['uniVariate'] = 'True' \n configSettingsJson['basic']['analysisApproach']['timeSeriesAnomalyDetection']['AutoEncoder']['multiVariate'] = 'False' \n if 'delimiter' in request.session: \n configSettingsJson['basic']['fileSettings']['delimiters'] = request.session['delimiter']\n else:\n configSettingsJson['basic']['fileSettings']['delimiters'] = ','\n if 'textqualifier' in request.session:\n configSettingsJson['basic']['fileSettings']['textqualifier'] = request.session['textqualifier']\n else:\n request.session['textqualifier'] = '\"'\n\n configSettingsJson['advance']['profiler']['featureDict'] = featuresListJson \n configSettingsJson['basic']['onlineLearning'] = 'False'\n configSettingsJson['basic']['dataLocation'] = request.session['datalocation']\n configSettingsJson['basic']['noOfRecords'] = request.session['NoOfRecords']\n onlineLearning = configSettingsJson['basic']['onlineLearning']\n updatedConfigSettings = json.dumps(configSettingsJson)\n with open(config_json_filename, \"w\") as fpWrite:\n fpWrite.write(updatedConfigSettings)\n fpWrite.close()\n\n '''\n p = Existusecases(DataFilePath=dataFile, DeployPath=DEPLOY_LOCATION, Status='Not Trained',\n ConfigPath=config_json_filename, Version=Version, ModelName=ModelName,\n TrainOuputLocation=outputfile)\n p.save()\n '''\n p = Existusecases.objects.get(ModelName=ModelName,Version=Version)\n p.DataFilePath = dataFile\n p.DeployPath = DEPLOY_LOCATION\n p.ConfigPath = config_json_filename \n p.TrainOuputLocation = outputfile \n p.save() \n #from appbe import telemetry\n #telemetry.telemetry_data('UseCaseCreated',modelname+'_'+str(Version),'UseCaseCreated')\n request.session['modelid'] = p.id\n # ---------------------------\n\n from appbe.compute import selectedInfratructure\n infra = selectedInfratructure()\n if infra.lower() in ['aws','gcp']:\n problemType = 'llmFineTuning'\n else:\n problemType = 'classification'\n #print(problemType)\n for key in configSettingsJson['basic']['analysisType']:\n if configSettingsJson['basic']['analysisType'][key] == 'True':\n problemType = key\n break\n scoringCreteria = 'NA'\n if problemType in ['classification','regression','survivalAnalysis','timeSeriesForecasting']: #task 11997\n for key in configSettingsJson['basic']['scoringCriteria'][problemType]:\n if configSettingsJson['basic']['scoringCriteria'][problemType][key] == 'True':\n scoringCreteria = key\n break\n selectAlgo = \"\"\n if problemType in ['classification','regression','timeSeriesForecasting','timeSeriesAnomalyDetection',\n 'recommenderSystem','clustering','anomalyDetection','topicModelling','survivalAnalysis','videoForecasting','imageClassification','objectDetection','stateTransition','llmFineTuning']: #task 11997\n for key in configSettingsJson['basic']['algorithms'][problemType]:\n if configSettingsJson['basic']['algorithms'][problemType][key] == 'True':\n if selectAlgo != \"\":\n selectAlgo += ','\n selectAlgo += key\n modelSize = ''\n if problemType == 'llmFineTuning':\n for key in configSettingsJson['basic']['modelSize']['llmFineTuning'][selectAlgo].keys():\n if configSettingsJson['basic']['modelSize']['llmFineTuning'][selectAlgo][key] == 'True':\n modelSize = key\n break\n \n movenext = True\n request.session['finalstate'] = 1\n request.session['currentstate'] = 1\n context = {'tab': 'tabconfigure','modelSize':modelSize,'tot_count':tot_count, 'temp': temp, 'configsettings': configSettingsJson, 'config': config,'numericFeature':numericFeature,'onlineLearning':onlineLearning,\n 'noOfRecords': records, 'selected_use_case': selected_use_case,'problemType':problemType,'scoringCreteria':scoringCreteria,'selectAlgo':selectAlgo,'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion, 'movenext': movenext,\n 'currentstate': request.session['currentstate'], 'finalstate': request.session['finalstate'],\n 'selected': 'modeltraning','advance':True,'basic_help':ht.basic_help\n # Retraing settings changes\n ,'IsSameFeatures':IsSameFeatures,'IsReTrainingCase':IsReTrainingCase\n \n # 10012:Decision Threshold related\n ,'DLCheckpoint':data_is_under_RAM_threshold}\n return context\n except UnicodeDecodeError as e:\n print(e)\n context = {'tab': 'tabconfigure','selected_use_case': selected_use_case,'ModelVersion': ModelVersion,'ModelStatus': ModelStatus,'selected': 'modeltraning','error': 'File Reading Error: '+str(e)}\n return context\n except Exception as e:\n print(e)\n import sys,os\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n context = {'tab': 'tabconfigure','selected_use_case': selected_use_case", "instruction": "", "output": "" }, { "input": ",'ModelVersion': ModelVersion,'ModelStatus': ModelStatus,'selected': 'modeltraning','error': 'Config Error: '+str(e)}\n return context '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport kfp\nimport kfp.dsl as dsl\nimport json\nfrom pathlib import Path\n\n\nclass aionpipelinets():\n \n containerRegistry = str()\n containerLabel = str()\n containerSecret = str()\n \n pipelineName = 'AION MLOps Pipeline {0}'\n exeCmd = 'python'\n codeFile = 'aionCode.py'\n mntPoint = '/aion'\n inputArg = '-i'\n msIP = '0.0.0.0'\n port = '8094'\n cachingStrategy = 'P0D'\n \n deafultVolume = '2Gi'\n volName = 'aion-pvc'\n volMode = 'ReadWriteMany'\n fileExt = '.tar.gz'\n fileName = 'aion_mlops_pipeline_{0}'\n \n containerMM = 'modelmonitoring'\n containerDI = 'dataingestion'\n containerDT = 'datatransformation'\n containerFE = 'featureengineering'\n containerMR = 'modelregistry'\n containerMS = 'modelserving'\n containerImage = '{0}/{1}:{2}'\n \n models = {}\n nameSeprator = '-'\n modelsLiteral = 'models'\n modelNameLiteral = 'modelname'\n 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}\"}}]}}'\n \n def __init__(self, models, containerRegistry, containerLabel, containerSecret=str()):\n self.models = models\n self.containerRegistry = containerRegistry\n self.containerLabel = containerLabel\n self.containerSecret = containerSecret \n \n @dsl.pipeline(\n name=pipelineName.format(containerLabel),\n description=pipelineName.format(containerLabel),\n )\n def aion_mlops(self, inputUri=str(), volSize=deafultVolume):\n vop = dsl.VolumeOp(\n name=self.volName + self.nameSeprator + self.containerLabel,\n resource_name=self.volName,\n modes=[self.volMode],\n size=volSize\n )\n \n mm = dsl.ContainerOp(\n name=self.containerMM,\n image=self.containerImage.format(self.containerRegistry,self.containerMM,self.containerLabel),\n command=self.exeCmd,\n arguments=[\n self.codeFile,\n self.inputArg,\n inputUri,\n ],\n pvolumes={self.mntPoint: vop.volume}\n )\n mm.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy\n \n di = dsl.ContainerOp(\n name=self.containerDI,\n image=self.containerImage.format(self.containerRegistry,self.containerDI,self.containerLabel),\n command=self.exeCmd,\n arguments=[\n self.codeFile,\n ],\n pvolumes={self.mntPoint: mm.pvolume}\n )\n di.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy\n \n dt = dsl.ContainerOp(\n name=self.containerDT,\n image=self.containerImage.format(self.containerRegistry,self.containerDT,self.containerLabel),\n command=self.exeCmd,\n arguments=[\n self.codeFile,\n ],\n pvolumes={self.mntPoint: di.pvolume}\n )\n dt.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy\n \n fe = dsl.ContainerOp(\n name=self.containerFE,\n image=self.containerImage.format(self.containerRegistry,self.containerFE,self.containerLabel),\n command=self.exeCmd,\n arguments=[\n self.codeFile,\n ],\n pvolumes={self.mntPoint: dt.pvolume}\n )\n fe.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy\n \n \n dictMT = {}\n listMTOps = []\n \n for model in self.models[self.modelsLiteral]:\n modelName = model[self.modelNameLiteral]\n mt=dsl.ContainerOp(\n name=modelName,\n image=self.containerImage.format(self.containerRegistry,modelName,self.containerLabel),\n command=self.exeCmd,\n arguments=[\n self.codeFile,\n ],\n pvolumes={self.mntPoint: fe.pvolume})\n mt.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy\n listMTOps.append(mt)\n dictMT[self.mntPoint]=mt.pvolume\n \n \n mr = dsl.ContainerOp(\n name=self.containerMR,\n image=self.containerImage.format(self.containerRegistry,self.containerMR,self.containerLabel),\n command=self.exeCmd,\n arguments=[\n self.codeFile,\n ],\n pvolumes=dictMT\n ).after(*tuple(listMTOps))\n \n mr.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy\n \n 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)\n ms = dsl.ResourceOp(\n name=self.containerMS + self.nameSeprator + self.containerLabel,\n k8s_resource=json.loads(msJson),\n ) \n ms.after(mr)\n \n \n def compilepl(self, targetPath=str()):\n filePath = self.fileName.format(self.containerLabel.lower()) + self.fileExt\n if targetPath != str():\n filePath = Path(targetPath, filePath)\n kfp.compiler.Compiler().compile(self.aion_mlops, str(filePath))\n\n \n def executepl(self, kfhost=str()):\n client = kfp.Client(kfhost)\n client.create_run_from_pipeline_func(self.aion_mlops,arguments={})\n import pandas as pd\nimport numpy as np\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.tsa.stattools import kpss\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nimport logging\nimport os\nimport warnings\nwarnings.filterwarnings('ignore')\n## Main class to find out seassonality and stationary in timeseries data.\nclass StationarySeasonalityTest:\n def __init__(self,df,featurename,datetimefeature):\n self.df=df\n self.targetFeature=featurename\n self.datetimefeature=datetimefeature \n \n ## to get the timeseries data stationary information\n def stationary_model(self,df,target_feature,stationary_check_method): \n stationary_status=None\n if (stationary_check_method.lower()=='adfuller'): \n stats_model=adfuller(df[target_feature])\n 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]\n if (p_value>0.05):\n stationary_status=str(\"Non-Stationary\")\n elif(p_value<0.05):\n stationary_status=str(\"Stationary\")\n \n ##kpss is opposite to ADF in considering null hypothesis. In KPSS, if null hypothesis,then it is stationary as oppose to ADF.\n elif (stationary_check_method.lower()=='kpss'):\n from statsmodels.tsa.stattools import kpss\n stats_model = kpss(df[target_feature])\n statistic, p_value, n_lags, critical_values=stats_model[0],stats_model[1],stats_model[2],stats_model[3]\n \n ##In kpss, the stationary condition is opposite to Adafuller.\n if (p_value>0.05):\n stationary_status=str(\"Stationary\")\n \n else:\n stationary_status=str(\"Non-Stationary\")\n \n return stats_model,n_lags,p_value,stationary_status\n \n ## Get stationary details\n def stationary_check(self,target_feature,time_col,method):\n df=self.df \n df[time_col]=pd.to_datetime(df[time_col])\n df=df.set_index(time_col) \n try:\n stationary_check_method=method\n except:\n stationary_check_method='adfuller'\n if (len(target_feature) == 1):\n try:\n if isinstance(target_feature,list):\n target_feature=''.join(target_feature) \n elif isinstance(target_feature,int):\n target_feature=str(target_feature)\n elif isinstance(target_feature,str):\n pass\n except Exception as e:\n pass\n stationary_result={}\n stats_model,n_lags,p_value,stationary_status=self.stationary_model(df,target_feature,stationary_check_method)\n # stationary_result[target_feature]=stationary_status\n stationary_result[target_feature]=stationary_status\n elif(len(target_feature) > 1):\n stationary_result={}\n for col in df.columns:\n stats_model,n_lags,p_value,stationary_status=self.stationary_model(df,col,stationary_check_method)\n stationary_result[col]=stationary_status \n else:\n pass\n stationary_val=None\n for v in stationary_result.values():\n stationary_val=v \n stationary_combined_res=dict()\n c_dict=[k for k,v in stationary_result.items() if 'non-stationary' in v]\n if (len(c_dict)>=1):\n stationary_combined_res['dataframe_stationarity']='Non-Stationary'\n else:\n stationary_combined_res['dataframe_stationarity']='Stationary'\n \n return stats_model,n_lags,p_value,stationary_val,stationary_combined_res\n #Get seasonality by using seasonal_decompose lib.\n def seasonality_model(self,target_feature,df):\n seasonality_status=None\n try:\n try:\n stats_model = kpss(df[target_feature])\n statistic, p_value, n_lags, critical_values=stats_model[0],stats_model[1],stats_model[2],stats_model[3]\n except:\n n_lags=1\n pass\n try:\n df_target=self.df[target_feature]\n decompose_result_mult = seasonal_decompose(df_target,model='additive', extrapolate_trend='freq', period=n_lags)\n except Exception as e:\n ##If additive model (type of seasonal component) failed, use multiplicative\n decompose_result_mult = seasonal_decompose(df_target,model='multiplicative', extrapolate_trend='freq', period=1)\n trend = decompose_result_mult.trend\n observed=decompose_result_mult.observed\n seasonal = decompose_result_mult.seasonal\n residual = decompose_result_mult.resid\n try:\n if isinstance(df_target, pd.Series):\n auto_correlation = df_target.autocorr(lag=n_lags)\n elif isinstance(df_target, pd.DataFrame):\n df_target = df_target.squeeze()\n auto_correlation = df_target.autocorr(lag=n_lags)\n except:\n pass\n if (seasonal.sum()==0):\n seasonality_status=\"Non-Seasonal\"\n else:\n seasonality_status=\"Seasonal\"\n\n # #Please use the below plot for GUI show (seasonality components)\n # decompose_result_mult.plot().savefig('seasonality_plot.png')\n df['observed'] = decompose_result_mult.observed\n df['residual'] = decompose_result_mult.resid\n df['seasonal'] = decompose_result_mult.seasonal\n df['trend'] = decompose_result_mult.trend\n \n except Exception as e:\n print(\"Seasonality function exception: \\\\t\",e)\n return df,decompose_result_mult,seasonality_status\n\n \n ##Main function to check seasonlity in data\n def seasonal_check(self,target_feature,time_col,seasonal_model):\n df=self.df\n try:\n df[time_col]=pd.to_datetime(df[time_col])\n except Exception as e:\n pass\n df=df.set_index(time_col)\n \n if (len(target_feature)==1):\n try:\n if isinstance(target_feature,list):\n target_feature=''.join(target_feature) \n elif isinstance(target_feature,int):\n target_feature=str(target_feature)\n elif isinstance(target_feature,str):\n pass\n except Exception as e:\n ## Because of EDA, all log messages removed. (self.log.info )\n pass\n ## Seasonal component for individual feature based.\n seasonality_result=dict()\n df,decompose_result_mult,seasonality_status = self.seasonality_model(target_feature,df)\n # seasonality_result[target_feature]=seasonality_status\n \n seasonality_result['Feature: '+str(target_feature)]=seasonality_status\n elif(len(target_feature) > 1):\n seasonality_result=dict()\n for col in df.columns:\n df,decompose_result_mult,seasonality_status = self.seasonality_model(col,df)\n seasonality_result[col]=seasonality_status\n else:\n pass\n\n \n # ## Seasonal component for whole dataset\n seasonality_val=None\n for v in seasonality_result.values():\n seasonality_val=v \n seasonality_combined_res=dict()\n c", "instruction": "", "output": "" }, { "input": "_dict=[k for k,v in seasonality_result.items() if 'non-seasonality' in v]\n if (len(c_dict)>=1):\n seasonality_combined_res['dataframe_seasonality']='No Seasonal elements'\n else:\n seasonality_combined_res['dataframe_seasonality']='contains seasonal elements.'\n \n return df,decompose_result_mult,seasonality_val,seasonality_combined_res\n \n #Main user defined caller for stationary and seasonality (SS) \n def analysis(self,seasonality_status,stationarity_status):\n seasonal_model=\"additive\"\n time_col=self.datetimefeature\n stationary_method='adfuller' \n if (isinstance(self.targetFeature,list)):\n target=self.targetFeature\n pass\n elif (isinstance(self.targetFeature,str)):\n target=list(self.targetFeature.split(','))\n if (stationarity_status.lower()==\"true\"):\n stats_model,n_lags,p_value,stationary_result,stationary_combined_res=self.stationary_check(target,time_col,stationary_method)\n return stationary_result\n if (seasonality_status.lower()==\"true\"):\n df,decompose_result_mult,seasonality_result,seasonality_combined_res=self.seasonal_check(target,time_col,seasonal_model)\n return seasonality_result\n \n \n#Main fn for standalone test purpose\nif __name__=='__main__':\n print(\"Inside seasonality-stationary test main function...\")\n print(\"Below code used for standalone test purpose.\")\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os.path\nimport time\nimport subprocess\nimport sys\nfrom appbe.aion_config import kafka_setting\nfrom appbe.aion_config import running_setting\nfrom appbe import installPackage\nfrom appbe import compute\nfrom appbe.models import getusercasestatus\nimport json\nimport pandas as pd\nimport ntpath\nimport shutil\nimport platform\nfrom pathlib import Path\nfrom appbe.dataPath import DATA_DIR\nLOG_FILE_PATH = os.path.join(DATA_DIR,'logs')\ndef encrptpackage_command(request,Existusecases,usecasedetails):\n command = request.POST.get('encryptedsubmit')\n \n kafkaSetting = kafka_setting()\n ruuningSetting = running_setting()\n computeinfrastructure = compute.readComputeConfig()\n modelID = request.POST.get('modelID')\n p = Existusecases.objects.get(id=modelID)\n usecasename = p.ModelName.UsecaseName\n usecaseid = p.ModelName.usecaseid\n runningStatus,pid,ip,port = installPackage.checkModelServiceRunning(usecasename)\n installationStatus,modelName,modelVersion=installPackage.checkInstalledPackge(usecasename)\n try:\n tacking_url =request.get_host()\n except Exception as e:\n tacking_url = '127.0.0.1' \n \n usecasedetail = usecasedetails.objects.get(id=p.ModelName.id)\n usecase = usecasedetails.objects.all()\n models = Existusecases.objects.filter(ModelName=usecasedetail,Status='SUCCESS')\n for model in models:\n model.scoringCreteria = 'NA'\n model.score = 'NA'\n model.deploymodel = 'NA'\n if os.path.isdir(str(model.DeployPath)):\n modelPath = os.path.join(str(model.DeployPath),'etc','output.json')\n try: \n with open(modelPath) as file:\n outputconfig = json.load(file)\n file.close()\n if outputconfig['status'] == 'SUCCESS':\n model.scoringCreteria = outputconfig['data']['ScoreType']\n model.score = outputconfig['data']['BestScore']\n model.deploymodel = outputconfig['data']['BestModel']\n model.modelType = outputconfig['data']['ModelType'] \n model.maacsupport = 'True'\n model.flserversupport = 'False'\n supportedmodels = [\"Logistic Regression\",\"Neural Network\",\"Linear Regression\"]\n if model.deploymodel in supportedmodels:\n model.flserversupport = 'True'\n else:\n model.flserversupport = 'False' \n supportedmodels = [\"Logistic Regression\",\n \"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)\"]\n if model.deploymodel in supportedmodels:\n model.maacsupport = 'True'\n else:\n model.maacsupport = 'False' \n supportedmodels = [\"Extreme Gradient Boosting (XGBoost)\"]\n if model.deploymodel in supportedmodels:\n model.encryptionsupport = 'True'\n else:\n model.encryptionsupport = 'False' \n except Exception as e: \n pass \n \n if command.lower() == 'secureclient':\n try:\n encryptedclient = os.path.join(str(p.DeployPath),'publish','SecureClient')\n shutil.rmtree(encryptedclient, ignore_errors=True)\n logPath = os.path.join(encryptedclient,'logs')\n scriptPath = os.path.join(encryptedclient,'script')\n modelPath = os.path.join(encryptedclient,'model')\n Path(modelPath).mkdir(parents=True, exist_ok=True) \n Path(encryptedclient).mkdir(parents=True, exist_ok=True)\n Path(logPath).mkdir(parents=True, exist_ok=True) \n Path(scriptPath).mkdir(parents=True, exist_ok=True)\n encryptedclientOrg = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','utilities','encryptedPackage')) \n modelProfiler = os.path.normpath(os.path.join(str(p.DeployPath),'script','inputprofiler.py'))\n modelselector = os.path.normpath(os.path.join(str(p.DeployPath),'aion_predict.py'))\n preprocessmodel = os.path.normpath(os.path.join(str(p.DeployPath),'model','preprocess_pipe.pkl'))\n # shutil.copy2(modelProfiler,scriptPath)\n # shutil.copy2(modelselector,scriptPath)\n ## For bug 15975\n if os.path.exists(modelProfiler):\n shutil.copy2(modelProfiler,scriptPath)\n if os.path.exists(modelselector):\n shutil.copy2(modelselector,scriptPath)\n if os.path.exists(preprocessmodel):\n shutil.copy2(preprocessmodel,modelPath)\n if model.modelType.lower() == 'classification':\n try:\n opfile = os.path.normpath(os.path.join(encryptedclientOrg,'Readme.txt')) \n shutil.copy2(opfile,encryptedclient)\n opfile = os.path.normpath(os.path.join(encryptedclientOrg,'requirements.txt')) \n shutil.copy2(opfile,encryptedclient)\n except:\n #failed to copy readme,requirements.txt files\n pass\n opfile = os.path.normpath(os.path.join(encryptedclientOrg,'client','heMulticlass.py')) \n shutil.copy2(opfile,scriptPath)\n opfile = os.path.normpath(os.path.join(encryptedclientOrg,'client','aion_hemulticlient.py')) \n shutil.copy2(opfile,encryptedclient)\n os.rename(os.path.join(encryptedclient,'aion_hemulticlient.py'),os.path.join(encryptedclient,'aion_sclient.py'))\n elif model.modelType.lower() == 'regression':\n try:\n opfile = os.path.normpath(os.path.join(encryptedclientOrg,'Readme.txt')) \n shutil.copy2(opfile,encryptedclient)\n opfile = os.path.normpath(os.path.join(encryptedclientOrg,'requirements.txt')) \n shutil.copy2(opfile,encryptedclient)\n except Exception as e:\n print(e)\n #failed to copy readme,requirements.txt files\n pass\n opfile = os.path.normpath(os.path.join(encryptedclientOrg,'client','heRegression.py')) \n shutil.copy2(opfile,scriptPath)\n opfile = os.path.normpath(os.path.join(encryptedclientOrg,'client','aion_heregressionclient.py')) \n shutil.copy2(opfile,encryptedclient)\n os.rename(os.path.join(encryptedclient,'aion_hemulticlient.py'),os.path.join(encryptedclient,'aion_sclient.py')) \n except Exception as e:\n Status = 'Error'\n Msg = 'Secure client error: Check log file for more details' \n Status = 'SUCCESS'\n Msg = 'Secure Client Code Generated at '+encryptedclient\n path= encryptedclient #Task 9981\n elif command.lower() == 'secureserver':\n try:\n configPath = os.path.join(str(p.DeployPath),'etc','secure_config.json')\n modelpath = usecasename+'_'+str(p.Version)+'.sav'\n config = {'model_name':modelpath}\n with open(configPath, \"w\") as outfile:\n json.dump(config, outfile)\n encryptedclientOrg = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','utilities','encryptedPackage')) \n if model.modelType.lower() == 'classification':\n opfile = os.path.normpath(os.path.join(encryptedclientOrg,'server','heMulticlass.py')) \n shutil.copy2(opfile,str(p.DeployPath))\n try:\n os.remove(os.path.join(str(p.DeployPath),'aion_spredict.py'))\n except OSError:\n pass\n os.rename(os.path.join(str(p.DeployPath),'heMulticlass.py'),os.path.join(str(p.DeployPath),'aion_spredict.py'))\n Status = 'SUCCESS'\n Msg = 'Secure rest end point enabled http://'+str(tacking_url)+'/api/spredict?usecaseid='+usecaseid+'&version='+str(p.Version)\n except Exception as e:\n Status = 'Error'\n Msg = 'Secure rest end point error: Check log file for more details'\n nouc = 0\n from appbe.pages import get_usecase_page \n status,context,action = get_usecase_page(request,usecasedetails,Existusecases) \n context['Status'] = Status \n context['Msg'] = Msg\n if command.lower() == 'secureclient': #Task 9981\n context['path'] = path\n '''\n selected_use_case,ModelVersion,ModelStatus = getusercasestatus(request)\n context = {'tab': 'upload','nouc':nouc,'usecasedetail': usecase, 'models': models, 'selected_use_case': selected_use_case,\n '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}\n '''\n return(context)\n\ndef download_sclient(request,context): #Task 9981\n import os\n from django.http import HttpResponse, Http404\n try:\n file_name = 'SecureClient_'+request.POST.get('modelsignature')\n path = context['path']\n file_path = shutil.make_archive(file_name, 'zip', path)\n if os.path.exists(file_path):\n with open(file_path, 'rb') as fh:\n response = HttpResponse(fh.read(),content_type='application/x-zip-compressed')\n response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)\n os.remove(file_path)\n return response\n except:\n raise Http404 '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os,sys\ndef read_service_url_params(request):\n hosturl =request.get_host()\n url='http://'+hosturl+'/api/' \n return url\n\ndef read_monitoring_service_url_params(request):\n hosturl =request.get_host()\n file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','config','aion.config'))\n file = open(file_path, \"r\")\n data = file.read()\n file.close()\n service_url = '127.0.0.1'\n service_port='60050'\n for line in data.splitlines():\n if 'aion_service_url=' in line:\n service_url= line.split('=',1)[1]\n if 'aion_service_port=' in line:\n service_port= line.split('=',1)[1]\n url='http://'+hosturl+'/api/' \n return url\n\ndef read_performance_service_url_params(request):\n hosturl =request.get_host()\n file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','config','aion.config'))\n file = open(file_path, \"r\")\n data = file.read()\n file.close()\n service_url = '127.0.0.1'\n service_port='60050'\n for line in data.splitlines():\n if 'aion_service_url=' in line:\n service_url= line.split('=',1)[1]\n if 'aion_service_port=' in line:\n service_port= line.split('=',1)[1]\n url='http://'+hosturl+'/api/' \n return url\n \ndef read_pattern_an", "instruction": "", "output": "" }, { "input": "omaly_url_params(request):\n hosturl =request.get_host()\n file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','config','aion.config'))\n file = open(file_path, \"r\")\n data = file.read()\n file.close()\n service_url = '127.0.0.1'\n service_port='60050'\n for line in data.splitlines():\n if 'aion_service_url=' in line:\n service_url= line.split('=',1)[1]\n if 'aion_service_port=' in line:\n service_port= line.split('=',1)[1]\n url='http://'+hosturl+'/api/pattern_anomaly_predict/' \n return url\n\ndef read_pattern_anomaly_setting_url_params(request):\n hosturl =request.get_host()\n file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','config','aion.config'))\n file = open(file_path, \"r\")\n data = file.read()\n file.close()\n service_url = '127.0.0.1'\n service_port='60050'\n for line in data.splitlines():\n if 'aion_service_url=' in line:\n service_url= line.split('=',1)[1]\n if 'aion_service_port=' in line:\n service_port= line.split('=',1)[1]\n url='http://'+hosturl+'/api/pattern_anomaly_settings/' \n return url '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport numpy as np\nimport os\nimport sys\nimport scipy.stats as st\n\ndef DistributionFinder(data):\n try:\n distributionName = \"\"\n sse = 0.0\n KStestStatic = 0.0\n dataType = \"\"\n if (data.dtype == \"float64\"):\n dataType = \"Continuous\"\n elif (data.dtype == \"int\"):\n dataType = \"Discrete\"\n elif (data.dtype == \"int64\"):\n dataType = \"Discrete\"\n if (dataType == \"Discrete\"):\n distributions = [st.bernoulli, st.binom, st.geom, st.nbinom, st.poisson]\n index, counts = np.unique(data.astype(int), return_counts=True)\n\n if (len(index) >= 2):\n best_sse = np.inf\n y1 = []\n total = sum(counts)\n mean = float(sum(index * counts)) / total\n variance = float((sum(index ** 2 * counts) - total * mean ** 2)) / (total - 1)\n dispersion = mean / float(variance)\n theta = 1 / float(dispersion)\n r = mean * (float(theta) / 1 - theta)\n\n for j in counts:\n y1.append(float(j) / total)\n\n pmf1 = st.bernoulli.pmf(index, mean)\n pmf2 = st.binom.pmf(index, len(index), p=mean / len(index))\n pmf3 = st.geom.pmf(index, 1 / float(1 + mean))\n pmf4 = st.nbinom.pmf(index, mean, r)\n pmf5 = st.poisson.pmf(index, mean)\n\n sse1 = np.sum(np.power(y1 - pmf1, 2.0))\n sse2 = np.sum(np.power(y1 - pmf2, 2.0))\n sse3 = np.sum(np.power(y1 - pmf3, 2.0))\n sse4 = np.sum(np.power(y1 - pmf4, 2.0))\n sse5 = np.sum(np.power(y1 - pmf5, 2.0))\n\n sselist = [sse1, sse2, sse3, sse4, sse5]\n best_distribution = 'NA'\n for i in range(0, len(sselist)):\n if best_sse > sselist[i] > 0:\n best_distribution = distributions[i].name\n best_sse = sselist[i]\n\n elif (len(index) == 1):\n best_distribution = \"Constant Data-No Distribution\"\n best_sse = 0.0\n\n distributionName = best_distribution\n sse = best_sse\n\n elif (dataType == \"Continuous\"):\n\n distributions = [st.uniform, st.expon, st.weibull_max, st.weibull_min, st.chi, st.norm, st.lognorm, st.t,\n st.gamma, st.beta]\n best_distribution = st.norm.name\n best_sse = np.inf\n datamin = data.min()\n datamax = data.max()\n nrange = datamax - datamin\n\n y, x = np.histogram(data.astype(float), bins='auto', density=True)\n x = (x + np.roll(x, -1))[:-1] / 2.0\n\n for distribution in distributions:\n params = distribution.fit(data.astype(float))\n arg = params[:-2]\n loc = params[-2]\n scale = params[-1]\n pdf = distribution.pdf(x, loc=loc, scale=scale, *arg)\n sse = np.sum(np.power(y - pdf, 2.0))\n if (best_sse > sse > 0):\n best_distribution = distribution.name\n best_sse = sse\n distributionName = best_distribution\n sse = best_sse\n except:\n response = str(sys.exc_info()[0])\n message = 'Job has Failed' + response\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type) + ' ' + str(fname) + ' ' + str(exc_tb.tb_lineno))\n print(message)\n return distributionName, sse '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n''' '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport random\nimport string\nfrom sklearn import datasets\nimport pandas as pd\nimport names # pip install names\nimport time\nimport numpy as np\nimport argparse\nimport json\nimport os\nimport platform\nimport time\nimport sys\nfrom appbe.dataPath import CONFIG_FILE_PATH\n\ndef randStr(chars = 'XYZABCDE', N=2):\n return ''.join(random.choice(chars) for _ in range(N))\n\ndef load_json_config(file):\n\n with open(file, 'r') as openfile: \n\n json_object = json.load(openfile)\n\n for key, value in json_object.items():\n print(key, value)\n\n return json_object\n \n \ndef gen_data_classification(number_samples=10000, number_numerical_features=25,\n file_name='file_class.csv', number_categorical_features=2,\n number_text_features=2,\n missing_proportion=0.1,\n number_informative=20, number_class=2,\n weights=[0.5,0.5], shift=0.0,\n value_range_dict={0:(1, 2)}):\n\n # TO-DO: need to add min max vlinear/non-linear\n try:\n features, output = datasets.make_classification(\n n_samples=number_samples,\n n_features=number_numerical_features,\n n_informative=number_informative,\n n_classes=number_class,\n weights = weights, # 20% of the targets will be 0, 80% will be 1. default is 50/50\n shift=shift,\n\n )\n\n columns = []\n\n # Numerical Features\n for i in range(number_numerical_features):\n columns.append('Feature_' + str(i))\n\n features = pd.DataFrame(features, columns=columns)\n\n # Setting min max value for features\n for col_name in features.columns:\n for key, value in value_range_dict.items():\n if (str(features.columns.get_loc(col_name)) == key):\n for item in features[col_name].values:\n if item < value[0]:\n features.loc[features[col_name] == item,\n col_name] = random.uniform(value[0],value[1])\n if item > value[1]:\n features.loc[features[col_name] == item,\n col_name] = random.uniform(value[0],value[1])\n\n df_list = []\n df_list.append(features)\n\n # Add Categorical Features\n for j in range(number_categorical_features):\n categorical_feature1_list = []\n number_categories_per_feature = random.randint(2, 5)\n for i in range(number_categories_per_feature):\n categorical_feature1_list.append(randStr(N=3))\n print(\"Categories of Categorical Feature \" + str(j) + \": \", categorical_feature1_list)\n categorical_feature1 = []\n for k in range(number_samples):\n categorical_feature1.append(random.choice(categorical_feature1_list))\n\n categorical_feature1 = pd.DataFrame(categorical_feature1, columns=['Categorical'+str(j)])\n df_list.append(categorical_feature1)\n\n # Add Text Features\n for l in range(number_text_features):\n text_feature = []\n for k in range(number_samples):\n text_feature.append(names.get_full_name())\n # text_feature.append(r.get_random_word())\n text_feature = pd.DataFrame(text_feature, columns=['Name'+str(l)])\n # text_feature = pd.DataFrame(text_feature, columns=['Word' + str(l)])\n df_list.append(text_feature)\n\n output = pd.DataFrame(output, columns=['Target'])\n df_list.append(output)\n df_final = pd.concat(df_list, axis=1)\n\n for col in df_final.columns:\n # df_final.loc[df_final.sample(frac=0.1).index, col] = np.NaN\n df_final.loc[df_final[col].sample(frac=missing_proportion).index, col] = np.NaN\n # Check to see proportion of NaN values:\n # df.isnull().sum() / len(df)\n\n df_final.to_csv(file_name)\n return True\n except Exception as e:\n print(e)\n return False\n\ndef gen_data_regression(\n number_samples=10000, number_numerical_features=25,\n file_name='file_regress.csv', number_categorical_features=2,\n number_text_features=2,\n missing_proportion=0.1,\n number_informative=10,\n number_target=1, bias=0.0, noise=0.0,\n value_range_dict={1:(5, 10)}\n ):\n try:\n features, output = datasets.make_regression(\n n_samples=number_samples,\n n_features=number_numerical_features,\n n_informative=number_informative,\n n_targets=number_target,\n bias=bias,\n noise=noise,\n\n )\n\n columns = []\n for i in range(number_numerical_features):\n columns.append('Feature_' + str(i))\n features = pd.DataFrame(features, columns=columns)\n\n for col_name in features.columns:\n for key, value in value_range_dict.items():\n if (str(features.columns.get_loc(col_name)) == key):\n for item in features[col_name].values:\n if item < value[0]:\n features.loc[features[col_name] == item,\n col_name] = random.uniform(value[0],value[1])\n if item > value[1]:\n features.loc[features[col_name] == item,\n col_name] = random.uniform(value[0],value[1])\n\n df_list = []\n df_list.append(features)\n\n for j in range(number_categorical_features):\n categorical_feature1_list = []\n number_categories_per_feature = random.randint(2, 5)\n for i in range(number_categories_per_feature):\n categorical_feature1_list.append(randStr(N=3))\n print(\"Categories of Categorical Feature \" + str(j) + \": \", categorical_feature1_list)\n categorical_feature1 = []\n for k in range(number_samples):\n categorical_feature1.append(random.choice(categorical_feature1_list))\n\n categorical_feature1 = pd.DataFrame(categorical_feature1, columns=['Categorical' + str(j)])\n df_list.append(categorical_feature1)\n\n for l in range(number_text_features):\n text_feature = []\n for k in range(number_samples):\n text_feature.append(names.get_full_name())\n text_feature = pd.DataFrame(text_feature, columns=['Name'+str(l)])\n df_list.append(text_feature)\n\n output = pd.DataFrame(output, columns=['Target'])\n df_list.append(output)\n df_final = pd.concat(df_list, axis=1)\n\n for col in df_final.columns:\n # df_final.loc[df_final.sample(frac=0.1).index, col] = np.NaN\n df_final.loc[df_final[col].sample(frac=missing_proportion).index, col] = np.NaN\n # Check to see proportion of NaN values:\n # df.isnull().sum() / len(df)\n df_final.to_csv(file_name)\n", "instruction": "", "output": "" }, { "input": " return True\n except Exception as e:\n print(e)\n return False\n\ndef gen_data_series(univariate=\"True\",\n start_time='2000-01-01 00:00',\n end_time='2022-12-31 00:00',\n number_samples=10000, number_numerical_features=25,\n file_name='file_regress.csv', number_categorical_features=2,\n # number_text_features=2,\n missing_proportion=0.1,\n number_informative=10,\n number_target=1, bias=0.0, noise=0.0,\n value_range_dict={1:(5, 10)}\n ):\n try:\n if univariate == \"True\":\n number_numerical_features = 1\n number_categorical_features = 0\n\n features, output = datasets.make_regression(\n n_samples=number_samples,\n n_features=number_numerical_features,\n n_informative=number_informative,\n n_targets=number_target,\n bias=bias,\n noise=noise,\n )\n\n columns = []\n\n # Numerical Features\n for i in range(number_numerical_features):\n columns.append('Feature_' + str(i))\n\n features = pd.DataFrame(features, columns=columns)\n\n # Setting min max value for features\n for col_name in features.columns:\n for key, value in value_range_dict.items():\n if (str(features.columns.get_loc(col_name)) == key):\n for item in features[col_name].values:\n if item < value[0]:\n features.loc[features[col_name] == item,\n col_name] = random.uniform(value[0],value[1])\n if item > value[1]:\n features.loc[features[col_name] == item,\n col_name] = random.uniform(value[0],value[1])\n\n df_list = []\n df_list.append(features)\n\n # Add Categorical Features\n for j in range(number_categorical_features):\n categorical_feature1_list = []\n number_categories_per_feature = random.randint(2, 5)\n for i in range(number_categories_per_feature):\n categorical_feature1_list.append(randStr(N=3))\n print(\"Categories of Categorical Feature \" + str(j) + \": \", categorical_feature1_list)\n categorical_feature1 = []\n for k in range(number_samples):\n categorical_feature1.append(random.choice(categorical_feature1_list))\n\n categorical_feature1 = pd.DataFrame(categorical_feature1, columns=['Categorical'+str(j)])\n df_list.append(categorical_feature1)\n\n # df2['date'] = pd.date_range(start='1890-01-01', freq=\"sec\",periods=len(df2))\n time_feature = pd.date_range(start=start_time, end=end_time, periods=number_samples) #freq=\"1sec\"\n time_feature = pd.DataFrame(time_feature, columns=['Date'])\n # df_list.append(time_feature)\n df_list.insert(0, time_feature)\n output = pd.DataFrame(output, columns=['Feature_' + str(number_numerical_features)])\n if univariate != \"True\":\n df_list.append(output)\n df_final = pd.concat(df_list, axis=1)\n\n for col in df_final.columns:\n # df_final.loc[df_final.sample(frac=0.1).index, col] = np.NaN\n df_final.loc[df_final[col].sample(frac=missing_proportion).index, col] = np.NaN\n\n # Check to see proportion of NaN values:\n # df.isnull().sum() / len(df)\n\n df_final.to_csv(file_name)\n return True\n except Exception as e:\n print(e)\n return False\n\ndef data_generated_csv():\n\n datajson = os.path.join(CONFIG_FILE_PATH, 'data_generated.json')\n with open(datajson, 'r+') as f:\n dictionary = json.load(f)\n# f.close()\n\n\n if dictionary.get('problemType') == 'classification':\n number_samples = dictionary.get(\"number_samples\")\n number_numerical_features = dictionary.get(\"number_numerical_features\")\n number_categorical_features = dictionary.get(\"number_categorical_features\")\n number_text_features = dictionary.get(\"number_text_features\")\n missing_proportion = dictionary.get(\"missing_proportion\")\n number_informative = dictionary.get(\"number_informative\")\n number_class = dictionary.get(\"number_class\")\n weights = dictionary.get(\"weights\")\n shift = dictionary.get(\"shift\")\n data_path = dictionary.get(\"data_path\")\n value_range_dict = dictionary.get(\"value_range_dict\")\n\n gen_data_classification(number_samples=number_samples, \n number_numerical_features=number_numerical_features,\n file_name=data_path,\n number_categorical_features=number_categorical_features,\n number_text_features=number_text_features,\n missing_proportion=missing_proportion,\n number_informative=number_informative,\n number_class=number_class, weights=weights,\n shift=shift, value_range_dict=value_range_dict)\n\n elif dictionary.get('problemType') == 'regression':\n number_samples = dictionary.get(\"number_samples\")\n number_numerical_features = dictionary.get(\"number_numerical_features\")\n number_categorical_features = dictionary.get(\"number_categorical_features\")\n number_text_features = dictionary.get(\"number_text_features\")\n missing_proportion = dictionary.get(\"missing_proportion\")\n number_informative = dictionary.get(\"number_informative\")\n number_target = dictionary.get(\"number_target\")\n bias = dictionary.get(\"bias\")\n noise = dictionary.get(\"noise\")\n data_path = dictionary.get(\"data_path\")\n value_range_dict = dictionary.get(\"value_range_dict\")\n\n gen_data_regression(number_samples=number_samples,\n number_numerical_features=number_numerical_features,\n file_name=data_path,\n number_categorical_features=number_categorical_features,\n number_text_features=number_text_features,\n missing_proportion=missing_proportion,\n number_informative=number_informative,\n number_target=number_target, bias=bias,\n noise=noise, value_range_dict=value_range_dict)\n \n elif dictionary.get('problemType') == 'timeseriesforecasting': #task 11997\n data_path = dictionary.get(\"data_path\")\n is_univariate = dictionary.get(\"univariate\")\n number_samples = dictionary.get(\"number_samples\")\n number_numerical_features = dictionary.get(\"number_numerical_features\")\n number_categorical_features = dictionary.get(\"number_categorical_features\")\n missing_proportion = dictionary.get(\"missing_proportion\")\n number_informative = dictionary.get(\"number_informative\")\n number_target = dictionary.get(\"number_target\")\n bias = dictionary.get(\"bias\")\n noise = dictionary.get(\"noise\")\n value_range_dict = dictionary.get(\"value_range_dict\")\n gen_data_series(univariate=is_univariate,\n number_samples=number_samples, \n number_numerical_features=number_numerical_features,\n file_name=data_path, \n number_categorical_features=number_categorical_features,\n # number_text_features=2,\n missing_proportion=missing_proportion,\n number_informative=number_informative,\n number_target=number_target, bias=bias, \n noise=noise,\n value_range_dict=value_range_dict)\n\n\nif __name__ == \"__main__\":\n data_generated_csv()\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport json\nimport os\nimport rsa\nimport boto3 #usnish\nimport pandas as pd\nimport time\ndef add_new_azureStorage(request):\n\ttry:\n\t\tfile_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','azurestorage.conf'))\n\t\twith open(file_path, 'r') as f:\n\t\t\tdata = json.load(f)\n\t\tf.close()\t\t\n\t\tif data == '':\n\t\t\tdata = []\t\t\n\texcept:\n\t\tdata = []\n\tif request.POST[\"azurename\"] =='' or request.POST[\"azureaccountkey\"] == '' or request.POST[\"containername\"] == '' :\n\t\treturn 'error'\n\tnewdata = {} \n\tnewdata['azurename'] = request.POST[\"azurename\"]\n\tnewdata['azureaccountkey'] = request.POST[\"azureaccountkey\"]\n\tnewdata['containername'] = request.POST[\"containername\"]\n\tdata.append(newdata)\n\twith open(file_path, 'w') as f:\n\t\tjson.dump(data, f)\n\tf.close()\n\treturn 'success'\n\ndef get_azureStorage():\n\ttry:\n\t\tfile_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','azurestorage.conf'))\n\t\twith open(file_path, 'r') as f:\n\t\t\tdata = json.load(f)\n\texcept:\n\t\tdata = []\n\treturn data\ndef read_azureStorage(name,directoryname,DATA_FILE_PATH):\n\ttry:\n\t\tfile_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','azurestorage.conf'))\n\t\twith open(file_path, 'r') as f:\n\t\t\tdata = json.load(f)\n\texcept:\n\t\tdata = []\n\tfound = False\n\tfor x in data:\n\t\tif x['azurename'] == name:\n\t\t\tstorage_account_name = str(x['azurename'])\n\t\t\tstorage_account_key = str(x['azureaccountkey'])\n\t\t\tazure_container_name = x['containername']\n\t\t\tfound = True\n\t\t\tbreak\t\t\n\ttry:\n\t\tif found:\n\t\t\troot_dir = str(directoryname)\n\t\t\tfrom azure.storage.filedatalake import DataLakeServiceClient\n\t\t\timport io\n\t\t\timport pandavro as pdx\n\t\t\tfrom detect_delimiter import detect\t\t\t\n\t\t\ttry:\n\t\t\t\tservice_client = DataLakeServiceClient(account_url=\"{}://{}.dfs.core.windows.net\".format(\"https\", storage_account_name), credential=storage_account_key)\n\t\t\t\tprint(azure_container_name)\n\t\t\t\tfile_system_client = service_client.get_file_system_client(azure_container_name)\n\t\t\t\tprint(root_dir)\n\t\t\t\tfile_paths = file_system_client.get_paths(path=root_dir)\t\t\t\t\n\t\t\t\tmain_df = pd.DataFrame()\n\t\t\t\tfor path in file_paths:\n\t\t\t\t\tif not path.is_directory:\n\t\t\t\t\t\tfile_client = file_system_client.get_file_client(path.name)\n\t\t\t\t\t\tfile_ext = os.path.basename(path.name).split('.', 1)[1]\n\t\t\t\t\t\tif file_ext in [\"csv\", \"tsv\"]:\n\t\t\t\t\t\t\twith open(csv_local, \"wb\") as my_file:\n\t\t\t\t\t\t\t\tdownload = file_client.download_file()\n\t\t\t\t\t\t\t\tdownload.readinto(my_file)\n\t\t\t\t\t\t\twith open(csv_local, 'r') as file:\n\t\t\t\t\t\t\t\tdata = file.read()\n\t\t\t\t\t\t\trow_delimiter = detect(text=data, default=None, whitelist=[',', ';', ':', '|', '\\\\t'])\n\t\t\t\t\t\t\tprocessed_df = pd.read_csv(csv_local, sep=row_delimiter)\n\t\t\t\t\t\tif file_ext == \"parquet\":\n\t\t\t\t\t\t\tdownload = file_client.download_file()\n\t\t\t\t\t\t\tstream = io.BytesIO()\n\t\t\t\t\t\t\tdownload.readinto(stream)\n\t\t\t\t\t\t\tprocessed_df = pd.read_parquet(stream, engine='pyarrow')\n\t\t\t\t\t\tif file_ext == \"avro\": \n\t\t\t\t\t\t\twith open(avro_local, \"wb\") as my_file:\n\t\t\t\t\t\t\t\tdownload = file_client.download_file()\n\t\t\t\t\t\t\t\tdownload.readinto(my_file)\n\t\t\t\t\t\t\tprocessed_df = pdx.read_avro(avro_local)\n\t\t\t\t\t\tif not main_df.empty:\n\t\t\t\t\t\t\tmain_df = main_df.append(processed_df, ignore_index=True)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tmain_df = pd.DataFrame(processed_df)\t\t\t\n\t\t\texcept Exception as e:\n\t\t\t\tprint(e)\n\t\t\treturn 'Success',main_df\n\texcept Exception as e:\n\t\tprint(e)\n\treturn 'Error', pd.DataFrame() '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport pyodbc as pyodbc\nimport pandas as pd\nimport json\nimport sqlalchemy as db\nimport pandas as pd\nimport urllib\n\n\ndef get_connection(request):\n\tdbType = request.session['dbType']\n\tconnection_string = \"\"\n\tif dbType.lower()==\"sqlite\":\n\t\tfilepath = request.session['filepath']\n\t\t#table = request.session[\"tablenamesql\"]\n\t\tconnection_string = \"sqlite:///\"+str(filepath)\n\telif dbType.lower() in [\"postgresql\",\"mysql\",\"mssql\"]:\n\t\tdb_name = request.session['dbname'] \n\t\tpassword = request.session['password'] \n\t\tuser = request.session['username'] \n\t\tport = request.session['port'] \n\t\thost = request.session['host']\n", "instruction": "", "output": "" }, { "input": "\t\tpassword=urllib.parse.quote_plus(password)\n\t\tif dbType.lower()==\"postgresql\":\n\t\t\tconnection_string = \"postgresql+psycopg2://\" + user + \":\" + password + \"@\" + host + \":\" + port + \"/\" + db_name\n\t\tif dbType.lower()==\"mysql\":\n\t\t\tconnection_string = \"mysql+pyodbc://\" + user + \":\" + password + \"@\" + host + \":\" + port + \"/\" + db_name\n\t\tif dbType.lower()==\"mssql\":\n\t\t\tdriver=request.session['driver']\n\t\t\tparams = urllib.parse.quote_plus(\n\t\t\t\t\t\t'Driver=%s;' % driver +\n\t\t\t\t\t\t'Server=tcp:%s,' % host +\n\t\t\t\t\t\t'%s;' % port + \n\t\t\t\t\t\t'Database=%s;' % db_name +\n\t\t\t\t\t\t'Uid=%s;' % user +\n\t\t\t\t\t\t'Pwd={%s};' % password +\n\t\t\t\t\t\t'Encrypt=yes;' +\n\t\t\t\t\t\t'TrustServerCertificate=no;' +\n\t\t\t\t\t\t'Connection Timeout=30;')\n\n\t\t\tconnection_string = 'mssql+pyodbc:///?odbc_connect=' + params\n\treturn connection_string\ndef list_tables(request):\n\tconnection_string = get_connection(request)\n\t\n\tengine = db.create_engine(connection_string)\n\tconnection = engine.connect()\n\tmetadata = db.MetaData()\n\tmetadata.reflect(engine)\n\tdt_list = []\n\ttry:\n\t\tdt_list= list(metadata.tables.keys())\n\t\tprint(dt_list)\n\t\treturn dt_list\n\texcept:\n\t\tprint(\"Something went wrong\")\n\t\treturn dt_list\n\ndef list_tables_fields(request,table_list):\n\tconnection_string = get_connection(request)\n\tengine = db.create_engine(connection_string)\n\tconnection = engine.connect()\n\tmetadata = db.MetaData()\n\tmetadata.reflect(engine)\n\ttable_field_obj = {}\n\ttable_field_obj['data'] = []\n\ttry:\n\t\t# filepath = request.session['filepath']\n\t\t#table = request.session[\"tablenamesql\"]\n\t\t\n\t\ttable_list = json.loads(table_list)\n\t\tfor table in table_list:\n\t\t\ttf_obj = {}\n\t\t\ttf_obj['TableName'] = str(table).strip()\n\t\t\ttf_obj['Fields']= []\n\n\t\t\ttable = db.Table(table, metadata, autoload=True, autoload_with=engine)\n\t\t\tcol = table.columns.keys()\n\t\t\ttempdata = []\n\t\t\tfor x in col:\n\t\t\t\tmy_list = {\"column_name\": x,\"is_select\":\"false\"}\n\t\t\t\ttempdata.append(my_list)\n\t\t\t\n\t\t\ttf_obj['Fields'] = tempdata\n\t\t\ttable_field_obj['data'].append(tf_obj)\n\t\treturn json.dumps(table_field_obj)\n\texcept Exception as e:\n\t\tprint(\"Something went wrong \"+str(e))\n\t\treturn table_field_obj\n\ndef get_data(connection_string,table):\n\tengine = db.create_engine(connection_string)\n\tconnection = engine.connect()\n\tmetadata = db.MetaData()\n\tmetadata.reflect(engine)\n\ttable = db.Table(table,metadata, autoload=True, autoload_with=engine)\n\tquery = db.select([table])\n\tResultProxy = connection.execute(query)\n\tResultSet = ResultProxy.fetchall()\n\tcol = table.columns.keys()\n\treturn pd.DataFrame(ResultSet, columns=col)\n\ndef getDataFromSingleTable(request):\n\t\n\tdbType = request.session['dbType']\n\tif dbType.lower() == \"sqlite\":\n\t\ttable = request.session[\"tablenamesql\"]\n\telse:\n\t\ttable = request.session[\"tablename\"]\n\tconnection_string = get_connection(request)\n\tdf = get_data(connection_string,table)\n\treturn df\n\t\ndef validatequery(request,table_details,join_details,where_details):\n\tresultdata = []\n\ttry:\n\t\ttable_details = json.loads(table_details)\n\t\tjoin_details = json.loads(join_details)\n\t\twhere_details = json.loads(where_details)\n\t\tconnection_string = get_connection(request)\n\t\tengine = db.create_engine(connection_string)\n\t\tconnection = engine.connect()\n\t\tmetadata = db.MetaData()\n\t\tmetadata.reflect(engine)\n\t\tsel_col = []\n\t\tfor item in table_details:\n\t\t\ttable = item[\"TableName\"]\n\t\t\ttable = db.Table(table, metadata, autoload=True, autoload_with=engine)\n\t\t\tfor ele in item[\"Fields\"]:\n\t\t\t\tif str(ele[\"is_select\"]).lower() == 'true':\n\t\t\t\t\tsel_col.append(table.columns[ele[\"column_name\"]])\n\t\t\n\t\tjoin_condition = []\n\t\twhere_clause = \"\"\n\t\tfor item in join_details:\n\t\t\ttable1 = item[\"Table1Name\"]\n\t\t\ttable1 = db.Table(table1, metadata, autoload=True, autoload_with=engine)\n\t\t\tleft_join = table1.columns[item[\"Table1Field\"]]\n\t\t\ttable2 = item[\"Table2Name\"]\n\t\t\ttable2 = db.Table(table2, metadata, autoload=True, autoload_with=engine)\n\t\t\tright_join = table2.columns[item[\"Table2Field\"]]\n\t\t\tjoin_condition = \"{left_join} {Condition}= {right_join}\".format(left_join=left_join,\n\t\t\t\t\t\t\t Condition=item[\"Condition\"],right_join= right_join)\n\t\t'''dbType = request.session['dbType']\n\t\tif dbType.lower()==\"sqlite\":\n\t\t\tfor item in where_details:\n\t\t\t\twhere_clause = \"{table}.'{column}'{condition}{value}\".format(table=item[\"TableName\"],column=str(item[\"FieldName\"]),condition=item[\"Condition\"],value=item[\"CompareValue\"])\n\t\t\t\n\t\tif dbType.lower()==\"postgresql\":\n\t\t\tfor item in where_details:\n \n\t\t\t\twhere_clause = \"{table}.{column}{condition}{value}\".format(table=item[\"TableName\"],column=str(item[\"FieldName\"]),condition=item[\"Condition\"],value=item[\"CompareValue\"])\n \n\t\t'''\n \n\t\tif len(join_details)!=0:\n\t\t\ttry:\n\t\t\t\tfor item in where_details:\n\t\t\t\t\twhere_clause = \"{table}.'{column}'{condition}{value}\".format(table=item[\"TableName\"],column=str(item[\"FieldName\"]),condition=item[\"Condition\"],value=item[\"CompareValue\"])\n\t\t\t\t\t\n\t\t\t\tquery =db.select(sel_col).\\\\\n\t\t\t\t\tselect_from(table1.join(table2,db.text(join_condition))). \\\\\n\t\t\t\t\twhere(db.and_(db.text(where_clause)))\n\t\t\t\tResultProxy = connection.execute(query)\n\t\t\t\tResultSet = ResultProxy.fetchall()\n\t\t\texcept:\n\t\t\t\tfor item in where_details:\n\t\t\t\t\twhere_clause = \"{table}.{column}{condition}{value}\".format(table=item[\"TableName\"],column=str(item[\"FieldName\"]),condition=item[\"Condition\"],value=item[\"CompareValue\"])\n\t\t\t\t\t\n\t\t\t\tquery =db.select(sel_col).\\\\\n\t\t\t\t\tselect_from(table1.join(table2,db.text(join_condition))). \\\\\n\t\t\t\t\twhere(db.and_(db.text(where_clause)))\n\t\t\t\tResultProxy = connection.execute(query)\n\t\t\t\tResultSet = ResultProxy.fetchall()\n \n\t\telse:\n\t\t\ttable = table_details[0][\"TableName\"]\n\t\t\ttable = db.Table(table, metadata, autoload=True, autoload_with=engine)\n\t\t\ttry:\n\t\t\t\tfor item in where_details:\n\t\t\t\t\twhere_clause = \"{table}.'{column}'{condition}{value}\".format(table=item[\"TableName\"],column=str(item[\"FieldName\"]),condition=item[\"Condition\"],value=item[\"CompareValue\"])\n\t\t\t\tquery = db.select(sel_col). \\\\\n\t\t\t\t\tselect_from(table). \\\\\n\t\t\t\t\twhere(db.and_(db.text(where_clause)))\n\t\t\t\tResultProxy = connection.execute(query)\n\t\t\t\tResultSet = ResultProxy.fetchall()\n\t\t\texcept:\n\t\t\t\tfor item in where_details:\n\t\t\t\t\twhere_clause = \"{table}.{column}{condition}{value}\".format(table=item[\"TableName\"],column=str(item[\"FieldName\"]),condition=item[\"Condition\"],value=item[\"CompareValue\"])\n\t\t\t\tquery = db.select(sel_col). \\\\\n\t\t\t\t\tselect_from(table). \\\\\n\t\t\t\t\twhere(db.and_(db.text(where_clause)))\n\t\t\t\tResultProxy = connection.execute(query)\n\t\t\t\tResultSet = ResultProxy.fetchall()\n\t\t\n\t\t\n\t\tif len(ResultSet) > 0:\n\t\t\tdata = pd.DataFrame(ResultSet)\n\t\t\tdata.columns = ResultSet[0].keys()\n\t\t\tprint(data)\n\t\t\treturn data,\"query exectuted successfully\"\n\t\telse:\n\t\t\treturn pd.DataFrame(),\"No rows returned\"\n\t\t\n\t\t# conn = get_connection(server_url,username_actian,password_actian,database_actian)\n\t\t# sql_text = query\n\t\t# cur = conn.cursor()\n\t\t# resultdata = simple_select(cur, query)\n\t\t# cur.close()\n\t\t#df = pd.DataFrame(resultdata)\n\t\t#print(df)\n\n\texcept Exception as e:\n\t\tprint(e)\n\t\treturn pd.DataFrame(), str(e)\t '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nfrom appbe.data_io import sqlite_db\nfrom os.path import expanduser\nimport platform\nimport pandas as pd\nimport os\nfrom appbe.dataPath import DATA_DIR\nPUBLISH_PATH = os.path.join(DATA_DIR,'publish')\t\nDEPLOY_DATABASE_PATH = os.path.join(DATA_DIR,'sqlite') \n\ndef chech_publish_info(usecasename):\n version = 0\n status = 'Not Published'\n inputDriftStatus = 'No Drift'\n MODEL_DEPLOY_DATABASE_PATH = os.path.join(PUBLISH_PATH,usecasename,'database') \n sqlite_dbObj = sqlite_db(DEPLOY_DATABASE_PATH,'deploy.db') \n if sqlite_dbObj.table_exists('publish'): \n data = sqlite_dbObj.read('publish',\"usecase = '\"+usecasename+\"' and status = 'Published'\")\n if data.shape[0] > 0:\n model_sqlite_dbObj = sqlite_db(MODEL_DEPLOY_DATABASE_PATH,'deploy.db')\n version = data['version'].iloc[0]\n status = 'Published'\n if model_sqlite_dbObj.table_exists('monitoring'):\n data = model_sqlite_dbObj.read('monitoring',\"version = '\"+str(version)+\"'\")\n if data.shape[0] > 0: \n msg = data['Msg'].iloc[-1]\n if 'Affected Columns' in msg:\n inputDriftStatus = 'Input Drift Found'\n return version,status,inputDriftStatus\n\ndef check_input_data(usecasename):\n MODEL_DEPLOY_DATABASE_PATH = os.path.join(PUBLISH_PATH,usecasename,'database') \n sqlite_dbObj = sqlite_db(DEPLOY_DATABASE_PATH,'deploy.db') \n data = pd.DataFrame()\n if sqlite_dbObj.table_exists('publish'): \n dataa = sqlite_dbObj.read('publish',\"usecase = '\"+usecasename+\"' and status = 'Published'\")\n if dataa.shape[0] > 0: \n modelsqlite_dbObj = sqlite_db(MODEL_DEPLOY_DATABASE_PATH,'deploy.db')\n if modelsqlite_dbObj.table_exists('prodData'):\n data = modelsqlite_dbObj.read('prodData')\n return data\n # -*- coding: utf-8 -*-\n\nimport os\n# import glob\nfrom glob import glob\nimport ast\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport numpy as np\nimport pandas as pd\nimport json\nimport time\nimport logging\nfrom datetime import datetime\n\n\"\"\" Code clone detection based on user input files. \"\"\"\nclass codeCloneDetectionSklearn:\n \"\"\" Detect code clones based on sklearn text vectorizer modules.\n Input params: files_dir: python files folder,\n deply_dir: logs,resultant dataframe stored location.\n chunk_size: max size split for the input text or code function.\n return values: report_dict which contains clone type, path and clones. \"\"\"\n def __init__(self,files_dir,deploy_dir, chunk_size):\n self.files_dir = files_dir\n self.deploy_dir = deploy_dir\n self.chunk_size = chunk_size\n try:\n self.ccdreportpath = os.path.join(self.deploy_dir, \"codeCloneReport\")\n os.makedirs(self.ccdreportpath, exist_ok = True)\n except OSError as error:\n print(\"Directory 'codeCloneReport' cann't be created.Error msg: \",error)\n \n try: \n current_datetime = datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n str_current_datetime = str(current_datetime)\n log_file_name = 'codeclonelog_sklearn'+f\"_{str_current_datetime}\"+\".log\"\n logpath = os.path.join(self.ccdreportpath,log_file_name)\n logging.basicConfig(level=logging.INFO,filename=logpath,filemode='w',format='%(message)s')\n self.log = logging.getLogger()\n except Exception as e:\n print(\"code clone log object creation error.\",e)\n pass\n \n def get_function_names(self,filename):\n \"\"\" Get the function names from python files \"\"\"\n try:\n with open(filename, 'r') as file:\n content = file.read()\n tree = ast.parse(content)\n function_names = []\n \n for node in ast.walk(tree):\n if isinstance(node, ast.FunctionDef):\n function_names.append(node.name)\n except Exception as e:\n self.log.info(\"function name read error: \"+str(e))\n\n return function_names\n \n def get_function_code(self,filename, function_name):\n \"\"\" To get the function codes \"\"\"\n try:\n with open(filename, 'r') as file:\n content = file.read()\n tree = ast.", "instruction": "", "output": "" }, { "input": "parse(content)\n function_code = \"\"\n \n for node in ast.walk(tree):\n if isinstance(node, ast.FunctionDef) and node.name == function_name:\n function_code = ast.unparse(node)\n except Exception as e:\n self.log.info(\"function name read error: \"+str(e))\n\n return function_code\n \n def get_python_files(self,root_dir):\n \"\"\" Walk thru the directory user given, get all py files. \"\"\"\n try:\n \n code_files = [y for x in os.walk(root_dir) for y in glob(os.path.join(x[0], '*.py'))]\n except Exception as e:\n self.log.info(\"Python file read error: \"+str(e))\n return code_files\n \n def chunk_functions(self,function_code, chunk_size):\n \"\"\" Check the function size based on chunk size. \"\"\"\n try:\n if (len(function_code) > 20):\n chunks = [function_code[i:i + chunk_size] for i in range(0, len(function_code), chunk_size)]\n else:\n chunks = list((function_code,))\n except Exception as e:\n self.log.info(\"function chunk based on chunk_size error: \"+str(e))\n total_tokens = round(len(function_code)/4)\n return chunks,total_tokens\n \n def get_clone(self):\n \"\"\" Main code clone detection function using sklearn tfidf_vectorizer and cosine_similarity.\n return values:report_dict which contains total_clones, \"\"\"\n try:\n \n start_time = time.time() \n chunk_size = int(self.chunk_size)\n ccdreportpath = os.path.join(self.deploy_dir, \"codeCloneReport\") \n python_files = self.get_python_files(self.files_dir)\n total_files = len(python_files)\n # print('python_files: \\\\n',python_files)\n function_codes = []\n function_n = []\n file_name=[]\n # files_info=[]\n total_tokens_used = []\n for file in python_files: \n function_names = self.get_function_names(file)\n for i,function_name in enumerate(function_names):\n file_name.append(file)\n function_n.append(function_name) \n function_code = self.get_function_code(file, function_name)\n chunks,total_tokens = self.chunk_functions(function_code, chunk_size)\n total_tokens_used.append(total_tokens)\n function_codes.extend(chunks)\n total_functions = len(function_n)\n files_info=list(zip(file_name, function_n,function_codes))\n tfidf_vectorizer = TfidfVectorizer()\n ## we can use other vectorizer models also.\n # tfidf_vectorizer = HashingVectorizer()\n tfidf_matrix = tfidf_vectorizer.fit_transform(function_codes) \n similarity_matrix = cosine_similarity(tfidf_matrix)\n #Uncomment if you want to send two different code clonne blocks at a time for similarity comparison\n # similarity_matrix = cosine_similarity(tfidf_matrix, tfidf_matrix) \n clone_d = dict() \n total_clones = 0\n final_report=list()\n #getting funtion and next function for comparison\n for i in range(len(similarity_matrix)):\n for j in range(i + 1, len(similarity_matrix)): \n if(similarity_matrix[i, j] >= 0.90 and similarity_matrix[i, j] <= 0.95): \n 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'}})\n report_json = json.dumps(clone_d, indent = 4) \n total_clones=total_clones+1\n elif(similarity_matrix[i, j] > 0.95): \n 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]\n },'cloneType':'exactClone'}})\n report_json = json.dumps(clone_d, indent = 4) \n final_report.append(clone_d)\n total_clones=total_clones+1\n elif(similarity_matrix[i, j] > 0.80 and similarity_matrix[i, j] < 0.90): \n 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]\n },'cloneType':'NearMissClones'}})\n report_json = json.dumps(clone_d, indent = 4) \n final_report.append(clone_d)\n total_clones=total_clones+1\n else:\n ##add other conditionas in future\n pass\n ## To get clone type\n clone_type = [list(item.values())[2] for item in list(clone_d.values())]\n report_str = json.dumps(final_report)\n json_l=json.loads(report_str) \n json_keys = list(json_l[0].keys())\n json_values = list(json_l[0].values())\n end_time = time.time()\n total_time_taken = end_time - start_time\n \n # self.log.info(\"ccd_report: \\\\n\"+str(ccd_report))\n f_df=pd.DataFrame(list(zip(json_keys, json_values,clone_type)),\n columns =['Clone', 'CloneDetails','CloneType'])\n codeclonereport_file = os.path.join(self.ccdreportpath,'clone_detection_report_sklearn.csv') \n f_df.to_csv(codeclonereport_file, index=False)\n ccd_report = f_df.to_markdown(tablefmt='psql')\n self.log.info(\"total_clones: \\\\n\"+str(total_clones))\n exact_clone_count = f_df['CloneType'].str.count(\"exactClone\").sum()\n parametric_clone_count = f_df['CloneType'].str.count(\"parametricClone\").sum()\n nearmiss_clone_count = f_df['CloneType'].str.count(\"NearMissClones\").sum()\n total_tokens = sum(total_tokens_used)\n # nearmiss_clone_count =0\n self.log.info(\"exact_clone_count: \\\\n\"+str(exact_clone_count))\n self.log.info(\"parametric_clone_count: \\\\n\"+str(parametric_clone_count))\n self.log.info(\"nearmiss_clone_count: \\\\n\"+str(nearmiss_clone_count))\n self.log.info(\"Total tokens used: \\\\n\"+str(total_tokens))\n self.log.info(\"Total time taken to excute code clone detction: \\\\t\"+str(total_time_taken))\n clone_info=\"1. Exact clone: Two code fragments similar to each other with little transformation in comments, layout, or whitespaces,\\\\\n 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,\\\\\n 3. Near-miss clone: Near-miss clone are clones detected with less similarity threshold.\"\n clone_count = {\"Exact Clone\":exact_clone_count,\"Parametric Clone\":parametric_clone_count,\"Nearmiss Clone\":nearmiss_clone_count}\n report_str = f\"\"\"Code_directory: {self.files_dir}\n Files: {total_files}\n Functions: {total_functions}\n \n Total_code_clones_detected: {total_clones}\n Tokens used: {total_tokens}\n \n Three_types_of_clone:\n 1. Exact clone: Two code fragments similar to each other with little transformation in comments, layout, or whitespaces.\n 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.\n 3. Near-miss clone: Near-miss clone are clones detected with less similarity threshold.\n \n Code_clones_count_by_clone_type:\n {clone_count}\n \n Clone_functions:\n {ccd_report}\n \n total_time_taken: {total_time_taken}\n \"\"\"\n codeclonereport_txt = os.path.join(self.ccdreportpath,'code_clone_report.txt')\n with open(codeclonereport_txt, \"w\") as f:\n f.write(report_str)\n 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 }\n self.log.info(\"ccd_report: \\\\n\"+str(ccd_report))\n # print(\"report_dict:\\\\n\\\\n\",report_dict)\n # end_time = time.time()\n # total_time = (end_time - start_time) \n \n return report_dict\n except Exception as e:\n self.log.info(\"Clone detection function error. error msg: \"+str(e))\n # import traceback\n # print(\"traceback error: \\\\n\",traceback.print_exc())\n \nif __name__ == \"__main__\":\n print(\"code clone detection started....\")\n ##Use this for standalone fn debuging. '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nfrom os.path import expanduser\nimport platform\nimport json\nimport subprocess\nimport re\nimport sys\nimport pandas as pd\nfrom django.http import HttpResponse\nfrom appbe.dataPath import DATA_DIR\nUsecaselocation = os.path.join(DATA_DIR,'Usecases')\ndef mlstyles(request):\n try:\n from appbe.aion_config import settings\n usecasetab = settings() \n selectid = request.GET['usecaseid']\n configFile = os.path.join(Usecaselocation, 'usecases.json')\n f = open(configFile, \"r\")\n configSettings = f.read()\n f.close()\n configSettingsJson = json.loads(configSettings)\n #usecase = configSettingsJson['usecaselist']\n desciption=\"\"\n usecasename=\"\"\n found = False\n for v_id in configSettingsJson['verticallist']:\n for p_id in v_id['usecaselist']:\n usecaseid = p_id.get('usecaseid')\n if str(usecaseid) == str(selectid) :\n \n usecasename = p_id.get('usecasename')\n desciption = p_id.get('desciption')\n usecaseid = p_id.get('usecaseid')\n iconname = p_id.get('iconname')\n prediction_input = p_id.get('prediction_input')\t\t\t\t\n outputtype = p_id.get('outputtype')\n smalldescription = p_id.get('smalldescription') \t\t\t\t\n trainingFeatures = p_id.get('trainingFeatures','None') \n if trainingFeatures != 'None':\n trainingFeatures = trainingFeatures.split(',')\n found = True\n break \n if found == True:\n break\n #print(usecaseid,selectid) \n context ={'usecasename':usecasename,'desciption':desciption,'prediction_input':prediction_input,'usecaseid':usecaseid,'trainingFeatures':trainingFeatures,'iconname':iconname,'smalldescription':smalldescription,'outputtype':outputtype,'usecasetab':usecasetab}\n return context\n except Exception as inst:\n print(inst) \n context = { 'error3':'error3','error1': \"No UseCases to show\"}\n return context \ndef getusecasedetails(selectid):\n configFile = os.path.join(Usecaselocation, 'usecases.json')\n f = open(configFile, \"r\")\n configSettings = f.read()\n f.close()\n configSettingsJson = json.loads(configSettings)\n #usecase = configSettingsJson['usecaselist']\n desciption=\"\"\n usecasename=\"\"\n found = False\n for v_id in configSettingsJson['verticallist']:\n for p_id in v_id['usecaselist']: \n usecaseid = p_id.get('usecaseid')\n \n if str(usecaseid) == str(selectid) :\n usecasename = p_id.get('usecasename')\n desciption = p_id.get('desciption')\n usecaseid = p_id.get('usecaseid')\n modelConfig = p_id.get('modelConfig')\n folder = p_id.get('folder')\n prediction = p_id.get('prediction')\n prediction_input = p_id.get('prediction_input')\n ai_modeldata = p_id.get('modeldata')\n outputtype = p_id.get('outputtype')\n smalldescription = p_id.get('smalldescription') \n prediction_template = p_id.get('prediction_template')\t\t\t\n trainingFeatures = p_id.get('trainingFeatures','None') \n if trainingFeatures != 'None':\n trainingFeatures = trainingFeatures.split(',') \n found = True \n break\n if found == True:\n break\n #print(usecasename)\n return(usecasename,desciption,usecaseid,modelConfig,folder,prediction,prediction_input,ai_modeldata,outputtype,smalldescription,prediction_template,trainingFeatures)\n \n \ndef mlpredict(request):\n selectid=request.POST.get('usecaseid')\n mlpredict =request.POST.get('mlpredict')\n usecasename,desciption,usecaseid,modelConfig,folder,prediction,prediction_input,ai_modeldata,output", "instruction": "", "output": "" }, { "input": "type,smalldescription,prediction_template,trainingFeatures = getusecasedetails(selectid)\n from appbe.aion_config import settings\n usecasetab = settings()\n usecasename = usecasename\n desciption = desciption\n input=''\n for x in prediction_input:\n if input != '':\n input += ','\t\t\t\n input = request.POST.get(x['name'])\n \n if mlpredict in ['prediction','predictsingle']:\n if mlpredict == 'prediction':\n dataFile = request.POST.get('predictfilePath')\n \n if(os.path.isfile(dataFile) == False) or dataFile==\"\":\n context = {'usecaseid':selectid ,'dataFile':dataFile,'usecasename':usecasename,'desciption':desciption , 'error1': 'Please enter a valid csv filepath','usecasetab':usecasetab}\n return context, mlpredict\n else:\n inputFieldsDict = {}\n for feature in trainingFeatures:\n inputFieldsDict[feature] = request.POST.get(feature) \n dataFile = json.dumps(inputFieldsDict) \n try:\n predictionScriptPath= os.path.join(Usecaselocation,folder,'model',prediction)\n # predictionScriptPath = os.path.join(predictionscript, 'aion_prediction.py')\n \n outputStr = subprocess.check_output([sys.executable, predictionScriptPath, dataFile,input])\n \n outputStr = outputStr.decode('utf-8')\n outputStr = re.search(r'predictions:(.*)', str(outputStr), re.IGNORECASE).group(1)\n outputStr = outputStr.strip()\n predict_dict = json.loads(outputStr)\n #print(predict_dict)\n heading =''\n timetaken=''\n print(predict_dict)\n if (predict_dict['status'] == 'SUCCESS'):\n predictionResults = predict_dict['data']\n #print(predictionResults)\n if 'heading' in predict_dict:\n heading = predict_dict['heading']\n if 'Time' in predict_dict:\t\t\t\t\n timetaken = round(predict_dict['Time'],2)\n if outputtype.lower() in ['similarityidentification','contextualsearch']:\n data = predictionResults[0]\n predictionResults= []\n Results={}\n prediction = data['prediction']\n i = 1\n for x in prediction:\n te = ''\n for y in x:\n info = (str(x[y])[:100] + '...') if len(str(x[y])) > 100 else str(x[y])\n te += y+': '+info+'\\\\n\\\\n'\n Results[i] = te\n i = i+1\n \n predictionResults.append(Results)\n\n else:\n context = {'usecaseid':selectid ,'dataFile':dataFile,'prediction_input':prediction_input,'usecasename':usecasename,'desciption':desciption , 'error': 'Failed To perform prediction','usecasetab':usecasetab}\n return context, mlpredict\n print(heading)\n 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}\n return context, mlpredict\n except Exception as inst:\n print(inst)\n context = { 'usecaseid':selectid ,'dataFile':dataFile,'usecasename':usecasename,'desciption':desciption ,'errorp': 'Failed To perform prediction','usecasetab':usecasetab}\n return context, mlpredict\n if mlpredict == 'download_predict':\n # predictionResults = 'C:\\\\\\\\DataSets\\\\\\\\Classification\\\\\\\\bug_severity_class.csv'\n try:\n csvdata= os.path.join(Usecaselocation,folder,'Data',prediction_template)\n if os.path.isfile(csvdata) and os.path.exists(csvdata):\n df = pd.read_csv(csvdata,encoding='utf8',encoding_errors= 'replace')\n downloadFileName = usecasename.replace(\" \", \"_\") + '_predict.csv'\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename='+downloadFileName\n df.to_csv(response, index=False)\n return response,mlpredict\n else:\n context = {'usecaseid':selectid ,'dataFile':dataFile,'usecasename':usecasename,'desciption':desciption, 'error': 'File not found','usecasetab':usecasetab}\n return context, mlpredict \n\t\t\t\t\n except Exception as inst:\n \n context = { 'usecaseid':selectid ,'usecasename':usecasename,'desciption':desciption, 'error3':'error3','error1': 'Failed To Download','usecasetab':usecasetab}\n return context, mltrain \ndef process(data):\n cleaned_data = {\"verticallist\":[]}\n for vertical in data['verticallist']:\n updated_list = []\n for usecase in vertical['usecaselist']:\n if usecase['prediction'] and usecase['prediction'] != \"Not Implemented\":\n updated_list.append(usecase)\n if updated_list:\n cleaned_data['verticallist'].append({'id':vertical['id'],'name':vertical['name'],'usecaselist':updated_list})\n return cleaned_data\n \ndef Aiusecases(request,selectedoption='Implemented'):\n try:\n from appbe.aion_config import settings\n usecasetab = settings() \n configFile = os.path.join(Usecaselocation, 'usecases.json')\n f = open(configFile, \"r\")\n configSettings = f.read()\n f.close()\n configSettingsJson = json.loads(configSettings)\n \n \n \n if selectedoption == 'Implemented':\n configSettingsJson = process(configSettingsJson)\n usecasedetails = configSettingsJson['verticallist']\n context ={'desciption1':usecasedetails,'selected':'AIusecases','usecasetab':usecasetab}\n return context\n except Exception as e:\n print(e)\n context ={'error':\"No Usecases to Show\",'selected':'AIusecases','usecasetab':usecasetab}\n return context\n\ndef mltrain(request):\n from appbe.aion_config import settings\n usecasetab = settings()\n selectid =request.POST.get('usecaseid1')\n mltrain =request.POST.get('mltrain')\n\n usecasename,desciption,usecaseid,modelConfig,folder,prediction,prediction_input,ai_modeldata,outputtype,smalldescription,prediction_template,trainingFeatures = getusecasedetails(selectid)\n usecasename = usecasename\n desciption = desciption\n \n if mltrain == 'training':\n dataFile = request.POST.get('trainfilePath')\n if(os.path.isfile(dataFile) == False) or dataFile==\"\":\n context = {'usecaseid':selectid ,'datatrainFile':dataFile,'usecasename':usecasename,'desciption':desciption ,'error3':'error3','error1': 'Please enter a valid csv filepath'}\n return context, mltrain \n try:\n scriptPath = os.path.join(Usecaselocation,folder,'config','aion_train.py')\n print(scriptPath,dataFile)\n outputStr = subprocess.check_output([sys.executable, scriptPath, dataFile])\n\n outputStr = outputStr.decode('utf-8')\n outputStr = re.search(r'aion_learner_status:(.*)', str(outputStr), re.IGNORECASE).group(1)\n outputStr = outputStr.strip()\n \n \n train = json.loads(outputStr)\n status = train['status']\n DeployLocation = train['data']['deployLocation']\n ModelType = train['data']['ModelType']\n BestModel = train['data']['BestModel']\n BestScore = train['data']['BestScore']\n ScoreType = train['data']['ScoreType']\n FeaturesUsed = train['data']['featuresused']\n \n 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}\n return context,mltrain \n except Exception as inst:\n \n context = {'usecaseid':selectid ,'datatrainFile':dataFile,'usecasename':usecasename,'desciption':desciption, 'errort': 'Failed To perform Training','usecasetab':usecasetab}\n return context, mltrain \n \n if mltrain == 'download_train':\n\n try:\n csvdata= os.path.join(Usecaselocation,folder,'data',ai_modeldata)\n #print(csvdata)\t\t\t\n if os.path.isfile(csvdata) and os.path.exists(csvdata):\n df = pd.read_csv(csvdata,encoding='utf8',encoding_errors= 'replace')\n downloadFileName = usecasename.replace(\" \", \"_\") + '_training.csv'\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename='+downloadFileName\n df.to_csv(response, index=False)\n return response,mltrain\n else:\n context = {'usecaseid':selectid ,'datatrainFile':dataFile,'usecasename':usecasename,'desciption':desciption, 'error': 'File not found','usecasetab':usecasetab}\n return context, mltrain \n except Exception as inst:\n \n context = { 'usecaseid':selectid ,'usecasename':usecasename,'desciption':desciption, 'error3':'error3','error1': 'Failed To Download','usecasetab':usecasetab}\n return context, mltrain \n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\n\nimport math\nimport sys,os\nimport pandas as pd\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import PCA\nimport numpy as np\nimport scipy.stats as st\nfrom sklearn.preprocessing import StandardScaler\nfrom dython.nominal import associations\nclass ux_eda ():\n\n def __init__(self, dataPath=pd.DataFrame(),delimiter=',',textqualifier='\"',optimize=None,):\n aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n self.dataFrame = pd.DataFrame()\n \n if isinstance(dataPath, pd.DataFrame):\n self.dataFrame = dataPath\n if optimize == 1:\n self.dataFrame = self.dataFrame.sample(n=1000, random_state=1)\n else:\n if optimize == 1:\n self.dataFrame = pd.read_csv(dataPath,nrows=1000,encoding='utf-8',sep=delimiter,quotechar=textqualifier,skipinitialspace = True,na_values=['-','?'],encoding_errors= 'replace')\n else:\n self.dataFrame = pd.read_csv(dataPath, encoding='utf-8',sep=delimiter,quotechar=textqualifier,skipinitialspace = True,na_values=['-','?'],encoding_errors= 'replace')\n self.dataFrame.rename(columns=lambda x: x.strip(), inplace=True)\n \n self.features = self.dataFrame.columns.tolist()\n self.indexFeature = []\n self.dateFeature = []\n self.categoricalFeature = []\n self.constantFeature = []\n self.textFeature = []\n self.numericFeature = []\n self.numericAndCatFeature = [] \n \n for feature, featureType in zip(self.features, self.dataFrame.dtypes):\n \n if self.__check_seq_feature(self.dataFrame[feature]):\n self.indexFeature.append(feature)\n elif self.__match_date_format(self.dataFrame[feature]):\n self.dateFeature.append(feature)\n elif self.__check_constant_features(self.dataFrame[feature]):\n self.constantFeature.append(feature)\n elif self.__check_category_features(self.dataFrame[feature]):\n self.categoricalFeature.append(feature)\n elif featureType == 'object':\n '''\n numOfRows = self.dataFrame.shape[0] \n distinctCount = len(self.dataFrame[feature].unique())\n tempDff = self.dataFrame[feature]\n self.dataFrame[feature]=self.dataFrame[feature].apply(lambda x: self.testNum(x))\n tempDf = self.dataFrame[feature]\n tempDf = tempDf.dropna()\n numberOfNonNullVals = tempDf.count()\n numericRatio = 0.8\n if(numberOfNonNullVals > int(numOfRows * numericRatio)):\n self.numericFeature.append(feature) \n else:\n self.dataFrame[feature] = tempDff\n '''\n self.textFeature.append(feature)\n elif featureType in aionNumericDtypes:\n self.numericFeature.append(feature)\n# self.dataFrame[self.categoricalFeature] = self.dataFrame[self.categoricalFeature].apply(lambda x: x.cat.codes)\n \n self.numericAndCatFeature = self.numericFeature + self.categoricalFeature\n\n\n # EDA Performance change\n # ----------------------------\n def subsampleData(self, subsampleData):\n self.dataFrame = self.dataFrame.sample(n=subsampleData, random_state=1)\n \n def get_features_datatype(self,v,num_list,cat_list,text_list):\n \"\"\" To get exact datatype of the feature in Data Overview.\"\"\" \n if v in cat_list:\n return 'Categorical'\n elif v in num_list: \n return 'Numerical'\n elif v in text_list: \n return 'Text'\n \n def getCorrelationMatrix(self):\n try:\n if len(self.dataFrame.columns) > 25:\n df3 = df[self.dataFrame.columns[0:24]]\n else:\n df3 = self.dataFrame.copy()\n cor_mat= associations(self.dataFrame,compute_only=True)\n cor_mat=cor_mat['corr'] \n cor_mat = cor_mat.astype(float).round(2)\n cor_mat.replace(np.nan, 0, inplace=True)\n cor_mat.fillna('None',inplace=True)\n return cor_mat\n except Exception as e:\n print(e)\n correlationgraph = pd.DataFrame()\n return (correlationgraph)\n \n def dataDistribution(self):\n df_eda_actual = self.dataFrame.copy()\n", "instruction": "", "output": "" }, { "input": " des1 = df_eda_actual.describe(include='all').T\n des1['missing count %'] = df_eda_actual.isnull().mean() * 100\n des1['zero count %'] = df_eda_actual.isin([0]).mean() * 100\n dataColumns = list(self.dataFrame.columns.values)\n des1.insert(0, 'Features', dataColumns)\n actual_df_numerical_features = df_eda_actual.select_dtypes(exclude='object')\n actual_df_categorical_features = df_eda_actual.select_dtypes(include='object')\n #For text features\n textFeature_df = df_eda_actual.filter(self.textFeature)\n actual_df_categorical_features = actual_df_categorical_features.drop(self.textFeature, axis=1) \n for i in des1['Features']:\n num_cols = actual_df_numerical_features.columns.to_list()\n cat_cols = actual_df_categorical_features.columns.to_list()\n text_cols = self.textFeature\n des1['Features Type'] = des1['Features'].apply(lambda x: self.get_features_datatype(x, num_cols,cat_cols,text_cols))\n curr_columns = des1.columns.to_list()\n curr_columns.remove('Features Type')\n insert_i = curr_columns.index('Features')+1\n curr_columns.insert(insert_i,'Features Type')\n des1 = des1[curr_columns]\n return des1\n # ----------------------------\n def subsetFeatures(self, edaFeatures):\n print(self.dataFrame.columns)\n self.dataFrame = self.dataFrame[edaFeatures] \n self.features = edaFeatures\n \n self.indexFeature = []\n self.dateFeature = []\n self.categoricalFeature = []\n self.constantFeature = []\n self.textFeature = []\n self.numericFeature = []\n self.numericAndCatFeature = []\n print('abc')\n aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n \n for feature, featureType in zip(self.features, self.dataFrame.dtypes):\n if self.__check_seq_feature(self.dataFrame[feature]):\n self.indexFeature.append(feature)\n elif self.__match_date_format(self.dataFrame[feature]):\n self.dateFeature.append(feature)\n elif self.__check_constant_features(self.dataFrame[feature]):\n self.constantFeature.append(feature)\n elif self.__check_category_features(self.dataFrame[feature]):\n self.categoricalFeature.append(feature)\n elif featureType == 'object':\n '''\n numOfRows = self.dataFrame.shape[0] \n distinctCount = len(self.dataFrame[feature].unique())\n tempDff = self.dataFrame[feature]\n self.dataFrame[feature]=self.dataFrame[feature].apply(lambda x: self.testNum(x))\n tempDf = self.dataFrame[feature]\n tempDf = tempDf.dropna()\n numberOfNonNullVals = tempDf.count()\n numericRatio = 0.8\n if(numberOfNonNullVals > int(numOfRows * numericRatio)):\n self.numericFeature.append(feature) \n else:\n self.dataFrame[feature] = tempDff\n '''\n self.textFeature.append(feature)\n elif featureType in aionNumericDtypes:\n self.numericFeature.append(feature)\n print('def')\n self.numericAndCatFeature = self.numericFeature + self.categoricalFeature\n # ----------------------------\n\n def testNum(self,value):\n try:\n x=eval(value)\n return x\n except:\n return np.nan \n \n def getFeatures(self):\n leastRatioFeature = self.__LeastfeatureRatio()\n return (self.features, self.dateFeature, self.indexFeature, self.constantFeature, self.textFeature, leastRatioFeature,self.numericAndCatFeature,self.numericFeature,self.categoricalFeature)\n def getNumericFeatureCount(self):\n return(len(self.numericAndCatFeature))\n def calculateNumberofCluster(self):\n df = self.dataFrame[self.numericFeature]\n return self.__NumberofCluster(df)\n def getTopTextFeatures(self,topn):\n df_text = pd.DataFrame()\n if (len(self.textFeature) > 1):\n df_text['combined'] = self.dataFrame[self.textFeature].apply(lambda row: ' '.join(row.values.astype(str)), axis=1)\n features = ['combined']\n else:\n df_text[['combined']] = self.dataFrame[self.textFeature]\n features = ['combined']\n \n df_text[features[0]] = df_text[features[0]].fillna(\"NA\")\n textCorpus = df_text[features[0]]\n from text import eda\n texteda_obj = eda.ExploreTextData()\n df = texteda_obj.MostCommonWords(textCorpus,topn)\n return df \n \n def __NumberofCluster(self, featureData):\n Sum_of_squared_distances = []\n K = range(1, 15)\n for k in K:\n km = KMeans(n_clusters=k)\n km = km.fit(featureData)\n Sum_of_squared_distances.append(km.inertia_)\n x1, y1 = 1, Sum_of_squared_distances[0]\n x2, y2 = 15, Sum_of_squared_distances[len(Sum_of_squared_distances) - 1]\n distances = []\n for inertia in range(len(Sum_of_squared_distances)):\n x0 = inertia + 2\n y0 = Sum_of_squared_distances[inertia]\n numerator = abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1)\n denominator = math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)\n distances.append(numerator / denominator)\n n_clusters = distances.index(max(distances)) + 2\n return (n_clusters)\n#13841 : TrustedAI: hopkins stat\n def getHopkinsVal(self,df):\n\n try:\n from appbe.hopkinsStat import hopkins\n from sklearn.preprocessing import StandardScaler,OneHotEncoder\n from sklearn.compose import ColumnTransformer\n from sklearn.pipeline import Pipeline\n from sklearn.impute import SimpleImputer\n numeric_transformer = Pipeline(\n steps=[(\"imputer\", SimpleImputer(missing_values=np.nan,strategy=\"mean\")),\n (\"standard_scaler\", StandardScaler())]\n )\n categorical_transformer = Pipeline(\n steps=[\n (\"imputer\", SimpleImputer(missing_values=np.nan,strategy=\"most_frequent\")),\n (\"encoder\", OneHotEncoder(handle_unknown=\"ignore\"))\n ]\n )\n\n preprocessor = ColumnTransformer(\n transformers=[\n (\"num\", numeric_transformer, self.numericFeature),\n (\"cat\", categorical_transformer, self.categoricalFeature)\n ]\n )\n pipe = Pipeline([('scaler',preprocessor)])\n scaled_df = pipe.fit_transform(df)\n if type(scaled_df) != np.ndarray:\n scaled_df = scaled_df.toarray()\n score = round(hopkins(scaled_df,scaled_df.shape[0]),2)\n \n return str(score)\n except Exception as e:\n print(e)\n return ''\n\n def getClusterDetails(self):\n aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n df_clus = pd.get_dummies(self.dataFrame[self.numericAndCatFeature], prefix_sep='####')\n for i in df_clus.columns:\n dataType = df_clus[i].dtypes\n if dataType not in aionNumericDtypes:\n df_clus[i] = df_clus[i].fillna(df_clus[i].mode()[0])\n else:\n df_clus[i] = df_clus[i].fillna(df_clus[i].mean())\n\n n = self.__NumberofCluster(df_clus)\n n = n - 1\n kmeans = KMeans(n_clusters=n, init='k-means++', max_iter=10, n_init=10, random_state=0)\n # Fit and predict\n y_means = kmeans.fit_predict(df_clus)\n centroids = kmeans.cluster_centers_.squeeze()\n labels = kmeans.labels_\n features = df_clus.columns\n cluster_details = []\n for j in range(len(features)):\n cluster = {}\n feature = features[j]\n perflag = 0\n if '####' in feature:\n x = features[j].split('####')\n feature = x[0] + ' ' + x[1] + '(%)'\n perflag = 1\n else:\n feature = feature + '(AVG)'\n cluster['label'] = feature\n total_sum = 0\n if perflag == 1:\n for i in range(n):\n centroid = centroids[i]\n value = round(centroid[j], 2)\n total_sum = total_sum + value\n\n for i in range(n):\n centroid = centroids[i]\n value = round(centroid[j], 2)\n if perflag == 1:\n value = (value / total_sum) * 100\n value = round(value, 2)\n cluster['Cluster ' + str(i + 1)] = value\n\n cluster_details.append(cluster)\n\n hopkins_val = self.getHopkinsVal(self.dataFrame,)\n return cluster_details,hopkins_val\n\n\n def getHighlyCorrelatedFeatures(self,noOfTop):\n df_corr = abs(self.dataFrame[self.numericAndCatFeature].corr()).stack().reset_index()\n df_corr.columns = ['FEATURE_1', 'FEATURE_2', 'CORRELATION']\n mask_dups = (df_corr[['FEATURE_1', 'FEATURE_2']].apply(frozenset, axis=1).duplicated()) | (\n df_corr['FEATURE_1'] == df_corr['FEATURE_2'])\n \n df_corr = df_corr[~mask_dups]\n df_corr = df_corr.sort_values(by='CORRELATION', ascending=False) \n df_top = df_corr.head(n=noOfTop)\n return(df_top)\n \n # ---------------------- 12686:Data Distribution related Changes S T A R T ----------------------\n def word_token_for_feature(self, selectedFeature, dataframe):\n comment_words = \"\"\n try:\n df_text = pd.DataFrame() \n df_text[[selectedFeature]] = dataframe\n features = [selectedFeature]\n \n df_text[features[0]] = df_text[features[0]].fillna(\"NA\")\n textCorpus = df_text[features[0]]\n from text import TextProcessing\n tp = TextProcessing.TextProcessing()\n preprocessed_text = tp.transform(textCorpus)\n df_text[selectedFeature] = preprocessed_text\n df_text_list = df_text.values.tolist()\n \n for val in df_text_list:\n val = str(val)\n tokens = val.split()\n for i in range(len(tokens)):\n tokens[i] = tokens[i].lower()\n comment_words += \" \".join(tokens) + \" \"\n except:\n comment_words = \"\"\n \n return comment_words\n # -------------------------------------------- E N D --------------------------------------------\n \n \n def word_token(self):\n df_text = pd.DataFrame()\n if (len(self.textFeature) > 1):\n df_text['combined'] = self.dataFrame[self.textFeature].apply(lambda row: ' '.join(row.values.astype(str)), axis=1)\n features = ['combined']\n else:\n df_text[['combined']] = self.dataFrame[self.textFeature]\n features = ['combined']\n df_text[features[0]] = df_text[features[0]].fillna(\"NA\")\n textCorpus = df_text[features[0]]\n from text import TextProcessing\n tp = TextProcessing.TextProcessing()\n preprocessed_text = tp.transform(textCorpus)\n df_text['combined'] = preprocessed_text\n df_text_list = df_text.values.tolist()\n comment_words = \"\"\n for val in df_text_list:\n val = str(val)\n tokens = val.split()\n for i in range(len(tokens)):\n tokens[i] = tokens[i].lower()\n comment_words += \" \".join(tokens) + \" \"\n if comment_words == \"\":\n comment_words = 'Not found any token'\n return comment_words\n def getdata(self):\n return self.dataFrame\n \n def getPCATop10Features(self):\n aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n df = self.dataFrame[self.numericAndCatFeature]\n for feature in self.numericAndCatFeature:\n if feature in self.categoricalFeature:\n df[feature] = pd.Categorical(df[feature])\n df[feature] = df[feature].cat.codes\n df[feature] = df[feature].fillna(df[feature].mode()[0])\n else:\n df[feature] = df[feature].fillna(df[feature].mean())\n pca = PCA(n_components=2).fit(StandardScaler().fit_transform(df))\n mapping = pd.DataFrame(pca.components_, columns=self.numericAndCatFeature)\n mapping = mapping.diff(axis=0).abs()\n mapping = mapping.iloc[1]\n mapping = mapping.sort_values(ascending=False).head(10)\n return mapping\n \n def getTopRows(self, rows=5):\n return self.dataFrame.head(rows)\n\n def __check_seq_feature(self, data):\n if data.dtypes in ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']:\n total_record = data.count()\n count = (data - data.shift() == 1).sum()\n if ((total_record - count) == 1):\n return True\n return False\n\n def __match_date_format(self, data):\n try:\n ## 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.\n import re\n u_data = data.to_string()\n date_find = (re.findall(r\"[0-9]{1,4}[\\\\_|\\\\-|\\\\/|\\\\|][0-9]{1,2}[\\\\_|\\\\-|\\\\/", "instruction": "", "output": "" }, { "input": "|\\\\|][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))\n if (date_find):\n try:\n data = pd.to_datetime(data, utc=True)\n return True\n except Exception as e:\n ##If not a datetime col, just pass to return false statement.\n pass\n except Exception as e:\n data = data.astype(str)\n beforecheckcount = data.count()\n #####YYYY-MM-DD HH:MM:SS####\n check1 = data[data.str.match(\n 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]\n aftercheckcount = check1.count()\n if (beforecheckcount == aftercheckcount):\n return True\n #####MM/DD/YYYY HH:MM####\n check2 = data[data.str.match(\n 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]\n aftercheckcount = check2.count()\n if (beforecheckcount == aftercheckcount):\n return True\n\n #####DD-MM-YYYY HH:MM####\n check2 = data[data.str.match(\n 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]\n aftercheckcount = check2.count()\n if (beforecheckcount == aftercheckcount):\n return True\n\n #####YYYY/MM/DD####\n 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]\n aftercheckcount = check2.count()\n if (beforecheckcount == aftercheckcount):\n return True\n #####MM/DD/YYYY####\n 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]\n aftercheckcount = check2.count()\n if (beforecheckcount == aftercheckcount):\n return True\n #####YYYY-MM-DD HH:MM:SS.fff####\n check11 = data[data.str.match(\n 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]\n aftercheckcount = check11.count()\n if (beforecheckcount == aftercheckcount):\n return True \n \n return False\n\n def __check_category_features(self, modelFeatures):\n aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n dataType = modelFeatures.dtypes\n numOfRows = len(modelFeatures)\n if dataType not in aionNumericDtypes:\n if dataType != 'bool':\n nUnique = len(modelFeatures.unique().tolist())\n if nUnique <= 30:\n return True\n return False\n\n def __check_constant_features(self, modelFeatures):\n return len(modelFeatures.unique().tolist()) == 1\n\n def __featureRatio(self, modelFeatures):\n if len(modelFeatures):\n return len(modelFeatures.unique().tolist()) / len(modelFeatures)\n return 0\n \n def __LeastfeatureRatio(self):\n ratio = 1\n feat = \"\"\n for feature in (self.numericAndCatFeature + self.textFeature):\n r = self.__featureRatio(self.dataFrame[feature])\n if r < ratio:\n ratio = r\n feat = feature\n return feat\n def getDistribution(self):\n aionNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n df = self.dataFrame[self.numericAndCatFeature]\n dist={}\n for feature in self.numericAndCatFeature:\n if feature in self.categoricalFeature:\n df[feature] = pd.Categorical(df[feature])\n df[feature] = df[feature].cat.codes\n df[feature] = df[feature].fillna(df[feature].mode()[0])\n else:\n df[feature] = df[feature].fillna(df[feature].mean())\n distributionname,sse = self.DistributionFinder(df[feature])\n if distributionname == '':\n dist[feature] = 'Unknown'\n else:\n dist[feature] = distributionname\n return dist\n \n def DistributionFinder(self,data):\n try:\n distributionName = \"\"\n sse = 0.0\n KStestStatic = 0.0\n dataType = \"\"\n if (data.dtype == \"float64\"):\n dataType = \"Continuous\"\n elif (data.dtype == \"int\"):\n dataType = \"Discrete\"\n elif (data.dtype == \"int64\"):\n dataType = \"Discrete\"\n if (dataType == \"Discrete\"):\n distributions = [st.bernoulli, st.binom, st.geom, st.nbinom, st.poisson]\n index, counts = np.unique(data.astype(int), return_counts=True)\n\n if (len(index) >= 2):\n best_sse = np.inf\n y1 = []\n total = sum(counts)\n mean = float(sum(index * counts)) / total\n variance = float((sum(index ** 2 * counts) - total * mean ** 2)) / (total - 1)\n dispersion = mean / float(variance)\n theta = 1 / float(dispersion)\n r = mean * (float(theta) / 1 - theta)\n datamin = data.min()\n datamax = data.max()\n for j in counts:\n y1.append(float(j) / total)\n\n pmf1 = st.bernoulli.pmf(index, mean)\n pmf2 = st.binom.pmf(index, len(index), p=mean / len(index))\n pmf3 = st.geom.pmf(index, 1 / float(1 + mean))\n pmf4 = st.nbinom.pmf(index, mean, r)\n pmf5 = st.poisson.pmf(index, mean) \n \n sse1 = np.sum(np.power(y1 - pmf1, 2.0))\n sse2 = np.sum(np.power(y1 - pmf2, 2.0))\n sse3 = np.sum(np.power(y1 - pmf3, 2.0))\n sse4 = np.sum(np.power(y1 - pmf4, 2.0))\n sse5 = np.sum(np.power(y1 - pmf5, 2.0))\n \n sselist = [sse1, sse2, sse3, sse4, sse5]\n best_distribution = 'NA'\n for i in range(0, len(sselist)):\n if best_sse > sselist[i] > 0:\n best_distribution = distributions[i].name\n best_sse = sselist[i]\n\n elif (len(index) == 1):\n best_distribution = \"Constant Data-No Distribution\"\n best_sse = 0.0\n\n distributionName = best_distribution\n sse = best_sse\n\n elif (dataType == \"Continuous\"):\n\n distributions = [st.uniform, st.expon, st.weibull_max, st.weibull_min, st.chi, st.norm, st.lognorm, st.t,\n st.gamma, st.beta]\n best_distribution = st.norm.name\n best_sse = np.inf\n datamin = data.min()\n datamax = data.max()\n nrange = datamax - datamin\n\n y, x = np.histogram(data.astype(float), bins='auto', density=True)\n x = (x + np.roll(x, -1))[:-1] / 2.0\n\n for distribution in distributions:\n params = distribution.fit(data.astype(float))\n arg = params[:-2]\n loc = params[-2]\n scale = params[-1]\n pdf = distribution.pdf(x, loc=loc, scale=scale, *arg)\n sse = np.sum(np.power(y - pdf, 2.0))\n if (best_sse > sse > 0):\n best_distribution = distribution.name\n best_sse = sse\n distributionName = best_distribution\n sse = best_sse\n except:\n response = str(sys.exc_info()[0])\n message = 'Job has Failed' + response\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type) + ' ' + str(fname) + ' ' + str(exc_tb.tb_lineno))\n \n return distributionName, sse\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\n#Standard Library modules\nimport sqlite3\nimport pandas as pd \nfrom pathlib import Path\nclass sqlite_writer():\n def __init__(self, target_path):\n self.target_path = Path(target_path)\n database_file = self.target_path.stem + '.db'\n self.db = sqlite_db(self.target_path, database_file)\n\n def file_exists(self, file):\n if file:\n return self.db.table_exists(file)\n else:\n return False\n\n def read(self, file):\n return self.db.read(file)\n \n def write(self, data, file):\n self.db.write(data, file)\n\n def close(self):\n self.db.close()\n\nclass sqlite_db():\n\n def __init__(self, location, database_file=None):\n if not isinstance(location, Path):\n location = Path(location)\n if database_file:\n self.database_name = database_file\n else:\n self.database_name = location.stem + '.db'\n db_file = str(location/self.database_name) \n self.conn = sqlite3.connect(db_file)\n self.cursor = self.conn.cursor()\n self.tables = []\n\n def table_exists(self, name):\n if name in self.tables:\n return True\n elif name:\n query = f\"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}';\"\n listOfTables = self.cursor.execute(query).fetchall()\n if len(listOfTables) > 0 :\n self.tables.append(name)\n return True\n return False\n\n def read(self, table_name,condition=''):\n if condition == '':\n return pd.read_sql_query(f\"SELECT * FROM {table_name}\", self.conn)\n else:\n return pd.read_sql_query(f\"SELECT * FROM {table_name} WHERE {condition}\", self.conn)\n\n def create_table(self,name, columns, dtypes):\n query = f'CREATE TABLE IF NOT EXISTS {name} ('\n \n for column, data_type in zip(columns, dtypes):\n query += f\"'{column}' TEXT,\"\n query = query[:-1]\n query += ');'\n self.conn.execute(query)\n return True\n def update(self,table_name,updates,condition):\n update_query = f'UPDATE {table_name} SET {updates} WHERE {condition}'\n self.cursor.execute(update_query)\n self.conn.commit()\n return True \n def write(self,data, table_name):\n if not self.table_exists(table_name):\n self.create_table(table_name, data.columns, data.dtypes)\n tuple_data = list(data.itertuples(index=False, name=None))\n insert_query = f'INSERT INTO {table_name} VALUES('\n for i in range(len(data.columns)):\n insert_query += '?,'\n insert_query = insert_query[:-1] + ')'\n self.cursor.executemany(insert_query, tuple_data)\n self.conn.commit()\n return True\n \n def delete(self, name):\n pass\n \n def close(self):\n self.conn.close()\n import json\nimport os\nimport random\nimport time\nfrom avro.datafile import DataFileReader\nfrom avro.io import DatumReader\nfrom pyarrow.parquet import ParquetFile\nfrom snorkel.labeling.model import LabelModel\nfrom snorkel.labeling import PandasLFApplier, LFAnalysis\nimport pandas as pd\nimport pandavro as pdx\nimport pyarrow as pa\nimport numpy as np\nimport platform\nfrom os.path import expanduser\n\nhome = expanduser(\"~\")\nif platform.system() == 'Windows':\n\n DATA_FILE_PATH = os.path.join(home,'AppData','Local','Programs','HCLTech','AION','data','storage')\nelse:\n DATA_FILE_PATH = os.path.join(home,'HCLT','AION','data')\n\n\n\n\ndef get_join(condition):\n if condition[\"join\"] == 'and':\n return \"", "instruction": "", "output": "" }, { "input": "&\"\n elif condition[\"join\"] == 'or':\n return \"|\"\n else:\n return \"\"\n\n\ndef create_labelling_function(rule_list, label_list):\n lfs_main_func = 'def lfs_list_create():\\\\n'\n lfs_main_func += '\\\\tfrom snorkel.labeling import labeling_function\\\\n'\n lfs_main_func += '\\\\timport numpy as np\\\\n'\n lfs_main_func += '\\\\timport json\\\\n'\n lfs_main_func += '\\\\tABSTAIN = -1\\\\n'\n lfs_main_func += '\\\\tlabels = json.loads(json.dumps(' + json.dumps(label_list) + '))\\\\n'\n lfs_list = '\\\\tlfs_list=['\n for rule in rule_list:\n lfs_list += 'lf_' + rule[\"rule_name\"] + ','\n lfs = '\\\\t@labeling_function()\\\\n'\n lfs += '\\\\tdef lf_' + rule[\"rule_name\"] + '(data):\\\\n'\n lfs += '\\\\t\\\\treturn np.where('\n for condition in rule[\"conditions\"]:\n if \"string\" in condition[\"sel_datatype\"]:\n if condition[\"sel_condition\"] in [\"==\", \"!=\"]:\n cond_statement = '(data[\"' + condition[\"sel_column\"] + '\"]' + condition[\n \"sel_condition\"] + '(\"' + str(condition[\"input_value\"]) + '\"))' + get_join(condition)\n else:\n cond_statement = '(data[\"' + condition[\"sel_column\"] + '\"].' + condition[\n \"sel_condition\"] + '(\"' + str(condition[\"input_value\"]) + '\"))' + get_join(condition)\n else:\n cond_statement = '(data[\"' + condition[\"sel_column\"] + '\"]' + condition[\"sel_condition\"] + \\\\\n str(condition[\"input_value\"]) + ')' + get_join(condition)\n lfs += cond_statement\n lfs += ', labels.index(\"' + rule[\"label\"] + '\"), ABSTAIN)\\\\n'\n lfs_main_func += lfs\n if lfs_list.endswith(\",\"):\n lfs_list = lfs_list.rstrip(lfs_list[-1])\n lfs_list += ']\\\\n'\n else:\n lfs_list += ']\\\\n'\n lfs_main_func += lfs_list\n lfs_main_func += '\\\\treturn lfs_list\\\\n'\n lfs_main_func += 'lfs_list_create()'\n f = open(os.path.join(DATA_FILE_PATH, 'lfs_list.txt'), 'w')\n f.write(lfs_main_func)\n f.close()\n return lfs_main_func\n\n\ndef label_dataset(rule_list, file_ext, label_list, not_satisfy_label):\n file_path = os.path.join(DATA_FILE_PATH, \"uploaded_file.\" + file_ext)\n if file_ext in [\"csv\", \"tsv\"]:\n df = pd.read_csv(file_path)\n elif file_ext == \"json\":\n df = pd.json_normalize(pd.read_json(file_path).to_dict(\"records\"))\n elif file_ext == \"avro\":\n reader = DataFileReader(open(file_path, \"rb\"), DatumReader())\n schema = json.loads(reader.meta.get('avro.schema').decode('utf-8'))\n df = pdx.read_avro(file_path, schema=schema, na_dtypes=True)\n elif file_ext == \"parquet\":\n df = pd.read_parquet(file_path, engine=\"pyarrow\")\n labelling_functions = create_labelling_function(rule_list, label_list)\n exec(labelling_functions)\n lfs = eval('lfs_list_create()')\n applier = PandasLFApplier(lfs)\n l_data = applier.apply(df)\n label_model = LabelModel(cardinality=len(label_list) + 1, verbose=True)\n label_model.fit(l_data, n_epochs=500, log_freq=50, seed=123)\n df[\"label\"] = label_model.predict(L=l_data, tie_break_policy=\"abstain\")\n df.loc[df[\"label\"] == -1, \"label\"] = not_satisfy_label\n for item in label_list:\n df.loc[df[\"label\"] == label_list.index(item), \"label\"] = item\n if file_ext in [\"csv\", \"tsv\"]:\n df.to_csv(os.path.join(DATA_FILE_PATH, \"result_file.\" + file_ext), index=False)\n elif file_ext == \"parquet\":\n df.to_parquet(os.path.join(DATA_FILE_PATH, \"result_file.\" + file_ext),\n engine=\"pyarrow\", index=False)\n elif file_ext == \"avro\":\n pdx.to_avro(os.path.join(DATA_FILE_PATH, \"result_file.\" + file_ext), df)\n else:\n raise ValueError(\"Invalid file format\")\n num_records = len(df.index)\n size_take = 100\n if num_records <= size_take:\n size_take = num_records\n display_df = df.sample(n=size_take)\n return display_df.to_html(classes='table table-striped text-left', justify='left', index=False)\n\n\ndef create_sample_function(rule, label_list, not_satisfy_label):\n lfs_main_func = 'def lf_rule_apply(data):\\\\n'\n lfs_main_func += '\\\\timport numpy as np\\\\n'\n lfs_main_func += '\\\\tABSTAIN = -1\\\\n'\n lfs_main_func += '\\\\tlabels = json.loads(json.dumps(' + json.dumps(label_list) + '))\\\\n'\n lfs = '\\\\treturn np.where('\n for condition in rule[\"conditions\"]:\n if \"string\" in condition[\"sel_datatype\"]:\n if condition[\"sel_condition\"] in [\"==\", \"!=\"]:\n cond_statement = '(data[\"' + condition[\"sel_column\"] + '\"]' + condition[\"sel_condition\"] + '(\"' + str(\n condition[\"input_value\"]) + '\"))' + get_join(condition)\n else:\n cond_statement = '(data[\"' + condition[\"sel_column\"] + '\"].str.' + condition[\n \"sel_condition\"] + '(\"' + str(condition[\"input_value\"]) + '\"))' + get_join(condition)\n print(cond_statement)\n else:\n cond_statement = '(data[\"' + condition[\"sel_column\"] + '\"]' + condition[\"sel_condition\"] + \\\\\n str(condition[\"input_value\"]) + ')' + get_join(condition)\n lfs += cond_statement\n lfs += ', \"' + rule[\"label\"] + '\", \"' + not_satisfy_label + '\")\\\\n'\n lfs_main_func += lfs\n return lfs_main_func\n\n\ndef get_sample_result_of_individual_rule(rule_json, file_ext, label_list, not_satisfy_label):\n file_path = os.path.join(DATA_FILE_PATH, \"uploaded_file.\" + file_ext)\n size_take = 100\n if file_ext in [\"csv\", \"tsv\"]:\n num_records = sum(1 for line in open(file_path)) - 1\n if num_records > size_take:\n skip = sorted(random.sample(range(1, num_records + 1), num_records - size_take))\n else:\n skip = 0\n df = pd.read_csv(file_path, skiprows=skip)\n elif file_path.endswith(\".json\"):\n df = pd.read_json(file_path)\n df = pd.json_normalize(df.to_dict(\"records\"))\n elif file_path.endswith(\".avro\"):\n reader = DataFileReader(open(file_path, \"rb\"), DatumReader())\n schema = json.loads(reader.meta.get('avro.schema').decode('utf-8'))\n df = pdx.read_avro(file_path, schema=schema, na_dtypes=True)\n elif file_path.endswith(\".parquet\"):\n pf = ParquetFile(file_path)\n take_rows = next(pf.iter_batches(batch_size=size_take))\n df = pa.Table.from_batches([take_rows]).to_pandas()\n # file_content = pd.read_parquet(file_path, engine=\"pyarrow\")\n else:\n raise ValueError(\"Invalid file format\")\n\n rule_applier_func = create_sample_function(rule_json, label_list, not_satisfy_label)\n exec(rule_applier_func)\n df[rule_json[\"rule_name\"]] = eval('lf_rule_apply')(df)\n return df.to_html(classes='table table-striped text-left', justify='left', index=False)\n\n\ndef create_sample_function_ver2(rule_json, label_list, not_satisfy_label):\n lfs_main_func = 'def lf_rule_apply(data):\\\\n'\n lfs_main_func += '\\\\timport numpy as np\\\\n'\n lfs_main_func += '\\\\tABSTAIN = -1\\\\n'\n lfs_main_func += '\\\\tlabels = json.loads(json.dumps(' + json.dumps(label_list) + '))\\\\n'\n counter = 0\n for condition in rule_json[\"conditions\"]:\n lfs_return = condition[\"sel_label\"]\n if counter > 0:\n lfs_return_condition = '\\\\telif'\n else:\n lfs_return_condition = '\\\\tif'\n for label_condition in condition[\"label_condition\"]:\n if label_condition[\"sel_datatype\"] == \"string\":\n if label_condition[\"sel_condition\"] == \"contains\":\n lfs_return_condition += '((' + str(label_condition[\"input_value\"]) + ') in data[\"' + \\\\\n label_condition[\"sel_column\"] + '\"])' + get_join(label_condition)\n elif label_condition[\"sel_condition\"] in [\"==\", \"!=\"]:\n lfs_return_condition += '(data[\"' + label_condition[\"sel_column\"] + '\"]' + label_condition[\n \"sel_condition\"] + '(\"' + str(\n label_condition[\"input_value\"]) + '\"))' + get_join(label_condition)\n else:\n lfs_return_condition += '(data[\"' + label_condition[\"sel_column\"] + '\"].' + label_condition[\n \"sel_condition\"] + '(\"' + str(label_condition[\"input_value\"]) + '\"))' + get_join(\n label_condition)\n else:\n lfs_return_condition += '(data[\"' + label_condition[\"sel_column\"] + '\"]' + label_condition[\n \"sel_condition\"] + str(label_condition[\"input_value\"]) + ')' + get_join(label_condition)\n if get_join(label_condition) == \"\":\n lfs_return_condition += \":\\\\n\"\n lfs_return_condition += '\\\\t\\\\treturn \"' + lfs_return + '\"\\\\n'\n lfs_main_func += lfs_return_condition\n counter += 1\n lfs_return_condition = '\\\\n\\\\telse:\\\\n'\n lfs_return_condition += '\\\\t\\\\treturn \"' + not_satisfy_label + '\"'\n lfs_main_func += lfs_return_condition\n return lfs_main_func\n\n\ndef get_sample_result_of_individual_rule_ver2(rule_json, file_ext, label_list, not_satisfy_label):\n file_path = os.path.join(DATA_FILE_PATH, \"uploaded_file.\" + file_ext)\n size_take = 100\n if file_ext in [\"csv\", \"tsv\"]:\n num_records = sum(1 for line in open(file_path)) - 1\n if num_records > size_take:\n skip = sorted(random.sample(range(1, num_records + 1), num_records - size_take))\n else:\n skip = 0\n df = pd.read_csv(file_path, skiprows=skip)\n elif file_path.endswith(\".json\"):\n df = pd.read_json(file_path)\n df = pd.json_normalize(df.to_dict(\"records\"))\n elif file_path.endswith(\".avro\"):\n reader = DataFileReader(open(file_path, \"rb\"), DatumReader())\n schema = json.loads(reader.meta.get('avro.schema').decode('utf-8'))\n df = pdx.read_avro(file_path, schema=schema, na_dtypes=True)\n elif file_path.endswith(\".parquet\"):\n pf = ParquetFile(file_path)\n take_rows = next(pf.iter_batches(batch_size=size_take))\n df = pa.Table.from_batches([take_rows]).to_pandas()\n # file_content = pd.read_parquet(file_path, engine=\"pyarrow\")\n else:\n raise ValueError(\"Invalid file format\")\n\n rule_applier_func = create_sample_function_ver2(rule_json, label_list, not_satisfy_label)\n exec(rule_applier_func)\n df[rule_json[\"rule_name\"]] = df.apply(eval('lf_rule_apply'), axis=1)\n return df.to_html(classes='table table-striped text-left', justify='left', index=False)\n\n\ndef create_labelling_function_ver2(rule_list, label_list):\n lfs_main_func = 'def lfs_list_create():\\\\n'\n lfs_main_func += '\\\\tfrom snorkel.labeling import labeling_function\\\\n'\n lfs_main_func += '\\\\timport numpy as np\\\\n'\n lfs_main_func += '\\\\timport json\\\\n'\n lfs_main_func += '\\\\tABSTAIN = -1\\\\n'\n lfs_main_func += '\\\\tlabels = json.loads(json.dumps(' + json.dumps(label_list) + '))\\\\n'\n lfs_list = '\\\\tlfs_list=['\n for rule in rule_list:\n lfs_list += 'lf_' + rule[\"rule_name\"] + ','\n lfs = '\\\\t@labeling_function()\\\\n'\n lfs += '\\\\tdef lf_' + rule[\"rule_name\"] + '(data):\\\\n'\n counter = 0\n for condition in rule[\"conditions\"]:\n lfs_return = 'labels.index(\"' + condition[\"sel_label\"] + '\")'\n if counter > 0:\n lfs_return_condition = '\\\\t\\\\telif'\n else:\n lfs_return_condition = '\\\\t\\\\tif'\n for label_condition in condition[\"label_condition\"]:\n if label_condition[\"sel_datatype\"] == \"string\":\n if label_condition[\"sel_condition\"] == \"contains\":\n lfs_return_condition += '((' + str(label_condition[\"input_value\"]) + ') in data[\"' + \\\\\n label_condition[\"sel_column\"] + '\"])' + get_join(label_condition)\n elif label_condition[\"sel_condition\"] in [\"==\", \"!=\"]:\n lfs_return_condition += '(data[\"' + label_condition[\"sel_column\"] + '\"]' + label_condition[\n \"sel_condition\"] + '(\"' + str(", "instruction": "", "output": "" }, { "input": "\n label_condition[\"input_value\"]) + '\"))' + get_join(label_condition)\n else:\n lfs_return_condition += '(data[\"' + label_condition[\"sel_column\"] + '\"].' + label_condition[\n \"sel_condition\"] + '(\"' + str(label_condition[\"input_value\"]) + '\"))' + get_join(\n label_condition)\n else:\n lfs_return_condition += '(data[\"' + label_condition[\"sel_column\"] + '\"]' + label_condition[\n \"sel_condition\"] + str(label_condition[\"input_value\"]) + ')' + get_join(label_condition)\n if get_join(label_condition) == \"\":\n lfs_return_condition += \":\\\\n\"\n lfs_return_condition += '\\\\t\\\\t\\\\treturn ' + lfs_return + '\\\\n'\n lfs += lfs_return_condition\n counter += 1\n lfs_return_condition = '\\\\n\\\\t\\\\telse:\\\\n'\n lfs_return_condition += '\\\\t\\\\t\\\\treturn ABSTAIN\\\\n'\n lfs += lfs_return_condition\n lfs_main_func += lfs\n if lfs_list.endswith(\",\"):\n lfs_list = lfs_list.rstrip(lfs_list[-1])\n lfs_list += ']\\\\n'\n else:\n lfs_list += ']\\\\n'\n lfs_main_func += lfs_list\n lfs_main_func += '\\\\treturn lfs_list\\\\n'\n lfs_main_func += 'lfs_list_create()'\n # f = open(os.path.join(DATA_FILE_PATH, 'lfs_list.txt'), 'w')\n # f.write(lfs_main_func)\n # f.close()\n return lfs_main_func\n\n\ndef get_rule_name_list(rule_list):\n rule_name_list = []\n for rule in rule_list:\n rule_name_list.append(rule[\"rule_name\"])\n return rule_name_list\n\n\ndef label_dataset_ver2(request,rule_list, file_ext, label_list, not_satisfy_label, label_weightage, include_proba):\n file_path = os.path.join(DATA_FILE_PATH, \"uploaded_file.\" + file_ext)\n if file_ext in [\"csv\", \"tsv\"]:\n df = pd.read_csv(file_path)\n elif file_ext == \"json\":\n df = pd.json_normalize(pd.read_json(file_path).to_dict(\"records\"))\n elif file_ext == \"avro\":\n reader = DataFileReader(open(file_path, \"rb\"), DatumReader())\n schema = json.loads(reader.meta.get('avro.schema').decode('utf-8'))\n df = pdx.read_avro(file_path, schema=schema, na_dtypes=True)\n elif file_ext == \"parquet\":\n df = pd.read_parquet(file_path, engine=\"pyarrow\")\n labelling_functions = create_labelling_function_ver2(rule_list, label_list)\n exec(labelling_functions)\n lfs = eval('lfs_list_create()')\n applier = PandasLFApplier(lfs)\n l_data = applier.apply(df)\n label_model = LabelModel(cardinality=len(label_list), verbose=True)\n label_model.fit(l_data, n_epochs=500, log_freq=50, seed=123, class_balance=label_weightage)\n df[\"label\"] = label_model.predict(L=l_data, tie_break_policy=\"abstain\")\n if include_proba:\n prediction_of_prob = label_model.predict_proba(L=l_data)\n for label in label_list:\n df[label + \"_prob\"] = np.around(prediction_of_prob[:, label_list.index(label)], 2) * 100\n df.loc[df[\"label\"] == -1, \"label\"] = not_satisfy_label\n\n\n filetimestamp = str(int(time.time()))\n datasetName = \"AION_labelled_\"+filetimestamp + '.' + file_ext\n request.session['AION_labelled_Dataset'] = datasetName\n for item in label_list:\n df.loc[df[\"label\"] == label_list.index(item), \"label\"] = item\n if file_ext in [\"csv\", \"tsv\"]:\n df.to_csv(os.path.join(DATA_FILE_PATH, datasetName), index=False)\n elif file_ext == \"parquet\":\n df.to_parquet(os.path.join(DATA_FILE_PATH, datasetName),\n engine=\"pyarrow\", index=False)\n elif file_ext == \"avro\":\n pdx.to_avro(os.path.join(DATA_FILE_PATH, datasetName), df)\n else:\n raise ValueError(\"Invalid file format\")\n\n #### saving file to database\n from appbe.dataPath import DATA_DIR\n from appbe.sqliteUtility import sqlite_db\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'config.db')\n newdata = {}\n newdata['datapath'] = [os.path.join(DATA_FILE_PATH, datasetName)]\n newdata['datasetname'] = [datasetName]\n sqlite_obj.write_data(pd.DataFrame.from_dict(newdata), 'dataingest')\n\n\n num_records = len(df.index)\n size_take = 100\n if num_records <= size_take:\n size_take = num_records\n display_df = df.sample(n=size_take)\n weightage = np.around(label_model.get_weights(), 2)\n rule_name_list = get_rule_name_list(rule_list)\n analysis_df = LFAnalysis(l_data, lfs).lf_summary()\n analysis_df[\"Rule\"] = analysis_df.index\n analysis_df[\"Rule\"] = analysis_df[\"Rule\"].str.replace(\"lf_\", \"\")\n analysis_df = analysis_df[[\"Rule\", \"Polarity\", \"Coverage\", \"Overlaps\", \"Conflicts\"]]\n weightage_dict = dict(zip(rule_name_list, weightage))\n analysis_json = analysis_df.to_dict(orient=\"records\")\n for item in analysis_json:\n item[\"Weightage\"] = weightage_dict[item[\"Rule\"]]\n analysis_df = pd.json_normalize(analysis_json)\n # rules_weightage = []\n # for key in weightage_dict:\n # rules_weightage.append({\n # \"label\": key,\n # \"y\": weightage_dict[key],\n # \"legendText\": key\n # })\n response = {\n # \"rule_name_list\": rule_name_list,\n # \"weightage_list\": list(weightage),\n \"analysis_df\": analysis_df.to_html(classes='table table-striped text-left', justify='left', index=False),\n \"result_html\": display_df.to_html(classes='table table-striped text-left', justify='left', index=False)\n }\n return response\n\n\ndef get_label_and_weightage(test_file_ext, marked_label_column,file_delim_test, custom_test_delim ):\n file_path = os.path.join(DATA_FILE_PATH, \"test_data_file.\" + test_file_ext)\n if test_file_ext in [\"csv\", \"tsv\"]:\n df = pd.read_csv(file_path)\n elif test_file_ext == \"json\":\n df = pd.json_normalize(pd.read_json(file_path).to_dict(\"records\"))\n elif test_file_ext == \"avro\":\n reader = DataFileReader(open(file_path, \"rb\"), DatumReader())\n schema = json.loads(reader.meta.get('avro.schema').decode('utf-8'))\n df = pdx.read_avro(file_path, schema=schema, na_dtypes=True)\n elif test_file_ext == \"parquet\":\n df = pd.read_parquet(file_path, engine=\"pyarrow\")\n json_df = pd.DataFrame(df[marked_label_column].value_counts(normalize=True) * 100)\n json_dict = json.loads(json_df.to_json())\n label_with_weightage = []\n for k in json_dict[marked_label_column]:\n label_with_weightage.append(\n {\"label_name\": k, \"label_weightage\": np.around(json_dict[marked_label_column][k], 2)})\n return label_with_weightage\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nfrom os.path import expanduser\nimport platform\nDEFAULT_FILE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),'conf')\ncur_dir = os.path.dirname(os.path.abspath(__file__))\nhome = expanduser(\"~\")\nif platform.system() == 'Windows':\n DATA_DIR = os.path.normpath(os.path.join(cur_dir,'..','..','..','..','..','..','data'))\n DATA_FILE_PATH = os.path.join(DATA_DIR,'storage')\n CONFIG_FILE_PATH = os.path.join(DATA_DIR,'config')\n DEPLOY_LOCATION = os.path.join(DATA_DIR,'target')\n LOG_LOCATION = os.path.join(DATA_DIR,'logs')\n LOG_FILE = os.path.join(DATA_DIR,'logs','ux.log')\nelse:\n DATA_DIR = os.path.join(home,'HCLT','data')\n DATA_FILE_PATH = os.path.join(DATA_DIR,'storage')\n CONFIG_FILE_PATH = os.path.join(DATA_DIR,'config')\n DEPLOY_LOCATION = os.path.join(DATA_DIR,'target')\n LOG_FILE = os.path.join(DATA_DIR,'logs','ux.log')\n LOG_LOCATION = os.path.join(DATA_DIR,'logs') '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport platform\nimport shutil\nimport subprocess\nimport sys\nimport glob\nfrom pathlib import Path\nimport json\nfrom django.http import FileResponse\nfrom django.http import HttpResponse\nfrom importlib.metadata import version\nCOMMON_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'\"\nDL_COMMON_PACKAGE = \"'tensorflow==2.11.0'\"\nTEXT_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'\"\n\n\ndef createPackagePackage(request,id,version,usecasedetails,Existusecases):\n from appbe.pages import get_usecase_page\n #print('2')\n usecasedetail = usecasedetails.objects.get(id=id)\n models = Existusecases.objects.filter(ModelName=usecasedetail,Status='SUCCESS',Version=version)\n modelid = models[0].id \n p = Existusecases.objects.get(id=modelid)\n deploymentfolder = str(p.DeployPath)\n modelname = p.ModelName.usecaseid\n version = p.Version\n deployed_code = 'AION'\n dockerimage = os.path.join(deploymentfolder,'publish','docker_image')\n dockersetup = os.path.join(deploymentfolder,'publish','docker_setup')\n tempPath = os.path.join(os.path.dirname(os.path.abspath(__file__)),'temp_'+modelname+'_'+str(version))\n try:\n shutil.rmtree(tempPath,ignore_errors=True)\n except:\n pass\n \n shutil.copytree(deploymentfolder,tempPath) \n shutil.rmtree(os.path.join(tempPath,'publish'), ignore_errors=True)\n try:\n Path(os.path.join(deploymentfolder,'publish')).mkdir(parents=True, exist_ok=True)\n os.mkdir(dockersetup) \n except:\n shutil.rmtree(dockersetup,ignore_errors=True)\n os.mkdir(dockersetup) \n try:\n os.mkdir(dockerimage) \n except:\n shutil.rmtree(dockerimage,ignore_errors=True)\n os.mkdir(dockerimage) \n shutil.copytree(tempPath, os.path.join(dockersetup,deployed_code))\n shutil.rmtree(tempPath)\n \n docker_setup = os.path.join(dockersetup,'AION')\n\n try:\n os.mkdir(dockerimage) \n except:\n pass\n requirementfilename = os.path.join(dockersetup,'requirements.txt')\n installfilename = os.path.join(dockersetup,'install.py')\n dockerfile = os.path.join(dockersetup,'Dockerfile')\n dockerdata='FROM python:3.10-slim-buster'\n dockerdata+='\\\\n'\n dockerdata+='WORKDIR /app'\n dockerdata+='\\\\n'\n dockerdata+='COPY AION AION'\n dockerdata+='\\\\n'\n dockerdata+='''RUN apt-get update \\\\\n && apt-get install -y build-essential manpages-dev \\\\\n && apt-get install -y libgomp1 \\\\ \n && python -m pip install --no-cache-dir -r AION/requirements.txt\n'''\n f = open(dockerfile, \"w\")\n f.write(str(dockerdata))\n f.close() \n try:\n try:\n import docker\n client = docker.from_env()\n client.containers.list()\n except: \n status,context,action = get_usecase_page(request,usecasedetails,Existusecases) \n context['Status'] = 'Error'\n 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('\\\\\\\\', '/') \n return context\n", "instruction": "", "output": "" }, { "input": " command = 'docker pull python:3.10-slim-buster'\n os.system(command); \n subprocess.check_call([\"docker\", \"build\", \"-t\",modelname.lower()+\":\"+str(version),\".\"], cwd=dockersetup) \n subprocess.check_call([\"docker\", \"save\", \"-o\",modelname.lower()+\"_\"+str(version)+\".tar\",modelname.lower()+\":\"+str(version)], cwd=dockersetup) \n dockerfilepath = os.path.join(dockersetup,modelname.lower()+\"_\"+str(version)+\".tar\")\t\t\n shutil.copyfile(dockerfilepath, os.path.join(dockerimage,modelname.lower()+\"_\"+str(version)+\".tar\")) \n shutil.rmtree(dockersetup)\n msg = 'Done'\n Status = 'SUCCESS' \n except Exception as e:\n msg = 'Error in docker images creation. To build manually docker image setup available in following location: '+dockersetup.replace('\\\\\\\\', '\\\\\\\\\\\\\\\\')\n Status = 'Fail' \n status,context,action = get_usecase_page(request,usecasedetails,Existusecases) \n context['Status'] = Status\n context['Msg'] = msg \n return context\n \ndef downloadPackage(request,id,version,usecasedetails,Existusecases):\n try:\n if 'downloadstatus' in request.session:\n if request.session['downloadstatus'] == 'Downloading':\n return HttpResponse(json.dumps(\"Error Creating Package\"), content_type=\"application/error\") \n request.session['downloadstatus'] = 'Downloading' \n usecasedetail = usecasedetails.objects.get(id=id)\n models = Existusecases.objects.filter(ModelName=usecasedetail,Status='SUCCESS',Version=version)\n modelid = models[0].id \n p = Existusecases.objects.get(id=modelid)\n deployPath = str(p.DeployPath)\n if os.path.isdir(os.path.join(deployPath,'publish','package')):\n for f in os.listdir(os.path.join(deployPath,'publish','package')):\n if f.endswith('whl'):\n os.remove(os.path.join(deployPath,'publish','package',f))\n usecasename = p.ModelName.usecaseid\n Version = p.Version\n deployed_code = usecasename\n targetname = usecasename+'_'+str(Version)\n whl_dir_name = 'WHEEL_'+usecasename+'_'+str(Version)\n deployLocation = os.path.join (deployPath,'..',whl_dir_name)\n try:\n os.makedirs(deployLocation)\n except OSError as e:\n shutil.rmtree(deployLocation)\n os.makedirs(deployLocation)\n shutil.copytree(deployPath,os.path.join(deployLocation,deployed_code))\n initstring = 'import os'\n initstring += '\\\\n'\n initstring += 'import sys'\n initstring += '\\\\n'\n initstring += 'sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__))))'\n filename = os.path.join(deployLocation,deployed_code,'__init__.py')\n f = open(filename, \"w\")\n f.write(str(initstring))\n f.close() \n textdata=0\n learner_type = 'ml'\n requirementfile = os.path.join(deployPath,'requirements.txt')\n install_requires = ''\n if os.path.exists(requirementfile): \n fileobj = open(requirementfile, 'r')\n requirePackages = fileobj.readlines()\n fileobj.close() \n for package in requirePackages:\n if install_requires != '':\n install_requires = install_requires+','\n install_requires = install_requires+'\\\\''+package.strip()+'\\\\'' \n setup_string = 'from setuptools import setup,find_packages'\n setup_string += '\\\\n'\n setup_string += 'setup(name=\\\\''+deployed_code+'\\\\','\n setup_string += '\\\\n'\n setup_string += 'version=\\\\'1\\\\','\n setup_string += '\\\\n'\n setup_string += 'packages = find_packages(),'\n setup_string += '\\\\n'\n setup_string += 'install_requires = ['+install_requires+'],' \n setup_string += '\\\\n'\n setup_string += 'package_data={\"'+deployed_code+'.pytransform\":[\"*.*\"],\"'+deployed_code+'\":[\"*.sav\",\"*.json\"],\"\":[\"*\",\"*/*\",\"*/*/*\"]}'\n setup_string += '\\\\n'\n setup_string += ')'\n filename = os.path.join(deployLocation,'setup.py')\n f = open(filename, \"w\")\n f.write(str(setup_string))\n f.close()\n \n subprocess.check_call([sys.executable, \"setup.py\", \"bdist_wheel\"], cwd=deployLocation)\n shutil.copytree(os.path.join(deployLocation,'dist'),os.path.join(deployPath,'publish','package'),dirs_exist_ok=True)\n shutil.rmtree(deployLocation)\n if os.path.isdir(os.path.join(deployPath,'publish','package')):\n for f in os.listdir(os.path.join(deployPath,'publish','package')):\n if f.endswith('whl'):\n package = f\n zip_file = open(os.path.join(deployPath,'publish','package',package), 'rb')\n request.session['downloadstatus'] = 'Done' \n return FileResponse(zip_file)\n except Exception as e:\n print(e)\n request.session['downloadstatus'] = 'Done'\n return HttpResponse(json.dumps(\"Error Creating Package\"), content_type=\"application/error\")\ndef installPackage(model,version,deployedPath):\n deployedPath = os.path.join(deployedPath,'publish','package')\n whlfilename='na'\n if os.path.isdir(deployedPath):\n for file in os.listdir(deployedPath):\n if file.endswith(\".whl\"):\n whlfilename = os.path.join(deployedPath,file)\n if whlfilename != 'na':\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"uninstall\",\"-y\",model])\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\",\"--no-dependencies\",whlfilename])\n status,pid,ip,port = checkModelServiceRunning(model)\n if status == 'Running':\n stopService(pid)\n startService(model,ip,port)\n return('Success')\n else:\n return('Installation Package not Found')\ndef getMIDFromUseCaseVersion(id,version,usecasedetails,Existusecases):\n usecasedetail = usecasedetails.objects.get(id=id)\n models = Existusecases.objects.filter(ModelName=usecasedetail,Status='SUCCESS',Version=version)\n return(models[0].id)\n\ndef stopService(pid):\n import psutil\n p = psutil.Process(int(pid))\n p.terminate()\n \ndef checkModelServiceRunning(package_name):\n from os.path import expanduser\n home = expanduser(\"~\")\n if platform.system() == 'Windows':\n modelServices = os.path.join(home,'AppData','Local','HCLT','AION','services')\n else:\n modelServices = os.path.join(home,'HCLT','AION','target','services') \n filename = package_name+'_service.py'\n modelservicefile = os.path.join(modelServices,filename)\n status = 'Not Initialized'\n ip = ''\n port = ''\n pid = ''\n if os.path.exists(modelservicefile):\n status = 'Not Running'\n import psutil\n for proc in psutil.process_iter():\n pinfo = proc.as_dict(attrs=['pid', 'name', 'cmdline','connections'])\n if 'python' in pinfo['name']:\n if filename in pinfo['cmdline'][1]:\n status = 'Running'\n pid = pinfo['pid']\n for x in pinfo['connections']:\n ip = x.laddr.ip\n port = x.laddr.port\n \n \n return(status,pid,ip,port)\ndef startService(package_name,ip,portNo):\n file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','bin','model_service.py'))\n from os.path import expanduser\n home = expanduser(\"~\")\n if platform.system() == 'Windows':\n modelServices = os.path.join(home,'AppData','Local','HCLT','AION','services')\n else:\n modelServices = os.path.join(home,'HCLT','AION','target','services')\n if not os.path.isdir(modelServices):\n os.makedirs(modelServices)\n filename = package_name+'_service.py'\n modelservicefile = os.path.join(modelServices,filename)\n status = 'File Not Exist'\n if os.path.exists(modelservicefile):\n status = 'File Exist'\n r = ([line.split() for line in subprocess.check_output(\"tasklist\").splitlines()])\n for i in range(len(r)):\n if filename in r[i]: \n status = 'Running'\n if status == 'File Not Exist':\n shutil.copy(file_path,modelservicefile)\n with open(modelservicefile, 'r+') as file:\n content = file.read()\n file.seek(0, 0)\n line = 'from '+package_name+' import aion_performance'\n file.write(line+\"\\\\n\")\n line = 'from '+package_name+' import aion_drift'\n file.write(line+ \"\\\\n\")\n line = 'from '+package_name+' import featureslist'\n file.write(line+ \"\\\\n\")\n line = 'from '+package_name+' import aion_prediction'\n file.write(line+ \"\\\\n\")\n file.write(content)\n file.close()\n status = 'File Exist'\n if status == 'File Exist': \n command = \"python \"+modelservicefile+' '+str(portNo)+' '+str(ip)\n os.system('start cmd /c \"'+command+'\"')\n \n \ndef checkInstalledPackge(package_name):\n import importlib.util\n spec = importlib.util.find_spec(package_name)\n if spec is None:\n return('Not Installed','','')\n else:\n if len(spec.submodule_search_locations) > 0:\n displaypath = os.path.join(spec.submodule_search_locations[0],'etc','display.json') \n with open(displaypath) as file:\n config = json.load(file)\n file.close()\n if 'usecasename' in config:\n modelName = config['usecasename']\n else:\n modelName = 'NA'\n \n if 'version' in config:\n version = config['version']\n else:\n version = 'NA'\n return('Installed',modelName,version) '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os,sys\nfrom appbe import compute\nfrom appbe.aion_config import kafka_setting\nfrom appbe.aion_config import running_setting\nfrom records import pushrecords\nfrom appbe import service_url\nimport json\nimport time\nimport pandas as pd\nfrom django.db.models import Max, F\nfrom os.path import expanduser\nimport platform\nfrom appbe.data_io import sqlite_db\nimport subprocess\nfrom appbe.dataPath import DEFAULT_FILE_PATH\nfrom appbe.dataPath import DATA_FILE_PATH\nfrom appbe.dataPath import CONFIG_FILE_PATH\nfrom appbe.dataPath import DEPLOY_LOCATION\nfrom appbe.dataPath import DATA_DIR\nDEPLOY_DATABASE_PATH = os.path.join(DATA_DIR,'sqlite')\ndef pushRecordForTraining():\n\tfrom appbe.pages import getversion\n\tAION_VERSION = getversion()\n\ttry:\n\t\tstatus,msg = pushrecords.enterRecord(AION_VERSION)\n\texcept Exception as e:\n\t\tprint(\"Exception\", e)\n\t\tstatus = False\n\t\tmsg = str(e)\n\treturn status,msg\n \ndef getversion():\n configFolder = \tos.path.join(os.path.dirname(os.path.abspath(__file__)),'..','config')\n version = 'NA'\n for file in os.listdir(configFolder):\n if file.endswith(\".var\"):\n version = file.rsplit('.', 1)\n version = version[0]\n break\n return version\ndef getusercasestatus(request):\n if 'UseCaseName' in request.session:\n selected_use_case = request.session['UseCaseName']\n else:\n selected_use_case = 'Not Defined'\n\n if 'ModelVersion' in request.session:\n ModelVersion = request.session['ModelVersion']\n else:\n ModelVersion = 0\n\n if 'ModelStatus' in request.session:\n ModelStatus = request.session['ModelStatus']\n else:\n ModelStatus = 'Not Trained'\n return selected_use_case,ModelVersion,ModelStatus\n\ndef getMLModels(configSettingsJson):\n mlmodels =''\n dlmodels = ''\n problem_type = \"\"\n problemtypes = configSettingsJson['basic']['analysisType'] \n for k in problemtypes.keys():\n if configSettingsJson['basic']['analysisType'][k] == 'True':\n problem_type = k\n break\n sc = \"\"\n if problemtypes in ['classification','regression','survivalAnalysis']:\n scoringCreteria = configSettingsJson['basic']['scoringCriteria'][problem_type]\n for k in scoringCreteria.keys():\n if configSettingsJson['basic']['scoringCriteria'][problem_type][k] == 'True':\n sc = k\n break\n else:\n sc = 'NA'\n if problem_type in ['classification','regression']:\n algorihtms = configSettingsJson['basic']['algorithms'][problem_type]\n #print(algorihtms)\n for k in algorihtms.keys():\n #print(configSettingsJson['basic']['algorithms'][problem_type][k])\n if configSettingsJson['basic']['algorithms'][problem_type][k] == 'True':\n if k in ['SNN','RNN','CNN']:\n if dlmodels != '':\n dlmodels += ', '\n dlmodels += k\n else:\n if mlmodels != '':\n mlmodels += ', '\n mlmodels += k \n elif problem_type in ['videoForecasting','imageClassification','objectDetection']: \n algorihtms = configSettingsJson['basic']['algorithms'][problem_type]\n for k in algorihtms.keys():\n if configSettingsJson['basic']['algorithms'][problem_type][k] == 'True':\n if dlmodels != '':\n dlmodels += ', '\n dlmodels += k\n else:\n algorihtms = configSettingsJson['basic']['alg", "instruction": "", "output": "" }, { "input": "orithms'][problem_type]\n for k in algorihtms.keys():\n if configSettingsJson['basic']['algorithms'][problem_type][k] == 'True':\n if mlmodels != '':\n mlmodels += ', ' \n mlmodels += k\n displayProblemType = problem_type\n selected_model_size = ''\n if problem_type.lower() == 'llmfinetuning':\n displayProblemType = 'LLM Fine-Tuning'\n supported_model_types = configSettingsJson['basic']['modelSize'][problem_type][mlmodels]\n for k in supported_model_types.keys():\n if configSettingsJson['basic']['modelSize'][problem_type][mlmodels][k] == 'True':\n selected_model_size = k\n break\n #print(selected_model_size)\n if mlmodels == 'TF_IDF':\n mlmodels = 'TF-IDF'\n if mlmodels == 'LatentSemanticAnalysis':\n mlmodels = 'Latent Semantic Analysis (LSA)'\n if mlmodels == 'SentenceTransformer_distilroberta':\n mlmodels = 'SentenceTransformer (DistilRoBERTa)'\n if mlmodels == 'SentenceTransformer_miniLM':\n mlmodels = 'SentenceTransformer (MiniLM)'\n if mlmodels == 'SentenceTransformer_mpnet':\n mlmodels = 'SentenceTransformer (MPNet)'\n return(problem_type,displayProblemType,sc,mlmodels,dlmodels,selected_model_size)\n \ndef get_usecase_page(request,usecasedetails,Existusecases,usecaseId = None,search_text=None):\n \n try:\n x = request.build_absolute_uri().split(\"http://\")\n y =\tx[1].split(\"/\")\n url = y[0].split(\":\")\n tacking_url = url[0]\n except:\t\n tacking_url = '127.0.0.1'\t\n computeinfrastructure = compute.readComputeConfig()\n \n \n \n ruuningSetting = running_setting()\n selected_use_case,ModelVersion,ModelStatus = getusercasestatus(request)\n status = 'SUCCESS'\n ser_url = service_url.read_service_url_params(request)\n hosturl =request.get_host()\n hosturl = hosturl.split(':') \n hosturl = hosturl[0]\n packagetip='''\nCall From Command Line\n1. Click AION Shell\n2. python {packageAbsolutePath}/aion_prediction.py {json_data}\nCall As a Package\n1. Go To package_path\\\\WHEELfile\n2. python -m pip install {packageName}-py3-none-any.whl\nCall the predict function after wheel package installation\n1. from {packageName} import aion_prediction as p1\n2. p1.predict({json_data})'''\t\n models = Existusecases.objects.filter(Status='SUCCESS').order_by('-id')\n usecase = usecasedetails.objects.all().order_by('-id')\n usecase = landing_page(usecasedetails,Existusecases,hosturl,usecaseId,search_text) \n if len(usecase) > 0: \t\t\n nouc = usecasedetails.objects.latest('id') \n nouc = (nouc.id)+1\n nouc = str(nouc).zfill(4)\n else:\n nouc = 1 \t\t\n nouc = str(nouc).zfill(4)\n description_text = 'This is a usecase for AI' + str(nouc)\n 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,\n 'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion, 'selected': 'usecase','computeinfrastructure':computeinfrastructure,'computeinfrastructure':computeinfrastructure,'ruuningSetting':ruuningSetting}\n return status,context,'usecases.html'\n\ndef checkText(configPath):\n isText='False'\n with open(configPath) as config:\n data = json.load(config)\n for feature in data['advance']['profiler']['featureDict'] :\n if feature['type']=='text':\n isText = 'True';\n break;\n\n return isText\n \n# For Task ID 12393\n# For BUG ID 13161\ndef checkFE(configPath): \n isFE = 'False'\n with open(configPath) as config:\n data = json.load(config)\n is_selection_method = data.get('advance', {}).get('selector', {}).get('selectionMethod', {}).get('featureEngineering','False')\n feature_dict= data.get('advance', {}).get('selector', {}).get('featureEngineering', {})\n if 'null' in feature_dict.keys():\n feature_dict.pop('null')\n if is_selection_method == 'True' or 'True' in list(feature_dict.values()):\n isFE = 'True' \n return isFE \n\ndef get_model(Existusecases,usercaseid,version=-1):\n from django.core import serializers\n if version == -1:\n models = Existusecases.objects.filter(ModelName=usercaseid).order_by('-id')\n else:\n models = Existusecases.objects.filter(ModelName=usercaseid,Version=version).order_by('-id')\n for model in models:\n model.scoringCreteria = 'NA'\n model.score = 'NA'\n model.deploymodel = 'NA'\n model.problemType = 'NA'\n model.maacsupport = 'False' \n model.flserversupport = 'False'\n model.onlinelerningsupport = 'False'\n model.oltrainingdetails=''\n model.xplain = 'True'\n model.isText = 'False' \n problemTypeNames = {'topicmodelling':'TopicModelling','anomalydetection':'AnomalyDetection'}\n if model.Status == 'SUCCESS':\n if os.path.isdir(str(model.DeployPath)):\n modelPath = os.path.join(str(model.DeployPath),'etc','output.json')\n try:\t\n with open(modelPath) as file:\n outputconfig = json.load(file)\n file.close()\n if outputconfig['status'] == 'SUCCESS':\n model.scoringCreteria = outputconfig['data']['ScoreType']\n model.score = outputconfig['data']['BestScore']\n model.deploymodel = outputconfig['data']['BestModel']\n model.problemType = outputconfig['data']['ModelType']\n if model.problemType in ['topicmodelling','anomalydetection']:\n model.problemType = problemTypeNames[model.problemType]\n model.featuresused = outputconfig['data']['featuresused']\n model.targetFeature = outputconfig['data']['targetFeature']\n if 'params' in outputconfig['data']:\n model.modelParams = outputconfig['data']['params']\n model.modelType = outputconfig['data']['ModelType']\n model.isText = checkText(str(model.ConfigPath))\n model.isFeatureEng = checkFE(str(model.ConfigPath))#task id 12393\n model.dataPath = os.path.join(str(model.DeployPath),'data', 'postprocesseddata.csv.gz')\n mlacSupportedModel = [\"Logistic Regression\",\"Naive Bayes\",\"Decision Tree\",\"Random Forest\",\n \"Support Vector Machine\",\"K Nearest Neighbors\",\"Gradient Boosting\",\"Extreme Gradient Boosting (XGBoost)\",\"Light Gradient Boosting (LightGBM)\",\n \"Categorical Boosting (CatBoost)\",\"Linear Regression\",\"Lasso\",\"Ridge\",\"MLP\",\"LSTM\"]\n\n if model.problemType.lower() in ['classification','regression','timeseriesforecasting']: #task 11997\n if model.deploymodel in mlacSupportedModel:\n model.maacsupport = 'True'\n if model.problemType.lower() not in ['classification','regression']:\n model.xplain = 'False' \n elif model in [\"Neural Architecture Search\"]:\n model.xplain = 'False' \n model.flserversupport = 'False'\n model.onlinelerningsupport = 'False'\n supportedmodels = [\"Logistic Regression\",\"Neural Network\",\"Linear Regression\"]\n if model.deploymodel in supportedmodels:\n model.flserversupport = 'True'\n else:\n model.flserversupport = 'False'\n supportedmodels = [\"Extreme Gradient Boosting (XGBoost)\"]\n if model.deploymodel in supportedmodels:\n model.encryptionsupport = 'True'\n else:\n model.encryptionsupport = 'False' \n supportedmodels = [\"Online Decision Tree Classifier\",\"Online Logistic Regression\",\"Online Linear Regression\",\"Online Decision Tree Regressor\",\"Online KNN Regressor\",\"Online Softmax Regression\",\"Online KNN Classifier\"]\n if model.deploymodel in supportedmodels:\n model.onlinelerningsupport = 'True'\n onlineoutputPath = os.path.join(str(model.DeployPath),'production','Config.json')\n with open(onlineoutputPath) as file:\n onlineoutputPath = json.load(file)\n file.close()\n details = {'Score' :onlineoutputPath['metricList'],'DataSize':onlineoutputPath['trainRowsList']}\n dfonline = pd.DataFrame(details)\n model.oltrainingdetails = dfonline\n else:\n model.onlinelerningsupport = 'False' \n except Exception as e: \n print(e)\n pass\n \n return models\n\n\ndef landing_page(usecasedetails,Existusecases,hosturl,usecaseId = None,search_text=None):\n \n sqlite_dbObj = sqlite_db(DEPLOY_DATABASE_PATH,'deploy.db')\n if usecaseId:\n usecase = usecasedetails.objects.filter(id=usecaseId)\n \n else:\n if search_text:\n usecase = usecasedetails.objects.filter(UsecaseName__contains=str(search_text)).order_by('-id')\n else:\n #usecase = usecasedetails.objects.all().order_by('-id')[:100] #top 100 records\n usecase = usecasedetails.objects.all().order_by('-id') #top 100 records\n usecaselist=[]\n\n if not usecaseId:\n for x in usecase:\n problemType= 'NA'\n publish_url = ''\n otherModel = {}\n models = Existusecases.objects.filter(Status='SUCCESS',publishStatus='Published',ModelName=x.id).order_by('-id')\n \n if len(models) > 0:\n #print(models[0])\n version = models[0].Version \n if os.path.isdir(str(models[0].DeployPath)):\n modelPath = os.path.join(str(models[0].DeployPath),'etc','output.json')\n with open(modelPath) as file:\n outputconfig = json.load(file)\n problemType = outputconfig['data']['ModelType']\n #print(problemType.lower())\n if problemType.lower() == \"llm fine-tuning\":\n cloudconfig = os.path.normpath(\n os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'config', 'compute_conf.json'))\n print(cloudconfig)\n from appbe.models import get_instance\n hypervisor,instanceid,region,image,status = get_instance(x.usecaseid+ '_' + str(version))\n from llm.llm_inference import get_ip\n instanceip = get_ip(cloudconfig,instanceid,hypervisor,region,image) #usnish__ server maynot running\n if instanceip != '':\n publish_url = 'http://' + instanceip + ':' + '8000' + '/generate'\n else:\n publish_url = 'service not available'\n else:\n publish_url = 'http://'+hosturl+':'+str(models[0].portNo)+'/AION/'+x.usecaseid+'/predict'\n publish_status = 'Published'\n #publish_url = 'http://'+hosturl+':'+str(models[0].portNo)+'/AION/'+x.usecaseid+'/predict'\n parentModel = get_model(Existusecases,x.id,int(version))\n else:\n models = Existusecases.objects.filter(Status='SUCCESS',ModelName=x.id).order_by('-id')\n if len(models) > 0:\n publish_status = 'Trained'\n version = models[0].Version\n parentModel = get_model(Existusecases,x.id,int(version))\n else:\n models = Existusecases.objects.filter(ModelName=x.id).order_by('-id')\n if len(models)==0:\n publish_status= 'Not Trained'\n version = -1 \n else:\n if models[0].Status == 'FAIL':\n publish_status= 'Failed'\n elif models[0].Status == 'Running':\n publish_status = 'Running'\n else:\n publish_status='Not Trained'\n \n problemType = models[0].ProblemType\n version = models[0].Version\n parentModel={}\n 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}\n usecaselist.append(usecasedetails)\n else:\n for x in usecase:\n otherModel = get_model(Existusecases,x.id)\n problemType = otherModel[0].problemType\n usecasedetails = {'uuid':x.id,'description':x.Description,'usecase':x.UsecaseName,'status':'','version':'','parentModel':{},'otherModel':otherModel,'problemType':problemType}\n usecaselist.append(usecasedetails) \n \n return usecaselist\ndef get_landing_model(Existusecases):\n models = Existusecases.objects.filter(Status='SUCCESS').order_by('-id')\n for model in models:\n model.scoringCreteria = 'NA'\n model.score = 'NA'\n model.deploymodel = 'NA'\n if os.path.isdir(str(model.DeployPath)):\n modelPath = os.path.join(str(model.DeployPath),'etc','output.json')\n try:\t\n with open(modelPath) as file:\n outputconfig = json.load(file)\n file.close()\n if outputconfig['status'] == 'SUCCESS':\n model.scoringCreteria = outputconfig['data']['ScoreType']\n model.score = outputconfig['data']['BestScore']\n model.deploymodel = outputconfig['data']['BestModel']\n model.problemType = outputconfig['data']['ModelType']\n model.ma", "instruction": "", "output": "" }, { "input": "acsupport = 'True'\n model.flserversupport = 'False'\n model.onlinelerningsupport = 'False'\n supportedmodels = [\"Logistic Regression\",\"Neural Network\",\"Linear Regression\"]\n if model.deploymodel in supportedmodels:\n model.flserversupport = 'True'\n else:\n model.flserversupport = 'False'\n supportedmodels = [\"Extreme Gradient Boosting (XGBoost)\"]\n if model.deploymodel in supportedmodels:\n model.encryptionsupport = 'True'\n else:\n model.encryptionsupport = 'False' \n supportedmodels = [\"Online Decision Tree Classifier\",\"Online Logistic Regression\"]\n if model.deploymodel in supportedmodels:\n model.onlinelerningsupport = 'True'\n onlineoutputPath = os.path.join(str(model.DeployPath),'production','Config.json')\n with open(onlineoutputPath) as file:\n onlineoutputPath = json.load(file)\n file.close()\n details = {'Score' :onlineoutputPath['metricList'],'DataSize':onlineoutputPath['trainRowsList']}\n dfonline = pd.DataFrame(details)\n model.oltrainingdetails = dfonline\n else:\n model.onlinelerningsupport = 'False' \n except Exception as e: \n pass\n return models\n\ndef usecase_page(request,usecasedetails,Existusecases,usecaseid,search_text):\n \n try:\n from appbe import read_service_url_params\n tacking_url = read_service_url_params(request)\n except:\t\n tacking_url = '127.0.0.1'\t\n hosturl =request.get_host()\n hosturl = hosturl.split(':') \n hosturl = hosturl[0]\n computeinfrastructure = compute.readComputeConfig() \n from appbe.aion_config import settings\n usecasetab = settings()\n kafkaSetting = kafka_setting()\n ruuningSetting = running_setting()\n selected_use_case,ModelVersion,ModelStatus = getusercasestatus(request)\n status,msg = pushRecordForTraining()\n if status == False:\n context = {'msg':msg}\n context['selected'] = 'License'\n return status,context,'licenseexpired.html'\n ser_url = service_url.read_service_url_params(request)\n packagetip='''\nCall From Command Line\n1. Click AION Shell\n2. python {packageAbsolutePath}/aion_predict.py {json_data}\nCall As a Package\n1. Go To package_path\\\\publish\\\\package\n2. python -m pip install {packageName}-py3-none-any.whl\nCall the predict function after wheel package installation\n1. from {packageName} import aion_predict as p1\n2. p1.predict({json_data})'''\n if request.method == \"POST\":\n usecasename = request.POST.get('UsecaseName')\n description = request.POST.get('Description')\n usecaseid = request.POST.get('usecaseid')\n #print('1',usecasename)\n if (usecasename == ''):\n \n usecase = landing_page(usecasedetails,Existusecases,hosturl)\n if len(usecase) > 0: \t\t\n nouc = usecasedetails.objects.latest('id') \n nouc = (nouc.id)+1\n else:\n nouc = 1\n nouc = str(nouc).zfill(4)\n description_text = 'This is a usecase for AI' + str(nouc)\n 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,\n 'ModelVersion': ModelVersion, 'selected': 'usecase','computeinfrastructure':computeinfrastructure,'kafkaSetting':kafkaSetting,'ruuningSetting':ruuningSetting}\n return status,context,'usecases.html'\n else:\n usecase_count = usecasedetails.objects.filter(usecaseid=usecaseid).count()\n usecasename_count = usecasedetails.objects.filter(UsecaseName=usecasename).count()\n usecase = landing_page(usecasedetails,Existusecases,hosturl)\n \n \n \n if (usecase_count > 0) or (usecasename_count > 0):\n \n nouc = usecasedetails.objects.latest('id') \n nouc = (nouc.id)+1\n nouc = str(nouc).zfill(4)\n Msg = 'Error in usecase creating, try again'\n if usecase_count > 0:\n Msg = 'Error in usecase creating, try again'\n if usecasename_count > 0:\n Msg = 'There is already a use case with same name, please provide unique name'\n description_text = 'This is a usecase for AI' + str(nouc)\n 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,\n 'ModelVersion': ModelVersion, 'selected': 'usecase','computeinfrastructure':computeinfrastructure,'kafkaSetting':kafkaSetting,'ruuningSetting':ruuningSetting}\n return status,context,'usecases.html'\n \n else:\n clusteringModels = Existusecases.objects.filter(Status='SUCCESS',ProblemType='unsupervised').order_by('-id')\n from appbe.s3bucketsDB import get_s3_bucket\n from appbe.gcsbucketsDB import get_gcs_bucket\n from appbe.azureStorageDB import get_azureStorage\n p = usecasedetails(UsecaseName=usecasename,usecaseid=usecaseid,Description=description)\n p.save()\n s1 = Existusecases.objects.filter(ModelName=p.id).annotate(maxver=Max('ModelName__existusecases__Version'))\n config_list = s1.filter(Version=F('maxver'))\n if config_list.count() > 0:\n Version = config_list[0].Version\n Version = Version + 1\n else:\n Version = 1 \n ps = Existusecases(DataFilePath='', DeployPath='', Status='Not Trained',ConfigPath='', Version=Version, ModelName=p,TrainOuputLocation='')\n ps.save()\n request.session['ModelName'] = p.id\n request.session['UseCaseName'] = usecasename\n request.session['usecaseid'] = usecaseid\n request.session['ModelVersion'] = Version\n request.session['ModelStatus'] = 'Not Trained'\n request.session['currentstate'] = 0\n request.session['finalstate'] = 0\n selected_use_case = usecasename\n model_status = 'Not Trained'\n ModelVersion = Version\n from appbe.telemetry import UseCaseCreated\n UseCaseCreated(usecaseid+'-'+str(Version))\n if len(usecase) > 0:\n nouc = usecasedetails.objects.latest('id') \n nouc = (nouc.id)+1\n else:\n nouc = 1\n nouc = str(nouc).zfill(4)\n description_text = 'This is a usecase for AI' + str(nouc)\n context = {'description_text':description_text,'usecasedetail': usecase, 'nouc': nouc, 'newusercase': usecasename,'tacking_url':tacking_url,'finalstate':request.session['finalstate'],\n '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(),\n 'ModelStatus': model_status, 'ModelVersion': ModelVersion, 'selected': 'modeltraning','computeinfrastructure':computeinfrastructure}\n return status,context,'upload.html'\n else:\n\n\n models = get_landing_model(Existusecases)\n\n usecase = landing_page(usecasedetails,Existusecases,hosturl,usecaseid,search_text)\n if len(usecase) > 0: \t\t\n nouc = usecasedetails.objects.latest('id') \n nouc = (nouc.id)+1\n else:\n nouc = 1\n nouc = str(nouc).zfill(4)\n description_text = 'This is a usecase for AI' + str(nouc)\n 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}\n if usecaseid:\n context.update({'ucdetails':'True'})\n return status,context,'usecases.html'\n \ndef index_page(request,usecasedetails,Existusecases):\n if 'ModelVersion' in request.session:\n del request.session['ModelVersion']\n if 'UseCaseName' in request.session:\n del request.session['UseCaseName']\n if 'ModelStatus' in request.session:\n del request.session['ModelStatus']\n if 'currentstate' in request.session:\n del request.session['currentstate']\n if 'finalstate' in request.session:\n del request.session['finalstate']\n return usecases_page(request,usecasedetails,Existusecases)\n\ndef usecases_page(request,usecasedetails,Existusecases,usecaseid=None,substring=None):\n return usecase_page(request,usecasedetails,Existusecases,usecaseid,substring)\n\ndef mllite_page(request):\n from appbe.aion_config import settings\n usecasetab = settings()\n status,msg = pushRecordForTraining()\n if status == False:\n context = {'selected':'mllite','lerror':msg}\n return context\n configFile = os.path.join(DEFAULT_FILE_PATH, 'model_converter.json')\n f = open(configFile, \"r\")\n configSettings = f.read()\n f.close()\n configSettingsJson = json.loads(configSettings) \n context = {}\n context = {'selected':'mllite','sagemaker':configSettingsJson,'usecasetab':usecasetab}\n return context\ndef mltesting_page(request):\n from appbe.aion_config import settings\n usecasetab = settings() \n status,msg = pushRecordForTraining()\n if status == False:\n context = {'lerror':msg}\n return context\n if request.method == \"POST\":\n models = request.POST['model']\n datap = request.POST['data']\n if(os.path.isfile(models) and os.path.isfile(datap)):\n request.session['datalocation'] = datap\n df = pd.read_csv(datap,encoding='utf-8',skipinitialspace = True,encoding_errors= 'replace')\n trainfea = df.columns.tolist()\n featurs = request.POST.getlist('Training')\n feature = \",\".join(featurs)\n filetimestamp = str(int(time.time()))\n settingconfig = os.path.join(CONFIG_FILE_PATH, 'MLTest_' + filetimestamp + '.json')\n request.session['MLTestResult'] = settingconfig\n mltestresult={}\n mltestresult['models'] = models\n mltestresult['datap'] = datap\n mltestresult['feature'] = feature\n # features = ['PetalLengthCm','PetalWidthCm']\n targ = request.POST['Target']\n tar =[targ]\n mltestresult['target'] = targ\n mltestresult = json.dumps(mltestresult)\n with open(settingconfig, \"w\") as fpWrite:\n fpWrite.write(mltestresult)\n fpWrite.close()\n from pathlib import Path\n mltest={}\n if Path(models).is_file() and Path(datap).is_file():\n try:\n from mltest import baseline\n outputStr = baseline.baseline_testing(models,datap, feature, targ)\n #scriptPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..','bin','run_mltest.py'))\n #print(scriptPath, models, datap, feature, targ)\n #outputStr = subprocess.check_output([sys.executable, scriptPath, models, datap, feature, targ])\n #print(outputStr)\n #outputStr = outputStr.decode('utf-8')\n #outputStr= outputStr.replace('\\\\'','\\\\\"')\n #print('ou',outputStr)\n #outputStr = outputStr.strip()\n mltest = json.loads(outputStr)\n Problemtype= mltest['Problemtype']\n with open(request.session['MLTestResult'], 'r+') as f:\n mltestresult = json.load(f)\n f.close()\n mltestresult['Problemtype'] = Problemtype\n mltestresult['ProblemName'] = mltest['ProblemName']\n status = mltest['Status']\n if status == 'Fail':\n errormsg= mltest['Msg']\n context = {'error':errormsg,'mltest':'mltest'}\n else: \n if Problemtype == 'Classification':\n mltestresult['Score'] = mltest['Accuracy']\n mltestresult['Params'] = mltest['Params']\n Problem= mltest['ProblemName']\n Parameters= mltest['Params']\n round_params = {}\n for key, value in Parameters.items():\n if isinstance(value, float):\n round_params[key] = round(value,2)\n else:\n round_params[key] = value\n matrixconfusion = mltest['Confusionmatrix']\n classificationreport = mltest['classificationreport']\n classificationreport = json.loads(classificationreport)\n matrixconfusion = json.loads(matrixconfusion)\n indexName =[]\n columnName = []\n for i in matrixconfusion.keys():\n \n indexName.append(\"act:\"+str(i))\n \n for j in matrixconfusion[i].keys():\n \n columnName.append(\"pre:\"+str(j))\n df3 = pd.DataFrame.from_dict(classificationreport)\n df = df3.transpose()\n df2 = pd.DataFrame.from_dict(matrixconfusion)\n df1 = pd.DataFrame(df2.values,", "instruction": "", "output": "" }, { "input": "index=indexName,columns=columnName)\n report = df.to_html()\n report1 = df1.to_html()\n recordone = mltest['onerecord']\n recordsten = mltest['tenrecords']\n recordshund = mltest['hundrecords']\n 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}\n \n elif Problemtype == 'Regression':\n Problem= mltest['ProblemName']\n mltestresult['Params'] = mltest['Params'] \n mltestresult['Score'] = mltest['R2']\n Parameters= mltest['Params']\n round_params = {}\n for key, value in Parameters.items():\n if isinstance(value, float):\n round_params[key] = round(value,2)\n else:\n round_params[key] = value\n Mse = mltest['MSE']\n Mae = mltest['MAE']\n Rmse = mltest['RMSE']\n R2 = mltest['R2'] \n recordone = mltest['onerecord']\n recordsten = mltest['tenrecords']\n recordshund = mltest['hundrecords']\n 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}\n else:\n errormsg= mltest['Msg']\n context = {'error':errormsg,'mltest':'mltest'} \n \n \n mltestresult = json.dumps(mltestresult)\n with open(settingconfig, \"w\") as fpWrite:\n fpWrite.write(mltestresult)\n fpWrite.close() \n except Exception as e:\n print(\"-------------\"+str(e)+'=================')\n e = str(e).replace('\\\\'','')\n errormsg = 'Error: Exception '+str(e)\n context = {'error':errormsg,'mltest':'mltest'}\n else:\n if not (Path(models).is_file() and Path(datap).is_file()):\n context = {'error':\"Please Check ModelPath & Datapath Format\",\"result\":\"result\",'selected':'mltesting','usecasetab':usecasetab}\n elif not Path(models).is_file():\n context = {'error':\"Please Check ModelPath Format\",\"result\":\"result\",'selected':'mltesting','usecasetab':usecasetab}\n elif not Path(datap).is_file():\n context = {'error':\"Please Check DataPath Format\",\"result\":\"result\",'selected':'mltesting','usecasetab':usecasetab}\n else:\n context = {'error':'Either model path or data path does not exist','mltest':'mltest','usecasetab':usecasetab}\n else:\n context = {'selected':'mltesting','usecasetab':usecasetab}\n return context '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport pandas as pd\nimport requests\nimport re\n\nimport json\nimport sys\nimport time\n\nfrom appbe.aion_config import get_llm_data\nfrom appbe.dataPath import LOG_LOCATION\nfrom appbe.log_ut import logg\nimport logging\n\nimport openai\nimport tiktoken\n\nopenai.api_key = ''\nopenai.api_base = '' \nopenai.api_type = ''\nopenai.api_version = '' \ndeployment_name=\"Text-Datvinci-03\"\n\n\ndef generateLabelPerRecord(OrgData):\n OrgData['LabelFromGPT'] = OrgData['Head_Description'].apply(lambda x: \\\\\n generate_gpt3_response\\\\\n \n (\"I am giving you the title and short description \\\\\n in the format [Title:Description], \\\\\n give me the related low level topics in one word in the \\\\\n format[Topic: your primary topic] along with top 5 important keywords in the \\\\\n format[Keywords: keywords]'{}' \".format(x)))\n\n #Cleaning the output as it is from ChatGPT\n OrgData['temp1'] = OrgData['LabelFromGPT'].apply(lambda x: (x.split('Topic:')[1]).replace(']',''))\n OrgData['LabelFromGPT'] = OrgData['temp1'].apply(lambda x: (x.split('Keywords:')[0]).replace(']','').rstrip())\n OrgData['Keywords'] = OrgData['temp1'].apply(lambda x: (x.split('Keywords:')[1]).replace(']',''))\n OrgData = OrgData.drop(['temp1','Head_Description'], axis=1)\n return OrgData\n\n\ndef generateLabelForChunkedRecords(OrgData):\n import io\n # OrgData = OrgData.head(120)\n \n Head_Description = {\"Head_Description\": [] }\n Head_Description2 = {\"Head_Description\": [] }\n Head_Description['Head_Description'] = OrgData['Head_Description']\n \n strt_ind = 0\n brk_ind = 0\n # encoding = tiktoken.get_encoding('p50k_base')\n encoding = tiktoken.encoding_for_model(\"text-davinci-003\")\n \n chunks = []\n _cur_token_count = 0\n _chunk_token_count = 0\n \n for ind in Head_Description['Head_Description'].index:\n tokenized_text = encoding.encode(Head_Description['Head_Description'][ind])\n _cur_token_count = len(tokenized_text)\n \n if _cur_token_count >= 600:\n OrgData['Head_Description'][ind] = OrgData['Head_Description'][ind][:1000]\n upto_ind = ind + 1\n \n \n Head_Description2['Head_Description'] = OrgData['Head_Description'][brk_ind:ind]\n _chunk_token_count = encoding.encode(Head_Description2['Head_Description'].to_string())\n if len(_chunk_token_count) >= 1200:\n brk_ind = ind\n # print(brk_ind)\n chunks.append(ind-1)\n \n \n _start_count = 0\n if len(chunks) == 0:\n output = generate_gpt3_response(\"I am giving you datatable of text records \\\\\n for each record give me the related low level topics in one word as a data column called Topic\\\\\n and important top five keywords as a data column called Keywords. \\\\\n 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']))\n \n out = io.StringIO(output[2:])\n df = pd.read_csv(out, sep='\\\\t')\n \n else:\n chunks.append(len(Head_Description['Head_Description']))\n \n for ind_val in chunks:\n _cur_ind_val = ind_val\n _recordsSent = 0\n \n Head_Description = {\"Head_Description\": [] }\n \n if _start_count == 0:\n Head_Description['Head_Description'] = OrgData['Head_Description'][strt_ind:_cur_ind_val].to_string()\n _recordsSent = len(OrgData['Head_Description'][strt_ind:_cur_ind_val])\n else:\n Head_Description['Head_Description'] = OrgData['Head_Description'][_pre_ind_val:_cur_ind_val].to_string()\n _recordsSent = len(OrgData['Head_Description'][_pre_ind_val:_cur_ind_val])\n \n _pre_ind_val = ind_val\n \n \n # if _start_count <= 5:\n output = generate_gpt3_response(\"I am giving you datatable of text records \\\\\n for each record give me the related low level topics in one word as a data column called Topic\\\\\n and important top five keywords as a data column called Keywords. \\\\\n 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']))\n \n \n out = io.StringIO(output[2:])\n \n if _start_count == 0:\n df = pd.read_csv(out, sep='\\\\t')\n else:\n df_tmp = pd.read_csv(out, sep='\\\\t')\n \n if len(df_tmp) > _recordsSent:\n df_tmp = df_tmp.head(_recordsSent)\n \n # df = df.append(df_tmp, ignore_index=True)\n df = pd.concat([df, df_tmp], ignore_index=True)\n \n _start_count += 1\n \n OrgData['LabelFromGPT'] = df['Topic']\n OrgData['Keywords'] = df['Keywords']\n OrgData = OrgData.drop(['Head_Description'], axis=1)\n return OrgData\n \n\n\n# Text Data Labelling using LLM related changes\n# --------------------------------------------------------\ndef generateTextLabel(request, DATA_FILE_PATH):\n log = logging.getLogger('log_ux')\n \n key,url,api_type,api_version = get_llm_data()\n openai.api_key = key\n openai.api_base = url\n openai.api_type = api_type\n openai.api_version = api_version\n \n try:\n features = request.POST.getlist('InputFeatures')\n datapath = request.session['textdatapath']\n OrgData = pd.read_csv(datapath)\n \n # OrgData = OrgData.head(2000)\n OrgData.fillna(\"\", inplace = True)\n \n OrgData['Head_Description'] = OrgData[features[0]]\n if (len(features) > 1):\n for indx in range(len(features)):\n if (indx > 0):\n OrgData['Head_Description'] = OrgData['Head_Description'] + \" \"+ OrgData[features[indx]]\n \n \n # OrgData = generateLabelPerRecord(OrgData)\n OrgData = generateLabelForChunkedRecords(OrgData)\n \n df = OrgData\n \n filetimestamp = str(int(time.time()))\n datasetName = 'AION_TextLabelled' + filetimestamp+'.csv'\n dataFile = os.path.join(DATA_FILE_PATH,datasetName)\n df.to_csv(dataFile)\n request.session['texttopicdatapath'] = dataFile\n \n df_json = df.to_json(orient=\"records\")\n df_json = json.loads(df_json)\n\n\n\n from appbe.dataPath import DATA_DIR\n from appbe.sqliteUtility import sqlite_db\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'config.db')\n newdata = {}\n newdata['datapath'] = [dataFile]\n newdata['datasetname'] = [datasetName]\n sqlite_obj.write_data(pd.DataFrame.from_dict(newdata), 'dataingest')\n\n\n ################################################\n\n context = {'data_topic':df_json, 'selected':'DataOperations'}\n return context\n \n except Exception as e:\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n \n errormsg = str(e)\n \n if 'Invalid URL' in errormsg or 'No connection adapters' in errormsg or 'invalid subscription key' in errormsg:\n 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.'\n \n if 'Max retries exceeded with url' in errormsg:\n errormsg = 'Please make sure you have good internet connection and access to API endpoint for your resource.'\n \n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n \n context = {'error': 'Failed to communicate LLM','LLM' : 'openAI', 'selected':'DataOperations', 'errormessage':errormsg}\n log.info('generateTextLabel -- Error : Failed to generate Text-Label.. '+str(e))\n log.info('Details : '+ str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n return context\n\n\n#function to return the queried response\ndef generate_gpt3_response(user_text, print_output=False):\n \"\"\"\n Query OpenAI GPT-3 for the specific key and get back a response\n :type user_text: str the user's text to query for\n :type print_output: boolean whether or not to print the raw output JSON\n \"\"\"\n time.sleep(2)\n \n completions = openai.Completion.create(\n # engine='Text-Datvinci-03', # Determines the quality, speed, and cost. engine='text-davinci-003',\n engine=deployment_name, # Determines the quality, speed, and cost. engine='text-davinci-003',\n \n temperature=0, # Level of creativity in the response\n prompt=user_text, # What the user typed in\n max_tokens=2000, # Maximum tokens in the prompt AND response\n n=1, # The number of completions to generate\n stop=None, # An optional setting to control response generation\n )\n\n # Displaying the output can be helpful if things go wrong\n if print_output:\n print(completions)\n\n # Return the first choice's text\n # print(completions.choices[0].text)\n return completions.choices[0].text\n \n# -------------------------------------------------------- '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n", "instruction": "", "output": "" }, { "input": "* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport json\n\nimport pandas as pd\n\n\ndef get_true_option(d, default_value=None):\n\tif isinstance(d, dict):\n\t\tfor k, v in d.items():\n\t\t\tif (isinstance(v, str) and v.lower() == 'true') or (isinstance(v, bool) and v == True):\n\t\t\t\treturn k\n\treturn default_value\n\n\ndef get_true_options(d):\n\toptions = []\n\tif isinstance(d, dict):\n\t\tfor k, v in d.items():\n\t\t\tif (isinstance(v, str) and v.lower() == 'true') or (isinstance(v, bool) and v == True):\n\t\t\t\toptions.append(k)\n\treturn options\n\ndef check_datetime(config):\n\tdateTime = config['basic']['dateTimeFeature']\n\tif dateTime == '' or dateTime.lower()=='na':\n\t\treturn False\n\treturn True\n\ndef check_dtype(d):\n\tflag= 1\n\tfor item in d:\n\t\tif item[\"type\"].lower() != \"text\" and item[\"type\"].lower() != \"index\":\n\t\t\tflag = 0\n\t\t\tbreak\n\treturn flag\n\ndef check_text(d): #task 12627\n\tflag= 0\n\tfor item in d:\n\t\tif item[\"type\"].lower() == \"text\":\n\t\t\tflag = 1\n\t\t\tbreak\n\treturn flag\n\ndef check_labelencoding(ftr_dict_list, target_ftr):\n\tfor ftr_dict in ftr_dict_list:\n\t\tif ftr_dict['feature']!=target_ftr and ftr_dict['type'].lower()=='categorical' and ftr_dict['categoryEncoding'].lower()!='labelencoding':\n\t\t\treturn False\n\treturn True\n\nclass timeseries():\n\n\tdef __init__(self,config):\n\t\tself.config=config\n\t\tif self.config['basic']['analysisType']['timeSeriesForecasting'].lower()=='true': #task 11997\n\t\t\tself.problemType = 'timeSeriesForecasting'\n\t\telif self.config['basic']['analysisType']['timeSeriesAnomalyDetection'].lower()=='true':\n\t\t\tself.problemType = 'timeSeriesAnomalyDetection' #task 11997\n\n\tdef validate_basic_config(self,status='pass',msg=None):\n\t\t#task 12627\n\t\tdate_time_status = check_datetime(self.config)\n\t\ttext_status = check_text(self.config['advance']['profiler']['featureDict'])\n\t\tif not date_time_status and text_status:\n\t\t\tmsg = 'For time series problem,\\\\\\\\n* One feature should be in datetime format\\\\\\\\n* Text feature not supported '\n\t\t\treturn 'error', msg\n\t\telif not date_time_status:\n\t\t\tmsg = 'For time series problem, one feature should be in datetime format'\n\t\t\treturn 'error', msg\n\t\telif text_status:\n\t\t\tmsg = 'For time series problem, text feature not supported '\n\t\t\treturn 'error', msg\n\t\tselected_algos = get_true_options(self.config['basic']['algorithms'][self.problemType]) #task 11997\n\t\tif isinstance(self.config['basic']['targetFeature'],str):\n\t\t\ttargetFeature = list(self.config['basic']['targetFeature'].split(','))\n\t\tif self.problemType=='timeSeriesForecasting': #task 11997\n\t\t\tif len(targetFeature) > 1:\n\t\t\t\tif 'ARIMA' in selected_algos:\n\t\t\t\t\tstatus = 'error'\n\t\t\t\t\tmsg = \"ARIMA is not supported for multilabel (target) feature\"\n\t\t\t\t\treturn status, msg\n\t\t\t\tif \"FBPROPHET\" in selected_algos:\n\t\t\t\t\tstatus = 'error'\n\t\t\t\t\tmsg = \"FBPROPHET is not supported for multiLabel (target) feature\"\n\t\t\t\t\treturn status, msg\n\t\t\t\tif 'MLP' in selected_algos:\n\t\t\t\t\tstatus = 'error'\n\t\t\t\t\tmsg = \"MLP is not supported for multiLabel (target) feature\"\n\t\t\t\t\treturn status, msg\n\t\t\tif len(targetFeature) == 1 and 'VAR' in selected_algos:\n\t\t\t\tstatus = 'error'\n\t\t\t\tmsg = \"VAR is not supported for singleLabel (target) feature\"\n\t\t\t\treturn status, msg\n\t\telif self.problemType=='timeSeriesAnomalyDetection': #task 11997\n\t\t\tanomChecker = anomaly(self.config)\n\t\t\tstatus, msg = anomChecker.validate_basic_config()\n\t\treturn status, msg\n\n\nclass anomaly():\n \n\tdef __init__(self,config):\n\t\tself.config = config\n\t\tif self.config['basic']['analysisType']['anomalyDetection'].lower()=='true': #task 11997\n\t\t\tself.problemType = 'anomalyDetection'\n\t\telif self.config['basic']['analysisType']['timeSeriesAnomalyDetection'].lower()=='true': #task 11997\n\t\t\tself.problemType = 'timeSeriesAnomalyDetection'\n\n\tdef validate_basic_config(self,status='pass',msg=None):\n\t\t#task 12627\n\t\tdate_time_status = check_datetime(self.config)\n\t\ttargetFeature = self.config['basic']['targetFeature']\n\t\tif self.problemType=='anomalyDetection' and date_time_status:\n\t\t\tstatus = 'error'\n\t\t\tmsg = 'Date feature detected. For anomaly detection on time series change problem type to Time Series Anomaly Detection or drop Date feature'\n\t\t\treturn status, msg\n\t\tif targetFeature.lower()!= 'na' and targetFeature!= \"\" and self.config['basic']['inlierLabels'] == '':\n\t\t\tstatus = 'error'\n\t\t\tmsg = 'Please provide inlier label in case of supervised anomaly detection'\n\t\treturn status, msg\n\nclass survival():\n\n\tdef __init__(self,config):\n\t\tself.config = config\n\t\tself.problemType= 'survivalAnalysis'\n\n\tdef validate_basic_config(self):\n\t\tdateTimeStatus = check_datetime(self.config)\n\t\tlabelencoding_status = check_labelencoding(self.config['advance']['profiler']['featureDict'], self.config['basic']['targetFeature'])\n\t\tif not dateTimeStatus and not labelencoding_status:\n\t\t\tmsg = 'For survival analysis problem,\\\\\\\\n* One feature should be in datetime format\\\\\\\\n* Encoding of categorical features should be of label encoding '\n\t\t\treturn 'error', msg \n\t\telif not dateTimeStatus:\n\t\t\tmsg = 'One feature should be in datetime format for survival analysis problem. Please select it from model feature'\n\t\t\treturn 'error', msg\n\t\telif not labelencoding_status:\n\t\t\tmsg = 'Categorical features are expected to be label encoded for survival analysis problem. Please select it from feature encoding'\n\t\t\treturn 'error', msg\n\t\telse:\n\t\t\treturn 'pass', \" \"\n\nclass associationrule():\n\n\tdef __init__(self,config):\n\t\tself.config=config\n\n\tdef validate_basic_config(self,status='pass', msg=None):\n\t\tif 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':\n\t\t\treturn \"error\",\"Make sure to configure invoice feature and item feature\"\n\t\telif self.config['basic']['algorithms']['recommenderSystem']['associationRulesConfig']['invoiceNoFeature'] == self.config['basic']['algorithms']['recommenderSystem']['associationRulesConfig']['itemFeature']:\n\t\t\treturn \"error\",\"Make sure to invoice feature and item feature is configure correctly\" \n\t\telse:\n\t\t\treturn \"pass\", \" \" \n\nclass itemrating(): #task 6081\n\n\tdef __init__(self,config):\n\t\tself.config = config\n\n\tdef validate_basic_config(self):\n\t\tdata_loc = self.config['basic']['dataLocation']\n\t\tdata_length = len(pd.read_csv(data_loc))\n\t\tif data_length >= 1000000:\n\t\t\treturn 'error', \"Recommender System can handle data up to 1 million records. Please try with a smaller dataset.\"\n\t\telse:\n\t\t\treturn \"pass\",\" \"\n\n\nclass documentsimilarity():\n\n\tdef __init__(self,config):\n\t\tself.config=config\n\n\tdef validate_basic_config(self,status='pass', msg=None):\n\t\tflag = check_dtype(self.config['advance']['profiler']['featureDict'])\n\t\tif flag == 1:\n\t\t\treturn \"pass\", \" \"\n\t\telse:\n\t\t\tmsg=\"Make sure to change the feature type from Categorical to Text and drop Numerical features for document similarity\"\n\t\t\treturn \"error\", msg\n\n\n\n\ndef validate(config):\n\ttry:\n\t\tproblem_type = get_true_option(config['basic']['analysisType'])\n\t\tstatus = 'pass'\n\t\tmsg = ''\n\t\tif 'timeseries' in problem_type.lower(): #task 11997\n\t\t\tobj = timeseries(config)\n\t\telif problem_type.lower() == 'survivalanalysis':\n\t\t\tobj = survival(config)\n\t\telif problem_type.lower() == 'anomalydetection':\n\t\t\tobj = anomaly(config)\n\t\telif problem_type.lower() in ['similarityidentification','contextualsearch']:\n\t\t\tobj = documentsimilarity(config)\n\t\telif problem_type.lower() == 'recommendersystem':\n\t\t\tif config['basic']['algorithms']['recommenderSystem']['AssociationRules-Apriori'].lower() == 'true':\n\t\t\t\tobj = associationrule(config) \n\t\t\telif config['basic']['algorithms']['recommenderSystem']['ItemRating'].lower() == 'true': #task 6081\n\t\t\t\tobj = itemrating(config)\n\t\t\telse:\n\t\t\t\treturn 'pass',\"\" \n\t\telse:\n\t\t\treturn 'pass',\"\"\n\t\tstatus,msg= obj.validate_basic_config()\n\t\tprint(status, msg, 'io')\n\t\treturn(status,msg)\n\texcept Exception as e:\n\t\tprint(e)\n\n\ndef start_check(config):\n return validate(config)\n\n\n\n import json\nimport os\nimport pandas as pd\nimport urllib, base64 \ndef check_deepCheckPlots(deployedLocation):\n deepCheck = 'False'\n boostOverfit = 'False'\n boostOverfitCond = 'False'\n mi='False'\n miCond='False'\n smc = 'False'\n smsCond = 'False'\n boostOverfitFile= os.path.join(deployedLocation,'log','boosting_overfit.html')\n boostOverfitCondFile= os.path.join(deployedLocation,'log','boosting_overfit_condition.html')\n smcFile= os.path.join(deployedLocation,'log','smc.html')\n smcCondFile= os.path.join(deployedLocation,'log','smc_condition.html')\n miFile= os.path.join(deployedLocation,'log','mi.html')\n miConFile= os.path.join(deployedLocation,'log','mi_con.html')\n file_exists = os.path.exists(boostOverfitFile)\n if file_exists:\n deepCheck = 'True'\n boostOverfit = 'True'\n file_exists = os.path.exists(boostOverfitCondFile)\n if file_exists:\n deepCheck = 'True'\n boostOverfitCond = 'True' \n file_exists = os.path.exists(miFile)\n if file_exists:\n deepCheck = 'True'\n mi = 'True' \n file_exists = os.path.exists(miConFile)\n if file_exists:\n deepCheck = 'True'\n miCond = 'True'\n file_exists = os.path.exists(smcFile)\n if file_exists:\n deepCheck = 'True'\n smc = 'True' \n file_exists = os.path.exists(smcCondFile)\n if file_exists:\n deepCheck = 'True'\n smsCond = 'True'\n output = {'deepCheck':deepCheck,'boostOverfit':boostOverfit,'boostOverfitCond':boostOverfitCond,'mi':mi,'miCond':miCond,'smc':smc,'smsCond':smsCond}\n return output\ndef FeaturesUsedForTraining(output_json):\n resultJsonObj = json.loads(output_json) \n result = {}\n result['Status'] = resultJsonObj['status']\n result['ModelType'] = resultJsonObj['data']['ModelType']\n result['ScoreType'] = resultJsonObj['data']['ScoreType']\n result['FeaturesUsed'] = resultJsonObj['data']['featuresused']\n result['BestModel'] = resultJsonObj['data']['BestModel']\n return result \ndef ParseResults(output_json):\n msg1 = 'Results...'\n resultJsonObj = json.loads(output_json)\n result = {}\n survical_images = []\n result['Status'] = resultJsonObj['status']\n result['ModelType'] = resultJsonObj['data']['ModelType']\n if 'vmDetails' in resultJsonObj['data']:\n result['DeployLocation'] = resultJsonObj['data']['vmDetails']\n else:\n result['DeployLocation'] = resultJsonObj['data']['deployLocation']\n result['BestModel'] = resultJsonObj['data']['BestModel']\n if str(resultJsonObj['data']['BestScore']) == \"NA\":\n result['BestScore'] = 'NA'\n else:\n result['BestScore'] = round(float(resultJsonObj['data']['BestScore']), 2)\n result['ScoreType'] = resultJsonObj['data']['ScoreType']\n result['FeaturesUsed'] = resultJsonObj['data']['featuresused']\n ##### Training Confusion Matrix\n result['problem_type'] = result['ModelType'] \n if result['ModelType'].lower() == 'timeseriesanomalydetection':\n result['problem_type'] = 'TimeSeriesAnomalydetection'\n if result['ModelType'] == 'classification' or result['ModelType'].lower() == 'distributed classification' or (result['ModelType'] == 'anomalydetection' and (result['BestScore']) != 0) or result['ModelType'] == 'ImageClassification':\n bestmodel = resultJsonObj['data']['BestModel']\n if bestmodel.lower() == 'nas':\n modelSummary= os.path.join(result['DeployLocation'],'summary.txt')\n f = open(modelSummary, 'r')\n file_content = f.read()\n f.close()\n #print(file_content)\n result['modelSummary'] = file_content\n #task 11997\n if result['ModelType'].lower() == 'classification':\n result['problem_type'] = 'Classification'\n elif result['ModelType'].lower() == 'anomalydetection':\n result['problem_type'] = 'AnomalyDetection'\n elif result['ModelType'].lower() == 'imageclassification':\n result['problem_type'] = 'ImageClassification'\n elif result['ModelType'].lower() == 'distributed classification':\n result['problem_type'] = ", "instruction": "", "output": "" }, { "input": "'Distributed Classification'\n try:\n result['deepCheck'] = check_deepCheckPlots(result['DeployLocation'])\n except Exception as e:\n print(e)\n \n if 'ConfusionMatrix' in resultJsonObj['data']['trainmatrix']:\n TrainConfusionMatrix = resultJsonObj['data']['trainmatrix']['ConfusionMatrix']\n \n numLabels = len(TrainConfusionMatrix)\n TrainConfusionMatrixList = []\n for act_key, value in TrainConfusionMatrix.items():\n temp = {}\n temp['Label'] = act_key\n for pred_key, pred_value in value.items():\n temp[pred_key] = pred_value\n TrainConfusionMatrixList.append(temp)\n result['TrainConfusionMatrix'] = TrainConfusionMatrixList\n\n TrainClassificationReport = resultJsonObj['data']['trainmatrix']['ClassificationReport']\n numRows = len(TrainClassificationReport)\n TrainClassificationReportList = []\n metrics_keys_list = []\n for key, value in TrainClassificationReport.items():\n temp = {}\n temp['Label'] = key\n if isinstance( value, dict):\n for metricsKey, metricsValue in value.items():\n temp[metricsKey] = round(metricsValue, 4)\n if metricsKey not in metrics_keys_list:\n metrics_keys_list.append( metricsKey)\n else:\n if metrics_keys_list:\n for key in metrics_keys_list:\n temp[key] = round(value, 4)\n TrainClassificationReportList.append(temp)\n\n result['TrainClassificationReport'] = TrainClassificationReportList\n result['Train_ROC_AUC_SCORE'] = round(float(resultJsonObj['data']['trainmatrix']['ROC_AUC_SCORE']), 4)\n else:\n result['TrainClassificationReport'] = ''\n result['Train_ROC_AUC_SCORE']=''\n \n ##### Testing Confusion Matix\n if 'ConfusionMatrix' in resultJsonObj['data']['matrix']:\n ConfusionMatrix = resultJsonObj['data']['matrix']['ConfusionMatrix']\n numLabels = len(ConfusionMatrix)\n ConfusionMatrixList = []\n for act_key, value in ConfusionMatrix.items():\n temp = {}\n temp['Label'] = act_key\n for pred_key, pred_value in value.items():\n temp[pred_key] = pred_value\n ConfusionMatrixList.append(temp)\n result['ConfusionMatrix'] = ConfusionMatrixList\n\n ClassificationReport = resultJsonObj['data']['matrix']['ClassificationReport']\n numRows = len(ClassificationReport)\n ClassificationReportList = []\n metrics_keys_list = []\n for key, value in ClassificationReport.items():\n temp = {}\n temp['Label'] = key\n if isinstance( value, dict):\n for metricsKey, metricsValue in value.items():\n temp[metricsKey] = round(metricsValue, 4)\n if metricsKey not in metrics_keys_list:\n metrics_keys_list.append( metricsKey)\n else:\n if metrics_keys_list:\n for key in metrics_keys_list:\n temp[key] = round(value, 4)\n ClassificationReportList.append(temp)\n\n result['ClassificationReport'] = ClassificationReportList\n result['ROC_AUC_SCORE'] = round(float(resultJsonObj['data']['matrix']['ROC_AUC_SCORE']), 4)\n elif result['ModelType'] == 'similarityIdentification':\n result['problem_type'] = 'similarityIdentification'\n elif result['ModelType'] == 'contextualSearch':\n result['problem_type'] = 'contextualSearch'\n elif result['ModelType'] == 'MultiLabelPrediction':\n result['problem_type'] = 'MultiLabelPrediction'\n matrix = resultJsonObj['data']['matrix']\n training_matrix = []\n for x in matrix:\n fmatrix = {}\n fmatrix['feature'] = x\n performance = {}\n for y in matrix[x]:\n performance[y] = matrix[x][y]\n fmatrix['performance'] = performance\n training_matrix.append(fmatrix)\n testmatrix = resultJsonObj['data']['testmatrix']\n testing_matrix = []\n for x in testmatrix:\n fmatrix = {}\n fmatrix['feature'] = x\n performance = {}\n for y in testmatrix[x]:\n performance[y] = testmatrix[x][y]\n fmatrix['performance'] = performance\n testing_matrix.append(fmatrix)\n result['testing_matrix'] = testing_matrix\n result['training_matrix'] = training_matrix \n elif result['ModelType'] == 'regression' or result['ModelType'].lower() == 'distributed regression':\n try:\n result['deepCheck'] = check_deepCheckPlots(result['DeployLocation'])\n except Exception as e:\n print(e) \n try:\n result['problem_type'] = 'Regression'\n testing_matrix = {}\n if 'MAE' in resultJsonObj['data']['matrix']:\n testing_matrix['MAE'] = float(resultJsonObj['data']['matrix'].get('MAE','0'))\n testing_matrix['R2Score'] = float(resultJsonObj['data']['matrix'].get('R2Score','0'))\n testing_matrix['MSE'] = float(resultJsonObj['data']['matrix'].get('MSE','0'))\n testing_matrix['MAPE'] = float(resultJsonObj['data']['matrix'].get('MAPE','0'))\n testing_matrix['RMSE'] = float(resultJsonObj['data']['matrix'].get('RMSE','0'))\n testing_matrix['NormalisedRMSEPercentage'] = float(resultJsonObj['data']['matrix'].get('Normalised RMSE(%)','0'))\n result['testing_matrix'] = testing_matrix\n training_matrix = {}\n training_matrix['MAE'] = float(resultJsonObj['data']['trainmatrix'].get('MAE','0'))\n training_matrix['R2Score'] = float(resultJsonObj['data']['trainmatrix'].get('R2Score','0'))\n training_matrix['MSE'] = float(resultJsonObj['data']['trainmatrix'].get('MSE','0'))\n training_matrix['MAPE'] = float(resultJsonObj['data']['trainmatrix'].get('MAPE','0'))\n training_matrix['RMSE'] = float(resultJsonObj['data']['trainmatrix'].get('RMSE','0'))\n training_matrix['NormalisedRMSEPercentage'] = float(resultJsonObj['data']['trainmatrix'].get('Normalised RMSE(%)','0'))\n result['training_matrix'] = training_matrix\n except Exception as e:\n print(e)\n \n elif result['ModelType'] == 'Text Similarity':\n result['problem_type'] = 'textsimilarity'\n testing_matrix = {}\n testing_matrix['Accuracy'] = float(resultJsonObj['data']['matrix']['Accuracy'])\n testing_matrix['ROC_AUC'] = float(resultJsonObj['data']['matrix']['ROC AUC'])\n result['testing_matrix'] = testing_matrix\n training_matrix = {}\n training_matrix['Accuracy'] = float(resultJsonObj['data']['trainmatrix']['Accuracy'])\n training_matrix['ROC_AUC'] = float(resultJsonObj['data']['trainmatrix']['ROC AUC'])\n result['training_matrix'] = training_matrix\n elif result['ModelType'] == 'RecommenderSystem': #taskid 11190\n result['problem_type'] = 'Recommender'\n testing_matrix = {}\n testing_matrix['RMSE'] = 'NA'\n result['testing_matrix'] = testing_matrix\n training_matrix = {}\n training_matrix['RMSE'] = 'NA'\n result['training_matrix'] = training_matrix\n elif result['ModelType'] == 'SurvivalAnalysis':\n result['problem_type'] = 'SurvivalAnalysis'\n survivalProbabilityjson = resultJsonObj['data']['survivalProbability']\n performanceimages = resultJsonObj['data']['imageLocation']\n start = '['\n end = ']'\n performanceimages = performanceimages[performanceimages.find(start) + len(start):performanceimages.rfind(end)]\n performanceimages = performanceimages.split(',')\n for imagefile in performanceimages:\n imagefile = imagefile.replace(\"'\", \"\")\n string = base64.b64encode(open(imagefile, \"rb\").read())\n image_64 = 'data:image/png;base64,' + urllib.parse.quote(string)\n survical_images.append(image_64)\n result['survivalProbability'] = survivalProbabilityjson\n elif result['ModelType'] == 'StateTransition':\n result['problem_type'] = 'StateTransition'\n stateprobabilityfile = os.path.join(result['DeployLocation'],'stateTransitionProbability.csv')\n clusterfile = os.path.join(result['DeployLocation'],'stateClustering.csv')\n if(os.path.isfile(stateprobabilityfile)):\n df_prob = pd.read_csv(stateprobabilityfile)\t\n df_prob = df_prob[['State','NextState','Probability']]\n result['probability'] = df_prob \n if(os.path.isfile(clusterfile)):\n df_clus = pd.read_csv(clusterfile)\t\n df_clus = df_clus[['clusterid','clusterlist']]\n result['cluster'] = df_clus \n elif result['ModelType'].lower() == 'timeseriesforecasting': #task 11997\n result['problem_type'] = 'TimeSeriesForecasting'\n if result['BestModel'] == 'FBPROPHET':\n imagefile = os.path.join(result['DeployLocation'],'log','img','prophet_fig.png')\n string = base64.b64encode(open(imagefile, \"rb\").read())\n image_64 = 'data:image/png;base64,' + urllib.parse.quote(string)\n survical_images.append(image_64)\n testing_matrix = {}\n testing_matrix['MAE'] = float(resultJsonObj['data']['matrix']['MAE'])\n testing_matrix['MSE'] = float(resultJsonObj['data']['matrix']['MSE'])\n testing_matrix['R2'] = float(resultJsonObj['data']['matrix']['R2'])\n testing_matrix['RMSE'] = float(resultJsonObj['data']['matrix']['RMSE'])\n result['testing_matrix'] = testing_matrix\n forecastjson = resultJsonObj['data']['forecasts']\n result['forecast'] = forecastjson \n if result['BestModel'] == 'VAR':\n '''\n FeaturesMatrix = resultJsonObj['data']['matrix']['FeaturesMatrix']\n mae = ''\n mse = ''\n mape = ''\n rmse = ''\n for x in FeaturesMatrix:\n if mae != '':\n mae += ','\n if mse != '':\n mse += ','\n if R2 != '':\n R2 += ','\n if rmse != '':\n rmse += ','\n featurename = x['Features']\n mae = mae + featurename + '=' + x['MAE']\n mse = mse + featurename + '=' + x['MSE']\n R2 = R2 + featurename + '=' + x['R2']\n rmse = rmse + featurename + '=' + x['RMSE']\n testing_matrix = {}\n testing_matrix['MAE'] = mae\n testing_matrix['MSE'] = mse\n testing_matrix['R2'] = R2\n testing_matrix['RMSE'] = rmse\n result['testing_matrix'] = testing_matrix\n forecastjson = resultJsonObj['data']['forecasts']\n result['forecast'] = forecastjson\n '''\n testing_matrix = {}\n testing_matrix['MAE'] = float(resultJsonObj['data']['matrix']['MAE'])\n testing_matrix['MSE'] = float(resultJsonObj['data']['matrix']['MSE'])\n testing_matrix['R2'] = float(resultJsonObj['data']['matrix']['R2'])\n testing_matrix['RMSE'] = float(resultJsonObj['data']['matrix']['RMSE'])\n result['testing_matrix'] = testing_matrix\n forecastjson = resultJsonObj['data']['forecasts']\n result['forecast'] = forecastjson\n elif result['BestModel'] == 'LSTM' or result['BestModel'] == 'MLP':\n testing_matrix = {}\n testing_matrix['MSE'] = float(resultJsonObj['data']['matrix']['MSE'])\n testing_matrix['RMSE'] = float(resultJsonObj['data']['matrix']['RMSE'])\n result['testing_matrix'] = testing_matrix\n forecastjson = resultJsonObj['data']['forecasts']\n result['forecast'] = forecastjson\t\t\t\n else:\n testing_matrix = {}\n testing_matrix['MAE'] = float(resultJsonObj['data']['matrix']['MAE'])\n testing_matrix['MSE'] = float(resultJsonObj['data']['matrix']['MSE'])\n testing_matrix['R2'] = float(resultJsonObj['data']['matrix']['R2'])\n testing_matrix['RMSE'] = float(resultJsonObj['data']['matrix']['RMSE'])\n result['testing_matrix'] = testing_matrix\n forecastjson = resultJsonObj['data']['forecasts']\n result['forecast'] = forecastjson\n elif result['ModelType'] == 'topicmodelling':\n result['problem_type'] = 'TopicModelling'\n topics = resultJsonObj['topics']\n \n df_topic = []\n dataDict = {}\n for x in topics:\n dataDict = {}\n words = topics[x]\n print(words)\n word = ''\n for key in words:\n print(key)\n if word != '':\n word = word+', '\t\t\t\t\n word = word+key+'('+str(round(words[key],2))+')' \n dataDict[\"ID\"] = x \n dataDict[\"Words\"] = word\n df_topic.append(dataDict)\n result['topics'] = df_topic\n elif result['ModelType'].lower() == 'association rule':\n result['problem_type'] = 'AssociationRules'\n deploy_location = result['DeployLocation']\n freq_item_file = os.path.join(result['DeployLocation'],'frequentItems.csv') \n if(os.path.isfile(freq_item_file)): \n rules_file = os.path.join(result['DeployLocation'],'associationRules.csv')\n if(os.path.isfile(rules_file)):\n df_rules = pd.read_csv(rules_file)\t\n df_rules = df_rules[['antecedents','consequents','support','confidence','lift']]\n #df_rules['antecedents'] = df_rules['antecedents']\n result['rules'] = df_rules\n else:\n result['error'] = 'There are no association found in frequent items above that threshold (minThreshold)'\n else:\n result['error'] = 'There are no frequent items above that threshold (minSupport), try by reducing the minSupport value'\n elif result['ModelType'] == 'clustering':\n result['problem_type'] = 'Clustering'\n testing_matrix = {}\n if 'SilHouette_Avg' in resultJsonObj['data']['matrix']:\n testing_matrix['SilHouette_Avg'] = round(float(resultJsonObj['data']['matrix']['SilHouette_Avg']),2)\n else:\n testing_matrix['SilHouette_Avg'] = 'NA'\n if 'DaviesBouldinScore' in resultJsonObj['data']['matrix']:\n testing_matrix['DaviesBouldinScore'] = round(float(resultJsonObj['data']['matrix']['DaviesBouldinScore']),2)\n else:\n testing_matrix['DaviesBouldinScore'] = 'NA'\n if 'CalinskiHarabazScore'", "instruction": "", "output": "" }, { "input": "in resultJsonObj['data']['matrix']:\n testing_matrix['CalinskiHarabazScore'] = round(float(resultJsonObj['data']['matrix']['CalinskiHarabazScore']),2)\n else:\n testing_matrix['CalinskiHarabazScore'] = 'NA'\n \n centroidpath = os.path.join(result['DeployLocation'],'centers.csv')\n if(os.path.isfile(centroidpath)):\n df_center = pd.read_csv(centroidpath)\t\n df_center = df_center.rename(columns={\"Unnamed: 0\": \"Cluster\"})\n result['centerpoints'] = round(df_center,2)\n result['testing_matrix'] = testing_matrix\n training_matrix = {}\n if 'SilHouette_Avg' in resultJsonObj['data']['matrix']:\n training_matrix['SilHouette_Avg'] = round(float(resultJsonObj['data']['matrix']['SilHouette_Avg']),2)\n training_matrix['DaviesBouldinScore'] = round(float(resultJsonObj['data']['matrix']['DaviesBouldinScore']),2)\n training_matrix['CalinskiHarabazScore'] = round(float(resultJsonObj['data']['matrix']['CalinskiHarabazScore']),2)\n else:\n training_matrix['SilHouette_Avg'] = 'NA'\n training_matrix['DaviesBouldinScore'] = 'NA'\n training_matrix['CalinskiHarabazScore'] = 'NA'\n \n result['training_matrix'] = training_matrix\n #print(result)\n evaluatedModelsList = resultJsonObj['data']['EvaluatedModels']\n #print(evaluatedModelsList)\n for index in range(len(evaluatedModelsList)):\n if evaluatedModelsList[index]['Score'] == 'NA':\n evaluatedModelsList[index]['Score'] = 'NA'\n else:\n evaluatedModelsList[index]['Score'] = round(float(evaluatedModelsList[index]['Score']), 4)\n if result['ModelType'] == 'classification':\n evaluatedModelsList = sorted(evaluatedModelsList, key=lambda k: k['Score'],reverse=True) \n else:\n evaluatedModelsList = sorted(evaluatedModelsList, key=lambda k: k['Score']) \n result['EvaluatedModels'] = evaluatedModelsList\n result['LogFile'] = resultJsonObj['data']['LogFile']\n return result, survical_images '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport pyodbc as pyodbc\nimport pandas as pd\nimport json\ndef simple_select(c, sql_query, bind_params=None, display_sql=False):\n \"\"\"where c is a cursor\"\"\"\n if bind_params is None:\n c.execute(sql_query)\n else:\n if display_sql:\n c.execute(sql_query, bind_params)\n headers = []\n if c.description is not None:\n # We have a SELECT statement\n for x in c.description:\n headers.append(x[0])\n row_count = 0\n row = c.fetchone()\n data=[]\n while row:\n row_count += 1\n xrow={}\n for i in range(len(row)):\n xrow[headers[i]] = row[i]\n data.append(xrow)\n row = c.fetchone()\n #df = pd.DataFrame(data)\n return(data)\n \ndef validatequery(request,query):\n resultdata = []\n try:\n server_url = request.session['server_url']\n username_actian = request.session['username']\n password_actian = request.session['password']\n database_actian = request.session['database']\n conn = get_connection(server_url,username_actian,password_actian,database_actian)\n sql_text = query\n cur = conn.cursor()\n resultdata = simple_select(cur, query)\n cur.close()\n\n if len(resultdata) > 0:\n return \"Query executed successfully\"\n else:\n return \"No rows returned\"\n except Exception as e:\n print(e)\n return str(e)\n\ndef executequery(request,query):\n resultdata = []\n try:\n server_url = request.session['server_url']\n username_actian = request.session['username']\n password_actian = request.session['password']\n database_actian = request.session['database']\n conn = get_connection(server_url,username_actian,password_actian,database_actian)\n sql_text = query\n cur = conn.cursor()\n resultdata = simple_select(cur, query)\n cur.close()\n return(resultdata)\n except Exception as e:\n print(e)\n return(resultdata)\n \ndef list_tables_fields(request,table_list):\n table_field_obj = {}\n table_field_obj['data'] = []\n try:\n server_url = request.session['server_url']\n username_actian = request.session['username']\n password_actian = request.session['password']\n database_actian = request.session['database']\n \n table_list = json.loads(table_list)\n conn = get_connection(server_url,username_actian,password_actian,database_actian)\n for table in table_list:\n tf_obj = {}\n tf_obj['TableName'] = str(table).strip()\n tf_obj['Fields']= []\n\n field_list = []\n sql_text = \"SELECT column_name, false as is_select FROM iicolumns WHERE table_name='\"+table+\"'\"\n cur = conn.cursor()\n field_list = simple_select(cur, sql_text)\n cur.close()\n print(field_list)\n tf_obj['Fields'] = field_list\n table_field_obj['data'].append(tf_obj)\n print(\"----------------------\")\n print(table_field_obj)\n print(json.dumps(table_field_obj))\n print(\"----------------------\")\n return json.dumps(table_field_obj)\n except Exception as e:\n print(\"Something went wrong \"+str(e))\n return table_field_obj\n \ndef list_tables(request):\n server_url = request.session['server_url']\n username_actian = request.session['username']\n password_actian = request.session['password']\n database_actian = request.session['database']\n dt_list = []\n try:\n conn = get_connection(server_url,username_actian,password_actian,database_actian)\n sql_text = \"select table_name from iitables where table_type='T' and table_owner='\"+username_actian+\"'\"\n cur = conn.cursor()\n\n dt_list = simple_select(cur, sql_text)\n cur.close()\n return dt_list\n except:\n print(\"Something went wrong\")\n return dt_list\n \ndef get_connection(server_url,username_actian,password_actian,database_actian):\n 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))\n print(\"connected\")\n return conn\n\n \ndef getDataFromActianAvalanche(request):\n server_url = request.POST.get('server_url')\n username_actian = request.POST.get('username')\n password_actian = request.POST.get('password')\n database_actian = request.POST.get('database')\n table_actian = request.POST.get('table')\n conn = get_connection(server_url,username_actian,password_actian,database_actian)\n c = conn.cursor()\n sql_text = \"select * from \"+str(table_actian) \n data = simple_select(c, sql_text)\n df = pd.DataFrame(data)\n return(df) '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport pandas as pd\nimport numpy as np\nimport json\nimport os\n\ndef downloadtrainingfile(request,Existusecases):\n usename = request.session['UseCaseName'].replace(\" \", \"_\") + '_' + str(request.session['ModelVersion'])\n updatedConfigFile = request.session['config_json']\n f = open(updatedConfigFile, \"r+\", encoding=\"utf-8\")\n configSettingsData = f.read()\n configSettingsJson = json.loads(configSettingsData)\n modelName = request.session['UseCaseName']\n modelVersion = request.session['ModelVersion']\n modelStatus = request.session['ModelStatus']\n model = Existusecases.objects.get(ModelName=request.session['ModelName'],Version=request.session['ModelVersion'])\n output_train_json_filename = str(model.TrainOuputLocation)\n f = open(output_train_json_filename, \"r+\")\n training_output = f.read()\n f.close()\n dict = {'Attribute':[],\n 'Value':[]\n }\n training_output = json.loads(training_output)\n dfdashbord = pd.DataFrame(dict)\n dfdashbord.loc[len(dfdashbord.index)] = ['UseCaseName',modelName]\n dfdashbord.loc[len(dfdashbord.index)] = ['ProblemType',training_output['data']['ModelType']]\n \n dfdashbord.loc[len(dfdashbord.index)] = ['Version',str(modelVersion)]\n dfdashbord.loc[len(dfdashbord.index)] = ['Status',modelStatus]\n if 'vmDetails' in training_output['data']:\n dfdashbord.loc[len(dfdashbord.index)] = ['DeployLocation', training_output['data']['vmDetails']]\n else:\n dfdashbord.loc[len(dfdashbord.index)] = ['DeployLocation',training_output['data']['deployLocation']]\n dfdashbord.loc[len(dfdashbord.index)] = ['BestModel',training_output['data']['BestModel']]\n dfdashbord.loc[len(dfdashbord.index)] = ['BestScore',training_output['data']['BestScore']]\n dfdashbord.loc[len(dfdashbord.index)] = ['ScoringParam',training_output['data']['ScoreType']]\n\n if training_output['data']['ModelType'] != 'LLM Fine-Tuning':\n dfdashbord.loc[len(dfdashbord.index)] = ['Test%',configSettingsJson['advance']['testPercentage']]\n dfdashbord.loc[len(dfdashbord.index)] = ['FeaturesUsed',training_output['data']['featuresused']]\n from io import BytesIO as IO \n excel_file = IO() \n edaFileName = usename + '_training.xlsx'\n excel_writer = pd.ExcelWriter(excel_file, engine=\"xlsxwriter\") \n dfdashbord.to_excel(excel_writer, sheet_name='Dashboard',index=False)\n if training_output['data']['ModelType'].lower() != 'multimodellearning' and training_output['data']['ModelType'].lower() != 'multilabelprediction':\n EvaluatedModels = training_output['data']['EvaluatedModels']\n EvaluatedModels = pd.DataFrame(EvaluatedModels)\n EvaluatedModels.to_excel(excel_writer, sheet_name='EvaluatedModels',startrow=0 , startcol=0)\n if training_output['data']['ModelType'].lower() == 'classification':\n #print(training_output['data']['matrix'])\n row1 = 10\n row2 = 10\n if 'ConfusionMatrix' in training_output['data']['matrix']:\n confusionMatrix = training_output['data']['matrix']['ConfusionMatrix']\n confusionMatrix = pd.DataFrame(confusionMatrix)\n confusionMatrix.to_excel(excel_writer, sheet_name='Testing Matrix',startrow=0 , startcol=0)\n row1 =confusionMatrix.shape[0]+5\n if 'ConfusionMatrix' in training_output['data']['trainmatrix']:\n confusionMatrix = training_output['data']['trainmatrix']['ConfusionMatrix']\n confusionMatrix = pd.DataFrame(confusionMatrix)\n confusionMatrix.to_excel(excel_writer, sheet_name='Training Matrix',startrow=0 , startcol=0)\n if 'ClassificationReport' in training_output['data']['matrix']:\n confusionMatrix = training_output['data']['matrix']['ClassificationReport']\n confusionMatrix = pd.DataFrame(confusionMatrix)\n confusionMatrix.to_excel(excel_writer, sheet_name='Testing Matrix',startrow=row1 , startcol=0)\n if 'ClassificationReport' in training_output['data']['trainmatrix']:\n confusionMatrix = training_output['data']['trainmatrix']['ClassificationReport']\n confusionMatrix = pd.DataFrame(confusionMatrix)\n confusionMatrix.to_excel(excel_writer, sheet_name='Training Matrix',startrow=row2 , startcol=0)\n if training_output['data']['ModelType'].lower() == 'regression':\n dict = {'Attribute':[],'Value':[]}\n testingDF = pd.DataFrame(dict) \n try:\n testingDF.loc[len(testingDF.index)] = ['MAE',training_output['data']['matrix']['MAE']]\n testingDF.loc[len(testingDF.index)] = ['R2Score',training_output['data']['matrix']['R2Score']]\n testingDF.loc[len(testingDF.index)] = ['MSE',training_output['data']['matrix']['MSE']]\n testingDF.loc[len(testingDF.index)] = ['MAPE',training_output['data']['matrix']['MAPE']]\n testingDF.loc[len(testingDF.index)] = ['RMSE',training_output['data']['matrix']['RMSE']]\n except:\n pass\n testingDF.to_excel(excel_writer, sheet_name='Testing Matrix',startrow=0 , startcol=0) \n trainingDF = pd.DataFrame(dict) \n try:\n trainingDF.loc[len(trainingDF.index)] = ['MAE',training_output['data']['trainmatrix']['MAE']]\n trainingDF.loc[len(trainingDF.index)] = ['R2Score',training_output['data']['trainmatrix']['R2Score']]\n trainingDF.loc[len(trainingDF.index)] = ['MSE',training_output['data']['trainmatrix']['MSE']]\n trainingDF.loc[len(trainingDF.index)] = ['MAPE',training_output['data']['trainmatrix']['MAPE']]\n trainingDF.loc[len(trainingDF.index)] = ['RMSE',training_output['data']['trainmatrix']['RMSE']]\n except:\n pass\n trainingDF.to_excel(excel_writer, sheet_name='Training Matrix',startrow=0 , startcol=0) \n if training_output['data']['ModelType'].lower() == 'clustering':\n dict = {'Attribute':[],'Value':[]}\n trainingDF = pd.DataFrame(dict)\n try:\n trainingDF.loc[len(trainingDF.index)] = ['SilHouette_", "instruction": "", "output": "" }, { "input": "Avg',round(training_output['data']['trainmatrix']['SilHouette_Avg'],2)]\n trainingDF.loc[len(trainingDF.index)] = ['DaviesBouldinScore',round(training_output['data']['trainmatrix']['DaviesBouldinScore'],2)]\n trainingDF.loc[len(trainingDF.index)] = ['CalinskiHarabazScore',round(training_output['data']['trainmatrix']['CalinskiHarabazScore'],2)]\n except:\n pass\n trainingDF.to_excel(excel_writer, sheet_name='Training Matrix',startrow=0 , startcol=0)\n centroidpath = os.path.join(training_output['data']['deployLocation'],'centers.csv')\n if(os.path.isfile(centroidpath)):\n df_center = pd.read_csv(centroidpath)\t\n df_center = df_center.rename(columns={\"Unnamed: 0\": \"Cluster\"})\n df_center.to_excel(excel_writer, sheet_name='Centroid',startrow=0 , startcol=0)\n if training_output['data']['ModelType'].lower() == 'timeseriesforecasting': #task 11997\n if training_output['data']['BestModel'].lower() == 'var':\n dict = {'Features':[],'Attribute':[],'Value':[]}\n trainingDF = pd.DataFrame(dict) \n FeaturesMatrix = training_output['data']['matrix']\n for x in FeaturesMatrix:\n try:\n trainingDF.loc[len(trainingDF.index)] = [x['Features'],'MAE',x['MAE']]\n trainingDF.loc[len(trainingDF.index)] = [x['Features'],'MSE',x['MSE']]\n trainingDF.loc[len(trainingDF.index)] = [x['Features'],'MAPE',x['MAPE']]\n trainingDF.loc[len(trainingDF.index)] = [x['Features'],'RMSE',x['RMSE']]\n except:\n pass\n trainingDF.to_excel(excel_writer, sheet_name='Testing Matrix',startrow=0 , startcol=0) \n else:\n dict = {'Attribute':[],'Value':[]}\n trainingDF = pd.DataFrame(dict)\n try:\n trainingDF.loc[len(trainingDF.index)] = ['MAE',training_output['data']['matrix']['MAE']]\n trainingDF.loc[len(trainingDF.index)] = ['MSE',training_output['data']['matrix']['MSE']]\n trainingDF.loc[len(trainingDF.index)] = ['MAPE',training_output['data']['matrix']['MAPE']]\n trainingDF.loc[len(trainingDF.index)] = ['RMSE',training_output['data']['matrix']['RMSE']]\n except:\n pass\n trainingDF.to_excel(excel_writer, sheet_name='Testing Matrix',startrow=0 , startcol=0) \n workbook = excel_writer.book\n \n #excel_writer.save()\n excel_writer.close()\n excel_file.seek(0)\n return edaFileName,excel_file\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os.path\nfrom pathlib import Path\nimport time\nimport subprocess\nimport sys\nimport shutil\nfrom appbe.aion_config import kafka_setting\nfrom appbe.aion_config import running_setting\nfrom appbe.publish import chech_publish_info\nfrom llm.llm_tuning import update_sqllite_data\nfrom appbe.data_io import sqlite_db\nfrom appbe.dataPath import DATA_DIR\nfrom appbe import installPackage\nfrom appbe import compute\nimport json\nimport os\nimport signal\nfrom os.path import expanduser\nimport platform\nimport pandas as pd\nLOG_FILE_PATH = os.path.join(DATA_DIR,'logs')\nGITHUB_FILE_PATH = os.path.join(DATA_DIR,'github')\t\nPUBLISH_PATH = os.path.join(DATA_DIR,'target')\t\nDEPLOY_DATABASE_PATH = os.path.join(DATA_DIR,'sqlite') \nos.makedirs(LOG_FILE_PATH, exist_ok=True)\n'''\ndef check_publish_info(usecase,version):\n sqlite_dbObj = sqlite_db(DEPLOY_DATABASE_PATH,'deploy.db')\n if sqlite_dbObj.table_exists('publish'): \n \n publishState= 'Published'\n'''\ndef get_instance(modelID):\n from appbe.sqliteUtility import sqlite_db\n from appbe.dataPath import DATA_DIR\n file_path = os.path.join(DATA_DIR,'sqlite')\n sqlite_obj = sqlite_db(file_path,'config.db')\n if sqlite_obj.table_exists(\"LLMTuning\"):\n data = sqlite_obj.get_data('LLMTuning','usecaseid',modelID)\n \n if len(data) > 0:\n return (data[3],data[2],data[5],data[6],data[4])\n else:\n return '','','','',''\n else:\n return '','','','',''\ndef startServices(request,usecasedetails,Existusecases):\n try:\n models = Existusecases.objects.filter(publishStatus='Published')\n print(models)\n if len(models) > 0:\n for model in models:\n try:\n portNo = model.portNo\n ppid = model.publishPID\n if ppid == 0:\n continue \n \n try:\n os.kill(int(model.publishPID), signal.SIGTERM)\n except Exception as e:\n print(e)\n scriptPath = os.path.join(PUBLISH_PATH,model.ModelName.usecaseid,'aion_publish_service.py')\n \n if os.path.exists(scriptPath):\n outputStr = subprocess.Popen([sys.executable, scriptPath,'-ip','0.0.0.0','-p',str(portNo)])\n model.publishStatus = 'Published'\n model.publishPID = outputStr.pid\n model.portNo = portNo\n model.save()\n else:\n print(\"Pass\")\n pass\n except Exception as e: \n print(e)\n except Exception as e:\n print(e)\n \ndef publishmodel(request,usecaseid,version,Existusecases,usecasedetails):\n portNo=0 \n usecased = usecasedetails.objects.get(usecaseid=usecaseid)\n models = Existusecases.objects.filter(ModelName=usecased,publishStatus='Published')\n if len(models) > 0:\n for model in models:\n try:\n portNo = model.portNo\n try:\n os.kill(int(model.publishPID), signal.SIGTERM)\n except Exception as e:\n print(e)\n mod = Existusecases.objects.get(id=model.id)\n mod.publishStatus = ''\n mod.publishPID = 0\n mod.portNo = 0\n mod.save()\n except Exception as e:\n print(e)\n pass\t\n missingNumbers = [] \n if portNo == 0: \n models = Existusecases.objects.filter(publishStatus='Published')\n usedPortNo=[]\n for model in models:\n usedPortNo.append(model.portNo)\n startPortNo = 8091\n endPortNo = 8091+5\n missingNumbers = [ i for i in range(startPortNo,endPortNo) if i not in usedPortNo]\n if len(missingNumbers) > 0:\n portNo = missingNumbers[0]\n if portNo != 0:\n scriptPath = os.path.join(PUBLISH_PATH,usecaseid,'aion_publish_service.py')\n \n model = Existusecases.objects.get(ModelName=usecased,Version=version)\n isExist = os.path.exists(scriptPath)\n if isExist:\n configfile = os.path.join(PUBLISH_PATH,usecaseid,'config.json')\n configdata = {'version': str(version)}\t\t\t\n with open(configfile, \"w\") as outfile:\n json.dump(configdata, outfile)\n outfile.close()\t\t\t\t\n outputStr = subprocess.Popen([sys.executable, scriptPath,'-ip','0.0.0.0','-p',str(portNo)])\n model.publishStatus = 'Published'\n model.publishPID = outputStr.pid\n model.portNo = portNo\n model.save()\n Status = 'SUCCESS'\n hosturl =request.get_host()\n hosturl = hosturl.split(':')\n url = 'http://'+hosturl[0]+':'+str(portNo)+'/AION/'+str(usecaseid)+'/predict'\n Msg = 'Model Published Successfully'\n else:\n Status = 'Error'\n Msg = 'Model Published Error'\n url = ''\n else:\n Status = 'Error'\n Msg = 'All ports are utilized'\n url=''\n return Status,Msg,url\ndef get_published_models(instanceid): \n from appbe.sqliteUtility import sqlite_db\n \n file_path = os.path.join(DATA_DIR,'sqlite')\n sqlite_obj = sqlite_db(file_path,'config.db')\n if sqlite_obj.table_exists(\"LLMTuning\"):\n condition = f'\"instance\"==\"{instanceid}\" AND \"status\"==\"Published\"'\n datas = sqlite_obj.read_data('LLMTuning',condition)\n \n if len(datas)>0:\n return True,datas[0][0] \n return False,''\n \ndef maac_command(request,Existusecases,usecasedetails):\n command = request.POST.get('maacsubmit')\n kafkaSetting = kafka_setting()\n ruuningSetting = running_setting()\n computeinfrastructure = compute.readComputeConfig()\n modelID = request.POST.get('modelID')\n Version = request.POST.get('Version')\n p = Existusecases.objects.get(id=modelID,Version=Version)\n usecasename = p.ModelName.usecaseid #bugid 13339\n usecaseid = p.ModelName.id\n\n # runningStatus,pid,ip,port = installPackage.checkModelServiceRunning(usecasename)\n # installationStatus,modelName,modelVersion=installPackage.checkInstalledPackge(usecasename)\n usecasedetail = usecasedetails.objects.get(id=p.ModelName.id)\n usecase = usecasedetails.objects.all()\n problemType = p.ProblemType\n score = 0\n scoreType = ''\n deployedModel = '' \n deployedModelVersion = p.Version\n models = Existusecases.objects.filter(ModelName=usecasedetail,Status='SUCCESS')\n computeinfrastructure = compute.readComputeConfig()\n for model in models:\n model.scoringCreteria = 'NA'\n model.score = 'NA'\n model.deploymodel = 'NA'\n if os.path.isdir(str(model.DeployPath)):\n modelPath = os.path.join(str(model.DeployPath),'etc','output.json')\n try:\t\n with open(modelPath) as file:\n outputconfig = json.load(file)\n file.close()\n if outputconfig['status'] == 'SUCCESS':\n if deployedModelVersion == model.Version:\n problemType = outputconfig['data']['ModelType']\n scoreType = outputconfig['data']['ScoreType']\n score = outputconfig['data']['BestScore']\n deployedModel = outputconfig['data']['BestModel']\n model.scoringCreteria = outputconfig['data']['ScoreType']\n model.score = outputconfig['data']['BestScore']\n model.deploymodel = outputconfig['data']['BestModel']\n model.maacsupport = 'True'\n model.flserversupport = 'False'\n supportedmodels = [\"Logistic Regression\",\"Neural Network\",\"Linear Regression\"]\n if model.deploymodel in supportedmodels:\n model.flserversupport = 'True'\n else:\n model.flserversupport = 'False'\n supportedmodels = [\"Extreme Gradient Boosting (XGBoost)\"]\n if model.deploymodel in supportedmodels:\n model.encryptionsupport = 'True'\n else:\n model.encryptionsupport = 'False' \n except Exception as e: \n print(e)\n pass\n MLaaC_output = ''\n \t\n if command == 'generatemaac':\n deployPath = str(p.DeployPath)\n codeconfig = os.path.join(deployPath,'etc','code_config.json')\n if os.path.isfile(codeconfig):\n with open(codeconfig,'r') as f: \n cconfig = json.load(f) \n f.close() \n dbserver = request.POST.get('productiondb')\n db_config = {}\n if dbserver.lower() == 'influxdb':\n cconfig['prod_db_type'] = 'influx'\n db_config['host'] = request.POST.get('influxdbhost')\n db_config['port'] = request.POST.get('influxdbportno')\n db_config['user'] = request.POST.get('influxdbuser')\n db_config['password'] = request.POST.get('influxpassword')\n db_config['database'] = 'production' \n db_config['measurement'] = usecasename\n tags = {}\n db_config['tags']=tags\n cconfig['db_config'] = db_config\n else:\n cconfig['prod_db_type'] = 'sqlite' \n cconfig['db_config'] = db_config\n dbserver = request.POST.get('mlflowserver')\n mlflow_config = {}\n if dbserver.lower() == 'local':\n cconfig['mlflow_config'] = mlflow_config\n else:\n mlflow_config['tracking_uri_type'] = request.POST.get('mlflowserverurl')\n mlflow_config['tracking_uri'] = request.POST.get('mlflowserverurl')\n mlflow_config['registry_uri'] = request.POST.get('mlflowserverurl') \n mlflow_config['artifacts_uri'] = request.POST.get('mlflowserverurl') \n cconfig['mlflow_config'] = mlflow_config\n with open(codeconfig,'w') as f: \n json.dump(cconfig, f) \n f.close()\n from bin.aion_mlac import generate_mlac_code\n outputStr = generate_mlac_code(codeconfig)\n output = json.loads(outputStr)\n from appbe.telemetry import UpdateTelemetry\n UpdateTelemetry(request.session['usecaseid']+'-'+str(request.session['ModelVersion']),'MLaC','Yes')\n if output['Status'] == 'SUCCESS':\n Status = 'SUCCESS'\n MLaaC_output = output['MLaC_Location'].replace('\\\\\\\\', '\\\\\\\\\\\\\\\\')\n Msg = 'MLaC code successfully generated'\n else:\n Status = '", "instruction": "", "output": "" }, { "input": "Failure'\n Msg = output['msg']\n else:\n Status = 'Failure'\n Msg = 'Code Config Not Present'\n if command == 'buildContainer':\n deployPath = str(p.DeployPath)\n maac_path = os.path.join(deployPath,'publish','MLaC')\n if os.path.isdir(maac_path):\n config={'usecase':str(usecasename),'version':str(p.Version),'mlacPath':maac_path}\n config = json.dumps(config) \n scriptPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','aion.py'))\n \n if platform.system() == 'Windows':\n outputStr = subprocess.Popen([sys.executable, scriptPath,'-m','buildMLaCContainerLocal' ,'-j',config],creationflags = subprocess.CREATE_NEW_CONSOLE)\n else:\n outputStr = subprocess.Popen([sys.executable, scriptPath,'-m','buildMLaCContainerLocal' ,'-j',config]) \n #cmd = scriptPath+\" \"+str(usecasename)+\" \"+str(p.Version)+\" \"+str(maac_path)\n #subprocess.Popen(cmd,shell=True)\n Status = 'SUCCESS'\n Msg = 'Build Container Started'\n else:\n Status = 'Failure'\n Msg = 'Run Code Generator'\n if command == 'runpipeline':\n deployPath = str(p.DeployPath)\n dockerlist = os.path.join(deployPath,'publish','MLaC','dockerlist.json')\t\n if os.path.isfile(dockerlist):\n persistancevolume = request.POST.get('persistancevolume')\n datasetpath = request.POST.get('dataset')\n filetimestamp = str(int(time.time()))\n logfilepath = os.path.join(LOG_FILE_PATH,'AIONPipeline_'+str(filetimestamp)+'.log')\n config={'usecase':str(usecasename),'version':str(p.Version),'persistancevolume':persistancevolume,'datasetpath':datasetpath,'dockerlist':str(dockerlist),'logfilepath':logfilepath}\n config = json.dumps(config) \n scriptPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','aion.py'))\t\t\t\n if platform.system() == 'Windows':\n outputStr = subprocess.Popen([sys.executable, scriptPath,'-m','runpipelinelocal','-j',config],creationflags = subprocess.CREATE_NEW_CONSOLE)\t\t\t\n else:\n outputStr = subprocess.Popen([sys.executable, scriptPath, str(usecasename),str(p.Version),persistancevolume,datasetpath,str(dockerlist),logfilepath])\t\t\t \n Status = 'SUCCESS'\n Msg = 'Pipeline Started'\n MLaaC_output = 'Check log file for pipeline execution status: ' + str(logfilepath)\n else:\n Status = 'Failure'\n Msg = 'Not found container information'\n if command == 'generateyaml':\n deployPath = str(p.DeployPath)\n maac_path = os.path.join(deployPath,'publish','MLaC')\t\t\n if os.path.isdir(maac_path):\n persistancevolume = request.POST.get('persistancevolume')\n datasetpath = request.POST.get('dataset')\t\t\t\n supported_urls_starts_with = ('gs://','https://','http://') \n if datasetpath.startswith(supported_urls_starts_with):\t\t\n datasetpath = request.POST.get('dataset') \t\t\t\n else:\t\t\t\n datasetpath = '/aion/'+request.POST.get('dataset')\n serviceport = request.POST.get('serviceport') \t\n scriptPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..','bin','run_generateyaml.py'))\n outputStr = subprocess.check_output([sys.executable, scriptPath, str(usecasename),str(p.Version),persistancevolume,datasetpath,maac_path,serviceport])\n outputStr = outputStr.decode('utf-8')\n outputStr=outputStr.strip()\n print(outputStr)\n output = json.loads(outputStr)\n if output['Status'] == 'SUCCESS':\n Status = 'SUCCESS'\n MLaaC_output = output['location']\n Msg = 'MLaaC dockerfile successfully generated'\n else:\n Status = 'Failure'\n Msg = output['msg']\n else:\n Status = 'Failure'\n Msg = 'Execute generate code first'\n if command == 'githubupload':\n if shutil.which('git') is None:\n Status = 'Failure'\n Msg = 'Git is not installed, Please install Git first.' \n else:\n try:\n deployPath = str(p.DeployPath)\n maac_path = os.path.join(deployPath,'publish','MLaC')\t\t\t\n if os.path.isdir(maac_path): \n githuburl = request.POST.get('githuburl')\n githubusername = request.POST.get('githubusername')\n githubtoken = request.POST.get('githubtoken')\n githubemail = request.POST.get('githubemail')\n githubconfig = {\"url_type\":\"https\",\"url\":githuburl,\"username\":githubusername,\"email\":githubemail,\"token\":githubtoken,\"location\":maac_path,\"modelName\":usecasename,\"gitFolderLocation\":GITHUB_FILE_PATH}\n from mlops import git_upload\n outputStr = git_upload.upload(githubconfig)\n print(outputStr)\n output = json.loads(outputStr)\n if output['Status'] == 'SUCCESS':\n Status = 'SUCCESS'\n MLaaC_output = githuburl\n Msg = 'Code Uploaded to GitHub Successfully'\n else:\n Status = 'Failure'\n Msg = output['msg']\n else:\n Status = 'Failure'\n Msg = 'GitHub Upload failed'\n except Exception as e:\n print(e)\n Status = 'Failure'\n Msg = 'GitHub Upload failed' \n if command == 'unpublishmodel':\n try:\n models = Existusecases.objects.filter(ModelName=usecasedetail,publishStatus='Published')\n if len(models) > 0:\n for model in models:\n try:\n\n if problemType.lower() == \"llm fine-tuning\":\n cloudconfig = os.path.normpath(\n os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'config', 'compute_conf.json'))\n modelid = usecasename + '_' + str(Version)\n usecasename = usecasename.replace(\" \", \"_\")\n \n hypervisor,instanceid,region,image,status = get_instance(usecasename + '_' + str(Version))\n from llm.llm_inference import kill_inference_server\n kill_inference_server(cloudconfig,instanceid,hypervisor,region,image)\n \n update_sqllite_data(modelid,'status','Success')\n else:\n try:\n os.kill(int(model.publishPID), signal.SIGTERM)\n mod.publishPID = 0\n except Exception as e:\n print(e)\n mod = Existusecases.objects.get(id=model.id)\n mod.publishStatus = ''\n \n mod.portNo = 0\n mod.save()\n Status = 'SUCCESS'\n Msg = 'Model Unpublished Successfully'\n except Exception as e:\n print(e)\n Status = 'Error'\n Msg = 'Model Unpublished Error'\n except Exception as e:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n print(e)\n pass \n \n if command == 'publishmodel':\n \n try:\n portNo=0 \n models = Existusecases.objects.filter(ModelName=usecasedetail,publishStatus='Published')\n if len(models) > 0:\n for model in models:\n try:\n portNo = model.portNo\n try:\n os.kill(int(model.publishPID), signal.SIGTERM)\n except Exception as e:\n print(e)\n mod = Existusecases.objects.get(id=model.id)\n mod.publishStatus = ''\n mod.publishPID = 0\n mod.portNo = 0\n mod.save()\n except Exception as e:\n print(e)\n pass\n missingNumbers = []\n\n if problemType.lower() == \"llm fine-tuning\":\n model = Existusecases.objects.get(ModelName=usecasedetail,Version=Version)\n try:\n usecasename = usecasename.replace(\" \", \"_\")\n hypervisor,instanceid,region,image,status = get_instance(usecasename + '_' + str(Version))\n if status.lower() in ['published','success'] :\n if status.lower() == 'published':\n from llm.llm_inference import kill_inference_server\n kill_inference_server('',instanceid, hypervisor, region, image)\n update_sqllite_data(usecasename + '_' + str(Version), 'status', 'Success')\n already_published,published_usecase = get_published_models(instanceid)\n if already_published:\n Status = 'Error'\n Msg = f'{published_usecase} is published at the same id, Please Unpublish mentioned model to proceed.'\n else:\n if not region:\n region = ''\n cloudconfig = os.path.normpath(\n os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'config', 'compute_conf.json'))\n usecase = usecasename + '_' + str(Version)\n #modelid = usecasename + '_' + str(Version)\n scriptPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'aion.py'))\n cmd = [sys.executable, scriptPath, '-m', 'llmpublish', '-cc', cloudconfig, '-i',instanceid,'-hv',hypervisor,'-md',deployedModel,'-uc',usecase,'-r',region,'-im',image ]\n outputStr = subprocess.Popen(cmd)\n model.publishStatus = 'Published'\n model.publishPID = 0\n model.portNo = 8000\n model.save()\n Status = 'SUCCESS'\n from llm.llm_inference import get_ip\n instanceip = get_ip(cloudconfig,instanceid,hypervisor,region,image)\n print(instanceip)\n url = 'http://' + instanceip + ':' + str(model.portNo) + '/generate'\n Msg = 'Model Published Successfully, Server will take few minutes to be ready for Inferencing. URL: ' + url\n update_sqllite_data(usecase,'status','Published')\n else:\n Status = 'Error'\n Msg = 'Only Trained models are availble for Publish.'\n \n except Exception as e:\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n Status = 'Error'\n Msg = 'Model Published Error'\n \n else:\n if portNo == 0: \n models = Existusecases.objects.filter(publishStatus='Published')\n usedPortNo=[]\n for model in models:\n usedPortNo.append(model.portNo)\n startPortNo = 8091\n endPortNo = 8091+5\n missingNumbers = [ i for i in range(startPortNo,endPortNo) if i not in usedPortNo]\n if len(missingNumbers) > 0:\n portNo = missingNumbers[0]\n if portNo != 0:\n model = Existusecases.objects.get(ModelName=usecasedetail,Version=Version) \n scriptPath = os.path.join(PUBLISH_PATH,usecasename,'aion_publish_service.py')\n isExist = os.path.exists(scriptPath)\n if isExist:\n configfile = os.path.join(PUBLISH_PATH,usecasename,'config.json')\n configdata = {'version': str(Version)}\n with open(configfile, \"w\") as outfile:\n json.dump(configdata, outfile)\n outfile.close()\n outputStr = subprocess.Popen([sys.executable, scriptPath,'-ip','0.0.0.0','-p',str(portNo)])\n model.publishStatus = 'Published'\n model.publishPID = outputStr.pid\n model.portNo = portNo\n model.save()\n Status = 'SUCCESS'\n hosturl =request.get_host()\n hosturl = hosturl.split(':')\n url = 'http://'+hosturl[0]+':'+str(portNo)+'/AION/'+str(usecasename)+'/predict'\n Msg = 'Model Published Successfully URL: '+url\n else:\n Status = 'Error'\n Msg = 'Model Published Error'\n else:\n Status = 'Error'\n Msg = 'All ports are utilized'\n except Exception as e:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n print(e)\n pass\n if command == 'generatekubeflowyaml':\n try:\n if problemType.lower() == 'timeseriesforecasting': #task 11997\n from appbe.aionpipelinets import aionpipelinets\t\n else:\n from appbe.aionpipeline import aionpipeline \n deployPath = str(p.DeployPath)\t\n codeconfig = os.path.join(deployPath,'etc','code_config.json')\n featuresmapping = {'modelBased':'mlbased','statisticalBased':'statisticalBased'}\n if os.path.isfile(codeconfig): \t\n with open(codeconfig,'r') as f: \n codeconfig = json.load(f) \n f.close()\n modelsarray=[]\n for featureselection in codeconfig['feature_selector']:\t\t\t\t\t\n for algo in codeconfig['algorithms'].keys():\n if problemType.lower() == 'timeseriesforecasting': #task 11997\n modelname = 'modeltraining_'+algo.lower()\n else:\n modelname =", "instruction": "", "output": "" }, { "input": "'modeltraining_'+algo.lower()+'_'+featuresmapping[featureselection]\n modelx = {'modelname':modelname}\t\t\n modelsarray.append(modelx)\n modelsjson = {'models':modelsarray}\n kubeflowhost= request.POST.get('kubeflowhost') \t\t\t\n containerregistry= request.POST.get('containerregistry')\t\t\t\n containerlabel= request.POST.get('containerlabel')\t\t\t\n containersecret= request.POST.get('containersecret')\n if problemType.lower() == 'timeseriesforecasting': #task 11997\n ap = aionpipelinets(modelsjson,containerregistry,containerlabel,containersecret)\n else: \n ap = aionpipeline(modelsjson,containerregistry,containerlabel,containersecret)\n ap.aion_mlops()\n ap.compilepl() \n ap.executepl(kubeflowhost)\t\t\t\n Status = 'SUCCESS'\n MLaaC_output = ''\n Msg = 'MLOps pipeline executed successfully' \t\t\t\n except Exception as e:\n print(e)\n Status = 'Failure'\n Msg = 'Error in pipeline execution'\t\t\n from appbe.pages import get_usecase_page \n if command in ['publishmodel','unpublishmodel']: \n status,context,action = get_usecase_page(request,usecasedetails,Existusecases,usecaseid)\n context['Status'] = Status\n context['MLaaC_output'] = MLaaC_output \n context['Msg'] = Msg \n return(context,'usecasedetails.html')\n else:\n status,context,action = get_usecase_page(request,usecasedetails,Existusecases) \n context['Status'] = Status\n context['MLaaC_output'] = MLaaC_output \n context['Msg'] = Msg \n return(context,'usecases.html') \n\ndef getusercasestatus(request):\n if 'UseCaseName' in request.session:\n selected_use_case = request.session['UseCaseName']\n else:\n selected_use_case = 'Not Defined'\n\n if 'ModelVersion' in request.session:\n ModelVersion = request.session['ModelVersion']\n else:\n ModelVersion = 0\n\n if 'ModelStatus' in request.session:\n ModelStatus = request.session['ModelStatus']\n else:\n ModelStatus = 'Not Trained'\n return selected_use_case,ModelVersion,ModelStatus # -*- coding: utf-8 -*-\nimport os\nimport glob, os\nimport pandas as pd\nfrom openai.embeddings_utils import cosine_similarity\nimport numpy as np\nfrom openai.embeddings_utils import get_embedding\nimport tiktoken\nimport openai\nimport importlib.util \nfrom sklearn.preprocessing import StandardScaler\nimport numpy as np\nfrom sklearn.cluster import DBSCAN\nfrom sklearn import metrics\nimport time\nfrom tqdm import tqdm\nimport concurrent.futures\nfrom openai.error import RateLimitError, Timeout\ntry:\n import chromadb\n from chromadb.api.types import Documents, Embeddings\nexcept:\n #Looks no chromadb installed,just proceed to use csv embedd\n pass\n\nfrom openai.embeddings_utils import get_embedding\nimport json\nfrom openai.embeddings_utils import cosine_similarity\nfrom langchain.schema import Document\nfrom langchain.vectorstores import Chroma\nimport warnings\nimport logging\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\n\"\"\"Code clone detection parent class, based on user input data,the class will detect similar code snippets in the python file \"\"\"\nclass CodeCloneDetection:\n #Constructor for base inputs\n 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):\n self.rootdir=rootdir\n self.embedd_storage_path=embedd_storage_path\n self.openai_baseurl=openai_baseurl\n self.openai_key=openai_key\n self.openai_api_type=openai_api_type\n self.openai_api_version=openai_api_version\n self.ccdreportpath = os.path.join(self.embedd_storage_path, \"codeCloneReport\")\n self.generativeai_chat_model=generativeai_chat_model\n self.generativeai_embedding_engine = generativeai_embedding_engine\n self.generativeai_embedding_model = generativeai_embedding_model\n self.generativeai_deploymentId = generativeai_deploymentId\n try:\n os.makedirs(self.ccdreportpath, exist_ok = True)\n except OSError as error:\n print(\"Directory 'codeclonedetection' can not be created\",self.ccdreportpath)\n \n try:\n self.logpath = os.path.join(self.ccdreportpath,'codeclonelog.log')\n logging.basicConfig(level=logging.INFO,filename=self.logpath,filemode='w',format='%(message)s')\n self.log = logging.getLogger()\n except Exception as e:\n print(\"code clone log object creation error.\",e)\n \n def get_function_name(self,code):\n \"\"\"\n Extract function name from a line beginning with \"def \"\n \"\"\"\n assert code.startswith(\"def \")\n return code[len(\"def \"): code.index(\"(\")]\n \n def get_until_no_space(self,all_lines, i) -> str:\n \"\"\"\n Get all lines until a line outside the function definition is found.\n \"\"\"\n ret = [all_lines[i]]\n for j in range(i + 1, i + 10000):\n if j < len(all_lines):\n if len(all_lines[j]) == 0 or all_lines[j][0] in [\" \", \"\\\\t\", \")\"]:\n ret.append(all_lines[j])\n else:\n break\n return \"\\\\n\".join(ret)\n \n def chunk_functions(self,function_code, chunk_size):\n \"\"\" To chunk input for gpt models because max token per model is 4090 \"\"\"\n try:\n # chunk_size = 1900\n chunks = [function_code[i:i + chunk_size] for i in range(0, len(function_code), chunk_size)]\n except Exception as e:\n self.log.info('Error in chunking input prompt data.')\n return chunks\n \n def get_functions(self,filepath):\n \"\"\"\n Get all functions in a Python file.\n \"\"\"\n try:\n whole_code = open(filepath).read().replace(\"\\\\r\", \"\\\\n\")\n all_lines = whole_code.split(\"\\\\n\")\n for i, l in enumerate(all_lines):\n if l.startswith(\"def \"):\n code = self.get_until_no_space(all_lines, i)\n function_name = self.get_function_name(code)\n yield {\"code\": code, \"function_name\": function_name, \"filepath\": filepath}\n except Exception as e:\n self.log.info(\"Error in getting function from file. Error message: \\\\n\"+str(e))\n \n def get_clone_function_details(self):\n \"\"\" To get available functions from python files \"\"\"\n try:\n code_root=self.rootdir\n from glob import glob\n code_files = [y for x in os.walk(code_root) for y in glob(os.path.join(x[0], '*.py'))]\n if code_files:\n all_funcs = []\n total_locs = 0\n for code_file in code_files:\n with open(code_file) as f:\n total_locs += len(f.readlines())\n \n funcs = list(self.get_functions(code_file))\n for func in funcs:\n all_funcs.append(func)\n return all_funcs,code_root,code_files,total_locs\n else:\n self.log.info(\"no python files available in the dir:\"+str(code_root))\n return {\"pythondiles_error\":\"No python files are found.\"}\n except Exception as e:\n print(\"Error in reading the functions from the given directory. Error message: \\\\n\",e)\n self.log.info(\"Error in reading the functions from the given directory. Error message: \\\\n\"+str(e))\n \n\n \n def getOpenAICredentials(self):\n \"\"\" To set openai credential using user input \"\"\"\n #Currently only support openai\n try:\n package_name = 'openai'\n lib_name = importlib.util.find_spec(package_name)\n if lib_name is None:\n return \"openai_pkg_check_failed\" \n else:\n \n embedding_model_lib ='openai'\n # \n if isinstance(self.openai_baseurl,str) and isinstance(self.openai_key,str) and isinstance(self.openai_api_type,str):\n os.environ['OPENAI_API_TYPE'] = self.openai_api_type\n os.environ['OPENAI_API_BASE'] = self.openai_baseurl\n # os.environ['OPENAI_API_VERSION'] = '2023-05-15' \n # os.environ['OPENAI_API_VERSION'] = \"2022-12-01\"\n os.environ['OPENAI_API_VERSION'] = self.openai_api_version\n os.environ['OPENAI_API_KEY'] = self.openai_key\n \n if (embedding_model_lib.lower()=='openai'):\n try:\n openai.api_type=os.getenv('OPENAI_API_TYPE')\n openai.api_base = os.getenv('OPENAI_API_BASE') \n openai.api_key = os.getenv('OPENAI_API_KEY')\n openai.api_version = os.getenv('OPENAI_API_VERSION')\n \n \n except Exception as e:\n self.log.info(\"Unable to get openai credentials,please provide proper credentials.\"+str(e))\n return {\"error_msg\":\"openai_environment_error\"} \n except Exception as e:\n print(\"Openai credential set and get function error. Error message: \\\\n\",e)\n \n return openai.api_type,openai.api_base,openai.api_key,openai.api_version\n \n \n \n def get_embedding_local(self,model: str, text: str) -> list[float]:\n \"\"\" To get embedding data for single user given prompt text\"\"\"\n try:\n response = openai.Embedding.create(\n input=text,\n engine=self.generativeai_embedding_engine)\n except Exception as e:\n self.log.info(\"openai embedding creation error.\"+str(e))\n \n return result['data'][0]['embedding'] \n \n \n\n def get_embeddings_pyfiles(self,all_funcs):\n \"\"\" To get embedding for python functions \"\"\"\n \n try:\n import tiktoken\n openai_api_type,openai_api_base,openai_api_key,openai_api_version = self.getOpenAICredentials()\n encoding = tiktoken.encoding_for_model(\"text-embedding-ada-002\")\n df = pd.DataFrame(all_funcs)\n df[\"tokens\"] = df[\"code\"].apply(lambda c: len(encoding.encode(c)))\n embedding_cost = df[\"tokens\"].sum() * (0.0004/1000) \n EMBEDDING_FILEPATH=self.ccdreportpath+'\\\\code_embeddings.csv'\n self.log.info(\"embedding storage location: \"+str(EMBEDDING_FILEPATH))\n vdb_status = self.get_vdb_status('chromadb')\n ##Currently chromadb not integrated\n vdb_status = False\n if not vdb_status:\n df['code_embedding'] = df['code'].apply(lambda x: get_embedding(x, engine=self.generativeai_embedding_engine))\n df['filepath'] = df['filepath'].apply(lambda x: x.replace(self.rootdir, \"\"))\n df.to_csv(EMBEDDING_FILEPATH, index=False)\n \n else:\n df = self.chromadb_embedding(df)\n \n \"\"\" Please uncomment below, currently assumption is each run we create embedd based on python files dir \"\"\"\n import numpy as np\n df = pd.read_csv(EMBEDDING_FILEPATH)\n df[\"code_embedding\"] = df[\"code_embedding\"].apply(eval).apply(np.array)\n except Exception as e:\n self.log.info(\"Error in get_embeddings_pyfiles for embedding conversion process. Error Message: \"+str(e))\n raise Exception(\"Error in get_embeddings_pyfiles for embedding conversion process.\")\n \n return df,embedding_cost\n \n \n def search_functions_vectordb(df,db, code_query, n=3, pprint=True, n_lines=7):\n \"\"\" Search function for user query (prompt content), used for vector database embedding query option. \"\"\"\n try:\n docs = db.similarity_search_with_score(code_query )[:n]\n docs = [{\"similarities\":score, \"code\": d.page_content, **d.metadata} for d,score in docs]\n res = pd.DataFrame(docs).drop(\"_additional\", axis=1)\n ##Uncomment for debug\n # if pprint:\n # for r in res.iterrows():\n # print(r[1].filepath+\" : \"+r[1].function_name + \" score=\" + str(round(r[1].similarities, 3)))\n # print(\"\\\\n\".join(r[1].code.split(\"\\\\n\")[:n_lines]))\n # print('-'*70)\n except Exception as e:\n self.log.info(\"Error in search_functions_vectordb to get similarity information based on user query. Error Message: \"+str(e))\n raise Exception(\"Error in search_functions_csv to get similarity information based on user query.\")\n \n return res\n \n def search_functions_csv(self,df, code_query, n=3, pprint=True, n_lines=7):\n \"\"\" Search function for user query (prompt content), used for csv embedding query option. \"\"\"\n try:\n embedding = get_embedding(code_query, engine=self.generativeai_embedding_engine)\n df['similarities'] = df.code_embedding.apply(lambda x: cosine_similarity(x, embedding)) \n res = df.sort_values('similarities', ascending=False)\n ## uncomment for debug purpose\n # if pprint:\n # for r in res.iterrows():\n # print(r[1].filepath+\" : \"+r[1].function_name + \" score=\" + str(round(r[1].similarities, 3)))\n # print(\"\\\\n\".join(r[1].code.split(\"\\\\n\")[:n_lines]))\n # print('-'*70)\n except Exception as e:\n self.log.info(\"Error in search_functions_functions_csv to get similarity information based on user query. Error Message: \"+str(e))\n raise Exception(\"Error in search_functions_csv to get similarity information based on user query.\")\n return res\n \n def get_prediction(self,prompt_data):\n \"\"\" To get prediction for given user data \"\"\"\n try:\n all_funcs,code_root,", "instruction": "", "output": "" }, { "input": "code_files,total_locs=self.get_clone_function_details()\n if not isinstance(all_funcs,type(None)):\n df,embedding_cost=self.get_embeddings_pyfiles(all_funcs)\n res = self.search_functions_csv(df, prompt_data, n=3)\n return res\n else:\n return dict({\"error\":\"Empty_root_directory\"})\n except Exception as e:\n self.log.info(\"Error in get prediction for user prompt information. Error Message: \"+str(e))\n raise Exception(\"Error in get prediction for user prompt information. .\")\n \n def get_vdb_status(self,vdb_name):\n \"\"\" To check chromadb python package installed or not\"\"\"\n try:\n vdb_name = 'chromadb'\n vdb_status=False\n lib_name = importlib.util.find_spec(vdb_name)\n if lib_name is None: \n vdb_status=False \n else:\n vdb_status=True\n ## Processing the files and create a embedding and save it using csv.\n except Exception as e:\n self.log.info(\"Error in checking chromadb installed or not. Error Message: \"+str(e))\n raise Exception(\"Error in checking chromadb installed or not. .\")\n ## Currently vector db (chromadb) not implemented, so vdb_status is set as False\n vdb_status = False\n return vdb_status\n \n \n def create_chroma_db(self,documents, name):\n \"\"\" Craete chromadb instance (persistant) \"\"\"\n #get openai status\n openai_api_type,openai_api_base,openai_api_key,openai_api_version = self.getOpenAICredentials()\n # openai_api_type,openai_api_base,openai_api_key = self.getOpenAICredentials()\n try:\n from langchain.embeddings.openai import OpenAIEmbeddings\n embed_function = OpenAIEmbeddings(deployment=self.generativeai_embedding_engine, chunk_size=1)\n except:\n from chromadb.utils import embedding_functions\n embed_function = embedding_functions.OpenAIEmbeddingFunction(\n api_key=openai.api_key,\n api_base=openai.api_base,\n api_type = openai.api_type,\n model_name=self.generativeai_embedding_model\n )\n \n try:\n # chroma_client = chromadb.Client()\n persist_directory = self.embedd_storage_path\n \n chroma_client = chromadb.Client(\n Settings(\n persist_directory=persist_directory,\n chroma_db_impl=\"duckdb+parquet\",\n )\n )\n # Start from scratch\n chroma_client.reset()\n chroma_client.persist() \n \n try:\n embed_function = OpenAIEmbeddings(deployment=self.generativeai_embedding_engine, chunk_size=1)\n except:\n embed_function = OpenAIEmbeddings()\n db = Chroma.from_documents(documents, embed_function, persist_directory=persist_directory)\n db.persist()\n except Exception as e:\n self.log.info(\"Error in chromadb based embeding creation. Error Message: \"+str(e))\n raise Exception(\"Error in chromadb based embeding creation.\")\n return db,chroma_client\n \n def chromadb_embedding(self,df): \n \"\"\" Base chromadb embedding creation and storage function, it calls above create_chroma_db() to create db.\n \"\"\"\n try:\n documents = df.apply(lambda x: Document(page_content= x[\"code\"], metadata= {\"function_name\": x[\"function_name\"], \"filepath\": x[\"filepath\"]}), axis=1)\n #setup the chromadb\n db,chroma_client = self.create_chroma_db(documents,collection_name)\n try:\n chromadb_df=pd.DataFrame(db)\n except:\n db_json = db.get(include=['embeddings', 'documents', 'metadatas'])\n chromadb_df = pd.read_json(db_json)\n self.log.info(\"chromadb_df records (top ~5 records): \"+str(chromadb_df.head(5)))\n except Exception as e:\n self.log.info(\"chromadb embedding error. Error message: \"+str(e))\n\n return chromadb_df\n \n def num_tokens_from_string(self, string: str) -> int:\n \"\"\" Get number of tokens of text using tiktokens lib.\"\"\"\n encoding = tiktoken.encoding_for_model(\"text-embedding-ada-002\")\n num_tokens = len(encoding.encode(string))\n return num_tokens\n \n def validate_code_clone_with_explanation(self,code1, code2, verbose=False):\n \"\"\" Validate clone detection code snippet and get explanation from openai chat model (gpt-3.5-turbo) \"\"\"\n ## Openai using 4 chars as 1 token, same method here followed. Here,we dont need to call tiktoken lib to save cost.\n if (len(code1)/4 >1900):\n chunk = self.chunk_functions(code1, 1900)\n code1 = chunk[0]\n print(\"In side , len of code1\\\\n\",len(code1))\n \n if (len(code2)/4 >1900):\n chunk = self.chunk_functions(code2, 1900)\n code2 = chunk[0]\n print(\"In side , len of code2\\\\n\",len(code2))\n try:\n SYS_ROLE = \"You are a Senior Code Reviewer, who helps in Code review and integration using code clone detection approach.\"\n openai_api_type,openai_api_base,openai_api_key,openai_api_version = self.getOpenAICredentials()\n # openai_api_type,openai_api_base,openai_api_key = self.getOpenAICredentials()\n prompt = f\"\"\"Given two code snippets, find if they are clones or not with suitable explaination.\n \n Four types of clone:\n \n 1. Exact clone: Two code fragments similar to each other with little transformation in comments, layout, or whitespaces.\n 2. Parameterized clone: Changes made in names of variables, keywords, identifiers, or bypassing parameter during function call in code fragments, result in this clone.\n 3. Near-miss clone: Near-miss clone occurs by adding, deleting statements in code fragments of type 2 clones.\n 4. Semantic clone: The code snippets have different syntax but with alike functionality results in this clone.\n \n Use JSON object format with following keys:\n \n IsClone: (True, False) wheather two code snippets are clone or not.\n CloneType: (Exact clone, Parameterized clone, Never-miss clone, Semantic clone) Choose appropriate clone type or \"None\".\n Explanation: A short explanation for the above answer.\n \n ### Code Snippets:\n \n ## Code 1:\n {code1}\n \n ## Code 2:\n {code2}\n \n ### Answer(Valid JSON object):\n \"\"\"\n \n response = openai.ChatCompletion.create(deployment_id=self.generativeai_deploymentId,\n messages=[{\"role\": \"system\", \"content\": SYS_ROLE},\n {\"role\": \"user\", \"content\": prompt},],\n temperature = 0,max_tokens = 3900,request_timeout=90)\n \n \n \n text = response['choices'][0]['message']['content']\n if verbose:\n self.log.info(\"validate_code_clone_with_explanation, text: \"+str(text))\n except Exception as e:\n print(\" validate_code_clone_with_explanation: \\\\n\",e)\n response = \"OpenAI Model Connection\"\n if e.code == \"invalid_request\" and \"token limit\" in e.message.lower():\n # Implement your logic to reduce the length of messages or split them into smaller parts\n # Modify messages or take appropriate action\n self.log.info(\"Given function is too large and exceeds openai chat model token limit,please review the source file function length. \"+str(e))\n \n return response\n \n def validate_code_clone_with_explanation_davinci(self,code1, code2, verbose=False):\n \"\"\" Validate clone detection code snippet and get explanation from openai chat model (davinci) \"\"\"\n if (len(code1)/4 >1900):\n chunk = self.chunk_functions(code1, 1900)\n code1 = chunk[0] \n if (len(code2)/4 >1900):\n chunk = self.chunk_functions(code2, 1900)\n code2 = chunk[0]\n \n try:\n SYS_ROLE = \"You are a Senior Code Reviewer, who helps in Code review and integration. Detecting code clone in the repository.\"\n openai_api_type,openai_api_base,openai_api_key,openai_api_version = self.getOpenAICredentials()\n # openai_api_type,openai_api_base,openai_api_key = self.getOpenAICredentials()\n prompt = f\"\"\"Given two code snippets, find if they are clones or not with suitable explaination.\n \n Four types of clone:\n \n 1. Exact clone: Two code fragments similar to each other with little transformation in comments, layout, or whitespaces.\n 2. Parameterized clone: Changes made in names of variables, keywords, identifiers, or bypassing parameter during function call in code fragments, result in this clone.\n 3. Near-miss clone: Near-miss clone occurs by adding, deleting statements in code fragments of type 2 clones.\n 4. Semantic clone: The code snippets have different syntax but with alike functionality results in this clone.\n \n Use JSON object format with following keys:\n \n IsClone: (True, False) wheather two code snippets are clone or not.\n CloneType: (Exact clone, Parameterized clone, Never-miss clone, Semantic clone) Choose appropriate clone type or \"None\".\n Explanation: A short explanation for the above answer.\n \n ### Code Snippets:\n \n ## Code 1:\n {code1}\n \n ## Code 2:\n {code2}\n \n ### Answer(Valid JSON object):\n \"\"\"\n # response = openai.Completion.create(engine='Text-Datvinci-03', prompt=prompt, temperature=0, max_tokens=1166)\n response = openai.Completion.create(engine=self.generativeai_chat_model, prompt=prompt, temperature=0, max_tokens=3900)\n text = response.choices[0][\"text\"]\n if verbose:\n self.log.info(\"validate_code_clone_with_explanation, text (chatmodel response) \"+str(text))\n except Exception as e:\n response = \"OpenAI Model Connection Error\"\n if e.code == \"invalid_request\" and \"token limit\" in e.message.lower():\n # Implement your logic to reduce the length of messages or split them into smaller parts\n # Modify messages or take appropriate action\n 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))\n \n return response\n \n \n \n\n\n## For dbscan based clone detction from python files, we use CodeCloneDetection parent class. (Using inheritance)\nclass CodeCloneDetectionFiles(CodeCloneDetection):\n \"\"\"For dbscan based clone detction from python files, we use CodeCloneDetection \n parent class. (Using inheritance) \n \"\"\"\n 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):\n 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)\n def get_embedd_fns(self):\n \"\"\" To get embedd vector, using parent class methods\"\"\"\n try:\n ## Processing the files and create a embedding and save it using csv.\n vdb_status = super().get_vdb_status('chromadb')\n self.log.info(\"<------- AION Code Clone Detection started ... ------>\\\\n \")\n if not vdb_status:\n openai_api_type,openai_api_base,openai_api_key,openai_api_version = super().getOpenAICredentials()\n # openai_api_type,openai_api_base,openai_api_key = self.getOpenAICredentials()\n all_funcs,code_root,code_files,total_locs = super().get_clone_function_details()\n if (openai.api_key or openai_api_key):\n if not isinstance(all_funcs,type(None)):\n embedded_df,embedding_cost=super().get_embeddings_pyfiles(all_funcs)\n else:\n return status\n except Exception as e:\n # print(\"Error in getting embedding vector using openai. Error message: \",e)\n self.log.info(\"Error in getting embedding vector using openai. Error message: \"+str(e))\n raise Exception(\"Error in getting embedding vector using openai.\")\n return embedded_df,embedding_cost\n \n\n \n def dbscan_clone_detection(self,df):\n \"\"\" DBScan based code clone similarity detection (for functions in given dir \"\"\"\n try:\n vdb_status = super().get_vdb_status('chromadb')\n if not vdb_status:\n X = np.array(list(df.code_embedding.values))\n else:\n X = np.array(list(df.embeddings.values))\n #X = StandardScaler().fit_transform(X)\n db = DBSCAN(eps=0.2, min_samples=2).fit(X)\n labels = db.labels_\n # Number of clusters in labels, ignoring noise if present.\n n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\n n_noise_ = list(labels).count(-1)\n df[\"cluster\"] = labels\n cluster_result = []\n for i in range(n_clusters_):\n cluster_df = df.loc[df['cluster'] == i]\n # with open(\"{}/cluster_{}.txt\".format(self.ccdreportpath,i), \"w\") as f:\n for index, row in cluster_df.iterrows():\n cluster_result.append({\"cluster_id\": i,\"filepath\": row.filepath,\"function_name\": row.function_name,\"code\": row.code })\n # f.write(f\"Source File: {row.filepath}, Function Name: {row.function_name}\")\n #f.write(f\"\\\\n{row.code}\\\\n\\\\n{'-'*80}\\\\n\\\\n\")\n \n cluster_result_df = pd.DataFrame(cluster_result)\n codeclonereport_df = os.path.join(self.ccdreportpath,'cluster_result.csv') \n cluster_result_df.to_csv(codeclonereport_df, index=False)\n return cluster_result_df\n except Exception as e:\n self.log.info(\"Error in dbscan based similar code clone clustering. Error Message: \"+str(e))\n raise Exception(\"Error in dbscan based similar code clone clustering", "instruction": "", "output": "" }, { "input": ".\")\n \n def make_pairs(self,data_list:list):\n try:\n if len(data_list) <=1:\n return []\n \n return [(data_list[0], d) for d in data_list[1:]] + self.make_pairs(data_list[1:])\n except Exception as e:\n self.log.info(\"Error in make pairs function, error message: \"+str(e))\n raise Exception(\"Error in clone code mapping.\")\n \n def code_clone_check_with_retry(self,code1,code2, retry_interval=1):\n \"\"\" Call chat models for code clone detection with retry mechanism. \"\"\"\n try:\n # res = super().validate_code_clone_with_explanation(code1,code2)\n ##sj\n if (self.generativeai_embedding_model.lower() =='text-embedding-ada-002' and self.generativeai_chat_model.lower() == 'text-datvinci-03'):\n res = super().validate_code_clone_with_explanation_davinci(code1,code2)\n return res\n elif (self.generativeai_embedding_model.lower() =='text-embedding-ada-002' and self.generativeai_chat_model.lower() == 'gpt-3.5-turbo'):\n res = super().validate_code_clone_with_explanation(code1,code2)\n return res\n \n except (RateLimitError, Timeout) as e:\n self.log.info(\"Calling chat model issue in code clone check function, error message: \"+str(e))\n time.sleep(retry_interval)\n return self.code_clone_check_with_retry(code1, code2)\n \n def res_formater(self,inp):\n \"\"\" Function to format gpt-3.5 or text-davinci-003 response body. \"\"\"\n try:\n line = inp.replace('{','')\n line = line.replace('}','')\n line = line.replace('\"','')\n end=line.split(',')\n d1={}\n l2=[]\n for l in end:\n l=l.split(',')\n for i in l: \n l1=i.split(\":\")\n l2.append(l1)\n import pandas as pd\n df=pd.DataFrame(l2)\n df=df.T\n df.columns = df.iloc[0]\n df = df[1:]\n df.columns = df.columns.str.replace('[#,@,&,\\\\']', '')\n # df.to_csv('test1.csv', index=False)\n response=df.iloc[0]\n fl=response.to_list()\n clone_status=fl[0]\n clone_type=fl[1]\n result=fl[2]\n except Exception as e:\n self.log.info(\"chat model response formatter error. Error message: \"+str(e))\n return clone_status,clone_type,result\n\n \n def getcloneresult_modelspecific(self,code_clone_check_tasks,embedding_cost):\n \"\"\" get the clone type and associated information from chat model response data. \"\"\"\n try:\n max_workers = min(len(code_clone_check_tasks), 100)\n all_funcs,code_root,code_files,total_locs = super().get_clone_function_details()\n if (self.generativeai_chat_model.lower() == 'text-datvinci-03'):\n self.log.info(\"<--- Text-Datvinci-03 chat model based code clone detection. --->\")\n code_clone_result = []\n for task in code_clone_check_tasks:\n response=self.code_clone_check_with_retry(task[0][\"code\"], task[1][\"code\"])\n with concurrent.futures.ThreadPoolExecutor(max_workers= max_workers) as executor:\n llm_requests = {\n executor.submit(self.code_clone_check_with_retry, task[0][\"code\"], task[1][\"code\"]): task for task in code_clone_check_tasks\n }\n \n with tqdm(total= len(llm_requests)) as progress:\n for future in concurrent.futures.as_completed(llm_requests):\n task = llm_requests[future]\n try:\n res = future.result()\n try:\n my_openai_obj1 = res[\"choices\"][0][\"text\"]\n clone_status,clone_type,result = self.res_formater(my_openai_obj1)\n model_value=res['model']\n total_tokens_value=res['usage']['total_tokens']\n \n code_clone_result.append({\"task\": task,\n \"result\":result,\n \"IsClone\": clone_status,\n \"CloneType\": clone_type,\n \"model\":model_value,\n \"total_tokens\":total_tokens_value})\n except Exception as e:\n self.log.info(\"getCloneReport, code_clone_result.append error: \"+str(e))\n except Exception as exc:\n self.log.info(\"getCloneReport error (text davinci chat model): \"+str(exc))\n progress.update()\n ## Please uncomment below part if you need to check chat model response body.\n #codeclonecheckresult_json = os.path.join(self.ccdreportpath,'code_clone_chatmodel_responsebody.json')\n #with open(codeclonecheckresult_json, \"w+\") as fp:\n #json.dump(code_clone_result, fp, indent=2)\n \n code_clone_result_json=json.dumps(code_clone_result)\n clone_report=pd.read_json(code_clone_result_json)\n cr_totaltokens = clone_report['total_tokens']\n total_amt = (cr_totaltokens).sum() * (0.002/1000)\n clone_report[\"function1\"] = clone_report[\"task\"].apply(lambda x: x[0][\"filepath\"] + \" -> \" + x[0][\"function_name\"])\n clone_report[\"function2\"] = clone_report[\"task\"].apply(lambda x: x[1][\"filepath\"] + \" -> \" + x[1][\"function_name\"])\n # clone_report[\"clone_type\"] = clone_report[\"result\"].apply(lambda x: x[\"CloneType\"])\n clone_report[\"clone_type\"] = clone_report[\"CloneType\"]\n \n code_dir = code_root\n total_files = len(code_files)\n total_locs = total_locs\n total_functions = len(all_funcs)\n total_tokens = clone_report['total_tokens'].sum()\n total_cost= embedding_cost + clone_report['total_tokens'].sum() * (0.002/1000)\n total_clones = len(clone_report[clone_report.clone_type != \"None\"])\n code_clone_count_by_df = clone_report[clone_report.clone_type != \"None\"].groupby(\"clone_type\").agg(Count=('clone_type', 'count')).to_markdown(tablefmt='psql')\n clone_functions = clone_report[[\"function1\", \"function2\", \"clone_type\"]][clone_report.clone_type != \"None\"].sort_values(\"function1\").to_markdown(tablefmt='psql', index=False)\n code_clone_count_dict = clone_report[clone_report.clone_type != \"None\"].groupby(\"clone_type\").agg(Count=('clone_type', 'count'))\n clone_function_dict = clone_report[[\"function1\", \"function2\", \"clone_type\"]][clone_report.clone_type != \"None\"].sort_values(\"function1\")\n ##Final report on code clone detection\n report_str = f\"\"\"Code_directory: {code_dir}\n Files: {total_files}\n LOCs: {total_locs}\n Functions: {total_functions}\n \n Total_code_clones_detected: {total_clones}\n Tokens used: {total_tokens}\n Total cost(embedding + clone check): {total_cost}\n \n Four_types_of_clone:\n 1. Exact clone: Two code fragments similar to each other with little transformation in comments, layout, or whitespaces.\n 2. Parameterized clone: Changes made in names of variables, keywords, identifiers, or bypassing parameter during function call in code fragments, result in this clone.\n 3. Near-miss clone: Near-miss clone occurs by adding, deleting statements in code fragments of type 2 clones.\n 4. Semantic clone: The code snippets have different syntax but with alike functionality results in this clone.\n \n Code_clones_count_by_clone_type:\n {code_clone_count_by_df}\n \n Clone_functions:\n {clone_functions}\n \"\"\"\n codeclonereport_txt = os.path.join(self.ccdreportpath,'code_clone_report.txt')\n with open(codeclonereport_txt, \"w\") as f:\n f.write(report_str)\n \n report_dict=dict({\"Code_directory\":code_dir,\"total_files\":total_files,\n \"total_locs\":total_locs,\"total_functions\":total_functions,\"total_clones\":total_clones,\n \"total_tokens\":total_tokens,\"total_cost\":total_cost,\n \"Code_clones_count_by_clone_type\":code_clone_count_dict,\"clone_functions\":clone_function_dict})\n ## report for chat model is gpt 3.5 turbo \n elif (self.generativeai_chat_model.lower() == 'gpt-3.5-turbo'):\n try:\n self.log.info(\"<--- gpt-3.5-turbo chat model based code clone detection. --->\")\n code_clone_result = []\n for task in code_clone_check_tasks:\n response=self.code_clone_check_with_retry(task[0][\"code\"], task[1][\"code\"])\n with concurrent.futures.ThreadPoolExecutor(max_workers= max_workers) as executor:\n llm_requests = {\n executor.submit(self.code_clone_check_with_retry, task[0][\"code\"], task[1][\"code\"]): task for task in code_clone_check_tasks\n }\n \n with tqdm(total= len(llm_requests)) as progress:\n for future in concurrent.futures.as_completed(llm_requests):\n task = llm_requests[future]\n try:\n res = future.result()\n my_openai_obj1 = res[\"choices\"][0][\"message\"]['content']\n clone_status,clone_type,result = self.res_formater(my_openai_obj1)\n # result = json.loads(res['choices'][0]['message']['content'])\n total_tokens = res[\"usage\"][\"total_tokens\"] \n code_clone_result.append({\"task\": task,\n \"result\":result ,\n \"CloneType\": clone_type,\n \"total_tokens\": total_tokens})\n except Exception as exc:\n self.log.info(\"gpt 3.5 chat model error: \"+str(exc))\n \n progress.update()\n except Exception as e:\n print(\"In gpt3.5,getcloneresult_modelspecific fn exception : \\\\n\",e)\n import traceback\n print(\"traceback, In gpt3.5,getcloneresult_modelspecific fn exception \\\\n\",traceback.print_exc())\n ## Please uncomment below part if you need to check chat model response body.\n #codeclonecheckresult_json = os.path.join(self.ccdreportpath,'code_clone_chatmodel_responsebody.json')\n #with open(codeclonecheckresult_json, \"w+\") as fp:\n #json.dump(code_clone_result, fp, indent=2)\n try:\n code_clone_result_json=json.dumps(code_clone_result)\n clone_report = pd.read_json(code_clone_result_json)\n codeclone_total_amt = clone_report[\"total_tokens\"].sum() * (0.002/1000)\n clone_report[\"function1\"] = clone_report[\"task\"].apply(lambda x: x[0][\"filepath\"] + \" -> \" + x[0][\"function_name\"])\n clone_report[\"function2\"] = clone_report[\"task\"].apply(lambda x: x[1][\"filepath\"] + \" -> \" + x[1][\"function_name\"])\n # clone_report[\"clone_type\"] = clone_report[\"result\"].apply(lambda x: x[\"CloneType\"])\n clone_report[\"clone_type\"] = clone_report[\"CloneType\"]\n code_dir = code_root\n total_files = len(code_files)\n total_locs = total_locs\n total_functions = len(all_funcs) \n total_tokens = clone_report[\"total_tokens\"].sum()\n except Exception as e:\n self.log.info(\"Error in getting clone report: \"+str(e))\n total_cost= embedding_cost + clone_report[\"total_tokens\"].sum() * (0.002/1000)\n total_clones = len(clone_report[clone_report.clone_type != \"None\"])\n code_clone_count_by_df = clone_report[clone_report.clone_type != \"None\"].groupby(\"clone_type\").agg(Count=('clone_type', 'count')).to_markdown(tablefmt='psql')\n clone_functions = clone_report[[\"function1\", \"function2\", \"clone_type\"]][clone_report.clone_type != \"None\"].sort_values(\"function1\").to_markdown(tablefmt='psql', index=False)\n code_clone_count_dict = clone_report[clone_report.clone_type != \"None\"].groupby(\"clone_type\").agg(Count=('clone_type', 'count'))\n clone_function_dict = clone_report[[\"function1\", \"function2\", \"clone_type\"]][clone_report.clone_type != \"None\"].sort_values(\"function1\")\n report_str = f\"\"\"Code_directory: {code_dir}\n Files: {total_files}\n LOCs: {total_locs}\n Functions: {total_functions}\n \n Total code clones detected: {total_clones}\n Tokens used: {total_tokens}\n Total cost(embedding + clone check): {total_cost}\n \n Four types of clone:\n 1. Exact clone: Two code fragments similar to each other with little transformation in comments, layout, or whitespaces.\n 2. Parameterized clone: Changes made in names of variables, keywords, identifiers, or bypassing parameter during function call in code fragments, result in this clone.\n 3. Near-miss clone: Near-miss clone occurs by adding, deleting statements in code fragments of type 2 clones.\n 4. Semantic clone: The code snippets have different syntax but with alike functionality results in this clone.\n 5. None: Not a clone, discard this one.\n \n Code_clones_count_by_clone_type:\n {code_clone_count_by_df}\n \n Clone_functions:\n {clone_functions}\n \"\"\" \n codeclonereport_txt = os.path.join(self.ccdreportpath,'code_clone_report.txt')\n with open(codeclonereport_txt, \"w\") as", "instruction": "", "output": "" }, { "input": "f:\n f.write(report_str)\n \n report_dict=dict({\"Code_directory\":code_dir,\"total_files\":total_files,\n \"total_locs\":total_locs,\"total_functions\":total_functions,\"total_clones\":total_clones,\n \"total_tokens\":total_tokens,\"total_cost\":total_cost,\n \"Code_clones_count_by_clone_type\":code_clone_count_dict,\"clone_functions\":clone_function_dict}) \n \n except Exception as e:\n self.log.info(\"Error in clone type and information retrival process .Error message: \"+str(e))\n \n return code_clone_result,report_str,report_dict\n \n \n def getCloneReport(self):\n \"\"\" To get the clone report from the given python directory \"\"\"\n try:\n self.log.info(\"To get clone report, we are calling embedding and chat model.\")\n import time\n vdb_status = super().get_vdb_status('chromadb')\n start_time = time.time()\n # self.log.info(\"code clone detection start time.\"+str(start_time))\n if not vdb_status:\n embedded_df,embedding_cost = self.get_embedd_fns() \n cluster_df = self.dbscan_clone_detection(embedded_df)\n cluster_df_group = cluster_df.groupby(\"cluster_id\")\n len_cluster_df_group = len(cluster_df_group)\n code_clone_check_tasks = []\n for name, group in cluster_df_group:\n res = self.make_pairs(group.to_dict(orient=\"records\"))\n code_clone_check_tasks += res\n \n #For text-embedding-ada-002 and gpt 3.5 chat model\n code_clone_result,report_str,report_dict = self.getcloneresult_modelspecific(code_clone_check_tasks,embedding_cost) \n end_time = time.time()\n total_time_taken = end_time - start_time\n self.log.info(\"Total time taken for code clone detction: \"+str(total_time_taken)) \n self.log.info(\"<------------- Final code clone report: -------------------> \\\\n\"+str(report_str))\n report_df = pd.DataFrame.from_dict(report_dict, orient=\"index\").reset_index()\n report_df.columns = ['ccd_properties', 'Values']\n report_df=report_df.T\n codecloneresult_df = os.path.join(self.ccdreportpath,'code_clone_report_df.csv') \n report_df.to_csv(codecloneresult_df)\n return report_str,report_dict,report_df,json.dumps(report_str)\n else:\n #Below code indended for vector db.\n all_funcs,code_root,code_files,total_locs = super().get_clone_function_details()\n df = pd.DataFrame(all_funcs)\n df['filepath'] = df['filepath'].apply(lambda x: x.replace(code_root, \"\"))\n chromadb_df=super().chromadb_embedding(df)\n df = self.dbscan_clone_detection(chromadb_df)\n cluster_df_group = cluster_df.groupby(\"cluster_id\")\n len_cluster_df_group = len(cluster_df_group)\n code_clone_check_tasks = []\n for name, group in cluster_df_group:\n res = self.make_pairs(group.to_dict(orient=\"records\"))\n code_clone_check_tasks += res\n code_clone_result = []\n max_workers = min(len(code_clone_check_tasks), 100)\n with concurrent.futures.ThreadPoolExecutor(max_workers= max_workers) as executor:\n llm_requests = {\n executor.submit(self.code_clone_check_with_retry, task[0][\"code\"], task[1][\"code\"]): task for task in code_clone_check_tasks\n }\n \n with tqdm(total= len(llm_requests)) as progress:\n for future in concurrent.futures.as_completed(llm_requests):\n task = llm_requests[future]\n try:\n res = future.result()\n code_clone_result.append({\"task\": task,\n \"result\": json.loads(res['choices'][0]['message']['content']),\n \"total_tokens\": res[\"usage\"][\"total_tokens\"]})\n \n except Exception as exc:\n print('%r generated an exception: %s' % (task, exc))\n \n progress.update()\n with open(\"code_clone_check_result.json\", \"w+\") as fp:\n json.dump(code_clone_result, fp, indent=2)\n \n code_clone_result_json=json.dumps(code_clone_result)\n clone_report=pd.read_json(code_clone_result_json)\n total_amt = clone_report[\"total_tokens\"].sum() * (0.002/1000)\n clone_report[\"function1\"] = clone_report[\"task\"].apply(lambda x: x[0][\"filepath\"] + \" -> \" + x[0][\"function_name\"])\n clone_report[\"function2\"] = clone_report[\"task\"].apply(lambda x: x[1][\"filepath\"] + \" -> \" + x[1][\"function_name\"])\n clone_report[\"clone_type\"] = clone_report[\"result\"].apply(lambda x: x[\"CloneType\"])\n all_funcs,code_root,code_files,total_locs = super().get_clone_function_details()\n \n code_dir = code_root\n total_files = len(code_files)\n total_locs = total_locs\n total_functions = len(all_funcs)\n total_tokens = clone_report[\"total_tokens\"].sum()\n # total_cost= embedding_cost + clone_report[\"total_tokens\"].sum() * (0.002/1000)\n total_clones = len(clone_report[clone_report.clone_type != \"None\"])\n code_clone_count_by_df = clone_report[clone_report.clone_type != \"None\"].groupby(\"clone_type\").agg(Count=('clone_type', 'count')).to_markdown(tablefmt='psql')\n clone_functions = clone_report[[\"function1\", \"function2\", \"clone_type\"]][clone_report.clone_type != \"None\"].sort_values(\"function1\").to_markdown(tablefmt='psql', index=False) \n code_clone_count_dict = clone_report[clone_report.clone_type != \"None\"].groupby(\"clone_type\").agg(Count=('clone_type', 'count'))\n clone_function_dict = clone_report[[\"function1\", \"function2\", \"clone_type\"]][clone_report.clone_type != \"None\"].sort_values(\"function1\")\n \n ##Final report on code clone detection\n report_str = f\"\"\"Code_directory: {code_dir}\n Files: {total_files}\n LOCs: {total_locs}\n Functions: {total_functions}\n \n Total code clones detected: {total_clones}\n Tokens used: {total_tokens}\n \n Four types of clone:\n 1. Exact clone: Two code fragments similar to each other with little transformation in comments, layout, or whitespaces.\n 2. Parameterized clone: Changes made in names of variables, keywords, identifiers, or bypassing parameter during function call in code fragments, result in this clone.\n 3. Near-miss clone: Near-miss clone occurs by adding, deleting statements in code fragments of type 2 clones.\n 4. Semantic clone: The code snippets have different syntax but with alike functionality results in this clone.\n \n Code_clones_count_by_clone_type:\n {code_clone_count_by_df}\n \n Clone_functions:\n {clone_functions}\n \"\"\"\n with open(\"code_clone_report.txt\", \"w\") as f:\n f.write(report_str)\n \n # print(report_str)\n self.log.info(\"<------------- Final code clone report: -------------------> \\\\n\"+str(report_str))\n self.log.info(\"<------------- clone_functions code clone report: -------------------> \\\\n\"+str(clone_functions))\n report_dict=dict({\"Code_directory\":code_dir,\"total_files\":total_files,\n \"total_locs\":total_locs,\"total_functions\":total_functions,\"total_clones\":total_clones,\n \"total_tokens\":total_tokens,\n \"Code_clones_count_by_clone_type\":code_clone_count_dict,\"clone_functions\": clone_function_dict})\n\n \n report_df= pd.DataFrame([report_dict.keys(), report_dict.values()]).T\n report_df.columns = [\"Code_directory\", \"total_files\",\"total_locs\",\"total_functions\",\"total_clones\",\"total_tokens\",\"Code_clones_count_by_clone_type\",\"clone_functions\"]\n report_df.to_csv(\"code_clone_report_df.csv\")\n return report_str,report_dict,report_df,json.dumps(report_str)\n except Exception as e:\n self.log.info(\"Error in clone detection function call. Error Message: \\\\n\"+str(e))\n raise Exception(\"Error in clone detection function.\")\n\n#For testing and code instance privacy \nif __name__=='__main__':\n ## For testing purpose.Uncomment n use.\n root_directory = r\"C:\\\\AION_Works\\\\Anomaly_Detection\\\\anomalydetectionpackage\\\\code_clone_testing_pyfiles\\\\code_clone_testing_pyfiles_large\"\n embedd_storage_path = r\"C:\\\\AION_Works\\\\ccddir\"\n generativeai_credentials={'openai_baseurl':\"\",\n 'openai_key':\"\",\n 'openai_api_type':\"\",\n 'openai_api_version':\"\",\n 'generativeai_embedding_engine':\"\",\n 'generativeai_embedding_model':\"\",\n 'generativeai_chat_model':\"\",\n 'generativeai_deploymentId':\"\"}\n openai_baseurl = generativeai_credentials['openai_baseurl']\n openai_key = generativeai_credentials['openai_key']\n openai_api_type = generativeai_credentials['openai_api_type']\n openai_api_version = generativeai_credentials['openai_api_version']\n generativeai_embedding_engine = generativeai_credentials['generativeai_embedding_engine']\n generativeai_embedding_model = generativeai_credentials['generativeai_embedding_model']\n generativeai_chat_model = generativeai_credentials['generativeai_chat_model']\n generativeai_deploymentId = generativeai_credentials['generativeai_deploymentId']\n 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)\n report_str,report_dict,report_json = codeclonedetection_obj.getCloneReport()\n print(\"End of code clone detection....\\\\n\")\n \n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os,sys\nimport json\n\ndef getInstanceonGCP(image,instances):\n try:\n from appbe.sqliteUtility import sqlite_db \n from appbe.dataPath import DATA_DIR\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'config.db')\n if sqlite_obj.table_exists('LLMTuning'): \n data = sqlite_obj.read_data('LLMTuning','image=\"'+image['id']+'\"')\n for values in data:\n instance = {}\n instance['type'] = 'instance'\n instance['id'] = values[2]\n instance['workLoad'] = image['workLoad']\n instance['machineImageProjectID'] = image['machineImageProjectID']\n instance['ssh'] = image['ssh']\n instance['machineConfiguration'] = image['machineConfiguration']\n instance['instanceType'] = image['instanceType']\n instances.append(instance)\n except Exception as e:\n print(e)\n return instances\n \ndef getInstanceonAWS(amiid,instances):\n try:\n from appbe.sqliteUtility import sqlite_db \n from appbe.dataPath import DATA_DIR\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'config.db')\n if sqlite_obj.table_exists('LLMTuning'): \n data = sqlite_obj.read_data('LLMTuning','image=\"'+amiid['id']+'\"')\n for values in data:\n instance = {}\n instance['type'] = 'instance'\n instance['id'] = values[2]\n instance['workLoad'] = amiid['workLoad']\n instance['regionName'] = amiid['regionName']\n instance['ssh'] = amiid['ssh']\n instance['machineConfiguration'] = amiid['machineConfiguration']\n instance['instanceType'] = amiid['instanceType']\n instances.append(instance)\n except Exception as e:\n print(e)\n return instances\ndef updatelocalsetings(request):\n from appbe.sqliteUtility import sqlite_db\n from appbe.dataPath import DATA_DIR\n import pandas as pd\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'config.db')\n if sqlite_obj.table_exists('computeInfrastructure'): \t\t\n updated_data = 'selectedInfrastructure=\"Local\"'\n sqlite_obj.update_data(updated_data,'','computeInfrastructure')\ndef updateToComputeSettings(infratructure):\n from appbe.sqliteUtility import sqlite_db\n from appbe.dataPath import DATA_DIR\n import pandas as pd\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'config.db')\n if sqlite_obj.table_exists('computeInfrastructure'): \t\t\n updated_data = 'selectedInfrastructure=\"'+infratructure+'\"'\n sqlite_obj.update_data(updated_data,'','computeInfrastructure')\ndef updateGCPConfig(request):\n try:\n credentialsJson = request.POST.get('credentialsJson')\n projectID = request.POST.get('gcpProjectid')\n machineType = request.POST.get('gcpmachineType')\n selectedID = request.POST.get('gcpInstance')\n gcpZone = request.POST.get('gcpZone')\n workload = request.POST.get('gcpworkload')\n noOfInstance = request.POST.get('GCPnoofinstance')\n #print(credentialsJson,projectID,machineType,selectedID,gcpZone,workload,noOfInstance)\n if credentialsJson != '' and projectID != '':\n from appbe", "instruction": "", "output": "" }, { "input": ".sqliteUtility import sqlite_db\n from appbe.dataPath import DATA_DIR\n import pandas as pd\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'config.db')\n if sqlite_obj.table_exists('gcpCredentials'):\n updated_data = 'credentialsJson=\"'+credentialsJson+'\",projectID=\"'+projectID+'\",machineType=\"'+machineType+'\",selectedID=\"'+selectedID+'\",regionName=\"'+gcpZone+'\",noOfInstance=\"'+str(noOfInstance)+'\",workload=\"'+workload+'\"'\n sqlite_obj.update_data(updated_data,'','gcpCredentials')\n else:\n newdata = {}\n newdata.update({'id':['1'],'credentialsJson': [credentialsJson],'projectID': [projectID],'machineType':[machineType],'selectedID':[selectedID],'regionName':[gcpZone],'noOfInstance':[noOfInstance],'workload':[workload]}) \n sqlite_obj.write_data(pd.DataFrame.from_dict(newdata),'gcpCredentials')\n return('success')\n else:\n return('error') \n except Exception as e:\n print(e)\n return('error') \ndef updateComputeConfig(request):\n try:\n AWSAccessKeyID = request.POST.get('AWSAccessKeyID')\n AWSSecretAccessKey = request.POST.get('AWSSecretAccessKey')\n workload = request.POST.get('workload')\n machineType = request.POST.get('machineType')\n selectedID = request.POST.get('amiInstance')\n regionName = request.POST.get('regionName')\n noOfInstance = request.POST.get('NoOfInstance')\n securitygroupid = request.POST.get('AWSSecuritygroupID')\n if AWSAccessKeyID != '' and AWSSecretAccessKey != '':\n from appbe.sqliteUtility import sqlite_db\n from appbe.dataPath import DATA_DIR\n import pandas as pd\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'config.db')\n if sqlite_obj.table_exists('awsCredentials'):\n column_names = sqlite_obj.column_names('awsCredentials')\n if 'securitygroupid' not in column_names:\n query = 'Alter Table awsCredentials ADD securitygroupid TEXT'\n sqlite_obj.execute_query(query)\n updated_data = 'AWSAccessKeyID=\"'+AWSAccessKeyID+'\",AWSSecretAccessKey=\"'+AWSSecretAccessKey+'\",machineType=\"'+machineType+'\",selectedID=\"'+selectedID+'\",regionName=\"'+regionName+'\",noOfInstance=\"'+noOfInstance+'\",workload=\"'+workload+'\",securitygroupid=\"'+securitygroupid+'\"'\n sqlite_obj.update_data(updated_data,'','awsCredentials')\n else:\n newdata = {}\n newdata.update({'id':['1'],'AWSAccessKeyID': [AWSAccessKeyID],'AWSSecretAccessKey': [AWSSecretAccessKey],'machineType':[machineType],'selectedID':[selectedID],'regionName':[regionName],'noOfInstance':[noOfInstance],'workload':[workload],'securitygroupid':[securitygroupid]})\n sqlite_obj.write_data(pd.DataFrame.from_dict(newdata),'awsCredentials')\n return('success')\n else:\n return('error') \n except Exception as e:\n print(e)\n return('error')\n\ndef selectedInfratructure():\n from appbe.sqliteUtility import sqlite_db\n from appbe.dataPath import DATA_DIR\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'config.db')\n selcInfra = 'Local'\n if sqlite_obj.table_exists('computeInfrastructure'):\n data = sqlite_obj.read_data('computeInfrastructure')\n for values in data:\n selcInfra = values[1]\n return selcInfra\n\ndef readComputeConfig():\n try:\n file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','config','compute_conf.json'))\n f = open(file_path, \"r\")\n configSettings = f.read()\n f.close()\n configSettingsJson = json.loads(configSettings)\n from appbe.sqliteUtility import sqlite_db\n from appbe.dataPath import DATA_DIR\n import pandas as pd\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'config.db')\n selcInfra = 'Local'\n if sqlite_obj.table_exists('computeInfrastructure'):\n data = sqlite_obj.read_data('computeInfrastructure')\n for values in data:\n selcInfra = values[1]\n \n else:\n data = {}\n data.update({'id':['1'],'selectedInfrastructure': ['Local']})\n sqlite_obj.write_data(pd.DataFrame.from_dict(data),'computeInfrastructure')\n configSettingsJson['computeInfrastructure'] = selcInfra\n for ami in configSettingsJson['AWS_EC2']['amis']:\n configSettingsJson['AWS_EC2']['instances'] = getInstanceonAWS(ami,configSettingsJson['AWS_EC2']['instances'])\n for image in configSettingsJson['GCP']['machineImage']:\n configSettingsJson['GCP']['instances'] = getInstanceonGCP(image,configSettingsJson['GCP']['instances']) \n \n AWSAccessKeyID = ''\n AWSSecretAccessKey = ''\n securitygroupid = ''\n machineType = 'AMI'\n selectedID = ''\n regionName = ''\n noofInfra = 1\n workLoad = 'LLM'\n if sqlite_obj.table_exists('awsCredentials'):\n column_names = sqlite_obj.column_names('awsCredentials')\n #print(column_names)\n if 'workload' not in column_names:\n query = 'Alter Table awsCredentials ADD workload TEXT'\n sqlite_obj.execute_query(query)\n if 'securitygroupid' not in column_names:\n query = 'Alter Table awsCredentials ADD securitygroupid TEXT'\n sqlite_obj.execute_query(query) \n data = sqlite_obj.read_data('awsCredentials')\n for values in data:\n AWSAccessKeyID = values[1] \n AWSSecretAccessKey = values[2]\n machineType = values[3]\n selectedID = values[4]\n regionName = values[5]\n noofInfra = values[6]\n workLoad = values[7]\n securitygroupid = values[8]\n selectedAWS = {}\n selectedAWS['accessKey'] = AWSAccessKeyID\n selectedAWS['secretAccessKey'] = AWSSecretAccessKey\n selectedAWS['machineType']=machineType\n selectedAWS['selectedID'] = selectedID\n selectedAWS['regionName'] = regionName\n selectedAWS['noOfInstance']=noofInfra\n selectedAWS['workLoad'] = workLoad\n selectedAWS['securitygroupid'] = securitygroupid\n configSettingsJson['awsCredentials'] = selectedAWS\n \n gcpCredentials=''\n projectID = ''\n selectedID = ''\n machineType = ''\n regionName = ''\n noOfInstance = 1\n workLoad = 'LLM'\n if sqlite_obj.table_exists('gcpCredentials'):\n column_names = sqlite_obj.column_names('gcpCredentials')\n if 'workload' not in column_names:\n query = 'Alter Table gcpCredentials ADD workload TEXT'\n sqlite_obj.execute_query(query)\n data = sqlite_obj.read_data('gcpCredentials') \n for values in data:\n gcpCredentials = values[1] \n projectID = values[2]\n machineType = values[3] \n selectedID = values[4] \n regionName = values[5] \n noOfInstance = values[6]\n workLoad = values[7]\n selectedGCP = {}\n selectedGCP['gcpCredentials'] = gcpCredentials\n selectedGCP['selectedID'] = selectedID\n selectedGCP['projectID'] = projectID \n selectedGCP['machineType'] = machineType\n selectedGCP['regionName'] = regionName \n selectedGCP['noOfInstance'] = noOfInstance\n selectedAWS['workLoad'] = workLoad\n configSettingsJson['gcpCredentials'] = selectedGCP\n #print(configSettingsJson)\n return(configSettingsJson)\n except Exception as e:\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno)) '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport json\nimport os\nimport rsa\nimport boto3 #usnish\nimport pandas as pd\nimport time\ndef add_new_bucket(request):\n\n try:\n \n file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','s3bucket.conf'))\n with open(file_path, 'r') as f:\n data = json.load(f)\n except:\n data = []\t\n\t\n if request.POST[\"aionreferencename\"] =='' or request.POST[\"s3bucketname\"] == '' or request.POST[\"awsaccesskey\"] == '' :\n return 'error' \n pkeydata='''-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAxIHM1FphEMMwViUrG0b2Bqf8tOxbhUWlnmjgFt5A25qbY1AfnrMv\nfVx8+7iCcZ/3TY9Jv2I584SOc1tvsgESCke/t6+o/u2esPBsnDFzV62l3Zvw0m4e\nwQeKlFC8EoOblyIXRbZdelSJinzlr9lOiKuid/xPvXHou6jxF1A2W7a89A2PM4Re\nn0W9YkjB7dRGW1sSrpruHdVJvgHhGZFZ7sCTue0jVOnc5sT3Tq5saLfEDqHyKxlq\ni/mcThmcTfisRIYFH5pyt/Ysr4VVP924QlcoqPOyg3RMCS3G0VjstSoVwNhxWrs/\nlujDuCnpxvWzNpq21OWmF66GXxwiq+6W0wIDAQAB\n-----END RSA PUBLIC KEY-----'''\n\n pubkey = rsa.PublicKey.load_pkcs1(pkeydata)\n awssecretaccesskey = rsa.encrypt(request.POST[\"awssecretaccesskey\"].encode(), pubkey)\n print(awssecretaccesskey)\n newdata = {}\n newdata['Name'] = request.POST[\"aionreferencename\"]\n newdata['AWSAccessKeyID'] = request.POST[\"awsaccesskey\"]\n newdata['AWSSecretAccessKey'] = str(awssecretaccesskey)\n newdata['S3BucketName'] = request.POST[\"s3bucketname\"]\n data.append(newdata)\n with open(file_path, 'w') as f:\n json.dump(data, f)\n f.close()\n\ndef get_s3_bucket():\n\ttry:\n\t\tfile_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','s3bucket.conf'))\n\t\twith open(file_path, 'r') as f:\n\t\t\tdata = json.load(f)\n\texcept:\n\t\tdata = []\n\treturn data\ndef read_s3_bucket(name,filename,DATA_FILE_PATH):\n\tprivkey = '''-----BEGIN RSA PRIVATE KEY-----\nMIIEqQIBAAKCAQEAxIHM1FphEMMwViUrG0b2Bqf8tOxbhUWlnmjgFt5A25qbY1Af\nnrMvfVx8+7iCcZ/3TY9Jv2I584SOc1tvsgESCke/t6+o/u2esPBsnDFzV62l3Zvw\n0m4ewQeKlFC8EoOblyIXRbZdelSJinzlr9lOiKuid/xPvXHou6jxF1A2W7a89A2P\nM4Ren0W9YkjB7dRGW1sSrpruHdVJvgHhGZFZ7sCTue0jVOnc5sT3Tq5saLfEDqHy\nKxlqi/mcThmcTfisRIYFH5pyt/Ysr4VVP924QlcoqPOyg3RMCS3G0VjstSoVwNhx\nWrs/lujDuCnpxvWzNpq21OWmF66GXxwiq+6W0wIDAQABAoIBAC/VbNfQPEqJSO3f\nVFPqfR73q2MbGdgiMQOTgeDvLxiF1QdizJ+j/I5mgiIAMviXuOpPU+NbdMHbZZWd\nD15kNlD8UCXVg6yyiOuHStjmjK4uHe8I86E1nxTb0hbyZCWZlbk/WizlDHInu+dT\nKdIZcq2AIidU6tAxtwA0ingHaRSoXDlSGwOTEigNqmWOKnDTVg0SMscoHOD7siXF\nDHm1/lkvD3uvcZk6c7fGxC8SgNX2dj6n/Nbuy0Em+bJ0Ya5wq4HFdLJn3EHZYORF\nODUDYoGaSxeXqYsGg/KHJBc8J7xW9FdN9fGbHfw1YplrmiGL3daATtArjMmAh0EQ\nH8Sj7+ECgYkA3oWMCHi+4t8txRPkg1Fwt8dcqYhGtqpAus3NESVurAdi0ZPqEJcQ\n4cUbflwQPhX0TOaBlkgzdP8DMdcW/4RalxHsAh5N8ezx/97PQMb3Bht0WsQUBeYJ\nxLV7T2astjTRWactGCG7dwTaUYRtU3FqL6//3CysmA12B5EMX0udNBOTKwmaYKww\nAwJ5AOISS7f12Q0fgTEVY0H8Zu5hHXNOA7DN92BUzf99iPx+H+codLet4Ut4Eh0C\ncFmjA3TC78oirp5mOOQmYxwaF", "instruction": "", "output": "" }, { "input": "axlZ7Rs60dlPFrhz0rsHYPK1yUOWRr3RcXWSR13\nr+kn+f+8k7nItfGi7shdcQW+adm/EqPfwTHM8QKBiQCIPEMrvKFBzVn8Wt2A+I+G\nNOyqbuC8XSgcNnvij4RelncN0P1xAsw3LbJTfpIDMPXNTyLvm2zFqIuQLBvMfH/q\nFfLkqSEXiPXwrb0975K1joGCQKHxqpE4edPxHO+I7nVt6khVifF4QORZHDbC66ET\naTHA3ykcPsGQiGGGxoiMpZ9orgxyO3l5Anh92jmU26RNjfBZ5tIu9dhHdID0o8Wi\nM8c3NX7IcJZGGeCgywDPEFmPrfRHeggZnopaAfuDx/L182pQeJ5MEqlmI72rz8bb\nJByJa5P+3ZtAtzc2RdqNDIMnM7fYU7z2S279U3nZv0aqkk3j9UDqNaqvsZMq73GZ\ny8ECgYgoeJDi+YyVtqgzXyDTLv6MNWKna9LQZlbkRLcpg6ELRnb5F/dL/eB/D0Sx\nQpUFi8ZqBWL+A/TvgrCrTSIrfk71CKv6h1CGAS02dXorYro86KBLbJ0yp1T/WJUj\nrHrGHczglvoB+5stY/EpquNpyca03GcutgIi9P2IsTIuFdnUgjc7t96WEQwL\n-----END RSA PRIVATE KEY-----'''\n\ttry:\n\t\tfile_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','s3bucket.conf'))\n\t\twith open(file_path, 'r') as f:\n\t\t\tdata = json.load(f)\n\texcept:\n\t\tdata = []\n\tawssecretaccesskey = ''\n\tfound = False\n\tfor x in data:\n\t\tif x['Name'] == name:\n\t\t\tawssecretaccesskey = x['AWSSecretAccessKey']\n\t\t\taws_access_key_id = x['AWSAccessKeyID']\n\t\t\tbucketName = x['S3BucketName']\n\t\t\tfound = True\n\t\t\tbreak\t\t\n\tif found:\n\t\tprivkey = rsa.PrivateKey.load_pkcs1(privkey,'PEM')\n\t\tawssecretaccesskey = eval(awssecretaccesskey)\n\t\tawssecretaccesskey = rsa.decrypt(awssecretaccesskey, privkey)\n\t\tawssecretaccesskey = awssecretaccesskey.decode('utf-8')\n\t\t#awssecretaccesskey = 'SGcyJavYEQPwTbOg1ikqThT+Op/ZNsk7UkRCpt9g'#rsa.decrypt(awssecretaccesskey, privkey)\n\t\tclient_s3 = boto3.client('s3', aws_access_key_id=aws_access_key_id, aws_secret_access_key=str(awssecretaccesskey))\n\t\t#print(bucketName,filename)\n\t\ttry: \n\t\t\tresponse = client_s3.get_object(Bucket=bucketName, Key=filename)\n\t\t\tdf = pd.read_csv(response['Body'])\n\t\texcept Exception as e:\n\t\t\tprint(e)#usnish\n\t\t\treturn 'Error', pd.DataFrame()\n\t\t\t\n\t\t\t#return 'Error', pd.DataFrame()\n\t\treturn 'Success',df\n\treturn 'Error', pd.DataFrame() '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os,sys\nimport json\nimport platform\nimport subprocess\ndef kafka_setting():\n file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','config','kafkaConfig.conf'))\n f = open(file_path, \"r\")\n configSettings = f.read()\n f.close()\n configSettingsJson = json.loads(configSettings)\n from os.path import expanduser\n home = expanduser(\"~\")\n if platform.system() == 'Windows':\n DEPLOY_LOCATION = os.path.join(home,'AppData','Local','HCLT','AION','target','kafka')\n else:\n DEPLOY_LOCATION = os.path.join(home,'HCLT','AION','target','kafka')\n configSettingsJson['kafkalocation'] = DEPLOY_LOCATION\n return(configSettingsJson)\n\ndef start_tracking():\n from appbe.dataPath import DEPLOY_LOCATION \n import platform\n mlflowpath = os.path.normpath(os.path.join(os.path.dirname(__file__),'..','..','..','..','Scripts','mlflow.exe'))\n script_path = os.path.normpath(os.path.join(os.path.dirname(__file__),'..','..','..','..','Scripts')) \n #Updating path for system environment; Bug-13835\n os.environ['PATH']= os.environ['PATH']+ ';'+ str(script_path) \n DEPLOY_LOCATION = os.path.join(DEPLOY_LOCATION,'mlruns')\n if platform.system() == 'Windows':\n subprocess.Popen([sys.executable, mlflowpath,\"ui\", \"--backend-store-uri\",\"file:///\"+DEPLOY_LOCATION])\n else:\n subprocess.Popen(['mlflow',\"ui\",\"-h\",\"0.0.0.0\",\"--backend-store-uri\",\"file:///\"+DEPLOY_LOCATION])\n\ndef aion_tracking():\n status = 'Success'\n import requests\n try:\n response = requests.get('http://localhost:5000')\n if response.status_code != 200:\n status = 'Error'\n except Exception as inst:\n print(inst) \n status = 'Error'\n return status\n \ndef aion_service():\n try:\n if platform.system() == 'Windows':\n nooftasks = getrunningstatus('AION_Service')\n else:\n nooftasks = getrunningstatus('run_service') \t\t\n if len(nooftasks):\n status = 'Running'\n else:\n if platform.system() == 'Windows':\n servicepath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','sbin','AION_Service.bat'))\t\t\t\n os.system('start cmd /c \"'+servicepath+'\"')\n else:\n servicepath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','bin','run_service.py'))\n subprocess.Popen([sys.executable,servicepath])\n status = 'Started'\n except Exception as inst:\n print(inst)\n status = 'Error'\n return status\n \n \ndef getrunningstatus(name):\n try:\n taskdetails = []\n if platform.system() == 'Windows':\n r = ([line.split() for line in subprocess.check_output('tasklist /v /FI \"IMAGENAME eq conhost.exe\"').decode('UTF-8').splitlines()])\n r.append([line.split() for line in subprocess.check_output('tasklist /v /FI \"IMAGENAME eq cmd.exe\"').decode('UTF-8').splitlines()])\n else:\n r = ([line.split() for line in subprocess.check_output(\"ps -ef | grep .py\",shell=True).decode('UTF-8').splitlines()])\n for i in range(len(r)):\n s = r[i]\n if any(name in j for j in s): \n taskdetails.append('Yes')\n break\n return (taskdetails)\n except Exception as inst:\n print(inst)\n status = 'Error'\n return status \ndef getTasks(mlflow,consumer,service):\n mlflowlist = []\n consumerlist=[]\n servicelist = []\n #r = os.popen('tasklist /v').read().strip().split('\\\\n')\n try:\n if platform.system() == 'Windows':\n r = ([line.split() for line in subprocess.check_output('tasklist /v /FI \"IMAGENAME eq conhost.exe\"').decode('UTF-8').splitlines()])\n r.append([line.split() for line in subprocess.check_output('tasklist /v /FI \"IMAGENAME eq cmd.exe\"').decode('UTF-8').splitlines()])\n else:\n r = ([line.split() for line in subprocess.check_output(\"ps -ef | grep .py\",shell=True).decode('UTF-8').splitlines()])\n except Exception as e:\n print(e)\n r = []\n \n #print(r)\n #print ('# of tasks is %s' % (len(r)))\n for i in range(len(r)):\n s = r[i]\n if any(mlflow in j for j in s):\n mlflowlist.append('Yes')\n if any(consumer in j for j in s):\n consumerlist.append('Yes')\n if any(service in j for j in s):\n servicelist.append('Yes') \n return (mlflowlist,consumerlist,servicelist)\n\ndef running_setting():\n otherApps = {}\n if platform.system() == 'Windows':\n mlflowlist,consumerlist,servicelist = getTasks('AION_MLFlow','AION_Consumer','AION_Service')\n else:\n mlflowlist,consumerlist,servicelist = getTasks('run_mlflow','AION_Consumer','run_service')\t\n if len(mlflowlist):\n otherApps['modeltracking'] = 'Running'\n else: \n otherApps['modeltracking'] = 'Not Running'\n \n #nooftasks = getTasks('AION_Consumer')\n if len(consumerlist):\n otherApps['consumer'] = 'Running'\n else: \n otherApps['consumer'] = 'Not Running' \n\n #nooftasks = getTasks('AION_Service')\n if len(servicelist):\n otherApps['service'] = 'Running'\n else: \n otherApps['service'] = 'Not Running'\n return(otherApps)\n\n\n#EDA Performance change\n# ----------------------------\ndef eda_setting():\n configfilepath = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','config','eda.config')\n sample_size=''\n try:\n if(os.path.isfile(configfilepath)):\n file = open(configfilepath, \"r\")\n read = file.read()\n file.close()\n for line in read.splitlines():\n if 'sample_size=' in line:\n sample_size = line.split('=',1)[1] \n except Exception as inst:\n pass \n return(sample_size)\ndef get_telemetryoptout():\n telemetryoptuout = \"No\"\n from appbe.sqliteUtility import sqlite_db\n from appbe.dataPath import DATA_DIR\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'config.db')\n try:\n if sqlite_obj.table_exists('settings'):\n data = sqlite_obj.read_data('settings')\n for values in data:\n telemetryoptuout = values[7]\n \n else:\n telemetryoptuout = 'No'\n except Exception as e:\n print(e)\n telemetryoptuout ='No'\n return telemetryoptuout \ndef get_edafeatures():\n No_of_Permissible_Features_EDA = \"\"\n from appbe.sqliteUtility import sqlite_db\n from appbe.dataPath import DATA_DIR\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'config.db')\n try:\n if sqlite_obj.table_exists('settings'):\n data = sqlite_obj.read_data('settings')\n for values in data:\n No_of_Permissible_Features_EDA = values[3]\n \n else:\n configfilepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'config', 'aion.config')\n if (os.path.isfile(configfilepath)):\n file = open(configfilepath, \"r\")\n read = file.read()\n file.close()\n for line in read.splitlines():\n if 'No_of_Permissible_Features_EDA=' in line:\n No_of_Permissible_Features_EDA = line.split('=', 1)[1]\n except Exception as e:\n print(e)\n No_of_Permissible_Features_EDA =20\n return No_of_Permissible_Features_EDA\n \ndef get_graviton_data():\n graviton_url = \"\"\n graviton_userid = \"\"\n\n from appbe.sqliteUtility import sqlite_db\n from appbe.dataPath import DATA_DIR\n \n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'config.db')\n try:\n if sqlite_obj.table_exists('settings'):\n data = sqlite_obj.read_data('settings')\n for values in data:\n graviton_url = values[0]\n graviton_userid = values[1]\n\n else:\n configfilepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'config', 'aion.config')\n if (os.path.isfile(configfilepath)):\n file = open(configfilepath, \"r\")\n read = file.read()\n file.close()\n for line in read.splitlines():\n if 'graviton_url=' in line:\n graviton_url = line.split('=', 1)[1]\n if 'graviton_userid=' in line:\n graviton_userid = line.split('=', 1)[1]\n\n except Exception as e:\n print(e)\n graviton_url = \"\"\n graviton_userid = \"\"\n return graviton_url,graviton_userid\n\n\ndef get_llm_data():\n apiKeyIdLLM = \"\"\n apiUrlLLM = \"\"\n from appbe.sqliteUtility import sqlite_db\n from appbe.dataPath import DATA_DIR\n \n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'config.db')\n try:\n if sqlite_obj.table_exists('openai'):\n data = sqlite_obj.read_data('openai')[0]\n param_keys", "instruction": "", "output": "" }, { "input": "= ['api_type','api_key','api_base','api_version']\n openai_data = dict((x,y) for x,y in zip(param_keys,data)) \n return openai_data['api_key'],openai_data['api_base'],openai_data['api_type'],openai_data[", "instruction": "", "output": "" }, { "input": "write_data(pd.DataFrame.from_dict(newdata),'dataingest')\n else:\n raise Exception(\"Data Genration failed.\")\n except Exception as e:\n print(e)\n raise Exception(str(e))\nif __name__ == \"__main__\":\n generate_json_config('classification')\n generate_json_config('regression')\n generate_json_config('timeseriesforecasting') #task 11997 '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport time\nfrom pathlib import Path\nimport logging\nfrom datetime import datetime as dt\n\n\nclass logg():\n from appbe.dataPath import LOG_LOCATION\n def __init__(self, LOG_LOCATION):\n self.log_location = LOG_LOCATION\n\n def create_log(self,version):\n log_file_path = Path(self.log_location)\n log_file_path.mkdir(parents=True, exist_ok=True)\n time_stamp = dt.fromtimestamp(time.time()).strftime('%Y-%m-%d-%H-%M-%S') \n fileName='log_ux_'+time_stamp+'.log'\n filehandler = logging.FileHandler(log_file_path/fileName, 'a','utf-8')\n formatter = logging.Formatter('%(asctime)s %(message)s')\n filehandler.setFormatter(formatter)\n log = logging.getLogger('log_ux')\n log.propagate = False \n for hdlr in log.handlers[:]: # remove the existing file handlers\n if isinstance(hdlr,logging.FileHandler):\n log.removeHandler(hdlr)\n log.addHandler(filehandler)\n log.setLevel(logging.INFO)\n log.info('********** AION_'+str(version)+' **********')\n return log '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport requests\nimport json\nimport os\nfrom datetime import datetime\nimport socket\nimport getmac\nfrom appbe.sqliteUtility import sqlite_db\nimport pandas as pd\nfrom appbe.dataPath import DATA_DIR\ndef TelemetryCreateSyncState(state):\n try:\n newdata = {}\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'telemetry.db')\n now = datetime.now()\n SyncingTime = int(datetime.timestamp(now))\n newdata.update({'ID':['1'],'state':[state],'syncingTime':[SyncingTime]})\n sqlite_obj.write_data(pd.DataFrame.from_dict(newdata),'syncState') \n except Exception as e:\n print(e)\n pass\n\ndef TelemetryUpdateSyncState(state):\n try:\n newdata = {}\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'telemetry.db')\n now = datetime.now()\n SyncingTime = int(datetime.timestamp(now))\n updated_data = '\"state\"=\"'+state+'\",\"syncingTime\"=\"'+str(SyncingTime)+'\"'\n sqlite_obj.update_data(updated_data,'ID=\"1\"','syncState')\n except Exception as e:\n print(e)\n pass\ndef checkTelemtry():\n import subprocess\n import sys\n scriptPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','aion.py'))\n if os.path.exists(scriptPath):\n outputStr = subprocess.Popen([sys.executable,scriptPath,'-m','pushtelemetry'])\n \ndef SyncTelemetry():\n try:\n newdata = {}\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'telemetry.db')\n if sqlite_obj.table_exists('syncState'):\n data = sqlite_obj.read_data('syncState')[0]\n param_keys = ['ID','state','syncingTime']\n sync_data = dict((x,y) for x,y in zip(param_keys,data))\n #print(sync_data['state'],sync_data['syncingTime'])\n if sync_data['state'].lower() != 'syncing':\n sync_time = sync_data['syncingTime']\n now = datetime.now()\n currTime = datetime.timestamp(now)\n diffTime = int(float(currTime)) - int(float(sync_time))\n #print(diffTime)\n if int(diffTime) > 86400:\n TelemetryUpdateSyncState('Syncing')\n SendTelemetryUpdate(sync_time) \n TelemetryUpdateSyncState('Done')\n else:\n TelemetryCreateSyncState('Initialize')\n except Exception as e:\n print(e)\n pass\n \n \ndef UseCaseCreated(Usecase):\n try:\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'telemetry.db')\n newdata = {}\n now = datetime.now()\n ID = datetime.timestamp(now)\n record_date = int(datetime.timestamp(now))\n computername = socket.getfqdn()\n macaddress = getmac.get_mac_address()\n try:\n user = os.getlogin()\n except:\n user = 'NA'\n 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']})\n sqlite_obj.write_data(pd.DataFrame.from_dict(newdata),'logs') \n except Exception as e:\n print(e)\n pass\ndef UpdateTelemetry(Usecase,operation,value):\n try:\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'telemetry.db') \n data = sqlite_obj.read_data('logs','Usecase=\"'+Usecase+'\"')\n #print(data)\n if sqlite_obj.table_exists('logs'): \n updated_data = operation+'=\"'+value+'\"'\n now = datetime.now()\n ID = datetime.timestamp(now)\n record_date = int(datetime.timestamp(now))\n updated_data += ',\"RecordDate\"=\"'+str(record_date)+'\"'\n sqlite_obj.update_data(updated_data,'Usecase=\"'+Usecase+'\"','logs')\n except Exception as e:\n print(e)\n pass \ndef SendTelemetryUpdate(sync_time):\n file_path = os.path.join(DATA_DIR, 'sqlite')\n sqlite_obj = sqlite_db(file_path, 'telemetry.db') \n if sqlite_obj.table_exists('logs'):\n ddata = sqlite_obj.read_data(\"logs\",\"RecordDate >= '\"+str(sync_time)+\"'\")\n #print(ddata)\n keys = sqlite_obj.column_names('logs')\n for data in ddata:\n now = datetime.now()\n ID = datetime.timestamp(now)\n item = {}\n item['ID'] = str(int(ID))\n item['RecordID'] = data[ keys.index('ID')]\n item['RecordDate'] = data[ keys.index('RecordDate')]\n item['Usecase'] = data[ keys.index('Usecase')]\n item['Operation'] = data[ keys.index('Operation')]\n item['User'] = data[ keys.index('User')]\n item['HostName'] = data[ keys.index('HostName')]\n item['MACAddress'] = data[ keys.index('MACAddress')]\n item['Algorithms'] = data[ keys.index('Algorithms')]\n item['ProblemType'] = data[ keys.index('ProblemType')]\n item['EDA'] = data[ keys.index('EDA')]\n item['Prediction'] = data[ keys.index('Prediction')]\n item['MLaC'] = data[ keys.index('MLaC')]\n item['Drift'] = data[ keys.index('Drift')]\n item['TrustedAI'] = data[ keys.index('TrustedAI')]\n url = 'https://l5m119j6v9.execute-api.ap-south-1.amazonaws.com/default/aion_telemetry'\n record = {}\n record['TableName'] = 'AION_LOGS'\n record['Item'] = item\n record = json.dumps(record)\n #print(record)\n try:\n response = requests.post(url, data=record,headers={\"x-api-key\":\"Obzt8ijfOT3dgBYma9JCt1tE3W6tzHaV8rVuQdMK\",\"Content-Type\":\"application/json\",})\n except Exception as e:\n print(e)\n \ndef telemetry_data(operation,Usecase,data):\n now = datetime.now()\n ID = datetime.timestamp(now)\n record_date = now.strftime(\"%y-%m-%d %H:%M:%S\")\n computername = socket.getfqdn()\n macaddress = getmac.get_mac_address()\n try:\n user = os.getlogin()\n except:\n user = 'NA' \n item = {}\n item['ID'] = str(int(ID))\n item['record_date'] = record_date\n item['UseCase'] = Usecase\n item['operation'] = operation\n item['remarks'] = data\n item['user'] = str(user)\n item['hostname'] = computername\n item['macaddress'] = macaddress\n url = 'https://l5m119j6v9.execute-api.ap-south-1.amazonaws.com/default/aion_telemetry'\n record = {}\n record['TableName'] = 'AION_OPERATION'\n record['Item'] = item\n record = json.dumps(record)\n \n try:\n response = requests.post(url, data=record,headers={\"x-api-key\":\"Obzt8ijfOT3dgBYma9JCt1tE3W6tzHaV8rVuQdMK\",\"Content-Type\":\"application/json\",})\n check_telemetry_file()\n except Exception as inst:\n \n filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),'telemetry.txt') \n f=open(filename, \"a+\")\n f.write(record+'\\\\n')\n f.close()\n \ndef check_telemetry_file():\n file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'telemetry.txt')\n if(os.path.isfile(file_path)):\n f = open(file_path, 'r')\n url = 'https://l5m119j6v9.execute-api.ap-south-1.amazonaws.com/default/aion_telemetry'\n file_content = f.read()\n f.close()\n matched_lines = file_content.split('\\\\n')\n write_lines = []\n for record in matched_lines:\n try:\n response = requests.post(url, data=record,headers={\"x-api-key\":\"Obzt8ijfOT3dgBYma9JCt1tE3W6tzHaV8rVuQdMK\",\"Content-Type\":\"application/json\",})\n except:\n write_lines.append(record)\n f = open(file_path, \"a\")\n f.seek(0)\n f.truncate()\n for record in write_lines:\n f.write(record+'\\\\n')\n f.close()\n \n \n else:\n return True '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport time\nimport subprocess\nimport sys\nimport json\nimport pandas as pd\ndef getDataSetRecordsCount(datalocation):\n\ttry:\n\t\trecords = 0\n\t\tif os.path.isfile(datalocation): \n\t\t\tfor chunk in pd.read_csv(datalocation, chunksize=20000):\n\t\t\t\trecords = records+len(chunk) \n\t\tif records == 0:\n\t\t\trecords = 'NA' \n\texcept Exception as e:\n\t\tprint(e) \n\t\trecords = 'NA'\n\treturn records \ndef get_train_model_details(deploy_location,request):\n\tupdatedConfigFile = request.session['config_json']\n\tf = open(updatedConfigFile, \"r\")\n\tconfigSettings = f.read()\n\tf.close()\n\tusename = request.session['usecaseid'].replace(\" \", \"_\")\n\toutputfile = os.path.join(deploy_location,usename,str(request.session['ModelVersion']),'etc','output.json')\t\n\tif os.path.isfile(outputfile):\n\t\tf1 = open(outputfile, \"r+\", encoding=\"utf-8\")\n\t\toutputStr = f1.read()\n\t\tf1.close()\t\n\t\tresultJsonObj = json.loads(outputStr)\n\t\ttrainingStatus = resultJsonObj['status']\n\t\tif trainingStatus.lower() == 'success':\n\t\t\tdetails = \tresultJsonObj['data']\n\t\t\tmodelType = details['ModelType']\n\t\t\tbestModel = details['BestModel']\n\t\t\treturn trainingStatus,modelType,bestModel\n\t\telse:\n\t\t\treturn trainingStatus,'NA','NA'\n\telse:\n\t\treturn 'Not Trained','NA','NA' '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport json\nimport os\nimport rsa\nimport boto3 #usnish\nimport pandas as pd\nimport time\ndef add_new_GCSBucket(request):\n\ttry:\n\t\tfile_path = os.path.abspath(", "instruction": "", "output": "" }, { "input": "os.path.join(os.path.dirname(__file__),'..','..','config','gcsbuckets.conf'))\n\t\twith open(file_path, 'r') as f:\n\t\t\tdata = json.load(f)\n\t\tf.close()\t\t\n\t\tif data == '':\n\t\t\tdata = []\t\t\n\texcept:\n\t\tdata = []\n\tprint(request.POST[\"aionreferencename\"])\t\t\n\tprint(request.POST[\"serviceaccountkey\"])\n\tprint(request.POST[\"bucketname\"])\n\tif request.POST[\"aionreferencename\"] =='' or request.POST[\"serviceaccountkey\"] == '' or request.POST[\"bucketname\"] == '' :\n\t\t\n\t\treturn 'error'\n\tnewdata = {}\n\n \n\tnewdata['Name'] = request.POST[\"aionreferencename\"]\n\tnewdata['GCSServiceAccountKey'] = request.POST[\"serviceaccountkey\"]\n\tnewdata['GCSbucketname'] = request.POST[\"bucketname\"]\n\tdata.append(newdata)\n\twith open(file_path, 'w') as f:\n\t\tjson.dump(data, f)\n\tf.close()\n\treturn 'success'\n\ndef get_gcs_bucket():\n\ttry:\n\t\tfile_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','gcsbuckets.conf'))\n\t\twith open(file_path, 'r') as f:\n\t\t\tdata = json.load(f)\n\texcept:\n\t\tdata = []\n\treturn data\ndef read_gcs_bucket(name,filename,DATA_FILE_PATH):\n\ttry:\n\t\tfile_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','config','gcsbuckets.conf'))\n\t\twith open(file_path, 'r') as f:\n\t\t\tdata = json.load(f)\n\texcept:\n\t\tdata = []\n\tfound = False\n\tprint(data)\n\tfor x in data:\n\t\tif x['Name'] == name:\n\t\t\tGCSServiceAccountKey = x['GCSServiceAccountKey']\n\t\t\tGCSbucketname = x['GCSbucketname']\n\t\t\tfound = True\n\t\t\tbreak\t\t\n\tprint(found)\n\tprint(name)\n\ttry:\n\t\tif found:\n\t\t\timport io \n\t\t\tfrom google.cloud import storage\t\n\t\t\tstorage_client = storage.Client.from_service_account_json(GCSServiceAccountKey)\n\t\t\tprint(GCSServiceAccountKey)\n\t\t\tprint(GCSbucketname)\n\t\t\tbucket = storage_client.get_bucket(GCSbucketname)\n\t\t\tblob = bucket.blob(filename)\t\t\n\t\t\tdata = blob.download_as_string()\n\t\t\tdf = pd.read_csv(io.BytesIO(data), encoding = 'utf-8', sep = ',',encoding_errors= 'replace')\n\t\t\treturn 'Success',df\n\texcept Exception as e:\n\t\tprint(e)\n\treturn 'Error', pd.DataFrame() '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport json\nimport os\nimport pandas as pd\nimport numpy as np\nimport subprocess\nimport sys\nimport re\nimport plotly.graph_objects as go\nimport plotly.figure_factory as ff\ndef global_explain(request):\n try:\t\n selected_use_case = request.session['UseCaseName']\n ModelVersion = request.session['ModelVersion']\n ModelStatus = request.session['ModelStatus']\n updatedConfigFile = request.session['config_json']\n f = open(updatedConfigFile, \"r\")\n configSettings = f.read()\n f.close()\t\n configSettingsJson = json.loads(configSettings)\n problemType = 'classification'\n for key in configSettingsJson['basic']['analysisType']:\n if configSettingsJson['basic']['analysisType'][key] == 'True':\n problemType = key\n break\n if problemType.lower() != 'classification' and problemType.lower() != 'regression':\n 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'\n \n displaypath = os.path.join( request.session['deploypath'],'etc','display.json')\n with open(displaypath) as file:\n config = json.load(file)\n file.close()\n inputFeatures = configSettingsJson['basic']['trainingFeatures']\n targetFeature = configSettingsJson['basic']['targetFeature']\n inputFeatures = inputFeatures.split(',')\n if targetFeature in inputFeatures:\n inputFeatures.remove(targetFeature)\n \n dataFilePath = str(configSettingsJson['basic']['dataLocation'])\n from utils.file_ops import read_df_compressed\n status,df = read_df_compressed(config['postprocessedData'],encoding='utf8',nrows=10)\n #print(df) \n df.rename(columns=lambda x: x.strip(), inplace=True) \n df = df[inputFeatures]\n #print(df)\n singleInstanceData = df.loc[5, inputFeatures]\n inputFieldsDict = singleInstanceData.to_dict()\n inputFields = []\n inputFields.append(inputFieldsDict)\n \n if 'nrows' in config:\n nrows = config['nrows']\n else:\n nrows = 'Not Available'\n \n if 'ncols' in config:\n ncols = config['ncols']\n else:\n ncols = 'Not Available'\n \n if 'targetFeature' in config:\n targetFeature = config['targetFeature']\n else:\n targetFeature = ''\n\n labelMaps = config['labelMaps']\n modelfeatures = config['modelFeatures']\n mfcount = len(modelfeatures)\n df_proprocessed = pd.read_csv(dataFilePath)\n if 'targetFeature' != '':\n target_classes = df_proprocessed[targetFeature].unique()\n numberofclasses = len(target_classes)\n else:\n target_classes = []\n numberofclasses = 'Not Available' \n dataPoints = df_proprocessed.shape[0]\t\n df_proprocessed = df_proprocessed.head(5)\n df_proprocessed = df_proprocessed.to_json(orient=\"records\")\n df_proprocessed = json.loads(df_proprocessed)\n expainableAIPath = os.path.join(request.session['deploypath'],'aion_xai.py') \n outputStr = subprocess.check_output([sys.executable,expainableAIPath,'global']) \t\t\n outputStr = outputStr.decode('utf-8')\n outputStr = re.search(r'aion_ai_explanation:(.*)',str(outputStr), re.IGNORECASE).group(1)\n outputStr = outputStr.strip()\n ale_json = json.loads(str(outputStr))\n ale_json = ale_json['data']\n ale_view = ale_json['data']\n sentences = ale_json['sentences']\n scoreMessage = ''\t\n feature_importance = ale_json['feature_importance']\n dfimp = pd.DataFrame.from_dict(feature_importance)\n dfimp = dfimp.sort_values(by=['values'],ascending=False).reset_index()\n yaxis_data = dfimp['values'].tolist()\n xaxis_data = dfimp['labels'].tolist()\n cfig = go.Figure()\n cfig.add_trace(go.Bar(x=xaxis_data,y=yaxis_data,name='Feature Importance'))\t\t\t\n cfig.update_layout(barmode='stack',xaxis_title='Features')\t\t\t\n bargraph = cfig.to_html(full_html=False, default_height=450,default_width=1000)\n dftoprecords = dfimp.head(2)\n topTwoFeatures = dfimp['labels'].tolist()\n topFeaturesMsg = []\n for i in range(0,len(dfimp)):\n value = round(dfimp.loc[i, \"values\"],2)*100\n value = round(value,2)\n tvalue = str(dfimp.loc[i, \"labels\"])+' contributing to '+ str(value)+'%'\n topFeaturesMsg.append(tvalue)\n most_influencedfeature = ale_json['most_influencedfeature']\n interceppoint = ale_json['interceptionpoint']\n anchorjson = ale_json['anchorjson']\t\t\n 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\n except Exception as Inst:\n print(Inst)\t\n 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' import json\nimport os\nimport sys\nimport re\nimport numpy as np\n\n\ndef check_unsupported_col(config): #bugId14444\n unsupported_chars = '[]<>#{}@&'\n try:\n featureList = config['basic']['featureList']\n return any([x in y for x in unsupported_chars for y in featureList])\n except Exception as e:\n print(str(e))\n return False\n\ndef check_granularity(configSettingsJson,datapath=None):\n try:\n from AION.appbe.utils import get_true_option\n import pandas as pd\n from pathlib import Path\n 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}\n if not get_true_option(configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']['aggregation']['type']):\n return ''\n if isinstance( configSettingsJson['basic']['dateTimeFeature'], list):\n datetime_feature = configSettingsJson['basic']['dateTimeFeature'][0]\n else:\n datetime_feature = configSettingsJson['basic']['dateTimeFeature']\n if get_true_option(configSettingsJson['basic']['analysisType']) == 'timeSeriesForecasting' and datetime_feature:\n if not datapath:\n datapath = configSettingsJson['basic']['dataLocation']\n if Path( datapath).exists():\n df = pd.read_csv(datapath, nrows=2)\n datetime = pd.to_datetime(df[ datetime_feature])\n if len(datetime) > 1:\n source_time_delta = (datetime[1] - datetime[0]).total_seconds()\n granularity_unit = get_true_option(configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']['aggregation']['granularity']['unit'])\n size = int(configSettingsJson['basic']['preprocessing']['timeSeriesForecasting']['aggregation']['granularity']['size'])\n target_time_delta = size * seconds_per_unit[granularity_unit]\n amplify = int(source_time_delta / target_time_delta)\n if amplify > 20:\n return f'Current Granularity setting will amplify the data approx {amplify} times. Depending on your system configuration, this may cause Memory error'\n \n return ''\n except Exception as e:\n return ''\n\ndef getStatusCount(matched_lines,total_steps):\n stepsdone = 0\n leaner = True\n #print(matched_lines)\n for line in matched_lines:\n if 'AION feature transformation completed' in line:\n stepsdone = stepsdone + 1\n elif 'AION feature engineering completed' in line:\n stepsdone = stepsdone + 1\n elif 'AION Association Rule completed' in line:\n stepsdone = stepsdone + 1\n elif 'AION Image Classification completed' in line:\n stepsdone = stepsdone + 1 \n elif 'AION Association Rule completed' in line:\n stepsdone = stepsdone + 1\n elif 'AION State Transition completed' in line:\n stepsdone = stepsdone + 1\n elif 'AION SurvivalAnalysis completed' in line:\n stepsdone = stepsdone + 1\n elif 'AION Recommender completed' in line:\n stepsdone = stepsdone + 1\n elif 'AION Gluon Stop' in line:\n stepsdone = stepsdone + 1\n elif 'AION Evaluation Stop' in line:\n stepsdone = stepsdone + 1\n elif 'AION Object Detection completed' in line:\n stepsdone = stepsdone + 1\n elif ('training completed' in line) and leaner:\n stepsdone = stepsdone + 1\n leaner = False\n elif 'Prediction Service completed' in line:\n stepsdone = stepsdone + 1\n elif 'AION TimeSeries Forecasting started' in line: #task 11997\n stepsdone = stepsdone + 1 \n elif 'Distributed Learning Completed' in line:\n stepsdone = stepsdone + 4 \n elif 'AION Batch Deployment completed' in line:\n stepsdone = stepsdone + 2 \n match_lines = []\n for line in matched_lines:\n count = len(line)-len(line.lstrip())\n uline = line.split('...')\n uline = uline[1]\n if count == 0:\n uline = '|... '+uline+''\n elif count == 8 or count == 1:\n uline = ' |... '+uline+''\n elif count == 16 or count == 2:\n uline = ' |... '+uline+''\n elif count == 32 or count == 3:\n uline = ' |... '+uline+'' \n else:\n uline = line \n match_lines.append(uline) \n stepline = 'Stage: ' + str(stepsdone) + '/' + str(total_steps) + ' Complete'\n match_lines.insert(0, stepline)\n #print(match_lines)\n output = \"\\\\n\".join([status_text for status_text in match_lines])\n output = \"
{}
\".format(output)\n #print(output)\n return(output)\n\ndef calculate_total_interations(config):\n try:\n noOfIterations = 0\n problemtypes = config['basic']['analysisType'] \n problem_type = \"\"\n for key in problemtypes:\n if config['basic']['analysisType'][key] == 'True':\n problem_type = key\n break\n if problem_type.lower", "instruction": "", "output": "" }, { "input": "() in ['classification','regression']: \n algorithms = config['basic']['algorithms'][problem_type]\n for key in algorithms:\n if config['basic']['algorithms'][problem_type][key] == 'True':\n 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']:\n if problem_type.lower() == 'classification':\n configparam = config['advance']['mllearner_config']['modelParams']['classifierModelParams'][key]\n else:\n configparam = config['advance']['mllearner_config']['modelParams']['regressorModelParams'][key]\n param = paramDefine(configparam,config['advance']['mllearner_config']['optimizationMethod'])\n interationsum = 1\n for x in param.values():\n interationsum = interationsum*len(x)\n if config['advance']['mllearner_config']['optimizationMethod'].lower() == 'random':\n if interationsum > int(config['advance']['mllearner_config']['optimizationHyperParameter']['iterations']):\n interationsum = int(config['advance']['mllearner_config']['optimizationHyperParameter']['iterations'])\n noOfIterations = noOfIterations+interationsum\n else:\n if key in ['Neural Network','Convolutional Neural Network (1D)','Recurrent Neural Network','Recurrent Neural Network (GRU)','Recurrent Neural Network (LSTM)']:\n if problem_type.lower() == 'classification':\n configparam = config['advance']['dllearner_config']['modelParams']['classifierModelParams'][key]\n else:\n configparam = config['advance']['dllearner_config']['modelParams']['regressorModelParams'][key]\n interationsum = 1\n for j in list(configparam.keys()):\n if isinstance(configparam[j],(list,dict,tuple,str)):\n x = configparam[j].split(',')\n interationsum = interationsum*len(x)\n noOfIterations = noOfIterations+interationsum\n elif key in ['Deep Q Network','Dueling Deep Q Network']:\n if problem_type.lower() == 'classification': \n configparam = config['advance']['rllearner_config']['modelParams']['classifierModelParams'][key] \n interationsum = 1\n for j in list(configparam.keys()):\n if isinstance(configparam[j],(list,dict,tuple,str)):\n x = configparam[j].split(',')\n interationsum = interationsum*len(x)\n noOfIterations = noOfIterations+interationsum \n elif problem_type.lower() in ['llmfinetuning']: \n algorithms = config['basic']['algorithms'][problem_type]\n for key in algorithms:\n if config['basic']['algorithms'][problem_type][key] == 'True':\n noOfIterations = configparam = config['advance']['llmFineTuning']['modelParams'][key]['epochs']\n break\n else:\n noOfIterations= 'NA'\n except Exception as e:\n print(e)\n noOfIterations = 'NA'\n pass\n return(noOfIterations)\ndef paramDefine(paramSpace, method):\n\t\tparamDict = {}\n\t\tfor j in list(paramSpace.keys()):\n\t\t\tinp = paramSpace[j]\n\t\t\ttry:\n\t\t\t\tisLog = False\n\t\t\t\tisLin = False\n\t\t\t\tisRan = False\n\t\t\t\tisList = False\n\t\t\t\tisString = False\n\t\t\t\ttry:\n\t\t\t\t\t# check if functions are given as input and reassign paramspace\n\t\t\t\t\tv = paramSpace[j]\n\t\t\t\t\tif 'logspace' in paramSpace[j]:\n\t\t\t\t\t\tparamSpace[j] = v[v.find(\"(\") + 1:v.find(\")\")].replace(\" \", \"\")\n\t\t\t\t\t\tisLog = True\n\t\t\t\t\telif 'linspace' in paramSpace[j]:\n\t\t\t\t\t\tparamSpace[j] = v[v.find(\"(\") + 1:v.find(\")\")].replace(\" \", \"\")\n\t\t\t\t\t\tisLin = True\n\t\t\t\t\telif 'range' in paramSpace[j]:\n\t\t\t\t\t\tparamSpace[j] = v[v.find(\"(\") + 1:v.find(\")\")].replace(\" \", \"\")\n\t\t\t\t\t\tisRan = True\n\t\t\t\t\telif 'list' in paramSpace[j]:\n\t\t\t\t\t\tparamSpace[j] = v[v.find(\"(\") + 1:v.find(\")\")].replace(\" \", \"\")\n\t\t\t\t\t\tisList = True\n\t\t\t\t\telif '[' and ']' in paramSpace[j]:\n\t\t\t\t\t\tparamSpace[j] = v.split('[')[1].split(']')[0].replace(\" \", \"\")\n\t\t\t\t\t\tisList = True\n\t\t\t\t\tx = paramSpace[j].split(',')\n\t\t\t\texcept:\n\t\t\t\t\tx = paramSpace[j]\n\t\t\t\tstr_arg = paramSpace[j]\n\n\t\t\t\t# check if arguments are string\n\t\t\t\ttry:\n\t\t\t\t\ttest = eval(x[0])\n\t\t\t\texcept:\n\t\t\t\t\tisString = True\n\n\t\t\t\tif isString:\n\t\t\t\t\tparamDict.update({j: hp.choice(j, x)} if method == 'bayesopt' else {j: x})\n\t\t\t\telse:\n\t\t\t\t\tres = eval(str_arg)\n\t\t\t\t\tif isLin:\n\t\t\t\t\t\ty = eval('np.linspace' + str(res))\n\t\t\t\t\t\tparamDict.update({j: hp.uniform(j, eval(x[0]), eval(x[1]))} if method == 'bayesopt' else {j: y})\n\t\t\t\t\telif isLog:\n\t\t\t\t\t\ty = eval('np.logspace' + str(res))\n\t\t\t\t\t\tparamDict.update(\n\t\t\t\t\t\t\t{j: hp.uniform(j, 10 ** eval(x[0]), 10 ** eval(x[1]))} if method == 'bayesopt' else {j: y})\n\t\t\t\t\telif isRan:\n\t\t\t\t\t\ty = eval('np.arange' + str(res))\n\t\t\t\t\t\tparamDict.update({j: hp.choice(j, y)} if method == 'bayesopt' else {j: y})\n\t\t\t\t\t# check datatype of argument\n\t\t\t\t\telif isinstance(eval(x[0]), bool):\n\t\t\t\t\t\ty = list(map(lambda i: eval(i), x))\n\t\t\t\t\t\tparamDict.update({j: hp.choice(j, eval(str(y)))} if method == 'bayesopt' else {j: y})\n\t\t\t\t\telif isinstance(eval(x[0]), float):\n\t\t\t\t\t\tres = eval(str_arg)\n\t\t\t\t\t\tif len(str_arg.split(',')) == 3 and not isList:\n\t\t\t\t\t\t\ty = eval('np.linspace' + str(res))\n\t\t\t\t\t\t\t#print(y)\n\t\t\t\t\t\t\tparamDict.update({j: hp.uniform(j, eval(x[0]), eval(x[1]))} if method == 'bayesopt' else {j: y})\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ty = list(res) if isinstance(res, tuple) else [res]\n\t\t\t\t\t\t\tparamDict.update({j: hp.choice(j, y)} if method == 'bayesopt' else {j: y})\n\t\t\t\t\telse:\n\t\t\t\t\t\tres = eval(str_arg)\n\t\t\t\t\t\tif len(str_arg.split(',')) == 3 and not isList:\n\t\t\t\t\t\t\ty = eval('np.linspace' +str(res)) if eval(x[2]) >= eval(x[1]) else eval('np.arange'+str(res))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ty = list(res) if isinstance(res, tuple) else [res]\n\t\t\t\t\t\tparamDict.update({j: hp.choice(j, y)} if method == 'bayesopt' else {j: y})\n\t\t\texcept Exception as inst:\n\t\t\t\tprint(inst)\n\t\treturn paramDict\n \ndef calculate_total_activities(config):\n req_step = 0\n problemtypes = config['basic']['analysisType'] \n problem_type = \"\"\n for key in problemtypes:\n if config['basic']['analysisType'][key] == 'True':\n problem_type = key\n break\n Modelproblem = problem_type\n if Modelproblem.lower() in ['classification','regression','clustering','anomalydetection','topicmodelling']: \n req_step = req_step+4\n if Modelproblem.lower() in ['timeseriesforecasting','imageclassification','objectdetection','multilabelprediction','similarityidentification','contextualsearch']: #task 11997\n req_step = req_step+2 \n if Modelproblem.lower() in ['survivalanalysis']:\n req_step = req_step+3 \n if Modelproblem.lower() in ['recommendersystem']: \n if config['basic']['algorithms']['recommenderSystem']['ItemRating'] == 'True':\n req_step = req_step+3 \n if config['basic']['algorithms']['recommenderSystem']['AssociationRules-Apriori'] == 'True':\n req_step = req_step+1\n if Modelproblem.lower() in ['statetransition']:\n req_step = req_step+1\n return (req_step)\ndef getModelStatus(Existusecases,modelid):\n model = Existusecases.objects.get(id=modelid)\n return(model.Status)\t\ndef changeModelStatus(Existusecases,modelid,status,problemType,deployPath):\n model = Existusecases.objects.get(id=modelid)\n model.Status = status\n model.ProblemType = problemType\n model.DeployPath = deployPath\n model.save()\ndef checkversionrunningstatus(modelid,usecasedetails,Existusecases):\n modelx = Existusecases.objects.get(id=modelid)\n ConfigPath = str(modelx.ConfigPath)\n status = 'Running'\n try:\n if os.path.exists(ConfigPath):\n with open(ConfigPath, 'r') as json_file:\n data = json.load(json_file)\n json_file.close()\n deployPath = str(data['basic']['deployLocation'])\n modelName = data['basic']['modelName']\n modelVersion = data['basic']['modelVersion'] \n modelName = modelName.replace(\" \", \"_\")\n logfile = os.path.join(deployPath,modelName,str(modelVersion),'log','model_training_logs.log')\n print(logfile)\n if os.path.exists(logfile):\n with open(logfile) as f:\n contents = f.read()\n f.close()\n contents = re.search(r'aion_learner_status:(.*)', str(contents), re.IGNORECASE).group(1)\n contents = contents.strip()\n print(contents)\n if contents != '':\n resultJsonObj = json.loads(contents)\n odataFile = str(modelx.TrainOuputLocation)\n with open(odataFile, 'w') as json_file:\n json.dump(resultJsonObj, json_file)\n json_file.close()\n modelx.Status = resultJsonObj['status']\n status = modelx.Status\n if resultJsonObj['status'] == 'SUCCESS': \n modelx.DeployPath = str(resultJsonObj['data']['deployLocation'])\n if resultJsonObj['data']['ModelType'] in ['clustering','anomalydetection']:\n modelx.ProblemType = 'unsupervised'\n else:\n modelx.ProblemType = 'supervised'\n modelx.save() \n except Exception as e:\n pass\n return status\ndef updateLLM_Model_training_logs(deployPath,modelName,modelVersion,model,configPath):\n from appbe.prediction import get_instance\n hypervisor,instanceid,region,image = get_instance(modelName+'_'+str(modelVersion))\n from llm.llm_tuning import llm_logs\n cloudconfig = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','config','compute_conf.json'))\n llm_logs(configPath,cloudconfig,instanceid,hypervisor,model)\n \ndef checkModelUnderTraining(request,usecasedetails,Existusecases):\n try:\n models = Existusecases.objects.filter(Status='Running')\n for model in models:\n ConfigPath = str(model.ConfigPath)\n try:\n if os.path.exists(ConfigPath):\n with open(ConfigPath, 'r') as json_file:\n data = json.load(json_file)\n json_file.close()\n deployPath = str(data['basic']['deployLocation'])\n modelName = data['basic']['modelName']\n modelVersion = data['basic']['modelVersion'] \n modelName = modelName.replace(\" \", \"_\")\n if data['basic']['analysisType']['llmFineTuning'] == 'True':\n mlmodels =''\n algorihtms = data['basic']['algorithms']['llmFineTuning']\n for k in algorihtms.keys():\n if data['basic']['algorithms']['llmFineTuning'][k] == 'True':\n if mlmodels != '':\n mlmodels += ', ' \n mlmodels += k\n \n updateLLM_Model_training_logs(deployPath,modelName,modelVersion,mlmodels,ConfigPath)\n logfile = os.path.join(deployPath,modelName,str(modelVersion),'log','model_training_logs.log')\n if os.path.exists(logfile):\n with open(logfile,encoding=\"utf-8\") as f:\n contents = f.read()\n f.close()\n contents = re.search(r'aion_learner_status:(.*)', str(contents), re.IGNORECASE).group(1)\n contents = contents.strip()\n if contents != '':\n resultJsonObj = json.loads(contents)\n odataFile = str(model.TrainOuputLocation)\n with open(odataFile, 'w') as json_file:\n json.dump(resultJsonObj, json_file)\n json_file.close()\n modelx = Existusecases.objects.get(id=model.id)\n modelx.Status = resultJsonObj['status']\n if resultJsonObj['status'] == 'SUCCESS':\n modelx.DeployPath = str(resultJsonObj['data']['deployLocation'])\n if resultJsonObj['data']['ModelType'] in ['clustering','anomalydetection']:\n modelx.ProblemType = 'unsupervised'\n else:\n modelx.ProblemType = 'supervised'\n modelx.save()\n except Exception as e:\n print(ConfigPath)\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb", "instruction": "", "output": "" }, { "input": ".tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n pass\n except Exception as e:\n print(e)\n from typing import Union\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.neighbors import BallTree\n\n\ndef hopkins(data_frame: Union[np.ndarray, pd.DataFrame], sampling_size: int) -> float:\n if type(data_frame) == np.ndarray:\n data_frame = pd.DataFrame(data_frame)\n\n data_frame_sample = sample_observation_from_dataset(data_frame, sampling_size)\n\n sample_distances_to_nearest_neighbours = get_distance_sample_to_nearest_neighbours(\n data_frame, data_frame_sample\n )\n\n uniformly_selected_observations_df = simulate_df_with_same_variation(\n data_frame, sampling_size\n )\n\n df_distances_to_nearest_neighbours = get_nearest_sample(\n data_frame, uniformly_selected_observations_df\n )\n\n x = sum(sample_distances_to_nearest_neighbours)\n y = sum(df_distances_to_nearest_neighbours)\n\n if x + y == 0:\n raise Exception(\"The denominator of the hopkins statistics is null\")\n\n return x / (x + y)[0]\n\n\ndef get_nearest_sample(df: pd.DataFrame, uniformly_selected_observations: pd.DataFrame):\n tree = BallTree(df, leaf_size=2)\n dist, _ = tree.query(uniformly_selected_observations, k=1)\n uniformly_df_distances_to_nearest_neighbours = dist\n return uniformly_df_distances_to_nearest_neighbours\n\n\ndef simulate_df_with_same_variation(\n df: pd.DataFrame, sampling_size: int\n) -> pd.DataFrame:\n max_data_frame = df.max()\n min_data_frame = df.min()\n uniformly_selected_values_0 = np.random.uniform(\n min_data_frame[0], max_data_frame[0], sampling_size\n )\n uniformly_selected_values_1 = np.random.uniform(\n min_data_frame[1], max_data_frame[1], sampling_size\n )\n uniformly_selected_observations = np.column_stack(\n (uniformly_selected_values_0, uniformly_selected_values_1)\n )\n if len(max_data_frame) >= 2:\n for i in range(2, len(max_data_frame)):\n uniformly_selected_values_i = np.random.uniform(\n min_data_frame[i], max_data_frame[i], sampling_size\n )\n to_stack = (uniformly_selected_observations, uniformly_selected_values_i)\n uniformly_selected_observations = np.column_stack(to_stack)\n uniformly_selected_observations_df = pd.DataFrame(uniformly_selected_observations)\n return uniformly_selected_observations_df\n\n\ndef get_distance_sample_to_nearest_neighbours(df: pd.DataFrame, data_frame_sample):\n tree = BallTree(df, leaf_size=2)\n dist, _ = tree.query(data_frame_sample, k=2)\n data_frame_sample_distances_to_nearest_neighbours = dist[:, 1]\n return data_frame_sample_distances_to_nearest_neighbours\n\n\ndef sample_observation_from_dataset(df, sampling_size: int):\n if sampling_size > df.shape[0]:\n raise Exception(\"The number of sample of sample is bigger than the shape of D\")\n data_frame_sample = df.sample(n=sampling_size)\n return data_frame_sample\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\n\n# def exploratorory_help():\n#\n#\n#\n# return (data_overview_tip, feature_importance_tip, correlation_analysis_tip, exploratory_analysis_tip, data_deep_drive_tip, drift_tip)\n\ndrift_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.'\n\ndata_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.'\n\ntimeseries_analysis_tip = \"Time Series Analysis provides information about the stationarity and seasonality of each of the features in the ingested data.\"\n\nfeature_importance_tip = 'Feature Importance provides a features and grades the features on a scale of relative importance'\n\ncorrelation_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.'\n\nexploratory_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.'\n\ndata_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.'\n\npair_graph_tip = 'It is used to present the correlations between two selected features.'\n\nfair_metrics_tip = 'It provides interface to detect the bias in data associated with a sensitive or protected attribute and used for training.'\n\nhopkins_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.']\n\nbasic_help={'RowFiltering':'You can easily filter rows based on whether the column match a condition or not'}\nadvance_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\"}',\n'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',\n'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'} from langkit import textstat\nfrom whylogs.experimental.core.udf_schema import udf_schema\nimport pandas as pd\nimport whylogs as why\nfrom langkit import light_metrics\nfrom whylogs.experimental.core.udf_schema import udf_schema\nfrom whylogs.experimental.core.udf_schema import register_dataset_udf\nimport whylogs as why\nimport json\nfrom sentence_transformers import SentenceTransformer, util\nfrom langkit import lang_config, response_column\n\n\ndef evaluate_prompt_metrics(prompt_msg: any):\n \"\"\" Evaluate prompt only information.\"\"\"\n text_schema = udf_schema()\n llm_schema = light_metrics.init()\n df = pd.DataFrame({\n \"prompt\": [\n prompt_msg\n ]})\n results = why.log(df, schema=udf_schema()) # .profile()\n view = results.view()\n\n automated_readability_index_prompt = view.get_column(\"prompt.automated_readability_index\").to_summary_dict()\n automated_readability_index_prompt_mean = automated_readability_index_prompt['distribution/mean']\n arip_m = lambda x:1 if x < 1 else (14 if x > 14 else x", "instruction": "", "output": "" }, { "input": ")\n automated_readability_index_prompt_mean = arip_m(automated_readability_index_prompt_mean)\n automated_readability_index_prompt_value = get_readability_index_range_value(automated_readability_index_prompt_mean)\n\n flesch_reading_ease_prompt = view.get_column(\"prompt.flesch_reading_ease\").to_summary_dict()\n flesch_reading_ease_prompt_mean = flesch_reading_ease_prompt['distribution/mean']\n frep_m = lambda x:1 if x < 1 else (100 if x > 100 else x)\n flesch_reading_ease_prompt_mean = frep_m(flesch_reading_ease_prompt_mean)\n flesch_reading_ease_prompt_value = get_flesch_reading_ease_prompt_value(flesch_reading_ease_prompt_mean)\n\n prompt_results = {'prompt_readability_score': str(automated_readability_index_prompt_mean),\n 'prompt_readability_value': automated_readability_index_prompt_value,\n\n 'prompt_reading_ease': str(flesch_reading_ease_prompt_mean),\n 'prompt_reading_ease_value': flesch_reading_ease_prompt_value}\n \n prompt_results_json = json.dumps(prompt_results, indent=4)\n return prompt_results_json,prompt_results\n\n\nmodel = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')\n@register_dataset_udf([\"prompt\", \"response\"], \"response.relevance_to_prompt\")\ndef similarity_MiniLM_L6_v2(text):\n x = text[\"prompt\"]\n y = text[\"response\"]\n embedding_1 = model.encode(x, convert_to_tensor=True)\n embedding_2 = model.encode(y, convert_to_tensor=True)\n similarity = util.pytorch_cos_sim(embedding_1, embedding_2)\n result = similarity.item()\n return result\n\n\ndef get_readability_index_range_value(readability_value):\n if readability_value <= 1:\n ## Grade level Kindergarden to fourth grade\n return \"Kindergarten\"\n elif 1 < readability_value <= 2:\n ## Grade level Kindergarden to fourth grade\n return \"First Grade\"\n elif 2 < readability_value <= 3:\n ## Grade level Fifth grade to Ninth grade\n return \"Second Grade\"\n elif 3 < readability_value <= 4:\n ## Grade level Fifth grade to Ninth grade\n return \"Third Grade\"\n elif 4 < readability_value <= 5:\n ## Grade level Fifth grade to Ninth grade\n return \"Fourth Grade\"\n elif 5 < readability_value <= 6:\n ## Grade level Fifth grade to Ninth grade\n return \"Fifth Grade\"\n elif 6 < readability_value <= 7:\n ## Grade level Fifth grade to Ninth grade\n return \"Sixth Grade\"\n elif 7 < readability_value <= 8:\n ## Grade level Fifth grade to Ninth grade\n return \"Seventh Grade\"\n elif 8 < readability_value <= 9:\n ## Grade level Fifth grade to Ninth grade\n return \"Eighth Grade\"\n elif 9 < readability_value <=10:\n ## Grade level Fifth grade to Ninth grade\n return \"Ninth Grade\"\n elif 10 < readability_value <=11:\n ## Grade level Fifth grade to Ninth grade\n return \"Tenth Grade\"\n elif 11 < readability_value <=12:\n ## Grade level Fifth grade to Ninth grade\n return \"Eleventh Grade\"\n elif 12 < readability_value <= 13:\n ## Grade level Fifth grade to Ninth grade\n return \"Twelfth Grade\"\n elif readability_value > 13:\n ## Grade level Fifth grade to Ninth grade\n return \"College Grade\"\n else:\n return \"College Grade\"\n\ndef get_flesch_reading_ease_prompt_value(readability_value):\n \"\"\" Get flesch readability score range approximation\"\"\"\n if readability_value <= 29:\n return \"Very Confusing\"\n elif 29 < readability_value <= 49:\n return \"Difficult\"\n elif 49 < readability_value <= 59:\n return \"Fairly Difficult\"\n elif 59 < readability_value <= 69:\n return \"Standard\"\n elif 69 < readability_value <= 79:\n return \"Fairly Easy\"\n elif 79 < readability_value <= 89:\n return \"Easy\"\n elif 89 < readability_value <= 100:\n return \"Very Easy\"\n else:\n return \"Very Easy\"\n\ndef get_relevence_to_response_value(similarity_score):\n \"\"\" To findout relevence to response results based on similarity score.\"\"\"\n if similarity_score <=0.3:\n return \"Low\"\n elif 0.3 < similarity_score <= 0.5:\n return \"Average\"\n elif 0.5 < similarity_score <= 0.8:\n return \"Good\"\n elif similarity_score > 0.8:\n return \"High\"\n\n\n\ndef evaluate_prompt_response_inputs (prompt_msg:any, response_msg:any)->str:\n \"\"\" Predict the text quality, text relevence for both prompt and response messages.\"\"\"\n df = pd.DataFrame({\n \"prompt\": [prompt_msg],\n \"response\": [response_msg]})\n results = why.log(df, schema=udf_schema())\n view = results.view()\n\n automated_readability_index_prompt = view.get_column(\"prompt.automated_readability_index\").to_summary_dict()\n automated_readability_index_prompt_mean = automated_readability_index_prompt['distribution/mean']\n arip_m = lambda x:1 if x < 1 else (14 if x > 14 else x)\n automated_readability_index_prompt_mean = arip_m(automated_readability_index_prompt_mean)\n automated_readability_index_prompt_value = get_readability_index_range_value(automated_readability_index_prompt_mean)\n\n flesch_reading_ease_prompt = view.get_column(\"prompt.flesch_reading_ease\").to_summary_dict()\n flesch_reading_ease_prompt_mean = flesch_reading_ease_prompt['distribution/mean']\n frep_m = lambda x:1 if x < 1 else (100 if x > 100 else x)\n flesch_reading_ease_prompt_mean = frep_m(flesch_reading_ease_prompt_mean)\n flesch_reading_ease_prompt_value = get_flesch_reading_ease_prompt_value(flesch_reading_ease_prompt_mean)\n\n automated_readability_index_response = view.get_column(\"response.automated_readability_index\").to_summary_dict()\n automated_readability_index_response_mean = automated_readability_index_response['distribution/mean']\n arir_m = lambda x:1 if x < 1 else (14 if x > 14 else x)\n automated_readability_index_response_mean = arir_m(automated_readability_index_response_mean)\n automated_readability_index_response_value = get_readability_index_range_value(automated_readability_index_response_mean)\n\n flesch_reading_ease_response = view.get_column(\"response.flesch_reading_ease\").to_summary_dict()\n flesch_reading_ease_response_mean = flesch_reading_ease_response['distribution/mean']\n frer_m = lambda x:1 if x < 1 else (100 if x > 100 else x)\n flesch_reading_ease_response_mean = frer_m(flesch_reading_ease_response_mean)\n flesch_reading_ease_response_value = get_flesch_reading_ease_prompt_value(flesch_reading_ease_response_mean)\n\n relevance_to_response = view.get_column(\"response.relevance_to_prompt\").to_summary_dict()\n relevance_to_response_mean = relevance_to_response['distribution/mean']\n r2r_m = lambda x:0 if x < 0 else (1 if x > 1 else x)\n relevance_to_response_mean = r2r_m(relevance_to_response_mean)\n relevance_to_response_value = get_relevence_to_response_value(relevance_to_response_mean)\n\n sentence_count_response = view.get_column(\"response.sentence_count\").to_summary_dict()\n sentence_count_response_mean = sentence_count_response['distribution/mean']\n word_count_response = view.get_column(\"response.lexicon_count\").to_summary_dict()\n word_count_response_mean = word_count_response['distribution/mean']\n prompt_response_results = {'prompt_readability_score': str(automated_readability_index_prompt_mean),\n 'prompt_readability_value': automated_readability_index_prompt_value,\n\n 'prompt_reading_ease': str(flesch_reading_ease_prompt_mean),\n 'prompt_reading_ease_value': flesch_reading_ease_prompt_value,\n\n 'response_readability': str(automated_readability_index_response_mean),\n 'response_readability_value': str(automated_readability_index_response_value),\n\n 'response_reading_ease': str(flesch_reading_ease_response_mean),\n 'response_reading_ease_value': str(flesch_reading_ease_response_value),\n\n 'response_sentence_count': str(sentence_count_response_mean),\n 'response_word_count_response': str(word_count_response_mean),\n\n 'relevance_to_response': str(relevance_to_response_mean),\n 'relevance_to_response_value': relevance_to_response_value\n }\n final_output_json = json.dumps(prompt_response_results, indent=4)\n return final_output_json,prompt_response_results\n\n\n\nif __name__ == \"__main__\":\n ##Test only prompt message information\n option = 'predict'\n if option == 'evaluate':\n 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., \u201cfew shots\u201d) 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\u2019s 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.\"\n prompt_res = evaluate_prompt_metrics(prompt_only_response_msg)\n elif option == 'predict':\n prompt_msg = \"What is AION?\"\n 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.\"\n evaluation_metrics_json = evaluate_prompt_response_inputs(prompt_msg,response_msg)\n print(\"evaluation_metrics_json: \\\\n\",evaluation_metrics_json) '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport logging\n\nfrom appbe.dataIngestion import getcommonfields\nfrom appbe.dataIngestion import getusercasestatus\nfrom appbe import service_url\nimport json\nfrom appbe.dataIngestion import delimitedsetting\nimport os,sys\nimport pandas as pd\nfrom django.http import HttpResponse\nimport time\n\nfrom appbe.dataPath import LOG_LOCATION\nfrom appbe.log_ut import logg\ndef get_instance_id(modelID):\n from appbe.sqliteUtility import sqlite_db\n from appbe.dataPath import DATA_DIR\n file_path = os.path.join(DATA_DIR,'sqlite')\n sqlite_obj = sqlite_db(file_path,'config.db')\n if sqlite_obj.table_exists(\"LLMTuning\"):\n data = sqlite_obj.get_data('LLMTuning','usecaseid',modelID)\n print(data)\n if len(data) > 0:\n return (data[3]+' instance '+data[2])\n else:\n return 'Instance ID not available'\n else:\n return 'Instance ID not available'\n\ndef get_instance(modelID):\n from appbe.sqliteUtility import sqlite_db\n from appbe.dataPath import DATA_DIR\n file_path = os.path.join(DATA_DIR,'sqlite')\n sqlite_obj = sqlite_db(file_path,'config.db')\n if sqlite_obj.table_exists(\"LL", "instruction": "", "output": "" }, { "input": "MTuning\"):\n data = sqlite_obj.get_data('LLMTuning','usecaseid',modelID)\n if len(data) > 0:\n return (data[3],data[2],data[5],data[6])\n else:\n return '','','',''\n else:\n return '','','',''\ndef getprompt(promptfeature,contextFeature,responseFeature,promptFriendlyName,responseFriendlyName,data):\n if contextFeature != '':\n promptData = data[promptfeature].replace('\\\\n','')\n inputData = data[contextFeature].replace('\\\\n','')\n prompt = (\n f\"Below is an {promptFriendlyName} that describes a task, paired with an Input that provides further context. \"\n f\"Write a {responseFriendlyName} that appropriately completes the request.\\\\n\\\\n\"\n f\"### {promptFriendlyName}:\\\\n{promptData}\\\\n\\\\n### Input:\\\\n{inputData}\\\\n\\\\n### {responseFriendlyName}:\\\\n\")\n \n else:\n promptData = data[promptfeature].replace('\\\\n','') \n prompt=(\n f\"Below is an {promptFriendlyName} that describes a task. \"\n f\"Write a {responseFriendlyName} that appropriately completes the request.\\\\n\\\\n\"\n f\"### {promptFriendlyName}:\\\\n{promptData}\\\\n\\\\n### {responseFriendlyName}:\\\\n\")\n return prompt \n \ndef getDataInstance(problem_type,mlmodels,configSettingsJson):\n log = logging.getLogger('log_ux')\n delimiters,textqualifier = delimitedsetting(configSettingsJson['basic']['fileSettings']['delimiters'],configSettingsJson['basic']['fileSettings']['textqualifier']) \n if problem_type == 'timeSeriesForecasting': #task 11997\n inputFieldsDict = {'noofforecasts': 10}\n elif problem_type == 'recommenderSystem' and mlmodels =='ItemRating':\n inputFieldsDict = {\"uid\": 1, \"iid\": 31, \"rating\": 0}\n elif problem_type == 'stateTransition': \n inputFeatures = configSettingsJson['basic']['trainingFeatures']\n targetFeature = configSettingsJson['basic']['targetFeature']\n inputFeaturesList = inputFeatures.split(',')\n inputFieldsDict = {inputFeatures:'session',targetFeature:'Activity'}\n else:\n inputFeatures = configSettingsJson['basic']['trainingFeatures']\n targetFeature = configSettingsJson['basic']['targetFeature']\n inputFeaturesList = inputFeatures.split(',')\n if targetFeature in inputFeaturesList:\n inputFeaturesList.remove(targetFeature)\n if problem_type == 'survivalAnalysis':\n inputFeaturesList.insert(0,configSettingsJson['basic']['dateTimeFeature'])\n dataFilePath = str(configSettingsJson['basic']['dataLocation'])\n if os.path.isfile(dataFilePath):\n df = pd.read_csv(dataFilePath,encoding='utf8',nrows=2,sep=delimiters,quotechar=textqualifier,encoding_errors= 'replace')\n try:\n singleInstanceData = df.loc[0, inputFeaturesList]\n except:\n singleInstanceData = pd.Series(0, index =inputFeaturesList) \n inputFieldsDict = singleInstanceData.to_dict()\n else:\n inputFieldsDict = {\"File\":\"EnterFileContent\"}\t\t\t\t\t\t\n inputFields = []\n inputFields.append(inputFieldsDict)\n return inputFields\ndef createInstanceFeatures(configSettingsJson,problem_type,mlmodels,usecaseid,version,ser_url):\n delimiters,textqualifier = delimitedsetting(configSettingsJson['basic']['fileSettings']['delimiters'],configSettingsJson['basic']['fileSettings']['textqualifier']) \n inputFeatures = configSettingsJson['basic']['trainingFeatures']\n targetFeature = configSettingsJson['basic']['targetFeature']\n if inputFeatures != '':\n inputFeaturesList = inputFeatures.split(',')\n else:\n inputFeaturesList = []\n if targetFeature in inputFeaturesList:\n inputFeaturesList.remove(targetFeature) \n if configSettingsJson['basic']['contextFeature'] != '':\n inputFeaturesList.append(configSettingsJson['basic']['contextFeature']) \n if problem_type == 'llmFineTuning':\n inputFeaturesList.append('Temperature')\n inputFeaturesList.append('Max Tokens')\n if problem_type in ['survivalAnalysis','anomalyDetection', 'timeSeriesAnomalyDetection']: #task 11997\n if configSettingsJson['basic']['dateTimeFeature'] != '' and configSettingsJson['basic']['dateTimeFeature'] != 'na':\n inputFeaturesList.insert(0,configSettingsJson['basic']['dateTimeFeature']) \n dataFilePath = str(configSettingsJson['basic']['dataLocation'])\n if problem_type == 'timeSeriesForecasting': #task 11997\n inputFieldsDict = {'noofforecasts': 10}\n elif problem_type == 'recommenderSystem' and mlmodels=='ItemRating':\n inputFieldsDict = {\"uid\": 1, \"numberOfRecommendation\":10} \n elif problem_type == 'stateTransition': \n inputFeatures = configSettingsJson['basic']['trainingFeatures']\n targetFeature = configSettingsJson['basic']['targetFeature']\n if inputFeatures != '':\n inputFeaturesList = inputFeatures.split(',')\n else:\n inputFeaturesList = []\n inputFieldsDict = {inputFeatures:'session',targetFeature:'Activity'}\n elif problem_type != 'llmFineTuning':\n if os.path.isfile(dataFilePath):\n df = pd.read_csv(dataFilePath,encoding='utf8',nrows=2,sep=delimiters,quotechar=textqualifier,skipinitialspace = True,encoding_errors= 'replace')\n try:\n inputFieldsDict = df.to_dict(orient='index')[0]\n except:\n inputFieldsDict = pd.Series(0, index =inputFeaturesList).to_dict()\n else:\n inputFieldsDict = {\"File\":\"EnterFileContent\"} \n else:\n inputFieldsDict = pd.Series('', index =inputFeaturesList).to_dict()\n inputFieldsDict['Temperature'] = '0.1'\n hypervisor,instanceid,region,image = get_instance(usecaseid+'_'+str(version))\n if hypervisor.lower() == 'AWS':\n inputFieldsDict['Max Tokens'] = '1024'\n else:\n inputFieldsDict['Max Tokens'] = '4096'\n inputFields = []\n inputFields.append(inputFieldsDict)\n if problem_type == 'llmFineTuning':\n ser_url = get_instance_id(usecaseid+'_'+str(version))\n elif problem_type == 'stateTransition': \n \n ser_url = ser_url+'pattern_anomaly_predict?usecaseid='+usecaseid+'&version='+str(version)\n else:\n \n ser_url = ser_url+'predict?usecaseid='+usecaseid+'&version='+str(version) \n return inputFields,ser_url \ndef singleInstancePredict(request, Existusecases, usecasedetails):\n log = logging.getLogger('log_ux')\n modelType=''\n context = getcommonfields()\n submittype = request.POST.get('predictsubmit')\n selected_use_case,ModelVersion,ModelStatus = getusercasestatus(request) \n t1 = time.time()\n try:\n try:\n model = Existusecases.objects.get(ModelName=request.session['ModelName'],\n Version=request.session['ModelVersion'])\n output_train_json_filename = str(model.TrainOuputLocation)\n f = open(output_train_json_filename, \"r+\")\n training_output = f.read()\n f.close()\n training_output = json.loads(training_output)\n featureused = training_output['data']['featuresused']\n except:\n featureused = []\n from appbe.telemetry import UpdateTelemetry\n UpdateTelemetry(request.session['usecaseid']+'-'+str(request.session['ModelVersion']),'Prediction','Yes')\n \n usecasename = request.session['usecaseid'].replace(\" \", \"_\")\n context.update({'usecasename':usecasename})\n updatedConfigFile = request.session['config_json']\n f = open(updatedConfigFile, \"r\", encoding = \"utf-8\")\n configSettings = f.read()\n f.close()\n configSettingsJson = json.loads(configSettings) \n inputFeatures = configSettingsJson['basic']['trainingFeatures']\n targetFeature = configSettingsJson['basic']['targetFeature']\n if inputFeatures != '':\n inputFeaturesList = inputFeatures.split(',')\n else:\n inputFeaturesList = []\n if targetFeature in inputFeaturesList:\n inputFeaturesList.remove(targetFeature) \n if configSettingsJson['basic']['contextFeature'] != '':\n inputFeaturesList.append(configSettingsJson['basic']['contextFeature'])\n\n problemtypes = configSettingsJson['basic']['analysisType'] \n problem_type = ''\n modelSize = ''\n for k in problemtypes.keys():\n if configSettingsJson['basic']['analysisType'][k] == 'True':\n problem_type = k\n break\n if problem_type == 'llmFineTuning':\n inputFeaturesList.append('Temperature')\n inputFeaturesList.append('Max Tokens')\n mlmodels =''\n algorihtms = configSettingsJson['basic']['algorithms'][problem_type]\n for k in algorihtms.keys():\n if configSettingsJson['basic']['algorithms'][problem_type][k] == 'True':\n if mlmodels != '':\n mlmodels += ', ' \n mlmodels += k\n \n if problem_type == 'llmFineTuning':\n ser_url = get_instance_id(usecasename+'_'+str(request.session['ModelVersion']))\n if 'modelSize' in configSettingsJson['basic']:\n selectedModelSize = configSettingsJson['basic']['modelSize']['llmFineTuning'][mlmodels]\n for k in selectedModelSize.keys():\n if configSettingsJson['basic']['modelSize']['llmFineTuning'][mlmodels][k] == 'True':\n modelSize = k\n break\n\n elif problem_type == 'stateTransition': \n ser_url = service_url.read_service_url_params(request)\n ser_url = ser_url+'pattern_anomaly_predict?usecaseid='+usecasename+'&version='+str(request.session['ModelVersion'])\n else:\n ser_url = service_url.read_service_url_params(request)\n ser_url = ser_url+'predict?usecaseid='+usecasename+'&version='+str(request.session['ModelVersion']) \n if submittype.lower() == 'predict':\n inputFieldsDict = {}\n if problem_type == 'timeSeriesForecasting': #task 11997\n inputFieldsDict['noofforecasts'] = int(request.POST.get('noofforecasts'))\n elif problem_type == 'stateTransition':\n inputFeatures = configSettingsJson['basic']['trainingFeatures']\n targetFeature = configSettingsJson['basic']['targetFeature']\n sessionid = request.POST.get('SessionID')\n activity = request.POST.get(targetFeature) \n inputFieldsDict[inputFeatures] = request.POST.get(inputFeatures)\n inputFieldsDict[targetFeature] = request.POST.get(targetFeature)\n \n elif problem_type == 'recommenderSystem' and mlmodels == 'ItemRating':\n inputFieldsDict['uid'] = request.POST.get('uid')\n inputFieldsDict['numberOfRecommendation'] = int(request.POST.get('numberOfRecommendation')) #Task 11190\n else:\n if problem_type in ['survivalAnalysis','anomalyDetection', 'timeSeriesAnomalyDetection']: #task 11997\n if configSettingsJson['basic']['dateTimeFeature'] != '' and configSettingsJson['basic']['dateTimeFeature'] != 'na':\n inputFeaturesList.insert(0,configSettingsJson['basic']['dateTimeFeature'])\n \n for feature in inputFeaturesList:\n inputFieldsDict[feature] = request.POST.get(feature)\n if problem_type.lower() not in ['contextualsearch','similarityidentification']:\n for key, value in inputFieldsDict.items():\n if value == 'nan':\n inputFieldsDict[key] = ''\n\n if value == '':\n if key in featureused:\n 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})\n return context\n inputFieldsJson = json.dumps(inputFieldsDict) \n if problem_type == 'llmFineTuning':\n modelType = request.POST.get('modelTypeforInferencing')\n\n x = inputFieldsDict.keys()\n from appbe.dataPath import DATA_DIR\n prompt = inputFieldsDict[configSettingsJson['basic']['trainingFeatures']]\n promptobj = {'prompt':prompt}\n if configSettingsJson['basic']['contextFeature'] != '':\n inputData = inputFieldsDict[configSettingsJson['basic']['contextFeature']]\n promptobj.update({'input':inputData})\n filetimestamp = str(int(time.time()))\n file_path = os.path.join(DATA_DIR,'logs',filetimestamp+'.json')\n f= open(file_path,\"w\",encoding=\"utf-8\")\n #print(promptobj)\n json.dump(promptobj,f)\n f.close()\n from llm.llm_inference import LLM_predict\n cloudconfig = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','config','compute_conf.json'))\n hypervisor,instanceid,region,image = get_instance(usecasename+'_'+str(request.session['ModelVersion']))\n if hypervisor and instanceid:\n if modelSize != '':\n mlmodels = mlmodels+'-'+modelSize\n cachepath = os.path.join(DATA_DIR,'sqlite','cachePrompt.db')\n import sqlite3\n conn = sqlite3.connect(cachepath)\n from llm.llm_cache import CachePrompt\n cachepromptObj = CachePrompt(conn)\n searchFlag,result = cachepromptObj.selectFromCache(prompt,usecasename+'_'+str(request.session['ModelVersion']),modelType,temperature=inputFieldsDict['Temperature'],max_token=inputFieldsDict['Max Tokens'])\n \n if searchFlag:\n buf = LLM_predict(cloudconfig,instanceid,file_path,hypervisor,mlmodels,usecasename+'_'+str(request.session['ModelVersion']),region,image,inputFieldsDict['Temperature'],inputFieldsDict['Max Tokens'],modelType)\n import re\n outputStr = buf.split('ModelOutput:')[1]\n cachepromptObj.insertRecord(prompt,outputStr,usecasename+'_'+str(request.session['ModelVersion']),modelType,temperature=inputFieldsDict['Temperature'],max_token=inputFieldsDict['Max Tokens'])\n else:\n outputStr = result\n if configSettingsJson['basic']['folderSettings']['fileType'].lower() != 'llm_document':\n outputStr = outputStr.split('### '+configSettingsJson['basic']['preprocessing']['llmFineTuning']['friendlyNames']['response']+':')[1]\n singlePredictionResults = []\n", "instruction": "", "output": "" }, { "input": " singlePredictionsummary=\"\"\n Results={}\n Results['Response'] = outputStr\n singlePredictionResults.append(Results)\n else:\n context.update(\n {'tab': 'tabconfigure', 'error': 'Prediction Error: Instance ID not found ', 'selected': 'prediction',\n 'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,\n 'ModelVersion': ModelVersion,'mlmodels':mlmodels})\n log.info('Predict Instance :' + str(selected_use_case) + ' : ' + str(\n ModelVersion) + ' : ' + '0 ' + 'sec' + ' : ' + 'Error : Prediction Error, Instance ID not found')\n return context\n else:\n try:\n import requests \n #response = requests.post(ser_url,auth=(aion_service_username,aion_service_password),data=inputFieldsJson,headers={\"Content-Type\":\"application/json\",})\n response = requests.post(ser_url,data=inputFieldsJson,headers={\"Content-Type\":\"application/json\",})\n if response.status_code != 200:\n outputStr=response.content\n context.update({'tab': 'tabconfigure', 'error': outputStr.decode('utf-8'), 'selected': 'prediction'})\n log.info('Predict Instance : '+str(selected_use_case) + ' : ' + str(ModelVersion) + ' : '+'0 '+'sec'+' : '+'Error : '+str(outputStr.decode('utf-8')))\n return context \n except Exception as inst:\n if 'Failed to establish a new connection' in str(inst):\n context.update({'tab': 'tabconfigure', 'error': 'AION service need to be started', 'selected': 'prediction', 'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,'ModelVersion': ModelVersion})\n log.info('Predict Instance :'+str(selected_use_case) + ' : ' + str(ModelVersion) + ' : '+'0'+' sec'+' : '+'Error : AION service need to be started, '+str(inst))\n return context\n else:\n context.update({'tab': 'tabconfigure', 'error': 'Prediction Error '+str(inst),'selected': 'prediction', 'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,'ModelVersion': ModelVersion})\n log.info('Predict Instance :'+str(selected_use_case) + ' : ' + str(ModelVersion) + ' : '+'0 '+'sec'+' : '+'Error : Prediction Error, '+str(inst))\n return context \n outputStr=response.content \n outputStr = outputStr.decode('utf-8','ignore')\n outputStr = outputStr.strip()\n predict_dict = json.loads(str(outputStr))\n #print(predict_dict)\n singlePredictionsummary=\"\" \n if (predict_dict['status'] == 'SUCCESS'):\n data = predict_dict['data']\n singlePredictionResults = []\n Results = {}\n if problem_type == 'multiModalLearning':\n data = data[0]\n Results['prediction'] = data['predict']\n singlePredictionResults.append(Results)\n\n if problem_type == 'textSummarization':\n data = data[0]\n Results['msg'] = predict_dict['msg']\n singlePredictionResults.append(Results)\n Results['prediction'] = predict_dict['data']\n singlePredictionResults.append(Results)\n Results1 = {}\n Results1['prediction'] = predict_dict['data']\n print(\"prdata------------\",predict_dict['data'])\n singlePredictionsummary=predict_dict['data']\n print(\"singlePredictionsummary\",singlePredictionsummary)\n t2 = time.time() \n \n elif problem_type == 'multiLabelPrediction':\n prediction = ''\n for x in data:\n for y in x:\n if 'predict' in y:\n if prediction != '':\n prediction += ','\n prediction += str(y)+':'+str(x[y])\n Results['prediction'] = prediction\n singlePredictionResults.append(Results)\n elif problem_type == 'timeSeriesForecasting': #task 11997\n Results['prediction'] = json.dumps(data)\n singlePredictionResults.append(Results)\n elif problem_type == 'stateTransition':\n if str(data['Anomaly']) == 'False':\n Results['prediction'] = 'No Anomaly'\n else:\n Results['prediction'] = str(data['Remarks'])\n singlePredictionResults.append(Results)\n elif problem_type.lower() in ['similarityidentification','contextualsearch']:\n data = data[0]\n prediction = data['prediction']\n i = 1\n for x in prediction:\n te = ''\n for y in x:\n info = (str(x[y])[:50] + '...') if len(str(x[y])) > 50 else str(x[y])\n te += y+': '+info+'\\\\n\\\\n'\n Results[i] = te\n i = i+1\n singlePredictionResults.append(Results)\n else:\n data = data[0]\n if 'prediction' in data:\n Results['prediction'] = data['prediction']\n\n if 'probability' in data:\n Results['probability'] = data['probability']\n if 'remarks' in data:\n Results['remarks'] = json.loads(data['remarks'])\n singlePredictionResults.append(Results)\n t2 = time.time()\n log.info('Predict Instance : '+str(selected_use_case) + ' : ' + str(ModelVersion) + ' : '+str(round(t2-t1))+' sec'+' : '+'Success')\n\n else:\n context.update({'tab': 'tabconfigure', 'error': 'Prediction Error '+str(predict_dict['message']), 'selected': 'prediction','selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,'ModelVersion': ModelVersion})\n log.info('Predict Instance : '+str(selected_use_case) + ' : ' + str(ModelVersion) + ' : '+'0 '+'sec'+' : '+'Error : Prediction Error')\n return context\n inputFields = []\n inputFields.append(inputFieldsDict)\n ##Below added by sjayaram for llm langkit evaluation metrics Task:17109\n prompt_response_results = ''\n if problem_type == 'llmFineTuning':\n try:\n response_msg = outputStr\n prompt_msg = prompt\n except:\n response_msg = ''\n prompt_msg = ''\n \n from appbe.evaluate_prompt import evaluate_prompt_response_inputs\n final_output_json,prompt_response_results = evaluate_prompt_response_inputs(prompt_msg,response_msg)\n #ser_url = service_url.read_service_url_params(request)\n #ser_url = ser_url+'predict?usecaseid='+usecasename+'&version='+str(ModelVersion)\n 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',\n 'prompt_response_results':prompt_response_results})\n return context\n elif submittype.lower() == 'script':\n scriptdata=\"'''\\\\n\"\n scriptdata+=\"* =============================================================================\\\\n\"\n scriptdata+=\"* COPYRIGHT NOTICE\\\\n\"\n scriptdata+=\"* =============================================================================\\\\n\"\n scriptdata+=\"* @ Copyright HCL Technologies Ltd. 2021, 2022, 2023\\\\n\"\n scriptdata+=\"* Proprietary and confidential. All information contained herein is, and\\\\n\"\n scriptdata+=\"* remains the property of HCL Technologies Limited. Copying or reproducing the\\\\n\" \n scriptdata+=\"* contents of this file, via any medium is strictly prohibited unless prior\\\\n\"\n scriptdata+=\"* written permission is obtained from HCL Technologies Limited.\\\\n\" \n scriptdata+=\"'''\\\\n\" \n scriptdata+='import sys\\\\n'\n scriptdata+='import json\\\\n'\n scriptdata+='import requests\\\\n'\n scriptdata+='import pandas as pd\\\\n'\n scriptdata+='from pandas import json_normalize\\\\n'\n scriptdata+='ser_url =\"'+ser_url+'\"\\\\n\\\\n'\n scriptdata+=\"def predict(data):\\\\n\"\n scriptdata+=\" if data.endswith('.tsv'):\\\\n\"\n scriptdata+=\" df=pd.read_csv(data,encoding='utf-8',encoding_errors= 'replace',sep='\\\\\\\\t')\\\\n\"\n scriptdata+=\" else:\\\\n\"\n scriptdata+=\" df=pd.read_csv(data,encoding='utf-8',encoding_errors= 'replace')\\\\n\"\n scriptdata+=' features = \"'+\",\".join([feature for feature in inputFeaturesList])+'\"\\\\n'\n scriptdata+=\" features = features.split(',')\\\\n\"\n scriptdata+=\" df = df[features]\\\\n\" \n scriptdata+=\" data = df.to_json(orient='records')\\\\n\"\n scriptdata+=\" try:\\\\n\"\n scriptdata+=' response = requests.post(ser_url,data=data,headers={\"Content-Type\":\"application/json\",})\\\\n'\n scriptdata+=\" if response.status_code == 200:\\\\n\" \n scriptdata+=\" outputStr=response.content\\\\n\" \n scriptdata+=\" outputStr = outputStr.decode('utf-8')\\\\n\" \n scriptdata+=\" outputStr = outputStr.strip()\\\\n\"\n scriptdata+=\" predict_dict = json.loads(str(outputStr))\\\\n\" \n scriptdata+=\" print(predict_dict)\\\\n\"\n scriptdata+=\" except Exception as e:\\\\n\"\n scriptdata+=' print(e)\\\\n'\n scriptdata+='\\\\nif __name__ == \"__main__\":\\\\n'\n scriptdata+=' predict(sys.argv[1])'\n response = HttpResponse()\n response['content_type'] = 'text/plain'\n response['Content-Disposition'] = 'attachment; filename=prediction.py'\n response.write(scriptdata)\n return response\n\n except Exception as inst:\n print(inst)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type) + ' ' + str(fname) + ' ' + str(exc_tb.tb_lineno))\n context.update({'tab': 'tabconfigure', 'error': 'Failed To perform prediction','selected_use_case': selected_use_case, 'ModelStatus': ModelStatus,'ModelVersion': ModelVersion, 'selected': 'prediction'})\n log.info('Predict Instance :' + str(selected_use_case) + ' : ' + str(ModelVersion) + ' : ' + ' 0 ' + 'sec' + ' : ' + 'Error : Failed To perform prediction, '+ str(inst))\n return context \n \n import os\nimport openai\nfrom langchain.llms import AzureOpenAI\nfrom sentence_transformers.SentenceTransformer import SentenceTransformer\nimport time\nimport datetime\nimport pandas as pd\nimport sys\nimport subprocess\nimport importlib\nfrom appbe.aion_config import get_llm_data\nfrom appbe.dataPath import DATA_FILE_PATH\n\nremote_data_dir = \"/home/aion/data/storage/llm_testing_data\"\nremote_data_processeddata_dir = '/home/aion/data/storage/processed_data'\nremote_config_dir = '/home/aion/data/config'\nsh_file_path = '/home/aion/llm/sbin/llm_testing.sh'\n\n\n\n\n\nprompt_command = '/home/aion/llm/sbin/llm_testing.sh'\n\nPRE_CONTEXT = \"Answer the following question in a concise manner.\\\\n\"\nDEFAULT_PARAMS = {\n 'OPENAI_API_TYPE' : \"azure\",\n 'OPENAI_API_BASE' : \"\",\n 'OPENAI_API_KEY' : \"\",\n 'OPENAI_API_VERSION' : \"2023-03-15-preview\"\n}\nfaq=\"\"\n\ndef getAMIDetails(config,selectedAMI):\n y = {}\n for x in config:\n print(x)\n if x['id'] == selectedAMI:\n return x\n return y\nclass test_LLM():\n\n def __init__(self, \n deployment_name='Text-Datvinci-03', params=DEFAULT_PARAMS, transformer=None, \n sentence_txfr_model='sentence-transformers/paraphrase-mpnet-base-v2'):\n self.deployment_name=deployment_name\n self.set_params( params)\n self.transformer = transformer\n self.sentence_txfr_model = sentence_txfr_model\n def fiddlerAuditorCheck(self):\n status = importlib.util.find_spec('auditor')\n if not status:\n subprocess.check_call([sys.executable, \"-m\", \"pip\",\"uninstall\", \"-q\",\"-y\",\"notebook\"])\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\",\"-q\", \"notebook==6.4.5\" ])\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\",\"-q\",\"fiddler-auditor==0.0.2\"])\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\",\"-q\",\"notebook==7.0.2\"])\n status = importlib.util.find_spec('auditor')\n return status\n \n \n\t\t\t\t\n def set_params(self, params={}):\n valid_params = ['OPENAI_API_TYPE','OPENAI_API_KEY','OPENAI_API_BASE','OPENAI_API_VERSION']\n for key, value in params.items():\n if 'OPENAI_API_TYPE' == key:\n openai.api_type = value\n os.environ['OPENAI_API_TYPE'] = openai.api_type\n elif 'OPENAI_API_KEY' == key:\n openai.api_key = value\n os.environ['OPENAI_API_KEY'] = openai.api_key\n elif 'OPENAI_API_BASE' == key:\n openai.api_base = value\n os.environ['OPENAI_API_BASE'] = openai.api_base\n elif key in valid_params:\n os.environ[key] = value\n \n def run(self,modelName, temperature, similarity_threshold, perturbations_per_sample, prompts, reference_generation,pre_context=PRE_CONTEXT):\n \n \n if not self.fiddlerAuditorCheck():\n raise ValueError('Fiddler-auditor is not instlled \"python -m pip install fiddler-auditor==0.0.2\"')\n \n openai_llm = AzureOpenAI(deployment_name=self.deployment_name, temperature=temperature, openai_api_key=open", "instruction": "", "output": "" }, { "input": "ai.api_key)\n from auditor.perturbations import Paraphrase\n from auditor.evaluation.expected_behavior import SimilarGeneration\n from auditor.evaluation.evaluate import LLMEval\n\n \n\n # For Azure OpenAI, it might be the case the api_version for chat completion\n # is different from the base model so we need to set that parameter as well.\n if self.transformer:\n azure_perturber = self.transformer\n else:\n azure_perturber = Paraphrase(\n model=\"GPT-35-Turbo\",\n api_version=\"2023-03-15-preview\",\n num_perturbations=perturbations_per_sample,\n )\n sent_xfmer = SentenceTransformer(self.sentence_txfr_model)\n similar_generation = SimilarGeneration(\n similarity_model=sent_xfmer,\n similarity_threshold=similarity_threshold,)\n llm_eval = LLMEval(\n llm=openai_llm,\n expected_behavior=similar_generation,\n transformation=azure_perturber,)\n test_result = llm_eval.evaluate_prompt_correctness(\n prompt=prompts,\n pre_context=pre_context,\n reference_generation=reference_generation,\n perturbations_per_sample=perturbations_per_sample\n )\n return test_result\n \n def runmultiple(self,modelName, temperature, similarity_threshold, perturbations_per_sample, prompts, reference_generation,pre_context=PRE_CONTEXT,faq=faq):\n \n \n if not self.fiddlerAuditorCheck():\n raise ValueError('Fiddler-auditor is not instlled \"python -m pip install fiddler-auditor==0.0.2\"')\n \n from auditor.evaluation.expected_behavior import SimilarGeneration\n from auditor.evaluation.evaluate import LLMEval\n openai_llm = AzureOpenAI(deployment_name=self.deployment_name, temperature=temperature, openai_api_key=openai.api_key)\n from auditor.perturbations import Paraphrase\n\n # For Azure OpenAI, it might be the case the api_version for chat completion\n # is different from the base model so we need to set that parameter as well.\n if self.transformer:\n azure_perturber = self.transformer\n else:\n azure_perturber = Paraphrase(\n model=\"GPT-35-Turbo\",\n api_version=\"2023-03-15-preview\",\n num_perturbations=perturbations_per_sample,\n )\n sent_xfmer = SentenceTransformer(self.sentence_txfr_model)\n similar_generation = SimilarGeneration(\n similarity_model=sent_xfmer,\n similarity_threshold=similarity_threshold,)\n llm_eval = LLMEval(\n llm=openai_llm,\n expected_behavior=similar_generation,\n transformation=azure_perturber,)\n rows = faq.shape[0]\n prompts = list(faq['Question'])\n listofDf = []\n\n for i in range(rows):\n test_result = llm_eval.evaluate_prompt_robustness(\n prompt=prompts[i],\n pre_context=pre_context,\n )\n\n try:\n now = datetime.datetime.now().strftime(\"%H%M%S\")\n name = str(i)+str(now)+'.html'\n test_result.save(name)\n df_iter=pd.read_html(name)\n df_actual = df_iter[0]\n listofDf.append(df_actual)\n except:\n pass\n \n perturbatedDF = pd.concat(listofDf)\n\n return perturbatedDF\n\n def run_offline_model(self, usecasename,modelName, temperature, similarity_threshold, perturbations_per_sample, reference_generation, prompts,isfinetuned):\n from appbe.compute import readComputeConfig\n from appbe.prediction import get_instance\n cloud_infra = readComputeConfig()\n \n dataFile = os.path.join(DATA_FILE_PATH, 'prompt.csv')\n remoteFile = os.path.join(remote_data_dir, 'prompt.csv')\n if not reference_generation:\n reference_generation = ''\n prompt = pd.DataFrame([{'prompts':prompts, 'reference_generation':reference_generation}])\n prompt.to_csv(dataFile, index=False)\n \n \n \n hypervisor, instanceid, region, image = get_instance(usecasename)\n key, url, api_type, api_version = get_llm_data()\n if hypervisor == 'AWS':\n aws_access_key_id = cloud_infra['awsCredentials']['accessKey']\n aws_secret_key = cloud_infra['awsCredentials']['secretAccessKey']\n currentDirectory = os.path.dirname(os.path.abspath(__file__))\n LLM_DIR = os.path.normpath(os.path.join(currentDirectory, '..', 'llm'))\n\n if image != '' and image != 'NA':\n amiDetails = getAMIDetails(cloud_infra['AWS_EC2']['amis'], image)\n else:\n amiDetails = getAMIDetails(cloud_infra['AWS_EC2']['instances'], instanceid)\n if region == '' or region == 'NA':\n region = amiDetails['regionName']\n from llm.aws_instance_api import start_instance\n # print(aws_access_key_id, aws_secret_key, instanceid, region)\n status, msg, ip = start_instance(aws_access_key_id, aws_secret_key, instanceid, region)\n \n \n if status.lower() == 'success':\n\n pem_file = os.path.join(LLM_DIR, amiDetails['ssh']['keyFilePath'])\n username = amiDetails['ssh']['userName']\n \n # cope file to server for sinfle prompt\n from AION.llm.ssh_command import copy_files_to_server\n copy_files_to_server(ip,pem_file,dataFile,'',username,'',remote_data_dir,remote_config_dir)\n if isfinetuned:\n command = prompt_command + ' ' + usecasename + ' ' + str(modelName) \\\\\n + ' ' + str(temperature) + ' ' + str(similarity_threshold) + ' ' \\\\\n + str(perturbations_per_sample) + \\\\\n ' '+ str(key) + \\\\\n ' '+ str(url) + \\\\\n ' '+ str(api_type) + \\\\\n ' '+ str(api_version)+ \\\\\n ' '+ str(\"single\") \n else: \n command = prompt_command + ' ' + 'BaseModel' + ' ' + str(modelName) \\\\\n + ' ' + str(temperature) + ' ' + str(similarity_threshold) + ' ' \\\\\n + str(perturbations_per_sample) + \\\\\n ' '+ str(key) + \\\\\n ' '+ str(url) + \\\\\n ' '+ str(api_type) + \\\\\n ' '+ str(api_version)+ \\\\\n ' '+ str(\"single\") \n \n \n \n from llm.ssh_command import run_ssh_cmd\n \n buf = run_ssh_cmd(ip, pem_file, username, '', '', command)\n print(buf)\n return buf\n def run_multiple_offline_model(self, usecasename,modelName, temperature, similarity_threshold, perturbations_per_sample, faq,isfinetuned):\n dataFile = os.path.join(DATA_FILE_PATH, 'prompt.csv')\n remoteFile = os.path.join(remote_data_dir, 'prompt.csv')\n faq.to_csv(dataFile, index=False)\n print(\"This is done\")\n from appbe.compute import readComputeConfig\n from appbe.prediction import get_instance\n cloud_infra = readComputeConfig()\n hypervisor, instanceid, region, image = get_instance(usecasename)\n key, url, api_type, api_version = get_llm_data()\n if hypervisor == 'AWS':\n aws_access_key_id = cloud_infra['awsCredentials']['accessKey']\n aws_secret_key = cloud_infra['awsCredentials']['secretAccessKey']\n currentDirectory = os.path.dirname(os.path.abspath(__file__))\n LLM_DIR = os.path.normpath(os.path.join(currentDirectory, '..', 'llm'))\n\n if image != '' and image != 'NA':\n amiDetails = getAMIDetails(cloud_infra['AWS_EC2']['amis'], image)\n else:\n amiDetails = getAMIDetails(cloud_infra['AWS_EC2']['instances'], instanceid)\n if region == '' or region == 'NA':\n region = amiDetails['regionName']\n from llm.aws_instance_api import start_instance\n # print(aws_access_key_id, aws_secret_key, instanceid, region)\n status, msg, ip = start_instance(aws_access_key_id, aws_secret_key, instanceid, region)\n \n \n if status.lower() == 'success':\n\n pem_file = os.path.join(LLM_DIR, amiDetails['ssh']['keyFilePath'])\n username = amiDetails['ssh']['userName']\n \n #print(ip,pem_file,promptfile,'',username,'',remote_data_dir,remote_config_dir)\n \n from AION.llm.ssh_command import copy_files_to_server\n copy_files_to_server(ip,pem_file,dataFile,'',username,'',remote_data_dir,remote_config_dir)\n \n if isfinetuned:\n command = prompt_command + ' ' + usecasename + ' ' + str(modelName) \\\\\n + ' ' + str(temperature) + ' ' + str(similarity_threshold) + ' ' \\\\\n + str(perturbations_per_sample) + \\\\\n ' '+ str(key) + \\\\\n ' '+ str(url) + \\\\\n ' '+ str(api_type) + \\\\\n ' '+ str(api_version)+ \\\\\n ' '+ str(\"multiple\")\n \n else:\n command = prompt_command + ' ' + 'BaseModel' + ' ' + str(modelName) \\\\\n + ' ' + str(temperature) + ' ' + str(similarity_threshold) + ' ' \\\\\n + str(perturbations_per_sample) + \\\\\n ' '+ str(key) + \\\\\n ' '+ str(url) + \\\\\n ' '+ str(api_type) + \\\\\n ' '+ str(api_version)+ \\\\\n ' '+ str(\"multiple\")\n \n \n from llm.ssh_command import run_ssh_cmd\n \n buf = run_ssh_cmd(ip, pem_file, username, '', '', command)\n print(buf)\n return buf\n import pandas as pd\nimport numpy as np\ndef get_leaderboard(file_content):\n matched_lines = [line.replace('Model:-', '') for line in file_content.split('\\\\n') if \"Model:-\" in line]\n df = pd.DataFrame(columns = ['Model', 'Iterations', 'Score (%)', 'Score Type', 'Best Score (%)'])\n import re\n try:\n for line in matched_lines:\n if 'Model Name::' in line:\n MODEL = line.split('::')\n model = MODEL[1]\n if 'ScoringType::' in line:\n S = line.split('::')\n #SC = ScorTyp[1]\n if 'make_scorer'in line:\n ST = line.split('make_scorer')\n ScorTyp = ST[1]\n df['Score Type'] = np.where(df['Model'] == model, ScorTyp,df['Score Type'])\n if 'Validation Score::' in line:\n BS = line.split('::')\n BestSc = round(float(BS[1]), 4)*100\n BestSc = abs(BestSc)\n df['Best Score (%)'] = np.where(df['Model'] == model, BestSc, df['Best Score (%)'])\n if 'Iteration::' in line:\n l = line.split('::')\n word = re.findall(r'\\\\[(.*?)\\\\]', l[1])\n if ';, score=' in line:\n sc = line.split('score=')\n SCR = sc[1].split(' ')\n Score = round(float(SCR[0]), 4)*100\n Score = abs(Score)\n # df = df.concat({'Model': model, 'Iterations': word,'Score (%)': Scor,'Score Type': '', 'Best Score (%)': 0}, ignore_index=True)\n newdf = pd.DataFrame([{'Model': model, 'Iterations': word,'Score (%)': Score,'Score Type': '', 'Best Score (%)': 0}])\n df = pd.concat([df,newdf],axis=0, ignore_index=True)\n\n LIST = []\n for i in range(int(len(df['Score (%)'])/5)):\n l = (sum(df['Score (%)'][5*i:5*(i+1)])/5)\n #LIST.concat(l)\n LIST.append(l)\n for i in range(len(LIST)):\n df['Score (%)'][5*i:5*(i+1)]=LIST[i]\n\n CL = [line.replace('------->Type of Model :classification', 'Model :classification') for line in file_content.split('\\\\n') if \"------->Type of Model :classification\" in line]\n for l in CL:\n if 'Model :classification' in l: \n df = df.sort_values(by = ['Best Score (%)'], ascending=False)\n RE = [line.replace('------->Type of Model :regression', 'Model :regression') for line in file_content.split('\\\\n') if \"------->Type of Model :regression\" in line] \n for l in RE: \n if 'Model :regression' in l: \n df = df.sort_values(by = ['Best Score (%)'])\n except Exception as e:\n print(e)\n return df\n \nif __name__ == \"__main__\":\n file_path = r\"C:\\\\Users\\\\richard.mochahari\\\\AppData\\\\Local\\\\Programs\\\\HCLTech\\\\AION\\\\data\\\\target\\\\AI0335\\\\1\\\\log\\\\model_training_logs.log\"\n my_file = open(file_path, 'r')\n file_content = my_file.read()\n my_file.close()\n print(get_leaderboard(file_content)) '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport sqlite3\nfrom pathlib import Path\nimport json\nimport os\nimport rsa\nimport boto3 #usnish\nimport pandas as pd\nimport time\n\nimport sqlite3\n\nclass sqlite_db():\n\n\tdef __init__(self, location, database_file=None):\n\t\tif not isinstance(location, Path):\n\t\t\tlocation = Path(location)\n\t\tif database_file:\n\t\t", "instruction": "", "output": "" }, { "input": "\tself.database_name = database_file\n\t\telse:\n\t\t\tself.database_name = location.stem\n\t\tdb_file = str(location/self.database_name)\n\t\tself.conn = sqlite3.connect(db_file)\n\t\tself.cursor = self.conn.cursor()\n\n\tdef table_exists(self, name):\n\t\tquery = f\"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}';\"\n\t\tlistOfTables = self.cursor.execute(query).fetchall()\n\t\treturn len(listOfTables) > 0\n\n\tdef read_data(self, table_name):\n\t\tquery = f\"SELECT * FROM {table_name}\"\n\t\trow = self.cursor.execute(query).fetchall()\n\t\treturn list(row)\n\t\t#return pd.read_sql_query(f\"SELECT * FROM {table_name}\", self.conn)\n\n\tdef create_table(self,name, columns, dtypes):\n\t\tquery = f'CREATE TABLE IF NOT EXISTS {name} ('\n\t\t\n\t\tfor column, data_type in zip(columns, dtypes):\n\t\t\tquery += f\"'{column}'\tTEXT,\"\n\t\tquery = query[:-1]\n\t\tquery += ');'\n\t\tself.conn.execute(query)\n\t\treturn True\n\tdef delete_record(self,table_name,col_name, col_value):\n\t\ttry:\n\t\t\tquery = f\"DELETE FROM {table_name} WHERE {col_name}='{col_value}'\"\n\t\t\tself.conn.execute(query)\n\t\t\tself.conn.commit()\n\t\t\treturn 'success'\n\t\texcept Exception as e :\n\t\t\tprint(str(e))\n\t\t\tprint(\"Deletion Failed\")\n\t\t\treturn 'error'\n\t\n\tdef get_data(self,table_name,col_name,col_value):\n\t\tquery = f\"SELECT * FROM {table_name} WHERE {col_name}='{col_value}'\"\n\t\trow = self.cursor.execute(query).fetchone()\n\t\tif(row == None):\n\t\t\treturn []\n\t\treturn list(row)\n\t\n\tdef write_data(self,data, table_name):\n\t\tif not self.table_exists(table_name):\n\t\t\tself.create_table(table_name, data.columns, data.dtypes)\n\t\ttuple_data = list(data.itertuples(index=False, name=None))\n\t\tinsert_query = f'INSERT INTO {table_name} VALUES('\n\t\tfor i in range(len(data.columns)):\n\t\t\tinsert_query += '?,'\n\t\tinsert_query = insert_query[:-1] + ')'\n\t\tself.cursor.executemany(insert_query, tuple_data)\n\t\tself.conn.commit()\n\t\treturn True\n\t\t\n\tdef close(self):\n\t\tself.conn.close()\n\n\ndef add_new_azureStorage(request):\n\ttry:\n\t\tfrom appbe.dataPath import DATA_DIR\n\t\tfile_path = os.path.join(DATA_DIR,'sqlite')\n\t\tsqlite_obj = sqlite_db(file_path,'config.db')\t\n\t\tif request.POST[\"azurename\"] =='' or request.POST[\"azureaccountkey\"] == '' or request.POST[\"containername\"] == '' :\n\t\t\treturn 'error'\n\t\tnewdata = {}\t\t \n\t\tnewdata['azurename'] = [request.POST[\"azurename\"]]\n\t\tnewdata['azureaccountkey'] = [request.POST[\"azureaccountkey\"]]\n\t\tnewdata['containername'] = [request.POST[\"containername\"]]\n\t\tname = request.POST[\"azurename\"]\n\t\tif sqlite_obj.table_exists(\"azurebucket\"):\t\t\n\t\t\tif(len(sqlite_obj.get_data('azurebucket','azurename',name))>0):\n\t\t\t\treturn 'error1' \n\t\tsqlite_obj.write_data(pd.DataFrame.from_dict(newdata),'azurebucket')\n\t\n\texcept:\n\t\treturn 'error'\n\ndef get_azureStorage():\n\ttry:\n\t\tfrom appbe.dataPath import DATA_DIR\n\t\tfile_path = os.path.join(DATA_DIR,'sqlite')\n\t\tsqlite_obj = sqlite_db(file_path,'config.db')\t\n\t\ttemp_data = sqlite_obj.read_data('azurebucket')\n\t\tdata = []\n\t\tfor x in temp_data:\n\t\t\tdata_dict = {}\n\t\t\tdata_dict['azurename'] = x[0]\n\t\t\tdata_dict['azureaccountkey'] = x[1]\n\t\t\tdata_dict['containername'] = x[2]\n\t\t\tdata.append(data_dict)\t\n\texcept Exception as e:\n\t\tprint(e)\n\t\tdata = []\n\treturn data\ndef read_azureStorage(name,directoryname,DATA_FILE_PATH):\n\ttry:\n\t\tfrom appbe.dataPath import DATA_DIR\n\t\tfile_path = os.path.join(DATA_DIR,'sqlite')\n\t\tsqlite_obj = sqlite_db(file_path,'config.db')\n\t\tdata = sqlite_obj.get_data('azurebucket','azurename',name)\n\texcept:\n\t\tdata = []\n\tfound = False\n\t\n\tif len(data)!=0:\n\t\tstorage_account_name = str(data[0])\n\t\tstorage_account_key = str(data[1])\n\t\tazure_container_name = data[2]\n\t\tfound = True\n\t\t\t\t\n\ttry:\n\t\tif found:\n\t\t\troot_dir = str(directoryname)\n\t\t\tfrom azure.storage.filedatalake import DataLakeServiceClient\n\t\t\timport io\n\t\t\timport pandavro as pdx\n\t\t\tfrom detect_delimiter import detect\t\t\t\n\t\t\ttry:\n\t\t\t\tservice_client = DataLakeServiceClient(account_url=\"{}://{}.dfs.core.windows.net\".format(\"https\", storage_account_name), credential=storage_account_key)\n\t\t\t\tprint(azure_container_name)\n\t\t\t\tfile_system_client = service_client.get_file_system_client(azure_container_name)\n\t\t\t\tprint(root_dir)\n\t\t\t\tfile_paths = file_system_client.get_paths(path=root_dir)\t\t\t\t\n\t\t\t\tmain_df = pd.DataFrame()\n\t\t\t\tfor path in file_paths:\n\t\t\t\t\tif not path.is_directory:\n\t\t\t\t\t\tfile_client = file_system_client.get_file_client(path.name)\n\t\t\t\t\t\tfile_ext = os.path.basename(path.name).split('.', 1)[1]\n\t\t\t\t\t\tif file_ext in [\"csv\", \"tsv\"]:\n\t\t\t\t\t\t\twith open(csv_local, \"wb\") as my_file:\n\t\t\t\t\t\t\t\tdownload = file_client.download_file()\n\t\t\t\t\t\t\t\tdownload.readinto(my_file)\n\t\t\t\t\t\t\twith open(csv_local, 'r') as file:\n\t\t\t\t\t\t\t\tdata = file.read()\n\t\t\t\t\t\t\trow_delimiter = detect(text=data, default=None, whitelist=[',', ';', ':', '|', '\\\\t'])\n\t\t\t\t\t\t\tprocessed_df = pd.read_csv(csv_local, sep=row_delimiter)\n\t\t\t\t\t\tif file_ext == \"parquet\":\n\t\t\t\t\t\t\tdownload = file_client.download_file()\n\t\t\t\t\t\t\tstream = io.BytesIO()\n\t\t\t\t\t\t\tdownload.readinto(stream)\n\t\t\t\t\t\t\tprocessed_df = pd.read_parquet(stream, engine='pyarrow')\n\t\t\t\t\t\tif file_ext == \"avro\": \n\t\t\t\t\t\t\twith open(avro_local, \"wb\") as my_file:\n\t\t\t\t\t\t\t\tdownload = file_client.download_file()\n\t\t\t\t\t\t\t\tdownload.readinto(my_file)\n\t\t\t\t\t\t\tprocessed_df = pdx.read_avro(avro_local)\n\t\t\t\t\t\tif not main_df.empty:\n\t\t\t\t\t\t\tmain_df = main_df.append(processed_df, ignore_index=True)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tmain_df = pd.DataFrame(processed_df)\n\t\t\texcept Exception as e:\n\t\t\t\t\n\t\t\t\tmsg = str(e).split(\".\")[0]\n\t\t\t\tprint(msg)\n\t\t\t\treturn 'Error',str(msg), pd.DataFrame()\n\t\t\treturn \"Success\",\"\",main_df\n\texcept:\n\t\treturn 'Error',\"Please check bucket configuration\", pd.DataFrame()\n\ndef remove_azure_bucket(name):\n\tfrom appbe.dataPath import DATA_DIR\n\tfile_path = os.path.join(DATA_DIR,'sqlite')\n\tsqlite_obj = sqlite_db(file_path,'config.db')\n\treturn sqlite_obj.delete_record('azurebucket','azurename',name) '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport pandas as pd\nimport json\nimport os,sys\nfrom appbe import help_Text as ht\n\ndef save(request):\n from appbe.dataPath import DEFAULT_FILE_PATH\n \n if request.method == 'POST':\n submittype = request.POST.get('AdvanceSubmit')\n if submittype != 'AdvanceDefault':\n configFile = request.session['config_json']\n f = open(configFile, \"r+\")\n configSettingsData = f.read()\n configSettings = json.loads(configSettingsData)\n try:\n if configSettings['basic']['analysisType']['llmFineTuning'].lower() == 'false':\n numericselectedmethod = request.POST.get('numericfillmethod')\n for x in list(configSettings['advance']['profiler']['numericalFillMethod'].keys()):\n configSettings['advance']['profiler']['numericalFillMethod'][x] = 'False'\n configSettings['advance']['profiler']['numericalFillMethod'][numericselectedmethod] = 'True'\n \n categoricalselectedmethod = request.POST.get('categorialfillmethod')\n for x in list(configSettings['advance']['profiler']['categoricalFillMethod'].keys()):\n configSettings['advance']['profiler']['categoricalFillMethod'][x] = 'False'\n configSettings['advance']['profiler']['categoricalFillMethod'][categoricalselectedmethod] = 'True'\n\n categoryEncodingMethod = request.POST.get('categoryencoding')\n for x in list(configSettings['advance']['profiler']['categoryEncoding'].keys()):\n configSettings['advance']['profiler']['categoryEncoding'][x] = 'False'\n configSettings['advance']['profiler']['categoryEncoding'][categoryEncodingMethod] = 'True'\n \n outlierDetection = request.POST.get('outlierDetection')\n \n for x in list(configSettings['advance']['profiler']['outlierDetection'].keys()):\n configSettings['advance']['profiler']['outlierDetection'][x] = 'False'\n if outlierDetection != 'Disable':\n configSettings['advance']['profiler']['outlierDetection'][outlierDetection] = 'True'\n \n #configSettings['advance']['profiler']['outlierDetectionStatus'] = request.POST.get('AnamolyDetectionStatus')\n #configSettings['advance']['profiler']['outlierDetectionMethod'] = request.POST.get('AnaTreatmentMethod')\n configSettings['advance']['profiler']['misValueRatio'] = request.POST.get('MisValueRatio')\n #configSettings['advance']['profiler']['categoricalToNumeric'] = request.POST.get('CategoricalToNumeric')\n configSettings['advance']['profiler']['numericFeatureRatio'] = request.POST.get('NumFeatureRatio')\n configSettings['advance']['profiler']['categoryMaxLabel'] = request.POST.get('CatMaxLabels')\n configSettings['advance']['selector']['categoryMaxLabel'] = request.POST.get('CatMaxLabels')\n normalizationtypes = configSettings['advance']['profiler']['normalization']\n for k in normalizationtypes.keys():\n configSettings['advance']['profiler']['normalization'][k] = 'False'\n if request.POST.get('NormalizationMethod').lower() != 'none':\n configSettings['advance']['profiler']['normalization'][request.POST.get('NormalizationMethod')] = 'True'\n #configSettings['advance']['profiler']['normalizationMethod'] = request.POST.get('NormalizationMethod')\n configSettings['advance']['profiler']['removeDuplicate'] = request.POST.get('removeDuplicate')\n # ---------------------------------------------- Debiasing Changes ----------------------------------------------\n configSettings['advance']['profiler']['deBiasing']['FeatureName'] = request.POST.get('InputFeature')\n configSettings['advance']['profiler']['deBiasing']['ClassName'] = request.POST.get('InputClass')\n configSettings['advance']['profiler']['deBiasing']['Algorithm'] = request.POST.get('InputAlgorithm')\n configSettings['advance']['profiler']['deBiasing']['TargetFeature'] = configSettings['basic']['targetFeature']\n # ---------------------------------------------- ----------------------------------------------\n problemtypes = configSettings['basic']['analysisType'] \n problem_type = \"\"\n for k in problemtypes.keys():\n if configSettings['basic']['analysisType'][k] == 'True':\n problem_type = k\n break \n if configSettings['basic']['analysisType']['llmFineTuning'].lower() == 'false' and configSettings['basic']['onlineLearning'].lower() == 'false' and configSettings['basic']['distributedLearning'].lower() == 'false':\n configSettings['advance']['profiler']['textCleaning']['removeNoise'] = request.POST.get('noiseStatus')\n \n # -------------------------------- 12301:Remove Noise Config related Changes S T A R T --------------------------------\n if request.POST.get('noiseStatus') == 'True':\n configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['decodeHTML'] = request.POST.get('DecodeHTML')\n configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeHyperLinks'] = request.POST.get('removeHyperlinks')\n configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeMentions'] = request.POST.get('RemoveMentions')\n configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeHashtags'] = request.POST.get('removeHashtags')\n configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeEmoji'] = request.POST.get('removeEmoji')\n configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['unicodeToAscii'] = request.POST.get('unicodeToAscii')\n configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeNonAscii'] = request.POST.get('removeNonAscii')\n else:\n configSettings['advance']['profiler']['textCleaning", "instruction": "", "output": "" }, { "input": "']['removeNoiseConfig']['decodeHTML'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeHyperLinks'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeMentions'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeHashtags'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeEmoji'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['unicodeToAscii'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['removeNoiseConfig']['removeNonAscii'] = \"False\"\n # ---------------------------------------------------------------- E N D ----------------------------------------------------------------\n \n configSettings['advance']['profiler']['textCleaning']['expandContractions'] = request.POST.get(\n 'expandContractions')\n configSettings['advance']['profiler']['textCleaning']['normalize'] = request.POST.get('normalize')\n if (request.POST.get('normalizeMethod') == 'Lemmatization'):\n configSettings['advance']['profiler']['textCleaning']['normalizeMethod']['lemmatization'] = \"True\"\n configSettings['advance']['profiler']['textCleaning']['normalizeMethod']['stemming'] = \"False\"\n else:\n configSettings['advance']['profiler']['textCleaning']['normalizeMethod']['stemming'] = \"True\"\n configSettings['advance']['profiler']['textCleaning']['normalizeMethod']['lemmatization'] = \"False\"\n\n configSettings['advance']['profiler']['textCleaning']['replaceAcronym'] = request.POST.get('replaceAcronym')\n if request.POST.get('acronymDict') != '' and request.POST.get('acronymDict') != 'None':\n configSettings['advance']['profiler']['textCleaning']['acronymConfig']['acronymDict'] = eval(request.POST.get(\n 'acronymDict'))\n configSettings['advance']['profiler']['textCleaning']['correctSpelling'] = request.POST.get(\n 'correctSpelling')\n configSettings['advance']['profiler']['textCleaning']['removeStopwords'] = request.POST.get(\n 'removeStopwords')\n if (request.POST.get('ExtendOrReplace') == 'NA'):\n configSettings['advance']['profiler']['textCleaning']['stopWordsConfig']['extend'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['stopWordsConfig']['replace'] = \"False\"\n elif (request.POST.get('ExtendOrReplace') == 'Extend'):\n configSettings['advance']['profiler']['textCleaning']['stopWordsConfig']['extend'] = \"True\"\n configSettings['advance']['profiler']['textCleaning']['stopWordsConfig']['replace'] = \"False\"\n else:\n configSettings['advance']['profiler']['textCleaning']['stopWordsConfig']['extend'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['stopWordsConfig']['replace'] = \"True\"\n\n configSettings['advance']['profiler']['textCleaning']['stopWordsConfig'][\n 'stopwordsList'] = request.POST.get('stopwordsList')\n configSettings['advance']['profiler']['textCleaning']['removePunctuation'] = request.POST.get(\n 'removePunctuation')\n configSettings['advance']['profiler']['textCleaning']['removePunctuationConfig'][\n 'removePuncWithinTokens'] = request.POST.get('removePuncWithinTokens')\n configSettings['advance']['profiler']['textCleaning']['removeNumericTokens'] = request.POST.get(\n 'removeNumericTokens')\n configSettings['advance']['profiler']['textCleaning']['removeNumericConfig'][\n 'removeNumeric_IncludeSpecialCharacters'] = request.POST.get('removeNumeric_IncludeSpecialCharacters')\n\n if (request.POST.get('tokenizationLib') == 'nltk'):\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['nltk'] = \"True\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][\n 'textblob'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['spacy'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['keras'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][\n 'gensim'] = \"False\"\n elif (request.POST.get('tokenizationLib') == 'textblob'):\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['nltk'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][\n 'textblob'] = \"True\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['spacy'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['keras'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][\n 'gensim'] = \"False\"\n elif (request.POST.get('tokenizationLib') == 'spacy'):\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['nltk'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][\n 'textblob'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['spacy'] = \"True\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['keras'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][\n 'gensim'] = \"False\"\n elif (request.POST.get('tokenizationLib') == 'keras'):\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['nltk'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][\n 'textblob'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['spacy'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['keras'] = \"True\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][\n 'gensim'] = \"False\"\n\n else:\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['nltk'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib'][\n 'textblob'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['spacy'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['keras'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['tokenizationLib']['gensim'] = \"True\"\n\n if (request.POST.get('lemmatizationLib') == 'nltk'):\n configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib']['nltk'] = \"True\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib'][\n 'textblob'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib'][\n 'spacy'] = \"False\"\n\n elif (request.POST.get('lemmatizationLib') == 'textblob'):\n configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib']['nltk'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib'][\n 'textblob'] = \"True\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib'][\n 'spacy'] = \"False\"\n\n else:\n configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib']['nltk'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib'][\n 'textblob'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['lemmatizationLib']['spacy'] = \"True\"\n\n if (request.POST.get('stopwordsRemovalLib') == 'nltk'):\n configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][\n 'nltk'] = \"True\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][\n 'gensim'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][\n 'spacy'] = \"False\"\n\n elif (request.POST.get('stopwordsRemovalLib') == 'gensim'):\n configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][\n 'nltk'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][\n 'gensim'] = \"True\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][\n 'spacy'] = \"False\"\n\n else:\n configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][\n 'nltk'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][\n 'gensim'] = \"False\"\n configSettings['advance']['profiler']['textCleaning']['libConfig']['stopwordsRemovalLib'][\n 'spacy'] = \"True\"\n configSettings['advance']['profiler']['textFeatureExtraction']['n_grams'] = request.POST.get('n_grams')\n configSettings['advance']['profiler']['textFeatureExtraction']['n_grams_config'][\n 'min_n'] = int(request.POST.get('range_min_n'))\n configSettings['advance']['profiler']['textFeatureExtraction']['n_grams_config'][\n 'max_n'] = int(request.POST.get('range_max_n'))\n configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags'] = request.POST.get('pos_tags')\n \n if (request.POST.get('pos_tags_lib') == 'nltk'):\n configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['nltk'] = \"True\"\n configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['textblob'] = \"False\"\n configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['spacy'] = \"False\"\n\n elif (request.POST.get('pos_tags_lib') == 'textblob'):\n configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['nltk'] = \"False\"\n configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['textblob'] = \"True\"\n configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['spacy'] = \"False\"\n\n else:\n configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['nltk'] = \"False\"\n configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['textblob'] = \"False\"\n configSettings['advance']['profiler']['textFeatureExtraction']['pos_tags_lib']['spacy'] = \"True\"\n textconvertionmethods = configSettings['advance']['profiler']['textConversionMethod']\n for k in textconvertionmethods.keys():\n configSettings['advance']['profiler']['textConversionMethod'][k] = 'False'\n if problem_type.lower() not in ['similarityidentification','contextualsearch']:\n configSettings['advance']['profiler']['textConversionMethod'][request.POST.get('textConvertionMethod')] = 'True' \n if 'embeddingSize' in configSettings['advance']['profiler']:\n glove = configSettings['advance']['profiler']['embeddingSize']['Glove']\n for k in glove.keys():\n configSettings['advance']['profiler']['embeddingSize']['Glove'][k] = 'False'\n configSettings['advance']['profiler']['embeddingSize']['Glove'][request.POST.get('txtglovedimensions')] = 'True'\n fastText = configSettings['advance']['profiler']['embeddingSize']['FastText']\n for k in fastText.keys():\n configSettings['advance']['profiler']['embeddingSize']['FastText'][k] = 'False'\n configSettings['advance']['profiler']['embeddingSize']['FastText'][request.POST.get('txtFastTextdimensions')] = 'True'\n if 'LatentSemanticAnalysis' in configSettings['advance']['profiler']['embeddingSize']:\n LatentSemanticAnalysis = configSettings['advance']['profiler']['embeddingSize']['LatentSemanticAnalysis']\n for k in LatentSemanticAnalysis.keys():\n configSettings['advance']['profiler']['embeddingSize']['LatentSemanticAnalysis'][k] = 'False'\n configSettings['advance']['profiler']['embeddingSize']['LatentSemanticAnalysis'][request.POST.get('txttfidfdimensions')] = 'True'\n if 'TF_IDF' in configSettings['advance']['profiler']['embeddingSize']:\n configSettings['advance']['profiler']['embeddingSize']['TF_IDF']['maxFeatures'] = request.POST.get('tfidfmaxfeatures')\n if 'CountVectors' in configSettings['advance']['profiler']['embeddingSize']:\n configSettings['advance']['profiler']['embeddingSize']['CountVectors']['maxFeatures'] = request.POST.get('cvmaxfeatures')\n if problem_type.lower() == 'imageclassification':\n configSettings['advance']['image_config']['img_width'] = int(request.POST.get('img_width'))\n configSettings['advance']['image_config']['img_height'] = int(request.POST.get('img_height'))\n configSettings['advance']['image_config']['img_channel'] = int(request.POST.get('img_channel'))\n configSettings['advance']['image_config']['lr'] = float(request.POST.get('lr'))\n configSettings['advance']['image_config']['epochs'] = int(request.POST.get('epoch", "instruction": "", "output": "" }, { "input": "s'))\n configSettings['advance']['image_config']['test_split_ratio'] = float(request.POST.get('test_split_ratio'))\n if problem_type.lower() == \"llmfinetuning\":\n configSettings = llmadvancesettings(configSettings,request)\n\n if problem_type.lower() == 'objectdetection' or problem_type.lower() == 'imageclassification':\n configSettings['advance']['ImageAugmentation']['Enable'] = request.POST.get('advance_ImageAugmentation_Enable')\n configSettings['advance']['ImageAugmentation']['KeepAugmentedImages'] = request.POST.get('advance_ImageAugmentation_keepAugmentedImages')\n configSettings['advance']['ImageAugmentation']['Noise']['Blur'] = request.POST.get('advance_ImageAugmentation_Noise_Blur')\n configSettings['advance']['ImageAugmentation']['Noise']['Brightness'] = request.POST.get('advance_ImageAugmentation_Noise_Brightness')\n configSettings['advance']['ImageAugmentation']['Noise']['Contrast'] = request.POST.get('advance_ImageAugmentation_Noise_Contrast')\n configSettings['advance']['ImageAugmentation']['Transformation']['Flip'] = request.POST.get('advance_ImageAugmentation_Transformation_Flip')\n configSettings['advance']['ImageAugmentation']['Transformation']['Rotate'] = request.POST.get('advance_ImageAugmentation_Transformation_Rotate')\n configSettings['advance']['ImageAugmentation']['Transformation']['Shift'] = request.POST.get('advance_ImageAugmentation_Transformation_Shift')\n configSettings['advance']['ImageAugmentation']['Transformation']['Crop'] = request.POST.get('advance_ImageAugmentation_Transformation_Crop')\n configSettings['advance']['ImageAugmentation']['configuration']['Blur']['noOfImages'] = request.POST.get('noofblurimages')\n configSettings['advance']['ImageAugmentation']['configuration']['Blur']['limit'] = request.POST.get('limitblurimage')\n configSettings['advance']['ImageAugmentation']['configuration']['Brightness']['noOfImages'] = request.POST.get('noofbrightnessimages')\n configSettings['advance']['ImageAugmentation']['configuration']['Brightness']['limit'] = request.POST.get('limitbrightnessimage')\n configSettings['advance']['ImageAugmentation']['configuration']['Contrast']['noOfImages'] = request.POST.get('noofcontrastimages')\n configSettings['advance']['ImageAugmentation']['configuration']['Contrast']['limit'] = request.POST.get('limitcontrastimage')\n configSettings['advance']['ImageAugmentation']['configuration']['Flip']['noOfImages'] = request.POST.get('noofflipimages')\n configSettings['advance']['ImageAugmentation']['configuration']['Rotate']['noOfImages'] = request.POST.get('noofrotateimages')\n configSettings['advance']['ImageAugmentation']['configuration']['Shift']['noOfImages'] = request.POST.get('noofshiftimages')\n configSettings['advance']['ImageAugmentation']['configuration']['Crop']['noOfImages'] = request.POST.get('noofcropimages')\t\t\t\t\t\n\t\t\t\t\t\n configSettings['advance']['selector']['selectionMethod']['featureSelection'] = 'False'\n configSettings['advance']['selector']['selectionMethod']['featureEngineering'] = 'False'\n configSettings['advance']['selector']['featureSelection']['allFeatures'] = 'False'\n configSettings['advance']['selector']['featureSelection']['statisticalBased'] = 'False'\n configSettings['advance']['selector']['featureSelection']['modelBased'] = 'False'\n if(request.POST.get('selectionMethod') == 'FeatureSelection'):\n configSettings['advance']['selector']['selectionMethod']['featureSelection'] = 'True'\n else:\n configSettings['advance']['selector']['selectionMethod']['featureEngineering'] = 'True'\n if request.POST.get('allFeatures'):\n configSettings['advance']['selector']['featureSelection']['allFeatures'] = request.POST.get('allFeatures')\n if request.POST.get('statisticalBased'):\n configSettings['advance']['selector']['featureSelection']['statisticalBased'] = request.POST.get('statisticalBased')\n if request.POST.get('modelBased'):\n configSettings['advance']['selector']['featureSelection']['modelBased'] = request.POST.get('modelBased')\n \n dimentionalityreductionmethod = request.POST.get('dimentionalityreductionmethod')\n for x in list(configSettings['advance']['selector']['featureEngineering'].keys()):\n if x != 'numberofComponents':\n configSettings['advance']['selector']['featureEngineering'][x] = 'False'\n configSettings['advance']['selector']['featureEngineering'][dimentionalityreductionmethod] = 'True'\n \n \n configSettings['advance']['selector']['featureEngineering']['numberofComponents'] = request.POST.get('numberofComponents')\n #configSettings['advance']['selector']['categoricalFeatureRatio'] = request.POST.get('CatFeatureRatio')\n configSettings['advance']['selector']['statisticalConfig']['correlationThresholdFeatures'] = request.POST.get('correlationThresholdFeatures')\n configSettings['advance']['selector']['statisticalConfig']['correlationThresholdTarget'] = request.POST.get('correlationThresholdTarget') \n configSettings['advance']['selector']['statisticalConfig']['pValueThresholdFeatures'] = request.POST.get('pValueThresholdFeatures')\n configSettings['advance']['selector']['statisticalConfig']['pValueThresholdTarget'] = request.POST.get('pValueThresholdTarget') \n configSettings['advance']['selector']['statisticalConfig']['varianceThreshold'] = request.POST.get('VarianceThreshold')\n \n \n \n \n if problem_type.lower() == 'recommendersystem':\n configSettings['advance']['recommenderparam']['svd_params']= eval(request.POST.get('svd_params'))\n configSettings['advance']['associationrule']['modelParams']['apriori'] = eval(request.POST.get('apriori'))\n configSettings['advance']['textSimilarityConfig'] = eval(request.POST.get('textsimilarity'))\n if configSettings['basic']['distributedLearning'].lower() == 'true':\n configSettings['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['Distributed Extreme Gradient Boosting (XGBoost)'] = eval(request.POST.get('classDistributedXGBoost'))\n configSettings['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['Distributed Light Gradient Boosting (LightGBM)'] = eval(request.POST.get('classDistributedLightGBM'))\n configSettings['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['Distributed Extreme Gradient Boosting (XGBoost)'] = eval(request.POST.get('DistributedXGBoostreg'))\n configSettings['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['Distributed Light Gradient Boosting (LightGBM)'] = eval(request.POST.get('DistributedLightGBMreg')) \n if configSettings['basic']['onlineLearning'].lower() != 'true' and configSettings['basic']['distributedLearning'].lower() != 'true': \n if (problem_type.lower() == 'classification') or (problem_type.lower() == 'regression') or (problem_type.lower() == 'clustering') or (problem_type.lower() == 'topicmodelling'):\n \n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Logistic Regression'] == 'True': \n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Logistic Regression'] = eval(request.POST.get('classification_LogisticRegression'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Naive Bayes'] == 'True': \n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Naive Bayes'] = eval(request.POST.get('classification_GaussianNB'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Support Vector Machine'] == 'True': \n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Support Vector Machine'] = eval(request.POST.get('classification_SVC'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['K Nearest Neighbors'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['K Nearest Neighbors'] = eval(request.POST.get('classification_KNeighborsClassifier'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Decision Tree'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Decision Tree'] = eval(request.POST.get('classification_DecisionTreeClassifier'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Random Forest'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Random Forest'] = eval(request.POST.get('classification_RandomForestClassifier'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Gradient Boosting'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Gradient Boosting'] = eval(request.POST.get('classification_GradientBoostingClassifier'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Extreme Gradient Boosting (XGBoost)'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Extreme Gradient Boosting (XGBoost)'] = eval(request.POST.get('classification_ExtremeGradientBoostingClassifier'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Light Gradient Boosting (LightGBM)'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Light Gradient Boosting (LightGBM)'] = eval(request.POST.get('classification_LightGradientBoostingClassifier'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Categorical Boosting (CatBoost)'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Categorical Boosting (CatBoost)'] = eval(request.POST.get('classification_CategoricalBoostingClassifier'))\n \n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Linear Regression'] == 'True': \n configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Linear Regression'] = eval(request.POST.get('regression_LinearRegression'))\n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Lasso'] == 'True': \n configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Lasso'] = eval(request.POST.get('regression_Lasso'))\n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Ridge'] == 'True': \n configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Ridge'] = eval(request.POST.get('regression_Ridge'))\n \n if problem_type.lower() == 'topicmodelling' and configSettings['basic']['algorithms']['topicModelling']['LDA'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['topicModellingParams']['LDA']= eval(request.POST.get('topicmodeling_lda'))\n\n if problem_type.lower() == 'clustering' and configSettings['basic']['algorithms']['clustering']['KMeans'] == 'True': \n configSettings['advance']['mllearner_config']['modelParams']['clusteringModelParams']['KMeans']= eval(request.POST.get('cluster_kmeans'))\n if problem_type.lower() == 'clustering' and configSettings['basic']['algorithms']['clustering']['DBSCAN'] == 'True': \n configSettings['advance']['mllearner_config']['modelParams']['clusteringModelParams']['DBSCAN']= eval(request.POST.get('cluster_DBSCAN'))\n \n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Decision Tree'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Decision Tree'] = eval(request.POST.get('regression_DecisionTreeRegressor'))\n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Random Forest'] == 'True': \n configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Random Forest'] = eval(request.POST.get('regression_RandomForestRegressor'))\n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Extreme Gradient Boosting (XGBoost)'] == 'True': \n configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Extreme Gradient Boosting (XGBoost)'] = eval(request.POST.get('regression_XGBoostRegressor'))\n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Light Gradient Boosting (LightGBM)'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Light Gradient Boosting (LightGBM)'] = eval(request.POST.get('regression_LightGBMRegressor'))\n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Categorical Boosting (CatBoost)'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Categorical Boosting (CatBoost)'] = eval(request.POST.get('regression_CatBoostRegressor'))\n configSettings['advance']['mllearner_config']['modelparamsfile'] = request.POST.get('ModelParamFile')\n configSettings['advance']['mllearner_config']['optimizationMethod'] = request.POST.get('OptimizationMethod')\n configSettings['advance']['mllearner_config']['optimizationHyperParameter'][\n 'iterations'] = request.POST.get('iterations')\n configSettings['advance']['mllearner_config']['optimizationHyperParameter'][\n 'trainTestCVSplit'] = request.POST.get('trainTestCVSplit')\n configSettings['advance']['mllearner_config']['thresholdTunning'] = request.POST.get('thresholdTunning')\n configSettings['advance']['mllearner_config']['Stacking (Ensemble)'] = request.POST.get('EnsembleStacking')\n configSettings['advance']['mllearner_config']['Voting (Ensemble)'] = request.POST.get('EnsembleVoting')\n \n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Logistic Regression']['enable'] = request.POST.get('ensemple_bagging_", "instruction": "", "output": "" }, { "input": "lr_enable')\n if configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Logistic Regression']['enable'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Logistic Regression']['param'] = eval(request.POST.get('classi_ensemple_bagging_lr_param'))\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Naive Bayes']['enable'] = request.POST.get('ensemple_bagging_naivebayes_enable')\n if configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Naive Bayes']['enable'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Naive Bayes']['param'] = eval(request.POST.get('classi_ensemple_bagging_naivebayes_param'))\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Support Vector Machine']['enable'] = request.POST.get('ensemple_bagging_svm_enable')\n if configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Support Vector Machine']['enable'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Support Vector Machine']['param'] = eval(request.POST.get('classi_ensemple_bagging_svm_param'))\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['K Nearest Neighbors']['enable'] = request.POST.get('ensemple_bagging_knn_enable')\n if configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['K Nearest Neighbors']['enable'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['K Nearest Neighbors']['param'] = eval(request.POST.get('classi_ensemple_bagging_knn_param')) \n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Decision Tree']['enable'] = request.POST.get('ensemple_bagging_dt_enable')\n if configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Decision Tree']['enable'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Decision Tree']['param'] = eval(request.POST.get('classi_ensemple_bagging_dt_param')) \n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Random Forest']['enable'] = request.POST.get('ensemple_bagging_rf_enable')\n if configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Random Forest']['enable'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']['Random Forest']['param'] = eval(request.POST.get('classi_ensemple_bagging_rf_param'))\n configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Linear Regression']['enable'] = request.POST.get('ensemple_bagging_lir_enable')\n if configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Linear Regression']['enable'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Linear Regression']['param'] = eval(request.POST.get('reg_ensemple_bagging_lir_param'))\n configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Decision Tree']['enable'] = request.POST.get('ensemple_bagging_dit_enable')\n if configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Decision Tree']['enable'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Decision Tree']['param'] = eval(request.POST.get('reg_ensemple_bagging_dit_param'))\n configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Ridge']['enable'] = request.POST.get('ensemple_bagging_ridge_enable')\n if configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Ridge']['enable'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']['Ridge']['param'] = eval(request.POST.get('reg_ensemple_bagging_ridge_param'))\n if problem_type.lower() == 'classification':\n if configSettings['advance']['mllearner_config']['Stacking (Ensemble)'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['classifierModelParams']['Stacking (Ensemble)'] = eval(request.POST.get('ensamblestackingClassifierparams'))\n if problem_type.lower() == 'regression':\n if configSettings['advance']['mllearner_config']['Stacking (Ensemble)'] == 'True':\n configSettings['advance']['mllearner_config']['modelParams']['regressorModelParams']['Stacking (Ensemble)'] = eval(request.POST.get('ensamblestackingRegressorparams'))\n configSettings['basic']['filterExpression'] = request.POST.get('filterExpression')\n #configSettings['advance']['mllearner_config']['trainPercentage'] = request.POST.get('trainPercentage')\n \n if (problem_type.lower() == 'classification') or (problem_type.lower() == 'regression'):\n configSettings['advance']['modelEvaluation']['smcStrategy'] = request.POST.get('smcStrategy')\n configSettings['advance']['modelEvaluation']['smcMaxDepth'] = request.POST.get('smcMaxDepth')\n configSettings['advance']['modelEvaluation']['smcCondition'] = request.POST.get('smcCondition')\n configSettings['advance']['modelEvaluation']['miCondition'] = request.POST.get('miCondition')\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Neural Network'] == 'True':\n configSettings['advance']['dllearner_config']['modelParams']['classifierModelParams']['Neural Network'] = eval(\n request.POST.get('dl_classification_SNN'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Recurrent Neural Network'] == 'True': \n configSettings['advance']['dllearner_config']['modelParams']['classifierModelParams']['Recurrent Neural Network'] = eval(\n request.POST.get('dl_classification_RNN'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Recurrent Neural Network (GRU)'] == 'True':\n configSettings['advance']['dllearner_config']['modelParams']['classifierModelParams']['Recurrent Neural Network (GRU)'] = eval(\n request.POST.get('dl_classification_GRURNN'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Recurrent Neural Network (LSTM)'] == 'True':\n configSettings['advance']['dllearner_config']['modelParams']['classifierModelParams']['Recurrent Neural Network (LSTM)'] = eval(\n request.POST.get('dl_classification_LSTMRNN'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Convolutional Neural Network (1D)'] == 'True':\n configSettings['advance']['dllearner_config']['modelParams']['classifierModelParams']['Convolutional Neural Network (1D)'] = eval(\n request.POST.get('dl_classification_CNN'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification'].get('Neural Architecture Search') == 'True':\n configSettings['advance']['dllearner_config']['modelParams']['classifierModelParams']['Neural Architecture Search'] = eval(\n request.POST.get('dl_classification_NAS'))\n \n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Neural Network'] == 'True':\n configSettings['advance']['dllearner_config']['modelParams']['regressorModelParams']['Neural Network'] = eval(\n request.POST.get('dl_regression_SNN'))\n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Recurrent Neural Network'] == 'True':\n configSettings['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network'] = eval(\n request.POST.get('dl_regression_RNN'))\n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Recurrent Neural Network (GRU)'] == 'True': \n configSettings['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network (GRU)'] = eval(\n request.POST.get('dl_regression_GRURNN'))\n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Recurrent Neural Network (LSTM)'] == 'True': \n configSettings['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network (LSTM)'] = eval(\n request.POST.get('dl_regression_LSTMRNN'))\n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Convolutional Neural Network (1D)'] == 'True': \n configSettings['advance']['dllearner_config']['modelParams']['regressorModelParams']['Convolutional Neural Network (1D)'] = eval(\n request.POST.get('dl_regression_CNN'))\n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression'].get('Neural Architecture Search') == 'True': \n configSettings['advance']['dllearner_config']['modelParams']['regressorModelParams']['Neural Architecture Search'] = eval(\n request.POST.get('dl_regression_NAS'))\n #configSettings['advance']['dllearner_config']['optimizationMethod'] = request.POST.get('DLOptimizationMethod')\n else:\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Online Logistic Regression'] == 'True': \n configSettings['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online Logistic Regression'] = eval(request.POST.get('OnlineLogisticRegression'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Online Decision Tree Classifier'] == 'True': \n configSettings['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online Decision Tree Classifier'] = eval(request.POST.get('OnlineDecisionTreeClassifier'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Online Softmax Regression'] == 'True':\n configSettings['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online Softmax Regression'] = eval(request.POST.get('OnlineSoftmaxRegression'))\n if problem_type.lower() == 'classification' and configSettings['basic']['algorithms']['classification']['Online KNN Classifier'] == 'True':\n configSettings['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online KNN Classifier'] = eval(request.POST.get('OnlineKNNClassifier')) \n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Online Linear Regression'] == 'True': \n configSettings['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['Online Linear Regression'] = eval(request.POST.get('OnlineLinearRegression'))\n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Online Decision Tree Regressor'] == 'True':\n configSettings['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['Online Decision Tree Regressor'] = eval(request.POST.get('OnlineDecisionTreeRegressor')) \n if problem_type.lower() == 'regression' and configSettings['basic']['algorithms']['regression']['Online KNN Regressor'] == 'True':\n configSettings['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['Online KNN Regressor'] = eval(request.POST.get('OnlineKNNRegressor')) \n configSettings['advance']['profiler']['targetEncodingParams'] = eval(request.POST.get('targetEncodingParams')) \n configSettings['advance']['profiler']['outlierDetectionParams'] = eval(request.POST.get('outlierDetectionParams'))\n \n if problem_type.lower() == 'objectdetection':\n configSettings['advance']['objectDetection']['pretrainedModel']= request.POST.get('objectdetectionpretrainedmodel')\n configSettings['advance']['objectDetection']['n_epoch'] = int(request.POST.get('objectDetection_n_epoch'))\n configSettings['advance']['objectDetection']['batch_size'] = int(request.POST.get('objectDetection_batch_size'))\n \n if problem_type.lower() == 'timeseriesforecasting': #task 11997 #task 13052\n\n configSettings['advance']['timeSeriesForecasting']['fix_seasonality'] = request.POST.get('seasionality') # task 13052\n configSettings['advance']['timeSeriesForecasting']['fix_stationarity'] =request.POST.get('stationarity') # task 13052\n configSettings['advance']['timeSeriesForecasting']['modelParams']['ARIMA'] = eval(request.POST.get('ARIMA')) #task 11997\n configSettings['advance']['timeSeriesForecasting']['modelParams']['FBPROPHET'] = eval(request.POST.get('FBPROPHET')) #task 11997\n configSettings['advance']['timeSeriesForecasting']['modelParams']['LSTM'] = eval(request.POST.get('TSLSTM')) #task 11997\n configSettings['advance']['timeSeriesForecasting']['modelParams']['Encoder_Decoder_LSTM_MVI_UVO'] = eval(request.POST.get('TSLSTMencoderdecoder'))\n configSettings['advance']['timeSeriesForecasting']['modelParams']['MLP'] = eval(request.POST.get('TSMLP')) #task 11997\n\n if problem_type.lower() == 'timeseriesan", "instruction": "", "output": "" }, { "input": "omalydetection':\n configSettings['advance']['timeSeriesAnomalyDetection']['modelParams']['AutoEncoder'] = eval(request.POST.get('autoEncoderAD')) #task 11997\n configSettings['advance']['timeSeriesAnomalyDetection']['modelParams']['DBScan'] = eval(request.POST.get('dbscanAD')) #task 13316\n if problem_type.lower() == 'anomalydetection':\n configSettings['advance']['anomalyDetection']['modelParams']['IsolationForest'] = eval(request.POST.get('IsolationForest'))\n configSettings['advance']['anomalyDetection']['modelParams']['oneclassSVM'] = eval(request.POST.get('oneclassSVM'))\n configSettings['advance']['anomalyDetection']['modelParams']['DBScan'] = eval(request.POST.get('DBScanAD'))\t\t\t\t\t\n\n\n\n updatedConfigSettingsJson = json.dumps(configSettings)\n f.seek(0)\n f.write(updatedConfigSettingsJson)\n f.truncate()\n f.close()\n errormsg = 'NA' \n request.session['ModelStatus'] = 'Not Trained' \n except Exception as e:\n import sys\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno)) \n errormsg = 'Input value error'\n print(e)\n \n if 'NoOfRecords' in request.session:\n records = request.session['NoOfRecords']\n else:\n records = 'NA'\n if request.session['datatype'] in ['Video', 'Image','Document']:\n folderLocation = str(request.session['datalocation'])\n dataFilePath = os.path.join(folderLocation, request.session['csvfullpath'])\n else:\n dataFilePath = str(request.session['datalocation'])\n # dataFilePath = configSettings['basic']['dataLocation']\n #df = pd.read_csv(dataFilePath, encoding='latin1')\n featuresList = configSettings['basic']['featureList']\n\n config = {}\n config['modelName'] = configSettings['basic']['modelName']\n config['modelVersion'] = configSettings['basic']['modelVersion']\n config['datetimeFeatures'] = configSettings['basic']['dateTimeFeature']\n config['sequenceFeatures'] = configSettings['basic']['indexFeature']\n config['FeaturesList'] = featuresList\n config['unimportantFeatures'] = list(set(featuresList) - set(configSettings['basic']['trainingFeatures']))\n config['targetFeature'] = configSettings['basic']['targetFeature']\n scoring = configSettings['basic']['scoringCriteria'] \n scoringCriteria = \"\"\n for k in scoring.keys():\n if configSettings['basic']['scoringCriteria'][k] == 'True':\n scoringCriteria = k\n break\n config['scoringCriteria'] = scoringCriteria\n\n temp = {}\n temp['ModelName'] = configSettings['basic']['modelName']\n temp['Version'] = configSettings['basic']['modelVersion']\n selected_use_case = request.session['UseCaseName']\n ModelVersion = request.session['ModelVersion']\n ModelStatus = request.session['ModelStatus']\n context = {'tab': 'advconfig', 'config': config, 'temp': temp, 'advconfig': configSettings,\n 'noOfRecords': records, 'advance_status_msg': 'Configuration Done',\n 'selected_use_case': selected_use_case, 'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion,'errormsg':errormsg,\n 'currentstate': request.session['currentstate'], 'finalstate': request.session['finalstate'],\n 'selected': 'modeltraining'}\n return context\n elif submittype == 'AdvanceDefault':\n try:\n MachineLearningModels = []\n configFile = os.path.join(DEFAULT_FILE_PATH, 'aion_config.json')\n f = open(configFile, \"r\")\n configSettings = f.read()\n f.close()\n updatedConfigFile = request.session['config_json']\n f = open(updatedConfigFile, \"r+\")\n configSettingsData = f.read()\n updateconfigSettingsJson = json.loads(configSettingsData)\n configSettingsJson = json.loads(configSettings)\n temp = {}\n temp['ModelName'] = request.session['UseCaseName']\n temp['Version'] = request.session['ModelVersion']\n config = {}\n config['modelName'] = request.session['UseCaseName']\n config['modelVersion'] = request.session['ModelVersion']\n config['datetimeFeatures'] = updateconfigSettingsJson['basic']['dateTimeFeature']\n config['sequenceFeatures'] = updateconfigSettingsJson['basic']['indexFeature']\n config['FeaturesList'] = updateconfigSettingsJson['basic']['trainingFeatures']\n config['unimportantFeatures'] = ''\n config['targetFeature'] = updateconfigSettingsJson['basic']['targetFeature']\n problemtypes = updateconfigSettingsJson['basic']['analysisType'] \n problem_type = \"\"\n for k in problemtypes.keys():\n if updateconfigSettingsJson['basic']['analysisType'][k] == 'True':\n problem_type = k\n break\n selectAlgo = \"\"\n if problem_type in ['classification','regression','timeSeriesForecasting',\n 'timeSeriesAnomalyDetection',\n 'recommenderSystem','clustering','anomalyDetection','topicModelling','survivalAnalysis','videoForecasting','imageClassification','objectDetection','stateTransition']: #task 11997\n for key in updateconfigSettingsJson['basic']['algorithms'][problem_type]:\n if updateconfigSettingsJson['basic']['algorithms'][problem_type][key] == 'True':\n if selectAlgo != \"\":\n selectAlgo += ','\n selectAlgo += key \n if problem_type not in ['classification','regression']:\n break\n for key in updateconfigSettingsJson['basic']['algorithms'][problem_type]:\n if updateconfigSettingsJson['basic']['algorithms'][problem_type][key] == 'True': \n MachineLearningModels.append(key)\n if problem_type == 'objectDetection':\n from AION import pretrainedModels\n ptmObj = pretrainedModels()\n obModels = ptmObj.get_info(selectAlgo)\n else:\n obModels = {}\n \n problemType = problem_type\n selected_use_case = request.session['UseCaseName']\n ModelVersion = request.session['ModelVersion']\n ModelStatus = request.session['ModelStatus']\n request.session['currentstate'] = 2\n if request.session['finalstate'] <= 2:\n request.session['finalstate'] = 2\n outlierDetection = 'False'\n updateconfigSettingsJson['advance'] = configSettingsJson['advance']\n for x in list(updateconfigSettingsJson['advance']['profiler']['outlierDetection'].keys()):\n if updateconfigSettingsJson['advance']['profiler']['outlierDetection'][x] == 'True':\n outlierDetection = 'True'\n if outlierDetection == 'False':\n updateconfigSettingsJson['advance']['profiler']['outlierDetection']['Disable'] = 'True' \n else:\n updateconfigSettingsJson['advance']['profiler']['outlierDetection']['Disable'] = 'False'\n updateconfigSettingsJson = advanceConfigfields(updateconfigSettingsJson)\n #print(configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['ExtremeGradientBoostingClassifier'])\n updateconfigSettingsJson['advance']['profiler']['normalizationMethod'] = 'None'\n normalizationtypes = updateconfigSettingsJson['advance']['profiler']['normalization']\n for k in normalizationtypes.keys():\n if updateconfigSettingsJson['advance']['profiler']['normalization'][k] == 'True':\n updateconfigSettingsJson['advance']['profiler']['normalizationMethod'] = k\n break\n\n \n #---------------- default Hypermarameter changes--- ----------Usnish--------------\n hyperparamFile = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','config', 'hyperparam_config.json'))\n with open(hyperparamFile) as json_file:\n hyperparamConfig = json.load(json_file)\n context = {'tab': 'advconfig','temp': temp,'advconfig': updateconfigSettingsJson,\n 'config': config, 'selected_use_case': selected_use_case,'MachineLearningModels':MachineLearningModels,\n 'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion,\"obModels\":obModels,\"problemType\":problemType,\n 'currentstate': request.session['currentstate'], 'finalstate': request.session['finalstate'],\n 'selected': 'modeltraning','advance_help':ht.advance_help,'hyperparamConfig':hyperparamConfig}\n return context\n except Exception as e:\n print(e)\ndef llmadvancesettings(configSettings,request):\n algo = ''\n for x in list(configSettings['basic']['algorithms']['llmFineTuning'].keys()):\n if configSettings['basic']['algorithms']['llmFineTuning'][x] == 'True':\n algo = x\n \n if algo == 'LLaMA-2':\n configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2']['fineTuningMethod'] = request.POST.get('llama2fullfinemethod')\n configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2']['epochs'] = request.POST.get('llama2epochs')\n configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2']['learning_rate'] = request.POST.get('llama2learningrate')\n if request.POST.get('llama2fullfinemethod') != 'Full Fine-Tuning':\n configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2']['lora_rank'] = request.POST.get('llama2lorarank')\n configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2']['lora_alpha'] = request.POST.get('llama2loraalpha')\n if algo == 'LLaMA-2-Chat':\n configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2-Chat']['fineTuningMethod'] = request.POST.get('llama2chatfullfinemethod')\n configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2-Chat']['epochs'] = request.POST.get('llmllama2chatepochs')\n configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2-Chat']['learning_rate'] = request.POST.get('llama2chatlearningrate')\n if request.POST.get('llama2chatfullfinemethod') != 'Full Fine-Tuning':\n configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2-Chat']['lora_rank'] = request.POST.get('llama2chatlorarank')\n configSettings['advance']['llmFineTuning']['modelParams']['LLaMA-2-Chat']['lora_alpha'] = request.POST.get('llama2chatloraalpha')\n if algo == 'CodeLLaMA-2':\n configSettings['advance']['llmFineTuning']['modelParams']['CodeLLaMA-2']['fineTuningMethod'] = request.POST.get('CodeLLaMA2fullfinemethod')\n configSettings['advance']['llmFineTuning']['modelParams']['CodeLLaMA-2']['epochs'] = request.POST.get('CodeLLaMA2epochs')\n configSettings['advance']['llmFineTuning']['modelParams']['CodeLLaMA-2']['learning_rate'] = request.POST.get('CodeLLaMA2learningrate')\n if request.POST.get('CodeLLaMA2fullfinemethod') != 'Full Fine-Tuning':\n configSettings['advance']['llmFineTuning']['modelParams']['CodeLLaMA-2']['lora_rank'] = request.POST.get('CodeLLaMA2lorarank')\n configSettings['advance']['llmFineTuning']['modelParams']['CodeLLaMA-2']['lora_alpha'] = request.POST.get('CodeLLaMA2loraalpha') \n if algo == 'Falcon':\n configSettings['advance']['llmFineTuning']['modelParams']['Falcon']['fullFineTuning'] = request.POST.get('falconfullfinetuning')\n configSettings['advance']['llmFineTuning']['modelParams']['Falcon']['epochs'] = request.POST.get('falconepochs')\n configSettings['advance']['llmFineTuning']['modelParams']['Falcon']['learning_rate'] = request.POST.get('falconlearningrate')\n configSettings['advance']['llmFineTuning']['modelParams']['Falcon']['lora_rank'] = request.POST.get('falconlorarank')\n configSettings['advance']['llmFineTuning']['modelParams']['Falcon']['lora_alpha'] = request.POST.get('falconloraalpha')\n \n \n \n \n return configSettings\n\ndef advanceConfigfields(configSettingsJson):\n try:\n configSettingsJson['advance']['mllearner_config']['EnsembleStacking'] = \\\\\n configSettingsJson['advance']['mllearner_config']['Stacking (Ensemble)']\n configSettingsJson['advance']['mllearner_config']['EnsembleVoting'] = \\\\\n configSettingsJson['advance']['mllearner_config']['Voting (Ensemble)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][\n 'LogisticRegression'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Logistic Regression']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['GaussianNB'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Naive Bayes']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['SVC'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][\n 'Support Vector Machine']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][\n 'KNeighborsClassifier'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['K Nearest Neighbors']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][\n 'DecisionTreeClassifier'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Decision Tree']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][\n 'RandomForestClassifier'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Random Forest']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][\n 'GradientBoostingClassifier'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Gradient Boosting']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][\n 'ExtremeGradientBoostingClassifier'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][\n 'Extreme Gradient Boosting (XGBoost)']\n configSettingsJson['advance']['mllearner_config']['", "instruction": "", "output": "" }, { "input": "modelParams']['classifierModelParams'][\n 'LightGradientBoostingClassifier'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][\n 'Light Gradient Boosting (LightGBM)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][\n 'CategoricalBoostingClassifier'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams'][\n 'Categorical Boosting (CatBoost)']\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['SNN'] = \\\\\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['Neural Network']\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['SimpleRNN'] = \\\\\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams'][\n 'Recurrent Neural Network']\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['GRURNN'] = \\\\\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams'][\n 'Recurrent Neural Network (GRU)']\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['LSTMRNN'] = \\\\\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams'][\n 'Recurrent Neural Network (LSTM)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleStacking'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Stacking (Ensemble)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][\n 'LogisticRegression'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][\n 'Logistic Regression']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][\n 'NaiveBayes'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][\n 'Naive Bayes']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][\n 'SVM'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][\n 'Support Vector Machine']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][\n 'KNN'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][\n 'K Nearest Neighbors']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][\n 'DecisionTree'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][\n 'Decision Tree']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][\n 'RandomForest'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging'][\n 'Random Forest']\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['SimpleRNN'] = \\\\\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][\n 'Recurrent Neural Network']\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['GRURNN'] = \\\\\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][\n 'Recurrent Neural Network (GRU)']\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['LSTMRNN'] = \\\\\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][\n 'Recurrent Neural Network (LSTM)']\n\n configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams']['DQN'] = \\\\\n configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams']['Deep Q Network']\n configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams']['DDQN'] = \\\\\n configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams'][\n 'Dueling Deep Q Network']\n configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams']['DQN'] = \\\\\n configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams']['Deep Q Network']\n configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams']['DDQN'] = \\\\\n configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams'][\n 'Dueling Deep Q Network']\n\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['CNN'] = \\\\\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams'][\n 'Convolutional Neural Network (1D)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['LinearRegression'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Linear Regression']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams'][\n 'DecisionTreeRegressor'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Decision Tree']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams'][\n 'RandomForestRegressor'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Random Forest']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['XGBoostRegressor'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams'][\n 'Extreme Gradient Boosting (XGBoost)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['LightGBMRegressor'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams'][\n 'Light Gradient Boosting (LightGBM)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['CatBoostRegressor'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams'][\n 'Categorical Boosting (CatBoost)']\n\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleStacking'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Stacking (Ensemble)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging'][\n 'LinearRegression'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging'][\n 'Linear Regression']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging'][\n 'DecisionTree'] = \\\\\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging'][\n 'Decision Tree']\n\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['NAS'] = \\\\\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][\n 'Neural Architecture Search']\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['NAS'] = \\\\\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams'][\n 'Neural Architecture Search']\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['SNN'] = \\\\\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Neural Network']\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['SimpleRNN'] = \\\\\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][\n 'Recurrent Neural Network']\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['GRURNN'] = \\\\\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][\n 'Recurrent Neural Network (GRU)']\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['LSTMRNN'] = \\\\\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][\n 'Recurrent Neural Network (LSTM)']\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['CNN'] = \\\\\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'][\n 'Convolutional Neural Network (1D)']\n\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][\n 'OnlineLogisticRegression'] = \\\\\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][\n 'Online Logistic Regression']\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][\n 'OnlineDecisionTreeClassifier'] = \\\\\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][\n 'Online Decision Tree Classifier']\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][\n 'OnlineSoftmaxRegression'] = \\\\\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][\n 'Online Softmax Regression']\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][\n 'OnlineKNNClassifier'] = \\\\\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams'][\n 'Online KNN Classifier']\n\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams'][\n 'OnlineLinearRegression'] = \\\\\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams'][\n 'Online Linear Regression']\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams'][\n 'OnlineDecisionTreeRegressor'] = \\\\\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams'][\n 'Online Decision Tree Regressor']\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams'][\n 'OnlineKNNRegressor'] = \\\\\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams'][\n 'Online KNN Regressor']\n\n configSettingsJson['advance']['profiler']['textConversionMethod']['LatentSemanticAnalysis'] = \\\\\n configSettingsJson['advance']['profiler']['textConversionMethod']['LatentSemanticAnalysis']\n configSettingsJson['advance']['profiler']['embeddingSize']['LatentSemanticAnalysis'] = \\\\\n configSettingsJson['advance']['profiler']['embeddingSize']['LatentSemanticAnalysis']\n if 'llmFineTuning' in configSettingsJson['advance']:\n configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA2'] = \\\\\n configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA-2']\n configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA2Chat'] = \\\\\n configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA-2-Chat']\n configSettingsJson['basic']['algorithms']['llmFineTuning']['CodeLLaMA2'] = \\\\\n configSettingsJson['basic']['algorithms']['llmFineTuning']['CodeLLaMA-2']\n\n configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA2'] = \\\\\n configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA-2']\n configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA2Chat'] = \\\\\n configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA-2-Chat']\n configSettingsJson['advance']['llmFineTuning']['modelParams']['CodeLLaMA2'] = \\\\\n configSettingsJson['advance']['llmFineTuning']['modelParams']['CodeLLaMA-2']\n\n configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA2'] = \\\\\n configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA-2']\n configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA2Chat'] = \\\\\n configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA-2-Chat']\n configSettingsJson['basic']['modelSize']['llmFineTuning']['CodeLLaMA2'] = \\\\\n configSettingsJson['basic']['modelSize']['llmFineTuning']['CodeLLaMA-2']\n\n if 'distributedlearner_config' in configSettingsJson['advance']:\n configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams'][\n 'DistributedXGBoost'] = \\\\\n configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams'][\n 'Distributed Extreme Gradient Boosting (XGBoost)']\n configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams'][\n 'DistributedLightGBM'] = \\\\\n configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams'][\n 'Distributed Light Gradient Boosting (LightGBM)']\n\n configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams'][\n 'DistributedXGBoost'] = \\\\\n configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams'][\n 'Distributed Extreme Gradient Boosting (XGBoost)']\n configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams'][\n 'DistributedLightGBM'] = \\\\\n configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams'][\n 'Distributed Light Gradient Boosting (LightGBM)']\n\n problem_type = \"\"\n problemtypes = configSettingsJson['basic']['", "instruction": "", "output": "" }, { "input": "analysisType'] \n for k in problemtypes.keys():\n if configSettingsJson['basic']['analysisType'][k] == 'True':\n problem_type = k\n break \n deepLearning = 'False' \n machineLearning = 'False'\n reinforcementLearning = 'False'\n selectAlgo = \"\"\n if problem_type.lower() in ['classification','regression']:\n for key in configSettingsJson['basic']['algorithms'][problem_type]:\n if configSettingsJson['basic']['algorithms'][problem_type][key] == 'True':\n if key in ['Neural Network','Convolutional Neural Network (1D)','Recurrent Neural Network','Recurrent Neural Network (GRU)','Recurrent Neural Network (LSTM)','Neural Architecture Search']:\n deepLearning = 'True'\n 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)']: \n machineLearning = 'True'\n if key in ['Deep Q Network','Dueling Deep Q Network']:\n reinforcementLearning = 'True'\n elif problem_type.lower() in ['clustering','topicmodelling']:#clustering(Bug 12611)\n machineLearning = 'True' \n configSettingsJson['basic']['deepLearning'] = deepLearning\n configSettingsJson['basic']['machineLearning'] = machineLearning\n configSettingsJson['basic']['reinforcementLearning'] = reinforcementLearning\n except Exception as e:\n print(e)\n return (configSettingsJson)\n \ndef basicconfignex(request):\n #pemfilename = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','modelTraining','static','key','AION_GPU.pem'))\n try:\n updatedConfigFile = request.session['config_json']\n f = open(updatedConfigFile, \"r+\")\n configSettingsData = f.read()\n configSettingsJson = json.loads(configSettingsData)\n #---------------- default Hypermarameter changes-------------Usnish--------------\n hyperparamFile = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','config', 'hyperparam_config.json'))\n with open(hyperparamFile) as json_file:\n hyperparamConfig = json.load(json_file)\n #---------------- default Hypermarameter changes end-------------Usnish--------------\n # ------------------ Debiasing Changes ------------------\n categorical_features = []\n class_list = []\n MachineLearningModels = []\n check_traget = configSettingsJson['basic']['targetFeature']\n selectedDebiasingFeature = 'None'\n selectedDebiasingClass = 'None'\n selectedDebiasingAlgorithm = ''\n problemtypes = configSettingsJson['basic']['analysisType']\n problem_type = \"\"\n for k in problemtypes.keys():\n if configSettingsJson['basic']['analysisType'][k] == 'True':\n problem_type = k\n break\n if request.method == 'GET':\n for key in configSettingsJson['basic']['algorithms'][problem_type]:\n if configSettingsJson['basic']['algorithms'][problem_type][key] == 'True':\n MachineLearningModels.append(key)\n else:\n MachineLearningModels = request.POST.getlist('MachineLearningModels')\n if problem_type.lower() in ['classification','regression']:\n if check_traget != '':\n try:\n if 'deBiasing' in configSettingsJson['advance']['profiler']:\n deBiasing = configSettingsJson['advance']['profiler']['deBiasing']\n selectedDebiasingFeature = deBiasing.get('FeatureName','None')\n selectedDebiasingClass = deBiasing.get('ClassName','None')\n selectedDebiasingAlgorithm = deBiasing.get('Algorithm','')\n\n if selectedDebiasingFeature != 'None':\n df = pd.read_csv(configSettingsJson['basic']['dataLocation'],encoding='utf8',encoding_errors= 'replace')\n classeslist = []\n classeslist = df[selectedDebiasingFeature].unique().tolist()\n for item in classeslist:\n class_list.append(item)\n else:\n class_list.append('None')\n except:\n pass\n feature_dict = configSettingsJson['advance']['profiler']['featureDict']\n for feature_config in feature_dict:\n if feature_config.get('type', '') == 'categorical' and feature_config['feature'] != check_traget:\n categorical_features.append(feature_config['feature'])\n # ------------------ ------------------\n #print(categorical_features)\n temp = {}\n temp['ModelName'] = request.session['UseCaseName']\n temp['Version'] = request.session['ModelVersion']\n config = {}\n config['modelName'] = request.session['UseCaseName']\n config['modelVersion'] = request.session['ModelVersion']\n config['datetimeFeatures'] = configSettingsJson['basic']['dateTimeFeature']\n config['sequenceFeatures'] = configSettingsJson['basic']['indexFeature']\n config['FeaturesList'] = configSettingsJson['basic']['trainingFeatures']\n config['unimportantFeatures'] = ''\n config['targetFeature'] = configSettingsJson['basic']['targetFeature']\n\n deepLearning = 'False' \n machineLearning = 'False'\n reinforcementLearning = 'False'\n selectAlgo = \"\"\n print(problem_type)\n if problem_type.lower() in ['classification','regression']:\n for key in configSettingsJson['basic']['algorithms'][problem_type]:\n if configSettingsJson['basic']['algorithms'][problem_type][key] == 'True':\n if key in ['Neural Network','Convolutional Neural Network (1D)','Recurrent Neural Network','Recurrent Neural Network (GRU)','Recurrent Neural Network (LSTM)','Neural Architecture Search']:\n deepLearning = 'True'\n 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)']: \n machineLearning = 'True'\n if key in ['Deep Q Network','Dueling Deep Q Network']:\n reinforcementLearning = 'True'\n elif problem_type.lower() in ['clustering','topicmodelling']:#clustering(Bug 12611)\n machineLearning = 'True' \n configSettingsJson['basic']['deepLearning'] = deepLearning\n configSettingsJson['basic']['machineLearning'] = machineLearning\n configSettingsJson['basic']['reinforcementLearning'] = reinforcementLearning\n if problem_type in ['classification','regression','timeSeriesForecasting',\n 'timeSeriesAnomalyDetection',\n 'recommenderSystem','clustering','anomalyDetection','topicModelling','survivalAnalysis','videoForecasting','imageClassification','objectDetection','stateTransition']: #task 11997\n for key in configSettingsJson['basic']['algorithms'][problem_type]:\n if configSettingsJson['basic']['algorithms'][problem_type][key] == 'True':\n if selectAlgo != \"\":\n selectAlgo += ','\n selectAlgo += key \n if problem_type not in ['classification','regression']:\n break\n if problem_type == 'objectDetection':\n from AION import pretrainedModels\n ptmObj = pretrainedModels()\n obModels = ptmObj.get_info(selectAlgo)\n else:\n obModels = {}\n \n problemType = problem_type\n \n selected_use_case = request.session['UseCaseName']\n ModelVersion = request.session['ModelVersion']\n ModelStatus = request.session['ModelStatus']\n request.session['currentstate'] = 2\n \n #configSettingsJson['advance']['remoteTraining']['ssh']['keyFilePath'] = pemfilename\n if request.session['finalstate'] <= 2:\n request.session['finalstate'] = 2\n outlierDetection = 'False'\n for x in list(configSettingsJson['advance']['profiler']['outlierDetection'].keys()):\n if configSettingsJson['advance']['profiler']['outlierDetection'][x] == 'True':\n outlierDetection = 'True'\n if outlierDetection == 'False':\n configSettingsJson['advance']['profiler']['outlierDetection']['Disable'] = 'True' \n else:\n configSettingsJson['advance']['profiler']['outlierDetection']['Disable'] = 'False'\n \n if 'distributedLearning' not in configSettingsJson['basic']:\n configSettingsJson['basic']['distributedLearning'] = 'False'\n configSettingsJson['advance']['mllearner_config']['EnsembleStacking']=configSettingsJson['advance']['mllearner_config']['Stacking (Ensemble)']\n configSettingsJson['advance']['mllearner_config']['EnsembleVoting']=configSettingsJson['advance']['mllearner_config']['Voting (Ensemble)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['LogisticRegression'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Logistic Regression']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['GaussianNB'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Naive Bayes']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['SVC'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Support Vector Machine']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['KNeighborsClassifier'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['K Nearest Neighbors']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['DecisionTreeClassifier'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Decision Tree']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['RandomForestClassifier'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Random Forest']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['GradientBoostingClassifier'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Gradient Boosting']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['ExtremeGradientBoostingClassifier'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Extreme Gradient Boosting (XGBoost)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['LightGradientBoostingClassifier'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Light Gradient Boosting (LightGBM)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['CategoricalBoostingClassifier'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Categorical Boosting (CatBoost)']\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['SNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['Neural Network']\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['SimpleRNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['Recurrent Neural Network']\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['GRURNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['Recurrent Neural Network (GRU)']\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['LSTMRNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['Recurrent Neural Network (LSTM)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']=configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Bagging (Ensemble)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleStacking']=configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['Stacking (Ensemble)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['LogisticRegression'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['Logistic Regression']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['NaiveBayes'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['Naive Bayes']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['SVM'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['Support Vector Machine']\t\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['KNN'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['K Nearest Neighbors']\t\t\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['DecisionTree'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['Decision Tree']\n configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['RandomForest'] = configSettingsJson['advance']['mllearner_config']['modelParams']['classifierModelParams']['EnsembleBagging']['Random Forest']\t\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['SimpleRNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network']\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['GRURNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network (GRU)']\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['LSTMRNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network (LSTM)']\n \n configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams']['DQN'] = configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams']['Deep", "instruction": "", "output": "" }, { "input": "Q Network']\n configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams']['DDQN'] = configSettingsJson['advance']['rllearner_config']['modelParams']['classifierModelParams']['Dueling Deep Q Network']\n configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams']['DQN'] = configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams']['Deep Q Network']\n configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams']['DDQN'] = configSettingsJson['advance']['rllearner_config']['modelParams']['regressorModelParams']['Dueling Deep Q Network']\n \n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['CNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['Convolutional Neural Network (1D)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['LinearRegression'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Linear Regression']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['DecisionTreeRegressor'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Decision Tree']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['RandomForestRegressor'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Random Forest']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['XGBoostRegressor'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Extreme Gradient Boosting (XGBoost)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['LightGBMRegressor'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Light Gradient Boosting (LightGBM)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['CatBoostRegressor'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Categorical Boosting (CatBoost)']\n \n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleStacking']=configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Stacking (Ensemble)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging']=configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['Bagging (Ensemble)']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging']['LinearRegression'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging']['Linear Regression']\n configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging']['DecisionTree'] = configSettingsJson['advance']['mllearner_config']['modelParams']['regressorModelParams']['EnsembleBagging']['Decision Tree']\n \n \n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['NAS'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams'].get('Neural Architecture Search')\n configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams']['NAS'] = configSettingsJson['advance']['dllearner_config']['modelParams']['classifierModelParams'].get('Neural Architecture Search')\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['SNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Neural Network']\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['SimpleRNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network']\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['GRURNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network (GRU)']\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['LSTMRNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Recurrent Neural Network (LSTM)']\n configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['CNN'] = configSettingsJson['advance']['dllearner_config']['modelParams']['regressorModelParams']['Convolutional Neural Network (1D)']\n\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['OnlineLogisticRegression'] = configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online Logistic Regression']\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['OnlineDecisionTreeClassifier'] = configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online Decision Tree Classifier']\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['OnlineSoftmaxRegression'] = configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online Softmax Regression']\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['OnlineKNNClassifier'] = configSettingsJson['advance']['onlinelearner_config']['modelParams']['classifierModelParams']['Online KNN Classifier'] \n\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['OnlineLinearRegression'] = configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['Online Linear Regression']\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['OnlineDecisionTreeRegressor'] = configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['Online Decision Tree Regressor']\n configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['OnlineKNNRegressor'] = configSettingsJson['advance']['onlinelearner_config']['modelParams']['regressorModelParams']['Online KNN Regressor'] \n\n configSettingsJson['advance']['profiler']['textConversionMethod']['LatentSemanticAnalysis'] = configSettingsJson['advance']['profiler']['textConversionMethod']['LatentSemanticAnalysis']\n configSettingsJson['advance']['profiler']['embeddingSize']['LatentSemanticAnalysis'] = configSettingsJson['advance']['profiler']['embeddingSize']['LatentSemanticAnalysis']\n if 'llmFineTuning' in configSettingsJson['advance']:\n configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA2'] = configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA-2']\n configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA2Chat'] = configSettingsJson['basic']['algorithms']['llmFineTuning']['LLaMA-2-Chat']\n configSettingsJson['basic']['algorithms']['llmFineTuning']['CodeLLaMA2'] = configSettingsJson['basic']['algorithms']['llmFineTuning']['CodeLLaMA-2']\n\n configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA2'] = configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA-2']\n configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA2Chat'] = configSettingsJson['advance']['llmFineTuning']['modelParams']['LLaMA-2-Chat']\n configSettingsJson['advance']['llmFineTuning']['modelParams']['CodeLLaMA2'] = configSettingsJson['advance']['llmFineTuning']['modelParams']['CodeLLaMA-2']\n\n configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA2'] = \\\\\n configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA-2']\n configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA2Chat'] = \\\\\n configSettingsJson['basic']['modelSize']['llmFineTuning']['LLaMA-2-Chat']\n configSettingsJson['basic']['modelSize']['llmFineTuning']['CodeLLaMA2'] = \\\\\n configSettingsJson['basic']['modelSize']['llmFineTuning']['CodeLLaMA-2']\n\n if 'distributedlearner_config' in configSettingsJson['advance']:\n configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['DistributedXGBoost'] = configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['Distributed Extreme Gradient Boosting (XGBoost)']\n configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['DistributedLightGBM'] = configSettingsJson['advance']['distributedlearner_config']['modelParams']['classifierModelParams']['Distributed Light Gradient Boosting (LightGBM)']\n \n configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams']['DistributedXGBoost'] = configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams']['Distributed Extreme Gradient Boosting (XGBoost)']\n configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams']['DistributedLightGBM'] = configSettingsJson['advance']['distributedlearner_config']['modelParams']['regressorModelParams']['Distributed Light Gradient Boosting (LightGBM)']\n \n \n configSettingsJson['advance']['profiler']['normalizationMethod'] = 'None'\n normalizationtypes = configSettingsJson['advance']['profiler']['normalization']\n for k in normalizationtypes.keys():\n if configSettingsJson['advance']['profiler']['normalization'][k] == 'True':\n configSettingsJson['advance']['profiler']['normalizationMethod'] = k\n break\n context = {'temp': temp, 'advconfig': configSettingsJson, 'MachineLearningModels':MachineLearningModels,'hyperparamConfig':hyperparamConfig,'config': config, 'selected_use_case': selected_use_case,\n 'categorical_features': categorical_features, 'selectedDebiasingFeature': selectedDebiasingFeature, 'selectedDebiasingAlgorithm': selectedDebiasingAlgorithm, 'Class_list': class_list, 'selectedDebiasingClass': selectedDebiasingClass, #Debiasing Changes\n 'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion,\"obModels\":obModels,\"problemType\":problemType,\n 'currentstate': request.session['currentstate'], 'finalstate': request.session['finalstate'],\n 'selected': 'modeltraning','advance_help':ht.advance_help}\n return context\n except Exception as e:\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n context={'erroradvance':'Fail to load advance config Json file'}\n return context\n\n\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\ndef analysis_images(folder_path):\n from AIX import image_eda\n qualityscore = image_eda.img_MeasureImageQuality(folder_path)\n eda_result = image_eda.img_EDA(folder_path)\n #Image Duplicate Finder\n duplicate_img = image_eda.img_duplicatefinder(folder_path)\n color_plt = image_eda.img_plot_colour_hist(folder_path)\n return qualityscore,eda_result,duplicate_img,color_plt '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport json\nimport time\nimport os\nimport subprocess\nimport base64\nimport sys\nimport re\nfrom appbe.dataIngestion import getcommonfields\nfrom appbe.dataIngestion import getusercasestatus\ndef startSummarization(request,DEFAULT_FILE_PATH,CONFIG_PATH,DATA_FILE_PATH):\n try:\n if request.FILES:\n Datapath = request.FILES['summarypath']\n ext = str(Datapath).split('.')[-1]\n filetimestamp = str(int(time.time()))\n if ext.lower() in ['txt','pdf','doc','docs']:\n dataFile = os.path.join(DATA_FILE_PATH,'AION_' + filetimestamp+'.'+ext)\n else:\n dataFile = os.path.join(DATA_FILE_PATH,'AION_' + filetimestamp)\n with open(dataFile, 'wb+') as destination:\n for chunk in Datapath.chunks():\n destination.write(chunk)\n destination.close()\n \n configFile = os.path.join(DEFAULT_FILE_PATH,'aion_textSummerization.json')\n filetimestamp = str(int(time.time()))\n config_json_filename = os.path.join(CONFIG_PATH, 'AION_' + filetimestamp + '.json') \n f = open(configFile)\n data = json.load(f)\n f.close()\n data['basic']['dataLocation'] = dataFile\n type = request.POST.get('type')\n model = request.POST.get('model')\n slength = request.POST.get('length')\n types = data['basic']['analysisAproach']['textSummarization']\n for x in list(types.keys()):\n data['basic']['analysisAproach']['textSummarization'][x] = 'False'\n data['basic']['analysisAproach']['textSummarization'][type] = 'True'\n format = request.POST.get('format')\n algorithm = data['basic']['algorithms']['textSummarization']\n for x in list(algorithm.keys()):\n data['basic']['algorithms']['textSummarization'][x] = 'False'\n data['basic']['algorithms']['textSummarization'][model]='True'\n length = data['advance']['textSummarization']['summaryLength']\n for x in list(types.keys()):\n data['advance']['textSummarization']['summaryLength'][x] = 'False' \n data['advance']['textSummarization']['summaryLength'][slength] = 'True' \n with open(config_json_filename, \"w\") as outfile:\n json.dump(data, outfile)\n outfile.close()\n from bin.aion_text_summarizer import aion_textsummary\n outputStr = aion_textsummary(config_json_filename)", "instruction": "", "output": "" }, { "input": "\n #scriptPath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..','bin','aion_text_summarizer.py'))\n #outputStr = subprocess.check_output([sys.executable, scriptPath, config_json_filename])\n #outputStr = outputStr.decode('utf-8')\n #outputStr = re.search(r'Summary:(.*)', str(outputStr), re.IGNORECASE).group(1)\n predict_dict = json.loads(str(outputStr))\n summary = predict_dict['summary']\n except Exception as e:\n print(e)\n summary = str(e)\n context = getcommonfields()\n selected_use_case,ModelVersion,ModelStatus = getusercasestatus(request)\n context.update({'selected_use_case': selected_use_case,'ModelStatus': ModelStatus, 'ModelVersion': ModelVersion}) \n context.update({'summary':summary})\n return context import os\nimport re\nimport json\nimport time\nimport sys\nimport tiktoken\nimport openai\nimport requests\nfrom appbe.aion_config import get_llm_data\nimport logging\nimport pdfplumber\nfrom docx import Document\n\nopenai.api_key = ''\nopenai.api_base = '' \nopenai.api_type = ''\nopenai.api_version = ''\n\ndeployment_name=\"GPT-35-Turbo\"\nmodel_name='gpt-3.5-turbo'\n\nset_tokens_limit = 500\nset_tokens_limit_offline = 400\nset_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.\"\n\n\n# QnA Generator using LLM related changes\n# --------------------------------------------------------\ndef ingestDataForQA(request, DATA_FILE_PATH):\n log = logging.getLogger('log_ux')\n\n try:\n Datapath = request.FILES['DataFileQnA']\n from appbe.eda import ux_eda\n \n ext = str(Datapath).split('.')[-1]\n request.session['uploadfiletype'] = 'Local'\n request.session['datatype'] = 'Normal'\n filetimestamp = str(int(time.time()))\n if ext.lower() in ['txt','pdf','docx']:\n dataFile = os.path.join(DATA_FILE_PATH,'AION_' + filetimestamp+'.'+ext)\n else:\n dataFile = os.path.join(DATA_FILE_PATH,'AION_' + filetimestamp)\n with open(dataFile, 'wb+') as destination:\n for chunk in Datapath.chunks():\n destination.write(chunk)\n destination.close()\n dataPath = dataFile\n request.session['textdatapathQA'] = dataPath\n \n llm_choice = request.POST.get(\"llm_choice\")\n _result = ''\n \n \n # if llm_choice == 'Haystack':\n # _result = generateQA_Haystack(request, DATA_FILE_PATH)\n if llm_choice == 'Offline':\n _result = generateQA_Offline(request, DATA_FILE_PATH)\n else:\n _result = generateQA_OpenAI(request, DATA_FILE_PATH)\n \n return _result\n \n except Exception as e:\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n \n context = {'error': 'Failed to read data','emptytxt' : 'emptytxt'}\n log.info('Text Data Ingestion -- Error : Failed to read data, '+str(e))\n log.info('Details : '+ str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n return context\n# ---------------------- E N D ---------------------------\n\n\n\ndef generateQA_OpenAI(request, DATA_FILE_PATH):\n \n log = logging.getLogger('log_ux')\n try:\n file_path = request.session['textdatapathQA']\n\n # Read the file content\n if file_path.endswith('.pdf'):\n pdf_file=pdfplumber.open(file_path)\n file_content = \" \".join([x.extract_text() for x in pdf_file.pages])\n elif file_path.endswith('.docx'):\n doc_file=Document(file_path)\n file_content = \" \\\\n\".join([x.text for x in doc_file.paragraphs])\n else:\n with open(file_path, \"r\", encoding=\"utf-8\",errors = \"ignore\") as file:\n file_content = file.read()\n \n text = file_content.strip()\n #text = text.strip()\n \n extracted_QnA = []\n chunk_counter = 0\n \n num_tokens_text = count_tokens_text(text)\n if num_tokens_text > set_tokens_limit:\n for sub_text in split_text(text):\n chunk_counter = chunk_counter + 1\n _result = extract_questions_from_splittedtext(sub_text)\n print(f\"Currently executed chunk no is - {chunk_counter}.\")\n extracted_QnA.extend(_result)\n \n else:\n _prompt = set_prompt\n msg = [ {\"role\": \"system\", \"content\": _prompt},\n {\"role\": \"user\", \"content\": text} ]\n \n extracted_QnA = run_model(msg)\n \n quesCount = len(extracted_QnA)\n context = {'extracted_QnA':extracted_QnA, 'quesCount':quesCount}\n \n filetimestamp = str(int(time.time()))\n output_filepath = os.path.join(DATA_FILE_PATH,'AION_QnA' + filetimestamp+'.txt')\n \n # Save the extracted questions as a JSON file\n with open(output_filepath, 'w') as output_file:\n json.dump(extracted_QnA, output_file, indent=4)\n print(f\"QnAs have been saved to {output_filepath}.\")\n request.session['QnAfilepath'] = output_filepath\n \n return context\n \n except Exception as e:\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n errormsg = str(e)\n \n if 'Invalid URL' in errormsg or 'No connection adapters' in errormsg or 'invalid subscription key' in errormsg:\n 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.'\n if 'The API type provided in invalid' in errormsg:\n errormsg = \"The API type provided is invalid. Please select one of the supported API types:'azure', 'azure_ad' or 'open_ai'\"\n \n if 'Max retries exceeded with url' in errormsg:\n errormsg = 'Please make sure you have good internet connection and access to API endpoint for your resource.'\n \n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n \n context = {'error': 'Failed to generate QnA List using openAI','LLM' : 'openAI', 'selected':'DataOperations', 'errormessage':errormsg}\n log.info('generateQA_OpenAI -- Error : Failed to generate QnA List using openAI.. '+str(e))\n log.info('Details : '+ str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n return context\n\n\ndef run_model(msg):\n key,url,api_type,api_version = get_llm_data()\n openai.api_key = key\n openai.api_base = url\n openai.api_type = api_type\n openai.api_version = api_version\n \n completions = openai.ChatCompletion.create(engine=deployment_name, temperature=0.0, max_tokens=2000, n=1, stop=None, messages=msg)\n # return completions.choices[0].message.content\n \n \n _questionList = completions.choices[0].message.content\n question_pattern = re.compile(r\"^Q\\\\s*\\\\d+\\\\.\\\\s*(.+)$\", re.MULTILINE)\n questions = question_pattern.findall(_questionList)\n \n answer_pattern = re.compile(r\"^A\\\\s*\\\\d+\\\\.\\\\s*(.+)$\", re.MULTILINE)\n answers = answer_pattern.findall(_questionList)\n \n if (len(questions) > 0) and (not re.search(r\"[.!?)]$\", questions[-1].strip())):\n print(f\"WARNING: Popping incomplete question: '{questions[-1]}'\")\n questions.pop()\n \n extracted_QnA = []\n for question, answer in zip(questions, answers):\n extracted_QnA.append({'question': question, 'answer': answer})\n \n return extracted_QnA\n \n\ndef count_tokens_text(text):\n import tiktoken\n model_type = model_name\n encoding = tiktoken.encoding_for_model(model_type)\n \n encoded_text = encoding.encode(text)\n return len(encoded_text)\n\n\ndef extract_questions_from_splittedtext(text):\n _prompt = set_prompt\n msg = [ {\"role\": \"system\", \"content\": _prompt},\n {\"role\": \"user\", \"content\": text} ]\n \n _ques_ans_List = run_model(msg)\n return _ques_ans_List\n\n\ndef split_text(text):\n lines = text.split('\\\\n')\n current_section = ''\n sections = []\n _lastsection = 0\n for line in lines:\n num_tokens_text = count_tokens_text(''.join([current_section,line]))\n \n if num_tokens_text < set_tokens_limit:\n current_section = ''.join([current_section,line])\n else:\n sections.append(current_section)\n current_section = line\n _lastsection = 1\n \n if _lastsection == 1:\n sections.append(current_section)\n \n return sections\n \n\n\n# --------------------------------------------------------------------------------- #\n\ndef generateQA_Haystack(request, DATA_FILE_PATH):\n file_path = request.session['textdatapathQA']\n\n # Read the file content\n with open(file_path, \"r\", encoding=\"utf-8\") as file:\n file_content = file.read()\n \n text = file_content.strip()\n text = text.strip()\n docs = []\n \n num_tokens_text = count_tokens_text(text)\n if num_tokens_text > set_tokens_limit:\n for sub_text in split_text(text):\n docs.append({\"content\": sub_text})\n else:\n docs = [{\"content\": text}]\n \n from pprint import pprint\n from tqdm.auto import tqdm\n from haystack.nodes import QuestionGenerator, BM25Retriever, FARMReader\n \n # from haystack.document_stores import ElasticsearchDocumentStore\n from haystack.document_stores import InMemoryDocumentStore\n # from haystack.document_stores import PineconeDocumentStore\n \n from haystack.pipelines import (\n QuestionGenerationPipeline,\n RetrieverQuestionGenerationPipeline,\n QuestionAnswerGenerationPipeline,\n )\n \n \n from haystack.utils import print_questions\n \n document_store = InMemoryDocumentStore(use_bm25=True)\n document_store.write_documents(docs)\n \n question_generator = QuestionGenerator()\n \n # reader = FARMReader(\"deepset/roberta-base-squad2\")\n # reader.save(\"my_local_roberta_model\")\n reader_local = FARMReader(model_name_or_path=\"my_local_roberta_model_1\")\n \n qag_pipeline = QuestionAnswerGenerationPipeline(question_generator, reader_local)\n \n extracted_QnA = []\n for idx, document in enumerate(tqdm(document_store)):\n print(f\"\\\\n * Generating questions and answers for document {idx}: {document.content[:100]}...\\\\n\")\n result = qag_pipeline.run(documents=[document])\n print_questions(result)\n \n answers = []\n questions = result['queries']\n answerList = result[\"answers\"]\n \n for _answers in answerList:\n for answer in _answers:\n ans = answer.answer\n answers.append(ans)\n \n for question, answer in zip(questions, answers):\n extracted_QnA.append({'question': question, 'answer': answer})\n\n quesCount = len(extracted_QnA)\n context = {'extracted_QnA':extracted_QnA, 'quesCount':quesCount}\n \n filetimestamp = str(int(time.time()))\n output_filepath = os.path.join(DATA_FILE_PATH,'AION_QnA' + filetimestamp+'.txt')\n \n # Save the extracted questions as a JSON file\n with open(output_filepath, 'w') as output_file:\n json.dump(extracted_QnA, output_file, indent=4)\n print(f\"QnAs have been saved to {output_filepath}.\")\n request.session['QnAfilepath'] = output_filepath\n \n return context\n \n\n\n# --------------------------------------------------------------------------------- #\n \ndef generateQA_Offline(request, DATA_FILE_PATH):\n\n log = logging.getLogger('log_ux')\n try:\n file_path = request.session['textdatapathQA']\n \n if file_path.endswith('.pdf'):\n pdf_file=pdfplumber.open(file_path)\n file_content = \" \".join([x.extract_text() for x in pdf_file.pages])\n elif file_path.endswith('.docx'):\n doc_file=Document(file_path)\n file_content = \" \\\\n\".join([x.text for x in doc_file.paragraphs])\n else:\n with open(file_path, \"r\", encoding=\"utf-8\",errors = \"ignore\") as file:\n file_content = file.read()\n \n \n\n # # Read the file content\n # with open(file_path, \"r\", encoding=\"utf-8\") as file:\n # file_content = file.read()\n \n text = file_content.strip()\n # text = text.strip()\n docs = []\n \n # num_tokens_text = count_tokens_text(text)\n # if num_tokens_text > set_tokens_limit:\n # for sub_text in split_text(text):\n # docs.append(sub_text)\n # else:\n # docs.append(text)\n \n \n model_name = \"valhalla/t5-base-qg-hl\" \n num_tokens_text = count_tokens_text_offline(text, model_name)\n if num_tokens_text > set_tokens_limit_offline:\n for sub_text in split_text_for_Off", "instruction": "", "output": "" }, { "input": "line(text, model_name):\n docs.append(sub_text)\n else:\n docs.append(text)\n\n\n from question_generation.pipelines import pipeline\n extracted_QnA = []\n extracted_QnAList = []\n \n \n nlp = pipeline(\"question-generation\", model = model_name)\n # nlp = pipeline(\"question-generation\", model=\"valhalla/t5-base-e2e-qg\") \n # nlp = pipeline(\"e2e-qg\", model=\"valhalla/t5-base-qg-hl\")\n # nlp = pipeline(\"multitask-qa-qg\", model=\"valhalla/t5-base-qa-qg-hl\")\n \n for _text in docs:\n res = nlp(_text)\n print(res)\n extracted_QnAList.extend(res)\n \n for _record in extracted_QnAList:\n extracted_QnA.append({'question': _record['question'], 'answer': _record['answer'].replace('', '')})\n \n quesCount = len(extracted_QnA)\n context = {'extracted_QnA':extracted_QnA, 'quesCount':quesCount}\n \n filetimestamp = str(int(time.time()))\n output_filepath = os.path.join(DATA_FILE_PATH,'AION_QnA' + filetimestamp+'.txt')\n \n # Save the extracted questions as a JSON file\n with open(output_filepath, 'w') as output_file:\n json.dump(extracted_QnA, output_file, indent=4)\n print(f\"T5 based QnAs have been saved to {output_filepath}.\")\n request.session['QnAfilepath'] = output_filepath\n \n return context\n \n except Exception as e:\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n errormsg = str(e)\n \n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n \n context = {'error': 'Failed to generate QnA List using T5','LLM' : 'T5', 'selected':'DataOperations', 'errormessage':errormsg}\n log.info('generateQA_Offline -- Error : Failed to generate QnA List using T5.. '+str(e))\n log.info('Details : '+ str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n return context\n \n\ndef split_text_for_Offline(text, model_name):\n lines = text.split('\\\\n')\n current_section = ''\n sections = []\n _lastsection = 0\n \n for line in lines:\n num_tokens = count_tokens_text_offline(''.join([current_section,line]), model_name)\n \n if num_tokens < set_tokens_limit_offline:\n current_section = ''.join([current_section,line])\n else:\n sections.append(current_section)\n current_section = line\n _lastsection = 1\n \n if _lastsection == 1:\n sections.append(current_section)\n \n return sections\n \n \ndef count_tokens_text_offline(text, model_name):\n from transformers import AutoTokenizer\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n \n inputs = tokenizer(text, return_tensors=\"pt\")\n input_ids = inputs[\"input_ids\"]\n _token_count = len(input_ids[0])\n \n return _token_count\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nfrom pathlib import Path\ndef label_filename(request):\n\tfilename = 'LabeledData.csv'\n\tlabelPath = os.path.join(request.session['datalocation'],'AION','Labels')\n\tPath(labelPath).mkdir(parents=True, exist_ok=True)\n\tfilePath = os.path.join(labelPath,filename)\n\treturn filePath\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport kfp\nimport kfp.dsl as dsl\nimport json\nfrom pathlib import Path\n\n\nclass aionpipeline():\n \n containerRegistry = str()\n containerLabel = str()\n containerSecret = str()\n \n pipelineName = 'AION MLOps Pipeline {0}'\n exeCmd = 'python'\n codeFile = 'aionCode.py'\n mntPoint = '/aion'\n inputArg = '-i'\n msIP = '0.0.0.0'\n port = '8094'\n cachingStrategy = 'P0D'\n \n deafultVolume = '1Gi'\n volName = 'aion-pvc'\n volMode = 'ReadWriteMany'\n fileExt = '.tar.gz'\n fileName = 'aion_mlops_pipeline_{0}'\n \n containerMM = 'modelmonitoring'\n containerDI = 'dataingestion'\n containerDT = 'datatransformation'\n containerFE = 'featureengineering'\n containerMR = 'modelregistry'\n containerMS = 'modelserving'\n containerImage = '{0}/{1}:{2}'\n \n models = {}\n nameSeprator = '-'\n modelsLiteral = 'models'\n modelNameLiteral = 'modelname'\n 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}\"}}]}}'\n \n def __init__(self, models, containerRegistry, containerLabel, containerSecret=str()):\n self.models = models\n self.containerRegistry = containerRegistry\n self.containerLabel = containerLabel\n self.containerSecret = containerSecret\n\n \n @dsl.pipeline(\n name=pipelineName.format(containerLabel),\n description=pipelineName.format(containerLabel),\n )\n def aion_mlops(self, inputUri=str(), volSize=deafultVolume):\n vop = dsl.VolumeOp(\n name=self.volName + self.nameSeprator + self.containerLabel,\n resource_name=self.volName,\n modes=[self.volMode],\n size=volSize\n )\n \n mm = dsl.ContainerOp(\n name=self.containerMM,\n image=self.containerImage.format(self.containerRegistry,self.containerMM,self.containerLabel),\n command=self.exeCmd,\n arguments=[\n self.codeFile,\n self.inputArg,\n inputUri,\n ],\n pvolumes={self.mntPoint: vop.volume}\n )\n mm.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy\n \n di = dsl.ContainerOp(\n name=self.containerDI,\n image=self.containerImage.format(self.containerRegistry,self.containerDI,self.containerLabel),\n command=self.exeCmd,\n arguments=[\n self.codeFile,\n ],\n pvolumes={self.mntPoint: mm.pvolume}\n )\n di.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy\n \n dt = dsl.ContainerOp(\n name=self.containerDT,\n image=self.containerImage.format(self.containerRegistry,self.containerDT,self.containerLabel),\n command=self.exeCmd,\n arguments=[\n self.codeFile,\n ],\n pvolumes={self.mntPoint: di.pvolume}\n )\n dt.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy\n \n fe = dsl.ContainerOp(\n name=self.containerFE,\n image=self.containerImage.format(self.containerRegistry,self.containerFE,self.containerLabel),\n command=self.exeCmd,\n arguments=[\n self.codeFile,\n ],\n pvolumes={self.mntPoint: dt.pvolume}\n )\n fe.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy\n \n \n dictMT = {}\n listMTOps = []\n \n for model in self.models[self.modelsLiteral]:\n modelName = model[self.modelNameLiteral]\n mt=dsl.ContainerOp(\n name=modelName,\n image=self.containerImage.format(self.containerRegistry,modelName,self.containerLabel),\n command=self.exeCmd,\n arguments=[\n self.codeFile,\n ],\n pvolumes={self.mntPoint: fe.pvolume})\n mt.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy\n listMTOps.append(mt)\n dictMT[self.mntPoint]=mt.pvolume\n \n \n mr = dsl.ContainerOp(\n name=self.containerMR,\n image=self.containerImage.format(self.containerRegistry,self.containerMR,self.containerLabel),\n command=self.exeCmd,\n arguments=[\n self.codeFile,\n ],\n pvolumes=dictMT\n ).after(*tuple(listMTOps))\n \n mr.execution_options.caching_strategy.max_cache_staleness = self.cachingStrategy\n \n 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)\n ms = dsl.ResourceOp(\n name=self.containerMS + self.nameSeprator + self.containerLabel,\n k8s_resource=json.loads(msJson),\n ) \n ms.after(mr)\n \n \n def compilepl(self, targetPath=str()):\n filePath = self.fileName.format(self.containerLabel.lower()) + self.fileExt\n if targetPath != str():\n filePath = Path(targetPath, filePath)\n kfp.compiler.Compiler().compile(self.aion_mlops, str(filePath))\n\n \n def executepl(self, kfhost=str()):\n client = kfp.Client(kfhost)\n client.create_run_from_pipeline_func(self.aion_mlops,arguments={})\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport sys\nimport json\nimport datetime, time, timeit\nimport logging\nlogging.getLogger('tensorflow').disabled = True\nimport shutil\nimport warnings\nfrom config_manager.online_pipeline_config import OTAionConfigManager\nfrom records import pushrecords\nimport logging\nimport mlflow\nfrom pathlib import Path\nfrom pytz import timezone\n\ndef pushRecordForOnlineTraining():\n\ttry:\n\t\tfrom appbe.pages import getversion\n\t\tstatus,msg = pushrecords.enterRecord(AION_VERSION)\n\texcept Exception as e:\n\t\tprint(\"Exception\", e)\n\t\tstatus = False\n\t\tmsg = str(e)\n\treturn status,msg\n\ndef mlflowSetPath(path,experimentname):\n\timport mlflow\n\turl = \"file:\" + str(Path(path).parent.parent) + \"/mlruns\"\n\tmlflow.set_tracking_uri(url)\n\tmlflow.set_experiment(str(experimentname))\n\t\t\nclass server():\n\n\tdef __init__(self):\n\t\tself.response = None\n\t\tself.dfNumCols=0\n\t\tself.dfNumRows=0\n\t\tself.features=[]\n\t\tself.mFeatures=[]\n\t\tself.emptyFeatures=[]\n\t\tself.vectorizerFeatures=[]\n\t\tself.wordToNumericFeatures=[]\n\t\tself.profilerAction = []\n\t\tself.targetType = ''\n\t\tself.matrix1='{'\n\t\tself.matrix2='{'\n\t\tself.matrix='{'\n\t\tself.trainmatrix='{'\n\t\tself.numericalFeatures=[]\n\t\tself.nonNumericFeatures=[]\n\t\tself.similarGroups=[]\n\t\tself.method = 'NA'\n\t\tself.pandasNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n\t\tself.modelSelTopFeatures=[]\n\t\tself.topFeatures=[]\n\t\tself.allFeatures=[]\n\n\n\tdef startScriptExecution(self, config_obj):\n\t\trowfilterexpression = ''\n\t\tgrouperbyjson = ''\n\t\tmodel_tried=''\n\t\tlearner_type = ''\n\t\ttopics = {}\n\t\tnumericContinuousFeatures=''\n\t\tdiscreteFeatures=''\n\t\tthreshold=-1\n\t\ttargetColumn = ''\n\t\tcategoricalFeatures=''\n\t\tdataFolderLocation = ''\n\t\toriginal_data_file = ''\n\t\tprofiled_data_file = ''\n\t\ttrained_data_file = ''\n\t\tpredicted_data_file=''\n\t\tfeatureReduction = 'False'\n\t\treduction_data_file=''\n\t\tparams={}\n\t\tscore = 0\n\t\tlabelMaps={}\n\t\tfeatureDataShape=[]\n\t\tself.riverModels = []\n\t\tself.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']\n\n\t\t#ConfigSettings\n\t\titerName,iterVersion,dataLocation,deployLocation,delimiter,textqualifier =", "instruction": "", "output": "" }, { "input": "config_obj.getAIONLocationSettings()\n\t\tscoreParam = config_obj.getScoringCreteria()\n\t\tdatetimeFeature,indexFeature,modelFeatures=config_obj.getFeatures()\n\t\titerName = iterName.replace(\" \", \"_\")\n\t\tdeployLocation,dataFolderLocation,original_data_file,profiled_data_file,trained_data_file,predicted_data_file,logFileName,outputjsonFile = config_obj.createDeploymentFolders(deployLocation,iterName,iterVersion)\n\n\t\t#Mlflow\n\t\tmlflowSetPath(deployLocation,iterName+'_'+iterVersion)\n \n\t\t\n\t\t#Logger\n\t\tfilehandler = logging.FileHandler(logFileName, 'w','utf-8')\n\t\tformatter = logging.Formatter('%(message)s')\n\t\tfilehandler.setFormatter(formatter)\n\t\tlog = logging.getLogger('eion')\n\t\tlog.propagate = False\n\t\tfor hdlr in log.handlers[:]: # remove the existing file handlers\n\t\t\tif isinstance(hdlr,logging.FileHandler):\n\t\t\t\tlog.removeHandler(hdlr)\n\t\tlog.addHandler(filehandler)\n\t\tlog.setLevel(logging.INFO)\n\t\tlog.info('************* Version - v2.2.5 *************** \\\\n')\n\t\tmsg = '-------> Execution Start Time: '+ datetime.datetime.now(timezone(\"Asia/Kolkata\")).strftime('%Y-%m-%d %H:%M:%S' + ' IST')\n\t\tlog.info(msg)\n\n\n\t\tstartTime = timeit.default_timer()\n\t\ttry:\n\n\t\t\toutput = {'bestModel': '', 'bestScore': 0, 'bestParams': {}}\n\n\t\t\t#ConfigSetting\n\t\t\tproblemType,targetFeature,profilerStatus,selectorStatus,learnerStatus,visualizationstatus,deployStatus = config_obj.getModulesDetails()\n\t\t\tselectorStatus = False\t \n\t\t\tif(problemType.lower() in ['classification','regression']):\n\t\t\t\tif(targetFeature == ''):\n\t\t\t\t\toutput = {\"status\":\"FAIL\",\"message\":\"Target Feature is Must for Classification and Regression Problem Type\"}\n\t\t\t\t\treturn output\n\t\t\t\n\t\t\t#DataReading\n\t\t\tfrom transformations.dataReader import dataReader\t\t\n\t\t\tobjData = dataReader()\n\t\t\tif os.path.isfile(dataLocation):\n\t\t\t\tdataFrame = objData.csvTodf(dataLocation,delimiter,textqualifier)\n\t\t\t\tdataFrame.rename(columns=lambda x:x.strip(), inplace=True)\n\n\n\t\t\t#FilterDataframe\n\t\t\tfilter = config_obj.getfilter()\n\t\t\tif filter != 'NA':\n\t\t\t\tdataFrame,rowfilterexpression = objData.rowsfilter(filter,dataFrame)\t\n\t\t\t\n\t\t\t#GroupDataframe\n\t\t\ttimegrouper = config_obj.gettimegrouper()\t\t\n\t\t\tgrouping = config_obj.getgrouper()\t\t\n\t\t\tif grouping != 'NA':\n\t\t\t\tdataFrame,grouperbyjson = objData.grouping(grouping,dataFrame)\n\t\t\telif timegrouper != 'NA':\n\t\t\t\tdataFrame,grouperbyjson = objData.timeGrouping(timegrouper,dataFrame)\n\n\t\t\t#KeepOnlyModelFtrs\n\t\t\tdataFrame = objData.removeFeatures(dataFrame,datetimeFeature,indexFeature,modelFeatures,targetFeature)\n\t\t\t\n\t\t\tlog.info('\\\\n-------> First Ten Rows of Input Data: ')\n\t\t\tlog.info(dataFrame.head(10))\n\t\t\tself.dfNumRows=dataFrame.shape[0]\n\t\t\tself.dfNumCols=dataFrame.shape[1]\n\n\t\t\tdataLoadTime = timeit.default_timer() - startTime\n\t\t\tlog.info('-------> COMPUTING: Total dataLoadTime time(sec) :'+str(dataLoadTime))\n\n\t\t\tif profilerStatus:\n\t\t\t\tlog.info('\\\\n================== Data Profiler has started ==================')\n\t\t\t\tlog.info('Status:-|... AION feature transformation started')\n\t\t\t\tdp_mlstart = time.time() \n\t\t\t\tprofilerJson = config_obj.getEionProfilerConfigurarion()\n\t\t\t\tlog.info('-------> Input dataFrame(5 Rows): ')\n\t\t\t\tlog.info(dataFrame.head(5))\n\t\t\t\tlog.info('-------> DataFrame Shape (Row,Columns): '+str(dataFrame.shape))\n\t\t\t\tfrom incremental.incProfiler import incProfiler\n\t\t\t\tincProfilerObj = incProfiler()\n\t\t\t\tdataFrame,targetColumn,self.mFeatures,self.numericalFeatures,self.nonNumericFeatures,labelMaps,self.configDict,self.textFeatures,self.emptyFeatures,self.wordToNumericFeatures = incProfilerObj.startIncProfiler(dataFrame,profilerJson,targetFeature,deployLocation,problemType)\n\t\t\t\tself.features = self.configDict['allFtrs']\n\t\t\t\tlog.info('-------> Data Frame Post Data Profiling(5 Rows): ')\n\t\t\t\tlog.info(dataFrame.head(5))\n\t\t\t\tlog.info('Status:-|... AION feature transformation completed')\n\t\t\t\tdp_mlexecutionTime=time.time() - dp_mlstart\n\t\t\t\tlog.info('-------> COMPUTING: Total Data Profiling Execution Time '+str(dp_mlexecutionTime))\n\t\t\t\tlog.info('================== Data Profiling completed ==================\\\\n')\n\t\t\t\t\n\t\t\tdataFrame.to_csv(profiled_data_file,index=False)\n\t\t\tselectorStatus = False\n\t\t\tif learnerStatus:\n\t\t\t\tlog.info('Status:-|... AION Learner data preparation started')\n\t\t\t\tldp_mlstart = time.time()\n\t\t\t\ttestPercentage = config_obj.getAIONTestTrainPercentage()\n\t\t\t\tbalancingMethod = config_obj.getAIONDataBalancingMethod()\n\t\t\t\tfrom learner.machinelearning import machinelearning\n\t\t\t\tmlobj = machinelearning()\n\t\t\t\tmodelType = problemType.lower()\n\t\t\t\ttargetColumn = targetFeature\n\t\t\t\tif modelType == \"na\":\n\t\t\t\t\tif self.targetType == 'categorical':\n\t\t\t\t\t\tmodelType = 'classification'\n\t\t\t\t\telif self.targetType == 'continuous':\n\t\t\t\t\t\tmodelType = 'regression'\n\t\t\t\tdatacolumns=list(dataFrame.columns)\t\t\n\t\t\t\tif targetColumn in datacolumns:\n\t\t\t\t\tdatacolumns.remove(targetColumn)\n\t\t\t\tfeatures =datacolumns\n\t\t\t\tfeatureData = dataFrame[features]\n\t\t\t\tif targetColumn != '':\n\t\t\t\t\ttargetData = dataFrame[targetColumn]\t\t\t \n\t\t\t\t\txtrain,ytrain,xtest,ytest = mlobj.split_into_train_test_data(featureData,targetData,testPercentage,modelType)\n\t\t\t\tcategoryCountList = []\t\n\t\t\t\tif modelType == 'classification':\n\t\t\t\t\tif(mlobj.checkForClassBalancing(ytrain) >= 1):\n\t\t\t\t\t\txtrain,ytrain = mlobj.ExecuteClassBalancing(xtrain,ytrain,balancingMethod)\n\t\t\t\t\tvalueCount=targetData.value_counts()\n\t\t\t\t\tcategoryCountList=valueCount.tolist()\n\t\t\t\tldp_mlexecutionTime=time.time() - ldp_mlstart\n\t\t\t\tlog.info('-------> COMPUTING: Total Learner data preparation Execution Time '+str(ldp_mlexecutionTime))\n\t\t\t\tlog.info('Status:-|... AION Learner data preparation completed')\n\t\t\tif learnerStatus:\n\t\t\t\tlog.info('\\\\n================== ML Started ==================')\n\t\t\t\tlog.info('Status:-|... AION training started')\n\t\t\t\tlog.info('-------> Memory Usage by DataFrame During Learner Status '+str(dataFrame.memory_usage(deep=True).sum()))\n\t\t\t\tmlstart = time.time()\n\t\t\t\tlog.info('-------> Target Problem Type:'+ self.targetType)\n\t\t\t\tlearner_type = 'ML'\n\t\t\t\tlearnerJson = config_obj.getEionLearnerConfiguration()\n\t\t\t\tlog.info('-------> Target Model Type:'+ modelType)\n\t\t\t\tmodelParams,modelList = config_obj.getEionLearnerModelParams(modelType)\n\t\t\t\tif(modelType == 'regression'):\n\t\t\t\t\tallowedmatrix = ['mse','r2','rmse','mae']\n\t\t\t\t\tif(scoreParam.lower() not in allowedmatrix):\n\t\t\t\t\t\tscoreParam = 'mse'\n\t\t\t\t\n\t\t\t\tif(modelType == 'classification'):\n\t\t\t\t\tallowedmatrix = ['accuracy','recall','f1_score','precision','roc_auc']\n\t\t\t\t\tif(scoreParam.lower() not in allowedmatrix):\n\t\t\t\t\t\tscoreParam = 'accuracy'\n\t\t\t\tscoreParam = scoreParam.lower()\t\t\t\t\n\t\t\t\tfrom incremental.incMachineLearning import incMachineLearning\n\t\t\t\tincMlObj = incMachineLearning(mlobj)\n\t\t\t\tself.configDict['riverModel'] = False\n\t\t\t\tstatus,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)\n\t\t\t\tif model in self.riverAlgoNames:\n\t\t\t\t\tself.configDict['riverModel'] = True\t\t\t\t\n\t\t\t\tif(self.matrix != '{'):\n\t\t\t\t\tself.matrix += ','\n\t\t\t\tif(self.trainmatrix != '{'):\n\t\t\t\t\tself.trainmatrix += ','\n\t\t\t\tself.trainmatrix += trainmatrix\n\t\t\t\tself.matrix += matrix\n\t\t\t\tmlexecutionTime=time.time() - mlstart\n\t\t\t\tlog.info('-------> Total ML Execution Time '+str(mlexecutionTime))\n\t\t\t\tlog.info('Status:-|... AION training completed')\n\t\t\t\tlog.info('================== ML Completed ==================\\\\n')\n\n\t\t\tif visualizationstatus:\n\t\t\t\tvisualizationJson = config_obj.getEionVisualizationConfiguration()\n\t\t\t\tlog.info('Status:-|... AION Visualizer started')\n\t\t\t\tvisualizer_mlstart = time.time()\n\t\t\t\tfrom visualization.visualization import Visualization\n\t\t\t\tvisualizationObj = 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)\n\t\t\t\tvisualizationObj.visualizationrecommandsystem()\n\t\t\t\tvisualizer_mlexecutionTime=time.time() - visualizer_mlstart\n\t\t\t\tlog.info('-------> COMPUTING: Total Visualizer Execution Time '+str(visualizer_mlexecutionTime))\n\t\t\t\tlog.info('Status:-|... AION Visualizer completed')\n\t\t\t\ttry:\n\t\t\t\t\tos.remove(os.path.join(deployLocation,'aion_xai.py'))\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\n\t\t\t\t\n\t\t\tif deployStatus:\n\t\t\t\tif str(model) != 'None':\n\t\t\t\t\tlog.info('\\\\n================== Deployment Started ==================')\n\t\t\t\t\tlog.info('Status:-|... AION Deployer started')\n\t\t\t\t\tdeployPath = deployLocation\n\t\t\t\t\tdeployer_mlstart = time.time()\n\t\t\t\t\tsrc = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','utilities','useCaseFiles')\n\t\t\t\t\tshutil.copy2(os.path.join(src,'incBatchLearning.py'),deployPath)\n\t\t\t\t\tos.rename(os.path.join(deployPath,'incBatchLearning.py'),os.path.join(deployPath,'aion_inclearning.py'))\n\t\t\t\t\tshutil.copy2(os.path.join(src,'incBatchPrediction.py'),deployPath)\n\t\t\t\t\tos.rename(os.path.join(deployPath,'incBatchPrediction.py'),os.path.join(deployPath,'aion_predict.py'))\n\t\t\t\t\tself.configDict['modelName'] = str(model)\n\t\t\t\t\tself.configDict['modelParams'] = params\n\t\t\t\t\tself.configDict['problemType'] = problemType.lower()\n\t\t\t\t\tself.configDict['score'] = score\n\t\t\t\t\tself.configDict['metricList'] = []\n\t\t\t\t\tself.configDict['metricList'].append(score)\n\t\t\t\t\tself.configDict['trainRowsList'] = []\n\t\t\t\t\tself.configDict['trainRowsList'].append(featureDataShape[0])\t\t\t\t\n\t\t\t\t\tself.configDict['scoreParam'] = scoreParam\n\t\t\t\t\tself.configDict['partialFit'] = 0\n\t\t\t\t\twith open(os.path.join(deployLocation,'production', 'Config.json'), 'w', encoding='utf8') as f:\n\t\t\t\t\t\tjson.dump(self.configDict, f, ensure_ascii=False)\n\t\t\t\t\tdeployer_mlexecutionTime=time.time() - deployer_mlstart\n\t\t\t\t\tlog.info('-------> COMPUTING: Total Deployer Execution Time '+str(deployer_mlexecutionTime))\n\t\t\t\t\tlog.info('Status:-|... AION Batch Deployment completed')\n\t\t\t\t\tlog.info('================== Deployment Completed ==================')\t\n\t\t\t\t\n\n\t\t\t# \tself.features = profilerObj.set_features(self.features,self.textFeatures,self.vectorizerFeatures)\n\t\t\tself.matrix += '}'\n\t\t\tself.trainmatrix += '}'\n\t\t\tmatrix = eval(self.matrix)\n\t\t\ttrainmatrix = eval(self.trainmatrix)\n\t\t\tmodel_tried = eval('['+model_tried+']')\n\t\t\ttry:\n\t\t\t\tjson.dumps(params)\n\t\t\t\toutput_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}}\n\t\t\texcept:\n\t\t\t\toutput_json = {\"status\":\"SUCCESS\",\"data\":{\"ModelType\":model", "instruction": "", "output": "" }, { "input": "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}}\n\n\t\t\t\tprint(output_json)\t\n\t\t\t\tif bool(topics) == True:\n\t\t\t\t\toutput_json['topics'] = topics\n\t\t\twith open(outputjsonFile, 'w') as f:\n\t\t\t\tjson.dump(output_json, f) \n\t\t\toutput_json = json.dumps(output_json) \n\n\t\t\tlog.info('\\\\n------------- Summary ------------')\n\t\t\tlog.info('------->No of rows & columns in data:('+str(self.dfNumRows)+','+str(self.dfNumCols)+')')\n\t\t\tlog.info('------->No of missing Features :'+str(len(self.mFeatures)))\n\t\t\tlog.info('------->Missing Features:'+str(self.mFeatures))\n\t\t\tlog.info('------->Text Features:'+str(self.textFeatures))\n\t\t\tlog.info('------->No of Nonnumeric Features :'+str(len(self.nonNumericFeatures)))\n\t\t\tlog.info('------->Non-Numeric Features :' +str(self.nonNumericFeatures))\n\t\t\tif threshold == -1:\n\t\t\t\tlog.info('------->Threshold: NA')\n\t\t\telse:\n\t\t\t\tlog.info('------->Threshold: '+str(threshold))\n\t\t\tlog.info('------->Label Maps of Target Feature for classification :'+str(labelMaps))\n\t\t\tif((learner_type != 'TS') & (learner_type != 'AR')):\n\t\t\t\tlog.info('------->No of columns and rows used for Modeling :'+str(featureDataShape))\n\t\t\t\tlog.info('------->Features Used for Modeling:'+str(self.features))\n\t\t\t\tlog.info('------->Target Feature: '+str(targetColumn))\n\t\t\t\tlog.info('------->Best Model Score :'+str(score))\n\t\t\t\tlog.info('------->Best Parameters:'+str(params))\n\t\t\tlog.info('------->Type of Model :'+str(modelType))\n\t\t\tlog.info('------->Best Model :'+str(model))\n\t\t\tlog.info('------------- Summary ------------\\\\n')\n\t\t\t\n\t\t\t\n\t\texcept Exception as inst:\n\t\t\tlog.info('server code execution failed !....'+str(inst))\n\t\t\toutput_json = {\"status\":\"FAIL\",\"message\":str(inst).strip('\"')}\n\t\t\toutput_json = json.dumps(output_json)\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tlog.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\n\t\texecutionTime = timeit.default_timer() - startTime\n\t\tlog.info('\\\\nTotal execution time(sec) :'+str(executionTime))\n\t\tlog.info('\\\\n------------- Output JSON ------------')\n\t\tlog.info('-------> Output :'+str(output_json))\n\t\tlog.info('------------- Output JSON ------------\\\\n')\n\t\tfor hdlr in log.handlers[:]: # remove the existing file handlers\n\t\t\tif isinstance(hdlr,logging.FileHandler):\n\t\t\t\thdlr.close()\n\t\t\t\tlog.removeHandler(hdlr)\n\t\treturn output_json\n\t\t\n\n\n\ndef aion_ot_train_model(arg):\n\twarnings.filterwarnings('ignore')\n\ttry:\n\t\tvalid, msg = pushRecordForOnlineTraining()\n\t\tif valid:\n\t\t\tserverObj = server()\n\t\t\tconfigObj = OTAionConfigManager()\n\t\t\tjsonPath = arg\n\t\t\treadConfistatus,msg = configObj.readConfigurationFile(jsonPath)\n\t\t\tif(readConfistatus == False):\n\t\t\t\toutput = {\"status\":\"FAIL\",\"message\":str(msg).strip('\"')}\n\t\t\t\toutput = json.dumps(output)\n\t\t\t\tprint(\"\\\\n\")\n\t\t\t\tprint(\"aion_learner_status:\",output)\n\t\t\t\tprint(\"\\\\n\")\n\t\t\t\treturn output\t\n\t\t\toutput = serverObj.startScriptExecution(configObj)\n\t\telse:\n\t\t\toutput = {\"status\":\"LicenseVerificationFailed\",\"message\":str(msg).strip('\"')}\n\t\t\toutput = json.dumps(output)\n\t\t\tprint(\"\\\\n\")\n\t\t\tprint(\"aion_learner_status:\",output)\n\t\t\tprint(\"\\\\n\")\n\t\t\treturn output\n\texcept Exception as inst:\n\t\toutput = {\"status\":\"FAIL\",\"message\":str(inst).strip('\"')}\n\t\toutput = json.dumps(output) \n\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\tprint(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\tprint(\"\\\\n\")\n\tprint(\"aion_learner_status:\",output)\n\tprint(\"\\\\n\")\n\treturn output\n\nif __name__ == \"__main__\":\n\taion_ot_train_model(sys.argv[1])\n\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n''' \nimport joblib\nimport time\nfrom pandas import json_normalize\nimport pandas as pd\nimport numpy as np\nimport argparse\nimport json\nimport os\nimport pathlib\nfrom pathlib import Path\nfrom sagemaker.aionMlopsService import aionMlopsService\nimport logging\nimport os.path\nfrom os.path import expanduser\nimport platform,sys\nfrom pathlib import Path\nfrom sklearn.model_selection import train_test_split\n\ndef getAWSConfiguration(mlops_params,log):\n awsId=mlops_params['awsSagemaker']['awsID']\n if ((not awsId) or (awsId is None)):\n awsId=\"\"\n log.info('awsId error. ')\n awsAccesskeyid=mlops_params['awsSagemaker']['accesskeyID']\n if ((not awsAccesskeyid) or (awsAccesskeyid is None)):\n awsAccesskeyid=\"\"\n log.info('awsAccesskeyid error. ')\n awsSecretaccesskey=mlops_params['awsSagemaker']['secretAccesskey']\n if ((not awsSecretaccesskey) or (awsSecretaccesskey is None)):\n awsSecretaccesskey=\"\"\n log.info('awsSecretaccesskey error. ')\n awsSessiontoken=mlops_params['awsSagemaker']['sessionToken']\n if ((not awsSessiontoken) or (awsSessiontoken is None)):\n awsSessiontoken=\"\"\n log.info('awsSessiontoken error. ')\n awsRegion=mlops_params['awsSagemaker']['region']\n if ((not awsRegion) or (awsRegion is None)):\n awsRegion=\"\"\n log.info('awsRegion error. ')\n IAMSagemakerRoleArn=mlops_params['awsSagemaker']['IAMSagemakerRoleArn']\n if ((not IAMSagemakerRoleArn) or (IAMSagemakerRoleArn is None)):\n IAMSagemakerRoleArn=\"\"\n log.info('IAMSagemakerRoleArn error. ')\n return awsId,awsAccesskeyid,awsSecretaccesskey,awsSessiontoken,awsRegion,IAMSagemakerRoleArn\n\ndef getMlflowParams(mlops_params,log):\n modelInput = mlops_params['modelInput']\n data = mlops_params['data'] \n\n mlflowtosagemakerDeploy=mlops_params['sagemakerDeploy']\n if ((not mlflowtosagemakerDeploy) or (mlflowtosagemakerDeploy is None)):\n mlflowtosagemakerDeploy=\"True\"\n mlflowtosagemakerPushOnly=mlops_params['deployExistingModel']['status']\n if ((not mlflowtosagemakerPushOnly) or (mlflowtosagemakerPushOnly is None)):\n mlflowtosagemakerPushOnly=\"False\"\n mlflowtosagemakerPushImageName=mlops_params['deployExistingModel']['dockerImageName']\n if ((not mlflowtosagemakerPushImageName) or (mlflowtosagemakerPushImageName is None)):\n mlflowtosagemakerPushImageName=\"mlops_image\"\n mlflowtosagemakerdeployModeluri=mlops_params['deployExistingModel']['deployModeluri']\n if ((not mlflowtosagemakerdeployModeluri) or (mlflowtosagemakerdeployModeluri is None)):\n mlflowtosagemakerdeployModeluri=\"None\"\n log.info('mlflowtosagemakerdeployModeluri error. ')\n cloudInfrastructure = mlops_params['modelOutput']['cloudInfrastructure']\n if ((not cloudInfrastructure) or (cloudInfrastructure is None)):\n cloudInfrastructure=\"Sagemaker\"\n endpointName=mlops_params['endpointName']\n if ((not endpointName) or (endpointName is None)):\n sagemakerAppName=\"aion-demo-app\"\n log.info('endpointName not given, setting default one. ')\n experimentName=str(endpointName)\n mlflowContainerName=str(endpointName)\n return modelInput,data,mlflowtosagemakerDeploy,mlflowtosagemakerPushOnly,mlflowtosagemakerPushImageName,mlflowtosagemakerdeployModeluri,cloudInfrastructure,endpointName,experimentName,mlflowContainerName\n\ndef getPredictionParams(mlops_params,log):\n \n predictStatus=mlops_params['prediction']['status']\n if ((not predictStatus) or (predictStatus is None)):\n predictStatus=\"False\"\n modelInput = mlops_params['modelInput']\n data = mlops_params['data']\n if (predictStatus == \"True\" or predictStatus.lower()== \"true\"):\n if ((not modelInput) or (modelInput is None)):\n log.info('prediction model input error.Please check given model file or its path for prediction ')\n if ((not data) or (data is None)):\n log.info('prediction data input error.Please check given data file or its path for prediction ')\n targetFeature=mlops_params['prediction']['target']\n return predictStatus,targetFeature\n \ndef sagemakerPrediction(mlopsobj,data,log):\n df = json_normalize(data)\n model=None\n predictionStatus=False\n try:\n endpointPrediction=mlopsobj.predict_sm_app_endpoint(df)\n \n if (endpointPrediction is None):\n log.info('Sagemaker endpoint application prediction Issue.')\n outputjson = {\"status\":\"Error\",\"msg\":\"Sagemaker endpoint application prediction Issue\"}\n outputjson = json.dumps(outputjson) \n #print(\"predictions: \"+str(outputjson))\n predictionStatus=False\n else:\n log.info(\"sagemaker end point Prediction: \\\\n\"+str(endpointPrediction))\n df['prediction'] = endpointPrediction\n outputjson = df.to_json(orient='records')\n outputjson = {\"status\":\"SUCCESS\",\"data\":json.loads(outputjson)}\n outputjson = json.dumps(outputjson) \n #print(\"predictions: \"+str(outputjson))\n predictionStatus=True \n except Exception as e:\n #log.info(\"sagemaker end point Prediction error: \\\\n\")\n outputjson = {\"status\":\"Error\",\"msg\":str(e)}\n outputjson=None\n predictionStatus=False\n return outputjson,predictionStatus\n## Main aion sagemaker fn call \ndef sagemaker_exec(mlops_params,log):\n #mlops_params = json.loads(config)\n mlops_params=mlops_params\n modelInput,data,mlflowtosagemakerDeploy,mlflowtosagemakerPushOnly,mlflowtosagemakerPushImageName,mlflowtosagemakerdeployModeluri,cloudInfrastructure,endpointName,experimentName,mlflowContainerName = getMlflowParams(mlops_params,log)\n mlflowModelname=None\n awsId,awsAccesskeyid,awsSecretaccesskey,awsSessiontoken,awsRegion,IAMSagemakerRoleArn = getAWSConfiguration(mlops_params,log)\n predictStatus,targetFeature = getPredictionParams(mlops_params,log)\n\n sagemakerDeployOption='create'\n deleteAwsecrRepository='False'\n sagemakerAppName=str(endpointName)\n ecrRepositoryName='aion-ecr-repo'\n #aws ecr model app_name should contain only [[a-zA-Z0-9-]], again rechecking here.\n import re \n if sagemakerAppName:\n pattern = re.compile(\"[A-Za-z0-9-]+\")\n # if found match (entire string matches pattern)\n if pattern.fullmatch(sagemakerAppName) is not None:\n #print(\"Found match: \")\n pass\n else:\n log.info('wrong sagemaker Application Name, Nmae should contains only [A-Za-z0-9-] .') \n app_name = 'aion-demo-app'\n else:\n app_name = 'aion-demo-app'\n #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 . \n sagemakerDeployOption=\"create\"\n deleteAwsecrRepository=\"False\"\n ecrRepositoryName=\"aion_test_repo\" \n log.info('mlops parameter check done.')\n # predictionStatus=False\n deploystatus = 'SUCCESS'\n try:\n log.info('cloudInfrastructure: '+str(cloudInfrastructure))\n if(cloudInfrastructure.lower() == \"sagemaker\"):\n ## sagemaker app prediction call\n if (predictStatus.lower() == \"true\"):\n \n # df = json_normalize(data)\n model=None\n mlopsobj = aionMlopsService(model,mlflowtosagemakerDeploy,mlflowtosagemakerPushOnly,mlflowtosagemakerPushImageName,mlflowtosagemakerdeployModeluri,experimentName,mlflowModelname,awsAccesskeyid,awsSecretaccesskey,awsSessiontoken,mlflowContainerName,awsRegion,awsId,IAMSagemakerRoleArn,sagemakerAppName,sagemakerDeployOption,deleteAwsecrRepository,ecrRepositoryName)\n outputjson,predictionStatus = sagemakerPrediction(mlopsobj,data,log)\n print(\"predictions: \"+str(outputjson))\n predictionStatus=predictionStatus\n return(outputjson)\n else:\n if Path(modelInput).is_file():\n \n msg = ''\n model = joblib.load(modelInput)\n ProblemName = model.__class__.__name__\n mlflowModelname=str(ProblemName)\n log.info('aion mlops Model name: '+str(mlflowModelname))\n df=None\n mlopsobj = aionMlopsService(model,mlflowtosagemakerDeploy,mlflowtosagemakerPush", "instruction": "", "output": "" }, { "input": "Only,mlflowtosagemakerPushImageName,mlflowtosagemakerdeployModeluri,experimentName,mlflowModelname,awsAccesskeyid,awsSecretaccesskey,awsSessiontoken,mlflowContainerName,awsRegion,awsId,IAMSagemakerRoleArn,sagemakerAppName,sagemakerDeployOption,deleteAwsecrRepository,ecrRepositoryName)\n mlflow2sm_status,localhost_container_status=mlopsobj.mlflow2sagemaker_deploy()\n log.info('mlflow2sm_status: '+str(mlflow2sm_status))\n log.info('localhost_container_status: '+str(localhost_container_status))\n # Checking deploy status\n if (mlflowtosagemakerPushOnly.lower() == \"true\" ):\n if (mlflow2sm_status.lower() == \"success\"):\n deploystatus = 'SUCCESS'\n msg = 'Endpoint succesfully deployed in sagemaker'\n log.info('Endpoint succesfully deployed in sagemaker (Push eisting model container).\\\\n ')\n elif(mlflow2sm_status.lower() == \"failed\"):\n deploystatus = 'ERROR'\n msg = 'Endpoint failed to deploy in sagemaker'\n log.info('Endpoint failed to deploy in sagemaker. (Push eisting model container).\\\\n ')\n else:\n pass\n elif(mlflowtosagemakerDeploy.lower() == \"true\"):\n if (mlflow2sm_status.lower() == \"success\"):\n deploystatus='SUCCESS'\n msg = 'Endpoint succesfully deployed in sagemaker'\n log.info('Endpoint succesfully deployed in sagemaker')\n elif(mlflow2sm_status.lower() == \"failed\"):\n deploystatus = 'ERROR'\n msg = 'Endpoint failed to deploy in sagemaker'\n log.info('Endpoint failed to deploy in sagemaker.\\\\n ')\n elif (mlflow2sm_status.lower() == \"Notdeployed\"):\n deploystatus= 'ERROR'\n msg = 'Sagemaker compatible container created'\n log.info('sagemaker endpoint not deployed, check aws connection and credentials. \\\\n')\n \n elif (mlflowtosagemakerDeploy.lower() == \"false\"):\n if(localhost_container_status.lower() == \"success\"):\n deploystatus = 'SUCCESS'\n msg = 'Localhost mlops docker created successfully'\n log.info('Localhost mlops docker created successfully. \\\\n')\n elif(localhost_container_status.lower() == \"failed\"):\n deploystatus = 'ERROR'\n msg = 'Localhost mlops docker created failed'\n log.info('Localhost mlops docker creation failed. \\\\n')\n elif (localhost_container_status.lower() == \"Notdeployed\"):\n deploystatus= 'ERROR'\n log.info('Localhost mlops docker not deployed, check local docker status. \\\\n')\n else:\n pass\n else:\n pass\n else:\n deploystatus = 'ERROR'\n msg = 'Model Path not Found'\n print('Error: Model Path not Found')\n outputjson = {\"status\":str(deploystatus),\"data\":str(msg)}\n outputjson = json.dumps(outputjson) \n print(\"predictions: \"+str(outputjson)) \n return(outputjson)\n except Exception as inst:\n outputjson = {\"status\":str(deploystatus),\"data\":str(msg)}\n outputjson = json.dumps(outputjson) \n print(\"predictions: \"+str(outputjson)) \n return(outputjson)\n\ndef aion_sagemaker(config):\n try:\n mlops_params = config\n print(mlops_params)\n from appbe.dataPath import LOG_LOCATION \n sagemakerLogLocation = LOG_LOCATION\n try:\n os.makedirs(sagemakerLogLocation)\n except OSError as e:\n if (os.path.exists(sagemakerLogLocation)):\n pass\n else:\n raise OSError('sagemakerLogLocation error.')\n\n filename_mlops = 'mlopslog_'+str(int(time.time()))\n filename_mlops=filename_mlops+'.log'\n filepath = os.path.join(sagemakerLogLocation, filename_mlops) \n logging.basicConfig(filename=filepath, format='%(message)s',filemode='w') \n log = logging.getLogger('aionMLOps')\n log.setLevel(logging.DEBUG)\n \n output = sagemaker_exec(mlops_params,log)\n return output\n \n except Exception as inst:\n print(inst)\n deploystatus = 'ERROR'\n output = {\"status\":str(deploystatus),\"data\":str(inst)}\n output = json.dumps(output) \n print(\"predictions: \"+str(output)) \n return(output)\n \n#Sagemaker main fn call\nif __name__=='__main__':\n json_config = str(sys.argv[1])\n output = aion_sagemaker(json.loads(json_config))\n \n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\nimport os\nfrom pathlib import Path\nos.chdir(Path(__file__).parent)\nimport json\nimport shutil \nfrom mlac.timeseries import app as ts_app\nfrom mlac.ml import app as ml_app\nimport traceback\n \ndef create_test_file(config):\n code_file = 'aionCode.py'\n text = \"\"\"\nfrom pathlib import Path\nimport subprocess\nimport sys\nimport json\nimport argparse\n\ndef run_pipeline(data_path):\n\tprint('Data Location:', data_path)\n\tcwd = Path(__file__).parent\n\n\tmonitor_file = str(cwd/'ModelMonitoring'/'{code_file}')\n\n\tload_file = str(cwd/'DataIngestion'/'{code_file}')\n\ttransformer_file = str(cwd/'DataTransformation'/'{code_file}')\n\tselector_file = str(cwd/'FeatureEngineering'/'{code_file}')\n\ttrain_folder = cwd\n\tregister_file = str(cwd/'ModelRegistry'/'{code_file}')\n\tdeploy_file = str(cwd/'ModelServing'/'{code_file}')\n\n\tprint('Running modelMonitoring')\n\tcmd = [sys.executable, monitor_file, '-i', data_path]\n\tresult = subprocess.check_output(cmd)\n\tresult = result.decode('utf-8')\n\tprint(result) \n\tresult = json.loads(result[result.find('{search}'):])\n\tif result['Status'] == 'Failure':\n\t\texit()\n\t\n\tprint('Running dataIngestion')\n\tcmd = [sys.executable, load_file]\n\tresult = subprocess.check_output(cmd)\n\tresult = result.decode('utf-8')\n\tprint(result) \n\tresult = json.loads(result[result.find('{search}'):])\n\tif result['Status'] == 'Failure':\n\t\texit()\n\n\tprint('Running DataTransformation')\n\tcmd = [sys.executable, transformer_file]\n\tresult = subprocess.check_output(cmd)\n\tresult = result.decode('utf-8')\n\tprint(result)\n\tresult = json.loads(result[result.find('{search}'):])\n\tif result['Status'] == 'Failure':\n\t\texit()\n\n\tprint('Running FeatureEngineering')\n\tcmd = [sys.executable, selector_file]\n\tresult = subprocess.check_output(cmd)\n\tresult = result.decode('utf-8')\n\tprint(result)\n\tresult = json.loads(result[result.find('{search}'):])\n\tif result['Status'] == 'Failure':\n\t\texit()\n\n\ttrain_models = [f for f in train_folder.iterdir() if 'ModelTraining' in f.name]\n\tfor model in train_models:\n\t\tprint('Running',model.name)\n\t\tcmd = [sys.executable, str(model/'{code_file}')]\n\t\ttrain_result = subprocess.check_output(cmd)\n\t\ttrain_result = train_result.decode('utf-8')\n\t\tprint(train_result) \n\n\tprint('Running ModelRegistry')\n\tcmd = [sys.executable, register_file]\n\tresult = subprocess.check_output(cmd)\n\tresult = result.decode('utf-8')\n\tprint(result)\n\tresult = json.loads(result[result.find('{search}'):])\n\tif result['Status'] == 'Failure':\n\t\texit()\n\n\tprint('Running ModelServing')\n\tcmd = [sys.executable, deploy_file]\n\tresult = subprocess.check_output(cmd)\n\tresult = result.decode('utf-8')\n\tprint(result)\n\nif __name__ == '__main__': \n\tparser = argparse.ArgumentParser() \n\tparser.add_argument('-i', '--inputPath', help='path of the input data') \n\targs = parser.parse_args() \n\tif args.inputPath: \n\t\tfilename = args.inputPath\n\telse:\n\t\tfilename = r\"{filename}\"\n\ttry: \n\t\tprint(run_pipeline(filename)) \n\texcept Exception as e: \n\t\tprint(e)\n\"\"\".format(filename=config['dataLocation'],search='{\"Status\":',code_file=code_file)\n deploy_path = Path(config[\"deploy_path\"])/'MLaC'\n deploy_path.mkdir(parents=True, exist_ok=True)\n py_file = deploy_path/\"run_pipeline.py\"\n with open(py_file, \"w\") as f:\n f.write(text)\n\ndef is_module_in_req_file(mod, folder):\n status = False\n if (Path(folder)/'requirements.txt').is_file():\n with open(folder/'requirements.txt', 'r') as f:\n status = mod in f.read()\n return status\n\ndef copy_local_modules(config):\n deploy_path = Path(config[\"deploy_path\"])\n local_modules_location = config.get(\"local_modules_location\", None)\n if local_modules_location:\n folder_loc = local_modules_location\n else:\n folder_loc = Path(__file__).parent/'local_modules'\n if not folder_loc.exists():\n folder_loc = None\n if folder_loc:\n file = folder_loc/'config.json'\n if file.exists():\n with open(file, 'r') as f:\n data = json.load(f)\n for key, values in data.items():\n local_module = folder_loc/key\n if local_module.exists():\n for folder in values:\n target_folder = Path(deploy_path)/'MLaC'/folder\n if target_folder.is_dir():\n if is_module_in_req_file(key, target_folder):\n shutil.copy(local_module, target_folder)\n \ndef validate(config):\n error = ''\n if 'error' in config.keys():\n error = config['error']\n return error\n \ndef generate_mlac_code(config):\n with open(config, 'r') as f:\n config = json.load(f)\n error = validate(config)\n if error:\n raise ValueError(error)\n if config['problem_type'] in ['classification','regression']:\n return generate_mlac_ML_code(config)\n elif config['problem_type'].lower() == 'timeseriesforecasting': #task 11997\n return generate_mlac_TS_code(config)\n \ndef generate_mlac_ML_code(config):\n try:\n ml_app.run_loader(config)\n ml_app.run_transformer(config)\n ml_app.run_selector(config)\n ml_app.run_trainer(config)\n ml_app.run_register(config)\n ml_app.run_deploy(config)\n ml_app.run_drift_analysis(config)\n copy_local_modules(config)\t\n create_test_file(config)\n status = {'Status':'SUCCESS','MLaC_Location':str(Path(config[\"deploy_path\"])/'MLaC')}\n except Exception as Inst:\n status = {'Status':'Failure','msg':str(Inst)}\n traceback.print_exc()\n status = json.dumps(status) \n return(status)\n \ndef generate_mlac_TS_code(config):\n try:\n ts_app.run_loader(config)\n ts_app.run_transformer(config)\n ts_app.run_selector(config)\n ts_app.run_trainer(config)\n ts_app.run_register(config)\n ts_app.run_deploy(config)\n ts_app.run_drift_analysis(config)\n create_test_file(config)\n status = {'Status':'SUCCESS','MLaC_Location':str(Path(config[\"deploy_path\"])/'MLaC')}\n except Exception as Inst:\n status = {'Status':'Failure','msg':str(Inst)}\n traceback.print_exc()\n status = json.dumps(status) \n return(status) #from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer\nfrom http.server import BaseHTTPRequestHandler,HTTPServer \n#from SocketServer import ThreadingMixIn\nfrom socketserver import ThreadingMixIn \nfrom functools import partial\nfrom http.server import SimpleHTTPRequestHandler, test\nimport base64\nfrom appbe.dataPath import DEPLOY_LOCATION\n\n'''\nfrom augustus.core.ModelLoader import ModelLoader\nfrom augustus.strict import modelLoader\n'''\nimport pandas as pd\nimport os,sys\nfrom os.path import expanduser\nimport platform\nimport numpy as np\nimport configparser\nimport threading\nimport subprocess\nimport argparse\nfrom functools import partial\nimport re\nimport cgi\nfrom datetime import datetime\nimport json\nimport sys\nfrom datetime import datetime\nuser_records = {}\nclass LocalModelData(object):\n\tmodels = {}\t\n \nclass HTTPRequestHandler(BaseHTTPRequestHandler):\n\tdef __init__(self, *args, **kwargs):\n\t\tusername = kwargs.pop(\"username\")\n\t\tpassword = kwargs.pop(\"password\")\n\t\tself._auth = base64.b64encode(f\"{username}:{password}\".encode()).decode()\n\t\tsuper().__init__(*args)\n\n\tdef do_HEAD(self):\n\t\tself.send_response(200)\n\t\tself.send_header(\"Content-type\", \"text/html\")\n\t\tself.end_headers()\n\n\tdef do_AUTHHEAD(self):\n\t\tself.send_response(401)\n\t\tself.send_header(\"WWW-Authenticate\", 'Basic realm=\"Test\"')\n\t\tself.send_header(\"Content-type\", \"text/html\")\n\t\tself.end_headers()\n \n\tdef do_POST(self):\n\t\tprint(\"PYTHON ######## REQUEST ####### STARTED\")\n\t\tif None != re.search('/AION/', self.path):\n\t\t\tctype, pdict = cgi.parse_header(self.headers.get('content-type'))\n\t\t\tif ctype == 'application/json':\n\t\t\t\tif self.headers.get(\"Authorization\") == None:\n\t\t\t\t\tself.do_AUTHHEAD()\n\t", "instruction": "", "output": "" }, { "input": "\t\t\t\tresp = \"Authentication Failed: Auth Header Not Present\"\n\t\t\t\t\tresp=resp.encode()\n\t\t\t\t\tself.wfile.write(resp)\n\t\t\t\telif self.headers.get(\"Authorization\") == \"Basic \" + self._auth:\n\t\t\t\t\tlength = int(self.headers.get('content-length'))\n\t\t\t\t\t#data = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)\n\t\t\t\t\tdata = self.rfile.read(length)\n\t\t\t\t\t#print(data)\n\t\t\t\t\t#keyList = list(data.keys())\n\t\t\t\t\t#print(keyList[0])\n\t\t\t\t\tmodel = self.path.split('/')[-2]\n\t\t\t\t\toperation = self.path.split('/')[-1]\n\t\t\t\t\thome = expanduser(\"~\")\n\t\t\t\t\t#data = json.loads(data)\n\t\t\t\t\tdataStr = data\n\t\t\t\t\tmodel_path = os.path.join(DEPLOY_LOCATION,model)\n\t\t\t\t\tisdir = os.path.isdir(model_path) \n\t\t\t\t\tif isdir: \n\t\t\t\t\t\tif operation.lower() == 'predict': \n\t\t\t\t\t\t\tpredict_path = os.path.join(model_path,'aion_predict.py')\n\t\t\t\t\t\t\toutputStr = subprocess.check_output([sys.executable,predict_path,dataStr])\n\t\t\t\t\t\t\toutputStr = outputStr.decode('utf-8')\n\t\t\t\t\t\t\toutputStr = re.search(r'predictions:(.*)',str(outputStr), re.IGNORECASE).group(1)\n\t\t\t\t\t\t\toutputStr = outputStr.strip()\n\t\t\t\t\t\t\tresp = outputStr\n\t\t\t\t\t\telif operation.lower() == 'spredict':\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tpredict_path = os.path.join(model_path,'aion_spredict.py')\n\t\t\t\t\t\t\t\tprint(predict_path)\n\t\t\t\t\t\t\t\toutputStr = subprocess.check_output([sys.executable,predict_path,dataStr])\n\t\t\t\t\t\t\t\toutputStr = outputStr.decode('utf-8')\n\t\t\t\t\t\t\t\toutputStr = re.search(r'predictions:(.*)',str(outputStr), re.IGNORECASE).group(1)\n\t\t\t\t\t\t\t\toutputStr = outputStr.strip()\n\t\t\t\t\t\t\t\tresp = outputStr\n\t\t\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\t\t\tprint(e)\n \n\t\t\t\t\t\telif operation.lower() == 'features': \n\t\t\t\t\t\t\tpredict_path = os.path.join(model_path,'featureslist.py')\n\t\t\t\t\t\t\toutputStr = subprocess.check_output([sys.executable,predict_path,dataStr])\n\t\t\t\t\t\t\toutputStr = outputStr.decode('utf-8')\n\t\t\t\t\t\t\toutputStr = re.search(r'predictions:(.*)',str(outputStr), re.IGNORECASE).group(1)\n\t\t\t\t\t\t\toutputStr = outputStr.strip()\n\t\t\t\t\t\t\tresp = outputStr\n\t\t\t\t\t\telif operation.lower() == 'explain':\n\t\t\t\t\t\t\tpredict_path = os.path.join(model_path,'explainable_ai.py') \n\t\t\t\t\t\t\toutputStr = subprocess.check_output([sys.executable,predict_path,'local',dataStr])\n\t\t\t\t\t\t\toutputStr = outputStr.decode('utf-8')\n\t\t\t\t\t\t\toutputStr = re.search(r'aion_ai_explanation:(.*)',str(outputStr), re.IGNORECASE).group(1)\n\t\t\t\t\t\t\toutputStr = outputStr.strip()\n\t\t\t\t\t\telif operation.lower() == 'monitoring': \n\t\t\t\t\t\t\tpredict_path = os.path.join(model_path,'aion_ipdrift.py')\n\t\t\t\t\t\t\toutputStr = subprocess.check_output([sys.executable,predict_path,dataStr])\n\t\t\t\t\t\t\toutputStr = outputStr.decode('utf-8')\n\t\t\t\t\t\t\toutputStr = re.search(r'drift:(.*)',str(outputStr), re.IGNORECASE).group(1)\n\t\t\t\t\t\t\toutputStr = outputStr.strip()\n\t\t\t\t\t\telif operation.lower() == 'performance': \n\t\t\t\t\t\t\tpredict_path = os.path.join(model_path,'aion_opdrift.py')\n\t\t\t\t\t\t\toutputStr = subprocess.check_output([sys.executable,predict_path,dataStr])\n\t\t\t\t\t\t\toutputStr = outputStr.decode('utf-8')\n\t\t\t\t\t\t\toutputStr = re.search(r'drift:(.*)',str(outputStr), re.IGNORECASE).group(1)\n\t\t\t\t\t\t\toutputStr = outputStr.strip()\n\t\t\t\t\t\telif operation.lower() == 'pattern_anomaly_predict':\n\t\t\t\t\t\t\tdata = json.loads(data)\n\t\t\t\t\t\t\tanomaly = False\n\t\t\t\t\t\t\tremarks = ''\n\t\t\t\t\t\t\tclusterid = -1\n\t\t\t\t\t\t\tconfigfilename = os.path.join(model_path,'datadetails.json')\n\t\t\t\t\t\t\tfilename = os.path.join(model_path,'clickstream.json')\n\t\t\t\t\t\t\tclusterfilename = os.path.join(model_path,'stateClustering.csv')\n\t\t\t\t\t\t\tprobfilename = os.path.join(model_path,'stateTransitionProbability.csv')\n \t \n\t\t\t\t\t\t\tdfclus = pd.read_csv(clusterfilename)\n\t\t\t\t\t\t\tdfprod = pd.read_csv(probfilename) \n\t\t\t\t\t\t\tf = open(configfilename, \"r\")\n\t\t\t\t\t\t\tconfigSettings = f.read()\n\t\t\t\t\t\t\tf.close() \n\t\t\t\t\t\t\tconfigSettingsJson = json.loads(configSettings)\n\t\t\t\t\t\t\tactivity = configSettingsJson['activity']\n\t\t\t\t\t\t\tsessionid = configSettingsJson['sessionid'] \n\t\t\t\t\t\t\tf = open(filename, \"r\")\n\t\t\t\t\t\t\tconfigSettings = f.read()\n\t\t\t\t\t\t\tf.close() \n\t\t\t\t\t\t\tconfigSettingsJson = json.loads(configSettings)\n\t\t\t\t\t\t\tgroupswitching = configSettingsJson['groupswitching']\n\t\t\t\t\t\t\tpage_threshold = configSettingsJson['transitionprobability']\n\t\t\t\t\t\t\tchain_count = configSettingsJson['transitionsequence']\n\t\t\t\t\t\t\tchain_probability = configSettingsJson['sequencethreshold'] \n\t\t\t\t\t\t\tcurrentactivity = data[activity]\n\t\t\t\t\t\t\tif bool(user_records):\n\t\t\t\t\t\t\t\tsessionid = data[sessionid]\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif sessionid != user_records['SessionID']:\n\t\t\t\t\t\t\t\t\tuser_records['SessionID'] = sessionid\n\t\t\t\t\t\t\t\t\tprevactivity = ''\n\t\t\t\t\t\t\t\t\tuser_records['probarry'] = []\n\t\t\t\t\t\t\t\t\tuser_records['prevclusterid'] = -1\n\t\t\t\t\t\t\t\t\tuser_records['NoOfClusterHopping'] = 0\n\t\t\t\t\t\t\t\t\tuser_records['pageclicks'] = 1\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tprevactivity = user_records['Activity']\n\t\t\t\t\t\t\t\tuser_records['Activity'] = currentactivity\n\t\t\t\t\t\t\t\tpageswitch = True\n\t\t\t\t\t\t\t\tif prevactivity == currentactivity or prevactivity == '':\n\t\t\t\t\t\t\t\t\tprobability = 0\t\n\t\t\t\t\t\t\t\t\tpageswitch = False\n\t\t\t\t\t\t\t\t\tremarks = ''\t\t\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tuser_records['pageclicks'] += 1\n\t\t\t\t\t\t\t\t\tdf1 = dfprod[(dfprod['State'] == prevactivity) & (dfprod['NextState'] == currentactivity)]\n\t\t\t\t\t\t\t\t\tif df1.empty:\n\t\t\t\t\t\t\t\t\t\tremarks = 'Anomaly Detected - User in unusual state'\t\n\t\t\t\t\t\t\t\t\t\tanomaly = True\n\t\t\t\t\t\t\t\t\t\tclusterid = -1\n\t\t\t\t\t\t\t\t\t\tprobability = 0\n\t\t\t\t\t\t\t\t\t\tuser_records['probarry'].append(probability)\n\t\t\t\t\t\t\t\t\t\tn=int(chain_count)\n\t\t\t\t\t\t\t\t\t\tnum_list = user_records['probarry'][-n:]\n\t\t\t\t\t\t\t\t\t\tavg = sum(num_list)/len(num_list)\n\t\t\t\t\t\t\t\t\t\tfor index, row in dfclus.iterrows():\n\t\t\t\t\t\t\t\t\t\t\tclusterlist = row[\"clusterlist\"]\n\t\t\t\t\t\t\t\t\t\t\tif currentactivity in clusterlist:\n\t\t\t\t\t\t\t\t\t\t\t\tclusterid = row[\"clusterid\"]\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tprobability = df1['Probability'].iloc[0]\n\t\t\t\t\t\t\t\t\t\tuser_records['probarry'].append(probability)\n\t\t\t\t\t\t\t\t\t\tn=int(chain_count)\n\t\t\t\t\t\t\t\t\t\tnum_list = user_records['probarry'][-n:]\n\t\t\t\t\t\t\t\t\t\tdavg = sum(num_list)/len(num_list)\n\t\t\t\t\t\t\t\t\t\tfor index, row in dfclus.iterrows():\n\t\t\t\t\t\t\t\t\t\t\tclusterlist = row[\"clusterlist\"]\n\t\t\t\t\t\t\t\t\t\t\tif currentactivity in clusterlist:\n\t\t\t\t\t\t\t\t\t\t\t\tclusterid = row[\"clusterid\"]\n\t\t\t\t\t\t\t\t\t\tremarks = ''\t\t\t\n\t\t\t\t\t\t\t\t\t\tif user_records['prevclusterid'] != -1:\n\t\t\t\t\t\t\t\t\t\t\tif probability == 0 and user_records['prevclusterid'] != clusterid:\n\t\t\t\t\t\t\t\t\t\t\t\tuser_records['NoOfClusterHopping'] = user_records['NoOfClusterHopping']+1\n\t\t\t\t\t\t\t\t\t\t\t\tif user_records['pageclicks'] == 1:\n\t\t\t\t\t\t\t\t\t\t\t\t\tremarks = 'Anomaly Detected - Frequent Cluster Hopping'\t\n\t\t\t\t\t\t\t\t\t\t\t\t\tanomaly = True\n\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\tremarks = 'Cluster Hopping Detected'\n\t\t\t\t\t\t\t\t\t\t\t\tuser_records['pageclicks'] = 0\n\t\t\t\t\t\t\t\t\t\t\t\tif user_records['NoOfClusterHopping'] > int(groupswitching) and anomaly == False:\n\t\t\t\t\t\t\t\t\t\t\t\t\tremarks = 'Anomaly Detected - Multiple Cluster Hopping' \t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\tanomaly = True\n\t\t\t\t\t\t\t\t\t\t\telif probability == 0:\n\t\t\t\t\t\t\t\t\t\t\t\tremarks = 'Anomaly Detected - Unusual State Transition Detected'\n\t\t\t\t\t\t\t\t\t\t\t\tanomaly = True\n\t\t\t\t\t\t\t\t\t\t\telif probability <= float(page_threshold):\n\t\t\t\t\t\t\t\t\t\t\t\tremarks = 'Anomaly Detected - In-frequent State Transition Detected'\t\t\n\t\t\t\t\t\t\t\t\t\t\t\tanomaly = True\n\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\tif pageswitch == True:\n\t\t\t\t\t\t\t\t\t\t\t\tif probability == 0:\n\t\t\t\t\t\t\t\t\t\t\t\t\tremarks = 'Anomaly Detected - Unusual State Transition Detected'\n\t\t\t\t\t\t\t\t\t\t\t\t\tanomaly = True\n\t\t\t\t\t\t\t\t\t\t\t\telif probability <= float(page_threshold):\n\t\t\t\t\t\t\t\t\t\t\t\t\tremarks = 'Anomaly Detected - In-frequent State Transition Detected'\n\t\t\t\t\t\t\t\t\t\t\t\t\tanomaly = True\n\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\tremarks = '' \n\t\t\t\t\t\t\t\t\t\tif davg < float(chain_probability):\n\t\t\t\t\t\t\t\t\t\t\tif anomaly == False:\n\t\t\t\t\t\t\t\t\t\t\t\tremarks = 'Anomaly Detected - In-frequent Pattern Detected' \t\n\t\t\t\t\t\t\t\t\t\t\t\tanomaly = True\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tuser_records['SessionID'] = data[sessionid]\n\t\t\t\t\t\t\t\tuser_records['Activity'] = data[activity]\n\t\t\t\t\t\t\t\tuser_records['probability'] = 0\n\t\t\t\t\t\t\t\tuser_records['probarry'] = []\n\t\t\t\t\t\t\t\tuser_records['chainprobability'] = 0\n\t\t\t\t\t\t\t\tuser_records['prevclusterid'] = -1\n\t\t\t\t\t\t\t\tuser_records['NoOfClusterHopping'] = 0\n\t\t\t\t\t\t\t\tuser_records['pageclicks'] = 1\n\t\t\t\t\t\t\t\tfor index, row in dfclus.iterrows():\n\t\t\t\t\t\t\t\t\tclusterlist = row[\"clusterlist\"]\n\t\t\t\t\t\t\t\t\tif currentactivity in clusterlist:\n\t\t\t\t\t\t\t\t\t\tclusterid = row[\"clusterid\"]\n\t\t\t\t\t\t\tuser_records['prevclusterid'] = clusterid\n\t\t\t\t\t\t\toutputStr = '{\"status\":\"SUCCESS\",\"data\":{\"Anomaly\":\"'+str(anomaly)+'\",\"Remarks\":\"'+str(remarks)+'\"}}'\n\t\t\t\t\t\telif operation.lower() == 'pattern_anomaly_settings':\n\t\t\t\t\t\t\tdata = json.loads(data)\n\t\t\t\t\t\t\tgroupswitching = data['groupswitching']\n\t\t\t\t\t\t\ttransitionprobability = data['transitionprobability']\n\t\t\t\t\t\t\ttransitionsequence = data['transitionsequence']\n\t\t\t\t\t\t\tsequencethreshold = data['sequencethreshold']\n\t\t\t\t\t\t\tfilename = os.path.join(model_path,'clickstream.json')\n\t\t\t\t\t\t\tdata = {}\n\t\t\t\t\t\t\tdata['groupswitching'] = groupswitching\n\t\t\t\t\t\t\tdata['transitionprobability'] = transitionprobability\n\t\t\t\t\t\t\tdata['transitionsequence'] = transitionsequence\n\t\t\t\t\t\t\tdata['sequencethreshold'] = sequencethreshold\n\t\t\t\t\t\t\tupdatedConfig = json.dumps(data)\n\t\t\t\t\t\t\twith open(filename, \"w\") as fpWrite:\n\t", "instruction": "", "output": "" }, { "input": "\t\t\t\t\t\t\tfpWrite.write(updatedConfig) \n\t\t\t\t\t\t\tfpWrite.close()\n\t\t\t\t\t\t\toutputStr = '{\"Status\":\"SUCCESS\"}' \n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\toutputStr = \"{'Status':'Error','Msg':'Operation not supported'}\" \n\t\t\t\t\telse:\n\t\t\t\t\t\toutputStr = \"{'Status':'Error','Msg':'Model Not Present'}\" \n\t\t\t\t\tresp = outputStr\n\t\t\t\t\tresp=resp+\"\\\\n\"\n\t\t\t\t\tresp=resp.encode()\n\t\t\t\t\tself.send_response(200)\n\t\t\t\t\tself.send_header('Content-Type', 'application/json')\n\t\t\t\t\tself.end_headers()\n\t\t\t\t\tself.wfile.write(resp)\n\t\t\t\telse:\n\t\t\t\t\tself.do_AUTHHEAD()\n\t\t\t\t\tself.wfile.write(self.headers.get(\"Authorization\").encode())\n\t\t\t\t\tresp = \"Authentication Failed\"\n\t\t\t\t\tresp=resp.encode()\n\t\t\t\t\tself.wfile.write(resp)\n\t\t\telse:\n\t\t\t\tprint(\"python ==> else1\")\n\t\t\t\tself.send_response(403)\n\t\t\t\tself.send_header('Content-Type', 'application/json')\n\t\t\t\tself.end_headers()\n\t\t\t\tprint(\"PYTHON ######## REQUEST ####### ENDED\")\n\t\t\treturn\n\tdef getModelFeatures(self,modelSignature): \n\t\tdatajson = {'Body':'Gives the list of features'} \n\t\thome = expanduser(\"~\")\n\t\tif platform.system() == 'Windows':\n\t\t\tpredict_path = os.path.join(home,'AppData','Local','HCLT','AION','target',modelSignature,'featureslist.py')\n\t\telse:\n\t\t\tpredict_path = os.path.join(home,'HCLT','AION','target',modelSignature,'featureslist.py')\n\t\tif(os.path.isfile(predict_path)):\n\t\t\toutputStr = subprocess.check_output([sys.executable,predict_path])\n\t\t\toutputStr = outputStr.decode('utf-8')\n\t\t\toutputStr = re.search(r'features:(.*)',str(outputStr), re.IGNORECASE).group(1)\n\t\t\toutputStr = outputStr.strip()\n\t\t\tdisplaymsg = outputStr\n\t\t\t#displaymsg = json.dumps(displaymsg)\n\t\t\treturn(True,displaymsg)\n\t\telse:\n\t\t\tdisplaymsg = \"{'status':'ERROR','msg':'Unable to fetch featuers'}\" \t\t\n\t\treturn(False,displaymsg) \n \n\tdef getFeatures(self,modelSignature): \n\t\tdatajson = {'Body':'Gives the list of features'}\n\t\turltext = '/AION/UseCase_Version/features'\n\t\tif modelSignature != '':\n\t\t\tstatus,displaymsg = self.getModelFeatures(modelSignature)\n\t\t\tif status:\n\t\t\t\turltext = '/AION/'+modelSignature+'/features' \n\t\t\telse:\n\t\t\t\tdisplaymsg = json.dumps(datajson)\n\t\telse:\n\t\t\tdisplaymsg = json.dumps(datajson)\n\t\tmsg=\"\"\"\nURL:{url}\nRequestType: POST\nContent-Type=application/json\nOutput: {displaymsg}. \n\t\t\t\"\"\".format(url=urltext,displaymsg=displaymsg) \n\t\treturn(msg)\n \n\tdef features_help(self,modelSignature):\n\t\thome = expanduser(\"~\")\n\t\tif platform.system() == 'Windows':\n\t\t\tdisplay_path = os.path.join(home,'AppData','Local','HCLT','AION','target',modelSignature,'display.json')\n\t\telse:\n\t\t\tdisplay_path = os.path.join(home,'HCLT','AION','target',modelSignature,'display.json')\n\t\t#display_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'target',model,'display.json')\n\t\tdatajson = {'Body':'Data Should be in JSON Format'}\n\t\tif(os.path.isfile(display_path)):\n\t\t\twith open(display_path) as file:\n\t\t\t\tconfig = json.load(file)\n\t\t\tfile.close()\n\t\t\tdatajson={}\n\t\t\tfor feature in config['numericalFeatures']:\n\t\t\t\tif feature != config['targetFeature']:\n\t\t\t\t\tdatajson[feature] = 'Numeric Value'\n\t\t\tfor feature in config['nonNumericFeatures']:\n\t\t\t\tif feature != config['targetFeature']:\n\t\t\t\t\tdatajson[feature] = 'Category Value'\n\t\t\tfor feature in config['textFeatures']:\n\t\t\t\tif feature != config['targetFeature']: \n\t\t\t\t\tdatajson[feature] = 'Category Value'\n\t\tdisplaymsg = json.dumps(datajson)\t\n\t\treturn(displaymsg)\n\tdef predict_help(self,modelSignature):\n\t\tif modelSignature != '':\n\t\t\tdisplaymsg = self.features_help(modelSignature)\n\t\t\turltext = '/AION/'+modelSignature+'/predict'\n\t\telse:\n\t\t\tdatajson = {'Body':'Data Should be in JSON Format'}\n\t\t\tdisplaymsg = json.dumps(datajson)\n\t\t\turltext = '/AION/UseCase_Version/predict'\n\t\tmsg=\"\"\"\nURL:{url}\nRequestType: POST\nContent-Type=application/json\nBody: {displaymsg}\nOutput: prediction,probability(if Applicable),remarks corresponding to each row. \n\t\t\t\"\"\".format(url=urltext,displaymsg=displaymsg) \n\t\treturn(msg)\n\tdef performance_help(self,modelSignature):\n\t\tif modelSignature != '':\n\t\t\turltext = '/AION/'+modelSignature+'/performance'\n\t\telse:\n\t\t\turltext = '/AION/UseCase_Version/performance'\n\t\tdatajson = {\"trainingDataLocation\":\"Reference Data File Path\",\"currentDataLocation\":\"Latest Data File Path\"}\n\t\tdisplaymsg = json.dumps(datajson)\n\t\tmsg=\"\"\"\nURL:{url}\nRequestType: POST\nContent-Type=application/json\nBody: {displaymsg}\nOutput: HTML File Path.\"\"\".format(url=urltext,displaymsg=displaymsg) \n\t\treturn(msg) \n\tdef monitoring_help(self,modelSignature):\n\t\tif modelSignature != '':\n\t\t\turltext = '/AION/'+modelSignature+'/monitoring'\n\t\telse:\n\t\t\turltext = '/AION/UseCase_Version/monitoring'\n\t\tdatajson = {\"trainingDataLocation\":\"Reference Data File Path\",\"currentDataLocation\":\"Latest Data File Path\"}\n\t\tdisplaymsg = json.dumps(datajson)\n\t\tmsg=\"\"\"\nURL:{url}\nRequestType: POST\nContent-Type=application/json\nBody: {displaymsg}\nOutput: Affected Columns. HTML File Path.\"\"\".format(url=urltext,displaymsg=displaymsg) \n\t\treturn(msg) \n\tdef explain_help(self,modelSignature):\n\t\tif modelSignature != '':\n\t\t\tdisplaymsg = self.features_help(modelSignature)\n\t\t\turltext = '/AION/'+modelSignature+'/explain'\n\t\telse:\n\t\t\tdatajson = {'Body':'Data Should be in JSON Format'}\n\t\t\tdisplaymsg = json.dumps(datajson)\n\t\t\turltext = '/AION/UseCase_Version/explain'\n\t\tmsg=\"\"\"\nURL:{url}\nRequestType: POST\nContent-Type=application/json\nBody: {displaymsg}\nOutput: anchor (Local Explanation),prediction,forceplot,multidecisionplot.\"\"\".format(url=urltext,displaymsg=displaymsg) \n\t\treturn(msg) \n\tdef help_text(self,modelSignature): \n\t\tpredict_help = self.predict_help(modelSignature) \n\t\texplain_help = self.explain_help(modelSignature) \n\t\tfeatures_help = self.getFeatures(modelSignature)\n\t\tmonitoring_help = self.monitoring_help(modelSignature)\n\t\tperformance_help = self.performance_help(modelSignature)\n\t\tmsg=\"\"\"\nFollowing URL:\n\nPrediction\n{predict_help}\n\nLocal Explaination\n{explain_help}\n\nFeatures\n{features_help}\n\nMonitoring\n{monitoring_help}\n\nPerformance\n{performance_help}\n\"\"\".format(predict_help=predict_help,explain_help=explain_help,features_help=features_help,monitoring_help=monitoring_help,performance_help=performance_help)\n\t\treturn msg\n \n\tdef do_GET(self):\n\t\tprint(\"PYTHON ######## REQUEST ####### STARTED\")\n\t\tif None != re.search('/AION/', self.path):\n\t\t\tself.send_response(200)\n\t\t\tself.send_header('Content-Type', 'application/json')\n\t\t\tself.end_headers()\n\t\t\thelplist = self.path.split('/')[-1]\n\t\t\tprint(helplist)\n\t\t\tif helplist.lower() == 'help':\n\t\t\t\tmodel = self.path.split('/')[-2] \n\t\t\t\tif model.lower() == 'aion':\n\t\t\t\t\tmodel =''\n\t\t\t\tmsg = self.help_text(model) \n\t\t\telif helplist.lower() == 'predict':\n\t\t\t\tmodel = self.path.split('/')[-2] \n\t\t\t\tif model.lower() == 'aion':\n\t\t\t\t\tmodel =''\n\t\t\t\tmsg = self.predict_help(model) \n\t\t\telif helplist.lower() == 'explain':\n\t\t\t\tmodel = self.path.split('/')[-2] \n\t\t\t\tif model.lower() == 'aion':\n\t\t\t\t\tmodel =''\n\t\t\t\tmsg = self.explain_help(model) \n\t\t\telif helplist.lower() == 'monitoring':\n\t\t\t\tmodel = self.path.split('/')[-2] \n\t\t\t\tif model.lower() == 'aion':\n\t\t\t\t\tmodel =''\n\t\t\t\tmsg = self.monitoring_help(model)\n\t\t\telif helplist.lower() == 'performance':\n\t\t\t\tmodel = self.path.split('/')[-2] \n\t\t\t\tif model.lower() == 'aion':\n\t\t\t\t\tmodel =''\n\t\t\t\tmsg = self.performance_help(model)\n\t\t\telif helplist.lower() == 'features':\n\t\t\t\tmodel = self.path.split('/')[-2] \n\t\t\t\tif model.lower() == 'aion':\n\t\t\t\t\tmodel =''\n\t\t\t\tstatus,msg = self.getModelFeatures(model)\n\t\t\telse:\n\t\t\t\tmodel = self.path.split('/')[-2] \n\t\t\t\tif model.lower() == 'aion':\n\t\t\t\t\tmodel =helplist\n\t\t\t\tmsg = self.help_text(model) \n\t\t\tself.wfile.write(msg.encode())\n\t\telse:\n\t\t\tself.send_response(403)\n\t\t\tself.send_header('Content-Type', 'application/json')\n\t\t\tself.end_headers()\n\t\treturn\n\t\nclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer):\n\tallow_reuse_address = True\n \n\tdef shutdown(self):\n\t\tself.socket.close()\n\t\tHTTPServer.shutdown(self)\n \nclass SimpleHttpServer():\n\tdef __init__(self, ip, port,username,password):\n\t\thandler_class = partial(HTTPRequestHandler,username=username,password=password,)\n\t\tself.server = ThreadedHTTPServer((ip,port), handler_class)\n \n\tdef start(self):\n\t\tself.server_thread = threading.Thread(target=self.server.serve_forever)\n\t\tself.server_thread.daemon = True\n\t\tself.server_thread.start()\n \n\tdef waitForThread(self):\n\t\tself.server_thread.join()\n \n\tdef stop(self):\n\t\tself.server.shutdown()\n\t\tself.waitForThread()\n\ndef start_server(ip,port,username,password):\n\tserver = SimpleHttpServer(ip,int(port),username,password)\n\tprint('HTTP Server Running...........')\n\tserver.start()\n\tserver.waitForThread()\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport joblib\nimport time\nimport pandas as pd\nimport numpy as np\nimport argparse\nimport json\nimport os\nimport pathlib\nfrom pathlib import Path\nfrom uncertainties.uq_main import aionUQ\nimport os\nfrom datetime import datetime\nfrom os.path import expanduser\nimport platform\nimport logging\n\nclass run_uq:\n def __init__(self,modelfeatures,modelFile,csvFile,target):\n self.modelfeatures=modelfeatures\n self.modelFile=modelFile\n self.csvFile=csvFile\n self.target=target\n ##UQ classification fn \n def getUQclassification(self,model,ProblemName,Params):\n df = pd.read_csv(self.csvFile)\n \n # # 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) \n object_cols = [col for col, col_type in zip(df.columns,df.dtypes) if col_type == 'object']\n \n df = df.drop(object_cols, axis=1)\n df = df.dropna(axis=1)\n df = df.reset_index(drop=True) \n modelfeatures = self.modelfeatures\n #tar = args.target\n # target = df[tar] \n y=df[self.target].values\n y = y.flatten()\n X = df.drop(self.target, axis=1)\n try:\n uqObj=aionUQ(df,X,y,ProblemName,Params,model,modelfeatures,self.target)\n accuracy,uq_ece,output_jsonobject=uqObj.uqMain_BBMClassification()\n except Exception as e:\n print(\"uq error\",e)\n # print(\"UQ Classification: \\\\n\",output_jsonobject)\n # print(accuracy,uq_ece,output_jsonobject,model_confidence_per,model_uncertaitny_per)\n #print(output_jsonobject)\n return accuracy,uq_ece,output_jsonobject\n \n ##UQ regression fn \n def getUQregression(self,model,ProblemName,Params):\n \n df = pd.read_csv(self.csvFile)\n modelfeatures = self.modelfeatures\n dfp = df[modelfeatures]\n tar = self.target\n target = df[tar]\n uqObj=aionUQ(df,dfp,target,ProblemName,Params,model,modelfeatures,tar)\n total_picp_percentage,total_Uncertainty_percentage,uq_medium,uq_best,scoringCriteria,uq_jsonobject=uqObj.uqMain_BB", "instruction": "", "output": "" }, { "input": "MRegression()\n return total_picp_percentage,total_Uncertainty_percentage,uq_medium,uq_best,scoringCriteria,uq_jsonobject\n \n def uqMain(self,model):\n #print(\"inside uq main.\\\\n\")\n reg_status=\"\"\n class_status=\"\"\n algorithm_status=\"\"\n try:\n model=model\n if Path(self.modelFile).is_file(): \n ProblemName = model.__class__.__name__ \n if ProblemName in ['LogisticRegression','SGDClassifier','SVC','DecisionTreeClassifier','RandomForestClassifier','GaussianNB','KNeighborsClassifier','GradientBoostingClassifier']:\n Problemtype = 'Classification'\n elif ProblemName in ['LinearRegression','Lasso','Ridge','DecisionTreeRegressor','RandomForestRegressor']:\n Problemtype = 'Regression'\n else:\n Problemtype = \"None\"\n \n if Problemtype.lower() == 'classification':\n try:\n Params = model.get_params()\n accuracy,uq_ece,output = self.getUQclassification(model,ProblemName,Params)\n class_status=\"SUCCESS\"\n #print(output)\n except Exception as e:\n print(e)\n class_status=\"FAILED\"\n output = {'Problem':'None','msg':str(e)}\n output = json.dumps(output)\n elif Problemtype.lower() == 'regression' :\n try:\n Params = model.get_params()\n total_picp_percentage,total_Uncertainty_percentage,uq_medium,uq_best,scoringCriteria,output = self.getUQregression(model,ProblemName,Params)\n #print(uq_jsonobject)\n reg_status=\"SUCCESS\"\n except Exception as e:\n output = {'Problem':'None','msg':str(e)}\n output = json.dumps(output)\n reg_status=\"FAILED\"\n else:\n try: \n output={}\n output['Problem']=\"None\"\n output['msg']=\"Uncertainty Quantification not supported for this algorithm.\"\n output = json.dumps(output)\n algorithm_status=\"FAILED\"\n except:\n algorithm_status=\"FAILED\" \n except Exception as e:\n print(e)\n reg_status=\"FAILED\"\n class_status=\"FAILED\"\n algorithm_status=\"FAILED\"\n output = {'Problem':'None','msg':str(e)}\n output = json.dumps(output)\n return class_status,reg_status,algorithm_status,output\n \n \ndef aion_uq(modelFile,dataFile,features,targetfeatures):\n try:\n from appbe.dataPath import DEPLOY_LOCATION\n uqLogLocation = os.path.join(DEPLOY_LOCATION,'logs')\n try:\n os.makedirs(uqLogLocation)\n except OSError as e:\n if (os.path.exists(uqLogLocation)):\n pass\n else:\n raise OSError('uqLogLocation error.')\n \n filename_uq = 'uqlog_'+str(int(time.time()))\n filename_uq=filename_uq+'.log'\n filepath = os.path.join(uqLogLocation, filename_uq) \n print(filepath)\n logging.basicConfig(filename=filepath, format='%(message)s',filemode='w') \n log = logging.getLogger('aionUQ')\n log.setLevel(logging.INFO)\n log.info('************* Version - v1.7.0 *************** \\\\n') \n if isinstance(features, list):\n modelfeatures = features\n else:\n if ',' in features:\n modelfeatures = [x.strip() for x in features.split(',')]\n else:\n modelfeatures = features.split(',') \n model = joblib.load(modelFile)\n \n uqobj = run_uq(modelfeatures,modelFile,dataFile,targetfeatures)\n class_status,reg_status,algorithm_status,output=uqobj.uqMain(model)\n if (class_status.lower() == 'failed'):\n log.info('uq classifiction failed./n')\n elif (class_status.lower() == 'success'):\n log.info('uq classifiction success./n')\n else:\n log.info('uq classifiction not used../n')\n \n if (reg_status.lower() == 'failed'):\n log.info('uq regression failed./n')\n elif (reg_status.lower() == 'success'):\n log.info('uq regression success./n')\n else:\n log.info('uq regression not used./n')\n if (algorithm_status.lower() == 'failed'):\n log.info('Problem type issue, UQ only support classification and regression. May be selected algorithm not supported by Uncertainty Quantification currently./n')\n \n except Exception as e:\n log.info('uq test failed.n'+str(e))\n #print(e)\n output = {'Problem':'None','msg':str(e)}\n output = json.dumps(output)\n \n return(output)\n#Sagemaker main fn call\n\nif __name__=='__main__':\n \n try:\n parser = argparse.ArgumentParser()\n parser.add_argument('savFile')\n parser.add_argument('csvFile')\n parser.add_argument('features')\n parser.add_argument('target')\n args = parser.parse_args()\n home = expanduser(\"~\")\n if platform.system() == 'Windows':\n uqLogLocation = os.path.join(home,'AppData','Local','HCLT','AION','uqLogs')\n else:\n uqLogLocation = os.path.join(home,'HCLT','AION','uqLogs')\n \n try:\n os.makedirs(uqLogLocation)\n except OSError as e:\n if (os.path.exists(uqLogLocation)):\n pass\n else:\n raise OSError('uqLogLocation error.')\n # self.sagemakerLogLocation=str(sagemakerLogLocation)\n filename_uq = 'uqlog_'+str(int(time.time()))\n filename_uq=filename_uq+'.log'\n # filename = 'mlopsLog_'+Time()\n filepath = os.path.join(uqLogLocation, filename_uq) \n logging.basicConfig(filename=filepath, format='%(message)s',filemode='w') \n log = logging.getLogger('aionUQ')\n log.setLevel(logging.DEBUG)\n \n \n if ',' in args.features:\n args.features = [x.strip() for x in args.features.split(',')]\n else:\n args.features = args.features.split(',')\n modelFile = args.savFile\n modelfeatures = args.features\n csvFile = args.csvFile\n target=args.target\n model = joblib.load(args.savFile)\n ##Main uq function call\n uqobj = run_uq(modelfeatures,modelFile,csvFile,target)\n class_status,reg_status,algorithm_status,output=uqobj.uqMain(model)\n \n if (class_status.lower() == 'failed'):\n log.info('uq classifiction failed./n')\n elif (class_status.lower() == 'success'):\n log.info('uq classifiction success./n')\n else:\n log.info('uq classifiction not used../n')\n \n if (reg_status.lower() == 'failed'):\n log.info('uq regression failed./n')\n elif (reg_status.lower() == 'success'):\n log.info('uq regression success./n')\n else:\n log.info('uq regression not used./n')\n if (algorithm_status.lower() == 'failed'):\n msg = 'Uncertainty Quantification not supported for this algorithm'\n log.info('Algorithm not supported by Uncertainty Quantification./n')\n output = {'Problem':'None','msg':str(msg)}\n output = json.dumps(output)\n except Exception as e:\n log.info('uq test failed.n'+str(e))\n output = {'Problem':'None','msg':str(e)}\n output = json.dumps(output)\n #print(e)\n print(output) '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport logging\nlogging.getLogger('tensorflow').disabled = True\n#from autogluon.tabular import TabularDataset, TabularPredictor\n#from autogluon.core.utils.utils import setup_outputdir\n#from autogluon.core.utils.loaders import load_pkl\n#from autogluon.core.utils.savers import save_pkl\nimport datetime, time, timeit\nfrom datetime import datetime as dt\nimport os.path\nimport json\nimport io\nimport shutil\nimport sys\n\n#from Gluon_MultilabelPredictor import MultilabelPredictor\n\nclass MultilabelPredictor():\n\n \"\"\" Tabular Predictor for predicting multiple columns in table.\n Creates multiple TabularPredictor objects which you can also use individually.\n You can access the TabularPredictor for a particular label via: `multilabel_predictor.get_predictor(label_i)`\n\n Parameters\n ----------\n labels : List[str]\n The ith element of this list is the column (i.e. `label`) predicted by the ith TabularPredictor stored in this object.\n path : str\n Path to directory where models and intermediate outputs should be saved.\n If unspecified, a time-stamped folder called \"AutogluonModels/ag-[TIMESTAMP]\" will be created in the working directory to store all models.\n 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.\n Otherwise files from first `fit()` will be overwritten by second `fit()`.\n Caution: when predicting many labels, this directory may grow large as it needs to store many TabularPredictors.\n problem_types : List[str]\n The ith element is the `problem_type` for the ith TabularPredictor stored in this object.\n eval_metrics : List[str]\n The ith element is the `eval_metric` for the ith TabularPredictor stored in this object.\n consider_labels_correlation : bool\n Whether the predictions of multiple labels should account for label correlations or predict each label independently of the others.\n 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).\n Set to False if during inference you may want to individually use just the ith TabularPredictor without predicting all the other labels.\n kwargs :\n Arguments passed into the initialization of each TabularPredictor.\n\n \"\"\"\n\n multi_predictor_file = 'multilabel_predictor.pkl'\n\n def __init__(self, labels, path, problem_types=None, eval_metrics=None, consider_labels_correlation=True, **kwargs):\n if len(labels) < 2:\n raise ValueError(\"MultilabelPredictor is only intended for predicting MULTIPLE labels (columns), use TabularPredictor for predicting one label (column).\")\n self.path = setup_outputdir(path, warn_if_exist=False)\n self.labels = labels\n #print(self.labels)\n self.consider_labels_correlation = consider_labels_correlation\n self.predictors = {} # key = label, value = TabularPredictor or str path to the TabularPredictor for this label\n if eval_metrics is None:\n self.eval_metrics = {}\n else:\n self.eval_metrics = {labels[i] : eval_metrics[i] for i in range(len(labels))}\n problem_type = None\n eval_metric = None\n for i in range(len(labels)):\n label = labels[i]\n path_i = self.path + \"Predictor_\" + label\n if problem_types is not None:\n problem_type = problem_types[i]\n if eval_metrics is not None:\n eval_metric = self.eval_metrics[i]\n self.predictors[label] = TabularPredictor(label=label, problem_type=problem_type, eval_metric=eval_metric, path=path_i, **kwargs)\n\n def fit(self, train_data, tuning_data=None, **kwargs):\n \"\"\" Fits a separate TabularPredictor to predict each of the labels.\n\n Parameters\n ----------\n train_data, tuning_data : str or autogluon.tabular.TabularDataset or pd.DataFrame\n See documentation for `TabularPredictor.fit()`.\n kwargs :\n Arguments passed into the `fit()` call for each TabularPredictor.\n \"\"\"\n if isinstance(train_data, str):\n train_data = TabularDataset(train_data)\n if tuning_data is not None and isinstance(tuning_data, str):\n tuning_data = TabularDataset(tuning_data)\n train_data_og = train_data.copy()\n if tuning_data is not None:\n tuning_data_og = tuning_data.copy()\n save_metrics = len(self.eval_metrics) == 0\n for i in range(len(self.labels)):\n label = self.labels[i]\n predictor = self.get_predictor(label)\n if not self.consider_labels_correlation:\n labels_to_drop = [l for l in self.labels if l!=label]\n else:\n labels_to_drop = [self.labels[j] for j in range(i+1,len(self.labels))]\n train_data = train_data_og.drop(labels_to_drop, axis=1)\n if tuning_data is not None:\n tuning_data = tuning_data_og.drop(labels_to_drop, axis=1)\n print(f\"Fitting TabularPredictor for label: {label} ...\")\n predictor.fit(train_data=train_data, tuning_data=tuning_data, **kwargs)\n self.predictors[label] = predictor.path\n if save_metrics:\n self.eval_metrics[label] = predictor.eval_metric\n self.save()\n\n def eval_metrics(self):\n return(self.eval_metrics)\n\n def predict(self, data, **kwargs):\n \"\"\" Returns DataFrame with label columns containing predictions for each label.\n\n Parameters\n ----------\n data : str or autogluon.tabular.TabularDataset or pd.DataFrame\n Data to make predictions for. If label columns are present in this data, they will be ignored. See documentation for `TabularPredictor.predict()`.\n kwargs :\n Arguments passed into the predict() call for each TabularPredictor.\n \"\"\"\n return self._predict(data, as_proba=False, **kwargs)\n\n def predict_proba(self, data, **kwargs):\n \"\"\" Returns dict where each key is a label and the corresponding value is the `predict_proba()` output for just that label.\n\n Parameters\n ----------\n data : str or autogluon.tabular.TabularDataset or pd.", "instruction": "", "output": "" }, { "input": "DataFrame\n Data to make predictions for. See documentation for `TabularPredictor.predict()` and `TabularPredictor.predict_proba()`.\n kwargs :\n Arguments passed into the `predict_proba()` call for each TabularPredictor (also passed into a `predict()` call).\n \"\"\"\n return self._predict(data, as_proba=True, **kwargs)\n\n def evaluate(self, data, **kwargs):\n \"\"\" Returns dict where each key is a label and the corresponding value is the `evaluate()` output for just that label.\n\n Parameters\n ----------\n data : str or autogluon.tabular.TabularDataset or pd.DataFrame\n Data to evalate predictions of all labels for, must contain all labels as columns. See documentation for `TabularPredictor.evaluate()`.\n kwargs :\n Arguments passed into the `evaluate()` call for each TabularPredictor (also passed into the `predict()` call).\n \"\"\"\n data = self._get_data(data)\n eval_dict = {}\n for label in self.labels:\n print(f\"Evaluating TabularPredictor for label: {label} ...\")\n predictor = self.get_predictor(label)\n eval_dict[label] = predictor.evaluate(data, **kwargs)\n if self.consider_labels_correlation:\n data[label] = predictor.predict(data, **kwargs)\n return eval_dict\n\n def save(self):\n \"\"\" Save MultilabelPredictor to disk. \"\"\"\n for label in self.labels:\n if not isinstance(self.predictors[label], str):\n self.predictors[label] = self.predictors[label].path\n save_pkl.save(path=self.path+self.multi_predictor_file, object=self)\n print(f\"MultilabelPredictor saved to disk. Load with: MultilabelPredictor.load('{self.path}')\")\n\n @classmethod\n def load(cls, path):\n \"\"\" Load MultilabelPredictor from disk `path` previously specified when creating this MultilabelPredictor. \"\"\"\n path = os.path.expanduser(path)\n if path[-1] != os.path.sep:\n path = path + os.path.sep\n return load_pkl.load(path=path+cls.multi_predictor_file)\n\n def get_predictor(self, label):\n \"\"\" Returns TabularPredictor which is used to predict this label. \"\"\"\n predictor = self.predictors[label]\n if isinstance(predictor, str):\n return TabularPredictor.load(path=predictor)\n return predictor\n\n def _get_data(self, data):\n if isinstance(data, str):\n return TabularDataset(data)\n return data.copy()\n\n def _predict(self, data, as_proba=False, **kwargs):\n data = self._get_data(data)\n if as_proba:\n predproba_dict = {}\n for label in self.labels:\n print(f\"Predicting with TabularPredictor for label: {label} ...\")\n predictor = self.get_predictor(label)\n if as_proba:\n predproba_dict[label] = predictor.predict_proba(data, as_multiclass=True, **kwargs)\n data[label] = predictor.predict(data, **kwargs)\n if not as_proba:\n return data[self.labels]\n else:\n return predproba_dict\n\ndef aion_train_gluon(arg):\n configFile = arg\n with open(configFile, 'rb') as cfile:\n data = json.load(cfile) \n cfile.close() \n rootElement = data['basic']\n modelname = rootElement['modelName']\n version = rootElement['modelVersion']\n dataLocation = rootElement['dataLocation']\n deployFolder = rootElement['deployLocation']\n analysisType = rootElement['analysisType']\n testPercentage = data['advance']['testPercentage']\n deployLocation = os.path.join(deployFolder,modelname+'_'+version)\n try:\n os.makedirs(deployLocation)\n except OSError as e:\n shutil.rmtree(deployLocation)\n os.makedirs(deployLocation)\n logLocation = os.path.join(deployLocation,'log')\n try:\n os.makedirs(logLocation)\n except OSError as e:\n pass\n etcLocation = os.path.join(deployLocation,'etc')\n try:\n os.makedirs(etcLocation)\n except OSError as e:\n pass\n logFileName=os.path.join(deployLocation,'log','model_training_logs.log')\n filehandler = logging.FileHandler(logFileName, 'w','utf-8')\n formatter = logging.Formatter('%(message)s')\n filehandler.setFormatter(formatter)\n log = logging.getLogger('eion')\n log.propagate = False\n for hdlr in log.handlers[:]: # remove the existing file handlers\n if isinstance(hdlr,logging.FileHandler):\n log.removeHandler(hdlr)\n log.addHandler(filehandler)\n log.setLevel(logging.INFO)\n log.info('************* Version - v1.2.0 *************** \\\\n')\n msg = '-------> Execution Start Time: '+ dt.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')\n log.info(msg)\n dataLabels = rootElement['targetFeature'].split(',')\n \n\n # Create and Write the config file used in Prediction\n # ----------------------------------------------------------------------------#\n \n tdata = TabularDataset(dataLocation) \n #train_data = tdata\n train_data = tdata.sample(frac = 0.8)\n test_data = tdata.drop(train_data.index)\n\n if rootElement['trainingFeatures'] != '':\n trainingFeatures = rootElement['trainingFeatures'].split(',')\n else:\n trainingFeatures = list(train_data.columns)\n features = trainingFeatures\n for x in dataLabels:\n if x not in features:\n features.append(x)\n indexFeature = rootElement['indexFeature']\n if indexFeature != '':\n indexFeature = indexFeature.split(',')\n for x in indexFeature:\n if x in features:\n features.remove(x) \n dateTimeFeature = rootElement['dateTimeFeature']\n if dateTimeFeature != '':\n dateTimeFeature = dateTimeFeature.split(',')\n for x in dateTimeFeature:\n if x in features:\n features.remove(x) \n train_data = train_data[features]\n test_data = test_data[features]\n \n \n configJsonFile = {\"targetFeature\":dataLabels,\"features\":\",\".join([feature for feature in features])}\n configJsonFilePath = os.path.join(deployLocation,'etc','predictionConfig.json')\n if len(dataLabels) == 1 and analysisType['multiLabelPrediction'] == \"False\":\n dataLabels = rootElement['targetFeature']\n with io.open(configJsonFilePath, 'w', encoding='utf8') as outfile:\n str_ = json.dumps(configJsonFile, ensure_ascii=False)\n outfile.write(str_)\n # ----------------------------------------------------------------------------#\n if analysisType['multiLabelPrediction'] == \"True\": \n \n # Copy and Write the Predictiion script file into deployment location\n # ----------------------------------------------------------------------------#\n srcFile = os.path.join(os.path.dirname(__file__),'gluon','AION_Gluon_MultiLabelPrediction.py')\n dstFile = os.path.join(deployLocation,'aion_predict.py')\n shutil.copy(srcFile,dstFile)\n # ----------------------------------------------------------------------------#\t\t\n \n labels = dataLabels # which columns to predict based on the others\n #problem_types = dataProblem_types # type of each prediction problem\n save_path = os.path.join(deployLocation,'ModelPath') # specifies folder to store trained models\n time_limit = 5 # how many seconds to train the TabularPredictor for each label\n log.info('Status:-|... AION Gluon Start')\n try:\n if len(labels) < 2:\n log.info('Status:-|... AION Evaluation Error: Target should be multiple column')\n # ----------------------------------------------------------------------------#\n output = {'status':'FAIL','message':'Number of target variable should be 2 or more than 2'}\n else:\t\t\t\t\n multi_predictor = MultilabelPredictor(labels=labels, path=save_path)\n multi_predictor.fit(train_data, time_limit=time_limit)\n log.info('Status:-|... AION Gluon Stop')\n log.info('Status:-|... AION Evaluation Start')\n trainevaluations = multi_predictor.evaluate(train_data)\n testevaluations = multi_predictor.evaluate(test_data) \n \n best_model = {} \n for label in labels:\n predictor_class = multi_predictor.get_predictor(label)\n predictor_class.get_model_best()\n best_model[label] = predictor_class.get_model_best() \n \n log.info('Status:-|... AION Evaluation Stop')\n # ----------------------------------------------------------------------------#\n 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}}\n except Exception as inst:\n log.info('Status:-|... AION Gluon Error')\n output = {\"status\":\"FAIL\",\"message\":str(inst).strip('\"')}\n if analysisType['multiModalLearning'] == \"True\":\n from autogluon.core.utils.utils import get_cpu_count, get_gpu_count\n from autogluon.text import TextPredictor \n # check the system and then set the equivelent flag\n # ----------------------------------------------------------------------------#\n os.environ[\"AUTOGLUON_TEXT_TRAIN_WITHOUT_GPU\"] = \"0\"\n if get_gpu_count() == 0:\n os.environ[\"AUTOGLUON_TEXT_TRAIN_WITHOUT_GPU\"] = \"1\"\n # ----------------------------------------------------------------------------#\n # Copy and Write the Predictiion script file into deployment location\n # ----------------------------------------------------------------------------#\n srcFile = os.path.join(os.path.dirname(__file__),'gluon','AION_Gluon_MultiModalPrediction.py')\n dstFile = os.path.join(deployLocation,'aion_predict.py')\n shutil.copy(srcFile,dstFile)\n time_limit = None # set to larger value in your applications\n save_path = os.path.join(deployLocation,'text_prediction')\n predictor = TextPredictor(label=dataLabels, path=save_path)\n predictor.fit(train_data, time_limit=time_limit)\n log.info('Status:-|... AION Gluon Stop')\n log.info('Status:-|... AION Evaluation Start')\n trainevaluations = predictor.evaluate(train_data)\n log.info('Status:-|... AION Evaluation Stop')\n # ----------------------------------------------------------------------------#\n output = {'status':'SUCCESS','data':{'ModelType':'MultiModelLearning','EvaluatedModels':'','featuresused':'','BestModel':'AutoGluon','BestScore': '0', 'ScoreType': 'SCORE','deployLocation':deployLocation,'matrix':trainevaluations,'LogFile':logFileName}} \n \n output = json.dumps(output) \n print(\"\\\\n\")\n print(\"aion_learner_status:\",output)\n print(\"\\\\n\")\n log.info('\\\\n------------- Output JSON ------------')\n log.info('-------> Output :'+str(output))\n log.info('------------- Output JSON ------------\\\\n')\n for hdlr in log.handlers[:]: # remove the existing file handlers\n if isinstance(hdlr,logging.FileHandler):\n hdlr.close()\n log.removeHandler(hdlr)\n \n return(output)\nif __name__ == \"__main__\":\n aion_train_gluon(sys.argv[1]) '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport platform\nimport shutil\nimport subprocess\nimport sys\nimport glob\nimport json\n\n\ndef publish(data):\n if os.path.splitext(data)[1] == \".json\":\n with open(data,'r',encoding='utf-8') as f:\n jsonData = json.load(f)\n else:\n jsonData = json.loads(data)\n model = jsonData['modelName']\n version = jsonData['modelVersion']\n deployFolder = jsonData['deployLocation']\n model = model.replace(\" \", \"_\")\n deployedPath = os.path.join(deployFolder,model+'_'+version)\n deployedPath = os.path.join(deployedPath,'WHEELfile')\n whlfilename='na'\n if os.path.isdir(deployedPath):\n for file in os.listdir(deployedPath):\n if file.endswith(\".whl\"):\n whlfilename = os.path.join(deployedPath,file)\n if whlfilename != 'na':\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"uninstall\",\"-y\",model])\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", whlfilename])\n \n status,pid,ip,port = check_service_running(jsonData['modelName'],jsonData['serviceFolder'])\n if status == 'Running':\n service_stop(json.dumps(jsonData))\n service_start(json.dumps(jsonData))\n \n output_json = {'status':\"SUCCESS\"}\n output_json = json.dumps(output_json)\n \n else:\n output_json = {'status':'Error','Msg':'Installation Package not Found'}\n output_json = json.dumps(output_json)\n return(output_json)\ndef check_service_running(model,serviceFolder):\n model = model.replace(\" \", \"_\")\n filename = model+'_service.py'\n modelservicefile = os.path.join(serviceFolder,filename)\n status = 'File Not Exist'\n ip = ''\n port = ''\n pid = ''\n if os.path.exists(modelservicefile):\n status = 'File Exist'\n import psutil\n for proc in psutil.process_iter():\n pinfo = proc.as_dict(attrs=['pid', 'name', 'cmdline','connections'])\n if 'python' in pinfo['name']:\n if filename in pinfo['cmdline'][1]:\n status = 'Running'\n pid = pinfo['pid']\n for x in pinfo['connections']:\n ip = x.laddr.ip\n port = x.laddr.port\n \n \n return(status,pid,ip,port)\ndef service_stop(data):\n if os.path.splitext(data)[1] == \".json\":\n with open(data,'r',encoding='utf-8') as f:\n jsonData = json", "instruction": "", "output": "" }, { "input": ".load(f)\n else:\n jsonData = json.loads(data)\n status,pid,ip,port = check_service_running(jsonData['modelName'],jsonData['serviceFolder'])\n if status == 'Running':\n import psutil\n p = psutil.Process(int(pid))\n p.terminate()\n time.sleep(2)\n output_json = {'status':'SUCCESS'} \n output_json = json.dumps(output_json)\n return(output_json)\n \ndef service_start(data):\n if os.path.splitext(data)[1] == \".json\":\n with open(data,'r',encoding='utf-8') as f:\n jsonData = json.load(f)\n else:\n jsonData = json.loads(data)\n model = jsonData['modelName']\n version = jsonData['modelVersion']\n ip = jsonData['ip']\n port = jsonData['port']\n deployFolder = jsonData['deployLocation']\n serviceFolder = jsonData['serviceFolder']\n model = model.replace(\" \", \"_\")\n deployLocation = os.path.join(deployFolder,model+'_'+version)\n org_service_file = os.path.abspath(os.path.join(os.path.dirname(__file__),'model_service.py'))\n filename = model+'_service.py'\n modelservicefile = os.path.join(serviceFolder,filename)\n status = 'File Not Exist'\n if os.path.exists(modelservicefile):\n status = 'File Exist'\n r = ([line.split() for line in subprocess.check_output(\"tasklist\").splitlines()])\n for i in range(len(r)):\n if filename in r[i]: \n status = 'Running'\n if status == 'File Not Exist':\n shutil.copy(org_service_file,modelservicefile)\n with open(modelservicefile, 'r+') as file:\n content = file.read()\n file.seek(0, 0)\n line = 'from '+model+' import aion_performance'\n file.write(line+\"\\\\n\")\n line = 'from '+model+' import aion_drift'\n file.write(line+ \"\\\\n\")\n line = 'from '+model+' import featureslist'\n file.write(line+ \"\\\\n\")\n line = 'from '+model+' import aion_prediction'\n file.write(line+ \"\\\\n\")\n file.write(content)\n file.close()\n status = 'File Exist'\n if status == 'File Exist': \n status,pid,ipold,portold = check_service_running(jsonData['modelName'],jsonData['serviceFolder'])\n if status != 'Running':\n command = \"python \"+modelservicefile+' '+str(port)+' '+str(ip)\n os.system('start cmd /c \"'+command+'\"')\n time.sleep(2)\n status = 'Running'\n output_json = {'status':'SUCCESS','Msg':status} \n output_json = json.dumps(output_json)\n return(output_json)\nif __name__ == \"__main__\":\n aion_publish(sys.argv[1])\n import json\nimport logging\nimport os\nimport shutil\nimport time\nimport sys\nfrom sys import platform\nfrom distutils.util import strtobool\nfrom config_manager.pipeline_config import AionConfigManager\nfrom summarizer import Summarizer\n# 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.\n\nclass AionTextManager:\n\n\t\n\tdef __init__(self):\n\t\tself.log = logging.getLogger('eion')\n\t\tself.data = ''\n\t\tself.problemType = ''\n\t\tself.basic = []\n\t\tself.advance=[]\n\n\tdef readTextfile(self,dataPath):\n\t\t#dataPath=self.[baisc][]\n\t\tfile = open(dataPath, \"r\")\n\t\tdata = file.read()\n\t\treturn data\n\t\t#print(data)\n\n\tdef generateSummary(self,data,algo,stype):\n\t\tbert_model = Summarizer()\n\t\tif stype == \"large\":\n\t\t\tbert_summary = ''.join(bert_model(data, min_length=300))\n\t\t\treturn(bert_summary)\n\t\telif stype == \"medium\":\n\t\t\tbert_summary = ''.join(bert_model(data, min_length=150))\n\t\t\treturn(bert_summary)\n\t\telif stype == \"small\":\n\t\t\tbert_summary = ''.join(bert_model(data, min_length=60))\n\t\t\treturn(bert_summary)\n\ndef aion_textsummary(arg):\n\tObj = AionTextManager()\n\tconfigObj = AionConfigManager()\n\treadConfistatus,msg = configObj.readConfigurationFile(arg)\n\tdataPath = configObj.getTextlocation()\n\ttext_data = Obj.readTextfile(dataPath)\n\tgetAlgo, getMethod = configObj.getTextSummarize()\n\tsummarize = Obj.generateSummary(text_data, getAlgo, getMethod)\n\toutput = {'status':'Success','summary':summarize} \n\toutput_json = json.dumps(output)\n\treturn(output_json)\nif __name__ == \"__main__\":\n\taion_textsummary(sys.argv[1])\n\t\n\n import os\nimport sys\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__))))\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport requests\nimport json\nimport os\nfrom datetime import datetime\nimport socket\nimport getmac\ndef telemetry_data(operation,Usecase,data):\n now = datetime.now()\n ID = datetime.timestamp(now)\n record_date = now.strftime(\"%y-%m-%d %H:%M:%S\")\n try:\n user = os.getlogin()\n except:\n user = 'NA'\n computername = socket.getfqdn()\n macaddress = getmac.get_mac_address()\n item = {}\n item['ID'] = str(int(ID))\n item['record_date'] = record_date\n item['UseCase'] = Usecase\n item['user'] = str(user)\n item['operation'] = operation\n item['remarks'] = data\n item['hostname'] = computername\n item['macaddress'] = macaddress\n url = 'https://l5m119j6v9.execute-api.ap-south-1.amazonaws.com/default/aion_telemetry'\n record = {}\n record['TableName'] = 'AION_OPERATION'\n record['Item'] = item\n record = json.dumps(record)\n try:\n response = requests.post(url, data=record,headers={\"x-api-key\":\"Obzt8ijfOT3dgBYma9JCt1tE3W6tzHaV8rVuQdMK\",\"Content-Type\":\"application/json\",})\n check_telemetry_file()\n except Exception as inst:\n filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),'telemetry.txt') \n f=open(filename, \"a+\")\n f.write(record+'\\\\n')\n f.close()\n \ndef check_telemetry_file():\n file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'telemetry.txt')\n if(os.path.isfile(file_path)):\n f = open(file_path, 'r')\n file_content = f.read()\n f.close()\n matched_lines = file_content.split('\\\\n')\n write_lines = []\n url = 'https://l5m119j6v9.execute-api.ap-south-1.amazonaws.com/default/aion_telemetry'\n for record in matched_lines:\n try:\n response = requests.post(url, data=record,headers={\"x-api-key\":\"Obzt8ijfOT3dgBYma9JCt1tE3W6tzHaV8rVuQdMK\",\"Content-Type\":\"application/json\",})\n except:\n write_lines.append(record)\n f = open(file_path, \"a\")\n f.seek(0)\n f.truncate()\n for record in write_lines:\n f.write(record+'\\\\n')\n f.close()\n return True \n else:\n return True '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport sys\nimport json\nimport datetime, time, timeit\nimport argparse\nimport logging\nlogging.getLogger('tensorflow').disabled = True\nimport math\nimport shutil\nimport re\nfrom datetime import datetime as dt\nimport warnings\nfrom config_manager.pipeline_config import AionConfigManager\nimport pandas as pd\nimport numpy as np\nimport sklearn\nimport string\nfrom records import pushrecords\nimport logging\n\n\nfrom pathlib import Path\nfrom pytz import timezone\nfrom config_manager.config_gen import code_configure\nimport joblib\nfrom sklearn.model_selection import train_test_split\nfrom config_manager.check_config import config_validate\nfrom utils.file_ops import save_csv_compressed,save_csv,save_chromadb\nLOG_FILE_NAME = 'model_training_logs.log'\n\nif 'AION' in sys.modules:\n try:\n from appbe.app_config import DEBUG_ENABLED\n except:\n DEBUG_ENABLED = False\nelse:\n DEBUG_ENABLED = True\n\ndef getversion():\n configFolder = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','config')\n version = 'NA'\n for file in os.listdir(configFolder):\n if file.endswith(\".var\"):\n version = file.rsplit('.', 1)\n version = version[0]\n break\n return version\n \nAION_VERSION = getversion()\ndef pushRecordForTraining():\n try:\n status,msg = pushrecords.enterRecord(AION_VERSION)\n except Exception as e:\n print(\"Exception\", e)\n status = False\n msg = str(e)\n return status,msg\n\ndef mlflowSetPath(path,experimentname):\n import mlflow\n url = \"file:\" + str(Path(path).parent.parent) + \"/mlruns\"\n mlflow.set_tracking_uri(url)\n mlflow.set_experiment(str(experimentname))\n\ndef set_log_handler( basic, mode='w'):\n deploy_loc = Path(basic.get('deployLocation'))\n log_file_parent = deploy_loc/basic['modelName']/basic['modelVersion']/'log'\n log_file_parent.mkdir(parents=True, exist_ok=True)\n log_file = log_file_parent/LOG_FILE_NAME\n \n filehandler = logging.FileHandler(log_file, mode,'utf-8')\n formatter = logging.Formatter('%(message)s')\n filehandler.setFormatter(formatter)\n log = logging.getLogger('eion')\n log.propagate = False\n for hdlr in log.handlers[:]: # remove the existing file handlers\n if isinstance(hdlr,logging.FileHandler):\n log.removeHandler(hdlr)\n log.addHandler(filehandler)\n log.setLevel(logging.INFO)\n return log\n\n \nclass server():\n def __init__(self):\n self.response = None\n self.features=[]\n self.mFeatures=[]\n self.emptyFeatures=[]\n self.textFeatures=[]\n self.vectorizerFeatures=[]\n self.wordToNumericFeatures=[]\n self.profilerAction = []\n self.targetType = ''\n self.matrix1='{'\n self.matrix2='{'\n self.matrix='{'\n self.trainmatrix='{'\n self.numericalFeatures=[]\n self.nonNumericFeatures=[]\n self.similarGroups=[]\n self.dfcols=0\n self.dfrows=0\n self.method = 'NA'\n self.pandasNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n self.modelSelTopFeatures=[]\n self.topFeatures=[]\n self.allFeatures=[]\n def startScriptExecution(self, config_obj, codeConfigure, log):\n oldStdout = sys.stdout\n model_training_details = ''\n model_tried=''\n learner_type = ''\n topics = {}\n pred_filename = ''\n numericContinuousFeatures=''\n discreteFeatures=''\n sessonal_freq = ''\n additional_regressors = ''\n threshold=-1\n targetColumn = ''\n numericalFeatures =''\n nonNumericFeatures=''\n categoricalFeatures=''\n dataFolderLocation = ''\n featureReduction = 'False' \n original_data_file = ''\n normalizer_pickle_file = ''\n pcaModel_pickle_file = ''\n bpca_features= []\n apca_features = []\n lag_order = 1\n profiled_data_file = ''\n trained_data_file = ''\n predicted_data_file=''\n dictDiffCount={}\n cleaning_kwargs = {}\n grouperbyjson = ''\n rowfilterexpression=''\n featureEngineeringSelector = 'false'\n conversion_method = ''\n params={}\n loss_matrix='binary_crossentropy'\n optimizer='Nadam'\n numericToLabel_json='[]'\n preprocessing_pipe=''\n firstDocFeature = ''\n secondDocFeature = ''\n padding_length = 30\n pipe = None\n scalertransformationFile=None\n column_merge_flag = False\n merge_columns = []\n score = 0\n profilerObj = None\n imageconfig=''\n labelMaps={}\n featureDataShape=[]\n normFeatures = []\n preprocess_out_columns = []\n preprocess_pipe = None\n label_encoder = None\n unpreprocessed_columns = []\n import pickle\n iterName,iterVersion,dataLocation,deployLocation,delimiter,textqualifier = config_obj.getAIONLocationSettings()\n inlierLabels=config_obj.getEionInliers()\n scoreParam = config_obj.getScoringCreteria()\n noofforecasts = config_obj.getNumberofForecasts()\n datetimeFeature,indexFeature,modelFeatures=config_obj.getFeatures()\n \n filter_expression = config_obj.getFilterExpression()\n refined_filter_expression = \"\"\n sa_images = []\n model_tried = ''\n deploy_config = {}\n iterName = iterName.replace(\" \", \"_\")\n deployFolder = deployLocation\n usecaseLocation,deployLocation,dataFolderLocation,imageFolderLocation,original_data_file,profiled", "instruction": "", "output": "" }, { "input": "_data_file,trained_data_file,predicted_data_file,logFileName,outputjsonFile,reduction_data_file = config_obj.createDeploymentFolders(deployFolder,iterName,iterVersion)\n outputLocation=deployLocation\n mlflowSetPath(deployLocation,iterName+'_'+iterVersion)\n # mlflowSetPath shut down the logger, so set again\n set_log_handler( config_obj.basic, mode='a')\n xtrain=pd.DataFrame() \n xtest=pd.DataFrame()\n log.info('Status:-|... AION Training Configuration started') \n startTime = timeit.default_timer()\n try:\n output = {'bestModel': '', 'bestScore': 0, 'bestParams': {}}\n 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()\n status, error_id, msg = config_obj.validate_config()\n if not status:\n if error_id == 'fasttext':\n raise ValueError(msg) \n VideoProcessing = False \n if(problem_type.lower() in ['classification','regression']):\n if(targetFeature == ''):\n output = {\"status\":\"FAIL\",\"message\":\"Target Feature is Must for Classification and Regression Problem Type\"}\n return output\n \n \n from transformations.dataReader import dataReader \n objData = dataReader()\n DataIsFolder = False\n folderdetails = config_obj.getFolderSettings()\n \n if os.path.isfile(dataLocation):\n log.info('Status:-|... AION Loading Data') \n dataFrame = objData.csvTodf(dataLocation,delimiter,textqualifier)\n status,msg = save_csv_compressed(dataFrame,original_data_file)\n if not status:\n log.info('CSV File Error: '+str(msg))\n elif os.path.isdir(dataLocation):\n if problem_type.lower() == 'summarization':\n from document_summarizer import summarize\n keywords, pretrained_type, embedding_sz = summarize.get_params()\n dataFrame = summarize.to_dataframe(dataLocation,keywords, deploy_loc, pretrained_type, embedding_sz)\n problem_type = 'classification'\n targetFeature = 'label'\n scoreParam = 'Accuracy'\n elif folderdetails['fileType'].lower() == 'document':\n dataFrame, error = objData.documentsTodf(dataLocation, folderdetails['labelDataFile'])\n if error:\n log.info(error)\n elif folderdetails['fileType'].lower() == 'object':\n testPercentage = config_obj.getAIONTestTrainPercentage() #Unnati\n intermediateLocation = os.path.join(deployLocation,'intermediate')\n os.mkdir(intermediateLocation)\n AugEnabled,keepAugImages,operations,augConf = config_obj.getEionImageAugmentationConfiguration() \n dataFrame, n_class = objData.createTFRecord(dataLocation, intermediateLocation, folderdetails['labelDataFile'], testPercentage,AugEnabled,keepAugImages,operations, \"objectdetection\",augConf) #Unnati\n DataIsFolder = True\n else:\n datafilelocation = os.path.join(dataLocation,folderdetails['labelDataFile'])\n dataFrame = objData.csvTodf(datafilelocation,delimiter,textqualifier)\n DataIsFolder = True\n if textSimilarityStatus or similarityIdentificationStatus or contextualSearchStatus:\n similaritydf = dataFrame\n\n filter = config_obj.getfilter()\n if filter != 'NA':\n dataFrame,rowfilterexpression = objData.rowsfilter(filter,dataFrame) \n \n timegrouper = config_obj.gettimegrouper() \n grouping = config_obj.getgrouper() \n if grouping != 'NA':\n dataFrame,grouperbyjson = objData.grouping(grouping,dataFrame)\n elif timegrouper != 'NA':\n dataFrame,grouperbyjson = objData.timeGrouping(timegrouper,dataFrame)\n if timeseriesStatus or anomalyDetectionStatus:\n from utils.validate_inputs import dataGarbageValue\n status,msg = dataGarbageValue(dataFrame,datetimeFeature)\n if status.lower() == 'error':\n raise ValueError(msg)\n if not DataIsFolder:\n if timeseriesStatus: \n if(modelFeatures != 'NA' and datetimeFeature != ''):\n if datetimeFeature:\n if isinstance(datetimeFeature, list): #to handle if time series having multiple time column \n unpreprocessed_columns = unpreprocessed_columns + datetimeFeature\n else:\n unpreprocessed_columns = unpreprocessed_columns + datetimeFeature.split(',')\n if datetimeFeature not in modelFeatures:\n modelFeatures = modelFeatures+','+datetimeFeature\n \n dataFrame = objData.removeFeatures(dataFrame,'NA',indexFeature,modelFeatures,targetFeature) \n \n elif survival_analysis_status or anomalyDetectionStatus:\n if(modelFeatures != 'NA'):\n if datetimeFeature != 'NA' and datetimeFeature != '':\n unpreprocessed_columns = unpreprocessed_columns + datetimeFeature.split(',')\n if datetimeFeature not in modelFeatures:\n modelFeatures = modelFeatures+','+datetimeFeature\n dataFrame = objData.removeFeatures(dataFrame,'NA',indexFeature,modelFeatures,targetFeature)\n else:\n dataFrame = objData.removeFeatures(dataFrame,datetimeFeature,indexFeature,modelFeatures,targetFeature)\n \n log.info('\\\\n-------> First Ten Rows of Input Data: ')\n log.info(dataFrame.head(10))\n self.dfrows=dataFrame.shape[0]\n self.dfcols=dataFrame.shape[1]\n log.info('\\\\n-------> Rows: '+str(self.dfrows))\n log.info('\\\\n-------> Columns: '+str(self.dfcols))\n topFeatures=[]\n \n profilerObj = None\n normalizer=None\n dataLoadTime = timeit.default_timer() - startTime\n log.info('-------> COMPUTING: Total dataLoadTime time(sec) :'+str(dataLoadTime))\n if timeseriesStatus:\n if datetimeFeature != 'NA' and datetimeFeature != '':\n preproces_config = config_obj.basic.get('preprocessing',{}).get('timeSeriesForecasting',{})\n if preproces_config:\n from transformations.preprocess import timeSeries as ts_preprocess\n preprocess_obj = ts_preprocess( preproces_config,datetimeFeature, log)\n dataFrame = preprocess_obj.run( dataFrame)\n log.info('-------> Input dataFrame(5 Rows) after preprocessing: ')\n log.info(dataFrame.head(5))\n deploy_config['preprocess'] = {}\n deploy_config['preprocess']['code'] = preprocess_obj.get_code()\n if profiler_status:\n log.info('\\\\n================== Data Profiler has started ==================')\n log.info('Status:-|... AION feature transformation started')\n from transformations.dataProfiler import profiler as dataProfiler\n dp_mlstart = time.time() \n profilerJson = config_obj.getEionProfilerConfigurarion()\n log.info('-------> Input dataFrame(5 Rows): ')\n log.info(dataFrame.head(5))\n log.info('-------> DataFrame Shape (Row,Columns): '+str(dataFrame.shape))\n testPercentage = config_obj.getAIONTestTrainPercentage() #Unnati\n if DataIsFolder:\n if folderdetails['type'].lower() != 'objectdetection':\n profilerObj = dataProfiler(dataFrame)\n topFeatures,VideoProcessing,tfrecord_directory = profilerObj.folderPreprocessing(dataLocation,folderdetails,deployLocation)\n elif textSimilarityStatus:\n firstDocFeature = config_obj.getFirstDocumentFeature()\n secondDocFeature = config_obj.getSecondDocumentFeature() \n profilerObj = dataProfiler(dataFrame,targetFeature, data_path=dataFolderLocation)\n dataFrame,pipe,targetColumn,topFeatures = profilerObj.textSimilarityStartProfiler(firstDocFeature,secondDocFeature) \n elif recommenderStatus:\n profilerObj = dataProfiler(dataFrame)\n dataFrame = profilerObj.recommenderStartProfiler(modelFeatures)\n else:\n if deeplearner_status or learner_status:\n if (problem_type.lower() != 'clustering') and (problem_type.lower() != 'topicmodelling'):\n if targetFeature != '': \n try:\n biasingDetail = config_obj.getDebiasingDetail()\n if len(biasingDetail) > 0:\n if biasingDetail['FeatureName'] != 'None':\n protected_feature = biasingDetail['FeatureName']\n privileged_className = biasingDetail['ClassName']\n target_feature = biasingDetail['TargetFeature']\n algorithm = biasingDetail['Algorithm']\n \n from debiasing.DebiasingManager import DebiasingManager\n mgrObj = DebiasingManager()\n log.info('Status:-|... Debiasing transformation started')\n transf_dataFrame = mgrObj.Bias_Mitigate(dataFrame, protected_feature, privileged_className, target_feature, algorithm)\n \n log.info('Status:-|... Debiasing transformation completed')\n dataFrame = transf_dataFrame\n except Exception as e:\n print(e)\n pass\n # ---------------------------------------------- ---------------------------------------------- \n targetData = dataFrame[targetFeature] \n featureData = dataFrame[dataFrame.columns.difference([targetFeature])]\n testPercentage = config_obj.getAIONTestTrainPercentage() #Unnati\n xtrain,ytrain,xtest,ytest = self.split_into_train_test_data(featureData,targetData,testPercentage,log,problem_type.lower())\n xtrain.reset_index(drop=True,inplace=True)\n ytrain.reset_index(drop=True,inplace=True)\n xtest.reset_index(drop=True,inplace=True)\n ytest.reset_index(drop=True,inplace=True)\n dataFrame = xtrain\n dataFrame[targetFeature] = ytrain \n encode_target_problems = ['classification','anomalyDetection', 'timeSeriesAnomalyDetection'] #task 11997\n if problem_type == 'survivalAnalysis' and dataFrame[targetFeature].nunique() > 1:\n encode_target_problems.append('survivalAnalysis')\n \n if timeseriesStatus: #task 12627 calling data profiler without target feature specified separately (i.e) profiling is done for model features along with target features\n profilerObj = dataProfiler(dataFrame, config=profilerJson, keep_unprocessed = unpreprocessed_columns.copy(), data_path=dataFolderLocation)\n else:\n 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\n dataFrame, preprocess_pipe, label_encoder = profilerObj.transform()\n preprocess_out_columns = dataFrame.columns.tolist()\n 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\n if targetFeature in preprocess_out_columns:\n preprocess_out_columns.remove(targetFeature)\n for x in unpreprocessed_columns:\n preprocess_out_columns.remove(x) \n if label_encoder:\n joblib.dump(label_encoder, Path(deployLocation)/'model'/'label_encoder.pkl')\n labelMaps = dict(zip(label_encoder.classes_, label_encoder.transform(label_encoder.classes_)))\n codeConfigure.update_config('train_features',list(profilerObj.train_features_type.keys()))\n codeConfigure.update_config('text_features',profilerObj.text_feature)\n self.textFeatures = profilerObj.text_feature\n deploy_config['profiler'] = {}\n deploy_config['profiler']['input_features'] = list(profilerObj.train_features_type.keys())\n deploy_config['profiler']['output_features'] = preprocess_out_columns\n deploy_config['profiler']['input_features_type'] = profilerObj.train_features_type\n deploy_config['profiler']['word2num_features'] = profilerObj.wordToNumericFeatures\n deploy_config['profiler']['unpreprocessed_columns'] = unpreprocessed_columns\n deploy_config['profiler']['force_numeric_conv'] = profilerObj.force_numeric_conv\n if self.textFeatures:\n deploy_config['profiler']['conversion_method'] = config_obj.get_conversion_method()\n if anomalyDetectionStatus and datetimeFeature != 'NA' and datetimeFeature != '':\n if unpreprocessed_columns:\n dataFrame.set_index( unpreprocessed_columns[0], inplace=True)\n log.info('-------> Data Frame Post Data Profiling(5 Rows): ')\n log.info(dataFrame.head(5))\n if not xtest.empty:\n if targetFeature != '':\n non_null_index = ytest.notna()\n ytest = ytest[non_null_index]\n xtest = xtest[non_null_index]\n if profilerObj.force_numeric_conv:\n xtest[ profilerObj.force_numeric_conv] = xtest[profilerObj.force_numeric_conv].apply(pd.to_numeric,errors='coerce')\n xtest.astype(profilerObj.train_features_type)\n if unpreprocessed_columns:\n xtest_unprocessed = xtest[unpreprocessed_columns]\n xtest = preprocess_pipe.transform(xtest)\n if not isinstance(xtest, np.ndarray):\n xtest = xtest.toarray() \n xtest = pd.DataFrame(xtest, columns=preprocess_out_columns)\n if unpreprocessed_columns:\n xtest[unpreprocessed_columns] = xtest_unprocessed\n if survival_analysis_status:\n xtest.astype({x:'float' for x in unpreprocessed_columns})\n xtrain.astype({x:'float' for x in unpreprocessed_columns})\n #task 11997 removed setting datetime column as index of dataframe code as it is already done before\n if label_encoder:\n ytest = label_encoder", "instruction": "", "output": "" }, { "input": ".transform(ytest)\n if preprocess_pipe:\n if self.textFeatures:\n from text.textProfiler import reset_pretrained_model\n reset_pretrained_model(preprocess_pipe) # pickle is not possible for fasttext model ( binary)\n joblib.dump(preprocess_pipe, Path(deployLocation)/'model'/'preprocess_pipe.pkl')\n \n self.features=topFeatures\n if targetColumn in topFeatures:\n topFeatures.remove(targetColumn)\n self.topFeatures=topFeatures\n if normalizer != None:\n normalizer_file_path = os.path.join(deployLocation,'model','normalizer_pipe.sav')\n normalizer_pickle_file = 'normalizer_pipe.sav'\n pickle.dump(normalizer, open(normalizer_file_path,'wb'))\n log.info('Status:-|... AION feature transformation completed')\n dp_mlexecutionTime=time.time() - dp_mlstart\n log.info('-------> COMPUTING: Total Data Profiling Execution Time '+str(dp_mlexecutionTime))\n log.info('================== Data Profiling completed ==================\\\\n')\n \n else:\n datacolumns=list(dataFrame.columns)\n if targetFeature in datacolumns:\n datacolumns.remove(targetFeature)\n 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:\n self.textFeatures,self.vectorizerFeatures,pipe,column_merge_flag,merge_columns = profilerObj.checkForTextClassification(dataFrame)\n self.topFeatures =datacolumns\n if(pipe is not None):\n preprocessing_pipe = 'pppipe'+iterName+'_'+iterVersion+'.sav'\n ppfilename = os.path.join(deployLocation,'model','pppipe'+iterName+'_'+iterVersion+'.sav')\n pickle.dump(pipe, open(ppfilename, 'wb'))\n status, msg = save_csv_compressed(dataFrame,profiled_data_file)\n if not status:\n log.info('CSV File Error: ' + str(msg))\n if selector_status:\n log.info(\"\\\\n================== Feature Selector has started ==================\")\n log.info(\"Status:-|... AION feature engineering started\")\n fs_mlstart = time.time()\n selectorJson = config_obj.getEionSelectorConfiguration()\n if self.textFeatures:\n config_obj.updateFeatureSelection(selectorJson, codeConfigure, self.textFeatures)\n log.info(\"-------> For vectorizer 'feature selection' is disabled and all the features will be used for training\")\n from feature_engineering.featureSelector import featureSelector\n selectorObj = featureSelector()\n 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)\n if(str(pcaModel) != 'None'):\n featureReduction = 'True'\n status, msg = save_csv(dataFrame,reduction_data_file)\n if not status:\n log.info('CSV File Error: ' + str(msg)) \n pcaFileName = os.path.join(deployLocation,'model','pca'+iterName+'_'+iterVersion+'.sav')\n pcaModel_pickle_file = 'pca'+iterName+'_'+iterVersion+'.sav'\n pickle.dump(pcaModel, open(pcaFileName, 'wb'))\n if not xtest.empty:\n xtest = pd.DataFrame(pcaModel.transform(xtest),columns= apca_features)\n if targetColumn in self.topFeatures:\n self.topFeatures.remove(targetColumn)\n fs_mlexecutionTime=time.time() - fs_mlstart\n log.info('-------> COMPUTING: Total Feature Selection Execution Time '+str(fs_mlexecutionTime))\n log.info('================== Feature Selection completed ==================\\\\n')\n log.info(\"Status:-|... AION feature engineering completed\")\n \n if deeplearner_status or learner_status:\n log.info('Status:-|... AION training started')\n ldp_mlstart = time.time()\n balancingMethod = config_obj.getAIONDataBalancingMethod()\n from learner.machinelearning import machinelearning\n mlobj = machinelearning()\n modelType = problem_type.lower()\n targetColumn = targetFeature\n if modelType == \"na\":\n if self.targetType == 'categorical':\n modelType = 'classification'\n elif self.targetType == 'continuous':\n modelType = 'regression'\n else:\n modelType='clustering'\n datacolumns=list(dataFrame.columns) \n if targetColumn in datacolumns:\n datacolumns.remove(targetColumn)\n features =datacolumns\n featureData = dataFrame[features]\n if(modelType == 'clustering') or (modelType == 'topicmodelling'):\n xtrain = featureData\n ytrain = pd.DataFrame() \n xtest = featureData\n ytest = pd.DataFrame()\n elif (targetColumn!=''):\n xtrain = dataFrame[features]\n ytrain = dataFrame[targetColumn]\n else:\n pass\n \n categoryCountList = [] \n if modelType == 'classification':\n if(mlobj.checkForClassBalancing(ytrain) >= 1):\n xtrain,ytrain = mlobj.ExecuteClassBalancing(xtrain,ytrain,balancingMethod)\n valueCount=targetData.value_counts()\n categoryCountList=valueCount.tolist()\n ldp_mlexecutionTime=time.time() - ldp_mlstart\n log.info('-------> COMPUTING: Total Learner data preparation Execution Time '+str(ldp_mlexecutionTime))\n if learner_status:\n base_model_score=0\n log.info('\\\\n================== ML Started ==================')\n \n log.info('-------> Memory Usage by DataFrame During Learner Status '+str(dataFrame.memory_usage(deep=True).sum()))\n mlstart = time.time()\n log.info('-------> Target Problem Type:'+ self.targetType)\n learner_type = 'ML'\n learnerJson = config_obj.getEionLearnerConfiguration()\n from learner.machinelearning import machinelearning \n mlobj = machinelearning()\n anomalyDetectionStatus = False\n anomalyMethod =config_obj.getEionanomalyModels()\n if modelType.lower() == \"anomalydetection\" or modelType.lower() == \"timeseriesanomalydetection\": #task 11997\n anomalyDetectionStatus = True\n \n if anomalyDetectionStatus == True :\n datacolumns=list(dataFrame.columns)\n if targetColumn in datacolumns:\n datacolumns.remove(targetColumn)\n if datetimeFeature in datacolumns:\n datacolumns.remove(datetimeFeature)\n self.features = datacolumns\n from learner.anomalyDetector import anomalyDetector\n anomalyDetectorObj=anomalyDetector()\n model_type =\"anomaly_detection\"\n saved_model = model_type+'_'+iterName+'_'+iterVersion+'.sav'\n if problem_type.lower() == \"timeseriesanomalydetection\": #task 11997\n anomalyconfig = config_obj.getAIONTSAnomalyDetectionConfiguration()\n modelType = \"TimeSeriesAnomalyDetection\"\n else:\n anomalyconfig = config_obj.getAIONAnomalyDetectionConfiguration()\n testPercentage = config_obj.getAIONTestTrainPercentage()\n ##Multivariate feature based anomaly detection status from gui (true/false)\n mv_featurebased_selection = config_obj.getMVFeaturebasedAD()\n mv_featurebased_ad_status=str(mv_featurebased_selection['uniVariate']) \n 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\n score = 'NA'\n if(self.matrix != '{'):\n self.matrix += ','\n self.matrix += matrix\n if(self.trainmatrix != '{'):\n self.trainmatrix += ','\n self.trainmatrix += trainmatrix\n scoreParam = 'NA'\n scoredetails = f'{{\"Model\":\"{model}\",\"Score\":\"{score}\"}}'\n if model_tried != '':\n model_tried += ','\n model_tried += scoredetails\n model = anomalyMethod\n else:\n log.info('-------> Target Problem Type:'+ self.targetType)\n log.info('-------> Target Model Type:'+ modelType)\n if(modelType == 'regression'):\n allowedmatrix = ['mse','r2','rmse','mae']\n if(scoreParam.lower() not in allowedmatrix):\n scoreParam = 'mse'\n \n if(modelType == 'classification'):\n allowedmatrix = ['accuracy','recall','f1_score','precision','roc_auc']\n if(scoreParam.lower() not in allowedmatrix):\n scoreParam = 'accuracy'\n scoreParam = scoreParam.lower() \n codeConfigure.update_config('scoring_criteria',scoreParam) \n modelParams,modelList = config_obj.getEionLearnerModelParams(modelType)\n 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)\n \n #Getting model,data for ensemble calculation\n e_model=loaded_model\n base_model_score=score\n if(self.matrix != '{'):\n self.matrix += ','\n if(self.trainmatrix != '{'):\n self.trainmatrix += ','\n self.trainmatrix += trainmatrix\n self.matrix += matrix\n mlexecutionTime=time.time() - mlstart\n log.info('-------> Total ML Execution Time '+str(mlexecutionTime))\n log.info('================== ML Completed ==================\\\\n')\n if deeplearner_status:\n learner_type = 'DL'\n log.info('Status:- |... AION DL training started')\n from dlearning.deeplearning import deeplearning\n dlobj = deeplearning()\n from learner.machinelearning import machinelearning\n mlobj = machinelearning() \n log.info('\\\\n================== DL Started ==================') \n dlstart = time.time()\n deeplearnerJson = config_obj.getEionDeepLearnerConfiguration()\n targetColumn = targetFeature\n method = deeplearnerJson['optimizationMethod']\n optimizationHyperParameter = deeplearnerJson['optimizationHyperParameter']\n cvSplit = optimizationHyperParameter['trainTestCVSplit']\n roundLimit=optimizationHyperParameter['roundLimit']\n if 'randomMethod' in optimizationHyperParameter:\n randomMethod = optimizationHyperParameter['randomMethod']\n else:\n randomMethod = 'Quantum'\n modelType = problem_type.lower()\n modelParams = deeplearnerJson['modelParams']\n modelParamsFile=deeplearnerJson['modelparamsfile']\n \n if roundLimit ==\"\":\n roundLimit=None\n else:\n roundLimit=int(roundLimit)\n \n if len(self.modelSelTopFeatures) !=0:\n dl_features=self.modelSelTopFeatures\n best_feature_model = 'ModelBased'\n elif len(self.topFeatures) != 0:\n dl_features=self.topFeatures\n if featureEngineeringSelector.lower() == 'true':\n best_feature_model = 'DimensionalityReduction'\n else: \n best_feature_model = 'StatisticalBased' \n \n elif len(self.allFeatures) != 0:\n dl_features=self.allFeatures\n best_feature_model = 'AllFeatures' \n else:\n datacolumns=list(dataFrame.columns)\n datacolumns.remove(targetColumn)\n dl_features =datacolumns\n best_feature_model = 'AllFeatures'\n log.info('-------> Features Used For Modeling: '+(str(dl_features))[:500])\n \n \n if cvSplit == \"\":\n cvSplit =None\n else:\n cvSplit =int(cvSplit)\n \n xtrain = xtrain[dl_features]\n xtest = xtest[dl_features]\n df_test = xtest.copy()\n df_test['actual'] = ytest\n \n modelParams,modelList = config_obj.getEionDeepLearnerModelParams(modelType) \n if modelType.lower() == 'classification': \n scoreParam = dlobj.setScoreParams(scoreParam,modelType)\n featureDataShape = xtrain.shape \n model_type = 'Classification'\n log.info('\\\\n------ Training DL: Classification ----')\n elif modelType.lower() == 'regression':\n model_type = \"Regression\"\n if scoreParam == 'None':\n scoreParam = None\n log.info('\\\\n------ Training DL: Regression ----')\n featureDataShape = xtrain.shape\n 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)\n if model_tried != '':\n model_tried += ','\n model_tried += model_tried_dl\n bestDL = True\n if learner_status:\n if score_dl <= score:\n bestDL = False\n log.info(\"\\\\n----------- Machine Learning is Good ---\")\n log.info(\"-------> Model: \"+str(model) +\" Score", "instruction": "", "output": "" }, { "input": ": \"+str(score))\n log.info(\"---------------------------------------\\\\n\")\n else:\n os.remove(filename)\n os.remove(predicted_data_file)\n log.info(\"\\\\n------------ Deep Learning is Good---\")\n log.info(\"-------> Model: \"+str(model_dl)+\" Score: \"+str(score_dl))\n log.info(\"---------------------------------------\\\\n\")\n if bestDL:\n model = model_dl\n score = score_dl\n best_model = best_model_dl\n params = params_dl\n filename = filename_dl\n status, msg = save_csv(df_test,predicted_data_file)\n if not status:\n log.info('CSV File Error: ' + str(msg))\n\n saved_model = saved_model_dl\n self.matrix = '{'+performancematrix\n self.trainmatrix = '{'+trainingperformancematrix\n self.features = dl_features\n else:\n learner_type = 'ML'\n shutil.rmtree(filename_dl)\n\n dlexecutionTime=time.time() - dlstart\n log.info('-------> DL Execution Time '+str(dlexecutionTime))\n log.info('Status:- |... AION DL training completed')\n log.info('================== Deep Completed ==================\\\\n')\n if deeplearner_status or learner_status:\n log.info('Status:-|... AION training completed') \n if stateTransitionStatus:\n log.info('Status:-|... AION State Transition start')\n learner_type = modelType = model_type = 'StateTransition'\n model = 'MarkovClustering'\n scoreParam = 'NA'\n score = 0\n from state_transition.pattern import pattern\n\n patternobj = pattern(modelFeatures,targetFeature)\n\n model_tried,probabilityfile,clusteringfile = patternobj.training(dataFrame,outputLocation)\n deploy_status = False\n visualizationstatus = False\n log.info('Status:-|... AION State Transition completed')\n if associationRuleStatus:\n log.info('\\\\n================== Association Rule Started ==================')\n log.info('Status:-|... AION Association Rule start')\n learner_type = 'AR'\n modelType = 'Association Rule'\n model = 'apriori'\n scoreParam = 'NA'\n score = 'NA'\n model_type = modelType\n associationRuleJson = config_obj.getEionAssociationRuleConfiguration()\n modelparams,modelList = config_obj.getEionAssociationRuleModelParams()\n invoiceNoFeature,itemFeature = config_obj.getAssociationRuleFeatures()\n if model in modelparams:\n modelparam = modelparams[model]\n log.info('\\\\n-------- Assciation Rule Start -----')\n from association_rules.associationrules import associationrules\n associationrulesobj = associationrules(dataFrame,associationRuleJson,modelparam,invoiceNoFeature,itemFeature)\n model_tried = associationrulesobj.apply_associationRules(outputLocation)\n log.info('-------- Association Rule End -----\\\\n')\n log.info('<--------Association Rule Completed----->')\n log.info('Status:-|... AION Association Rule completed')\n deploy_status = False\n if textSimilarityStatus:\n log.info('================ Text Similarity Started ====================')\n log.info('Status:-|... AION Text Similarity started')\n learner_type = 'Text Similarity'\n model_type = 'Text Similarity'\n scoreParam = 'Accuracy'\n modelType = model_type\n firstDocFeature = config_obj.getFirstDocumentFeature()\n secondDocFeature = config_obj.getSecondDocumentFeature() \n textSimilarityCongig = config_obj.getEionTextSimilarityConfig()\n testPercentage = config_obj.getAIONTestTrainPercentage() #Unnati\n from recommender.text_similarity import eion_similarity_siamese\n objTextSimilarity = eion_similarity_siamese()\n 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)\n if(self.matrix != '{'):\n self.matrix += ','\n self.matrix += matrix\n if model_tried != '':\n model_tried += ','\n model_tried += modeltried\n if(self.trainmatrix != '{'):\n self.trainmatrix += ','\n self.trainmatrix += trainmatrix\n log.info('Status:-|... AION Text Similarity completed')\n log.info('================ Text Similarity Started End====================')\n if timeseriesStatus:\n log.info('================ Time Series Forecasting Started ====================') #task 11997\n log.info('Status:-|... AION TimeSeries Forecasting started') #task 11997\n modelType = 'TimeSeriesForecasting' #task 11997\n model_type = 'TimeSeriesForecasting' #task 11997\n learner_type = 'TS'\n modelName='ARIMA'\n numericContinuousFeatures = targetFeature.split(\",\")\n profilerJson = config_obj.getEionTimeSeriesConfiguration()\n modelParams,modelList = config_obj.getEionTimeSeriesModelParams()\n modelName = modelList\n testPercentage = config_obj.getAIONTestTrainPercentage() #Unnati\n \n from time_series.timeseries import timeseries\n allowedmatrix = ['mse','r2','rmse','mae']\n if(scoreParam.lower() not in allowedmatrix):\n scoreParam = 'rmse'\n objTS = timeseries(profilerJson,modelParams,modelList,dataFrame,targetFeature,datetimeFeature,modelName,testPercentage,iterName,iterVersion,deployLocation,scoreParam)\n 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)\n \n xtrain = dataFrame\n self.matrix += errormatrix\n log.info(\"Best model to deploy: \\\\n\"+str(model))\n ## Below part is for var,arima,fbprophet\n \n try:\n with open(filename, 'rb') as f:\n loaded_model = pickle.load(f)\n f.close() \n except:\n loaded_model=best_model\n pass\n df_l=len(dataFrame)\n pred_threshold=0.1\n max_pred_by_user= round((df_l)*pred_threshold)\n #prediction for 24 steps or next 24 hours\n if noofforecasts == -1:\n noofforecasts = max_pred_by_user\n no_of_prediction=noofforecasts\n if (no_of_prediction > max_pred_by_user):\n log.info(\"-------> Forecast beyond the threshold.So, Reset to Maximum:\" +str(max_pred_by_user))\n no_of_prediction=max_pred_by_user\n noofforecasts = no_of_prediction\n log.info(\"-------> Number of Forecast Records: \"+str(no_of_prediction))\n log.info(\"\\\\n------ Forecast Prediction Start -------------\")\n if(model.lower() == 'var'):\n sfeatures.remove(datetimeFeature)\n self.features = sfeatures \n originalPredictions=objTS.var_prediction(no_of_prediction)\n log.info(\"-------> Predictions\")\n log.info(originalPredictions)\n predictions=originalPredictions\n forecast_output = predictions.to_json(orient='records')\n else:\n if (model.lower() == 'fbprophet'):\n self.features = sfeatures\n if not pred_freq:\n sessonal_freq = 'H'\n else:\n sessonal_freq=pred_freq\n ts_prophet_future = best_model.make_future_dataframe(periods=no_of_prediction,freq=sessonal_freq,include_history = False)\n #If additional regressor given by user.\n if (additional_regressors):\n log.info(\"------->Prophet additional regressor given by user: \"+str(additional_regressors))\n ts_prophet_future[additional_regressors] = dataFrame[additional_regressors]\n ts_prophet_future.reset_index(drop=True)\n ts_prophet_future=ts_prophet_future.dropna()\n else:\n pass\n \n train_forecast = best_model.predict(ts_prophet_future)\n train_forecast = train_forecast.round(2)\n prophet_forecast_tail=train_forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']]\n prophet_forecast_tail['ds'] = prophet_forecast_tail['ds'].dt.strftime('%Y-%m-%d %H:%i:%s')\n log.info(\"------->Prophet Predictions\")\n log.info(prophet_forecast_tail)\n forecast_output = prophet_forecast_tail.to_json(orient='records')\n elif (model.lower() == 'arima'):\n predictions = loaded_model.predict(n_periods=no_of_prediction)\n predictions = predictions.round(2) \n self.features = sfeatures \n col = targetFeature.split(\",\")\n pred = pd.DataFrame(predictions,columns=col)\n predictionsdf = pred\n log.info(\"-------> Predictions\")\n log.info(predictionsdf)\n forecast_output = predictionsdf.to_json(orient='records')\n elif (model.lower() == 'encoder_decoder_lstm_mvi_uvo'):\n log.info(datetimeFeature)\n log.info(sfeatures)\n self.features = sfeatures\n if len(sfeatures) == 1:\n xt = xtrain[self.features].values\n else:\n xt = xtrain[self.features].values\n \n with open(scalertransformationFile, 'rb') as f:\n loaded_scaler_model = pickle.load(f)\n f.close()\n xt = xt.astype('float32')\n xt = loaded_scaler_model.transform(xt)\n pred_data = xt\n y_future = []\n \n featuerlen = len(sfeatures)\n targetColIndx = (xtrain.columns.get_loc(targetFeature))\n #in case of lstm multivariate input and univariate out prediction only one sequence can be predicted\n #consider the last xtrain window as input sequence\n\n pdata = pred_data[-lag_order:] \n pdata = pdata.reshape((1,lag_order, featuerlen))\n pred = loaded_model.predict(pdata)\n pred_1d = pred.ravel()\n #pred_1d = pred_1d.reshape(len(pred_1d),1)\n pdata_2d = pdata.ravel().reshape(len(pdata) * lag_order, featuerlen)\n pdata_2d[:,targetColIndx] = pred_1d\n pred_2d_inv = loaded_scaler_model.inverse_transform(pdata_2d) \n predout = pred_2d_inv[:, targetColIndx] \n predout = predout.reshape(len(pred_1d),1) \n #y_future.append(predout)\n\n col = targetFeature.split(\",\")\n pred = pd.DataFrame(index=range(0,len(predout)),columns=col)\n for i in range(0, len(predout)):\n pred.iloc[i] = predout[i]\n predictions = pred\n log.info(\"-------> Predictions\")\n log.info(predictions)\n forecast_output = predictions.to_json(orient='records')\n elif (model.lower() == 'mlp' or model.lower() == 'lstm'):\n sfeatures.remove(datetimeFeature)\n self.features = sfeatures\n if len(sfeatures) == 1:\n xt = xtrain[self.features].values\n else:\n xt = xtrain[self.features].values\n \n with open(scalertransformationFile, 'rb') as f:\n loaded_scaler_model = pickle.load(f)\n f.close()\n xt = xt.astype('float32')\n xt = loaded_scaler_model.transform(xt)\n pred_data = xt\n y_future = []\n for i in range(no_of_prediction):\n pdata = pred_data[-lag_order:] \n if model.lower() == 'mlp':\n pdata = pdata.reshape((1,lag_order)) \n else:\n pdata = pdata.reshape((1,lag_order, len(sfeatures))) \n if (len(sfeatures) > 1):\n pred = loaded_model.predict(pdata)\n predout = loaded_scaler_model.inverse_transform(pred) \n y_future.append(predout)\n pred_data=np.append(pred_data,pred,axis=0)\n else: \n pred = loaded_model.predict(pdata)\n predout = loaded_scaler_model.inverse_transform(pred) \n y_future.append(predout.flatten()[-1])\n pred_data = np.append(pred_data,pred)\n col = targetFeature.split(\",\")\n pred = pd.DataFrame(index=range(0,len(y_future)),columns=col)\n for i in range(0, len(y_future)):\n pred.iloc[i] = y_future[i]\n predictions = pred\n log.info(\"-------> Predictions\")\n log.info(predictions)\n forecast_output = predictions.to_json(orient='records')\n else:\n pass\n log.info('Status:-|... AION TimeSeries Forecasting completed') #task 11997\n log.info(\"------ Forecast Prediction End -------------\\\\n\")\n log.info('================ Time Series Forecasting Completed ================\\\\n') #task 11997\n if recommenderStatus:\n log.info('\\\\n================ Recommender Started ================ ')\n log.info('Status:-|... AION Recommender started')\n learner_type = 'RecommenderSystem'\n model_type = 'RecommenderSystem'\n modelType = model_type\n model = model_type\n targetColumn=''\n datacolumns=list(dataFrame.columns)\n self.features=datacolumns\n svd_params = config_obj.getEionRecommenderConfiguration()\n from recommender.item_rating import recommendersystem\n recommendersystemObj = recommendersystem(modelFeatures,svd_params)\n\n testPercentage = config_obj.getAION", "instruction": "", "output": "" }, { "input": "TestTrainPercentage() #Unnati\n saved_model,rmatrix,score,trainingperformancematrix,model_tried = recommendersystemObj.recommender_model(dataFrame,outputLocation)\n scoreParam = 'NA' #Task 11190\n log.info('Status:-|... AION Recommender completed')\n log.info('================ Recommender Completed ================\\\\n')\n \n if textsummarizationStatus:\n log.info('\\\\n================ text Summarization Started ================ ')\n log.info('Status:-|... AION text Summarization started')\n modelType = 'textsummarization'\n model_type = 'textsummarization'\n learner_type = 'Text Summarization'\n modelName='TextSummarization'\n from sklearn.preprocessing import LabelEncoder\n from sklearn.ensemble import RandomForestClassifier\n from scipy import spatial\n model = model_type \n dataLocationTS,deployLocationTS,KeyWordsTS,pathForKeywordFileTS = config_obj.getEionTextSummarizationConfig()\n #print(\"dataLocationTS\",dataLocationTS)\n #print(\"deployLocationTS\",deployLocationTS)\n #print(\"KeyWordsTS\",KeyWordsTS)\n #print(\"pathForKeywordFileTS\",pathForKeywordFileTS) \n #PreTrained Model Download starts-------------------------\n from appbe.dataPath import DATA_DIR\n preTrainedModellocation = Path(DATA_DIR)/'PreTrainedModels'/'TextSummarization'\n preTrainedModellocation = Path(DATA_DIR)/'PreTrainedModels'/'TextSummarization'\n models = {'glove':{50:'glove.6B.50d.w2vformat.txt'}}\n supported_models = [x for y in models.values() for x in y.values()]\n modelsPath = Path(DATA_DIR)/'PreTrainedModels'/'TextSummarization'\n Path(modelsPath).mkdir(parents=True, exist_ok=True)\n p = Path(modelsPath).glob('**/*')\n modelsDownloaded = [x.name for x in p if x.name in supported_models]\n selected_model=\"glove.6B.50d.w2vformat.txt\" \n if selected_model not in modelsDownloaded:\n print(\"Model not in folder, downloading\")\n import urllib.request\n location = Path(modelsPath)\n local_file_path = location/f\"glove.6B.50d.w2vformat.txt\"\n urllib.request.urlretrieve(f'https://aion-pretrained-models.s3.ap-south-1.amazonaws.com/text/glove.6B.50d.w2vformat.txt', local_file_path)\n from transformers import AutoTokenizer, AutoModelForSeq2SeqLM\n tokenizer = AutoTokenizer.from_pretrained(\"sshleifer/distilbart-cnn-12-6\")\n model = AutoModelForSeq2SeqLM.from_pretrained(\"sshleifer/distilbart-cnn-12-6\")\n tokenizer.save_pretrained(preTrainedModellocation)\n model.save_pretrained(preTrainedModellocation)\n #PreTrained Model Download ends-----------------------\n deployLocationData=deployLocation+\"\\\\\\\\data\\\\\\\\\"\n modelLocation=Path(DATA_DIR)/'PreTrainedModels'/'TextSummarization'/'glove.6B.50d.w2vformat.txt'\n KeyWordsTS=KeyWordsTS.replace(\",\", \" \") \n noOfKeyword = len(KeyWordsTS.split())\n keywords = KeyWordsTS.split()\n embeddings = {}\n word = ''\n with open(modelLocation, 'r', encoding=\"utf8\") as f:\n header = f.readline()\n header = header.split(' ')\n vocab_size = int(header[0])\n embed_size = int(header[1])\n for i in range(vocab_size):\n data = f.readline().strip().split(' ')\n word = data[0]\n embeddings[word] = [float(x) for x in data[1:]]\n readData=pd.read_csv(pathForKeywordFileTS,encoding='utf-8',encoding_errors= 'replace')\n for i in range(noOfKeyword):\n terms=(sorted(embeddings.keys(), key=lambda word: spatial.distance.euclidean(embeddings[word], embeddings[keywords[i]])) )[1:6] \n readData = readData.append({'Keyword': keywords[i]}, ignore_index=True)\n for j in range(len(terms)):\n readData = readData.append({'Keyword': terms[j]}, ignore_index=True)\n deployLocationDataKwDbFile=deployLocationData+\"keywordDataBase.csv\"\n readData.to_csv(deployLocationDataKwDbFile,encoding='utf-8',index=False)\n datalocation_path=dataLocationTS\n path=Path(datalocation_path)\n fileList=os.listdir(path)\n textExtraction = pd.DataFrame()\n textExtraction['Sentences']=\"\"\n rowIndex=0\n for i in range(len(fileList)):\n fileName=str(datalocation_path)+\"\\\\\\\\\"+str(fileList[i])\n if fileName.endswith(\".pdf\"):\n print(\"\\\\n files \",fileList[i])\n from pypdf import PdfReader\n reader = PdfReader(fileName)\n number_of_pages = len(reader.pages)\n text=\"\"\n textOutputForFile=\"\" \n OrgTextOutputForFile=\"\" \n for i in range(number_of_pages) :\n page = reader.pages[i]\n text1 = page.extract_text()\n text=text+text1\n import nltk\n tokens = nltk.sent_tokenize(text)\n for sentence in tokens:\n sentence=sentence.replace(\"\\\\n\", \" \") \n if (len(sentence.split()) < 4 ) or (len(str(sentence.split(',')).split()) < 8)or (any(chr.isdigit() for chr in sentence)) :\n continue\n textExtraction.at[rowIndex,'Sentences']=str(sentence.strip()) \n rowIndex=rowIndex+1 \n if fileName.endswith(\".txt\"):\n print(\"\\\\n txt files\",fileList[i])\n data=[]\n with open(fileName, \"r\",encoding=\"utf-8\") as f:\n data.append(f.read())\n str1 = \"\"\n for ele in data:\n str1 += ele\n sentences=str1.split(\".\")\n count=0\n for sentence in sentences:\n count += 1\n textExtraction.at[rowIndex+i,'Sentences']=str(sentence.strip())\n rowIndex=rowIndex+1 \n df=textExtraction\n #print(\"textExtraction\",textExtraction)\n deployLocationDataPreProcessData=deployLocationData+\"preprocesseddata.csv\"\n save_csv_compressed(deployLocationDataPreProcessData, df, encoding='utf-8')\n df['Label']=0\n kw=pd.read_csv(deployLocationDataKwDbFile,encoding='utf-8',encoding_errors= 'replace')\n Keyword_list = kw['Keyword'].tolist()\n for i in df.index:\n for x in Keyword_list:\n if (str(df[\"Sentences\"][i])).find(x) != -1:\n df['Label'][i]=1\n break\n deployLocationDataPostProcessData=deployLocationData+\"postprocesseddata.csv\"\n #df.to_csv(deployLocationDataPostProcessData,encoding='utf-8')\n save_csv_compressed(deployLocationDataPostProcessData, df, encoding='utf-8')\n labelledData=df\n train_df=labelledData\n labelencoder = LabelEncoder()\n train_df['Sentences'] = labelencoder.fit_transform(train_df['Sentences'])\n X = train_df.drop('Label',axis=1)\n y = train_df['Label'] \n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) \n Classifier = RandomForestClassifier(n_estimators = 10, random_state = 42)\n modelTs=Classifier.fit(X, y)\n import pickle\n deployLocationTS=deployLocation+\"\\\\\\\\model\\\\\\\\\"+iterName+'_'+iterVersion+'.sav'\n deployLocationTS2=deployLocation+\"\\\\\\\\model\\\\\\\\\"+\"classificationModel.sav\" \n pickle.dump(modelTs, open(deployLocationTS, 'wb'))\n pickle.dump(modelTs, open(deployLocationTS2, 'wb')) \n print(\"\\\\n trainModel Ends\")\n\n saved_model = 'textsummarization_'+iterName+'_'+iterVersion\n log.info('Status:-|... AION text summarization completed')\n model = learner_type\n log.info('================ text summarization Completed ================\\\\n')\n if survival_analysis_status:\n sa_method = config_obj.getEionanomalyModels()\n labeldict = {}\n log.info('\\\\n================ SurvivalAnalysis Started ================ ')\n log.info('Status:-|... AION SurvivalAnalysis started')\n\n log.info('\\\\n================ SurvivalAnalysis DataFrame ================ ')\n log.info(dataFrame)\n from survival import survival_analysis\n from learner.machinelearning import machinelearning\n sa_obj = survival_analysis.SurvivalAnalysis(dataFrame, preprocess_pipe, sa_method, targetFeature, datetimeFeature, filter_expression, profilerObj.train_features_type)\n if sa_obj != None:\n predict_json = sa_obj.learn()\n\n if sa_method.lower() in ['kaplanmeierfitter','kaplanmeier','kaplan-meier','kaplan meier','kaplan','km','kmf']:\n predicted = sa_obj.models[0].predict(dataFrame[datetimeFeature])\n\n status, msg = save_csv(predicted,predicted_data_file)\n if not status:\n log.info('CSV File Error: ' + str(msg))\n self.features = [datetimeFeature]\n elif sa_method.lower() in ['coxphfitter','coxregression','cox-regression','cox regression','coxproportionalhazard','coxph','cox','cph']:\n predicted = sa_obj.models[0].predict_cumulative_hazard(dataFrame)\n datacolumns = list(dataFrame.columns)\n targetColumn = targetFeature\n if targetColumn in datacolumns:\n datacolumns.remove(targetColumn)\n self.features = datacolumns\n score = sa_obj.score\n scoreParam = 'Concordance_Index'\n\n status,msg = save_csv(predicted,predicted_data_file)\n if not status:\n log.info('CSV File Error: ' + str(msg))\n model = sa_method\n \n modelType = \"SurvivalAnalysis\"\n model_type = \"SurvivalAnalysis\"\n modelName = sa_method\n i = 1\n for mdl in sa_obj.models:\n saved_model = \"%s_%s_%s_%d.sav\"%(model_type,sa_method,iterVersion,i)\n pickle.dump(mdl, open(os.path.join(deployLocation,'model',saved_model), 'wb')),\n i+=1\n p = 1\n for plot in sa_obj.plots:\n img_name = \"%s_%d.png\"%(sa_method,p)\n img_location = os.path.join(imageFolderLocation,img_name)\n plot.savefig(img_location,bbox_inches='tight')\n sa_images.append(img_location)\n p+=1\n log.info('Status:-|... AION SurvivalAnalysis completed')\n log.info('\\\\n================ SurvivalAnalysis Completed ================ ')\n if visualizationstatus:\n visualizationJson = config_obj.getEionVisualizationConfiguration()\n log.info('\\\\n================== Visualization Recommendation Started ==================')\n \n visualizer_mlstart = time.time()\n from visualization.visualization import Visualization\n 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)\n visualizationObj.visualizationrecommandsystem()\n visualizer_mlexecutionTime=time.time() - visualizer_mlstart\n log.info('-------> COMPUTING: Total Visualizer Execution Time '+str(visualizer_mlexecutionTime))\n \n log.info('================== Visualization Recommendation Started ==================\\\\n')\n if similarityIdentificationStatus or contextualSearchStatus:\n datacolumns=list(dataFrame.columns)\n features = modelFeatures.split(\",\")\n if indexFeature != '' and indexFeature != 'NA':\n iFeature = indexFeature.split(\",\")\n for ifea in iFeature:\n if ifea not in features:\n features.append(ifea) \n for x in features:\n dataFrame[x] = similaritydf[x]\n #get vectordb(chromadb) status selected\n if similarityIdentificationStatus:\n learner_type = 'similarityIdentification'\n else:\n learner_type = 'contextualSearch'\n vecDBCosSearchStatus = config_obj.getVectorDBCosSearchStatus(learner_type)\n if vecDBCosSearchStatus:\n status, msg = save_chromadb(dataFrame, config_obj, trained_data_file, modelFeatures)\n if not status:\n log.info('Vector DB File Error: '+str(msg))\n else:\n status, msg = save_csv(dataFrame,trained_data_file)\n if not status:\n log.info('CSV File Error: '+str(msg))\n self.features = datacolumns\n\n model_type = config_obj.getAlgoName(problem_type)\n model = model_type #bug 12833\n model_tried = '{\"Model\":\"'+model_type+'\",\"FeatureEngineering\":\"NA\",\"Score\":\"NA\",\"ModelUncertainty\":\"NA\"}'\n modelType = learner_type\n saved_model = learner_type\n score = 'NA' \n if deploy_status:\n if str(model) != 'None':\n log.info('\\\\n================== Deployment Started ==================')\n log.info('Status:-|... AION Creating Prediction Service Start')\n deployer_mlstart = time.time()\n \n deployJson = config_obj.getEionDeployerConfiguration()\n deploy_name = iterName+'_'+iterVersion\n from prediction_package.model_deploy import DeploymentManager\n if textsummarizationStatus :\n deploy = DeploymentManager()\n deploy.deployTSum(deployLocation,preTrainedModellocation)\n codeConfigure.save_config(deployLocation", "instruction": "", "output": "" }, { "input": ")\n deployer_mlexecutionTime=time.time() - deployer_mlstart\n log.info('-------> COMPUTING: Total Deployer Execution Time '+str(deployer_mlexecutionTime))\n log.info('Status:-|... AION Deployer completed')\n log.info('================== Deployment Completed ==================') \n else:\n deploy = DeploymentManager()\n 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)\n codeConfigure.update_config('deploy_path',os.path.join(deployLocation,'publish'))\n codeConfigure.save_config(deployLocation)\n deployer_mlexecutionTime=time.time() - deployer_mlstart\n log.info('-------> COMPUTING: Total Deployer Execution Time '+str(deployer_mlexecutionTime))\n log.info('Status:-|... AION Creating Prediction Service completed')\n log.info('================== Deployment Completed ==================') \n \n if not outputDriftStatus and not inputDriftStatus:\n from transformations.dataProfiler import set_features\n self.features = set_features(self.features,profilerObj)\n self.matrix += '}'\n self.trainmatrix += '}'\n print(model_tried)\n model_tried = eval('['+model_tried+']')\n matrix = eval(self.matrix)\n trainmatrix = eval(self.trainmatrix)\n deployPath = deployLocation.replace(os.sep, '/')\n if survival_analysis_status:\n 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}}\n elif not timeseriesStatus:\n try:\n json.dumps(params)\n 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}}\n except:\n 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}}\n else:\n if config_obj.summarize:\n modelType = 'Summarization'\n 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}} \n if bool(topics) == True:\n output_json['topics'] = topics\n with open(outputjsonFile, 'w',encoding='utf-8') as f:\n json.dump(output_json, f)\n f.close() \n output_json = json.dumps(output_json) \n\n log.info('\\\\n------------- Summary ------------')\n log.info('------->No of rows & columns in data:('+str(self.dfrows)+','+str(self.dfcols)+')')\n log.info('------->No of missing Features :'+str(len(self.mFeatures)))\n log.info('------->Missing Features:'+str(self.mFeatures))\n log.info('------->Text Features:'+str(self.textFeatures))\n log.info('------->No of Nonnumeric Features :'+str(len(self.nonNumericFeatures)))\n log.info('------->Non-Numeric Features :' +str(self.nonNumericFeatures))\n if threshold == -1:\n log.info('------->Threshold: NA')\n else:\n log.info('------->Threshold: '+str(threshold))\n log.info('------->Label Maps of Target Feature for classification :'+str(labelMaps))\n for i in range(0,len(self.similarGroups)):\n log.info('------->Similar Groups '+str(i+1)+' '+str(self.similarGroups[i]))\n if((learner_type != 'TS') & (learner_type != 'AR')):\n log.info('------->No of columns and rows used for Modeling :'+str(featureDataShape))\n log.info('------->Features Used for Modeling:'+str(self.features))\n log.info('------->Target Feature: '+str(targetColumn))\n log.info('------->Best Model Score :'+str(score))\n log.info('------->Best Parameters:'+str(params))\n log.info('------->Type of Model :'+str(modelType))\n log.info('------->Best Model :'+str(model))\n log.info('------------- Summary ------------\\\\n')\n log.info('Status:-|... AION Model Training Successfully Done')\n \n except Exception as inst:\n log.info('server code execution failed !....'+str(inst))\n log.error(inst, exc_info = True)\n output_json = {\"status\":\"FAIL\",\"message\":str(inst).strip('\"'),\"LogFile\":logFileName}\n output_json = json.dumps(output_json)\n\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\n executionTime = timeit.default_timer() - startTime\n log.info('\\\\nTotal execution time(sec) :'+str(executionTime))\n log.info('\\\\n------------- Output JSON ------------')\n log.info('aion_learner_status:'+str(output_json))\n log.info('------------- Output JSON ------------\\\\n')\n for hdlr in log.handlers[:]: # remove the existing file handlers\n if isinstance(hdlr,logging.FileHandler):\n hdlr.close()\n log.removeHandler(hdlr)\n return output_json\n\n def split_into_train_test_data(self,featureData,targetData,testPercentage,log,modelType='classification'): #Unnati\n log.info('\\\\n-------------- Test Train Split ----------------')\n if testPercentage == 0 or testPercentage == 100: #Unnati\n xtrain=featureData\n ytrain=targetData\n xtest=pd.DataFrame()\n ytest=pd.DataFrame()\n else:\n testSize= testPercentage/100 #Unnati\n if modelType == 'regression':\n log.info('-------> Split Type: Random Split')\n xtrain,xtest,ytrain,ytest=train_test_split(featureData,targetData,test_size=testSize,shuffle=True,random_state=42)\n else:\n try:\n log.info('-------> Split Type: Stratify Split')\n xtrain,xtest,ytrain,ytest=train_test_split(featureData,targetData,stratify=targetData,test_size=testSize,random_state=42)\n except Exception as ValueError:\n count_unique = targetData.value_counts()\n feature_with_single_count = count_unique[ count_unique == 1].index.tolist()\n 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\"\n raise Exception(error) from ValueError\n\n except:\n log.info('-------> Split Type: Random Split')\n xtrain,xtest,ytrain,ytest=train_test_split(featureData,targetData,test_size=testSize,shuffle=True,random_state=42)\n\n log.info('Status:- !... Train / test split done: '+str(100-testPercentage)+'% train,'+str(testPercentage)+'% test') #Unnati\n log.info('-------> Train Data Shape: '+str(xtrain.shape)+' ---------->')\n log.info('-------> Test Data Shape: '+str(xtest.shape)+' ---------->')\n log.info('-------------- Test Train Split End ----------------\\\\n')\n return(xtrain,ytrain,xtest,ytest)\n\ndef aion_train_model(arg):\n warnings.filterwarnings('ignore')\n config_path = Path( arg)\n with open( config_path, 'r') as f:\n config = json.load( f)\n log = set_log_handler(config['basic'])\n log.info('************* Version - v'+AION_VERSION+' *************** \\\\n')\n msg = '-------> Execution Start Time: '+ datetime.datetime.now(timezone(\"Asia/Kolkata\")).strftime('%Y-%m-%d %H:%M:%S' + ' IST')\n log.info(msg)\n try:\n config_validate(arg)\n valid, msg = pushRecordForTraining()\n if valid:\n serverObj = server()\n configObj = AionConfigManager()\n codeConfigure = code_configure()\n codeConfigure.create_config(config)\n readConfistatus,msg = configObj.readConfigurationFile(config)\n if(readConfistatus == False):\n raise ValueError( msg)\n output = serverObj.startScriptExecution(configObj, codeConfigure, log)\n else:\n output = {\"status\":\"LicenseVerificationFailed\",\"message\":str(msg).strip('\"')}\n output = json.dumps(output)\n print( f\"\\\\naion_learner_status:{output}\\\\n\")\n log.info( f\"\\\\naion_learner_status:{output}\\\\n\")\n except Exception as inst:\n output = {\"status\":\"FAIL\",\"message\":str(inst).strip('\"')}\n output = json.dumps(output) \n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n print(f\"\\\\naion_learner_status:{output}\\\\n\")\n log.info( f\"\\\\naion_learner_status:{output}\\\\n\")\n return output\n\nif __name__ == \"__main__\":\n aion_train_model( sys.argv[1])\n \n\n\n'''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\n\nimport time\nimport os\nimport sys\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.preprocessing import binarize\nfrom learner.optimizetechnique import OptimizationTq\nfrom learner.parameters import parametersDefine\nimport logging\nfrom learner.aion_matrix import aion_matrix\n\n\n# apply threshold to positive probabilities to create labels\ndef to_labels(pos_probs, threshold):\n\treturn (pos_probs >= threshold).astype('int')\nclass incClassifierModel():\n\tdef __init__(self,noOfClasses,modelList,params,scoreParam,cvSplit,numIter,geneticParam,trainX,trainY,testX,testY,method,modelType,MakeFP0,MakeFN0,deployLocation):\n\t\tself.noOfClasses = noOfClasses\n\t\tself.modelList =modelList\n\t\tself.params =params\n\t\tself.trainX =trainX\n\t\tself.X =trainX\n\t\tself.trainY =trainY\n\t\tself.testX = testX\n\t\tself.testY = testY\n\t\tself.method =method\n\t\tself.scoreParam=scoreParam\n\t\tself.cvSplit=cvSplit\n\t\tself.numIter=numIter\n\t\tself.geneticParam=geneticParam\n\t\tself.MakeFP0= MakeFP0\n\t\tself.MakeFN0=MakeFN0\n\t\tself.log = logging.getLogger('eion')\n\t\tself.modelType = modelType\n\t\tself.deployLocation = deployLocation\n\t\tself.isRiverModel = False\n\t\tself.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'}\n\t\tself.modelToAlgoNames = {value: key for key, value in self.AlgorithmNames.items()}\n\t\t\n\tdef check_threshold(self,estimator,testX,testY,threshold_range,checkParameter,modelName):\n\t\tthresholdx = -1\n\t\tfor threshold in threshold_range:\n\t\t\tpredictedData = estimator.predict_proba(testX)\n\t\t\tpredictedData = binarize(predictedData[:,1].reshape(-1, 1),threshold=threshold)#bug 12437\n\t\t\tp_score = precision_score(testY, predictedData) \n\t\t\tr_score = recall_score(testY, predictedData)\n\t\t\ttn, fp, fn, tp = confusion_matrix(testY, predictedData).ravel()\n\t\t\tif(checkParameter.lower() == 'fp'):\n\t\t\t\tif fp == 0:\n\t\t\t\t\tif(p_score == 1):\n\t\t\t\t\t\tthresholdx = threshold\n\t\t\t\t\t\tself.log.info('---------------> Best Threshold:'+str(threshold))\n\t\t\t\t\t\tself.log.info('---------------> Best Precision:'+str(p_score))\n\t\t\t\t\t\tself.log.", "instruction": "", "output": "" }, { "input": "info('---------------> Best Recall:'+str(r_score))\n\t\t\t\t\t\tself.log.info('---------------> TN:'+str(tn))\n\t\t\t\t\t\tself.log.info('---------------> FP:'+str(fp))\n\t\t\t\t\t\tself.log.info('---------------> FN:'+str(fn))\n\t\t\t\t\t\tself.log.info('---------------> TP:'+str(tp))\n\t\t\t\t\t\tbreak\n\t\t\t\n\t\t\tif(checkParameter.lower() == 'fn'):\n\t\t\t\tif fn == 0:\n\t\t\t\t\tif(r_score == 1):\n\t\t\t\t\t\tthresholdx = threshold\n\t\t\t\t\t\tself.log.info('---------------> Best Threshold:'+str(threshold))\n\t\t\t\t\t\tself.log.info('---------------> Best Precision:'+str(p_score))\n\t\t\t\t\t\tself.log.info('---------------> Best Recall:'+str(r_score))\n\t\t\t\t\t\tself.log.info('---------------> TN:'+str(tn))\n\t\t\t\t\t\tself.log.info('---------------> FP:'+str(fp))\n\t\t\t\t\t\tself.log.info('---------------> FN:'+str(fn))\n\t\t\t\t\t\tself.log.info('---------------> TP:'+str(tp))\n\t\t\t\t\t\tbreak\n\t\treturn(thresholdx,p_score,r_score)\n\n\tdef getBestModel(self,fp0,fn0,threshold,bestthreshold,rscore,brscore,pscore,bpscore,tscore,btscore):\n\t\tcmodel = False \n\t\tif(threshold != -1):\n\t\t\tif(bestthreshold == -1):\n\t\t\t\tcmodel = True\n\t\t\t\tbestthreshold = threshold\n\t\t\t\tbrscore = rscore\n\t\t\t\tbpscore = pscore\n\t\t\t\tbtscore = tscore\t\n\t\t\telif fp0:\n\t\t\t\tif rscore > brscore:\t\n\t\t\t\t\tcmodel = True\n\t\t\t\t\tbestthreshold = threshold\n\t\t\t\t\tbrscore = rscore\n\t\t\t\t\tbpscore = pscore\n\t\t\t\t\tbtscore = tscore\t\n\t\t\t\telif rscore == brscore:\n\t\t\t\t\tif tscore > btscore or btscore == -0xFFFF:\t\n\t\t\t\t\t\tcmodel = True\n\t\t\t\t\t\tbestthreshold = threshold\n\t\t\t\t\t\tbrscore = rscore\n\t\t\t\t\t\tbpscore = pscore\n\t\t\t\t\t\tbtscore = tscore\t\n\t\t\telif fn0:\n\t\t\t\tif pscore > bpscore:\t\n\t\t\t\t\tcmodel = True\n\t\t\t\t\tbestthreshold = threshold\n\t\t\t\t\tbrscore = rscore\n\t\t\t\t\tbpscore = pscore\n\t\t\t\t\tbtscore = tscore\t\n\t\t\t\telif pscore == bpscore:\n\t\t\t\t\tif tscore > btscore or btscore == -0xFFFF:\t\n\t\t\t\t\t\tcmodel = True\n\t\t\t\t\t\tbestthreshold = threshold\n\t\t\t\t\t\tbrscore = rscore\n\t\t\t\t\t\tbpscore = pscore\n\t\t\t\t\t\tbtscore = tscore\t\n\t\t\telse:\n\t\t\t\tif tscore > btscore or btscore == -0xFFFF:\t\n\t\t\t\t\tcmodel = True\t\n\t\t\t\t\tbtscore = tscore\n\t\telse:\n\t\t\tif(bestthreshold == -1):\n\t\t\t\tif tscore > btscore or btscore == -0xFFFF:\t\n\t\t\t\t\tcmodel = True\n\t\t\t\t\tbtscore = tscore\n\t\t\n\t\treturn cmodel,btscore,bestthreshold,brscore,bpscore\n\t\t\t\n\t\t\t\t\n\tdef firstFit(self): \n\t\tbestModel='None'\n\t\tbestParams={}\n\t\tbestScore=-0xFFFF\n\t\tbestEstimator = 'None'\n\t\tscoredetails = ''\n\t\tthreshold = -1\n\t\tbestthreshold = -1\n\t\tprecisionscore =-1\n\t\tbestprecisionscore=-1\n\t\trecallscore = -1\n\t\tbestrecallscore=-1\n\t\tself.bestTrainPredictedData = None\n\t\tself.bestPredictedData = None\n\t\tself.log.info('\\\\n---------- ClassifierModel has started ----------')\n\t\tobjClf = aion_matrix()\n\t\ttry:\n\t\t\tfor modelName in self.modelList:\t\t\t\t\n\t\t\t\tparamSpace=self.params[modelName]\n\t\t\t\talgoName = self.AlgorithmNames[modelName]\n\t\t\t\tfrom incremental.riverML import riverML\n\t\t\t\triverMLObj = riverML()\t\n\t\t\t\tself.log.info(\"-------> Model Name: \"+str(modelName))\n\t\t\t\tstart = time.time()\n\t\t\t\tmodel, modelParams, estimator, trainPredictedData = riverMLObj.startLearn('classification',algoName,paramSpace,self.trainX, self.trainY, self.noOfClasses)\n\t\t\t\tmodelParams = str(modelParams)\n\t\t\t\tpredictedData = riverMLObj.getPrediction(estimator,self.testX)\n\t\t\t\texecutionTime=time.time() - start\n\t\t\t\tself.testY.reset_index(inplace=True, drop=True)\n\t\t\t\tscore = objClf.get_score(self.scoreParam,self.testY.values.flatten(),predictedData.values.flatten())\n\t\t\t\tself.log.info(str(score))\n\t\t\t\tmetrices = {}\n\t\t\t\tmetrices[\"score\"] = score\n\t\t\t\tthreshold = -1\n\t\t\t\tprecisionscore = precision_score(self.testY, predictedData, average='macro')\n\t\t\t\trecallscore = recall_score(self.testY, predictedData, average='macro')\n\t\t\t\tself.log.info('---------> Total Execution: '+str(executionTime))\n\t\t\t\t\n\t\t\n\t\t\t\tif(scoredetails != ''):\n\t\t\t\t\tscoredetails += ','\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\tscoredetails += '{\"Model\":\"'+self.modelToAlgoNames[model]+'\",\"Score\":'+str(score)+'}'\n\t\t\n\t\t\t\tstatus,bscore,bthres,brscore,bpscore = self.getBestModel(self.MakeFP0,self.MakeFN0,threshold,bestthreshold,recallscore,bestrecallscore,precisionscore,bestprecisionscore,score,bestScore)\t\t\t\n\t\t\t\tif status:\n\t\t\t\t\tbestScore =bscore\n\t\t\t\t\tbestModel =model\n\t\t\t\t\tbestParams=modelParams\n\t\t\t\t\tbestEstimator=estimator\n\t\t\t\t\tbestthreshold = threshold\n\t\t\t\t\tbestrecallscore = recallscore\n\t\t\t\t\tbestprecisionscore = precisionscore\n\t\t\t\t\tself.bestTrainPredictedData = trainPredictedData\n\t\t\t\t\tself.bestPredictedData = predictedData\n\t\t\t\tself.log.info('Status:- |... ML Algorithm applied: '+modelName)\n\t\t\t\tself.log.info(\"Status:- |... Testing Score: \"+str(score))\n\n\t\t\tself.log.info('---------- ClassifierModel End ---------- \\\\n')\n\t\t\tself.log.info('\\\\n------- Best Model and its parameters -------------')\n\t\t\tself.log.info('Status:- |... Best Algorithm selected: '+str(self.modelToAlgoNames[bestModel])+' Score='+str(round(bestScore,2)))\n\t\t\tself.log.info(\"-------> Best Name: \"+str(bestModel))\n\t\t\tself.log.info(\"-------> Best Score: \"+str(bestScore))\n\n\t\t\treturn self.modelToAlgoNames[bestModel],bestParams,bestScore,bestEstimator,scoredetails,bestthreshold,bestprecisionscore,bestrecallscore\n\t\texcept Exception as inst:\n\t\t\tself.log.info( '\\\\n-----> ClassifierModel failed!!!.'+str(inst))\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport warnings\nwarnings.filterwarnings('ignore')\nimport logging\nimport sklearn\nfrom random import sample\nfrom numpy.random import uniform\nimport numpy as np\nimport math\nimport pickle\nimport os\nimport json\nfrom math import isnan\nfrom sklearn.preprocessing import binarize\nfrom sklearn.preprocessing import LabelEncoder\nimport pandas as pd\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom incremental.incClassificationModel import incClassifierModel\nfrom incremental.incRegressionModel import incRegressionModel\n\n\n\t\nclass incMachineLearning(object):\n\tdef __init__(self,mlobj):\n\t\tself.features=[]\n\t\tself.mlobj=mlobj\n\t\tself.log = logging.getLogger('eion')\n\n\t\n\t\n\n\tdef 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): \n\t\tmodel = 'None'\n\t\tparams = 'None'\n\t\tscore = 0xFFFF\n\t\testimator = None\n\t\tmodel_tried = ''\n\t\tthreshold = -1\n\t\tpscore = -1\n\t\trscore = -1\t\t\n\t\ttopics = {}\t\t\n\t\tif(targetColumn != ''):\n\t\t\ttargetData = dataFrame[targetColumn]\n\t\tdatacolumns=list(dataFrame.columns)\n\t\tif targetColumn in datacolumns:\n\t\t\tdatacolumns.remove(targetColumn)\n\t\t\n\n\t\tscoreParam = self.mlobj.setScoreParams(scoreParam,modelType,categoryCountList)\n\n\t\t\n\t\tself.log.info('\\\\n-------------- Training ML: Start --------------')\n\t\tmodel_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)\n\t\tself.log.info('-------------- Training ML: End --------------\\\\n')\t\t\t\t\n\n\t\tfilename = os.path.join(deployLocation,'production','model',model+'.pkl')\n\t\tsaved_model = model+'.pkl'\n\t\tpickle.dump(estimator, open(filename, 'wb'))\n\t\tdf_test = xtest.copy()\n\t\tdf_test.reset_index(inplace = True,drop=True)\n\t\ttrainPredictedData = incObj.bestTrainPredictedData\n\t\tpredictedData = incObj.bestPredictedData\n\t\ttry: \n\t\t\tif(model_type == 'Classification'):\n\t\t\t\tself.log.info('\\\\n--------- Performance Matrix with Train Data ---------')\n\t\t\t\ttrain_matrix = self.mlobj.getClassificationPerformaceMatrix(ytrain,trainPredictedData,labelMaps)\n\t\t\t\tself.log.info('--------- Performance Matrix with Train Data End ---------\\\\n')\n\t\t\t\tself.log.info('\\\\n--------- Performance Matrix with Test Data ---------')\n\t\t\t\tperformancematrix = self.mlobj.getClassificationPerformaceMatrix(ytest,predictedData,labelMaps)\n\t\t\t\tytest.reset_index(inplace=True,drop=True)\n\t\t\t\tdf_test['actual'] = ytest\n\t\t\t\tdf_test['predict'] = predictedData\n\t\t\t\tself.log.info('--------- Performance Matrix with Test Data End ---------\\\\n')\n\t\t\t\n\t\t\t\tmatrix = performancematrix\n\t\t\telif(model_type == 'Regression'):\n\t\t\t\tself.log.info('\\\\n--------- Performance Matrix with Train Data ---------')\n\t\t\t\ttrain_matrix = self.mlobj.get_regression_matrix(ytrain, trainPredictedData)\n\t\t\t\tself.log.info('--------- Performance Matrix with Train Data End ---------\\\\n')\n\t\t\t\tself.log.info('\\\\n--------- Performance Matrix with Test Data ---------')\n\t\t\t\tmatrix = self.mlobj.get_regression_matrix(ytest, predictedData)\n\t\t\t\tytest.reset_index(inplace=True, drop=True)\n\t\t\t\tdf_test['actual'] = ytest\n\t\t\t\tdf_test['predict'] = predictedData\n\t\t\t\tself.log.info('--------- Performance Matrix with Test Data End ---------\\\\n')\n\n\t\texcept Exception as Inst:\n\t\t\tself.log.info('--------- Error Performance Matrix ---------\\\\n') \n\t\t\tself.log.info(str(Inst))\n\t\t\tdf_test['predict'] = predictedData\n\t\t\tmatrix = \"\"\n\t\t\ttrain_matrix = \"\"\n\t\t\tself.log.info('--------- Performance Matrix with Test Data End ---------\\\\n')\n\t\tdf_test.to_csv(predicted_data_file)\n\t\treturn '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\n\n\n\n\n\tdef startLearnerModule(self,mlconfig,modelType,modelParams,modelList,scoreParam,targetColumn,dataFrame,xtrain,ytrain,xtest,ytest,categoryCountList,targetType,deployLocation,iterName,iterVersion,trained_data_file,labelMaps):\n\t\tmatrix = ''\n\t\tthreshold = -1\n\t\tpscore = -1\n\t\trscore = -1\n\t\tdatacolumns=list(xtrain.columns)\n\t\tif targetColumn in datacolumns:\n\t\t\tdatacolumns.remove(targetColumn)\n\t\tself.features =datacolumns\n\t\tself.log.info('-------> Features Used For Training the Model: '+(str(self.features))[:500])\n\t\txtrain = xtrain[self.features]\n\t\txtest = xtest[self.features]\n\t\tmethod = mlconfig['optimizationMethod']\n\t\tmethod = method.lower()\n\t\tgeneticParam = ''\n\t\toptimizationHyperParameter = mlconfig['optimizationHyperParameter']\n\t\tcvSplit = optimizationHyperParameter['trainTestCVSplit']\n\t\tnIter = int(optimizationHyperParameter['iterations'])\n\t\tif(method.lower() == 'genetic'):\n\t\t\tgeneticParam = optimizationHyperParameter['geneticparams']\n\t\tscoreParam = scoreParam\n\t\tif 'thresholdTunning' in mlconfig:\n\t\t\tthresholdTunning = mlconfig['thresholdTunning']", "instruction": "", "output": "" }, { "input": "\n\t\telse:\n\t\t\tthresholdTunning = 'NA'\n\t\tif cvSplit == \"\":\n\t\t\tcvSplit =None\n\t\telse:\n\t\t\tcvSplit =int(cvSplit)\n\n\t\tif modelType == 'classification':\n\t\t\tmodel_type = \"Classification\"\n\t\t\tMakeFP0 = False\n\t\t\tMakeFN0 = False\n\t\t\tif(len(categoryCountList) == 2):\n\t\t\t\tif(thresholdTunning.lower() == 'fp0'):\n\t\t\t\t\tMakeFP0 = True\n\t\t\t\telif(thresholdTunning.lower() == 'fn0'):\n\t\t\t\t\tMakeFN0 = True\n\t\t\tnoOfClasses= len(labelMaps)\n\t\t\tincObjClf = incClassifierModel(noOfClasses,modelList, modelParams, scoreParam, cvSplit, nIter,geneticParam, xtrain,ytrain,xtest,ytest,method,modelType,MakeFP0,MakeFN0,deployLocation)\n\t\t\tmodel, params, score, estimator,model_tried,threshold,pscore,rscore = incObjClf.firstFit()\n\t\t\tincObj = incObjClf \n\n\t\telif modelType == 'regression':\n\t\t\tmodel_type = \"Regression\"\n\t\t\tincObjReg = incRegressionModel(modelList, modelParams, scoreParam, cvSplit, nIter,geneticParam, xtrain,ytrain,xtest,ytest,method,deployLocation)\n\t\t\tmodel,params,score,estimator,model_tried = incObjReg.firstFit()\n\t\t\tincObj = incObjReg\n\n\t\t\t\n\t\treturn model_type,model,params, score, estimator,model_tried,xtrain,ytrain,xtest,ytest,threshold,pscore,rscore,method, incObj \nimport logging\nimport pickle\nimport os\nimport sys\nimport pandas as pd\nfrom river import stream\n\nfrom river.linear_model import LogisticRegression, SoftmaxRegression, LinearRegression\nfrom river.tree import ExtremelyFastDecisionTreeClassifier, HoeffdingAdaptiveTreeRegressor\n# from river.ensemble import AdaptiveRandomForestRegressor, AdaptiveRandomForestClassifier\nfrom river.neighbors import KNNClassifier, KNNRegressor\nfrom river.multiclass import OneVsRestClassifier\nfrom river.optim import SGD, Adam, AdaDelta, NesterovMomentum, RMSProp\n# from river.optim.losses import CrossEntropy, Log, MultiClassLoss, Poisson, RegressionLoss, BinaryLoss, Huber\n# from river.optim.initializers import Normal\n\n\nclass riverML(object):\n\tdef __init__(self):\n\t\tself.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}\n\t\tself.optDict={'sgd': SGD, 'adam':Adam, 'adadelta':AdaDelta, 'nesterovmomentum':NesterovMomentum, 'rmsprop':RMSProp}\n\t\tself.log = logging.getLogger('eion')\n\n\n\n\tdef getPrediction(self, model,X):\n\t\ttestStream = stream.iter_pandas(X)\n\t\tpreds = []\n\t\tfor (xi,yi) in testStream:\n\t\t\tpred = model.predict_one(xi)\n\t\t\tpreds.append(pred)\n\t\treturn pd.DataFrame(preds)\n\n\n\tdef startLearn(self,problemType,algoName,params,xtrain,ytrain,noOfClasses=None):\n\t\ttry:\n\t\t\tmodel = self.algoDict[algoName]\n\t\t\tparams = self.parseParams(params, algoName)\n\t\t\tif problemType == 'classification':\n\t\t\t\tif noOfClasses>2:\n\t\t\t\t\tmodel = OneVsRestClassifier(classifier=model(**params))\n\t\t\t\telse:\n\t\t\t\t\tmodel = model(**params)\n\t\t\telse:\n\t\t\t\tmodel = model(**params)\n\n\t\t\ttrainStream = stream.iter_pandas(xtrain, ytrain)\n\t\t\t#head start\n\t\t\tfor i, (xi, yi) in enumerate(trainStream):\n\t\t\t\tif i>100:\n\t\t\t\t\tbreak\n\t\t\t\tif yi!=None:\n\t\t\t\t\tmodel.learn_one(xi, yi)\n\t\t\ttrainPredictedData = []\n\t\t\ttrainStream = stream.iter_pandas(xtrain, ytrain)\n\t\t\tfor i, (xi, yi) in enumerate(trainStream):\n\t\t\t\tif yi!=None:\n\t\t\t\t\ttrainPredictedData.append(model.predict_one(xi))\n\t\t\t\t\tmodel.learn_one(xi, yi)\n\t\t\ttrainPredictedData = pd.DataFrame(trainPredictedData)\n\t\t\treturn algoName, params, model, trainPredictedData\n\t\texcept Exception as inst:\n\t\t\tself.log.info( '\\\\n-----> '+algoName+' failed!!!.'+str(inst))\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\n\tdef parseParams(self, params, algoName):\n\t\ttry:\n\t\t\tfrom learner.parameters import parametersDefine\n\t\t\tparamsObj = parametersDefine()\n\t\t\tparamDict =paramsObj.paramDefine(params,method=None)\n\t\t\tparamDict = {k:v[0] for k,v in paramDict.items()}\n\t\t\tif algoName=='Online Logistic Regression' or algoName=='Online Softmax Regression' or algoName=='Online Linear Regression':\n\t\t\t\topt = self.optDict[paramDict.pop('optimizer').lower()]\n\t\t\t\tlr = float(paramDict.pop('optimizer_lr'))\n\t\t\t\tparamDict['optimizer'] = opt(lr)\n\t\t\treturn paramDict\n\t\texcept Exception as inst:\n\t\t\tself.log.info( '\\\\n-----> Parameter parsing failed!!!.'+str(inst))\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\n\n\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\n#System imports\nimport logging\nimport os\nimport sys\nimport pickle\n\n#Sci-Tools imports\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom scipy import stats\nfrom word2number import w2n\n\n\n#river imports\nfrom river.preprocessing import StatImputer\nfrom river import stats, compose, anomaly\n\n\n\nclass incProfiler():\n\t\n\tdef __init__(self):\n\t\tself.DtypesDic={}\n\t\tself.pandasNumericDtypes=['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n\t\tself.allNumberTypeCols = [] #all number type columns\n\t\tself.allNumCols = [] #only numerical columns which includes num features and target if it is numerical\n\t\tself.allCatCols = []\n\t\tself.numFtrs = []\n\t\tself.catFtrs = []\n\t\tself.textFtrs = []\n\t\tself.textVectorFtrs = []\n\t\tself.numDiscreteCols = []\n\t\tself.numContinuousCols = []\n\t\tself.wordToNumericFeatures=[]\n\t\tself.emptyCols=[]\n\t\tself.missingCols = []\n\t\tself.targetColumn = \"\"\n\n\t\tself.le_dict = {}\n\t\tself.configDict = {}\n\t\tself.incFill = None\n\t\tself.incLabelMapping = None\n\t\tself.incCatEncoder = None\n\t\tself.incScaler = None\n\t\tself.incOutlierRem = None\n\t\tself.log = logging.getLogger('eion')\n\t\t\n\n\n\tdef pickleDump(self, model, path):\n\t\tif model is not None:\n\t\t\twith open(path, 'wb') as f:\n\t\t\t\tpickle.dump(model, f)\t\n\t\t\t\t\n\n\tdef saveProfilerModels(self, deployLocation):\n\t\tif isinstance(self.incFill['num_fill'], StatImputer) or isinstance(self.incFill['cat_fill'], StatImputer):\n\t\t\tself.pickleDump(self.incFill, os.path.join(deployLocation,'production','profiler','incFill.pkl'))\n\t\tself.pickleDump(self.incLabelMapping, os.path.join(deployLocation,'production','profiler','incLabelMapping.pkl'))\n\t\tself.pickleDump(self.incCatEncoder, os.path.join(deployLocation,'production','profiler','incCatEncoder.pkl'))\n\t\tself.pickleDump(self.incScaler, os.path.join(deployLocation,'production','profiler','incScaler.pkl'))\n\t\tself.pickleDump(self.incOutlierRem, os.path.join(deployLocation,'production','profiler','incOutlierRem.pkl'))\n\n\n\n\n\tdef featureAnalysis(self, df, conf_json, targetFeature):\n\t\ttry:\n\t\t\tself.log.info('-------> Remove Duplicate Rows')\n\t\t\tnoofdplicaterows = df.duplicated(keep='first').sum()\n\t\t\tdf = df.drop_duplicates(keep=\"first\")\n\t\t\tdf = df.reset_index(drop=True)\n\t\t\tself.log.info('Status:- |... Duplicate row treatment done: '+str(noofdplicaterows))\n\t\t\tself.log.info(df.head(5))\n\t\t\tself.log.info( '\\\\n----------- Inspecting Features -----------')\t\n\t\t\tctn_count = 0\n\t\t\tdf = df.replace('-', np.nan)\n\t\t\tdf = df.replace('?', np.nan)\n\t\t\tdataFDtypes=self.dataFramecolType(df)\n\t\t\tnumerical_ratio = float(conf_json['numericFeatureRatio'])\n\t\t\tcategoricalMaxLabel = int(conf_json['categoryMaxLabel'])\n\t\t\tindexFeatures = []\n\t\t\tnumOfRows = df.shape[0]\n\t\t\tdataCols = df.columns\n\t\t\tfor item in dataFDtypes:\n\t\t\t\tif(item[1] == 'object'):\n\t\t\t\t\tfilteredDf,checkFlag = self.smartFilter(item[0],df,numerical_ratio)\n\t\t\t\t\tif(checkFlag):\n\t\t\t\t\t\tself.wordToNumericFeatures.append(item[0])\n\t\t\t\t\t\tself.log.info('----------> Data Type Converting to numeric :Yes')\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tdf[item[0]]=filteredDf[item[0]].astype(float)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\tpass\n\t\t\t\t\t\tctn_count = ctn_count+1\n\t\t\t\telse:\n\t\t\t\t\tcount = (df[item[0]] - df[item[0]].shift() == 1).sum()\n\t\t\t\t\tif((numOfRows - count) == 1):\n\t\t\t\t\t\tself.log.info( '-------> Feature :'+str(item[0]))\n\t\t\t\t\t\tself.log.info('----------> Sequence Feature')\n\t\t\t\t\t\tindexFeatures.append(item[0])\n\t\t\tself.configDict['wordToNumCols'] = self.wordToNumericFeatures\n\t\t\tself.configDict['emptyFtrs'] = indexFeatures\n\t\t\tself.log.info('Status:- |... Feature inspection done for numeric data: '+str(ctn_count)+' feature(s) converted to numeric')\n\t\t\tself.log.info('Status:- |... Feature word to numeric treatment done: '+str(self.wordToNumericFeatures))\n\t\t\tself.log.info( '----------- Inspecting Features End -----------\\\\n')\n\t\texcept Exception as inst:\n\t\t\tself.log.info(\"Error in Feature inspection: \"+str(inst))\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\ttry:\n\t\t\tself.log.info('\\\\n---------- Dropping Index features ----------')\n\t\t\tself.log.info('Index Features to remove '+str(indexFeatures))\n\t\t\tif len(indexFeatures) > 0:\n\t\t\t\tdataCols = list(set(dataCols) - set(indexFeatures))\n\t\t\t\tfor empCol in indexFeatures:\n\t\t\t\t\tself.log.info('-------> Drop Feature: '+empCol)\n\t\t\t\t\tdf = df.drop(columns=[empCol])\n\t\t\tself.log.info('---------- Dropping Index features End----------\\\\n')\t\n\n\n\t\t\tdataFDtypes=self.dataFramecolType(df)\n\t\t\tcategoricalMaxLabel = int(conf_json['categoryMaxLabel'])\n\t\t\tfor item in dataFDtypes:\t\t\t\t\n\t\t\t\tself.DtypesDic[item[0]] = item[1]\t\t\t\t\n\t\t\t\tnUnique=len(df[item[0]].unique().tolist())\n\t\t\t\tif item[1] in self.pandasNumericDtypes:\n\t\t\t\t\tself.allNumberTypeCols.append(item[0])\n\t\t\t\t\tif nUnique >= categoricalMaxLabel:\n\t\t\t\t\t\tself.allNumCols.append(item[0]) #pure numerical\n\t\t\t\t\t\tif item[1] in ['int16', 'int32', 'int64']:\n\t\t\t\t\t\t\tself.numDiscreteCols.append(item[0])\n\t\t\t\t\t\telif item[1] in ['float16', 'float32', 'float64']:\n\t\t\t\t\t\t\tself.numContinuousCols.append(item[0])\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.allCatCols.append(item[0])\n\t\t\t\telif item[1] != 'bool':\t\t\n\t\t\t\t\tif (nUnique >= categoricalMaxLabel) and targetFeature != item[0]:\n\t\t\t\t\t\tself.textFtrs.append(item[0])\n\t\t\t\t\telse:\n\t\t\t\t\t\tcol = item[0]\n\t\t\t\t\t\tif (max(df[col", "instruction": "", "output": "" }, { "input": "].astype(str).str.split().str.len()) > 10) and targetFeature != item[0]:\n\t\t\t\t\t\t\tself.textFtrs.append(item[0])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.allCatCols.append(item[0])\n\t\t\t\telse:\n\t\t\t\t\tself.allCatCols.append(item[0])\n\t\t\tmisval_ratio = float(conf_json['misValueRatio'])\n\t\t\tself.configDict['misval_ratio'] = misval_ratio\n\t\t\tmissingCols, emptyCols = self.getMissingVals(df, dataCols, misval_ratio)\n\t\t\tif targetFeature in emptyCols:\n\t\t\t\t\traise Exception('Target column '+str(targetFeature)+' cannot be empty')\n\t\t\tdataCols = list(set(dataCols) - set(emptyCols))\t\n\t\t\tself.log.info('\\\\n---------- Dropping empty features ----------')\n\t\t\tfor empCol in emptyCols:\n\t\t\t\tself.log.info('-------> Drop Feature: '+empCol)\n\t\t\t\tdf = df.drop(columns=[empCol])\n\t\t\tself.log.info('---------- Dropping empty features End----------\\\\n')\n\t\t\tself.log.info('Status:- |... Empty feature treatment done: '+str(len(emptyCols))+' empty feature(s) found')\n\t\t\tself.log.info('-------> Data Frame Shape After Dropping (Rows,Columns): '+str(df.shape))\n\t\t\tself.allNumCols = list(set(self.allNumCols) - set(emptyCols))\n\t\t\tself.allCatCols = list(set(self.allCatCols) - set(emptyCols))\n\t\t\tself.textFtrs = list(set(self.textFtrs) - set(emptyCols))\n\t\t\tmissingValFtrs = list(set(missingCols) - set(emptyCols))\n\t\t\tself.log.info(str(len(missingValFtrs))+' feature(s) found with missing value(s)')\n\t\t\tself.log.info('\\\\n-------> Numerical continuous columns :'+(str(self.numContinuousCols))[:500])\n\t\t\tself.log.info('-------> Numerical discrete columns :'+(str(self.numDiscreteCols))[:500])\n\t\t\tself.log.info('-------> Non numerical columns :'+(str(self.allCatCols))[:500])\n\t\t\tself.log.info('-------> Text columns :'+(str(self.textFtrs))[:500])\n\t\texcept Exception as inst:\n\t\t\tself.log.info(\"Error in segregating numerical and categorical columns: \"+str(inst))\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\t\n\t\treturn df, missingValFtrs, emptyCols, dataCols, self.allNumCols, self.allCatCols, self.textFtrs\t\n\n\n\n\tdef createIncProfiler(self, df, conf_json, allNumCols, numFtrs, allCatCols, textFtrs, missingValFtrs):\n\t\tself.incLabelMapping = None\n\t\tcatFtrs = allCatCols.copy()\n\t\t#LabelEncoding\n\t\tif self.targetColumn in allCatCols:\n\t\t\tcatFtrs.remove(self.targetColumn)\n\t\t\tself.incLabelMapping = LabelEncoder()\n\t\t\tdf[self.targetColumn] = df[self.targetColumn].apply(str)\n\t\t\tself.incLabelMapping.fit(df[self.targetColumn])\n\t\t\tself.le_dict = dict(zip(self.incLabelMapping.classes_, self.incLabelMapping.transform(self.incLabelMapping.classes_)))\n\t\t\tself.log.info('----------> Encoded Values of Target Labels: '+(str(self.le_dict))[:500])\n\n\t\t#self.incFill --> {num_fill:SI/0.0/'drop', cat_fill:SI/0.0/'drop'}\n\t\t#fill\n\t\tself.incFill = {}\n\t\tself.incCatEncoder = None\n\t\tself.incScaler = None\n\t\tself.incOutlierRem = None\n\t\tnum_fill_method = 'Mean'\n\t\tfor x in list(conf_json['numericalFillMethod'].keys()):\n\t\t\tif conf_json['numericalFillMethod'][x] == 'True': \n\t\t\t\tnum_fill_method = x\n\t\t\t\tbreak \t\n\t\tif num_fill_method.lower() =='mean':\n\t\t\tnum_fill = [(col, stats.Mean()) for col in allNumCols]\n\t\t\tself.incFill['num_fill'] = StatImputer(*num_fill)\n\t\telif num_fill_method.lower() =='min':\n\t\t\tnum_fill = [(col, stats.Min()) for col in allNumCols]\n\t\t\tself.incFill['num_fill'] = StatImputer(*num_fill)\t\t\t\t\t\n\t\telif num_fill_method.lower() == 'max':\n\t\t\tnum_fill = [(col, stats.Max()) for col in allNumCols]\t\n\t\t\tself.incFill['num_fill'] = StatImputer(*num_fill)\t\n\t\telif num_fill_method.lower() =='zero':\n\t\t\tself.incFill['num_fill'] = 'zero'\t\t\t\t\n\t\telif num_fill_method.lower() =='drop':\n\t\t\tself.incFill['num_fill'] = 'drop'\n\t\telse:\n\t\t\tnum_fill = [(col, stats.Mean()) for col in allNumCols]\n\t\t\tself.incFill['num_fill'] = StatImputer(*num_fill)\n\t\t\t\n\t\tcat_fill_method = 'Mode'\n\t\tfor x in list(conf_json['categoricalFillMethod'].keys()):\n\t\t\tif conf_json['categoricalFillMethod'][x] == 'True': \n\t\t\t\tcat_fill_method = x\n\t\t\t\tbreak \n\t\tif cat_fill_method.lower() =='zero':\n\t\t\tself.incFill['cat_fill'] = 'zero'\n\t\telif cat_fill_method.lower() == 'mode':\n\t\t\tcat_fill = [(col, stats.Mode()) for col in allCatCols]\t\n\t\t\tself.incFill['cat_fill'] = StatImputer(*cat_fill)\t\t\t\t\t\n\t\telif cat_fill_method.lower() =='drop':\n\t\t\tself.incFill['cat_fill'] = 'drop'\n\n\t\t#CatEncoding\n\t\tfor x in list(conf_json['categoryEncoding'].keys()):\n\t\t\tif conf_json['categoryEncoding'][x] == 'True': \n\t\t\t\tcatEncoder = x\n\t\t\t\tbreak\n\t\tcatEncHow = 'Mean'\n\t\tfor x in list(conf_json['targetEncodingParams']['how'].keys()):\n\t\t\tif conf_json['targetEncodingParams']['how'][x] == 'True': \n\t\t\t\tcatEncHow = x\n\t\t\t\tbreak \n\t\tif self.targetColumn in catFtrs:\n\t\t\tcatFtrs.remove(self.targetColumn)\n\t\tif len(catFtrs) > 0:\n\t\t\tfrom river.feature_extraction import TargetAgg\n\t\t\tif catEncHow.lower() == 'mean':\n\t\t\t\tagg_stat = stats.Mean()\n\t\t\tif catEncHow.lower() == 'bayesianmean' or catEncHow.lower() == 'bayesian mean':\n\t\t\t\tagg_stat = stats.BayesianMean(prior=0.5, prior_weight=50)\n\t\t\tself.incCatEncoder = TargetAgg(\n\t\t\t\tby=catFtrs[0], how=agg_stat)\n\t\t\tfor col in catFtrs[1:]:\n\t\t\t\tself.incCatEncoder += TargetAgg(\n\t\t\t\tby=col, how=agg_stat)\n\t\t\tself.incCatEncoder|= compose.Discard(*catFtrs)\n\n\t\t#Scaling\n\t\tnormalization_status = 'False'\n\t\tnormalization_method = \"\"\n\t\tif 'normalization' in conf_json:\n\t\t\tnor_supported_methods = conf_json['normalization']\n\t\t\tfor k in nor_supported_methods.keys(): \n\t\t\t\tif conf_json['normalization'][k].lower() == 'true': \n\t\t\t\t\tnormalization_status='True'\n\t\t\t\t\tnormalization_method =k\n\t\t\t\t\tbreak\n\t\tif normalization_status.lower() == \"true\" and len(numFtrs) > 0:\n\t\t\tfrom sklearn.preprocessing import MinMaxScaler, StandardScaler, MaxAbsScaler\n\t\t\tif self.targetColumn in numFtrs:\n\t\t\t\tnumFtrs.remove(self.targetColumn)\n\t\t\tif normalization_method.lower() =='standardscaler':\n\t\t\t\tself.incScaler = StandardScaler()\n\t\t\telif normalization_method.lower() =='minmaxscaler' or normalization_method.lower() =='minmax':\n\t\t\t\tself.incScaler = MinMaxScaler()\n\t\t\telif normalization_method.lower() =='maxabsscaler' or normalization_method.lower() =='maxabs':\n\t\t\t\tself.incScaler = MaxAbsScaler()\n\t\t\telse:\n\t\t\t\tself.incScaler = None\n\n\t\t#OutlierRemoval\n\t\t\toutlier_status = 'False'\n\t\t\toutlier_method = 'None'\n\t\t\tfor x in list(conf_json['outlierDetection'].keys()): \n\t\t\t\tif conf_json['outlierDetection'][x] == 'True': \n\t\t\t\t\toutlier_method = x\n\t\t\t\t\toutlier_status = 'True'\n\t\t\t\t\tbreak\n\t\t\tif outlier_status and numFtrs:\n\t\t\t\toutlierMethodNames = list(conf_json['outlierDetectionParams'].keys())\n\t\t\t\tif outlier_method.lower() == 'oneclasssvm' or outlier_method.lower() == 'one class svm':\n\t\t\t\t\tfor x in outlierMethodNames:\n\t\t\t\t\t\tif x[0].lower() == 'o':\n\t\t\t\t\t\t\tkey = x\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tparams = conf_json['outlierDetectionParams'][key]\n\t\t\t\t\tself.log.info('<--- one class SVM with quantile filter --->')\n\t\t\t\t\tself.incOutlierRem = anomaly.QuantileFilter(anomaly.OneClassSVM(nu=float(params['nu'])),q=float(params['q']))\n\t\t\t\telif outlier_method.lower() =='halfspacetrees' or outlier_method.lower() =='half space trees':\n\t\t\t\t\tfor x in outlierMethodNames:\n\t\t\t\t\t\tif x[0].lower() == 'h':\n\t\t\t\t\t\t\tkey = x\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tparams = conf_json['outlierDetectionParams'][key]\n\t\t\t\t\tself.log.info('<--- Half space trees with quantile filter --->')\n\t\t\t\t\tself.incOutlierRem = anomaly.QuantileFilter(anomaly.HalfSpaceTrees(n_trees=int(params['n_trees']),height=int(params['height']), window_size=int(params['window_size'])) ,q=float(params['q']))\n\t\t\t\telse:\n\t\t\t\t\tself.log.info(\"No method is provided for outlier analysis\")\n\n\n\n\tdef getMissingVals(self,dataframe,columns,misval_ratio):\n\t\ttry:\n\t\t\tself.log.info( '\\\\n----------- Detecting for Missing Values -----------')\n\t\t\tnonNAArray=[]\n\t\t\tnumOfRows = dataframe.shape[0]\n\t\t\tfor i in columns:\n\t\t\t\tnumNa=dataframe.loc[(pd.isna(dataframe[i])),i ].shape[0]\n\t\t\t\tnonNAArray.append(tuple([i,numNa]))\n\t\t\tfor item in nonNAArray:\n\t\t\t\tnumofMissingVals = item[1]\n\t\t\t\tif(numofMissingVals !=0):\n\t\t\t\t\tself.log.info('-------> Feature '+str(item[0]))\n\t\t\t\t\tself.log.info('----------> Number of Empty Rows '+str(numofMissingVals))\n\t\t\t\t\tself.missingCols.append(item[0])\n\t\t\t\t\t\n\t\t\t\tif(numofMissingVals >= numOfRows * misval_ratio):\n\t\t\t\t\tself.log.info('----------> Empty: Yes')\n\t\t\t\t\tself.log.info('----------> Permitted Rows: '+str(int(numOfRows * misval_ratio)))\n\t\t\t\t\tself.emptyCols.append(item[0])\n\t\t\tif(len(self.missingCols) !=0):\n\t\t\t\tself.log.info( '----------- Detecting for Missing Values End -----------\\\\n')\n\t\t\t\treturn self.missingCols, self.emptyCols\n\t\t\telse:\n\t\t\t\tself.log.info( '-------> Missing Value Features :Not Any')\n\t\t\t\tself.log.info( '----------- Detecting for Missing Values End -----------\\\\n')\n\t\t\t\treturn self.missingCols, self.emptyCols\n\t\texcept Exception as e:\n\t\t\tself.log.info(\"getMissingVals failed ==>\" +str(e))\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\treturn None, None\n\n\n\tdef startIncProfiler(self,df,conf_json,targetFeature,deployLocation,problemType):\n\t\ttry:\n\t\t\tself.targetColumn = targetFeature\t\t \n\t\t\tdf, missingValFtrs, emptyFtrs, dataFtrs, allNumCols, allCatCols, textFtrs = self.featureAnalysis(df, conf_json, self.targetColumn)\n\t\t\tif len(textFtrs)>0:\n\t\t\t\tself.log.info('Text Features are not supported. Dropping '+str(textFtrs)[:500])\n\t\t\t\tdf = df.drop(columns=textFtrs)\n\t\t\tcatFtrs = allCatCols.copy()\n\t\t\tnumFtrs = allNumCols.copy()\n\t\t\tif self.targetColumn in catFtrs:\n\t\t\t\tcatFtrs.remove(self.targetColumn)\n\n\t\t\tif targetFeature in allNumCols:\n\t\t\t\tnumFtrs.remove(targetFeature)\n\n\t\t\tself.configDict['targetCol'] = self.targetColumn\n\t\t\tself.configDict['numFtrs'] = numFtrs\n\t\t\tself.configDict['catFtrs'] = catFtrs\n\t\t\tself.configDict['allNumCols'] = allNumCols\n\t\t\tself.configDict['allCatCols'] = allCatCols\n\t\t\tself.configDict['allFtrs'] = numFtrs+catFtrs\n", "instruction": "", "output": "" }, { "input": "\n\n\t\t\ttry:\n\t\t\t\tself.log.info('\\\\n---------- Creating Incremental profiler models ----------') \n\t\t\t\tself.createIncProfiler(df, conf_json, allNumCols, numFtrs, allCatCols, textFtrs, missingValFtrs)\n\t\t\t\tself.log.info('\\\\n--------- Incremental profiler models have been created ---------')\n\t\t\texcept Exception as inst:\n\t\t\t\tself.log.info(\"Error in creating Incremental profiler models\"+str(inst))\n\t\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\t\traise\n\n\t\t\ttry:\n\t\t\t\t#mvt\n\t\t\t\t# if missingValFtrs:\n\t\t\t\tif self.incFill['num_fill'] == 'drop':\n\t\t\t\t\tdf = df.dropna(axis = 0, subset=allNumCols)\n\t\t\t\t\tself.configDict['num_fill'] = 'drop'\n\t\t\t\telif self.incFill['num_fill'] == 'zero':\n\t\t\t\t\tdf[allNumCols] = df[allNumCols].fillna(value = 0.0)\n\t\t\t\t\tself.configDict['num_fill'] = 'zero'\n\t\t\t\telse:\n\t\t\t\t\tdf = df.astype(object).where(df.notna(), None)\n\t\t\t\t\tdf[allNumCols]= df[allNumCols].apply(lambda row: self.apply_river_model(row.to_dict(), self.incFill\n\t\t\t\t\t['num_fill']), axis='columns')\n\t\t\t\t\tself.configDict['num_fill'] = {col:self.incFill['num_fill'].stats[col].get() for col in allNumCols}\n\t\t\t\t\n\t\t\t\tif self.incFill['cat_fill'] == 'drop':\n\t\t\t\t\tdf = df.dropna(axis = 0, subset=allCatCols)\n\t\t\t\t\tself.configDict['cat_fill'] = 'drop'\n\t\t\t\telif self.incFill['cat_fill'] == 'zero':\n\t\t\t\t\t\tdf[allCatCols] = df[allCatCols].fillna(value = 0.0)\n\t\t\t\t\t\tself.configDict['cat_fill'] = 'zero'\n\t\t\t\telse:\n\t\t\t\t\tdf = df.astype(object).where(df.notna(), None)\n\t\t\t\t\tdf[allCatCols]= df[allCatCols].apply(lambda row: self.apply_river_model(row.to_dict(), self.incFill['cat_fill']), axis='columns')\n\t\t\t\t\tself.configDict['cat_fill'] = {col:self.incFill['cat_fill'].stats[col].get() for col in allCatCols}\n\n\t\t\t\tself.log.info('\\\\nStatus:- |... Missing value treatment done')\n\t\t\texcept Exception as inst:\n\t\t\t\tself.log.info(\"Error in Missing value treatment \"+str(inst))\n\t\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\t\traise\n\n\t\t\ttry:\n\t\t\t\t#labelenc\n\t\t\t\tif self.incLabelMapping:\n\t\t\t\t\tdf[targetFeature] = self.incLabelMapping.transform(df[targetFeature])\n\t\t\t\t\t# self.configDict['labelMapping'] = self.le_dict\n\t\t\texcept Exception as inst:\n\t\t\t\tself.log.info(\"Error in Label mapping \"+str(inst))\n\t\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\t\traise\n\n\t\t\ttry:\n\t\t\t\t#catenc\n\t\t\t\tif self.incCatEncoder:\n\t\t\t\t\tself.log.info('\\\\n--------- Converting Non Numerical Categorical Features to Numerical Features ---------')\n\t\t\t\t\tself.encTarget = targetFeature\n\t\t\t\t\tif problemType.lower() == 'regression':\n\t\t\t\t\t\tfrom sklearn.preprocessing import StandardScaler\n\t\t\t\t\t\tsc = StandardScaler()\n\t\t\t\t\t\tself.encTarget = 'scaledTarget'\n\t\t\t\t\t\tdf['scaledTarget'] = sc.fit_transform(df[targetFeature].to_numpy().reshape(-1,1))\n\t\t\t\t\tencCols = catFtrs.copy()\n\t\t\t\t\tencCols.append(self.encTarget)\n\t\t\t\t\tself.configDict['encCols'] = encCols\n\t\t\t\t\tself.configDict['encTarget'] = self.encTarget\n\t\t\t\t\ttransformed_data = df[encCols].apply(lambda row: self.apply_enc(row.to_dict()), axis='columns')\t\t\t\n\t\t\t\t\tif targetFeature in transformed_data.columns:\n\t\t\t\t\t\ttransformed_data.drop(targetFeature, inplace=True, axis = 1)\n\t\t\t\t\tif problemType.lower() == 'regression':\n\t\t\t\t\t\tdf.drop('scaledTarget', inplace=True, axis = 1)\n\t\t\t\t\tdf[catFtrs] = transformed_data\n\t\t\t\t\t# self.log.info('Status:- |... Target Encoding state is as follows: ')\n\t\t\t\t\tself.configDict['catEnc'] = []\n\t\t\t\t\tif len(catFtrs) == 1:\n\t\t\t\t\t\tcol = catFtrs[0]\n\t\t\t\t\t\tself.configDict['catEnc'].append({col:self.incCatEncoder['TargetAgg'].state.to_dict()})\n\t\t\t\t\telse:\n\t\t\t\t\t\tfor i, col in enumerate(catFtrs):\n\t\t\t\t\t\t\tif i==0:\n\t\t\t\t\t\t\t\tno = ''\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tno = str(i)\n\t\t\t\t\t\t\tself.configDict['catEnc'].append({col:self.incCatEncoder['TransformerUnion']['TargetAgg'+no].state.to_dict()})\t\t\t\t\t\t\n\t\t\t\t\t# print(self.incCatEncoder['TransformerUnion']['TargetAgg'].state)\n\t\t\t\t\t# self.log.info(self.incCatEncoder)\n\t\t\t\t\tself.log.info('Status:- |... Categorical to numeric feature conversion done: '+str(len(catFtrs))+' features converted') \n\n\t\t\texcept Exception as inst:\n\t\t\t\tself.log.info(\"Error in categorical encoding \"+str(inst))\n\t\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\t\traise\n\n\t\t\ttry:\n\t\t\t\t#scaler\n\t\t\t\tif self.incScaler:\n\t\t\t\t\tself.log.info(\"\\\\n---------- Data Normalization has started ----------\")\n\t\t\t\t\tself.incScaler = self.incScaler.partial_fit(df[numFtrs])\n\t\t\t\t\tdf[numFtrs] = self.incScaler.transform(df[numFtrs])\n\t\t\t\t\tself.log.info( \"---------- Normalization Done on Following features ----------\")\n\t\t\t\t\tself.log.info(numFtrs)\n\t\t\t\t\tself.log.info('Status:- |... Normalization treatment done')\n\t\t\texcept Exception as inst:\n\t\t\t\tself.log.info(\"Error in normalization \"+str(inst))\n\t\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\t\traise\n\t\t\t\t\n\t\t\ttry:\n\t\t\t\t#outlierrem\n\t\t\t\tif self.incOutlierRem:\n\t\t\t\t\tself.log.info('\\\\n---------- Performing outlier analysis ----------')\n\t\t\t\t\tdf = df[df[numFtrs].apply(lambda x: False if self.apply_od_pipe(x.to_dict()) else True, axis=1)]\n\t\t\t\t\tself.log.info('\\\\n <--- dataframe after outlier analysis --->')\n\t\t\t\t\tdf.reset_index(drop=True, inplace=True) \n\t\t\t\t\tself.log.info(df.head(5))\n\t\t\t\t\tself.log.info('Status:- |... Outlier treatment done')\n\t\t\t\t\tself.log.info('\\\\n <--- shape of dataframe after outlier analysis --->')\n\t\t\t\t\tself.log.info(df.shape) \n\t\t\texcept Exception as inst:\n\t\t\t\tself.log.info(\"Error in outlier treatment \"+str(inst))\n\t\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\t\traise\n\n\t\t\t#saveprofiler\n\t\t\tself.log.info('\\\\n---------- Saving profiler models ----------')\n\t\t\tself.saveProfilerModels(deployLocation)\t\n\t\t\tself.log.info('<--- Profiler models saved at '+deployLocation+' --->')\n\t\t\treturn df,targetFeature,missingValFtrs,numFtrs,catFtrs,self.le_dict,self.configDict,textFtrs,emptyFtrs,self.wordToNumericFeatures\n\t\texcept Exception as inst:\n\t\t\tself.log.info(\"Error: dataProfiler failed \"+str(inst))\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\n\n\tdef transformData(self, df, targetFeature, missingValFtrs,numFtrs, catFtrs, textFtrs):\n\t\ttry:\n\t\t\tdf = df.drop_duplicates(keep=\"first\")\n\t\t\tdf = df.reset_index(drop=True)\n\t\t\tdf = df.replace('-', np.nan)\n\t\t\tdf = df.replace('?', np.nan)\n\t\t\ttext_mv_cols = list(set(missingValFtrs).intersection(set(textFtrs)))\n\t\t\tif len(text_mv_cols)>0:\n\t\t\t\tdf[text_mv_cols] = df[text_mv_cols].fillna(value = 'NA')\n\t\t\tif 'num_fill' in self.configDict:\n\t\t\t\tif self.configDict['num_fill'] == 'drop':\n\t\t\t\t\t\tdf = df.dropna(axis = 0, subset=self.allNumCols)\n\t\t\t\telif self.configDict['num_fill'] == 'zero':\n\t\t\t\t\t\tdf[self.allNumCols] = df[self.allNumCols].fillna(value = 0.0)\n\t\t\t\telse:\n\t\t\t\t\tfor x in self.allNumCols:\n\t\t\t\t\t\tdf[x] = df[x].fillna(value = self.configDict['num_fill'][x])\n\t\t\tif 'cat_fill' in self.configDict:\n\t\t\t\tif self.configDict['cat_fill'] == 'drop':\n\t\t\t\t\tdf = df.dropna(axis = 0, subset=self.allCatCols)\n\t\t\t\telif self.configDict['cat_fill'] == 'zero':\n\t\t\t\t\t\tdf[self.allCatCols] = df[self.allCatCols].fillna(value = 0.0)\n\t\t\t\telse:\n\t\t\t\t\tfor x in self.allCatCols:\n\t\t\t\t\t\tdf[x] = df[x].fillna(value = self.configDict['cat_fill'][x])\n\n\t\t\tif self.incLabelMapping:\n\t\t\t\t\tdf[targetFeature] = self.incLabelMapping.transform(df[targetFeature])\n\n\t\t\tif self.incCatEncoder:\n\t\t\t\ttransformed_data = df[catFtrs].apply(lambda row: self.apply_enc(row.to_dict(), isTrain=False), axis='columns')\n\t\t\t\tdf[catFtrs] = transformed_data\n\n\t\t\tif self.incScaler:\n\t\t\t\tdf[numFtrs] = self.incScaler.transform(df[numFtrs])\n\n\t\t\treturn df\n\t\texcept Exception as inst:\n\t\t\tself.log.info(\"Error: DataProfiling transformation failed \"+str(inst))\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\n\t\n\tdef checknumStr(self,dataframe,feature):\n\t\ttry:\n\t\t\tdataframe[feature]=dataframe[feature].apply(lambda x: self.testStr(x))\n\t\t\treturn dataframe\n\t\texcept:\n\t\t\tself.log.info(\"checknumStr failed\")\n\t\t\treturn dataframe\n\t\t\t\n\t#test whether the value is numeric /string\t\t\t\n\tdef testStr(self,value):\n\t\ttry:\n\t\t\tx=eval(value)\n\t\t\treturn np.nan\n\t\texcept:\n\t\t\treturn value\n\t\t\t\n\t\"\"\"\n\tMissing values analysis\n\tDetects number of missing values in each column of dataframe\n\t\"\"\"\n\tdef checksRows(self,dataframe,target_column,dataColumns):\n\t\tself.log.info( '\\\\n----------- Checking Target Feature Empty Rows -----------')\n\t\tif self.targetColumn != '':\n\t\t\tnumNa=dataframe.loc[(pd.isna(dataframe[self.targetColumn])),self.targetColumn].shape[0]\n\t\t\tself.log.info('------->No of Empty Rows in Target Fields: '+str(numNa))\n\t\t\tif numNa >0:\n\t\t\t\tself.log.info('-------> Remove Empty Target Field Rows')\n\t\t\t\tdataframe = dataframe.dropna(axis=0, subset=[self.targetColumn])\n\t\tself.log.info('", "instruction": "", "output": "" }, { "input": "-------> Remove Duplicate Rows')\n\t\tdataframe = dataframe.dropna(axis=0,how='all',subset=dataColumns)\n\t\tnoofdplicaterows = dataframe.duplicated(keep='first').sum()\n\t\tdataframe = dataframe.drop_duplicates(keep=\"first\")\n\t\tdataframe = dataframe.reset_index(dr", "instruction": "", "output": "" }, { "input": "cmd):\n try:\n subprocess.check_output(cmd, stderr=subprocess.PIPE)\n except subprocess.CalledProcessError as e:\n if e.stderr:\n if isinstance(e.stderr, bytes):\n err_msg = e.stderr.decode(sys.getfilesystemencoding())\n else:\n err_msg = e.stderr\n elif e.output:\n if isinstance(e.output, bytes):\n err_msg = e.output.decode(sys.getfilesystemencoding())\n else:\n err_msg = e.output\n else:\n err_msg = str(e)\n return False, err_msg\n return True, \"\"\n\ndef validate_config(config):\n non_null_keys = ['url','username', 'token', 'location', 'gitFolderLocation', 'email', 'modelName']\n missing_keys = [k for k in non_null_keys if k not in config.keys()]\n if missing_keys:\n raise ValueError(f\"following fields are missing in config file: {missing_keys}\")\n for k,v in config.items():\n if k in non_null_keys and not v:\n raise ValueError(f\"Please provide value for '{k}' in config file.\")\n\ndef upload(config): \n \n validate_config(config)\n url_type = config.get('url_type','https')\n if url_type == 'https':\n https_str = \"https://\"\n url = https_str + config['username'] + \":\" + config['token'] + \"@\" + config['url'][len(https_str):]\n else:\n url = config['url']\n model_location = Path(config['location'])\n git_folder_location = Path(config['gitFolderLocation'])\n git_folder_location.mkdir(parents=True, exist_ok=True)\n (git_folder_location/'.github'/'workflows').mkdir(parents=True, exist_ok=True)\n if not model_location.exists():\n raise ValueError('Trained model data not found')\n\n os.chdir(str(git_folder_location))\n (git_folder_location/config['modelName']).mkdir(parents=True, exist_ok=True)\n shutil.copytree(model_location, git_folder_location/config['modelName'], dirs_exist_ok=True)\n create_and_save_yaml((git_folder_location/'.github'/'workflows'), config['modelName'],config['location']) \n if (Path(git_folder_location)/'.git').exists():\n first_upload = False\n else:\n first_upload = True\n if first_upload:\n cmd = ['git','init']\n status, msg = run_cmd(cmd)\n if not status:\n raise ValueError(msg)\n\n cmd = ['git','config','user.name',config['username']]\n status, msg = run_cmd(cmd)\n if not status:\n raise ValueError(msg)\n\n cmd = ['git','config','user.email',config['email']]\n status, msg = run_cmd(cmd)\n if not status:\n raise ValueError(msg)\n \n cmd = ['git','add', '-A']\n status, msg = run_cmd(cmd)\n if not status:\n raise ValueError(msg)\n\n cmd = ['git','commit','-m',f\"commit {config['modelName']}\"]\n status, msg = run_cmd(cmd)\n if not status:\n raise ValueError(msg)\n\n cmd = ['git','branch','-M','main']\n status, msg = run_cmd(cmd)\n if not status:\n raise ValueError(msg)\n\n if first_upload:\n cmd = ['git','remote','add','origin', url]\n status, msg = run_cmd(cmd)\n if not status:\n raise ValueError(msg)\n\n cmd = ['git','push','-f','-u','origin', 'main']\n status, msg = run_cmd(cmd)\n if not status:\n raise ValueError(msg)\n else:\n cmd = ['git','push']\n status, msg = run_cmd(cmd)\n if not status:\n raise ValueError(msg)\n \n return json.dumps({'Status':'SUCCESS'})\n \nif __name__ == '__main__': \n try: \n if shutil.which('git') is None:\n raise ValueError(\"git is not installed on this system\")\n parser = argparse.ArgumentParser() \n parser.add_argument('-c', '--config', help='Config file location or as a string')\n\n args = parser.parse_args() \n if Path(args.config).is_file() and Path(args.config).suffix == '.json': \n with open(args.config,'r') as f: \n config = json.load(f) \n else: \n config = json.loads(args.config) \n print(upload(config))\n except Exception as e: \n status = {'Status':'Failure','msg':str(e)} \n print(json.dumps(status)) import os\nimport shutil \nimport sys\nimport subprocess\nfrom os.path import expanduser \nimport platform\nimport json\n\ndef createDockerImage(model_name,model_version,module,folderpath):\n\tcommand = 'docker pull python:3.8-slim-buster'\n\tos.system(command);\n\tsubprocess.check_call([\"docker\", \"build\", \"-t\",module+'_'+model_name.lower()+\":\"+model_version,\".\"], cwd=folderpath) \n\t\ndef local_docker_build(config):\n\tprint(config)\n\tconfig = json.loads(config)\n\tmodel_name = config['usecase']\n\tmodel_version = config['version']\n\tmlaac__code_path = config['mlacPath'] \n\tdocker_images = {}\n\tdocker_images['ModelMonitoring'] = 'modelmonitoring'+'_'+model_name.lower()+':'+model_version\n\tdataset_addr = os.path.join(mlaac__code_path,'ModelMonitoring')\n\tcreateDockerImage(model_name,model_version,'modelmonitoring',dataset_addr)\n\tdocker_images['DataIngestion'] = 'dataingestion'+'_'+model_name.lower()+':'+model_version\n\tdataset_addr = os.path.join(mlaac__code_path,'DataIngestion')\n\tcreateDockerImage(model_name,model_version,'dataingestion',dataset_addr)\n\ttransformer_addr = os.path.join(mlaac__code_path,'DataTransformation')\n\tdocker_images['DataTransformation'] = 'datatransformation'+'_'+model_name.lower()+':'+model_version\n\tcreateDockerImage(model_name,model_version,'datatransformation',transformer_addr)\n\tfeatureengineering_addr = os.path.join(mlaac__code_path,'FeatureEngineering')\n\tdocker_images['FeatureEngineering'] = 'featureengineering'+'_'+model_name.lower()+':'+model_version\n\tcreateDockerImage(model_name,model_version,'featureengineering',featureengineering_addr)\n\tfrom os import listdir\n\tarr = [filename for filename in os.listdir(mlaac__code_path) if filename.startswith(\"ModelTraining\")]\t\n\tdocker_training_images = []\n\tfor x in arr:\n\t\tdockertraing={}\n\t\tdockertraing['Training'] = str(x).lower()+'_'+model_name.lower()+':'+model_version\n\t\tdocker_training_images.append(dockertraing)\n\t\ttraining_addri = os.path.join(mlaac__code_path,x)\n\t\tcreateDockerImage(model_name,model_version,str(x).lower(),training_addri)\n\tdocker_images['ModelTraining'] = docker_training_images\n\tdocker_images['ModelRegistry'] = 'modelregistry'+'_'+model_name.lower()+':'+model_version\n\tdeploy_addr = os.path.join(mlaac__code_path,'ModelRegistry')\n\tcreateDockerImage(model_name,model_version,'modelregistry',deploy_addr)\t\n\tdocker_images['ModelServing'] = 'modelserving'+'_'+model_name.lower()+':'+model_version\n\tdeploy_addr = os.path.join(mlaac__code_path,'ModelServing')\n\tcreateDockerImage(model_name,model_version,'modelserving',deploy_addr)\n\toutputjsonFile = os.path.join(mlaac__code_path,'dockerlist.json')\n\twith open(outputjsonFile, 'w') as f:\n\t\tjson.dump(docker_images, f)\n\tf.close()\n\toutput = {'Status':'Success','Msg':outputjsonFile}\n\toutput = json.dumps(output)\n\tprint(\"aion_build_container:\",output) import docker\nimport json\nimport logging\ndef read_json(file_path): \n\tdata = None \n\twith open(file_path,'r') as f: \n\t\tdata = json.load(f) \n\treturn data\n\ndef run_pipeline(inputconfig):\t\n\tinputconfig = json.loads(inputconfig)\n\tlogfilepath = inputconfig['logfilepath']\n\tlogging.basicConfig(level=logging.INFO,filename =logfilepath)\t\t\n\tusecasename = inputconfig['usecase']\n\tlogging.info(\"UseCaseName :\"+str(usecasename))\n\tversion = inputconfig['version']\n\tlogging.info(\"version :\"+str(version))\n\tconfig = inputconfig['dockerlist'] \n\tpersistancevolume = inputconfig['persistancevolume']\n\tlogging.info(\"PersistanceVolume :\"+str(persistancevolume))\n\tdatasetpath = inputconfig['datasetpath'] \n\tlogging.info(\"DataSet Path :\"+str(datasetpath))\n\tconfig = read_json(config) \n\tclient = docker.from_env()\n\tinputconfig = {'modelName':usecasename,'modelVersion':str(version),'dataLocation':datasetpath}\n\tinputconfig = json.dumps(inputconfig)\t\t\t\t\t \n\tinputconfig = inputconfig.replace('\"', '\\\\\\\\\"')\n\tlogging.info(\"===== Model Monitoring Container Start =====\")\n\toutputStr = client.containers.run(config['ModelMonitoring'],'python code.py -i'+datasetpath,volumes=[persistancevolume+':/aion'])\n\toutputStr = outputStr.decode('utf-8')\n\tlogging.info('ModelMonitoring: '+str(outputStr))\n\tprint('ModelMonitoring: '+str(outputStr))\n\tlogging.info(\"===== ModelMonitoring Stop =====\")\n\tlogging.info(\"===== Data Ingestion Container Start =====\")\n\toutputStr = client.containers.run(config['DataIngestion'],'python code.py',volumes=[persistancevolume+':/aion'])\n\toutputStr = outputStr.decode('utf-8')\n\tlogging.info('DataIngestion: '+str(outputStr))\n\tprint('DataIngestion: '+str(outputStr))\n\tlogging.info(\"===== Data Ingestion Container Stop =====\")\n\toutputStr = outputStr.strip()\n\tdecoded_data = json.loads(outputStr)\n\tstatus = decoded_data['Status']\n\tif status != 'Success':\n\t\toutput = {'Status':'Error','Msg':'Data Ingestion Fails'}\n\tlogging.info(\"===== Transformation Container Start =====\")\n\toutputStr = client.containers.run(config['DataTransformation'],'python code.py',volumes=[persistancevolume+':/aion'])\t\n\toutputStr = outputStr.decode('utf-8')\n\tlogging.info('Data Transformations: '+str(outputStr))\n\tprint('Data Transformations: '+str(outputStr))\n\tlogging.info(\"===== Transformation Container Done =====\")\n\toutputStr = outputStr.strip()\n\tdecoded_data = json.loads(outputStr)\n\tstatus = decoded_data['Status']\n\tif status != 'Success':\n\t\toutput = {'Status':'Error','Msg':'Data Transformations Fails'}\n\tlogging.info(\"===== Feature Engineering Container Start =====\")\n\toutputStr = client.containers.run(config['FeatureEngineering'],'python code.py',volumes=[persistancevolume+':/aion'])\t\n\toutputStr = outputStr.decode('utf-8')\n\tlogging.info('FeatureEngineering: '+str(outputStr))\n\tprint('FeatureEngineering: '+str(outputStr))\t\n\tlogging.info(\"===== Feature Engineering Container Done =====\")\n\toutputStr = outputStr.strip()\n\tdecoded_data = json.loads(outputStr)\n\tstatus = decoded_data['Status']\n\tmodeltraining = config['ModelTraining'] \n\tfor mt in modeltraining:\n\t\tlogging.info(\"===== Training Container Start =====\")\n\t\toutputStr = client.containers.run(mt['Training'],'python code.py',volumes=[persistancevolume+':/aion'])\n\t\toutputStr = outputStr.decode('utf-8')\n\t\tlogging.info('ModelTraining: '+str(outputStr))\n\t\tprint('ModelTraining: '+str(outputStr))\t\t\t\n\t\tlogging.info(\"===== Training Container Done =====\")\n\t\toutputStr = outputStr.strip()\n\t\ttry:\n\t\t\tdecoded_data = json.loads(outputStr)\n\t\t\tstatus = decoded_data['Status']\n\t\texcept Exception as inst:\n\t\t\tlogging.info(inst)\n\tlogging.info(\"===== Model Registry Start =====\")\t\t\n\toutputStr = client.containers.run(config['ModelRegistry'],'python code.py',volumes=[persistancevolume+':/aion'])\n\toutputStr = outputStr.decode('utf-8')\n\tlogging.info('ModelRegistry: '+str(outputStr))\n\tprint('ModelRegistry: '+str(outputStr))\n\tlogging.info(\"===== ModelRegistry Done =====\")\t\t\n\tlogging.info(\"===== ModelServing Start =====\")\t\t\n\toutputStr = client.containers.run(config['ModelServing'],'python code.py',volumes=[persistancevolume+':/aion'])\n\toutputStr = outputStr.decode('utf-8')\n\tlogging.info('Prediction: '+str(outputStr))\n\tprint('Prediction: '+str(outputStr))\n\tlogging.info(\"===== ModelServing Done =====\")\t\t\t '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n''' from kafka import KafkaConsumer\nfrom json import loads\nimport pandas as pd\nimport json\nimport os,sys\nimport time\nimport multiprocessing\nfrom os.path import expanduser\nimport platform\nimport datetime\nmodelDetails = {}\nclass Process(multiprocessing.Process):\n def __init__(self, modelSignature,jsonData,predictedData,modelpath):\n super(Process, self).__init__()\n self.config = jsonData\n self.modelSignature = modelSignature\n self.data = predictedData\n self.modelpath = modelpath\n def run(self):\n #data = pd.json_normalize(self.data)\n minotoringService = self.config['minotoringService']['url']\n trainingdatalocation = self.config['trainingDataLocation'][self.modelSignature]\n #filetimestamp = 'AION_'+str(int(time.time()))+'.csv'\n #data.to_csv(dataFile, index=False)\n inputFieldsJson = {\"trainingDataLocation\":trainingdatalocation,\"currentDataLocation\":self.data}\n inputFieldsJson = json.dumps(inputFieldsJson)\n ser_url = minotoringService+self.modelSignature+'/monitoring'\n driftTime = datetime.datetime.now()\n import requests\n try:\n ", "instruction": "", "output": "" }, { "input": "response = requests.post(ser_url, data=inputFieldsJson,headers={\"Content-Type\":\"application/json\",})\n outputStr=response.content\n outputStr = outputStr.decode('utf-8')\n outputStr = outputStr.strip()\n decoded_data = json.loads(outputStr)\n print(decoded_data)\n status = decoded_data['status']\n msg = decoded_data['data']\n except Exception as inst:\n if 'Failed to establish a new connection' in str(inst):\n status = 'Fail'\n msg = 'AION Service needs to be started'\n else:\n status = 'Fail'\n msg = 'Error during Drift Analysis'\n statusFile = os.path.join(self.modelpath,self.modelSignature+'_status.csv')\n df = pd.DataFrame(columns = ['dateTime', 'status', 'msg'])\n df = df.append({'dateTime' : driftTime, 'status' : status, 'msg' : msg},ignore_index = True)\n \n print(df)\n if (os.path.exists(statusFile)):\n df.to_csv(statusFile, mode='a', header=False,index=False)\n else:\n df.to_csv(statusFile, header=True,index=False)\n \n \n \n \ndef launch_kafka_consumer():\n from appbe.dataPath import DATA_DIR \n configfile = os.path.join(os.path.dirname(__file__),'..','config','kafkaConfig.conf')\n with open(configfile,'r',encoding='utf-8') as f:\n jsonData = json.load(f)\n f.close()\n kafkaIP=jsonData['kafkaCluster']['ip']\n kafkaport = jsonData['kafkaCluster']['port']\n topic = jsonData['kafkaCluster']['topic']\n kafkaurl = kafkaIP+':'+kafkaport\n if jsonData['database']['csv'] == 'True':\n database = 'csv'\n elif jsonData['database']['mySql'] == 'True':\n database = 'mySql'\n else:\n database = 'csv'\n kafkaPath = os.path.join(DATA_DIR,'kafka')\n if not (os.path.exists(kafkaPath)): \n try:\n os.makedirs(kafkaPath)\n except OSError as e:\n pass\n consumer = KafkaConsumer(topic,bootstrap_servers=[kafkaurl],auto_offset_reset='earliest',enable_auto_commit=True,group_id='my-group',value_deserializer=lambda x: loads(x.decode('utf-8')))\n for message in consumer:\n message = message.value\n data = message['data']\n data = pd.json_normalize(data)\n modelname = message['usecasename']\n version = message['version']\n modelSignature = modelname+'_'+str(version)\n modelpath = os.path.join(kafkaPath,modelSignature)\n try:\n os.makedirs(modelpath)\n except OSError as e:\n pass\n secondsSinceEpoch = time.time()\n if modelSignature not in modelDetails:\n modelDetails[modelSignature] = {}\n modelDetails[modelSignature]['startTime'] = secondsSinceEpoch \n if database == 'csv':\n csvfile = os.path.join(modelpath,modelSignature+'.csv')\n if (os.path.exists(csvfile)):\n data.to_csv(csvfile, mode='a', header=False,index=False)\n else:\n data.to_csv(csvfile, header=True,index=False)\n modelTimeFrame = jsonData['timeFrame'][modelSignature]\n currentseconds = time.time()\n print(currentseconds - modelDetails[modelSignature]['startTime'])\n if (currentseconds - modelDetails[modelSignature]['startTime']) >= float(modelTimeFrame):\n csv_path = os.path.join(modelpath,modelSignature+'.csv')\n #predictedData = pd.read_csv(csv_path) \n ##predictedData = predictedData.to_json(orient=\"records\")\n index = Process(modelSignature,jsonData,csv_path,modelpath)\n index.start()\n modelDetails[modelSignature]['startTime'] = secondsSinceEpoch \n \n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport pandas as pd\nimport logging\nimport numpy as np\nimport sys\nfrom pathlib import Path\nimport nltk\nfrom nltk.tokenize import sent_tokenize\nfrom nltk import pos_tag\nfrom nltk import ngrams\nfrom nltk.corpus import wordnet\nfrom nltk import RegexpParser\nfrom textblob import TextBlob\nimport spacy\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.base import BaseEstimator, TransformerMixin\nimport urllib.request\nimport zipfile\nimport os\nfrom os.path import expanduser\nimport platform\n\nfrom text import TextCleaning as text_cleaner\nfrom text.Embedding import extractFeatureUsingPreTrainedModel\n\nlogEnabled = False\nspacy_nlp = None\n \ndef ExtractFeatureCountVectors(ngram_range=(1, 1),\n max_df=1.0,\n min_df=1,\n max_features=None,\n binary=False):\n vectorizer = CountVectorizer(ngram_range = ngram_range, max_df = max_df, \\\\\n min_df = min_df, max_features = max_features, binary = binary)\n return vectorizer \n\ndef ExtractFeatureTfIdfVectors(ngram_range=(1, 1), \n max_df=1.0, \n min_df=1, \n max_features=None,\n binary=False,\n norm='l2',\n use_idf=True,\n smooth_idf=True,\n sublinear_tf=False):\n vectorizer = TfidfVectorizer(ngram_range = ngram_range, max_df = max_df, \\\\\n min_df = min_df, max_features = max_features, \\\\\n binary = binary, norm = norm, use_idf = use_idf, \\\\\n smooth_idf = smooth_idf, sublinear_tf = sublinear_tf)\n return vectorizer \n\ndef GetPOSTags( inputText, getPOSTags_Lib='nltk'):\n global spacy_nlp\n tokens_postag_list = []\n \n if (inputText == \"\"):\n __Log(\"debug\", \"{} function: Input text is not provided\".format(sys._getframe().f_code.co_name))\n else:\n if getPOSTags_Lib == 'spacy':\n if spacy_nlp == None:\n spacy_nlp = spacy.load('en_core_web_sm') \n doc = spacy_nlp(inputText)\n for token in doc:\n tokens_postag_list.append((token.text, token.tag_))\n elif getPOSTags_Lib == 'textblob':\n doc = TextBlob(inputText)\n tokens_postag_list = doc.tags\n else:\n tokensList = WordTokenize(inputText)\n tokens_postag_list = pos_tag(tokensList)\n \n return tokens_postag_list\n \ndef GetNGrams( inputText, ngramRange=(1,1)):\n ngramslist = []\n for n in range(ngramRange[0],ngramRange[1]+1):\n nwordgrams = ngrams(inputText.split(), n)\n ngramslist.extend([' '.join(grams) for grams in nwordgrams])\n return ngramslist \n \ndef NamedEntityRecognition( inputText):\n global spacy_nlp\n neResultList = []\n if (inputText == \"\"):\n __Log(\"debug\", \"{} function: Input text is not provided\".format(sys._getframe().f_code.co_name))\n else:\n if spacy_nlp == None:\n spacy_nlp = spacy.load('en_core_web_sm') \n doc = spacy_nlp(inputText)\n neResultList = [(X.text, X.label_) for X in doc.ents]\n \n return neResultList\n \ndef KeywordsExtraction( inputText, ratio=0.2, words = None, scores=False, pos_filter=('NN', 'JJ'), lemmatize=False):\n keywordsList = []\n if (inputText == \"\"):\n __Log(\"debug\", \"{} function: Input text is not provided\".format(sys._getframe().f_code.co_name))\n else:\n keywordsList = keywords(inputText, ratio = ratio, words = words, split=True, scores=scores, \n pos_filter=pos_filter, lemmatize=lemmatize)\n return keywordsList\n\ndef __get_nodes(parent): \n nounList = []\n verbList = []\n for node in parent:\n if type(node) is nltk.Tree:\n if node.label() == \"NP\":\n subList = []\n for item in node.leaves():\n subList.append(item[0])\n nounList.append((\" \".join(subList)))\n elif node.label() == \"VP\":\n subList = []\n for item in node.leaves():\n subList.append(item[0])\n verbList.append((\" \".join(subList)))\n #verbList.append(node.leaves()[0][0])\n __get_nodes(node)\n result = {'NP': nounList, 'VP': verbList}\n return result\n\ndef ShallowParsing( inputText, lib='spacy'):\n tags = GetPOSTags(inputText, getPOSTags_Lib=lib)\n \n chunk_regex = r\"\"\"\n NBAR:\n {
?*+} # Nouns and Adjectives, terminated with Nouns\n VBAR:\n {**?*+?} # Verbs and Verb Phrases\n \n NP:\n {}\n {} # Above, connected with in/of/etc...\n VP: \n {}\n {} # Above, connected with in/of/etc...\n \"\"\"\n rp = RegexpParser(chunk_regex)\n t = rp.parse(tags)\n return __get_nodes(t)\n\ndef SyntacticAndEntityParsing(inputCorpus, \n featuresList=['POSTags','NGrams','NamedEntityRecognition','KeywordsExtraction','ShallowParsing'],\n posTagsLib='nltk', \n ngramRange=(1,1), \n ke_ratio=0.2, \n ke_words = None, \n ke_scores=False, \n ke_pos_filter=('NN', 'JJ'), \n ke_lemmatize=False):\n columnsList = ['Input']\n columnsList.extend(featuresList)\n df = pd.DataFrame(columns=columnsList)\n df['Input'] = inputCorpus\n for feature in featuresList:\n if feature == 'POSTags':\n df[feature] = inputCorpus.apply(lambda x: GetPOSTags(x, posTagsLib))\n if feature == 'NGrams':\n df[feature] = inputCorpus.apply(lambda x: GetNGrams(x, ngramRange))\n if feature == 'NamedEntityRecognition':\n df[feature] = inputCorpus.apply(lambda x: NamedEntityRecognition(x))\n if feature == 'KeywordsExtraction':\n df[feature] = inputCorpus.apply(lambda x: KeywordsExtraction(x, \n ratio=ke_ratio, words=ke_words,\n scores=ke_scores, pos_filter=ke_pos_filter,\n lemmatize=ke_lemmatize))\n if feature == 'ShallowParsing':\n df[feature] = inputCorpus.apply(lambda x: ShallowParsing(x, lib=posTagsLib))\n return df\n \ndef __Log( logType=\"info\", text=None):\n if logType.lower() == \"exception\":\n logging.exception( text)\n elif logEnabled:\n if logType.lower() == \"info\":\n logging.info( text)\n elif logType.lower() == \"debug\":\n logging.debug( text)\n\ndef SentenceTokenize( inputText):\n return text_cleaner.WordTokenize(inputText)\n\ndef WordTokenize( inputText, tokenizationLib = 'nltk'):\n return text_cleaner.WordTokenize(inputText, tokenizationLib)\n\ndef Lemmatize( inputTokensList, lemmatizationLib = 'nltk'):\n return text_cleaner.Lemmatize(inputTokensList, lemmatizationLib)\n\ndef Stemmize( inputTokensList):\n return text_cleaner.Stemmize(inputTokensList)\n \ndef ToLowercase( inputText):\n resultText = \"\"\n if inputText is not None and inputText != \"\":\n resultText = inputText.lower()\n return resultText\n\ndef ToUppercase( inputText):\n resultText = \"\"\n if inputText is not None and inputText != '': \n resultText = inputText.upper()\n return resultText\n \ndef RemoveNoise(\n inputText, \n removeNoise_fHtmlDecode = True, \n removeNoise_fRemoveHyperLinks = True,\n removeNoise_fRemoveMentions = True, \n removeNoise_fRemoveHashtags = True, \n removeNoise_RemoveOrReplaceEmoji = 'remove',\n removeNoise_fUnicodeToAscii = True,\n removeNoise_fRemoveNonAscii = True):\n return text_cleaner.RemoveNoise(inputText, removeNoise_fHtmlDecode, removeNoise_fRemoveHyperLinks, removeNoise_fRemoveMentions,\n removeNoise_fRemoveHashtags, removeNoise_RemoveOrReplaceEmoji, removeNoise_fUnicodeToAscii, removeNoise_fRemoveNonAscii)\n \ndef RemoveStopwords( inputTokensList, stopwordsRemovalLib='nltk', stopwordsList = None, extend_or_replace='extend'):\n return text_cleaner.RemoveStopwords(inputTokensList, stopwordsRemovalLib, stopwordsList, extend_or_replace)\n \ndef RemoveNumericTokens( inputText, removeNumeric_fIncludeSpecialCharacters=True):\n return text_cleaner.RemoveNumericTokens(inputText, removeNumeric_fIncludeSpecialCharacters)\n \ndef RemovePunctuation( inputText, fRemovePuncWithinTokens=False):\n return text_cleaner.RemovePunctuation(inputText, fRemovePuncWithinTokens)\n \ndef CorrectSpelling( inputTokensList):\n return text_cleaner.CorrectSpelling(inputTokensList)\n \ndef ReplaceAcronym( inputTokensList, acrDict=None):\n return text_cleaner.ReplaceAcronym(inputTokensList, acrDict)\n \ndef ExpandContractions( inputText, expandContractions_googleNewsWordVectorPath=None):\n return text_cleaner.ExpandContractions(inputText, expandContractions_googleNewsWordVectorPath)\n \ndef get_pretra", "instruction": "", "output": "" }, { "input": "ined_model_path():\n try:\n from appbe.dataPath import DATA_DIR\n modelsPath = Path(DATA_DIR)/'PreTrainedModels'/'TextProcessing'\n except:\n modelsPath = Path('aion')/'PreTrainedModels'/'TextProcessing'\n if not modelsPath.exists():\n modelsPath.mkdir(parents=True, exist_ok=True)\n return modelsPath\n \ndef checkAndDownloadPretrainedModel(preTrainedModel, embedding_size=300):\n \n models = {'glove':{50:'glove.6B.50d.w2vformat.txt',100:'glove.6B.100d.w2vformat.txt',200:'glove.6B.200d.w2vformat.txt',300:'glove.6B.300d.w2vformat.txt'}, 'fasttext':{300:'wiki-news-300d-1M.vec'}}\n supported_models = [x for y in models.values() for x in y.values()]\n embedding_sizes = {x:y.keys() for x,y in models.items()}\n preTrainedModel = preTrainedModel.lower()\n if preTrainedModel not in models.keys():\n raise ValueError(f'model not supported: {preTrainedModel}')\n if embedding_size not in embedding_sizes[preTrainedModel]:\n raise ValueError(f\"Embedding size '{embedding_size}' not supported for {preTrainedModel}\")\n selected_model = models[preTrainedModel][embedding_size]\n modelsPath = get_pretrained_model_path()\n p = modelsPath.glob('**/*')\n modelsDownloaded = [x.name for x in p if x.name in supported_models]\n if selected_model not in modelsDownloaded:\n if preTrainedModel == \"glove\":\n try:\n local_file_path = modelsPath/f\"glove.6B.{embedding_size}d.w2vformat.txt\"\n file_test, header_test = urllib.request.urlretrieve(f'https://aion-pretrained-models.s3.ap-south-1.amazonaws.com/text/glove.6B.{embedding_size}d.w2vformat.txt', local_file_path)\n except Exception as e:\n raise ValueError(\"Error: unable to download glove pretrained model, please try again or download it manually and placed it at {}. \".format(modelsPath)+str(e))\n\n elif preTrainedModel == \"fasttext\":\n try:\n local_file_path = modelsPath/\"wiki-news-300d-1M.vec.zip\"\n url = 'https://aion-pretrained-models.s3.ap-south-1.amazonaws.com/text/wiki-news-300d-1M.vec.zip'\n file_test, header_test = urllib.request.urlretrieve(url, local_file_path)\n with zipfile.ZipFile(local_file_path) as zip_ref:\n zip_ref.extractall(modelsPath)\n Path(local_file_path).unlink()\n except Exception as e:\n raise ValueError(\"Error: unable to download fastText pretrained model, please try again or download it manually and placed it at {}. \".format(location)+str(e))\n return modelsPath/selected_model\n \ndef load_pretrained(path):\n embeddings = {}\n word = ''\n with open(path, 'r', encoding=\"utf8\") as f:\n header = f.readline()\n header = header.split(' ')\n vocab_size = int(header[0])\n embed_size = int(header[1])\n for i in range(vocab_size):\n data = f.readline().strip().split(' ')\n word = data[0]\n embeddings[word] = [float(x) for x in data[1:]]\n return embeddings\n\nclass TextProcessing(BaseEstimator, TransformerMixin):\n \n def __init__(self,\n functionSequence = ['RemoveNoise','ExpandContractions','Normalize','ReplaceAcronym',\n 'CorrectSpelling','RemoveStopwords','RemovePunctuation','RemoveNumericTokens'],\n fRemoveNoise = True,\n fExpandContractions = False,\n fNormalize = True,\n fReplaceAcronym = False,\n fCorrectSpelling = False,\n fRemoveStopwords = True,\n fRemovePunctuation = True,\n fRemoveNumericTokens = True,\n removeNoise_fHtmlDecode = True, \n removeNoise_fRemoveHyperLinks = True,\n removeNoise_fRemoveMentions = True, \n removeNoise_fRemoveHashtags = True,\n removeNoise_RemoveOrReplaceEmoji = 'remove',\n removeNoise_fUnicodeToAscii = True,\n removeNoise_fRemoveNonAscii = True,\n tokenizationLib='nltk',\n normalizationMethod = 'Lemmatization',\n lemmatizationLib = 'nltk',\n acronymDict = None,\n stopwordsRemovalLib = 'nltk',\n stopwordsList = None,\n extend_or_replace_stopwordslist = 'extend',\n removeNumeric_fIncludeSpecialCharacters = True,\n fRemovePuncWithinTokens = False,\n data_path = None\n):\n global logEnabled\n #logEnabled = EnableLogging\n self.functionSequence = functionSequence\n self.fRemoveNoise = fRemoveNoise\n self.fExpandContractions = fExpandContractions\n self.fNormalize = fNormalize\n self.fReplaceAcronym = fReplaceAcronym\n self.fCorrectSpelling = fCorrectSpelling\n self.fRemoveStopwords = fRemoveStopwords\n self.fRemovePunctuation = fRemovePunctuation\n self.fRemoveNumericTokens = fRemoveNumericTokens\n self.removeNoise_fHtmlDecode = removeNoise_fHtmlDecode\n self.removeNoise_fRemoveHyperLinks = removeNoise_fRemoveHyperLinks\n self.removeNoise_fRemoveMentions = removeNoise_fRemoveMentions \n self.removeNoise_fRemoveHashtags = removeNoise_fRemoveHashtags\n self.removeNoise_RemoveOrReplaceEmoji = removeNoise_RemoveOrReplaceEmoji\n self.removeNoise_fUnicodeToAscii = removeNoise_fUnicodeToAscii\n self.removeNoise_fRemoveNonAscii = removeNoise_fRemoveNonAscii\n self.tokenizationLib = tokenizationLib\n self.normalizationMethod = normalizationMethod\n self.lemmatizationLib = lemmatizationLib\n self.acronymDict = acronymDict\n self.stopwordsRemovalLib = stopwordsRemovalLib\n self.stopwordsList = stopwordsList\n self.extend_or_replace_stopwordslist = extend_or_replace_stopwordslist\n self.removeNumeric_fIncludeSpecialCharacters = removeNumeric_fIncludeSpecialCharacters\n self.fRemovePuncWithinTokens = fRemovePuncWithinTokens\n self.data_path = data_path\n self.fit_and_transformed_ = False\n\n def fit(self, x, y=None):\n return self\n \n def transform(self, x):\n x = map(lambda inputText: text_cleaner.cleanText(inputText, functionSequence = self.functionSequence, fRemoveNoise = self.fRemoveNoise, fExpandContractions = self.fExpandContractions, fNormalize = self.fNormalize, fReplaceAcronym = self.fReplaceAcronym, fCorrectSpelling = self.fCorrectSpelling, fRemoveStopwords = self.fRemoveStopwords, fRemovePunctuation = self.fRemovePunctuation, fRemoveNumericTokens = self.fRemoveNumericTokens, removeNoise_fHtmlDecode = self.removeNoise_fHtmlDecode, removeNoise_fRemoveHyperLinks = self.removeNoise_fRemoveHyperLinks, removeNoise_fRemoveMentions = self.removeNoise_fRemoveMentions , removeNoise_fRemoveHashtags = self.removeNoise_fRemoveHashtags, removeNoise_RemoveOrReplaceEmoji = self.removeNoise_RemoveOrReplaceEmoji, removeNoise_fUnicodeToAscii = self.removeNoise_fUnicodeToAscii, removeNoise_fRemoveNonAscii = self.removeNoise_fRemoveNonAscii, tokenizationLib = self.tokenizationLib, normalizationMethod = self.normalizationMethod, lemmatizationLib = self.lemmatizationLib, acronymDict = self.acronymDict, stopwordsRemovalLib = self.stopwordsRemovalLib, stopwordsList = self.stopwordsList, extend_or_replace_stopwordslist = self.extend_or_replace_stopwordslist, removeNumeric_fIncludeSpecialCharacters = self.removeNumeric_fIncludeSpecialCharacters, fRemovePuncWithinTokens = self.fRemovePuncWithinTokens), x)\n x = pd.Series(list(x))\n if hasattr(self, 'fit_and_transformed_') and not self.fit_and_transformed_:\n self.fit_and_transformed_ = True\n if self.data_path and Path(self.data_path).exists():\n x.to_csv(Path(self.data_path)/'text_cleaned.csv', index=False)\n return x\n\n def get_feature_names_out(self):\n return ['tokenize']\n\nclass wordEmbedding(BaseEstimator, TransformerMixin):\n\n def __init__(self, preTrainedModel, embeddingSize=300,external_model=None,external_model_type='binary'):\n self.number_of_features = 0\n self.embeddingSize = embeddingSize\n self.preTrainedModel = preTrainedModel.lower()\n self.external_model=external_model\n self.external_model_type = external_model_type\n if self.preTrainedModel == \"glove\":\n self.preTrainedModelpath = f'glove.6B.{self.embeddingSize}d.w2vformat.txt'\n self.binary = False\n elif self.preTrainedModel == \"fasttext\":\n self.preTrainedModelpath = 'wiki-news-300d-1M.vec'\n self.binary = False\n else:\n raise ValueError(f'Model ({self.preTrainedModel}) not supported')\n \n def fit(self, x, y=None):\n return self\n \n def transform(self, x):\n if ((isinstance(self.external_model, pd.DataFrame) and not self.external_model.empty) or (not isinstance(self.external_model, pd.DataFrame) and self.external_model)):\n if self.preTrainedModel == \"fasttext\" and self.external_model_type == 'binary':\n print('Transforming using external binary')\n extracted = np.vstack([self.external_model.get_sentence_vector( sentense) for sentense in x])\n else:\n print('Transforming using external vector')\n extracted = extractFeatureUsingPreTrainedModel(x, pretrainedModelPath=None, loaded_model=self.external_model, embed_size=300)\n else:\n print('Transforming using Vector')\n models_path = checkAndDownloadPretrainedModel(self.preTrainedModel, self.embeddingSize)\n extracted = extractFeatureUsingPreTrainedModel(x, models_path)\n\n self.number_of_features = extracted.shape[1]\n return extracted\n \n def get_feature_names_out(self):\n return [str(x) for x in range(self.number_of_features)]\n\n def get_feature_names(self):\n return self.get_feature_names_out()\n\ndef getProcessedPOSTaggedData(pos_tagged_data):\n def get_wordnet_post(tag):\n if tag.startswith('V'):\n return wordnet.VERB\n elif tag.startswith('J'):\n return wordnet.ADJ\n elif tag.startswith('R'):\n return wordnet.ADV\n else:\n return wordnet.NOUN\n\n def process_pos_tagged_data(text):\n processed_text = [f\"{t[0]}_{get_wordnet_post(t[1])}\" for t in text]\n processed_text = \" \".join(processed_text)\n return processed_text\n\n processed_pos_tagged_data = pos_tagged_data.apply(process_pos_tagged_data)\n return processed_pos_tagged_data\n \n \nclass PosTagging(BaseEstimator, TransformerMixin):\n\n def __init__(self, posTagsLib, data_path):\n self.posTagsLib = posTagsLib\n self.fit_and_transformed_ = False\n self.data_path = data_path\n \n def fit(self, x, y=None):\n return self\n \n def transform(self, x):\n parsing_output = SyntacticAndEntityParsing(x, featuresList=['POSTags'], posTagsLib=self.posTagsLib)\n output = getProcessedPOSTaggedData(parsing_output['POSTags'])\n if not self.fit_and_transformed_:\n self.fit_and_transformed_ = True\n if self.data_path and Path(self.data_path).exists():\n output.to_csv(Path(self.data_path)/'pos_tagged.csv', index=False)\n return output\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\n\nimport openai\nimport tiktoken\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nfrom openai.embeddings_utils import get_embedding\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\nclass embedding(BaseEstimator, TransformerMixin):\n\n def __init__(self, embedding_engine='Text-Embedding', embedding_ctx_size=8191, encoding_method='cl100k_base'):\n self.embedding_engine = embedding_engine\n self.embedding_ctx_size = embedding_ctx_size\n self.encoding_method = encoding_method\n self.number_of_features = 1536\n \n def fit(self,X,y=None):\n return self\n\n def transform(self, X):\n setup_openai()\n \n X = map(lambda text: self.len_safe_get_embedding( text), X)\n return list(X)\n\n def split_large_text(self, large_text):\n encoding = tiktoken.get_encoding( self.encoding_method)\n tokenized_text = encoding.encode(large_text)\n\n chunks = []\n current_chunk = []\n current_length = 0\n\n for token in tokenized_text:\n current_chunk.append(token)\n current_length += 1\n\n if current_length >= self.embedding_ctx_size:\n chunks.append(encoding.decode(current_chunk).rstrip(' .,;'))\n current_chunk = []\n current_length = 0\n\n if current_chunk:\n chunks.append(encoding.decode(current_chunk).rstrip(' .,;'))\n \n return chunks\n \n def len_safe_get_embedding(self, text):\n chunk_embeddings = []\n chunk_lens = []\n for chunk in self.split_large_text(text):\n ", "instruction": "", "output": "" }, { "input": "chunk_embeddings.append( get_embedding(chunk, engine=self.embedding_engine))\n chunk_lens.append(len(chunk))\n\n chunk_embeddings = np.average(chunk_embeddings, axis=0, weights=None)\n chunk_embeddings = chunk_embeddings / np.linalg.norm(chunk_embeddings) # normalizes length to 1\n chunk_embeddings = chunk_embeddings.tolist()\n return chunk_embeddings\n\n def get_feature_names_out(self):\n return [str(x) for x in range(self.number_of_features)]\n\n def get_feature_names(self):\n return self.get_feature_names_out()\n\n\"\"\"\nOpen AI initialization has to be done separately as follows:\n 1. During training read the parameters from user \n a. from config \n b. SQLite database\n c. From Json file\n\"\"\"\nclass setup_openai():\n\n def __init__( self, config=None):\n param_keys = ['api_type','api_key','api_base','api_version']\n if isinstance(config, dict):\n valid_params = {x:y for x,y in config.items() if x in param_keys}\n self._update_params(valid_params) \n elif self._is_sqlite():\n self._update_params( self._get_cred_from_sqlite())\n elif ((Path(__file__).parent.parent/'etc')/'openai.json').exists():\n with open(((Path(__file__).parent.parent/'etc')/'openai.json'), 'r') as f:\n import json\n params = json.load(f)\n valid_params = {x:y for x,y in params.items() if x in param_keys}\n self._update_params(valid_params)\n else:\n raise ValueError('Open AI credentials are not provided.')\n\n def _is_sqlite(self):\n try:\n from AION.appbe.sqliteUtility import sqlite_db\n from AION.appbe.dataPath import DATA_DIR\n db_dir = Path(DATA_DIR)/'sqlite'\n db_file = 'config.db'\n if (db_dir/db_file).exists():\n sqlite_obj = sqlite_db(db_dir,db_file)\n if sqlite_obj.table_exists('openai'):\n return True\n return False \n except:\n return False\n\n def _get_cred_from_sqlite(self):\n from AION.appbe.sqliteUtility import sqlite_db\n from AION.appbe.dataPath import DATA_DIR\n db_dir = Path(DATA_DIR)/'sqlite'\n db_file = 'config.db'\n sqlite_obj = sqlite_db(db_dir,db_file)\n data = sqlite_obj.read_data('openai')[0]\n param_keys = ['api_type','api_key','api_base','api_version']\n return dict((x,y) for x,y in zip(param_keys,data))\n\n def _update_params(self, valid_params):\n for key, value in valid_params.items():\n if key == 'api_type':\n openai.api_type = value\n elif key == 'api_key':\n openai.api_key = value\n elif key == 'api_base':\n openai.api_base = value\n elif key == 'api_version':\n openai.api_version = value\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\n\nimport re\nimport string\nimport sys\nimport demoji\n#demoji.download_codes()\nimport nltk\nimport spacy\nfrom nltk.corpus import stopwords\nfrom bs4 import BeautifulSoup\nfrom text_unidecode import unidecode\nfrom textblob import TextBlob\nfrom spellchecker import SpellChecker\nfrom nltk import pos_tag\nfrom nltk.tokenize import word_tokenize \nfrom nltk.corpus import wordnet\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk.stem.porter import PorterStemmer\nfrom spacy.lang.en import English\nfrom collections import defaultdict\nimport contractions\n\n\nspacy_nlp = None\n\ndef WordTokenize( inputText, tokenizationLib = 'nltk'):\n tokenList = []\n if inputText is not None and inputText != \"\":\n tokenizationLib = tokenizationLib.lower()\n if tokenizationLib == 'nltk':\n tokenList = word_tokenize(inputText)\n elif tokenizationLib == 'textblob':\n tbObj = TextBlob(inputText)\n tokenList = tbObj.words\n elif tokenizationLib == 'spacy':\n nlp = English()\n nlpDoc = nlp(inputText)\n for token in nlpDoc:\n tokenList.append(token.text)\n elif tokenizationLib == 'keras':\n from tensorflow.keras.preprocessing.text import text_to_word_sequence\n tokenList = text_to_word_sequence(inputText)\n else:\n tokenList = word_tokenize(inputText)\n \n return tokenList\n \ndef SentenceTokenize( inputText):\n sentenceList = []\n if inputText is not None and inputText != \"\":\n sentenceList = sent_tokenize(inputText)\n return sentenceList\n\ndef Lemmatize(inputTokensList, lemmatizationLib = 'nltk'):\n global spacy_nlp\n lemmatized_list= []\n lemmatizationLib = lemmatizationLib.lower()\n if (inputTokensList is not None) and (len(inputTokensList)!=0):\n if (lemmatizationLib == 'textblob'):\n inputText = \" \".join(inputTokensList)\n sent = TextBlob(inputText)\n tag_dict = {\"J\": 'a', \n \"N\": 'n', \n \"V\": 'v', \n \"R\": 'r'}\n words_and_tags = [(w, tag_dict.get(pos[0], 'n')) for w, pos in sent.tags] \n lemmatized_list = [wd.lemmatize(tag) for wd, tag in words_and_tags]\n if (lemmatizationLib == 'spacy'):\n inputText = \" \".join(inputTokensList)\n if spacy_nlp == None:\n spacy_nlp = spacy.load('en_core_web_sm')\n doc = spacy_nlp(inputText)\n \n for token in doc:\n if token.text != token.lemma_:\n if token.lemma_ != \"-PRON-\":\n lemmatized_list.append(token.lemma_)\n else:\n lemmatized_list.append(token.text)\n else:\n lemmatized_list.append(token.text)\n else:\n tag_map = defaultdict(lambda : wordnet.NOUN)\n tag_map['J'] = wordnet.ADJ\n tag_map['V'] = wordnet.VERB\n tag_map['R'] = wordnet.ADV\n \n wnLemmatizer = WordNetLemmatizer()\n token_tags = pos_tag(inputTokensList)\n lemmatized_list = [wnLemmatizer.lemmatize(token, tag_map[tag[0]]) for token, tag in token_tags]\n\n return lemmatized_list\n \ndef Stemmize(inputTokensList):\n stemmedTokensList= []\n \n if (inputTokensList is not None) and (len(inputTokensList)!=0):\n porterStemmer = PorterStemmer()\n stemmedTokensList = [porterStemmer.stem(token) for token in inputTokensList]\n \n return stemmedTokensList\n \ndef ToLowercase(inputText):\n resultText = \"\"\n if inputText is not None and inputText != \"\":\n resultText = inputText.lower()\n \n return resultText\n\ndef ToUppercase(inputText):\n resultText = \"\"\n if inputText is not None and inputText != '': \n resultText = inputText.upper()\n \n return resultText\n \ndef RemoveNoise(inputText, \n removeNoise_fHtmlDecode = True, \n removeNoise_fRemoveHyperLinks = True,\n removeNoise_fRemoveMentions = True, \n removeNoise_fRemoveHashtags = True, \n removeNoise_RemoveOrReplaceEmoji = 'remove',\n removeNoise_fUnicodeToAscii = True,\n removeNoise_fRemoveNonAscii = True):\n if inputText is not None and inputText != \"\": \n if removeNoise_fHtmlDecode == True:\n inputText = BeautifulSoup(inputText, \"html.parser\").text\n if removeNoise_fRemoveHyperLinks == True:\n inputText = re.sub(r'https?:\\\\/\\\\/\\\\S*', '', inputText, flags=re.MULTILINE) \n if removeNoise_fRemoveMentions == True:\n inputText = re.sub('[@]+\\\\S+','', inputText)\n if removeNoise_fRemoveHashtags == True:\n inputText = re.sub('[#]+\\\\S+','', inputText)\n if removeNoise_RemoveOrReplaceEmoji == 'remove':\n inputText = demoji.replace(inputText, \"\")\n elif removeNoise_RemoveOrReplaceEmoji == 'replace':\n inputText = demoji.replace_with_desc(inputText, \" \")\n if removeNoise_fUnicodeToAscii == True:\n inputText = unidecode(inputText)\n if removeNoise_fRemoveNonAscii == True:\n inputText= re.sub(r'[^\\\\x00-\\\\x7F]+',' ', inputText)\n \n inputText = re.sub(r'\\\\s+', ' ', inputText)\n inputText = inputText.strip()\n \n return inputText\n\ndef RemoveStopwords(inputTokensList, stopwordsRemovalLib='nltk', stopwordsList = None, extend_or_replace='extend'):\n resultTokensList = []\n if (inputTokensList is not None) and (len(inputTokensList)!=0):\n stopwordsRemovalLib= stopwordsRemovalLib.lower()\n \n if stopwordsRemovalLib == 'spacy':\n nlp = English()\n stopwordRemovalList = nlp.Defaults.stop_words\n else:\n stopwordRemovalList = set(stopwords.words('english'))\n \n if extend_or_replace == 'replace':\n if stopwordsList is not None:\n stopwordRemovalList = set(stopwordsList)\n else:\n if stopwordsList:\n stopwordRemovalList = stopwordRemovalList.union(set(stopwordsList))\n \n resultTokensList = [word for word in inputTokensList if word not in stopwordRemovalList] \n \n return resultTokensList \n \ndef RemoveNumericTokens(inputText, removeNumeric_fIncludeSpecialCharacters=True):\n resultText = \"\"\n if inputText is not None and inputText != \"\": \n if removeNumeric_fIncludeSpecialCharacters == True:\n #Remove tokens having numbers and punctuations \n resultText = re.sub(r'\\\\b\\\\d+[^a-zA-Z]*\\\\d*\\\\b',' ', inputText)\n else:\n #Remove only numeric tokens\n resultText = re.sub(r'\\\\b\\\\d+\\\\b','', inputText)\n \n # convert consecutive whitespaces to single space in the results\n resultText = re.sub(r'\\\\s+', ' ', resultText)\n \n return resultText\n \ndef RemovePunctuation(inputText, fRemovePuncWithinTokens=False):\n resultText = \"\"\n if inputText is not None and len(inputText) != 0:\n if fRemovePuncWithinTokens == True:\n resultText = inputText.translate(str.maketrans(\"\",\"\", string.punctuation))\n else:\n punctuationList = list(string.punctuation)\n tokensList = WordTokenize(inputText) \n resultTokensList = [word for word in tokensList if word not in punctuationList] \n resultText = \" \".join(resultTokensList) \n \n resultText = re.sub(r'\\\\s+', ' ', resultText)\n return resultText\n \n \ndef CorrectSpelling(inputTokensList):\n correctedTokensList = []\n \n if (inputTokensList is not None) and (len(inputTokensList)!=0): \n spell = SpellChecker()\n for word in inputTokensList:\n word = word.lower()\n if word not in spell:\n word = spell.correction(word)\n if word:\n correctedTokensList.append(word) \n return correctedTokensList\n \ndef ReplaceAcronym(inputTokensList, acrDict=None):\n resultTokensList = []\n \n if (inputTokensList is not None) and (len(inputTokensList)!=0): \n if ((acrDict is not None) and (len(acrDict) != 0)):\n acrDictLowercase = dict((key.lower(), value.lower()) for key, value in acrDict.items())\n resultTokensList = [acrDictLowercase.get(token.lower(), token.lower()) for token in inputTokensList]\n else:\n resultTokensList = inputTokensList\n \n return resultTokensList \n \ndef ExpandContractions(inputText):\n resultText = \"\"\n if inputText != '':\n resultText = contractions.fix(inputText)\n return resultText \n\ndef cleanText( inputText,\n functionSequence = ['RemoveNoise','ExpandContractions','Normalize','ReplaceAcronym',\n 'CorrectSpelling','RemoveStopwords','RemovePunctuation','RemoveNumericTokens'],\n fRemoveNoise = True,\n fExpandContractions = False,\n fNormalize = True,\n fReplaceAcronym = False,\n fCorrectSpelling = False,\n fRemoveStopwords = True,\n fRemovePunctuation = True,\n fRemoveNumericTokens = True,\n removeNoise_fHtmlDecode = True, \n removeNoise_fRemoveHyperLinks = True,\n removeNoise_fRemoveMentions = True, \n removeNoise_fRemoveHashtags = True,\n removeNoise_RemoveOrReplaceEmoji = 'remove',\n removeNoise_fUnicodeToAscii = True,\n removeNoise_fRemoveNonAscii = True,\n tokenizationLib='nltk',\n normalizationMethod = 'Lemmatization',\n lemmatizationLib = 'nltk',\n acronymDict = None,\n stopwordsRemovalLib = 'nltk',\n stopwordsList = None,\n extend_or_replace_stopwordslist = 'extend',\n removeNumeric_fIncludeSpecialCharacters = True,\n fRemovePuncWithinTokens = False\n ):\n if inputText is not None and inputText != \"\": \n for function in functionSequence:\n if function == 'RemoveNoise':\n if (fRemoveNoise == True):\n inputText = RemoveNoise(inputText, \n removeNoise_fHtmlDecode, \n removeNoise_fRemoveHyperLinks,\n removeNoise_fRemoveMentions, \n removeNoise_fRemoveHasht", "instruction": "", "output": "" }, { "input": "ags, \n removeNoise_RemoveOrReplaceEmoji, \n removeNoise_fUnicodeToAscii, \n removeNoise_fRemoveNonAscii)\n if function == 'ExpandContractions':\n if (fExpandContractions == True):\n inputText = ExpandContractions(inputText)\n if function == 'Normalize': \n if (fNormalize == True):\n inputTokens = WordTokenize(inputText, tokenizationLib) \n if (normalizationMethod == 'Stemming'):\n inputTokens = Stemmize(inputTokens)\n else: \n inputTokens = Lemmatize(inputTokens, lemmatizationLib)\n inputText = \" \".join(inputTokens)\n if function == 'ReplaceAcronym': \n if fReplaceAcronym == True and (acronymDict is not None) and acronymDict != 'None':\n inputText = ToLowercase(inputText)\n inputTokens = WordTokenize(inputText, tokenizationLib) \n inputTokens= ReplaceAcronym(inputTokens, acronymDict)\n inputText = \" \".join(inputTokens)\n if function == 'CorrectSpelling':\n if (fCorrectSpelling == True):\n try:\n inputTokens = WordTokenize(inputText, tokenizationLib) \n inputTokens = CorrectSpelling(inputTokens)\n inputText = \" \".join(inputTokens)\n except Exception as e:\n print(e)\n pass\n if function == 'RemoveStopwords':\n if (fRemoveStopwords == True):\n inputText = ToLowercase(inputText)\n inputTokens = WordTokenize(inputText, tokenizationLib)\n inputTokens = RemoveStopwords(inputTokens, stopwordsRemovalLib, stopwordsList, extend_or_replace_stopwordslist)\n inputText = \" \".join(inputTokens)\n if function == 'RemovePunctuation':\n if (fRemovePunctuation == True):\n inputText = RemovePunctuation(inputText, fRemovePuncWithinTokens)\n if function == 'RemoveNumericTokens': \n if (fRemoveNumericTokens == True):\n inputText = RemoveNumericTokens(inputText, removeNumeric_fIncludeSpecialCharacters)\n inputText = ToLowercase(inputText)\n\n return inputText\n \n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport sys\nimport logging\nfrom collections import Counter\n\nimport spacy\nimport numpy as np\nimport pandas as pd\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk import pos_tag\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom textblob import TextBlob\nfrom sklearn.feature_extraction.text import CountVectorizer\n'''\nnltk.download(\"punkt\")\nnltk.download(\"wordnet\")\n'''\nstopWords = stopwords.words(\"english\")\n\nclass ExploreTextData:\n\n\n def __init__(self, logEnabled=False):\n self.logEnabled = logEnabled\n \n def __Log(self, logType=\"info\", text=None):\n if logType.lower() == \"exception\":\n logging.exception( text)\n elif self.logEnabled:\n if logType.lower() == \"info\":\n logging.info( text)\n elif logType.lower() == \"debug\":\n logging.debug( text)\n\n def Describe(self, inputCorpus):\n \"\"\" Generate descriptive statistics for length of documents.\n Parameters\n ----------\n \n inputCorpus: sequence of input documents where each document consists of paragraphs or sentences\n Returns\n -------\n dict\n Summary statistics of the Series or Dataframe provided.\n \"\"\"\n try:\n self.__Log(\"info\", \"Start of {} function\".format(sys._getframe().f_code.co_name))\n stat = {}\n word_count = self.DocumentWordCount(inputCorpus)\n stat['count'] = float(len(word_count))\n stat['mean'] = float(word_count.mean())\n stat['std'] = float(word_count.std())\n stat['max'] = float(word_count.max())\n stat['min'] = float(word_count.min())\n return pd.DataFrame.from_dict(stat, orient='index')\n except:\n self.__Log(\"exception\", sys.exc_info())\n raise\n \n def DocumentLength(self, inputCorpus):\n \"\"\" Calculate the length of each document in corpus\n Parameters\n ----------\n \n inputCorpus: sequence of input documents where each document consists of paragraphs or sentences\n Returns\n -------\n pandas.Series of {int}\n series of length of documents\n \"\"\"\n try:\n self.__Log(\"info\", \"Start of {} function\".format(sys._getframe().f_code.co_name))\n return inputCorpus.str.len()\n except:\n self.__Log(\"exception\", sys.exc_info())\n raise\n \n def DocumentWordCount(self, inputCorpus):\n \"\"\" Calculate the number of words in each document in corpus\n Parameters\n ----------\n inputCorpus: sequence of input documents where each document consists of paragraphs or sentences\n Returns\n -------\n pandas.Series of {int}\n series of number of words in documents\n \"\"\"\n try:\n self.__Log(\"info\", \"Start of {} function\".format(sys._getframe().f_code.co_name))\n return inputCorpus.str.split().map(lambda x: len(x))\n except:\n self.__Log(\"exception\", sys.exc_info())\n raise\n \n def AverageWordLength(self, inputCorpus):\n \"\"\" Calculate the average length of words in each document in corpus\n Parameters\n ----------\n inputCorpus: sequence of input documents where each document consists of paragraphs or sentences\n Returns\n -------\n pandas.Series of {double}\n series of average length of words in documents\n \"\"\"\n try:\n self.__Log(\"info\", \"Start of {} function\".format(sys._getframe().f_code.co_name))\n return inputCorpus.str.split()\\\\\n .apply(lambda x: [len(i) for i in x])\\\\\n .map(lambda x: np.mean(x))\n except:\n self.__Log(\"exception\", sys.exc_info())\n raise\n \n def StopWordsCount(self, inputCorpus):\n \"\"\" Calculate the number of stopwords in each document in corpus\n Parameters\n ----------\n inputCorpus: sequence of input documents where each document consists of paragraphs or sentences\n Returns\n -------\n pandas.Series of {int}\n series of count of stopwords in documents\n \"\"\"\n try:\n self.__Log(\"info\", \"Start of {} function\".format(sys._getframe().f_code.co_name))\n stopWordsCount = []\n inputCorpus = list(inputCorpus)\n for doc in inputCorpus:\n count = 0\n for word in doc.split():\n if word in stopWords:\n count += 1\n stopWordsCount.append(count)\n return pd.Series(stopWordsCount)\n except:\n self.__Log(\"exception\", sys.exc_info())\n raise\n \n def MostCommonWords(self, inputCorpus, num_of_words=40):\n \"\"\" get the most common words in corpus\n Parameters\n ----------\n inputCorpus: sequence of input documents where each document consists of paragraphs or sentences\n Returns\n -------\n Pandas.DataFrame{string, int}\n Dataframe with columns \"most_common_words\" and \"freq\"\n \"\"\"\n try:\n self.__Log(\"info\", \"Start of {} function\".format(sys._getframe().f_code.co_name))\n new = inputCorpus.str.split()\n new = new.values.tolist()\n corpus = [word for i in new for word in i if word not in stopWords]\n counter = Counter(corpus)\n most = counter.most_common()\n \n x, y = [], []\n for word, count in most[: num_of_words + 1]:\n x.append(word)\n y.append(count)\n return pd.DataFrame([x, y],index=['most_common_words', 'freq']).T\n except:\n self.__Log(\"exception\", sys.exc_info())\n raise\n \n def NullCount(self, inputCorpus):\n \"\"\" Calculate the number of null entries in corpus\n Parameters\n ----------\n inputCorpus: sequence of input documents where each document consists of paragraphs or sentences\n Returns\n -------\n int\n count of null entries in corpus\n \"\"\"\n try:\n self.__Log(\"info\", \"Start of {} function\".format(sys._getframe().f_code.co_name))\n return pd.Series(inputCorpus.isnull().sum())\n except:\n self.__Log(\"exception\", sys.exc_info())\n raise\n \n def TopNgram(self, inputCorpus, ngram, num_of_words=10):\n \"\"\" Get the top words from the ngrams\n Parameters\n ----------\n inputCorpus: sequence of input documents where each document consists of paragraphs or sentences\n ngram: int\n ngram required\n num_of_words:int, optional\n numbers of words to be returned\n Returns\n -------\n Pandas.DataFrame{string, int}\n Dataframe with columns \"ngram_words\" and \"freq\"\n \"\"\"\n try:\n self.__Log(\"info\", \"Start of {} function\".format(sys._getframe().f_code.co_name))\n words = []\n for doc in inputCorpus:\n word = [w for w in word_tokenize(doc) if (w not in stopWords)]\n words.append(\" \".join(word))\n vec = CountVectorizer(ngram_range=(ngram, ngram)).fit(words)\n bag_of_words = vec.transform(inputCorpus)\n sum_words = bag_of_words.sum(axis=0)\n words_freq = [(word, sum_words[0, idx]) for word, idx in vec.vocabulary_.items()]\n words_freq = sorted(words_freq, key=lambda x: x[1], reverse=True)[:num_of_words]\n words = []\n frequency = []\n for word, freq in words_freq:\n words.append(word)\n frequency.append(freq)\n return pd.DataFrame([words, frequency],index=['ngram_words', 'freq']).T\n except:\n self.__Log(\"exception\", sys.exc_info())\n raise\n \n def Polarity(self, inputCorpus):\n \"\"\" Get the polarity of the text\n Parameters\n ----------\n inputCorpus: sequence of input documents where each document consists of paragraphs or sentences\n \n Returns\n -------\n pandas.Series {double}\n series of calculated polarity of the documents\n \"\"\"\n try:\n self.__Log(\"info\", \"Start of {} function\".format(sys._getframe().f_code.co_name))\n return inputCorpus.apply(lambda x: TextBlob(x).sentiment.polarity)\n except:\n self.__Log(\"exception\", sys.exc_info())\n raise\n \n def ReadabilityScore(self, inputCorpus):\n \"\"\" Get the Readability Score of the text\n Parameters\n ----------\n inputCorpus: sequence of input documents where each document consists of paragraphs or sentences\n \n Returns\n -------\n pandas.Series {double}\n series of calculated Readability Score of the documents\n \"\"\"\n import textstat\n try:\n self.__Log(\"info\", \"Start of {} function\".format(sys._getframe().f_code.co_name))\n \n if isinstance(inputCorpus, pd.Series):\n return pd.Series([textstat.flesch_reading_ease(text) for text in inputCorpus])\n else:\n return [textstat.flesch_reading_ease(inputCorpus)]\n except:\n self.__Log(\"exception\", sys.exc_info())\n raise\n \n def TagEntityCount(self, inputCorpus):\n \"\"\" Calculate the frequency of each entity present in documents\n Parameters\n ----------\n inputCorpus: sequence of input documents where each document consists of paragraphs or sentences\n \n Returns\n -------\n Pandas.DataFrame{string, int}\n Dataframe with columns \"entity\" and \"freq\"\n \"\"\"\n def ner(text):\n doc = nlp(text)\n return [X.label_ for X in doc.ents]\n \n try:\n self.__Log(\"info\", \"Start of {} function\".format(sys._getframe().f_code.co_name))\n nlp = spacy.load(\"en_core_web_sm\")\n \n ent = inputCorpus.apply(lambda x: ner(x))\n ent = [x for sub in ent for x in sub]\n \n counter = Counter(ent)\n count = counter.most_common()\n x, y = map(list, zip(*count))\n return pd.DataFrame([x, y],index=['entity', 'freq']).T\n except:\n self.__Log(\"exception\", sys.exc_info())\n raise\n \n def MostCommonTokenPerEntity(self, inputCorpus, entity=\"GPE\"):\n \"\"\" Get the frequency of most common words corresponding to the specified entity in documents\n Parameters\n ----------\n inputCorpus: sequence of input documents where each document consists of paragraphs or sentences\n \n entity: string, optional\n name of the entity corresponding to which words are counted\n Returns\n -------\n Pandas.DataFrame{string, int}\n Dataframe with columns \"token\" and \"freq\"\n \"\"\"\n \n def ner(text, ent):\n doc = nlp(text)\n return [X.text for X in doc.ents if X.label_ == ent]\n \n try:\n self.__Log(\"info\", \"Start of {} function\".format(sys._getframe().f_code.co_name))\n nlp = spacy.load(\"en_core_web_sm\")\n gpe = inputCorpus.apply(lambda x: ner(x, entity.upper()))\n gpe = [i for x in gpe for i in x]\n counter = Counter(gpe)\n \n x, y = map(list, zip(*counter.most_common(10)))\n return pd.DataFrame([x, y],index=['token', 'freq']).T\n except:\n self.__Log(\"exception\", sys.exc_info())\n raise\n \n def MostCommonPosTag(self, inputCorpus):\n \"\"\" Get the frequency of most common POS tag present in documents\n Parameters\n ----------\n inputCorpus: sequence of input documents where each document consists of paragraphs or sentences\n \n Returns\n -------\n Pandas.DataFrame{string, int}\n Dataframe with columns \"postag\" and \"freq\"\n \"\"\"\n def pos(text):\n pos = pos_tag(word_tokenize(text))\n pos = list(map(list, zip(*pos)))[1]\n return pos\n \n try:\n self.__Log(\"info\", \"Start of {} function\".format(sys._getframe().f_code.co_name))\n tags = inputCorpus.apply(lambda x: pos(x))\n tags = [x for l in tags for x in l]", "instruction": "", "output": "" }, { "input": "\n counter = Counter(tags)\n \n x, y = list(map(list, zip(*counter.most_common(7))))\n return pd.DataFrame([x, y],index=['postag', 'freq']).T\n except:\n self.__Log(\"exception\", sys.exc_info())\n raise\n \n def MostCommonWordsInPOSTag(self, inputCorpus, tag=\"NN\"):\n \"\"\" Get the frequency of most common words related to specified POS tag present in documents\n Parameters\n ----------\n inputCorpus: sequence of input documents where each document consists of paragraphs or sentences\n \n tag: string, optional\n POS tag corresponding to which words frequency will be calculated\n Returns\n -------\n Pandas.DataFrame{string, int}\n Dataframe with columns \"words\" and \"freq\"\n \"\"\"\n def get_POSTag(text, tag):\n adj = []\n pos = pos_tag(word_tokenize(text))\n for word, tg in pos:\n if tg == tag:\n adj.append(word)\n return adj\n \n try:\n self.__Log(\"info\", \"Start of {} function\".format(sys._getframe().f_code.co_name))\n words = inputCorpus.apply(lambda x: get_POSTag(x, tag.upper()))\n words = [x for l in words for x in l]\n counter = Counter(words)\n x = []\n y = []\n if len(counter):\n x, y = list(map(list, zip(*counter.most_common(7))))\n return pd.DataFrame([x, y],index=['words', 'freq']).T\n except:\n self.__Log(\"exception\", sys.exc_info())\n raise\n \n def __preprocessData(self, inputCorpus):\n \"\"\" Prepare the data for topic modelling\n \"\"\"\n try:\n self.__Log(\"info\", \"Start of {} function\".format(sys._getframe().f_code.co_name))\n corpus = []\n lem = WordNetLemmatizer()\n for doc in inputCorpus:\n words = [w for w in word_tokenize(doc) if (w not in stopWords)]\n words = [lem.lemmatize(w) for w in words if len(w) > 2]\n corpus.append(words)\n return corpus\n except:\n self.__Log(\"exception\", sys.exc_info())\n raise '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport numpy as np\nimport pandas as pd\nfrom nltk.tokenize import word_tokenize\n\n# Private function\ndef unitvec(vec):\n return vec / np.linalg.norm(vec)\n \ndef __word_average(vectors, sent, vector_size,key_to_index):\n \"\"\"\n Compute average word vector for a single doc/sentence.\n \"\"\"\n try:\n mean = []\n for word in sent:\n index = key_to_index.get( word, None)\n if index != None:\n mean.append( vectors[index] )\n if len(mean):\n return unitvec(np.array(mean).mean(axis=0))\n return np.zeros(vector_size)\n except:\n raise\n\n# Private function\ndef __word_average_list(vectors, docs, embed_size,key_to_index):\n \"\"\"\n Compute average word vector for multiple docs, where docs had been tokenized.\n \"\"\"\n try:\n return np.vstack([__word_average(vectors, sent, embed_size,key_to_index) for sent in docs])\n except:\n raise\n\ndef load_pretrained(path):\n df = pd.read_csv(path, index_col=0,sep=' ',quotechar = ' ' , header=None, skiprows=1,encoding_errors= 'replace')\n return len(df.columns), df\n \ndef get_model( df:pd.DataFrame):\n index_to_key = {k:v for k,v in enumerate(df.index)}\n key_to_index = {v:k for k,v in enumerate(df.index)}\n df = df.to_numpy()\n return df, index_to_key, key_to_index\n \ndef extractFeatureUsingPreTrainedModel(inputCorpus, pretrainedModelPath=None, loaded_model=False,key_to_index={}, embed_size=300):\n \"\"\"\n Extract feature vector from input Corpus using pretrained Vector model(word2vec,fasttext, glove(converted to word2vec format)\n \"\"\"\n try:\n if inputCorpus is None: \n return None\n else:\n if not pretrainedModelPath and ((isinstance(loaded_model, pd.DataFrame) and loaded_model.empty) or (not isinstance(loaded_model, pd.DataFrame) and not loaded_model)):\n inputCorpusWordVectors = None\n else:\n if (isinstance(loaded_model, pd.DataFrame) and not loaded_model.empty) or loaded_model:\n pretrainedModel = loaded_model\n else:\n embed_size, pretrainedModel = load_pretrained(pretrainedModelPath)\n pretrainedModel, index_to_key,key_to_index = get_model( pretrainedModel)\n if len(pretrainedModel):\n input_docs_tokens_list = [word_tokenize(inputDoc) for inputDoc in inputCorpus]\n inputCorpusWordVectors = __word_average_list(pretrainedModel, input_docs_tokens_list,embed_size,key_to_index)\n else:\n inputCorpusWordVectors = None\n return inputCorpusWordVectors\n except:\n raise \n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport logging\nfrom distutils.util import strtobool\nimport numpy as np\nimport pandas as pd\nfrom text import TextProcessing\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom pathlib import Path\n\nexternal_model = None\nexternal_model_type = None\n\ndef get_one_true_option(d, default_value):\n\tif isinstance(d, dict):\n\t\tfor k,v in d.items():\n\t\t\tif (isinstance(v, str) and v.lower() == 'true') or (isinstance(v, bool) and v == True):\n\t\t\t\treturn k\n\treturn default_value\n\n\nclass textProfiler():\n\t\t\n\tdef __init__(self):\n\t\tself.log = logging.getLogger('eion')\n\t\tself.embedder = None\n\t\tself.bert_embedder_size = 0\n\t\t\n\tdef textCleaning(self, textCorpus):\n\t\ttextProcessor = TextProcessing.TextProcessing()\n\t\ttextCorpus = textProcessor.transform(textCorpus)\n\t\treturn(textCorpus)\n\t\n\tdef sentense_encode(self, item):\n\t\treturn self.model.encode(item,show_progress_bar=False)\n\t\t\n\tdef get_embedding_size(self, model, config):\n\t\tif model in config.keys():\n\t\t\tconfig = config[model]\n\t\telse:\n\t\t\tconfig = {}\n\t\tmodel = model.lower()\n\t\tif model == 'glove':\n\t\t\tsize_map = {'default': 100, '50d': 50, '100d':100, '200d': 200, '300d':300}\n\t\t\tsize_enabled = get_one_true_option(config, 'default')\n\t\t\treturn size_map[size_enabled]\n\t\telif model == 'fasttext':\n\t\t\tsize_map = {'default': 300}\n\t\t\tsize_enabled = get_one_true_option(config, 'default')\n\t\t\treturn size_map[size_enabled]\n\t\telif model == 'latentsemanticanalysis':\n\t\t\tsize_map = {'default': 100, '50d': 50, '100d':100, '200d': 200, '300d':300,'500d':500,'700d':700,'1000d':1000}\n\t\t\tsize_enabled = get_one_true_option(config, 'default')\n\t\t\treturn size_map[size_enabled]\t\t\t\n\t\telif model in ['tf_idf', 'countvectors']:\n\t\t\treturn int(config.get('maxFeatures', 2000))\n\t\telse: # for word2vec\n\t\t\treturn 300\n\t\t\t\n\t\t\n\tdef cleaner(self, conf_json, pipeList, data_path=None):\n\t\tcleaning_kwargs = {}\n\t\ttextCleaning = conf_json.get('textCleaning')\n\t\tself.log.info(\"Text Preprocessing config: \",textCleaning)\n\t\tcleaning_kwargs['fRemoveNoise'] = strtobool(textCleaning.get('removeNoise', 'True'))\n\t\tcleaning_kwargs['fNormalize'] = strtobool(textCleaning.get('normalize', 'True'))\n\t\tcleaning_kwargs['fReplaceAcronym'] = strtobool(textCleaning.get('replaceAcronym', 'False'))\n\t\tcleaning_kwargs['fCorrectSpelling'] = strtobool(textCleaning.get('correctSpelling', 'False'))\n\t\tcleaning_kwargs['fRemoveStopwords'] = strtobool(textCleaning.get('removeStopwords', 'True'))\n\t\tcleaning_kwargs['fRemovePunctuation'] = strtobool(textCleaning.get('removePunctuation', 'True'))\n\t\tcleaning_kwargs['fRemoveNumericTokens'] = strtobool(textCleaning.get('removeNumericTokens', 'True'))\n\t\tcleaning_kwargs['normalizationMethod'] = get_one_true_option(textCleaning.get('normalizeMethod'),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'lemmatization').capitalize()\n\t\t\n\t\tremoveNoiseConfig = textCleaning.get('removeNoiseConfig')\n\t\tif type(removeNoiseConfig) is dict:\n\t\t\tcleaning_kwargs['removeNoise_fHtmlDecode'] = strtobool(removeNoiseConfig.get('decodeHTML', 'True'))\n\t\t\tcleaning_kwargs['removeNoise_fRemoveHyperLinks'] = strtobool(removeNoiseConfig.get('removeHyperLinks', 'True'))\n\t\t\tcleaning_kwargs['removeNoise_fRemoveMentions'] = strtobool(removeNoiseConfig.get('removeMentions', 'True'))\n\t\t\tcleaning_kwargs['removeNoise_fRemoveHashtags'] = strtobool(removeNoiseConfig.get('removeHashtags', 'True'))\n\t\t\tcleaning_kwargs['removeNoise_RemoveOrReplaceEmoji'] = 'remove' if strtobool(removeNoiseConfig.get('removeEmoji', 'True')) else 'replace'\n\t\t\tcleaning_kwargs['removeNoise_fUnicodeToAscii'] = strtobool(removeNoiseConfig.get('unicodeToAscii', 'True'))\n\t\t\tcleaning_kwargs['removeNoise_fRemoveNonAscii'] = strtobool(removeNoiseConfig.get('removeNonAscii', 'True'))\n\n\t\tacronymConfig = textCleaning.get('acronymConfig')\n\t\tif type(acronymConfig) is dict:\n\t\t\tcleaning_kwargs['acronymDict'] = acronymConfig.get('acronymDict', None)\n\t\t\n\t\tstopWordsConfig = textCleaning.get('stopWordsConfig')\n\t\tif type(stopWordsConfig) is dict:\n\t\t\tcleaning_kwargs['stopwordsList'] = stopWordsConfig.get('stopwordsList', '[]')\n\t\t\tif isinstance(cleaning_kwargs['stopwordsList'], str):\n\t\t\t\tif cleaning_kwargs['stopwordsList'] != '[]':\n\t\t\t\t\tcleaning_kwargs['stopwordsList'] = cleaning_kwargs['stopwordsList'][1:-1].split(',')\n\t\t\t\telse:\n\t\t\t\t\tcleaning_kwargs['stopwordsList'] = []\n\t\t\tcleaning_kwargs['extend_or_replace_stopwordslist'] = 'replace' if strtobool(stopWordsConfig.get('replace', 'True')) else 'extend'\n\t\tremoveNumericConfig = textCleaning.get('removeNumericConfig')\n\t\tif type(removeNumericConfig) is dict:\n\t\t\tcleaning_kwargs['removeNumeric_fIncludeSpecialCharacters'] = strtobool(removeNumericConfig.get('removeNumeric_IncludeSpecialCharacters', 'True'))\n\n\t\tremovePunctuationConfig = textCleaning.get('removePunctuationConfig')\n\t\tif type(removePunctuationConfig) is dict:\n\t\t\tcleaning_kwargs['fRemovePuncWithinTokens'] = strtobool(removePunctuationConfig.get('removePuncWithinTokens', 'False'))\n\t\t\n\t\tcleaning_kwargs['fExpandContractions'] = strtobool(textCleaning.get('expandContractions', 'False'))\n\n\t\tlibConfig = textCleaning.get('libConfig')\n\t\tif type(libConfig) is dict:\n\t\t\tcleaning_kwargs['tokenizationLib'] = get_one_true_option(libConfig.get('tokenizationLib'), 'nltk')\n\t\t\tcleaning_kwargs['lemmatizationLib'] = get_one_true_option(libConfig.get('lemmatizationLib'), 'nltk')\n\t\t\tcleaning_kwargs['stopwordsRemovalLib'] = get_one_true_option(libConfig.get('stopwordsRemovalLib'), 'nltk')\n\t\tif data_path:\n\t\t\tcleaning_kwargs['data_path'] = data_path\n\t\ttextProcessor = TextProcessing.TextProcessing(**cleaning_kwargs)\n\t\tpipeList.append((\"TextProcessing\",textProcessor))\n\n\t\ttextFeatureExtraction = conf_json.get('textFeatureExtraction')\n\t\tif strtobool(textFeatureExtraction.get('pos_tags', 'False')):\n\t\t\tpos_tags_lib = get_one_true_option(textFeatureExtraction.get('pos_tags_lib'), 'nltk')\n\t\t\tposTagger = TextProcessing.PosTagging( pos_tags_lib, data_path)\n\t\t\tpipeList.append((\"posTagger\",posTagger))\n\t\treturn pipeList\n\n\tdef embedding(self, conf_json, pipeList):\n\t\tngram_min = 1\n\t\tngram_max = 1\n\t\ttextFeatureExtraction = conf_json.get('textFeatureExtraction')\n\t\tif strtobool(textFeatureExtraction.get('n_grams', 'False')):\n\t\t\tn_grams_config = textFeatureExtraction.get(\"n_grams_config\")\n\t\t\tngram_min = int(n_grams_config.get('min_n', 1))\n\t\t\tngram_max = int(n_grams_config.get('max_n', 1))\n\t\t\tif (ngram_min < 1) or ngram_min > ngram_max:\n\t", "instruction": "", "output": "" }, { "input": "\t\t\tngram_min = 1\n\t\t\t\tngram_max = 1\n\t\t\t\tinvalidNgramWarning = 'WARNING : invalid ngram config.\\\\nUsing the default values min_n={}, max_n={}'.format(ngram_min, ngram_max)\n\t\t\t\tself.log.info(invalidNgramWarning)\n\t\tngram_range_tuple = (ngram_min, ngram_max)\n\t\ttextConversionMethod = conf_json.get('textConversionMethod')\n\t\tconversion_method = get_one_true_option(textConversionMethod, None)\n\t\tembedding_size_config = conf_json.get('embeddingSize', {})\n\t\tembedding_size = self.get_embedding_size(conversion_method, embedding_size_config)\n\t\tif conversion_method.lower() == \"countvectors\":\n\t\t\tvectorizer = TextProcessing.ExtractFeatureCountVectors( ngram_range=ngram_range_tuple,max_features=embedding_size)\n\t\t\tpipeList.append((\"vectorizer\",vectorizer))\n\t\t\tself.log.info('----------> Conversion Method: CountVectors')\n\t\telif conversion_method.lower() in [\"fasttext\",\"glove\"]:\n\t\t\tembedding_method = conversion_method\n\t\t\twordEmbeddingVecotrizer = TextProcessing.wordEmbedding(embedding_method, embedding_size)\n\t\t\tpipeList.append((\"vectorizer\",wordEmbeddingVecotrizer))\n\t\t\tself.log.info('----------> Conversion Method: '+str(conversion_method))\n\t\telif conversion_method.lower() == \"openai\":\n\t\t\tfrom text.openai_embedding import embedding as openai_embedder\n\t\t\tvectorizer = openai_embedder()\n\t\t\tpipeList.append((\"vectorizer\",vectorizer))\n\t\t\tself.log.info('----------> Conversion Method: '+str(conversion_method)) \n\t\telif conversion_method.lower() == \"sentencetransformer_distilroberta\":\n\t\t\tfrom sentence_transformers import SentenceTransformer\n\t\t\tembedding_pretrained = {'model':'sentence-transformers/msmarco-distilroberta-base-v2','size': 768}\n\t\t\tself.bert_embedder_size = embedding_pretrained['size']\n\t\t\tself.model = SentenceTransformer(embedding_pretrained['model'])\n\t\t\tself.embedder = FunctionTransformer(self.sentense_encode, feature_names_out = self.sentence_transformer_output)\n\t\t\tpipeList.append((\"vectorizer\",self.embedder))\n\t\t\tself.log.info('----------> Conversion Method: SentenceTransformer using msmarco_distilroberta')\n\t\t\n\t\telif conversion_method.lower() == \"sentencetransformer_minilm\":\n\t\t\tfrom sentence_transformers import SentenceTransformer\n\t\t\tembedding_pretrained = {'model':'sentence-transformers/all-MiniLM-L6-v2','size': 384}\n\t\t\tself.bert_embedder_size = embedding_pretrained['size']\n\t\t\tself.model = SentenceTransformer(embedding_pretrained['model'])\n\t\t\tself.embedder = FunctionTransformer(self.sentense_encode, feature_names_out = self.sentence_transformer_output)\n\t\t\tpipeList.append((\"vectorizer\",self.embedder))\n\t\t\tself.log.info('----------> Conversion Method: SentenceTransformer using MiniLM-L6-v2')\n\t\t\t\n\t\telif conversion_method.lower() == \"sentencetransformer_mpnet\":\n\t\t\tfrom sentence_transformers import SentenceTransformer\n\t\t\tembedding_pretrained = {'model':'sentence-transformers/all-mpnet-base-v2','size': 768}\n\t\t\tself.bert_embedder_size = embedding_pretrained['size']\n\t\t\tself.model = SentenceTransformer(embedding_pretrained['model'])\n\t\t\tself.embedder = FunctionTransformer(self.sentense_encode, feature_names_out = self.sentence_transformer_output)\n\t\t\tpipeList.append((\"vectorizer\",self.embedder))\n\t\t\tself.log.info('----------> Conversion Method: SentenceTransformer using mpnet-base-v2')\n\t\t\t\n\t\telif conversion_method.lower() == 'latentsemanticanalysis':\n\t\t\tvectorizer = TextProcessing.ExtractFeatureTfIdfVectors(ngram_range=ngram_range_tuple)\n\t\t\tpipeList.append((\"vectorizer\",vectorizer))\n\t\t\tself.log.info('----------> Conversion Method: latentsemanticanalysis')\n\t\telif conversion_method.lower() == 'tf_idf':\n\t\t\tvectorizer = TextProcessing.ExtractFeatureTfIdfVectors(ngram_range=ngram_range_tuple,max_features=embedding_size)\n\t\t\tpipeList.append((\"vectorizer\",vectorizer))\n\t\t\tself.log.info('----------> Conversion Method: TF_IDF')\n\t\telse:\n\t\t\tdf1 = pd.DataFrame()\n\t\t\t#df1['tokenize'] = textCorpus\n\t\t\tself.log.info('----------> Conversion Method: '+str(conversion_method)) \n\t\treturn pipeList\n\n\tdef sentence_transformer_output(self, transformer, names=None):\n\t\treturn [str(x) for x in range(self.bert_embedder_size)]\n\t\t\n\nclass textCombine(TransformerMixin):\n\tdef __init__(self):\n\t\tpass\n\tdef fit(self, X, y=None):\n\t\treturn self\n\tdef transform(self, X):\n\t\tif X.shape[1] > 1:\n\t\t\treturn np.array([\" \".join(i) for i in X])\n\t\telse:\n\t\t\tif isinstance(X, np.ndarray):\n\t\t\t\treturn np.ndarray.flatten(X)\n\t\t\telse: \n\t\t\t\treturn X\n\ndef get_pretrained_model_path():\n\ttry:\n\t\tfrom appbe.dataPath import DATA_DIR\n\t\tmodelsPath = Path(DATA_DIR)/'PreTrainedModels'/'TextProcessing'\n\texcept:\n\t\tmodelsPath = Path('aion')/'PreTrainedModels'/'TextProcessing'\n\t\n\tif not modelsPath.exists():\n\t\tmodelsPath.mkdir(parents=True, exist_ok=True)\n\treturn modelsPath\n\t\ndef set_pretrained_model(pipe):\n\tfrom text.Embedding import load_pretrained\n\timport importlib.util\n\tglobal external_model\n\tglobal external_model_type\n\tparams = pipe.get_params()\n\tmodel_name = params.get('text_process__vectorizer__preTrainedModel', None)\n\tif model_name and model_name.lower() in ['fasttext','glove'] and not external_model:\n\t\tif model_name == 'fasttext' and importlib.util.find_spec('fasttext'):\n\t\t\timport fasttext\n\t\t\timport fasttext.util\n\t\t\tcwd = os.getcwd()\n\t\t\tos.chdir(get_pretrained_model_path())\n\t\t\tfasttext.util.download_model('en', if_exists='ignore')\n\t\t\texternal_model = fasttext.load_model('cc.en.300.bin')\n\t\t\tos.chdir(cwd)\n\t\t\texternal_model_type = 'binary'\n\t\t\tprint('loaded fasttext binary')\n\t\telse:\n\t\t\tmodel_path = TextProcessing.checkAndDownloadPretrainedModel(model_name)\n\t\t\tembed_size, external_model = load_pretrained(model_path)\n\t\t\texternal_model_type = 'vector'\n\t\t\tprint(f'loaded {model_name} vector')\n\t\tpipe.set_params(text_process__vectorizer__external_model = external_model)\n\t\tpipe.set_params(text_process__vectorizer__external_model_type = external_model_type)\n\ndef reset_pretrained_model(pipe, clear_mem=True):\n\tglobal external_model\n\tglobal external_model_type\n\tparams = pipe.get_params()\n\tis_external_model = params.get('text_process__vectorizer__external_model', None)\n\tif (isinstance(is_external_model, pd.DataFrame) and not is_external_model.empty) or is_external_model:\n\t\tpipe.set_params(text_process__vectorizer__external_model = None)\n\t\tpipe.set_params(text_process__vectorizer__external_model_type = None)\n\t\tif clear_mem:\n\t\t\texternal_model = None\n\ndef release_pretrained_model():\n\tglobal external_model\n\tglobal external_model_type\n\texternal_model = None\n\texternal_model_type = None\n\t '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport sys\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__))))\n#from .eda import ExploreTextData '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\n\nimport numpy as np\nimport logging\nimport warnings\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.linear_model import Ridge\nfrom sklearn.preprocessing import binarize\nfrom sklearn.ensemble import VotingRegressor\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nfrom learner.aion_matrix import aion_matrix\nwarnings.filterwarnings('always') \n\n\n\n\nclass ensemble_voting():\n\tdef __init__(self,ensemble_params,scoreParam): \n\t\tself.ensemble_params = ensemble_params\n\t\tself.scoreParam=scoreParam\n\t\tself.final_estimator_r=''\n\t\tself.final_estimator_c=''\n\t\tself.log = logging.getLogger('eion')\n\t''' Read the aion config \"Ensemble-Voting\", parse the algorithm and associated params based on enable or True status.Not used now '''\n\tdef getSelected_algs_params(self,problemType,ensembleType,ensembleConfig):\n\t\tfrom learner.parameters import parametersDefine\n\t\tparamObj=parametersDefine()\n\t\tensClass_algs_params={}\n\t\t# algs_status={}\n\t\tfor key,val in ensembleConfig.items():\n\t\t\tfor s,p in val.items():\n\t\t\t\t\n\t\t\t\tif (s == \"enable\" and p == \"True\"): \n\t\t\t\t\tparams = val['param'] \n\t\t\t\t\tparams_eval = paramObj.paramDefine(params,None)\n\t\t\t\t\tparams_eval = {param_key: param_value[0] for param_key, param_value in params_eval.items()}\n\t\t\t\t\tensClass_algs_params[key]=params_eval\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\treturn ensClass_algs_params\n\t\n\t''' To make array of voting algorithm based on user config list. Not used now, in future if needed similar line with bagging ensemble, please use this. '''\n\tdef listEnsembleClassVotingAlgs(self,ensClass_algs_params):\n\t\tensembleVotingClassList=list()\n\t\tfor key,val in ensClass_algs_params.items():\n\t\t\tif (key == 'Logistic Regression'):\n\t\t\t\tlr=LogisticRegression()\n\t\t\t\tlr=lr.set_params(**val)\n\t\t\t\tensembleVotingClassList.append(lr)\n\t\t\t\t\n\t\t\telif (key == 'Support Vector Machine'):\n\t\t\t\tsvm=SVC()\n\t\t\t\tsvm=svm.set_params(**val)\n\t\t\t\tensembleVotingClassList.append(svm)\n\t\t\t\t\n\t\t\telif (key == 'Naive Bayes'):\n\t\t\t\tnb=GaussianNB()\n\t\t\t\tnb=nb.set_params(**val)\n\t\t\t\tensembleVotingClassList.append(nb)\n\t\t\t\t\n\t\t\telif (key == 'K Nearest Neighbors'):\n\t\t\t\tknn=KNeighborsClassifier()\n\t\t\t\tknn=knn.set_params(**val)\n\t\t\t\tensembleVotingClassList.append(knn)\n\t\t\t\t\n\t\t\telif (key == 'Decision Tree'):\n\t\t\t\tdt=DecisionTreeClassifier()\n\t\t\t\tdt=dt.set_params(**val)\n\t\t\t\tensembleVotingClassList.append(dt)\n\t\t\t\t\n\t\t\t\t\n\t\t\telif (key == 'Random Forest'):\n\t\t\t\trf=RandomForestClassifier()\n\t\t\t\trf=rf.set_params(**val)\n\t\t\t\tensembleVotingClassList.append(rf)\n\t\t\t\t\n\t\t\telse:\n\t\t\t\t## Algorithm not found in config, so forming empty alg list. If needs, make list with default alg.\n\t\t\t\tensembleVotingClassList=[]\n\t\t\t\tpass\n\t\t\t\n\t\treturn ensembleVotingClassList\n\t\n\t''' To make array of voting regression algorithm based on user config list. Not used now, in future if needed similar line with bagging ensemble, please use this. '''\n\tdef listEnsembleRegVotingAlgs(self,ensReg_algs_params):\n\t\t\t\n\t\t\tensembleVotingRegList=list()\n\t\t\tfor key,val in ensReg_algs_params.items():\n\t\t\t\tif (key == 'Linear Regression'):\n\t\t\t\t\tlir=LinearRegression()\n\t\t\t\t\tlir=lir.set_params(**val)\n\t\t\t\t\tensembleVotingRegList.append(lir)\n\t\t\t\telif (key == 'Decision Tree'):\n\t\t\t\t\tdtr=DecisionTreeRegressor()\n\t\t\t\t\tdtr=dtr.set_params(**val)\n\t\t\t\t\tensembleVotingRegList.append(dtr)\n\t\t\t\telif (key == 'Ridge'):\n\t\t\t\t\tridge=Ridge()\n\t\t\t\t\tridge=ridge.set_params(**val)\n\t\t\t\t\tensembleVotingRegList.append(ridge)\n\t\t\t\telse:\n\t\t\t\t\t## Algorithm not found in config, so forming empty alg list. If needs, make list with default alg.\n\t\t\t\t\tensembleVotingRegList=[] \n\t\t\t\t\n\t\t\treturn ensembleVotingRegList\n\t\t\n\n\t\t\n\tdef ensemble_voting_classifier(self,X_train,y_train, X_test, y_test,MakeFP0,MakeFN0,modelList): \n\t\t#bug 12437\n\t\tstatus='ERROR' \n\t\tmodel=None\n\t\testimator=None\n\t\tscore=", "instruction": "", "output": "" }, { "input": "None\n\t\tparams=None\n\t\tthreshold = -1\n\t\tprecisionscore =-1\n\t\trecallscore = -1 \n\t\tobjClf = aion_matrix()\n\t\ttry:\n\t\t\tlr = LogisticRegression(solver='lbfgs',random_state=1,max_iter=200) \n\t\t\trf = RandomForestClassifier(random_state=1)\n\t\t\tgnb = GaussianNB()\n\t\t\tsvc = SVC(probability=True) #Need to keep probability=True, because cross_val_score,predict_proba fn calls\n\t\t\tknn=KNeighborsClassifier(n_neighbors=5)\n\t\t\tbase_estimators = []\n\t\t\tif 'Logistic Regression' in modelList:\n\t\t\t\tbase_estimators.append(('LogisticRegression', lr))\n\t\t\t\tself.log.info('-------- Ensemble: Logistic Regression-------')\n\t\t\tif 'Random Forest' in modelList:\n\t\t\t\tbase_estimators.append(('RandomForestClassifier', rf)) \n\t\t\t\tself.log.info('-------- Ensemble: Random Forest-------')\n\t\t\tif 'Naive Bayes' in modelList:\n\t\t\t\tbase_estimators.append(('GaussianNB', gnb))\n\t\t\t\tself.log.info('-------- Ensemble: Naive Bayes-------')\n\t\t\tif 'Support Vector Machine' in modelList:\n\t\t\t\tself.log.info('-------- Ensemble: Support Vector Machine-------')\n\t\t\t\tbase_estimators.append(('SVC', svc))\n\t\t\tif 'K Nearest Neighbors' in modelList:\n\t\t\t\tbase_estimators.append(('KNeighborsClassifier', knn)) \n\t\t\t\tself.log.info('-------- Ensemble: K Nearest Neighbors-------') \n\t\t\tif len(base_estimators) == 0:\n\t\t\t\tself.log.info('-------- Ensemble Voting is only supported for Logistic Regression, Random Forest Classifier, Naive Bayes, SVM and KNN -------')\n\t\t\t\tstatus = \"UNSUPPORTED\"\n\t\t\t\treturn status, estimator,params,score,model,threshold,precisionscore,recallscore \n\t\t\teclf1 = VotingClassifier(base_estimators, voting='soft') \n\t\t\teclf1.fit(X_train, y_train)\n\t\t\ty_predict = eclf1.predict(X_test)\n\t\t\tscore = objClf.get_score(self.scoreParam,y_test,y_predict) \n\t\t\tself.log.info('-------- Ensemble (VoteClassifier) Soft Score:'+str(score)) \n\t\t\tif MakeFP0:\n\t\t\t\tself.log.info('-------- Ensemble: Calculate Threshold for FP Start-------')\n\t\t\t\tstartRange = 0.0\n\t\t\t\tendRange = 1.0\n\t\t\t\tstepsize = 0.01\n\t\t\t\tthreshold_range = np.arange(startRange,endRange,stepsize)\n\t\t\t\tthreshold,precisionscore,recallscore = objClf.check_threshold(eclf1,X_train,y_train,threshold_range,'FP','')\n\t\t\t\tself.log.info('-------- Calculate Threshold for FP End-------')\n\t\t\telif MakeFN0:\t\t\t\t\t\t\t\n\t\t\t\tself.log.info('-------- Ensemble: Calculate Threshold for FN Start-------')\n\t\t\t\tstartRange = 1.0\n\t\t\t\tendRange = 0.0\n\t\t\t\tstepsize = -0.01\n\t\t\t\tthreshold_range = np.arange(startRange,endRange,stepsize)\n\t\t\t\tthreshold,precisionscore,recallscore = objClf.check_threshold(eclf1,X_train,y_train,threshold_range,'FN','')\n\t\t\t\tself.log.info('-------- Calculate Threshold for FN End-------')\n\t\t\t\n\t\t\tif threshold != -1:\n\t\t\t\tpredictedData = eclf1.predict_proba(X_test)\n\t\t\t\tpredictedData = binarize(predictedData[:,1].reshape(-1, 1),threshold=threshold)\t\t#bug 12437\t\t\t\t\t\n\t\t\t\tscore = objClf.get_score(self.scoreParam,y_test,predictedData)\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\tstatus = 'SUCCESS'\n\t\t\tmodel =eclf1.__class__.__name__\n\t\t\testimator=eclf1\n\t\t\tparams = estimator.get_params() \n\t\t\t\n\t\t\t#bug 12437 - Removed ensemble hard voting as predict_proba in the later stages will break\t\t\t\t\t\t\n\t\texcept Exception as Inst: #bug 12437\n\t\t\tself.log.info('--------- Error in Ensemble Voting ---------\\\\n') \n\t\t\tself.log.info(str(Inst))\n\t\treturn status,estimator,params,score,model,threshold,precisionscore,recallscore\n\t\t\n\tdef ensemble_voting__regressor(self,X_train,y_train, X_test, y_test,modelList):\n\t\tscoredetails = ''\n\t\tvr_predict=None\n\t\tvr_model=None\n\t\ttry:\n\t\t\tlr = LinearRegression()\n\t\t\trfr = RandomForestRegressor(n_estimators=10, random_state=1)\n\t\t\tdtr=DecisionTreeRegressor()\n\t\t\tbase_estimators = []\n\t\t\tif 'Linear Regression' in modelList:\n\t\t\t\tbase_estimators.append(('LinearRegression', lr))\n\t\t\tif 'Decision Tree' in modelList:\n\t\t\t\tbase_estimators.append(('DecisionTreeRegressor', dtr)) \n\t\t\tif 'Random Forest' in modelList:\n\t\t\t\tbase_estimators.append(('RandomForestRegressor', rfr)) \n\t\t\tif len(base_estimators) == 0: \n\t\t\t\tbase_estimators = [('LinearRegression', lr), ('RandomForestRegressor', rfr),('DecisionTreeRegressor', dtr)]\n\t\t\tvoting_reg = VotingRegressor(base_estimators)\n\t\t\tvr_model=voting_reg.fit(X_train,y_train)\n\t\t\tvr_predict=voting_reg.predict(X_test) \n\t\t\tbest_vr_alg=voting_reg.__class__.__name__\n\t\t\tself.log.info('-----------> Voting regression Model '+str(best_vr_alg))\t\n\n\t\texcept Exception as e:\n\t\t\tself.log.info(\"voting regression Exception info: \\\\n\")\n\t\t\tself.log.info(e)\n\t\t\t\n\t\taion_matrixobj = aion_matrix() \n\t\tscore = aion_matrixobj.get_score(self.scoreParam,y_test,vr_predict)\n\t\t \n\t\treturn voting_reg,voting_reg.get_params(),score,best_vr_alg \n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport numpy as np\n#Classification metrics lib\n\nimport logging\nimport warnings\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.preprocessing import binarize\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import StackingClassifier\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import StackingRegressor\nfrom sklearn.svm import LinearSVR\nfrom sklearn.linear_model import RidgeCV\nfrom sklearn.linear_model import LassoCV\nfrom learner.aion_matrix import aion_matrix\n\nwarnings.filterwarnings('always') # \"error\", \"ignore\", \"always\", \"default\", \"module\" or \"once\"\n\n\n\nclass ensemble_stacking():\n def __init__(self,ensemble_params,scoreParam): \n self.ensemble_params = ensemble_params\n self.scoreParam=scoreParam\n self.final_estimator_r=''\n self.final_estimator_c=''\n self.log = logging.getLogger('eion')\n\n \n ## Read the aion config \"Ensemble-Stacking\", parse the algorithm and associated params based on enable or True status.\n def getSelected_algs_params(self,problemType,ensembleType,ensembleConfig):\n from learner.parameters import parametersDefine\n paramObj=parametersDefine()\n ensClass_algs_params={}\n # algs_status={}\n for key,val in ensembleConfig.items():\n for s,p in val.items():\n if (s == \"enable\" and p == \"True\"): \n params = val['param'] \n params_eval = paramObj.paramDefine(params,None)\n params_eval = {param_key: param_value[0] for param_key, param_value in params_eval.items()}\n ensClass_algs_params[key]=params_eval\n else:\n pass \n\n return ensClass_algs_params\n \n ## To make array of stacking algorithm based on user config list. Not used now, in future if needed similar line with bagging ensemble, please use this.\n \n def listEnsembleClassStackingAlgs(self,ensClass_algs_params):\n\n ensembleBaggingClassList=list()\n for key,val in ensClass_algs_params.items():\n # print(key)\n if (key == 'Logistic Regression'):\n lr=LogisticRegression()\n lr=lr.set_params(**val)\n ensembleBaggingClassList.append(lr)\n \n elif (key == 'Support Vector Machine'):\n svm=SVC()\n svm=svm.set_params(**val)\n ensembleBaggingClassList.append(svm)\n \n elif (key == 'Naive Bayes'):\n nb=GaussianNB()\n nb=nb.set_params(**val)\n ensembleBaggingClassList.append(nb)\n \n elif (key == 'K Nearest Neighbors'):\n knn=KNeighborsClassifier()\n knn=knn.set_params(**val)\n ensembleBaggingClassList.append(knn)\n \n elif (key == 'Decision Tree'):\n dt=DecisionTreeClassifier()\n dt=dt.set_params(**val)\n ensembleBaggingClassList.append(dt)\n \n \n elif (key == 'Random Forest'):\n rf=RandomForestClassifier()\n rf=rf.set_params(**val)\n ensembleBaggingClassList.append(rf)\n \n else:\n ensembleBaggingClassList=[]\n pass\n \n \n return ensembleBaggingClassList\n \n\n ## To make array of stacking regression algorithm based on user config list. Not used now, in future if needed similar line with bagging ensemble, please use this.\n \n def listEnsembleRegStackingAlgs(self,ensReg_algs_params):\n \n ensembleBaggingRegList=list()\n for key,val in ensReg_algs_params.items():\n if (key == 'LinearSVR'):\n lir=LinearSVR()\n lir=lir.set_params(**val)\n ensembleBaggingRegList.append(lir)\n elif (key == 'LinearRegression'):\n lr=LinearRegression()\n lr=lr.set_params(**val)\n ensembleBaggingRegList.append(lr) \n elif (key == 'LassoCV'):\n lcv=LassoCV()\n lcv=lcv.set_params(**val)\n ensembleBaggingRegList.append(lcv)\n elif (key == 'RandomForestRegressor'):\n rfr=RandomForestRegressor()\n rfr=rfr.set_params(**val)\n ensembleBaggingRegList.append(rfr) \n elif (key == 'RidgeCV'):\n ridge=RidgeCV()\n ridge=ridge.set_params(**val)\n ensembleBaggingRegList.append(ridge) \n \n else:\n ## NO algorithms found in configuration settings, instead of sending empty array,we can add any one of algorithms.\n ensembleBaggingRegList=[] \n \n return ensembleBaggingRegList\n \n def extract_params(self,dict):\n self.dict=dict\n for k,v in self.dict.items():\n return k,v\n \n def stacking_params(self):\n for k,v in self.ensemble_params.items():\n try:\n if (k == \"max_features_percentage\"):\n max_features_percentage=float(v)\n elif (k == \"max_samples\"):\n max_samples=float(v)\n elif (k == \"seed\"):\n seed=int(v)\n elif (k == \"final_estimator_stack_c\"):\n final_estimator_c=str(v)\n elif (k == \"final_estimator_stack_r\"):\n final_estimator_r=str(v)\n else:\n self.log.info(\"Invalid Param in ensemble advanced configuration.\\\\n\")\n except Exception as e:\n self.log.info(\"\\\\n Ensemble config param parsing error\"+str(e))\n continue\n return final_estimator_c,final_estimator_r,seed,max_samples,max_features_percentage\n \n def ensemble_stacking_classifier(self,X_train,y_train, X_test, y_test,MakeFP0,MakeFN0,modelList):\n \n final_estimator_c,final_estimator_r,seed,max_samples,max_features_percentage= self.stacking_params()\n final_estimator_c=\"\"\n final_estimator=final_estimator_c \n scoredetails=''\n lr = LogisticRegression(solver='lbfgs',random_state=1,max_iter=200) \n rf = RandomForestClassifier(random_state=2)\n gnb = GaussianNB()\n svc = SVC(probability=True) #Need to keep probability=True, because of cross_val_score,predict_proba fn calls\n knn=KNeighborsClassifier(n_neighbors=5)\n \n try:\n if (final_estimator == 'LogisticRegression'):\n final_estimator_a=lr\n elif (final_estimator == 'RandomForestClassifier'):\n final_estimator_a=rf\n elif (final_estimator == 'GaussianNB'):\n final_estimator_a=gnb\n elif (final_estimator == 'SVC'):\n final_estimator_a=svc\n elif (final_estimator == 'KNeighborsClassifier'):\n final_estimator_a=knn\n else:\n final_estimator_a", "instruction": "", "output": "" }, { "input": "#NAME?", "instruction": "", "output": "" }, { "input": " MakeFP0 = True\n self.log.info('-------- Calculate Threshold for FP End-------')\n if self.MakeFN0:\t\t\t\t\t\t\t\n self.log.info('-------- Ensemble: Calculate Threshold for FN Start-------')\n startRange = 1.0\n endRange = 0.0\n stepsize = -0.01\n threshold_range = np.arange(startRange,endRange,stepsize)\n threshold,precisionscore,recallscore = objClf.check_threshold(bagging_clf,X_train,y_train,threshold_range,'FN','')\n MakeFN0 = True \n self.log.info('-------- Calculate Threshold for FN End-------')\n\t\t\t\t\t\t\n if threshold != -1:\n if not X_test.empty:\n predictedData = bagging_clf.predict_proba(X_test)\n predictedData = binarize(predictedData[:,1].reshape(-1, 1),threshold=threshold)\t\t#bug 12437\t\t\t\t\t\n accuracy_score_test = objClf.get_score(self.scoreParam,y_test,predictedData)\n\t\t\t\t\t\t\t\n status,bscore,bthres,brscore,bpscore = objClf.getBestModel(MakeFP0,MakeFN0,threshold,bestthreshold,recallscore,bestrecallscore,precisionscore,bestprecisionscore,accuracy_score_test,bestScore)\n if status:\n bestScore =bscore\n bestModel =bagging_clf.__class__.__name__\n bestEstimator=bagging_clf\n bestthreshold = bthres\n bestBaseModel = clf.__class__.__name__\n bestrecallscore = brscore\n bestprecisionscore = bpscore\n else:\n pass\n\n best_alg_name=bestEstimator.__class__.__name__\n self.log.info('-----------> Best Bagging Classifier Model '+str(bestBaseModel))\t\t\n self.log.info('-----------> Best Score '+str(bestScore))\n # self.log.info('-----------> Threshold '+str(bestthreshold)) #bug 12438\n if bestthreshold != -1:\n if not X_test.empty:\n predictedData_test = bestEstimator.predict_proba(X_test)\n predictedData_test = binarize(predictedData_test[:,1].reshape(-1, 1),threshold=bestthreshold)\t\t#bug 12437\t\t\t\t\t\n predictedData_train = bestEstimator.predict_proba(X_train)\n predictedData_train = binarize(predictedData_train[:,1].reshape(-1, 1),threshold=bestthreshold)\t\t#bug 12437\t\t\t\t\t\n else:\n if not X_test.empty:\n predictedData_test = bestEstimator.predict(X_test)\n predictedData_train = bestEstimator.predict(X_train)\n \n return bestEstimator,bestEstimator.get_params(),bestScore,best_alg_name,bestthreshold,bestprecisionscore,bestrecallscore\n \n \n def ensemble_bagging__regressor(self,X_train,y_train, X_test, y_test):\n from sklearn.ensemble import BaggingRegressor\n ensemble_method='Bagging_regressor'\n problemType='regression'\n ensembleType='bagging'\n model_dict=self.ensemble_params\n ensReg_algs_params = self.getSelected_algs_params(problemType,ensembleType,model_dict)\n ensembleBaggingList = self.listEnsembleRegBaggingAlgs(ensReg_algs_params)\n \n scoredetails = ''\n aion_matrixobj = aion_matrix()\n reg_array = ensembleBaggingList\n \n num_trees = len(reg_array)\n #self.log.info(num_trees)\n # max_samples=float(max_samples)\n n_estimators = num_trees\n r_state=10 \n \n bestModel=''\n bestParams={}\n bestScore=-sys.float_info.max #extension of bugfix 11656\n objClf = aion_matrix()\n for reg in reg_array:\n self.log.info('-----------> Ensemble Algorithm '+str(reg.__class__.__name__))\n nmodel=reg.fit(X_train, y_train)\n model = reg.__class__.__name__\n estimator = BaggingRegressor(base_estimator=reg, random_state=r_state) \n bagging_ensemble_t=estimator.fit(X_train, y_train)\n predictedData = estimator.predict(X_test)\n score = objClf.get_score(self.scoreParam,y_test,predictedData)\n if self.scoreParam == \"r2\":\n if score > bestScore:\n bestScore =score\n bestModel =model\n bestEstimator=estimator\n else:\n if abs(score) < bestScore or bestScore == -sys.float_info.max: #extension of bugfix 11656\n bestScore =abs(score)\n bestModel =model\n bestEstimator=estimator\n best_alg_name=bestEstimator.__class__.__name__\n self.log.info('-----------> Best Ensemble Algorithm '+str(bestModel))\t\t\n return bestEstimator,bestEstimator.get_params(),bestScore,best_alg_name\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n''' '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport logging\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.preprocessing import LabelBinarizer\nfrom imblearn.over_sampling import RandomOverSampler,SMOTE\nfrom imblearn.under_sampling import RandomUnderSampler\nfrom imblearn.under_sampling import TomekLinks\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_absolute_error,make_scorer\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import log_loss\nimport tensorflow as tf\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.models import load_model\nfrom dlearning.Classification import DLClassificationModel\nfrom dlearning.Regression import DLRegressionModel\nfrom learner.machinelearning import machinelearning\nfrom sklearn.metrics import matthews_corrcoef, brier_score_loss\nimport os\ndef recall_m(y_true, y_pred):\n\ttrue_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n\tpossible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n\trecall = true_positives / (possible_positives + K.epsilon())\n\treturn recall\n\t\ndef precision_m(y_true, y_pred):\n\ttrue_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n\tpredicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n\tprecision = true_positives / (predicted_positives + K.epsilon())\n\treturn precision\n\ndef f1_m(y_true, y_pred):\n\tprecision = precision_m(y_true, y_pred)\n\trecall = recall_m(y_true, y_pred)\n\treturn 2*((precision*recall)/(precision+recall+K.epsilon()))\n\t\n\ndef rmse_m(y_true, y_pred):\n\treturn K.sqrt(K.mean(K.square(y_pred - y_true), axis=-1))\n\ndef r_square(y_true, y_pred):\n\tSS_res = K.sum(K.square(y_true-y_pred))\n\tSS_tot = K.sum(K.square(y_true-K.mean(y_true)))\n\treturn (1 - SS_res/(SS_tot+K.epsilon()))\n\n\nclass deeplearning(object):\n\tdef __init__(self):\n\t\tself.log = logging.getLogger('eion')\n\t\n\tdef getDLPredictionData(self,model_dl,hist_reloaded,X):\n\t\tif model_dl == \"Neural Network\":\n\t\t\tXSNN = X.values\n\t\t\tpredictedData = hist_reloaded.predict(XSNN)\n\t\telse:\n\t\t\tX1 = np.expand_dims(X, axis=2)\n\t\t\tpredictedData = hist_reloaded.predict(X1)\n\t\treturn(predictedData)\n\t\t\n\tdef getPredictionData(self,model_dl,hist_reloaded,X):\n\t\tif model_dl == \"Neural Network\":\n\t\t\tXSNN = X.values\n\t\t\t#predictedData = hist_reloaded.predict_classes(XSNN)\n\t\t\tpredict_x=hist_reloaded.predict(XSNN) \n\t\t\tpredictedData=np.argmax(predict_x,axis=1)\n\t\telse:\n\t\t\tX1 = np.expand_dims(X, axis=2)\n\t\t\t#predictedData = hist_reloaded.predict_classes(X1)\n\t\t\tpredict_x=hist_reloaded.predict(X1) \n\t\t\tpredictedData=np.argmax(predict_x,axis=1)\n\t\treturn(predictedData, predict_x)\t\n\t\n\tdef LoadDL_Regression_Model(self,filename_dl,scoreParam,loss_matrix,optimizer):\n\t\tif(scoreParam.lower() == 'rmse'):\n\t\t\thist_reloaded = load_model(filename_dl,custom_objects={\"rmse\": rmse_m},compile=False)\n\t\t\thist_reloaded.compile(loss=loss_matrix,optimizer=optimizer, metrics=[rmse_m])\n\t\telif(scoreParam.lower() == 'r2'):\n\t\t\thist_reloaded = load_model(filename_dl,custom_objects={\"r2\": r_square},compile=False)\n\t\t\thist_reloaded.compile(loss=loss_matrix,optimizer=optimizer, metrics=[r_square])\n\t\telse:\n\t\t\thist_reloaded = load_model(filename_dl)\t\t\n\t\treturn(hist_reloaded)\n\t\n\n\tdef startLearning(self,model_type,modelList, modelParams, scoreParam, cvSplit, xtrain,ytrain,xtest,ytest,method,randomMethod,roundLimit,labelMaps,df_test,deployLocation,modelName,modelVersion,best_feature_model):\n\t\tmlobj = machinelearning() \n\t\tif model_type == 'Classification':\n\t\t\tself.log.info('\\\\n------ Training DL: Classification ----') \n\t\t\tobjClf = DLClassificationModel(modelList, modelParams, scoreParam, cvSplit, xtrain,ytrain,xtest,ytest,method,randomMethod,roundLimit,best_feature_model) \n\t\t\tdftrain = xtrain.copy()\n\t\t\tdftrain['Target'] = ytrain\n\t\t\tmodel_dl,score_dl,best_model_dl,params_dl,X1,XSNN,model_tried_dl,loss_matrix,optimizer = objClf.TalosScan(objClf) \n\t\t\tself.log.info('------ Training DL: Classification End----\\\\n') \n\t\t\tsaved_model_dl = 'dl_'+modelName+'_'+modelVersion+'.sav'\n\t\t\tfilename_dl = os.path.join(deployLocation,'model',saved_model_dl)\n\t\t\tbest_model_dl.save(filename_dl) \n\t\t\thist_reloaded = self.LoadDL_Classification_Model(filename_dl,scoreParam,loss_matrix,optimizer)\n\t\t\tself.log.info('\\\\n--------- Performance Matrix with Train Data ---------')\n\t\t\tpredictedData, prob = self.getPredictionData(model_dl,hist_reloaded,xtrain) \n\t\t\ttrainingperformancematrix = mlobj.getClassificationPerformaceMatrix(ytrain, predictedData, prob,labelMaps)\n\t\t\tself.log.info('\\\\n--------- Performance Matrix with Train Data End ---------')\n\t\t\tpredictedData, prob = self.getPredictionData(model_dl,hist_reloaded,xtest) \n\t\t\tdf_test['predict'] = predictedData\n\t\t\tself.log.info('\\\\n--------- Performance Matrix with Test Data ---------')\n\t\t\tperformancematrix = mlobj.getClassificationPerformaceMatrix(ytest, predictedData, prob,labelMaps)\n\t\t\tself.log.info('\\\\n--------- Performance Matrix with Test Data End ---------') \n\t\t\treturn(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) \n\t\telse: \n\t\t\tobjReg = DLRegressionModel(modelList, modelParams, scoreParam, cvSplit, xtrain,ytrain,xtest,ytest,method,randomMethod,roundLimit,best_feature_model)\n\t\t\tdftrain = xtrain.copy()\n\t\t\tdftrain['Target'] = ytrain \n\t\t\tmodel_dl,score_dl,best_model_dl,params_dl,X1,XSNN,model_tried_dl,loss_matrix,optimizer = objReg.TalosScan(objReg) \n\t\t\tself.log.info('------ Training DL: Regression End----\\\\n')\n\t\t\tself.log.info('\\\\n------- Best DL Model and its parameters -------------')\n\t\t\tself.log.info('-------> Best Model: '+str(model_dl))\n\t\t\tself.log.info('-------> Best Score: '+str(score_dl))\n\t\t\tself.log.info('-------> Best Params: '+str(params_dl))\n\t\t\tself.log.info('------- Best DL Model and its parameters End-------------\\\\n')\n\t\t\tsaved_model_dl = 'dl_'+modelName+'_'+modelVersion+'.sav'\n\t\t\tfilename_dl = os.path.join(deployLocation,'model',saved_model_dl)\n\t\t\tbest_model_dl.save(filename_dl) \n\t\t\thist_reloaded=self.LoadDL_Regression_Model(filename_dl,scoreParam,loss_matrix,optimizer)\n\t\t\tpredictedData = self.getDLPredictionData(model_dl,hist_reloaded,xtrain", "instruction": "", "output": "" }, { "input": ")\n\t\t\tself.log.info('\\\\n--------- Performance Matrix with Train Data ---------')\n\t\t\ttrainingperformancematrix = mlobj.get_regression_matrix(ytrain, predictedData)\n\t\t\tself.log.info('--------- Performance Matrix with Train Data End---------\\\\n')\n\t\t\tpredictedData = self.getDLPredictionData(model_dl,hist_reloaded,xtest)\n\t\t\tdf_test['predict'] = predictedData\n\t\t\tself.log.info('\\\\n--------- Performance Matrix with Test Data ---------')\n\t\t\tperformancematrix = mlobj.get_regression_matrix(ytest, predictedData)\n\t\t\tself.log.info('--------- Performance Matrix with Test Data End---------\\\\n')\n\t\t\treturn(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) \n\t\t\t\n\tdef LoadDL_Classification_Model(self,filename_dl,scoreParam,loss_matrix,optimizer):\n\t\tif(scoreParam.lower() == 'recall'):\n\t\t\thist_reloaded = load_model(filename_dl,custom_objects={\"recall\": recall_m},compile=False)\n\t\t\thist_reloaded.compile(loss=loss_matrix,optimizer=optimizer, metrics=[recall_m])\n\t\telif(scoreParam.lower() == 'precision'):\n\t\t\thist_reloaded = load_model(filename_dl,custom_objects={\"precision\": precision_m},compile=False)\n\t\t\thist_reloaded.compile(loss=loss_matrix,optimizer=optimizer, metrics=[precision_m])\n\t\telif(scoreParam.lower() == 'roc_auc'):\n\t\t\thist_reloaded = load_model(filename_dl,compile=False)\n\t\t\thist_reloaded.compile(loss=loss_matrix,optimizer=optimizer, metrics=[tf.keras.metrics.AUC()])\n\t\telif(scoreParam.lower() == 'f1_score'):\n\t\t\thist_reloaded = load_model(filename_dl,custom_objects={\"f1_score\": f1_m},compile=False)\n\t\t\thist_reloaded.compile(loss=loss_matrix,optimizer=optimizer, metrics=[f1_m])\t\n\t\telse:\n\t\t\thist_reloaded = load_model(filename_dl)\n\t\treturn(hist_reloaded)\t\n\t\t\t\n\tdef getClassificationPerformaceMatrix(self,le_trainY,predictedData,prob,labelMaps):\n\t\tsetOfyTrue = set(le_trainY)\n\t\tunqClassLst = list(setOfyTrue)\n\t\tif(str(labelMaps) != '{}'):\n\t\t\tinv_mapping_dict = {v: k for k, v in labelMaps.items()}\n\t\t\tunqClassLst2 = (pd.Series(unqClassLst)).map(inv_mapping_dict)\n\t\t\tunqClassLst2 = list(unqClassLst2)\n\t\telse:\n\t\t\tunqClassLst2 = \tunqClassLst\n\t\tindexName = []\n\t\tcolumnName = []\n\t\tfor item in unqClassLst2:\n\t\t\tindexName.append(\"true:\"+str(item))\n\t\t\tcolumnName.append(str(item))\n\t\tmatrixconfusion = pd.DataFrame(confusion_matrix(le_trainY,predictedData, labels = unqClassLst),index = indexName, columns = columnName)\n\t\tself.log.info('\\\\n <--- Confusion Matrix --->')\n\t\tself.log.info(matrixconfusion)\n\t\tclassificationreport = pd.DataFrame(classification_report(le_trainY, predictedData, output_dict=True))\n\t\tself.log.info('\\\\n <--- Classification Report --->')\n\t\tself.log.info(classificationreport)\n\t\tlb = LabelBinarizer()\n\t\tlb.fit(le_trainY)\n\t\ttransformTarget= lb.transform(le_trainY)\n\t\tif transformTarget.shape[-1] == 1:\n\t\t\ttransformTarget = le_trainY\n\t\t\tprob = np.delete( prob, 0, 1)\n\t\trocaucscore = roc_auc_score(transformTarget,prob,average=\"macro\")\n\t\tbrier_score = None\n\t\tmcc_score = matthews_corrcoef(le_trainY,predictedData)\n\t\tif len(unqClassLst) > 2:\n\t\t\tbrier_score = np.mean(np.sum(np.square(prob - transformTarget), axis=1))\n\t\telse:\n\t\t\tbrier_score = brier_score_loss(transformTarget,prob)\n\t\tself.log.info('-------> ROC AUC SCORE :'+str(rocaucscore))\n\t\tself.log.info(f'-------> Matthews correlation coefficient SCORE : {mcc_score}')\n\t\tself.log.info(f'-------> BRIER SCORE : {brier_score}')\n\t\tmatrixconfusion = matrixconfusion.to_json(orient='index')\n\t\tclassificationreport = classificationreport.to_json(orient='index')\n\t\tmatrix = f'\"ConfusionMatrix\": {matrixconfusion},\"ClassificationReport\": {classificationreport},\"ROC_AUC_SCORE\": {rocaucscore},\"MCC_SCORE\": {mcc_score},\"BRIER_SCORE\": {brier_score}'\n\t\treturn(matrix)\n\t\t\n\tdef split_into_train_test_data(self,featureData,targetData,cvSplit,testPercentage,modelType='classification'):\n\t\t'''\n\t\tif cvSplit == None:\n\t\t'''\n\t\ttestSize=testPercentage/100\n\t\tif modelType == 'regression':\n\t\t\txtrain,xtest,ytrain,ytest=train_test_split(featureData,targetData,test_size=testSize,shuffle=True)\n\t\telse:\n\t\t\ttry:\n\t\t\t\txtrain,xtest,ytrain,ytest=train_test_split(featureData,targetData,stratify=targetData,test_size=testSize,shuffle=True)\n\t\t\texcept:\n\t\t\t\txtrain,xtest,ytrain,ytest=train_test_split(featureData,targetData,test_size=testSize,shuffle=True)\n\t\t\t\t\n\t\tself.log.info('\\\\n<-------------- Test Train Split ---------------->\\\\n')\n\t\tself.log.info('\\\\n<-------- Train Data Shape '+str(xtrain.shape)+' ---------->\\\\n')\n\t\tself.log.info('\\\\n<-------- Test Data Shape '+str(xtest.shape)+' ---------->\\\\n')\n\t\t'''\n\t\telse:\n\t\t\txtrain=featureData\n\t\t\tytrain=targetData\n\t\t\txtest=featureData\n\t\t\tytest=targetData\n\t\t'''\n\t\treturn(xtrain,ytrain,xtest,ytest)\n\t\t\n\tdef checkForClassBalancing(self,targetData):\n\t\timbalancedCount=0\n\t\tvalueCount=targetData.value_counts()\n\t\tself.log.info(\"<------ Categories and Count ------>\")\n\t\tself.log.info(valueCount)\n\t\tcategoryList=valueCount.keys().tolist()\n\t\tcategoryCountList=valueCount.tolist()\n\t\tfor i in range(0,len(categoryCountList)):\n\t\t\tif float(categoryCountList[i])<=float(0.3*max(categoryCountList)):\n\t\t\t\tself.log.info(\"<------ Imbalanced class ------>\"+str(categoryCountList[i])+' '+str(categoryList[i]))\n\t\t\t\timbalancedCount=imbalancedCount+1\n\t\treturn(imbalancedCount)\n\tdef setScoreParams(self,scoreParam,problem_type):\n\t\t\n\t\tif problem_type.lower() == 'classification' or problem_type.lower() == 'textclassification':\n\t\t\tallowedmatrix = ['accuracy','recall','precision','f1_score','roc_auc']\n\t\t\tif(scoreParam.lower() not in allowedmatrix):\n\t\t\t\tscoreParam = 'accuracy'\n\t\t\telif scoreParam.lower() == 'none':\n\t\t\t\tscoreParam = 'accuracy'\n\t\t\telse:\n\t\t\t\tscoreParam = scoreParam.lower()\n\t\telse:\n\t\t\tallowedmatrix = ['mse','rmse','r2','mae']\n\t\t\tif(scoreParam.lower() not in allowedmatrix):\n\t\t\t\tscoreParam = 'mse'\n\t\t\telif scoreParam.lower() == 'none':\n\t\t\t\tscoreParam = 'mse'\n\t\t\telse:\t\n\t\t\t\tscoreParam = scoreParam.lower()\n\t\treturn(scoreParam)\n\t\t\n\tdef ExecuteClassBalancing(self,featureData,targetData,balancingMethod):\n\t\tif balancingMethod.lower() == \"oversample\":\n\t\t\tself.log.info(\"<------ Balancing data using SMOTE OverSampling Technique ------>\")\n\t\t\toversample = SMOTE()\n\t\t\tbalfeatureData, baltargetData = oversample.fit_resample(featureData, targetData)\n\t\t\tself.log.info(baltargetData.value_counts())\n\t\telif balancingMethod.lower() == \"undersample\":\n\t\t\tself.log.info(\"<------ Balancing data using Tomelinks UnderSampling Technique ------>\")\n\t\t\ttLinks = TomekLinks()\n\t\t\tbalfeatureData, baltargetData= tLinks.fit_sample(featureData, targetData)\n\t\t\tself.log.info(baltargetData.value_counts())\n\t\telse:\n\t\t\tbalfeatureData = featureData\n\t\t\tbaltargetData = targetData\n\t\t\tself.log.info(\"<------ No balancing technique has been defined ,using imbalanced data for classification ------>\")\n\t\treturn(balfeatureData,baltargetData)\n\tdef get_regression_matrix(self,targetData,predictedData):\n\t\ttry: \n\t\t\tself.log.info('\\\\n <--------- r2_score-------------- --->') \n\t\t\tr2score=r2_score(targetData, predictedData)\n\t\t\tself.log.info(r2score)\n\t\texcept Exception as e: \n\t\t\tself.log.info('\\\\n--------- r2_score ',str(e)) \n\t\t\tr2score = 0\n\t\ttry: \n\t\t\tself.log.info('\\\\n <--- Mean Absolute Error --->')\n\t\t\tmeanabsoluteerror=(mean_absolute_error(targetData, predictedData))\n\t\t\tself.log.info(meanabsoluteerror)\n\t\texcept Exception as e: \n\t\t\tself.log.info('\\\\n---------Error: meanabsoluteerror ',str(e))\n\t\t\tmeanabsoluteerror = 0\n\t\ttry: \n\t\t\tself.log.info(\"<------------mean_squared_error--------------->\")\n\t\t\tmeanssquatederror=mean_squared_error(targetData, predictedData)\n\t\t\tself.log.info(meanssquatederror)\n\t\texcept Exception as e: \n\t\t\tself.log.info('\\\\n---------Error: meanssquatederror ',str(e))\n\t\t\tmeanssquatederror = 0 \n\t\ttry: \n\t\t\tself.log.info(\"<------------root mean_squared_error--------------->\")\n\t\t\trootmeanssquatederror=mean_squared_error(targetData, predictedData,squared=False)\n\t\t\tself.log.info(rootmeanssquatederror)\n\t\texcept Exception as e: \n\t\t\tself.log.info('\\\\n---------Error: rootmeanssquatederror ',str(e))\n\t\t\trootmeanssquatederror = 0\n\t\ttry: \n\t\t\tself.log.info('\\\\n <--- Mean Absolute Percentage Error --->')\n\t\t\ttargetArray, predictedArray = np.array(targetData), np.array(predictedData)\n\t\t\tmeanpercentageerror=np.mean(np.abs((targetArray - predictedArray) / targetArray))*100\n\t\t\tself.log.info(meanpercentageerror)\n\t\texcept Exception as e: \n\t\t\tself.log.info('\\\\n---------Error: meanpercentageerror ',str(e))\n\t\t\tmeanpercentageerror = 0 \n\t\tmatrix = '\"MAE\":'+str(meanabsoluteerror)+',\"R2Score\":'+str(r2score)+',\"MSE\":'+str(meanssquatederror)+',\"MAPE\":'+str(meanpercentageerror)+',\"RMSE\":'+str(rootmeanssquatederror)\n\t\treturn matrix '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport logging\nclass VideoTraining(object):\n\tdef __init__(self):\n\t\tself.log = logging.getLogger('eion')\n\tdef train_model(self,model,modelParam,outputLocation,tfrecord_directory):\n\t\tprint(model)\n\t\tprint(modelParam)\n\t\tprint(outputLocation)\n\t\tprint(tfrecord_directory)\n\t\tfrom savp import TrainSAVP\n\t\tTrainSAVP(tfrecord_directory,outputLocation,modelParam,model)\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\n\nimport numpy as np\nimport pandas as pd\nimport talos\nfrom talos import Evaluate\nimport json\nimport sys\nimport time\nimport os\nimport tensorflow.keras.utils as kutils\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,Dropout,LSTM,GRU,SimpleRNN,Flatten,Input\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.layers import Conv1D,MaxPooling1D\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_absolute_error,make_scorer\nfrom sklearn.metrics import mean_squared_error\nimport logging\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\n\n\ndef rmse_m(y_true, y_pred):\n\treturn K.sqrt(K.mean(K.square(y_pred - y_true), axis=-1))\n\ndef r_square(y_true, y_pred):\n\tSS_res = K.sum(K.square(y_true-y_pred))\n\tSS_tot = K.sum(K.square(y_true-K.mean(y_true)))\n\treturn (1 - SS_res/(SS_tot+K.epsilon()))\n\nclass DLRegressionModel:\n\t\n\tdef __init__(self,modelList, modelParams, scoreParam, cvSplit, featuresData,\n targetData,testX,testY, method,randomMethod,roundLimit,best_feature_model):\n\n\t\t\n\t\tself.modelList =modelList\n\t\tself.modelParams =modelParams\n\t\tself.scoreParam = scoreParam\n\t\tself.cvSplit =cvSplit\n\t\tself.featuresData =featuresData\n\t\tself.targetData = targetData\n\t", "instruction": "", "output": "" }, { "input": "\tself.testX = testX\n\t\tself.testY = testY\n\t\tself.method =method\n\t\t#self.logFile = logFile\n\t\tself.randomMethod=randomMethod\n\t\tself.roundLimit=roundLimit\n\t\tself.log = logging.getLogger('eion')\n\t\tself.best_feature_model = best_feature_model \n\n\tdef RNNRegression(self,x_train,y_train,x_val,y_val,params):\n\t\ttf.keras.backend.clear_session() \n\t\tx_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))\n\t\tx_val = np.reshape(x_val, (x_val.shape[0], x_val.shape[1], 1))\n\t\tmodel = Sequential() \n\t\tif params['RNNType'] == \"LSTM\" : \n\t\t\tif params['numRNNLayers'] > 1: \n\t\t\t\tmodel.add(LSTM(params['first_neuron'],return_sequences=True,input_shape=(x_train.shape[1],1)))\n\t\t\t\tfor x in range(1,params['numRNNLayers']):\n\t\t\t\t\tmodel.add(LSTM(params['first_neuron']))\n\t\t\telse:\n\t\t\t\tmodel.add(LSTM(params['first_neuron'],input_shape=(x_train.shape[1],1)))\n\n\t\telif params['RNNType'] == \"GRU\" :\n\t\t\tif params['numRNNLayers'] > 1: \n\t\t\t\tmodel.add(GRU(params['first_neuron'],return_sequences=True,input_shape=(x_train.shape[1],1)))\n\t\t\t\tfor x in range(1,params['numRNNLayers']):\n\t\t\t\t\t\tmodel.add(GRU(params['first_neuron']))\n\t\t\telse:\n\t\t\t\tmodel.add(GRU(params['first_neuron'],input_shape=(x_train.shape[1],1)))\n\n\n\t\telif params['RNNType'] == \"SimpleRNN\" : \n\t\t\tif params['numRNNLayers'] > 1: \n\t\t\t\tmodel.add(SimpleRNN(params['first_neuron'],return_sequences=True,input_shape=(x_train.shape[1],1)))\n\t\t\t\tfor x in range(1,params['numRNNLayers']):\n\t\t\t\t\tmodel.add(SimpleRNN(params['first_neuron']))\n\t\t\telse:\n\t\t\t\tmodel.add(SimpleRNN(params['first_neuron'],input_shape=(x_train.shape[1],1)))\n\n\n\t\ttalos.utils.hidden_layers(model, params, 1) \n\t\tmodel.add(Dense(1,activation=params['activation']))\n\t\tmodel.compile(loss=params['losses'],optimizer=params['optimizer'],metrics=['mae','mse',rmse_m,r_square]) \n\t\tout = model.fit(x_train, y_train, validation_data=(x_val, y_val), batch_size=params['batch_size'],\n\t\t\t\tepochs=params['epochs'],verbose=0,shuffle=True)\n \n\t\treturn out, model\n\t\n\tdef SNNRegression(self,x_train,y_train,x_val,y_val,params):\n\t\ttf.keras.backend.clear_session() \n\t\tmodel = Sequential()\n\t\tmodel.add(Dense(params['first_neuron'],input_dim=x_train.shape[1],activation=params['activation']))\n\t\ttalos.utils.hidden_layers(model, params, 1)\n\t\tmodel.add(Dense(1, activation=params['activation']))\n\t\tmodel.compile(loss=params['losses'], optimizer=params['optimizer'], metrics=['mae','mse',rmse_m,r_square])\n\t\tout = model.fit(x=x_train, \n\t\t\t y=y_train,\n\t\t\t validation_data=(x_val, y_val),\n\t\t\t epochs=params['epochs'],\n\t\t\t batch_size=params['batch_size'],\n\t\t\t verbose=0)\n\t\treturn out, model\n \n\tdef CNNRegression(self,x_train,y_train,x_val,y_val,params):\n\t\ttf.keras.backend.clear_session() \n\t\tx_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))\n\t\tself.log.info(x_train.shape)\n\t\tx_val = np.reshape(x_val, (x_val.shape[0], x_val.shape[1], 1))\n\t\tmodel = Sequential()\n\t\tself.log.info(params['kernel_size'])\n\t\tmodel.add(Conv1D(filters=params['first_neuron'], kernel_size=int(params['kernel_size']), activation=params['activation'], input_shape=(x_train.shape[1],1)) )\n\t\tif params['numConvLayers'] > 1:\n\t\t\t\tfor x in range(1,params['numConvLayers']):\n\t\t\t\t\tif params['MaxPool'] == \"True\":\n\t\t\t\t\t\tmodel.add(MaxPooling1D(pool_size=2))\n\t\t\t\t\tmodel.add(Conv1D(filters=8, kernel_size=int(params['kernel_size']), activation=params['activation']))\n\t\t\n\t\ttalos.utils.hidden_layers(model, params, 1)\n\t\tmodel.add(Flatten())\n\t\tmodel.add(Dense(1))\n\t\tmodel.compile(loss=params['losses'],optimizer=params['optimizer'],metrics=['mae','mse',rmse_m,r_square])\n\t\tout = model.fit(x_train, y_train, validation_data=(x_val, y_val), batch_size=params['batch_size'],\n\t\t\t\tepochs=params['epochs'],verbose=0,shuffle=True)\n\n\t\treturn out, model\n\n\n\tdef TalosScan(self,modelObj):\n\t\t\n\t\ttry:\n\t\t\t#dataPath = pd.read_csv(self.dataLocation)\n\t\t\t#X = dataPath.drop(self.targetData, axis=1)\n\t\t\tX = self.featuresData\n\t\t\tx = X.values\n\t\t\tloss_matrix = 'mean_absolute_error'\n\t\t\toptimizer='Nadam'\n\t\t\tY= self.targetData\n\t\t\ty = Y.values\n\t\t\tXSNN = X.values\n\t\t\tX1 = np.expand_dims(X, axis=2)\t\t\t\n\t\t\tscoredetails = ''\n\n\t\t\tkf = KFold(n_splits = self.cvSplit)\n\t\t\tfor train_index, test_index in kf.split(X):\n\t\t\t\tX_train, X_test = x[train_index], x[test_index]\n\t\t\t\ty_train, y_test = y[train_index], y[test_index]\t\n\n\t\t\t\n\t\t\tdata = self.modelParams\n\t\t\tmodels = data.keys() \n\t\t\tlstart = time.time()\n\t\t\tscoreSNN = []\n\t\t\tscoreRNN = []\n\t\t\tscoreCNN = []\n\t\t\tscoreRNNGRU = []\n\t\t\tscoreRNNLSTM = [] \n\t\t\tbest_paramsSNN = {} \t\n\t\t\tbest_paramsRNN = {} \n\t\t\tbest_paramsRNNGRU = {} \n\t\t\tbest_paramsRNNLSTM = {} \n\t\t\tbest_paramsCNN = {} \n\t\t\t\n\t\t\tif \"Neural Network\"in self.modelList:\n\t\t\t\tself.log.info(\"-------> Model Name: Neural Network\")\n\t\t\t\tstart = time.time()\n\t\t\t\tdata = self.modelParams[\"Neural Network\"]\n\t\t\t\tp = {\"activation\":data[\"activation\"].split(\",\"),\n\t\t\t\t \"optimizer\":data[\"optimizer\"].split(\",\"),\n\t\t\t\t \"losses\":data[\"losses\"].split(\",\"),\n\t\t\t\t \"first_neuron\":[int(n) for n in data[\"first_layer\"].split(\",\")],\n\t\t\t\t \"shapes\": data[\"shapes\"].split(\",\"),\n\t\t\t\t \"hidden_layers\":[int(n) for n in data[\"hidden_layers\"].split(\",\")],\n\t\t\t\t \"dropout\": [float(n) for n in data[\"dropout\"].split(\",\")],\n\t\t\t\t \"lr\": [float(n) for n in data[\"learning_rate\"].split(\",\")],\n\t\t\t\t \"batch_size\": [int(n) for n in data[\"batch_size\"].split(\",\")],\n\t\t\t\t \"epochs\": [int(n) for n in data[\"epochs\"].split(\",\")]}\n\t\t\t\t\n\t\t\t\tscan_object = talos.Scan(x=X_train,y=y_train,x_val = X_test,y_val = y_test,model = modelObj.SNNRegression,experiment_name='SNN',params=p,round_limit=self.roundLimit,random_method=self.randomMethod)\n\t\t\t\t\n\t\t\t\tmatrix_type = 'val_loss'\n\t\t\t\tif self.scoreParam.lower() == 'rmse':\n\t\t\t\t\tmatrix_type = 'val_rmse_m'\n\t\t\t\telif(self.scoreParam.lower() == 'r2'):\n\t\t\t\t\tmatrix_type = 'val_r_square'\n\t\t\t\telif(self.scoreParam.lower() == 'mae'):\n\t\t\t\t\tmatrix_type = 'val_mae'\n\t\t\t\telif(self.scoreParam.lower() == 'mse'):\n\t\t\t\t\tmatrix_type = 'val_mse'\n\t\t\t\n\t\t\t\t\t\n\t\t\t\tanalyze_objectSNN = talos.Analyze(scan_object)\t\t\t\t\n\t\t\t\thighValAccSNN = analyze_objectSNN.low(matrix_type)\n\t\t\t\t\n\t\t\t\tdfSNN = \tanalyze_objectSNN.data\n\t\t\t\n\t\t\t\tnewdfSNN = dfSNN.loc[dfSNN[matrix_type] == highValAccSNN]\n\n\t\t\t\n\t\t\t\tbest_paramsSNN[\"activation\"] = list(newdfSNN[\"activation\"])[0]\n\t\t\t\tbest_paramsSNN[\"optimizer\"] = list(newdfSNN[\"optimizer\"])[0]\n\t\t\t\tbest_paramsSNN[\"losses\"] = list(newdfSNN[\"losses\"])[0]\n\t\t\t\tbest_paramsSNN[\"first_layer\"] = list(newdfSNN[\"first_neuron\"])[0]\n\t\t\t\tbest_paramsSNN[\"shapes\"] = list(newdfSNN[\"shapes\"])[0]\n\t\t\t\tbest_paramsSNN[\"hidden_layers\"] = list(newdfSNN[\"hidden_layers\"])[0]\n\t\t\t\tbest_paramsSNN[\"dropout\"] = list(newdfSNN[\"dropout\"])[0]\n\t\t\t\tbest_paramsSNN[\"batch_size\"] = list(newdfSNN[\"batch_size\"])[0]\n\t\t\t\tbest_paramsSNN[\"epochs\"] = list(newdfSNN[\"epochs\"])[0]\n\t\t\t\tbest_paramsSNN[\"lr\"] = list(newdfSNN[\"lr\"])[0]\n\n\t\t\t\t\n\t\t\t\tbest_modelSNN = scan_object.best_model(metric=matrix_type, asc=True)\n\t\t\t\t\n\t\t\t\tloss_matrix = best_paramsSNN[\"losses\"]\n\t\t\t\toptimizer = best_paramsSNN[\"optimizer\"]\n\t\t\t\tbatchsize = best_paramsSNN[\"batch_size\"]\n\t\t\t\t\n\t\t\t\tif self.scoreParam == 'rmse': \n\t\t\t\t\tbest_modelSNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[rmse_m])\n\t\t\t\telif self.scoreParam == 'r2':\n\t\t\t\t\tbest_modelSNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[r_square])\n\t\t\t\telif self.scoreParam == 'mae':\n\t\t\t\t\tbest_modelSNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=['mae'])\n\t\t\t\telse:\n\t\t\t\t\tbest_modelSNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=['mse'])\n\t\t\t\tscoreSNN = best_modelSNN.evaluate(XSNN,Y, batch_size=batchsize)\n\t\t\t\tself.log.info(\"----------> Score Matrix: \"+str(best_modelSNN.metrics_names))\n\t\t\t\tself.log.info(\"----------> Score: \"+str(scoreSNN))\n\t\t\t\tself.log.info(\"----------> Model Params: \"+str(best_paramsSNN))\n\t\t\t\texecutionTime=time.time() - start\n\t\t\t\tself.log.info('----------> SNN Execution Time: '+str(executionTime)+'\\\\n')\n\t\t\t\tXSNN = self.testX.values\n\t\t\t\tpredictedData = best_modelSNN.predict(XSNN)\n\t\t\t\tif self.scoreParam.lower() == 'mse':\n\t\t\t\t\tscore = mean_squared_error(self.testY,predictedData)\n\t\t\t\telif self.scoreParam.lower() == 'rmse': \n\t\t\t\t\tscore=mean_squared_error(self.testY,predictedData,squared=False)\n\t\t\t\telif self.scoreParam.lower() == 'mae':\n\t\t\t\t\tscore=mean_absolute_error(self.testY,predictedData)\n\t\t\t\telif self.scoreParam.lower() == 'r2':\n\t\t\t\t\tscore=r2_score(self.testY,predictedData)\n\t\t\t\telse:\n\t\t\t\t\tscore = scoreSNN[1]\n\t\t\t\tself.log.info(\"----------> Testing Score: \"+str(score))\t\t\n\t\t\t\tscoreSNN[1] = score\n\t\t\t\tif(scoredetails != ''):\n\t\t\t\t\tscoredetails += ','\n\t\t\t\tscoredetails += '{\"Model\":\"Neural Network\",\"FeatureEngineering\":\"'+str(self.best_feature_model)+'\",\"Score\":'+str(scoreSNN[1])+'}'\n\t\t\t\tself.log.info('Status:- |... DL Algorithm applied: Neural Network')\n\t\t\t\tself.log.info('Status:- |... Score after hyperparameter tuning: '+str(round(score,2)))\n\t\t\t \n\t\t\tif \"Recurrent Neural Network\"in self.modelList:\n\t\t\t\tself.log.info(\"-------> Model Name: Recurrent Neural Network\")\n\t\t\t\tstart = time.time()\n\t\t\t\tdata = self.modelParams[\"Recurrent Neural Network\"]\n\t\t\t\tp = {\"RNNType\":[\"SimpleRNN\"],\n\t\t\t\t \"numRNNLayers\":[int(n) for n in data[\"numRNNLayers\"].split(\",\")],\n\t\t\t\t \"activation\":data[\"activation\"].split(\",\"),\n\t\t\t\t \"optimizer\":data[\"optimizer\"].split(\",\"),\n\t\t\t\t \"losses\":data[\"losses\"].split(\",\"),\n\t\t\t\t \"first_neuron\":[int(n) for n in data[\"first_layer\"].split(\",\")],\n\t\t\t\t \"shapes\": data[\"shapes\"].split(\",\"),\n\t\t\t\t \"hidden_layers\":[int(n) for n in data[\"hidden_layers\"].split(\",\")],\n\t\t\t\t \"dropout", "instruction": "", "output": "" }, { "input": "\": [float(n) for n in data[\"dropout\"].split(\",\")],\n\t\t\t\t \"lr\": [float(n) for n in data[\"learning_rate\"].split(\",\")],\n\t\t\t\t \"batch_size\": [int(n) for n in data[\"batch_size\"].split(\",\")],\n\t\t\t\t \"epochs\": [int(n) for n in data[\"epochs\"].split(\",\")]}\n\n\t\t\t\tscan_object = talos.Scan(x=X_train,y=y_train,x_val = X_test,y_val = y_test,model = modelObj.RNNRegression,experiment_name='RNN',params=p,round_limit=self.roundLimit,random_method=self.randomMethod)\n\t\t\t\t\n\t\t\t\tmatrix_type = 'val_loss'\n\t\t\t\tif self.scoreParam.lower() == 'rmse':\n\t\t\t\t\tmatrix_type = 'val_rmse_m'\n\t\t\t\telif(self.scoreParam.lower() == 'r2'):\n\t\t\t\t\tmatrix_type = 'val_r_square'\n\t\t\t\telif(self.scoreParam.lower() == 'mae'):\n\t\t\t\t\tmatrix_type = 'val_mae'\n\t\t\t\telif(self.scoreParam.lower() == 'mse'):\n\t\t\t\t\tmatrix_type = 'val_mse'\n\t\t\t\t\t\n\t\t\t\tanalyze_objectRNN = talos.Analyze(scan_object)\t\t\t\t\n\t\t\t\thighValAccRNN = analyze_objectRNN.low(matrix_type)\t\t\t\t\n\t\t\t\tdfRNN = \tanalyze_objectRNN.data\n\t\t\t\n\t\t\t\tnewdfRNN = dfRNN.loc[dfRNN[matrix_type] == highValAccRNN]\n\n\t\t\t\n\t\t\t\tbest_paramsRNN[\"RNNType\"] = \"SimpleRNN\"\n\t\t\t\tbest_paramsRNN[\"numRNNLayers\"] = list(newdfRNN[\"numRNNLayers\"])[0]\n\t\t\t\tbest_paramsRNN[\"activation\"] = list(newdfRNN[\"activation\"])[0]\n\t\t\t\tbest_paramsRNN[\"optimizer\"] = list(newdfRNN[\"optimizer\"])[0]\n\t\t\t\tbest_paramsRNN[\"losses\"] = list(newdfRNN[\"losses\"])[0]\n\t\t\t\tbest_paramsRNN[\"first_layer\"] = list(newdfRNN[\"first_neuron\"])[0]\n\t\t\t\tbest_paramsRNN[\"shapes\"] = list(newdfRNN[\"shapes\"])[0]\n\t\t\t\tbest_paramsRNN[\"hidden_layers\"] = list(newdfRNN[\"hidden_layers\"])[0]\n\t\t\t\tbest_paramsRNN[\"dropout\"] = list(newdfRNN[\"dropout\"])[0]\n\t\t\t\tbest_paramsRNN[\"batch_size\"] = list(newdfRNN[\"batch_size\"])[0]\n\t\t\t\tbest_paramsRNN[\"epochs\"] = list(newdfRNN[\"epochs\"])[0]\n\t\t\t\tbest_paramsRNN[\"lr\"] = list(newdfRNN[\"lr\"])[0]\n\n\t\t\t\tbest_modelRNN = scan_object.best_model(metric=matrix_type, asc=True)\n\t\t\t\t\n\t\t\t\tloss_matrix = best_paramsRNN[\"losses\"]\n\t\t\t\toptimizer = best_paramsRNN[\"optimizer\"]\n\t\t\t\tbatchsize = best_paramsRNN[\"batch_size\"]\n\t\t\t\t\n\t\t\t\tif self.scoreParam == 'rmse': \n\t\t\t\t\tbest_modelRNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[rmse_m])\n\t\t\t\telif self.scoreParam == 'r2':\n\t\t\t\t\tbest_modelRNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[r_square])\n\t\t\t\telif self.scoreParam == 'mae':\n\t\t\t\t\tbest_modelRNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=['mae'])\n\t\t\t\telse:\n\t\t\t\t\tbest_modelRNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=['mse'])\n\t\t\t\t\n\t\t\t\tscoreRNN = best_modelRNN.evaluate(X1,Y, batch_size=batchsize)\n\t\t\t\tself.log.info(\"----------> Score Matrix: \"+str(best_modelRNN.metrics_names))\n\t\t\t\tself.log.info(\"----------> Score: \"+str(scoreRNN))\n\t\t\t\tself.log.info(\"----------> Model Params: \"+str(best_paramsRNN))\n\t\t\t\texecutionTime=time.time() - start\n\t\t\t\tself.log.info('----------> RNN Execution Time: '+str(executionTime)+'\\\\n')\n\t\t\t\tXSNN = np.expand_dims(self.testX, axis=2)\n\t\t\t\tpredictedData = best_modelRNN.predict(XSNN)\n\t\t\t\tif self.scoreParam.lower() == 'mse':\n\t\t\t\t\tscore = mean_squared_error(self.testY,predictedData)\n\t\t\t\telif self.scoreParam.lower() == 'rmse': \n\t\t\t\t\tscore=mean_squared_error(self.testY,predictedData,squared=False)\n\t\t\t\telif self.scoreParam.lower() == 'mae':\n\t\t\t\t\tscore=mean_absolute_error(self.testY,predictedData)\n\t\t\t\telif self.scoreParam.lower() == 'r2':\n\t\t\t\t\tscore=r2_score(self.testY,predictedData)\n\t\t\t\telse:\n\t\t\t\t\tscore = scoreRNN[1]\n\t\t\t\tself.log.info(\"----------> Testing Score: \"+str(score))\t\t\n\t\t\t\tscoreRNN[1] = score\n\t\t\t\t\n\t\t\t\tif(scoredetails != ''):\n\t\t\t\t\tscoredetails += ','\n\t\t\t\tscoredetails += '{\"Model\":\"Recurrent Neural Network\",\"FeatureEngineering\":\"'+str(self.best_feature_model)+'\",\"Score\":'+str(scoreRNN[1])+'}'\n\t\t\t\tself.log.info('Status:- |... DL Algorithm applied: Recurrent Neural Network')\n\t\t\t\tself.log.info('Status:- |... Score after hyperparameter tuning: '+str(round(score,2)))\n \n\t\t\tif \"Recurrent Neural Network (GRU)\"in self.modelList:\n\t\t\t\tself.log.info(\"-------> Model Name: Recurrent Neural Network (GRU)\")\n\t\t\t\tstart = time.time()\n\t\t\t\tdata = self.modelParams[\"Recurrent Neural Network (GRU)\"]\n\t\t\t\tp = {\"RNNType\":[\"GRU\"],\n\t\t\t\t \"numRNNLayers\":[int(n) for n in data[\"numRNNLayers\"].split(\",\")],\n\t\t\t\t \"activation\":data[\"activation\"].split(\",\"),\n\t\t\t\t \"optimizer\":data[\"optimizer\"].split(\",\"),\n\t\t\t\t \"losses\":data[\"losses\"].split(\",\"),\n\t\t\t\t \"first_neuron\":[int(n) for n in data[\"first_layer\"].split(\",\")],\n\t\t\t\t \"shapes\": data[\"shapes\"].split(\",\"),\n\t\t\t\t \"hidden_layers\":[int(n) for n in data[\"hidden_layers\"].split(\",\")],\n\t\t\t\t \"dropout\": [float(n) for n in data[\"dropout\"].split(\",\")],\n\t\t\t\t \"lr\": [float(n) for n in data[\"learning_rate\"].split(\",\")],\n\t\t\t\t \"batch_size\": [int(n) for n in data[\"batch_size\"].split(\",\")],\n\t\t\t\t \"epochs\": [int(n) for n in data[\"epochs\"].split(\",\")]}\n\n\t\t\t\tscan_object = talos.Scan(x=X_train,y=y_train,x_val = X_test,y_val = y_test,model = modelObj.RNNRegression,experiment_name='RNNGRU',params=p,round_limit=self.roundLimit,random_method=self.randomMethod)\n\t\t\t\t\n\t\t\t\tmatrix_type = 'val_loss'\n\t\t\t\tif self.scoreParam.lower() == 'rmse':\n\t\t\t\t\tmatrix_type = 'val_rmse_m'\n\t\t\t\telif(self.scoreParam.lower() == 'r2'):\n\t\t\t\t\tmatrix_type = 'val_r_square'\n\t\t\t\telif(self.scoreParam.lower() == 'mae'):\n\t\t\t\t\tmatrix_type = 'val_mae'\n\t\t\t\telif(self.scoreParam.lower() == 'mse'):\n\t\t\t\t\tmatrix_type = 'val_mse'\n\t\t\t\t\t\n\t\t\t\tanalyze_objectRNNGRU = talos.Analyze(scan_object)\t\t\t\t\n\t\t\t\thighValAccRNNGRU = analyze_objectRNNGRU.low(matrix_type)\t\t\t\t\n\t\t\t\tdfRNNGRU = \tanalyze_objectRNNGRU.data\n\t\t\t\n\t\t\t\tnewdfRNNGRU = dfRNNGRU.loc[dfRNNGRU[matrix_type] == highValAccRNNGRU]\n\n\t\t\t\n\t\t\t\tbest_paramsRNNGRU[\"RNNType\"] = \"GRU\"\n\t\t\t\tbest_paramsRNNGRU[\"numRNNLayers\"] = list(newdfRNNGRU[\"numRNNLayers\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"activation\"] = list(newdfRNNGRU[\"activation\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"optimizer\"] = list(newdfRNNGRU[\"optimizer\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"losses\"] = list(newdfRNNGRU[\"losses\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"first_layer\"] = list(newdfRNNGRU[\"first_neuron\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"shapes\"] = list(newdfRNNGRU[\"shapes\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"hidden_layers\"] = list(newdfRNNGRU[\"hidden_layers\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"dropout\"] = list(newdfRNNGRU[\"dropout\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"batch_size\"] = list(newdfRNNGRU[\"batch_size\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"epochs\"] = list(newdfRNNGRU[\"epochs\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"lr\"] = list(newdfRNNGRU[\"lr\"])[0]\n\n\t\t\t\tbest_modelRNNGRU = scan_object.best_model(metric=matrix_type, asc=True)\n\t\t\t\t\n\t\t\t\tloss_matrix = best_paramsRNNGRU[\"losses\"]\n\t\t\t\toptimizer = best_paramsRNNGRU[\"optimizer\"]\n\t\t\t\tbatchsize = best_paramsRNNGRU[\"batch_size\"]\n\t\t\t\t\n\t\t\t\tif self.scoreParam == 'rmse': \n\t\t\t\t\tbest_modelRNNGRU.compile(loss=loss_matrix,optimizer=optimizer, metrics=[rmse_m])\n\t\t\t\telif self.scoreParam == 'r2':\n\t\t\t\t\tbest_modelRNNGRU.compile(loss=loss_matrix,optimizer=optimizer, metrics=[r_square])\n\t\t\t\telif self.scoreParam == 'mae':\n\t\t\t\t\tbest_modelRNNGRU.compile(loss=loss_matrix,optimizer=optimizer, metrics=['mae'])\n\t\t\t\telse:\n\t\t\t\t\tbest_modelRNNGRU.compile(loss=loss_matrix,optimizer=optimizer, metrics=['mse'])\n\t\t\t\t\n\t\t\t\tscoreRNNGRU = best_modelRNNGRU.evaluate(X1,Y, batch_size=batchsize)\n\t\t\t\tself.log.info(\"----------> Score Matrix: \"+str(best_modelRNNGRU.metrics_names))\n\t\t\t\tself.log.info(\"----------> Score: \"+str(scoreRNNGRU))\n\t\t\t\tself.log.info(\"----------> Model Params: \"+str(best_paramsRNNGRU))\n\t\t\t\texecutionTime=time.time() - start\n\t\t\t\tself.log.info('----------> RNN Execution Time: '+str(executionTime)+'\\\\n')\n\t\t\t\tXSNN = np.expand_dims(self.testX, axis=2)\n\t\t\t\tpredictedData = best_modelRNNGRU.predict(XSNN)\n\t\t\t\tif self.scoreParam.lower() == 'mse':\n\t\t\t\t\tscore = mean_squared_error(self.testY,predictedData)\n\t\t\t\telif self.scoreParam.lower() == 'rmse': \n\t\t\t\t\tscore=mean_squared_error(self.testY,predictedData,squared=False)\n\t\t\t\telif self.scoreParam.lower() == 'mae':\n\t\t\t\t\tscore=mean_absolute_error(self.testY,predictedData)\n\t\t\t\telif self.scoreParam.lower() == 'r2':\n\t\t\t\t\tscore=r2_score(self.testY,predictedData)\n\t\t\t\telse:\n\t\t\t\t\tscore = scoreRNNGRU[1]\n\t\t\t\tself.log.info(\"----------> Testing Score: \"+str(score))\t\t\n\t\t\t\tscoreRNNGRU[1] = score\n\t\t\t\t\n\t\t\t\tif(scoredetails != ''):\n\t\t\t\t\tscoredetails += ','\n\t\t\t\tscoredetails += '{\"Model\":\"Recurrent Neural Network (GRU)\",\"FeatureEngineering\":\"'+str(self.best_feature_model)+'\",\"Score\":'+str(scoreRNNGRU[1])+'}'\n\t\t\t\tself.log.info('Status:- |... DL Algorithm applied: Recurrent Neural Network (GRU)')\n\t\t\t\tself.log.info('Status:- |... Score after hyperparameter tuning: '+str(round(score,2)))\n\n\t\t\tif \"Recurrent Neural Network (LSTM)\"in self.modelList:\n\t\t\t\tself.log.info(\"-------> Model Name: Recurrent Neural Network (LSTM)\")\n\t\t\t\tstart = time.time()\n\t\t\t\tdata = self.modelParams[\"Recurrent Neural Network (LSTM)\"]\n\t\t\t\tp = {\"RNNType\":[\"LSTM\"],\n\t\t\t\t \"numRNNLayers\":[int(n) for n in data[\"numRNNLayers\"].split(\",\")],\n\t\t\t\t \"activation\":data[\"activation\"].split(\",\"),\n\t\t\t\t \"optimizer\":data[\"optimizer\"].split(\",\"),\n\t\t\t\t \"losses\":data[\"losses\"].split(\",\"),\n\t\t\t\t \"first_neuron\":[int(n) for n in data[\"first_layer\"].split(\",\")],\n\t\t\t\t \"shapes\": data[\"shapes\"].split(\",\"),\n\t\t\t\t \"hidden_layers\":[int(n) for n in data[\"hidden_layers\"].split(\",\")],\n\t\t\t\t \"dropout\": [float(n) for n in data[\"dropout\"].split(\",\")],\n\t\t\t\t \"lr\": [float(n) for n in data[\"learning_rate\"].split(\",\")],\n\t\t\t\t \"batch_size\": [int(n) for n in data[\"batch_size\"].split(\",\")],\n\t\t\t\t \"epochs\": [int(n) for n in data[\"epochs\"].split(\",\")]}\n\n\t\t\t\tscan", "instruction": "", "output": "" }, { "input": "_object = talos.Scan(x=X_train,y=y_train,x_val = X_test,y_val = y_test,model = modelObj.RNNRegression,experiment_name='RNNLSTM',params=p,round_limit=self.roundLimit,random_method=self.randomMethod)\n\t\t\t\t\n\t\t\t\tmatrix_type = 'val_loss'\n\t\t\t\tif self.scoreParam.lower() == 'rmse':\n\t\t\t\t\tmatrix_type = 'val_rmse_m'\n\t\t\t\telif(self.scoreParam.lower() == 'r2'):\n\t\t\t\t\tmatrix_type = 'val_r_square'\n\t\t\t\telif(self.scoreParam.lower() == 'mae'):\n\t\t\t\t\tmatrix_type = 'val_mae'\n\t\t\t\telif(self.scoreParam.lower() == 'mse'):\n\t\t\t\t\tmatrix_type = 'val_mse'\n\t\t\t\t\t\n\t\t\t\tanalyze_objectRNNLSTM = talos.Analyze(scan_object)\t\t\t\t\n\t\t\t\thighValAccRNNLSTM = analyze_objectRNNLSTM.low(matrix_type)\t\t\t\t\n\t\t\t\tdfRNNLSTM = \tanalyze_objectRNNLSTM.data\n\t\t\t\n\t\t\t\tnewdfRNNLSTM = dfRNNLSTM.loc[dfRNNLSTM[matrix_type] == highValAccRNNLSTM]\n\n\t\t\t\n\t\t\t\tbest_paramsRNNLSTM[\"RNNType\"] = \"GRU\"\n\t\t\t\tbest_paramsRNNLSTM[\"numRNNLayers\"] = list(newdfRNNLSTM[\"numRNNLayers\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"activation\"] = list(newdfRNNLSTM[\"activation\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"optimizer\"] = list(newdfRNNLSTM[\"optimizer\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"losses\"] = list(newdfRNNLSTM[\"losses\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"first_layer\"] = list(newdfRNNLSTM[\"first_neuron\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"shapes\"] = list(newdfRNNLSTM[\"shapes\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"hidden_layers\"] = list(newdfRNNLSTM[\"hidden_layers\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"dropout\"] = list(newdfRNNLSTM[\"dropout\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"batch_size\"] = list(newdfRNNLSTM[\"batch_size\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"epochs\"] = list(newdfRNNLSTM[\"epochs\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"lr\"] = list(newdfRNNLSTM[\"lr\"])[0]\n\t\t\t\t\n\n\t\t\t\tbest_modelRNNLSTM = scan_object.best_model(metric=matrix_type, asc=True)\n\t\t\t\t\n\t\t\t\tloss_matrix = best_paramsRNNLSTM[\"losses\"]\n\t\t\t\toptimizer = best_paramsRNNLSTM[\"optimizer\"]\n\t\t\t\tbatchsize = best_paramsRNNLSTM[\"batch_size\"]\n\t\t\t\t\n\t\t\t\tif self.scoreParam == 'rmse': \n\t\t\t\t\tbest_modelRNNLSTM.compile(loss=loss_matrix,optimizer=optimizer, metrics=[rmse_m])\n\t\t\t\telif self.scoreParam == 'r2':\n\t\t\t\t\tbest_modelRNNLSTM.compile(loss=loss_matrix,optimizer=optimizer, metrics=[r_square])\n\t\t\t\telif self.scoreParam == 'mae':\n\t\t\t\t\tbest_modelRNNLSTM.compile(loss=loss_matrix,optimizer=optimizer, metrics=['mae'])\n\t\t\t\telse:\n\t\t\t\t\tbest_modelRNNLSTM.compile(loss=loss_matrix,optimizer=optimizer, metrics=['mse'])\n\t\t\t\t\n\t\t\t\tscoreRNNLSTM = best_modelRNNLSTM.evaluate(X1,Y, batch_size=batchsize)\n\t\t\t\tself.log.info(\"----------> Score Matrix: \"+str(best_modelRNNLSTM.metrics_names))\n\t\t\t\tself.log.info(\"----------> Score: \"+str(scoreRNNLSTM))\n\t\t\t\tself.log.info(\"----------> Model Params: \"+str(best_paramsRNNLSTM))\n\t\t\t\texecutionTime=time.time() - start\n\t\t\t\tself.log.info('----------> RNN Execution Time: '+str(executionTime)+'\\\\n')\n\t\t\t\tXSNN = np.expand_dims(self.testX, axis=2)\n\t\t\t\tpredictedData = best_modelRNNLSTM.predict(XSNN)\n\t\t\t\tif self.scoreParam.lower() == 'mse':\n\t\t\t\t\tscore = mean_squared_error(self.testY,predictedData)\n\t\t\t\telif self.scoreParam.lower() == 'rmse': \n\t\t\t\t\tscore=mean_squared_error(self.testY,predictedData,squared=False)\n\t\t\t\telif self.scoreParam.lower() == 'mae':\n\t\t\t\t\tscore=mean_absolute_error(self.testY,predictedData)\n\t\t\t\telif self.scoreParam.lower() == 'r2':\n\t\t\t\t\tscore=r2_score(self.testY,predictedData)\n\t\t\t\telse:\n\t\t\t\t\tscore = scoreRNNLSTM[1]\n\t\t\t\tself.log.info(\"----------> Testing Score: \"+str(score))\t\t\n\t\t\t\tscoreRNNLSTM[1] = score\n\t\t\t\t\n\t\t\t\tif(scoredetails != ''):\n\t\t\t\t\tscoredetails += ','\n\t\t\t\tscoredetails += '{\"Model\":\"Recurrent Neural Network (LSTM)\",\"FeatureEngineering\":\"'+str(self.best_feature_model)+'\",\"Score\":'+str(scoreRNNLSTM[1])+'}'\n\t\t\t\tself.log.info('Status:- |... DL Algorithm applied: Recurrent Neural Network (LSTM)')\n\t\t\t\tself.log.info('Status:- |... Score after hyperparameter tuning: '+str(round(score,2)))\n\n\t\t\tif \"Convolutional Neural Network (1D)\"in self.modelList:\n\t\t\t\tself.log.info(\"-------> Model Name: CNN\")\n\t\t\t\tstart = time.time()\n\t\t\t\tdata = self.modelParams[\"Convolutional Neural Network (1D)\"]\n\t\t\t\tp = {\"activation\":data[\"activation\"].split(\",\"),\n\t\t\t\t\t \"kernel_size\":data[\"kernel_size\"].split(\",\"),\n\t\t\t\t \"numConvLayers\":[int(n) for n in data[\"numConvLayers\"].split(\",\")],\n\t\t\t\t \"MaxPool\":data[\"activation\"].split(\",\"),\n\t\t\t\t \"optimizer\":data[\"optimizer\"].split(\",\"),\n\t\t\t\t \"losses\":data[\"losses\"].split(\",\"),\n\t\t\t\t \"first_neuron\":[int(n) for n in data[\"first_layer\"].split(\",\")],\n\t\t\t\t \"shapes\": data[\"shapes\"].split(\",\"),\n\t\t\t\t \"hidden_layers\":[int(n) for n in data[\"hidden_layers\"].split(\",\")],\n\t\t\t\t \"dropout\": [float(n) for n in data[\"dropout\"].split(\",\")],\n\t\t\t\t \"lr\": [float(n) for n in data[\"learning_rate\"].split(\",\")],\n\t\t\t\t \"batch_size\": [int(n) for n in data[\"batch_size\"].split(\",\")],\n\t\t\t\t \"epochs\": [int(n) for n in data[\"epochs\"].split(\",\")]}\n\t\t\t\tscan_object = talos.Scan(x=X_train,y=y_train, x_val = X_test, y_val = y_test, model = modelObj.CNNRegression,experiment_name='CNN', params=p,round_limit=self.roundLimit,random_method=self.randomMethod)\n\t\t\t\t\n\t\t\t\tmatrix_type = 'val_loss'\n\t\t\t\tif self.scoreParam.lower() == 'rmse':\n\t\t\t\t\tmatrix_type = 'val_rmse_m'\n\t\t\t\telif(self.scoreParam.lower() == 'r2'):\n\t\t\t\t\tmatrix_type = 'val_r_square'\n\t\t\t\telif(self.scoreParam.lower() == 'mae'):\n\t\t\t\t\tmatrix_type = 'val_mae'\n\t\t\t\telif(self.scoreParam.lower() == 'mse'):\n\t\t\t\t\tmatrix_type = 'val_mse'\n\t\t\t\t\t\n\t\t\t\tanalyze_objectCNN = talos.Analyze(scan_object)\t\t\t\t\n\t\t\t\thighValAccCNN = analyze_objectCNN.low(matrix_type)\t\t\t\t\n\t\t\t\tdfCNN = \tanalyze_objectCNN.data\n\t\t\t\n\t\t\t\tnewdfCNN = dfCNN.loc[dfCNN[matrix_type] == highValAccCNN]\n\n\t\t\t\n\t\t\t\tbest_paramsCNN[\"numConvLayers\"] = list(newdfCNN[\"numConvLayers\"])[0]\n\t\t\t\tbest_paramsCNN[\"MaxPool\"] = list(newdfCNN[\"MaxPool\"])[0]\n\t\t\t\tbest_paramsCNN[\"activation\"] = list(newdfCNN[\"activation\"])[0]\n\t\t\t\tbest_paramsCNN[\"optimizer\"] = list(newdfCNN[\"optimizer\"])[0]\n\t\t\t\tbest_paramsCNN[\"losses\"] = list(newdfCNN[\"losses\"])[0]\n\t\t\t\tbest_paramsCNN[\"first_layer\"] = list(newdfCNN[\"first_neuron\"])[0]\n\t\t\t\tbest_paramsCNN[\"shapes\"] = list(newdfCNN[\"shapes\"])[0]\n\t\t\t\tbest_paramsCNN[\"hidden_layers\"] = list(newdfCNN[\"hidden_layers\"])[0]\n\t\t\t\tbest_paramsCNN[\"dropout\"] = list(newdfCNN[\"dropout\"])[0]\n\t\t\t\tbest_paramsCNN[\"batch_size\"] = list(newdfCNN[\"batch_size\"])[0]\n\t\t\t\tbest_paramsCNN[\"epochs\"] = list(newdfCNN[\"epochs\"])[0]\n\t\t\t\tbest_paramsCNN[\"lr\"] = list(newdfCNN[\"lr\"])[0]\n\n\n\t\t\t\tbest_modelCNN = scan_object.best_model(metric=matrix_type, asc=True)\n\t\t\t\t\n\t\t\t\tloss_matrix = best_paramsCNN[\"losses\"]\n\t\t\t\toptimizer = best_paramsCNN[\"optimizer\"]\n\t\t\t\tbatchsize = best_paramsCNN[\"batch_size\"]\n\t\t\t\t\n\t\t\t\tif self.scoreParam == 'rmse': \n\t\t\t\t\tbest_modelCNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[rmse_m])\n\t\t\t\telif self.scoreParam == 'r2':\n\t\t\t\t\tbest_modelCNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[r_square])\n\t\t\t\telif self.scoreParam == 'mae':\n\t\t\t\t\tbest_modelCNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=['mae'])\n\t\t\t\telse:\n\t\t\t\t\tbest_modelCNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=['mse'])\n\t\t\t\t\n\t\t\t\tscoreCNN = best_modelCNN.evaluate(X1,Y, batch_size=batchsize)\n\t\t\t\tself.log.info(\"----------> Score Matrix: \"+str(best_modelCNN.metrics_names))\n\t\t\t\tself.log.info(\"----------> Score: \"+str(scoreCNN))\t\t\t\t\n\t\t\t\tself.log.info(\"----------> Model Params: \"+str(best_paramsCNN))\n\t\t\t\texecutionTime=time.time() - start\n\t\t\t\tself.log.info('----------> CNN Execution Time: '+str(executionTime)+'\\\\n')\n\t\t\t\t\n\t\t\t\tXSNN = np.expand_dims(self.testX, axis=2)\n\t\t\t\tpredictedData = best_modelCNN.predict(XSNN)\n\t\t\t\tif self.scoreParam.lower() == 'mse':\n\t\t\t\t\tscore = mean_squared_error(self.testY,predictedData)\n\t\t\t\telif self.scoreParam.lower() == 'rmse': \n\t\t\t\t\tscore=mean_squared_error(self.testY,predictedData,squared=False)\n\t\t\t\telif self.scoreParam.lower() == 'mae':\n\t\t\t\t\tscore=mean_absolute_error(self.testY,predictedData)\n\t\t\t\telif self.scoreParam.lower() == 'r2':\n\t\t\t\t\tscore=r2_score(self.testY,predictedData)\n\t\t\t\telse:\n\t\t\t\t\tscore = scoreCNN[1]\n\t\t\t\tself.log.info(\"----------> Testing Score: \"+str(score))\t\t\n\t\t\t\tscoreCNN[1] = score\n\t\t\t\t\n\t\t\t\tif(scoredetails != ''):\n\t\t\t\t\t\tscoredetails += ','\n\t\t\t\tscoredetails += '{\"Model\":\"CNN\",\"FeatureEngineering\":\"'+str(self.best_feature_model)+'\",\"Score\":'+str(scoreCNN[1])+'}'\n\t\t\t\tself.log.info('Status:- |... DL Algorithm applied: CNN')\n\t\t\t\tself.log.info('Status:- |... Score after hyperparameter tuning: '+str(round(score,2)))\n\t\t\t\n\t\t\tmodelScore = []\n\t\t\t \n\t\t\tif len(scoreSNN) != 0:\n\t\t\t\tmodelScore.append(scoreSNN[1])\n\t\t\tif len(scoreRNN) != 0:\n\t\t\t\tmodelScore.append(scoreRNN[1])\n\t\t\tif len(scoreRNNGRU) != 0:\n\t\t\t\tmodelScore.append(scoreRNNGRU[1])\n\t\t\tif len(scoreRNNLSTM) != 0:\n\t\t\t\tmodelScore.append(scoreRNNLSTM[1])\n\t\t\tif len(scoreCNN) != 0:\n\t\t\t\tmodelScore.append(scoreCNN[1])\n \n\t\t\tselectedModel = \"\"\n\t\t\tbest_model = \"\"\n\t\t\tif self.scoreParam == \"r2\":\n\t\t\t\tif len(scoreSNN) != 0 and max(modelScore) == scoreSNN[1]:\n\t\t\t\t\tselectedModel = \"Neural Network\"\n\t\t\t\t\tbest_model = best_modelSNN\n\t\t\t\t\tbest_params = best_paramsSNN\n\n\t\t\t\telif len(scoreRNN) != 0 and max(modelScore) == scoreRNN[1]:\n\t\t\t\t\tselectedModel = \"Recurrent Neural Network\"\n\t\t\t\t\tbest_model = best_modelRNN\n\t\t\t\t\tbest_params = best_paramsRNN\n\n\t\t\t\telif len(scoreRNNGRU) != 0 and max(modelScore) == scoreRNNGRU[1]:\n\t\t\t\t\tselectedModel = \"Recurrent Neural Network (GRU)\"", "instruction": "", "output": "" }, { "input": "\n\t\t\t\t\tbest_model = best_modelRNNGRU\n\t\t\t\t\tbest_params = best_paramsRNNGRU\n\n\t\t\t\telif len(scoreRNNLSTM) != 0 and max(modelScore) == scoreRNNLSTM[1]:\n\t\t\t\t\tselectedModel = \"Recurrent Neural Network (LSTM)\"\n\t\t\t\t\tbest_model = best_modelRNNLSTM\n\t\t\t\t\tbest_params = best_paramsRNNLSTM\n \n\t\t\t\telif len(scoreCNN) != 0 and max(modelScore) == scoreCNN[1]:\n\t\t\t\t\tselectedModel = \"Convolutional Neural Network (1D)\"\n\t\t\t\t\tbest_model = best_modelCNN\n\t\t\t\t\tbest_params = best_paramsCNN\n\n\t\t\t\tmodelScore = max(modelScore)\n\t\t\t\n\t\t\telse:\n\t\t\t\tif len(scoreSNN) != 0 and min(modelScore) == scoreSNN[1]:\n\t\t\t\t\tselectedModel = \"Neural Network\"\n\t\t\t\t\tbest_model = best_modelSNN\n\t\t\t\t\tbest_params = best_paramsSNN\n\n\t\t\t\telif len(scoreRNN) != 0 and min(modelScore) == scoreRNN[1]:\n\t\t\t\t\tselectedModel = \"Recurrent Neural Network\"\n\t\t\t\t\tbest_model = best_modelRNN\n\t\t\t\t\tbest_params = best_paramsRNN\n\n\t\t\t\telif len(scoreRNNGRU) != 0 and min(modelScore) == scoreRNNGRU[1]:\n\t\t\t\t\tselectedModel = \"Recurrent Neural Network (GRU)\"\n\t\t\t\t\tbest_model = best_modelRNNGRU\n\t\t\t\t\tbest_params = best_paramsRNNGRU\n \n\t\t\t\telif len(scoreRNNLSTM) != 0 and min(modelScore) == scoreRNNLSTM[1]:\n\t\t\t\t\tselectedModel = \"Recurrent Neural Network (LSTM)\"\n\t\t\t\t\tbest_model = best_modelRNNLSTM\n\t\t\t\t\tbest_params = best_paramsRNNLSTM\n \n\t\t\t\telif len(scoreCNN) != 0 and min(modelScore) == scoreCNN[1]:\n\t\t\t\t\tselectedModel = \"Convolutional Neural Network (1D)\"\n\t\t\t\t\tbest_model = best_modelCNN\n\t\t\t\t\tbest_params = best_paramsCNN\n\n\t\t\t\tmodelScore = min(modelScore)\n\t\t\t\t\n\t\t\texecutionTime=time.time() - lstart\n\t\t\tself.log.info(\"-------> Total Execution Time(sec):\"+str(executionTime))\n\t\t\tself.log.info('Status:- |... Best Algorithm selected: '+str(selectedModel)+' '+str(round(modelScore,2)))\n\t\t\t\t\t\t\n\t\t\treturn selectedModel,modelScore,best_model,best_params,X1,XSNN,scoredetails,loss_matrix,optimizer\n\n\t\texcept Exception as inst:\n\n self.log.info( '\\\\n-----> regressionModel failed!!!.'+str(inst))\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n self.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\n\t\t\n\n\n\n\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n''' '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\n\nimport numpy as np\nimport pandas as pd\nimport talos\nimport json\nimport sys\nimport time\nimport os\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import f1_score\nimport tensorflow.keras.utils as kutils\nfrom talos.model.normalizers import lr_normalizer\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,Dropout,LSTM,GRU,SimpleRNN,Flatten, Input\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.layers import Conv1D,MaxPooling1D\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.optimizers import Nadam\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.optimizers import SGD\nimport logging\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\n\n\ndef recall_m(y_true, y_pred):\n\ttrue_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n\tpossible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n\trecall = true_positives / (possible_positives + K.epsilon())\n\treturn recall\n\t\ndef precision_m(y_true, y_pred):\n\ttrue_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n\tpredicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n\tprecision = true_positives / (predicted_positives + K.epsilon())\n\treturn precision\n\ndef f1_m(y_true, y_pred):\n\tprecision = precision_m(y_true, y_pred)\n\trecall = recall_m(y_true, y_pred)\n\treturn 2*((precision*recall)/(precision+recall+K.epsilon()))\n\n\nclass DLClassificationModel:\n\t\n\tdef __init__(self,modelList, modelParams, scoreParam, cvSplit, featuresData,\n targetData,testX,testY, method,randomMethod,roundLimit,best_feature_model):\n\n\t\t\n\t\tself.modelList =modelList\n\t\tself.modelParams =modelParams\n\t\tself.scoreParam = scoreParam\n\t\tself.cvSplit =cvSplit\n\t\tself.featuresData =featuresData\n\t\tself.targetData = targetData\n\t\tself.testX = testX\n\t\tself.testY = testY\n\t\tself.method =method\n\t\tself.randomMethod=randomMethod\n\t\tself.roundLimit=roundLimit\n\t\tself.best_feature_model = best_feature_model\n\t\tself.log = logging.getLogger('eion')\n\t\t\n\tdef RNNClassification(self,x_train,y_train,x_val,y_val,params):\n\t\ttf.keras.backend.clear_session()\n\t\tx_train = K.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))\n\t\tx_val = K.reshape(x_val, (x_val.shape[0], x_val.shape[1], 1))\n\t\tmodel = Sequential() \n\t\t\n\t\tif params['RNNType'] == \"LSTM\" :\n\t\t\tif params['numRNNLayers'] > 1: \n\t\t\t\tmodel.add(LSTM(params['first_neuron'],return_sequences=True,input_shape=(x_train.shape[1],1)))\n\t\t\t\tfor x in range(1,params['numRNNLayers']):\n\t\t\t\t\tmodel.add(LSTM(params['first_neuron']))\n\t\t\telse:\n\t\t\t\tmodel.add(LSTM(params['first_neuron'],input_shape=(x_train.shape[1],1)))\n\t\t\t\t\n\t\telif params['RNNType'] == \"GRU\" :\n\t\t\tif params['numRNNLayers'] > 1: \n\t\t\t\tmodel.add(GRU(params['first_neuron'],return_sequences=True,input_shape=(x_train.shape[1],1)))\n\t\t\t\tfor x in range(1,params['numRNNLayers']):\n\t\t\t\t\tmodel.add(GRU(params['first_neuron']))\n\t\t\telse:\n\t\t\t\tmodel.add(GRU(params['first_neuron'],input_shape=(x_train.shape[1],1)))\n\n\t\telif params['RNNType'] == \"SimpleRNN\" :\n\t\t\tif params['numRNNLayers'] > 1: \n\t\t\t\tmodel.add(SimpleRNN(params['first_neuron'],return_sequences=True,input_shape=(x_train.shape[1],1)))\n\t\t\t\tfor x in range(1,params['numRNNLayers']):\n\t\t\t\t\tmodel.add(SimpleRNN(params['first_neuron']))\n\t\t\telse:\n\t\t\t\tmodel.add(SimpleRNN(params['first_neuron'],input_shape=(x_train.shape[1],1)))\n\n\n\t\ttalos.utils.hidden_layers(model, params, x_train.shape[1])\n \n\t\tmodel.add(Dense(y_train.shape[1],activation=params['last_activation']))\n\n\t\tmodel.compile(loss=params['losses'],optimizer=params['optimizer'],metrics=['acc',f1_m,precision_m,recall_m,tf.keras.metrics.AUC()])\n \n\t\tout = model.fit(x_train, y_train, validation_data=(x_val, y_val), batch_size=params['batch_size'],epochs=params['epochs'],verbose=0,shuffle=True)\n \n\t\treturn out, model\n\t\n\tdef SNNClassification(self,x_train,y_train,x_val,y_val,params):\n\t\ttf.keras.backend.clear_session()\n\t\tmodel = Sequential()\n\t\tmodel.add(Dense(params['first_neuron'], input_dim=x_train.shape[1], activation=params['activation']))\n\t\ttalos.utils.hidden_layers(model, params,1)\n\t\tmodel.add(Dropout(params['dropout']))\n\t\tmodel.add(Dense(y_train.shape[1], activation=params['last_activation']))\n\t\tmodel.compile(loss=params['losses'], \n\t\t\toptimizer=params['optimizer'],\n\t\t\t\tmetrics=['acc',f1_m,precision_m,recall_m,tf.keras.metrics.AUC()])\n\t\tout = model.fit(x=x_train, \n\t\t\t y=y_train,\n\t\t\t validation_data=(x_val, y_val),\n\t\t\t epochs=params['epochs'],\n\t\t\t batch_size=params['batch_size'],\n\t\t\t verbose=0)\n\t\t\n\t\treturn out, model\n\n\tdef CNNClassification(self,x_train,y_train,x_val,y_val,params):\n\t\ttf.keras.backend.clear_session()\n\t\tx_train = K.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))\n\t\tx_val = K.reshape(x_val, (x_val.shape[0], x_val.shape[1], 1))\n\t\tmodel = Sequential()\n\t\tmodel.add(Conv1D(filters=params['first_neuron'], kernel_size=(3), activation=params['activation'], input_shape=(x_train.shape[1],1),padding='same') )\n\t\tif params['numConvLayers'] > 1:\n\t\t\tfor x in range(1,params['numConvLayers']):\n\t\t\t\tif params['MaxPool'] == \"True\":\n\t\t\t\t\tmodel.add(MaxPooling1D(pool_size=2,padding='same'))\n\t\t\t\t\tmodel.add(Conv1D(filters=8, kernel_size=3, activation=params['activation'],padding='same'))\n\t\ttalos.utils.hidden_layers(model, params, x_train.shape[1])\n\t\tmodel.add(MaxPooling1D(pool_size=2,padding='same'))\n\t\tmodel.add(Flatten())\n\t\tmodel.add(Dense(y_train.shape[1],activation=params['last_activation']))\n\t\tmodel.compile(loss=params['losses'],optimizer=params['optimizer'],metrics=['acc',f1_m,precision_m,recall_m,tf.keras.metrics.AUC()])\n\t\tout = model.fit(x_train, y_train, validation_data=(x_val, y_val), batch_size=params['batch_size'],\n\t\t\t\tepochs=params['epochs'],verbose=0,shuffle=True)\n\n\t\treturn out, model\n\n\n\tdef TalosScan(self,modelObj):\n\t\t\n\t\ttry:\n\t\t\t#dataPath = pd.read_csv(self.dataLocation)\n\t\t\t#X = dataPath.drop(self.targetData, axis=1)\n\t\t\tloss_matrix='binary_crossentropy'\n\t\t\toptimizer='Nadam'\n\t\t\tX = self.featuresData\n\t\t\tx = X.values\n\t\t\tY = self.targetData\n\t\t\tscoredetails = ''\n\t\t\t#Y= dataPath[self.targetData]\n\t\t\ty = Y.values\n\t\t\ty = kutils.to_categorical(y)\n\t\t\tXSNN = X.values\n\t\t\tX1 = np.expand_dims(X, axis=2)\t\t\t\n\t\t\t\n\n\t\t\tkf = KFold(n_splits = self.cvSplit)\n\t\t\t\n\t\t\tfor train_index, test_index in kf.split(X):\n\t\t\t\tX_train, X_test = x[train_index], x[test_index]\n\t\t\t\ty_train, y_test = y[train_index], y[test_index]\t\n\t\t\t\t\t\n\t\t\tdata = self.modelParams\n\t\t\tmodels = data.keys() \n\t\t\tstart = time.time()\n\t\t\tscoreSNN = []\n\t\t\tscoreRNN = []\n\t\t\tscoreCNN = []\n\t\t\tscoreRNNGRU = []\n\t\t\tscoreRNNLSTM = []\n\t\t\tbest_paramsSNN = {} \t\n\t\t\tbest_paramsRNN = {} \n\t\t\tbest_paramsRNNGRU = {} \n\t\t\tbest_paramsRNNLSTM = {}\n\t\t\tbest_paramsCNN = {} \t\n\t\t\tif \"Neural Network\"in self.modelList:\n\t\t\t\tself.log.info(\"-------> Model Name: Neural Network\")\n\t\t\t\tstart = time.time()\n\t\t\t\tdata = self.modelParams[\"Neural Network\"]\n\t\t\t\t\n\t\t\t\tp = {\"activation\":data[\"activation\"].split(\",\"),\n\t\t\t\t\t \"last_", "instruction": "", "output": "" }, { "input": "activation\":data[\"last_activation\"].split(\",\"),\n\t\t\t\t\t \"optimizer\":data[\"optimizer\"].split(\",\"),\n\t\t\t\t\t \"losses\":data[\"losses\"].split(\",\"),\n\t\t\t\t\t \"first_neuron\":[int(n) for n in data[\"first_layer\"].split(\",\")],\n\t\t\t\t\t \"shapes\": data[\"shapes\"].split(\",\"),\n\t\t\t\t\t \"hidden_layers\":[int(n) for n in data[\"hidden_layers\"].split(\",\")],\n\t\t\t\t\t \"dropout\": [float(n) for n in data[\"dropout\"].split(\",\")],\n\t\t\t\t\t \"lr\": [float(n) for n in data[\"learning_rate\"].split(\",\")],\n\t\t\t\t\t \"batch_size\": [int(n) for n in data[\"batch_size\"].split(\",\")],\n\t\t\t\t\t \"epochs\": [int(n) for n in data[\"epochs\"].split(\",\")]\n\t\t\t\t\t }\n\t\t\t\tparam_combinations = int(np.prod([len(x.split(',')) for x in p]))\n\t\t\t\tround_limit = self.roundLimit if not self.roundLimit else min(self.roundLimit, param_combinations)\n\t\t\t\tscan_object = talos.Scan(x=X_train,\n\t\t\t\t\t\t y=y_train,\n\t\t\t\t\t\t x_val = X_test,\n\t\t\t\t\t\t y_val = y_test,\n\t\t\t\t\t\t model = modelObj.SNNClassification,\n\t\t\t\t\t\t experiment_name='SNN',\n\t\t\t\t\t\t params=p,\n\t\t\t\t\t\tround_limit=round_limit,\n\t\t\t\t\t\t random_method=self.randomMethod\n\t\t\t\t\t )\n\t\t\t\tmatrix_type = 'val_acc'\n\t\t\t\tif self.scoreParam.lower() == 'accuracy':\n\t\t\t\t\tmatrix_type = 'val_acc'\n\t\t\t\telif(self.scoreParam.lower() == 'roc_auc'):\n\t\t\t\t\tmatrix_type = 'val_auc'\n\t\t\t\telif(self.scoreParam.lower() == 'recall'):\n\t\t\t\t\tmatrix_type = 'val_recall_m'\n\t\t\t\telif(self.scoreParam.lower() == 'precision'):\n\t\t\t\t\tmatrix_type = 'val_precision_m'\n\t\t\t\telif(self.scoreParam.lower() == 'f1_score'):\n\t\t\t\t\tmatrix_type = 'val_f1_m'\n\t\t\t\t\t\n\t\t\t\tanalyze_objectSNN = talos.Analyze(scan_object)\t\t\t\t\n\t\t\t\thighValAccSNN = analyze_objectSNN.high(matrix_type)\n\t\t\t\tdfSNN = \tanalyze_objectSNN.data\n\t\t\t\t#pd.set_option('display.max_columns',20)\n\t\t\t\t#print(dfSNN)\n\t\t\t\t#pd.reset_option('display.max_columns')\n\t\t\t\tnewdfSNN = dfSNN.loc[dfSNN[matrix_type] == highValAccSNN]\n\t\t\t\tif(len(newdfSNN) > 1):\n\t\t\t\t\tlowLoss = analyze_objectSNN.low('val_loss')\n\t\t\t\t\tnewdfSNN = newdfSNN.loc[newdfSNN['val_loss'] == lowLoss]\n\t\t\t\tbest_paramsSNN[\"activation\"] = list(newdfSNN[\"activation\"])[0]\n\t\t\t\tbest_paramsSNN[\"optimizer\"] = list(newdfSNN[\"optimizer\"])[0]\n\t\t\t\tbest_paramsSNN[\"losses\"] = list(newdfSNN[\"losses\"])[0]\n\t\t\t\tbest_paramsSNN[\"first_layer\"] = list(newdfSNN[\"first_neuron\"])[0]\n\t\t\t\tbest_paramsSNN[\"shapes\"] = list(newdfSNN[\"shapes\"])[0]\n\t\t\t\tbest_paramsSNN[\"hidden_layers\"] = list(newdfSNN[\"hidden_layers\"])[0]\n\t\t\t\tbest_paramsSNN[\"dropout\"] = list(newdfSNN[\"dropout\"])[0]\n\t\t\t\tbest_paramsSNN[\"batch_size\"] = list(newdfSNN[\"batch_size\"])[0]\n\t\t\t\tbest_paramsSNN[\"epochs\"] = list(newdfSNN[\"epochs\"])[0]\n\t\t\t\tbest_paramsSNN[\"lr\"] = list(newdfSNN[\"lr\"])[0]\n\t\t\t\tbest_paramsSNN[\"last_activation\"] = list(newdfSNN[\"last_activation\"])[0]\t\t\t\t\n\t\t\t\t\n\t\t\t\tbest_modelSNN = scan_object.best_model(metric=matrix_type)\n\t\t\t\ttry:\n\t\t\t\t\tif(len(best_paramsSNN[\"losses\"]) == 0):\n\t\t\t\t\t\tloss_matrix = 'binary_crossentropy'\n\t\t\t\t\telse:\n\t\t\t\t\t\tloss_matrix = best_paramsSNN[\"losses\"]\n\t\t\t\t\tif(len(best_paramsSNN[\"optimizer\"]) == 0):\n\t\t\t\t\t\toptimizer = 'Nadam'\n\t\t\t\t\telse:\n\t\t\t\t\t\toptimizer = best_paramsSNN[\"optimizer\"]\n\t\t\t\t\tif best_paramsSNN[\"batch_size\"] == 0:\n\t\t\t\t\t\tbatchsize = 32\n\t\t\t\t\telse:\n\t\t\t\t\t\tbatchsize = best_paramsSNN[\"batch_size\"]\n\t\t\t\texcept:\n\t\t\t\t\tloss_matrix = 'binary_crossentropy'\n\t\t\t\t\toptimizer = 'Nadam'\n\t\t\t\t\tbatchsize = 32\n\t\t\t\t\t\n\t\t\t\tif self.scoreParam == 'accuracy':\n\t\t\t\t\tbest_modelSNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=['accuracy'])\n\t\t\t\telif self.scoreParam == 'roc_auc':\n\t\t\t\t\tbest_modelSNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[tf.keras.metrics.AUC()])\n\t\t\t\telif self.scoreParam == 'recall':\n\t\t\t\t\tbest_modelSNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[recall_m])\n\t\t\t\telif self.scoreParam == 'precision':\n\t\t\t\t\tbest_modelSNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[precision_m])\n\t\t\t\telif self.scoreParam == 'f1_score':\n\t\t\t\t\tbest_modelSNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[f1_m])\n\t\t\t\t\n\t\t\t\tscoreSNN = best_modelSNN.evaluate(XSNN,y, batch_size=batchsize)\n\t\t\t\tself.log.info(\"----------> Score Matrix: \"+str(best_modelSNN.metrics_names))\n\t\t\t\tself.log.info(\"----------> Score: \"+str(scoreSNN))\n\t\t\t\tself.log.info(\"----------> Model Params: \"+str(best_paramsSNN))\n\t\t\t\texecutionTime=time.time() - start\n\t\t\t\tXSNN = self.testX.values\n\t\t\t\t#predict_x=best_modelSNN.predict(XSNN) \n\t\t\t\tpredictedData=np.argmax(best_modelSNN.predict(XSNN),axis=1)\n\t\t\t\t#predictedData = best_modelSNN.predict_classes(XSNN)\n\t\t\t\t#print(predictedData)\n\t\t\t\t#predictedData = best_modelSNN.predict(self.testX)\n\t\t\t\tif 'accuracy' in str(self.scoreParam):\n\t\t\t\t\tscore = accuracy_score(self.testY,predictedData)\n\t\t\t\telif 'recall' in str(self.scoreParam):\n\t\t\t\t\tscore = recall_score(self.testY,predictedData, average='macro')\n\t\t\t\telif 'precision' in str(self.scoreParam):\n\t\t\t\t\tscore = precision_score(self.testY,predictedData,average='macro')\n\t\t\t\telif 'f1_score' in str(self.scoreParam):\n\t\t\t\t\tscore = f1_score(self.testY,predictedData, average='macro')\n\t\t\t\telif 'roc_auc' in str(self.scoreParam):\n\t\t\t\t\tscore = roc_auc_score(self.testY,predictedData,average=\"macro\")\n\t\t\t\tscore = round((score*100),2) \t\t\t\t\t\n\t\t\t\tself.log.info(\"----------> Testing Score: \"+str(score))\n\t\t\t\tself.log.info('----------> Total Execution: '+str(executionTime)+'\\\\n')\n\t\t\t\tscoreSNN[1] = score\n\t\t\t\tif(scoredetails != ''):\n\t\t\t\t\t\tscoredetails += ','\n\t\t\t\tscoredetails += '{\"Model\":\"Neural Network\",\"FeatureEngineering\":\"'+str(self.best_feature_model)+'\",\"Score\":'+str(scoreSNN[1])+'}'\n\t\t\t\tself.log.info('Status:- |... DL Algorithm applied: Neural Network')\n\t\t\t\tself.log.info('Status:- |... Score after hyperparameter tuning: '+str(round(score,2)))\n \n\t\t\tif \"Recurrent Neural Network\"in self.modelList:\n\t\t\t\tself.log.info(\"-------> Model Name: Recurrent Neural Network\")\n\t\t\t\tstart = time.time()\n\t\t\t\tdata = self.modelParams[\"Recurrent Neural Network\"]\n\t\t\t\tp = {\"RNNType\":[\"SimpleRNN\"],\n\t\t\t\t\t \"numRNNLayers\":[int(n) for n in data[\"numRNNLayers\"].split(\",\")],\n\t\t\t\t\t \"activation\":data[\"activation\"].split(\",\"),\n\t\t\t\t\t \"last_activation\":data[\"last_activation\"].split(\",\"),\n\t\t\t\t\t \"optimizer\":data[\"optimizer\"].split(\",\"),\n\t\t\t\t\t \"losses\":data[\"losses\"].split(\",\"),\n\t\t\t\t\t \"first_neuron\":[int(n) for n in data[\"first_layer\"].split(\",\")],\n\t\t\t\t\t \"shapes\": data[\"shapes\"].split(\",\"),\n\t\t\t\t\t \"hidden_layers\":[int(n) for n in data[\"hidden_layers\"].split(\",\")],\n\t\t\t\t\t \"dropout\": [float(n) for n in data[\"dropout\"].split(\",\")],\n\t\t\t\t\t \"lr\": [float(n) for n in data[\"learning_rate\"].split(\",\")],\n\t\t\t\t\t \"batch_size\": [int(n) for n in data[\"batch_size\"].split(\",\")],\n\t\t\t\t\t \"epochs\": [int(n) for n in data[\"epochs\"].split(\",\")]}\n\t\t\t\tparam_combinations = int(np.prod([len(x.split(',')) for x in p]))\n\t\t\t\tround_limit = self.roundLimit if not self.roundLimit else min(self.roundLimit, param_combinations)\n\n\t\t\t\tscan_object = talos.Scan(x=X_train,\n\t\t\t\t\t\t y=y_train,\n\t\t\t\t\t\t x_val = X_test,\n\t\t\t\t\t\t y_val = y_test,\n\t\t\t\t\t\t model = modelObj.RNNClassification,\n\t\t\t\t\t\t experiment_name='RNN',\n\t\t\t\t\t\t params=p,\n\t\t\t\t\t\t round_limit=round_limit,\n\t\t\t\t\t\t random_method=self.randomMethod\n\t\t\t\t\t )\n\n\t\t\t\tmatrix_type = 'val_acc'\n\t\t\t\tif self.scoreParam.lower() == 'accuracy':\n\t\t\t\t\tmatrix_type = 'val_acc'\n\t\t\t\telif(self.scoreParam.lower() == 'roc_auc'):\n\t\t\t\t\tmatrix_type = 'val_auc'\n\t\t\t\telif(self.scoreParam.lower() == 'recall'):\n\t\t\t\t\tmatrix_type = 'val_recall_m'\n\t\t\t\telif(self.scoreParam.lower() == 'precision'):\n\t\t\t\t\tmatrix_type = 'val_precision_m'\n\t\t\t\telif(self.scoreParam.lower() == 'f1_score'):\n\t\t\t\t\tmatrix_type = 'val_f1_m'\n\t\t\t\t\t\n\t\t\t\tanalyze_objectRNN = talos.Analyze(scan_object)\t\t\t\t\n\t\t\t\thighValAccRNN = analyze_objectRNN.high(matrix_type)\t\t\t\t\n\t\t\t\tdfRNN = \tanalyze_objectRNN.data\n\t\t\t\tnewdfRNN = dfRNN.loc[dfRNN[matrix_type] == highValAccRNN]\n\t\t\t\tif(len(newdfRNN) > 1):\n\t\t\t\t\tlowLoss = analyze_objectRNN.low('val_loss')\n\t\t\t\t\tnewdfRNN = newdfRNN.loc[newdfRNN['val_loss'] == lowLoss]\n\t\t\t\n\t\t\t\tbest_paramsRNN[\"RNNType\"] = list(newdfRNN[\"RNNType\"])[0]\n\t\t\t\tbest_paramsRNN[\"numRNNLayers\"] = list(newdfRNN[\"numRNNLayers\"])[0]\n\t\t\t\tbest_paramsRNN[\"activation\"] = list(newdfRNN[\"activation\"])[0]\n\t\t\t\tbest_paramsRNN[\"optimizer\"] = list(newdfRNN[\"optimizer\"])[0]\n\t\t\t\tbest_paramsRNN[\"losses\"] = list(newdfRNN[\"losses\"])[0]\n\t\t\t\tbest_paramsRNN[\"first_layer\"] = list(newdfRNN[\"first_neuron\"])[0]\n\t\t\t\tbest_paramsRNN[\"shapes\"] = list(newdfRNN[\"shapes\"])[0]\n\t\t\t\tbest_paramsRNN[\"hidden_layers\"] = list(newdfRNN[\"hidden_layers\"])[0]\n\t\t\t\tbest_paramsRNN[\"dropout\"] = list(newdfRNN[\"dropout\"])[0]\n\t\t\t\tbest_paramsRNN[\"batch_size\"] = list(newdfRNN[\"batch_size\"])[0]\n\t\t\t\tbest_paramsRNN[\"epochs\"] = list(newdfRNN[\"epochs\"])[0]\n\t\t\t\tbest_paramsRNN[\"lr\"] = list(newdfRNN[\"lr\"])[0]\n\t\t\t\tbest_paramsRNN[\"last_activation\"] = list(newdfRNN[\"last_activation\"])[0]\n\t\t\n\t\t\t\tbest_modelRNN = scan_object.best_model(metric=matrix_type, asc=False)\n\t\t\t\t\n\t\t\t\ttry:\n\t\t\t\t\tif(len(best_paramsRNN[\"losses\"]) == 0):\n\t\t\t\t\t\tloss_matrix = 'binary_crossentropy'\n\t\t\t\t\telse:\n\t\t\t\t\t\tloss_matrix = best_paramsRNN[\"losses\"][0]\n\t\t\t\t\t\n\t\t\t\t\tif(len(best_paramsRNN[\"optimizer\"]) == 0):\n\t\t\t\t\t\toptimizer = 'Nadam'\n\t\t\t\t\telse:\n\t\t\t\t\t\toptimizer = best_paramsRNN[\"optimizer\"][0]\n\t\t\t\t\t\n\t\t\t\t\tif(best_paramsRNN[\"batch_size\"] == 0):\n\t\t\t\t\t\tbatchsize = 32\n\t\t\t\t\telse:\n\t\t\t\t\t\tbatchsize = best_paramsRNN[\"batch_size\"][0]\n\t\t\t\texcept:\n\t\t\t\t\tloss_matrix = 'binary_crossentropy'\n\t\t", "instruction": "", "output": "" }, { "input": "\t\t\toptimizer = 'Nadam'\n\t\t\t\t\tbatchsize = 32\n\t\t\t\t\t\n\t\t\t\tif self.scoreParam == 'accuracy':\n\t\t\t\t\tbest_modelRNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=['accuracy'])\n\t\t\t\telif self.scoreParam == 'recall':\n\t\t\t\t\tbest_modelRNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[recall_m])\n\t\t\t\telif self.scoreParam == 'roc_auc':\n\t\t\t\t\tbest_modelRNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[tf.keras.metrics.AUC()])\n\t\t\t\telif self.scoreParam == 'precision':\n\t\t\t\t\tbest_modelRNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[precision_m])\n\t\t\t\telif self.scoreParam == 'f1_score':\n\t\t\t\t\tbest_modelRNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[f1_m])\n\t\t\t\tself.log.info(\"----------> Score Matrix: \"+str(best_modelRNN.metrics_names))\n\t\t\t\tscoreRNN = best_modelRNN.evaluate(X1,y, batch_size=batchsize)\t\n\t\t\t\tself.log.info(\"----------> Score: \"+str(scoreRNN))\n\t\t\t\tself.log.info(\"----------> Model Params: \"+str(best_paramsRNN))\n\t\t\t\texecutionTime=time.time() - start\n\t\t\t\tself.log.info('----------> Total Execution: '+str(executionTime)+'\\\\n')\n\t\t\t\t\n\t\t\t\tXSNN = np.expand_dims(self.testX, axis=2)\n\t\t\t\t#predictedData = best_modelRNN.predict_classes(XSNN)\n\t\t\t\tpredictedData=np.argmax(best_modelRNN.predict(XSNN),axis=1)\n\t\t\t\t#predictedData = best_modelSNN.predict(self.testX)\n\t\t\t\tif 'accuracy' in str(self.scoreParam):\n\t\t\t\t\tscore = accuracy_score(self.testY,predictedData)\n\t\t\t\telif 'recall' in str(self.scoreParam):\n\t\t\t\t\tscore = recall_score(self.testY,predictedData, average='macro')\n\t\t\t\telif 'precision' in str(self.scoreParam):\n\t\t\t\t\tscore = precision_score(self.testY,predictedData,average='macro')\n\t\t\t\telif 'f1_score' in str(self.scoreParam):\n\t\t\t\t\tscore = f1_score(self.testY,predictedData, average='macro')\n\t\t\t\telif 'roc_auc' in str(self.scoreParam):\n\t\t\t\t\tscore = roc_auc_score(self.testY,predictedData,average=\"macro\")\n\t\t\t\tscore = round((score*100),2)\n\t\t\t\tself.log.info(\"----------> Testing Score: \"+str(score))\n\t\t\t\tscoreRNN[1] = score\n\t\t\t\tif(scoredetails != ''):\n\t\t\t\t\t\tscoredetails += ','\n\t\t\t\tscoredetails += '{\"Model\":\"Recurrent Neural Network\",\"FeatureEngineering\":\"'+str(self.best_feature_model)+'\",\"Score\":'+str(scoreRNN[1])+'}'\n\t\t\t\tself.log.info('Status:- |... DL Algorithm applied: Recurrent Neural Network')\n\t\t\t\tself.log.info('Status:- |... Score after hyperparameter tuning: '+str(round(score,2)))\n \n\t\t\tif \"Recurrent Neural Network (GRU)\"in self.modelList:\n\t\t\t\tself.log.info(\"-------> Model Name: Recurrent Neural Network (GRU)\")\n\t\t\t\tstart = time.time()\n\t\t\t\tdata = self.modelParams[\"Recurrent Neural Network (GRU)\"]\n\t\t\t\tprint(data)\n\t\t\t\tp = {\"RNNType\":[\"GRU\"],\n\t\t\t\t\t \"numRNNLayers\":[int(n) for n in data[\"numRNNLayers\"].split(\",\")],\n\t\t\t\t\t \"activation\":data[\"activation\"].split(\",\"),\n\t\t\t\t\t \"last_activation\":data[\"last_activation\"].split(\",\"),\n\t\t\t\t\t \"optimizer\":data[\"optimizer\"].split(\",\"),\n\t\t\t\t\t \"losses\":data[\"losses\"].split(\",\"),\n\t\t\t\t\t \"first_neuron\":[int(n) for n in data[\"first_layer\"].split(\",\")],\n\t\t\t\t\t \"shapes\": data[\"shapes\"].split(\",\"),\n\t\t\t\t\t \"hidden_layers\":[int(n) for n in data[\"hidden_layers\"].split(\",\")],\n\t\t\t\t\t \"dropout\": [float(n) for n in data[\"dropout\"].split(\",\")],\n\t\t\t\t\t \"lr\": [float(n) for n in data[\"learning_rate\"].split(\",\")],\n\t\t\t\t\t \"batch_size\": [int(n) for n in data[\"batch_size\"].split(\",\")],\n\t\t\t\t\t \"epochs\": [int(n) for n in data[\"epochs\"].split(\",\")]}\n\t\t\t\tparam_combinations = int(np.prod([len(x.split(',')) for x in p]))\n\t\t\t\tround_limit = self.roundLimit if not self.roundLimit else min(self.roundLimit, param_combinations)\n\n\t\t\t\tscan_object = talos.Scan(x=X_train,\n\t\t\t\t\t\t y=y_train,\n\t\t\t\t\t\t x_val = X_test,\n\t\t\t\t\t\t y_val = y_test,\n\t\t\t\t\t\t model = modelObj.RNNClassification,\n\t\t\t\t\t\t experiment_name='RNN',\n\t\t\t\t\t\t params=p,\n\t\t\t\t\t\t round_limit=round_limit,\n\t\t\t\t\t\t random_method=self.randomMethod\n\t\t\t\t\t )\n\n\t\t\t\tmatrix_type = 'val_acc'\n\t\t\t\tif self.scoreParam.lower() == 'accuracy':\n\t\t\t\t\tmatrix_type = 'val_acc'\n\t\t\t\telif(self.scoreParam.lower() == 'roc_auc'):\n\t\t\t\t\tmatrix_type = 'val_auc'\n\t\t\t\telif(self.scoreParam.lower() == 'recall'):\n\t\t\t\t\tmatrix_type = 'val_recall_m'\n\t\t\t\telif(self.scoreParam.lower() == 'precision'):\n\t\t\t\t\tmatrix_type = 'val_precision_m'\n\t\t\t\telif(self.scoreParam.lower() == 'f1_score'):\n\t\t\t\t\tmatrix_type = 'val_f1_m'\n\t\t\t\t\t\n\t\t\t\tanalyze_objectRNNGRU = talos.Analyze(scan_object)\t\t\t\t\n\t\t\t\thighValAccRNNGRU = analyze_objectRNNGRU.high(matrix_type)\t\t\t\t\n\t\t\t\tdfRNNGRU = \tanalyze_objectRNNGRU.data\n\t\t\t\tnewdfRNNGRU = dfRNNGRU.loc[dfRNNGRU[matrix_type] == highValAccRNNGRU]\n\t\t\t\tif(len(newdfRNNGRU) > 1):\n\t\t\t\t\tlowLoss = analyze_objectRNNGRU.low('val_loss')\n\t\t\t\t\tnewdfRNNGRU = newdfRNNGRU.loc[newdfRNNGRU['val_loss'] == lowLoss]\n\t\t\t\n\t\t\t\tbest_paramsRNNGRU[\"RNNType\"] = \"GRU\"\n\t\t\t\tbest_paramsRNNGRU[\"numRNNLayers\"] = list(newdfRNNGRU[\"numRNNLayers\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"activation\"] = list(newdfRNNGRU[\"activation\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"optimizer\"] = list(newdfRNNGRU[\"optimizer\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"losses\"] = list(newdfRNNGRU[\"losses\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"first_layer\"] = list(newdfRNNGRU[\"first_neuron\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"shapes\"] = list(newdfRNNGRU[\"shapes\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"hidden_layers\"] = list(newdfRNNGRU[\"hidden_layers\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"dropout\"] = list(newdfRNNGRU[\"dropout\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"batch_size\"] = list(newdfRNNGRU[\"batch_size\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"epochs\"] = list(newdfRNNGRU[\"epochs\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"lr\"] = list(newdfRNNGRU[\"lr\"])[0]\n\t\t\t\tbest_paramsRNNGRU[\"last_activation\"] = list(newdfRNNGRU[\"last_activation\"])[0]\n\t\t\n\t\t\t\tbest_modelRNNGRU = scan_object.best_model(metric=matrix_type, asc=False)\n\t\t\t\ttry:\n\t\t\t\t\tif(len(best_paramsRNNGRU[\"losses\"]) == 0):\n\t\t\t\t\t\tloss_matrix = 'binary_crossentropy'\n\t\t\t\t\telse:\n\t\t\t\t\t\tloss_matrix = best_paramsRNNGRU[\"losses\"][0]\n\t\t\t\t\t\n\t\t\t\t\tif(len(best_paramsRNNGRU[\"optimizer\"]) == 0):\n\t\t\t\t\t\toptimizer = 'Nadam'\n\t\t\t\t\telse:\n\t\t\t\t\t\toptimizer = best_paramsRNNGRU[\"optimizer\"][0]\n\t\t\t\t\t\n\t\t\t\t\tif(best_paramsRNNGRU[\"batch_size\"]== 0):\n\t\t\t\t\t\tbatchsize = 32\n\t\t\t\t\telse:\n\t\t\t\t\t\tbatchsize = best_paramsRNNGRU[\"batch_size\"][0]\n\t\t\t\texcept: \n\t\t\t\t\tloss_matrix = 'binary_crossentropy'\n\t\t\t\t\toptimizer = 'Nadam'\n\t\t\t\t\tbatchsize = 32\n\t\t\t\t\t\n\t\t\t\tif self.scoreParam == 'accuracy':\n\t\t\t\t\tbest_modelRNNGRU.compile(loss=loss_matrix,optimizer=optimizer, metrics=['accuracy'])\n\t\t\t\telif self.scoreParam == 'recall':\n\t\t\t\t\tbest_modelRNNGRU.compile(loss=loss_matrix,optimizer=optimizer, metrics=[recall_m])\n\t\t\t\telif self.scoreParam == 'roc_auc':\n\t\t\t\t\tbest_modelRNNGRU.compile(loss=loss_matrix,optimizer=optimizer, metrics=[tf.keras.metrics.AUC()])\n\t\t\t\telif self.scoreParam == 'precision':\n\t\t\t\t\tbest_modelRNNGRU.compile(loss=loss_matrix,optimizer=optimizer, metrics=[precision_m])\n\t\t\t\telif self.scoreParam == 'f1_score':\n\t\t\t\t\tbest_modelRNNGRU.compile(loss=loss_matrix,optimizer=optimizer, metrics=[f1_m])\n\t\t\t\tself.log.info(\"----------> Score Matrix: \"+str(best_modelRNNGRU.metrics_names))\n\t\t\t\tscoreRNNGRU = best_modelRNNGRU.evaluate(X1,y, batch_size=batchsize)\t\n\t\t\t\tself.log.info(\"----------> Score: \"+str(scoreRNNGRU))\n\t\t\t\tself.log.info(\"----------> Model Params: \"+str(best_paramsRNNGRU))\n\t\t\t\texecutionTime=time.time() - start\n\t\t\t\tself.log.info('----------> Total Execution: '+str(executionTime)+'\\\\n')\n\t\t\t\t\n\t\t\t\tXSNN = np.expand_dims(self.testX, axis=2)\n\t\t\t\t#predictedData = best_modelRNNGRU.predict_classes(XSNN)\n\t\t\t\tpredictedData=np.argmax(best_modelRNNGRU.predict(XSNN),axis=1)\n\t\t\t\t#predictedData = best_modelSNN.predict(self.testX)\n\t\t\t\tif 'accuracy' in str(self.scoreParam):\n\t\t\t\t\tscore = accuracy_score(self.testY,predictedData)\n\t\t\t\telif 'recall' in str(self.scoreParam):\n\t\t\t\t\tscore = recall_score(self.testY,predictedData, average='macro')\n\t\t\t\telif 'precision' in str(self.scoreParam):\n\t\t\t\t\tscore = precision_score(self.testY,predictedData,average='macro')\n\t\t\t\telif 'f1_score' in str(self.scoreParam):\n\t\t\t\t\tscore = f1_score(self.testY,predictedData, average='macro')\n\t\t\t\telif 'roc_auc' in str(self.scoreParam):\n\t\t\t\t\tscore = roc_auc_score(self.testY,predictedData,average=\"macro\")\n\t\t\t\tscore = round((score*100),2)\n\t\t\t\tself.log.info(\"----------> Testing Score: \"+str(score))\n\t\t\t\tscoreRNNGRU[1] = score\n\t\t\t\tif(scoredetails != ''):\n\t\t\t\t\t\tscoredetails += ','\n\t\t\t\tscoredetails += '{\"Model\":\"Recurrent Neural Network (GRU)\",\"FeatureEngineering\":\"'+str(self.best_feature_model)+'\",\"Score\":'+str(scoreRNNGRU[1])+'}'\n\t\t\t\tself.log.info('Status:- |... DL Algorithm applied: Recurrent Neural Network (GRU)')\n\t\t\t\tself.log.info('Status:- |... Score after hyperparameter tuning: '+str(round(score,2)))\t\t\t\n\t\t\t\n\t\t\tif \"Recurrent Neural Network (LSTM)\"in self.modelList:\n\t\t\t\tself.log.info(\"-------> Model Name: Recurrent Neural Network (LSTM)\")\n\t\t\t\tstart = time.time()\n\t\t\t\tdata = self.modelParams[\"Recurrent Neural Network (LSTM)\"]\n\t\t\t\tp = {\"RNNType\":[\"LSTM\"],\n\t\t\t\t\t \"numRNNLayers\":[int(n) for n in data[\"numRNNLayers\"].split(\",\")],\n\t\t\t\t\t \"activation\":data[\"activation\"].split(\",\"),\n\t\t\t\t\t \"last_activation\":data[\"last_activation\"].split(\",\"),\n\t\t\t\t\t \"optimizer\":data[\"optimizer\"].split(\",\"),\n\t\t\t\t\t \"losses\":data[\"losses\"].split(\",\"),\n\t\t\t\t\t \"first_neuron\":[int(n) for n in data[\"first_layer\"].split(\",\")],\n\t\t\t\t\t \"shapes\": data[\"shapes\"].split(\",\"),\n\t\t\t\t\t \"hidden_layers\":[int(n) for n in data[\"hidden_layers\"].split(\",\")],\n\t\t\t\t\t \"dropout\": [float(n) for n in data[\"dropout\"].split(\",\")],\n\t\t\t\t\t \"lr\": [float(n) for n in data[\"learning_rate\"].split(\",\")],\n\t\t\t\t\t \"batch_size\": [int(n) for n in data[\"batch_size\"].split(\",\")],\n\t\t\t\t\t \"epochs\": [int(n) for n in data[\"ep", "instruction": "", "output": "" }, { "input": "ochs\"].split(\",\")]}\n\t\t\t\tparam_combinations = int(np.prod([len(x.split(',')) for x in p]))\n\t\t\t\tround_limit = self.roundLimit if not self.roundLimit else min(self.roundLimit, param_combinations)\n\n\t\t\t\tscan_object = talos.Scan(x=X_train,\n\t\t\t\t\t\t y=y_train,\n\t\t\t\t\t\t x_val = X_test,\n\t\t\t\t\t\t y_val = y_test,\n\t\t\t\t\t\t model = modelObj.RNNClassification,\n\t\t\t\t\t\t experiment_name='RNN',\n\t\t\t\t\t\t params=p,\n\t\t\t\t\t\t round_limit=round_limit,\n\t\t\t\t\t\t random_method=self.randomMethod\n\t\t\t\t\t )\n\n\t\t\t\tmatrix_type = 'val_acc'\n\t\t\t\tif self.scoreParam.lower() == 'accuracy':\n\t\t\t\t\tmatrix_type = 'val_acc'\n\t\t\t\telif(self.scoreParam.lower() == 'roc_auc'):\n\t\t\t\t\tmatrix_type = 'val_auc'\n\t\t\t\telif(self.scoreParam.lower() == 'recall'):\n\t\t\t\t\tmatrix_type = 'val_recall_m'\n\t\t\t\telif(self.scoreParam.lower() == 'precision'):\n\t\t\t\t\tmatrix_type = 'val_precision_m'\n\t\t\t\telif(self.scoreParam.lower() == 'f1_score'):\n\t\t\t\t\tmatrix_type = 'val_f1_m'\n\t\t\t\t\t\n\t\t\t\tanalyze_objectRNNLSTM = talos.Analyze(scan_object)\t\t\t\t\n\t\t\t\thighValAccRNNLSTM = analyze_objectRNNLSTM.high(matrix_type)\t\t\t\t\n\t\t\t\tdfRNNLSTM = \tanalyze_objectRNNLSTM.data\n\t\t\t\tnewdfRNNLSTM = dfRNNLSTM.loc[dfRNNLSTM[matrix_type] == highValAccRNNLSTM]\n\t\t\t\tif(len(newdfRNNLSTM) > 1):\n\t\t\t\t\tlowLoss = analyze_objectRNNLSTM.low('val_loss')\n\t\t\t\t\tnewdfRNNLSTM = newdfRNNLSTM.loc[newdfRNNLSTM['val_loss'] == lowLoss]\n\t\t\t\n\t\t\t\tbest_paramsRNNLSTM[\"RNNType\"] = \"LSTM\"\n\t\t\t\tbest_paramsRNNLSTM[\"numRNNLayers\"] = list(newdfRNNLSTM[\"numRNNLayers\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"activation\"] = list(newdfRNNLSTM[\"activation\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"optimizer\"] = list(newdfRNNLSTM[\"optimizer\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"losses\"] = list(newdfRNNLSTM[\"losses\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"first_layer\"] = list(newdfRNNLSTM[\"first_neuron\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"shapes\"] = list(newdfRNNLSTM[\"shapes\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"hidden_layers\"] = list(newdfRNNLSTM[\"hidden_layers\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"dropout\"] = list(newdfRNNLSTM[\"dropout\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"batch_size\"] = list(newdfRNNLSTM[\"batch_size\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"epochs\"] = list(newdfRNNLSTM[\"epochs\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"lr\"] = list(newdfRNNLSTM[\"lr\"])[0]\n\t\t\t\tbest_paramsRNNLSTM[\"last_activation\"] = list(newdfRNNLSTM[\"last_activation\"])[0]\n\t\t\n\t\t\t\tbest_modelRNNLSTM = scan_object.best_model(metric=matrix_type, asc=False)\n\t\t\t\ttry:\n\t\t\t\t\tif(len(best_paramsRNNLSTM[\"losses\"]) == 0):\n\t\t\t\t\t\tloss_matrix = 'binary_crossentropy'\n\t\t\t\t\telse:\n\t\t\t\t\t\tloss_matrix = best_paramsRNNLSTM[\"losses\"][0]\n\t\t\t\t\t\n\t\t\t\t\tif(len(best_paramsRNNLSTM[\"optimizer\"]) == 0):\n\t\t\t\t\t\toptimizer = 'Nadam'\n\t\t\t\t\telse:\n\t\t\t\t\t\toptimizer = best_paramsRNNLSTM[\"optimizer\"][0]\n\t\t\t\t\t\n\t\t\t\t\tif(best_paramsRNNLSTM[\"batch_size\"] == 0):\n\t\t\t\t\t\tbatchsize = 32\n\t\t\t\t\telse:\n\t\t\t\t\t\tbatchsize = best_paramsRNNLSTM[\"batch_size\"][0]\n\t\t\t\texcept:\n\t\t\t\t\tloss_matrix = 'binary_crossentropy'\n\t\t\t\t\toptimizer = 'Nadam'\n\t\t\t\t\tbatchsize = 32\n\t\t\t\t\t\n\t\t\t\tif self.scoreParam == 'accuracy':\n\t\t\t\t\tbest_modelRNNLSTM.compile(loss=loss_matrix,optimizer=optimizer, metrics=['accuracy'])\n\t\t\t\telif self.scoreParam == 'recall':\n\t\t\t\t\tbest_modelRNNLSTM.compile(loss=loss_matrix,optimizer=optimizer, metrics=[recall_m])\n\t\t\t\telif self.scoreParam == 'roc_auc':\n\t\t\t\t\tbest_modelRNNLSTM.compile(loss=loss_matrix,optimizer=optimizer, metrics=[tf.keras.metrics.AUC()])\n\t\t\t\telif self.scoreParam == 'precision':\n\t\t\t\t\tbest_modelRNNLSTM.compile(loss=loss_matrix,optimizer=optimizer, metrics=[precision_m])\n\t\t\t\telif self.scoreParam == 'f1_score':\n\t\t\t\t\tbest_modelRNNLSTM.compile(loss=loss_matrix,optimizer=optimizer, metrics=[f1_m])\n\t\t\t\tself.log.info(\"----------> Score Matrix: \"+str(best_modelRNNLSTM.metrics_names))\n\t\t\t\tscoreRNNLSTM = best_modelRNNLSTM.evaluate(X1,y, batch_size=batchsize)\t\n\t\t\t\tself.log.info(\"----------> Score: \"+str(scoreRNNLSTM))\n\t\t\t\tself.log.info(\"----------> Model Params: \"+str(best_paramsRNNLSTM))\n\t\t\t\texecutionTime=time.time() - start\n\t\t\t\tself.log.info('----------> Total Execution: '+str(executionTime)+'\\\\n')\n\t\t\t\t\n\t\t\t\tXSNN = np.expand_dims(self.testX, axis=2)\n\t\t\t\t#predictedData = best_modelRNNLSTM.predict_classes(XSNN)\n\t\t\t\tpredictedData=np.argmax(best_modelRNNLSTM.predict(XSNN),axis=1)\n\t\t\t\t#predictedData = best_modelSNN.predict(self.testX)\n\t\t\t\tif 'accuracy' in str(self.scoreParam):\n\t\t\t\t\tscore = accuracy_score(self.testY,predictedData)\n\t\t\t\telif 'recall' in str(self.scoreParam):\n\t\t\t\t\tscore = recall_score(self.testY,predictedData, average='macro')\n\t\t\t\telif 'precision' in str(self.scoreParam):\n\t\t\t\t\tscore = precision_score(self.testY,predictedData,average='macro')\n\t\t\t\telif 'f1_score' in str(self.scoreParam):\n\t\t\t\t\tscore = f1_score(self.testY,predictedData, average='macro')\n\t\t\t\telif 'roc_auc' in str(self.scoreParam):\n\t\t\t\t\tscore = roc_auc_score(self.testY,predictedData,average=\"macro\")\n\t\t\t\tscore = round((score*100),2) \n\t\t\t\tself.log.info(\"----------> Testing Score: \"+str(score))\n\t\t\t\tscoreRNNLSTM[1] = score\n\t\t\t\tif(scoredetails != ''):\n\t\t\t\t\t\tscoredetails += ','\n\t\t\t\tscoredetails += '{\"Model\":\"Recurrent Neural Network (LSTM)\",\"FeatureEngineering\":\"'+str(self.best_feature_model)+'\",\"Score\":'+str(scoreRNNLSTM[1])+'}'\n\t\t\t\tself.log.info('Status:- |... DL Algorithm applied: Recurrent Neural Network (LSTM)')\n\t\t\t\tself.log.info('Status:- |... Score after hyperparameter tuning: '+str(round(score,2)))\n \n\t\t\tif \"Convolutional Neural Network (1D)\"in self.modelList:\n\t\t\t\tself.log.info(\"-------> Model Name: CNN\")\n\t\t\t\tstart = time.time()\n\t\t\t\tdata = self.modelParams[\"Convolutional Neural Network (1D)\"]\n\t\t\t\tp = {\"activation\":data[\"activation\"].split(\",\"),\n\t\t\t\t\t\"last_activation\":data[\"last_activation\"].split(\",\"),\n\t\t\t\t\t \"numConvLayers\":[int(n) for n in data[\"numConvLayers\"].split(\",\")],\n\t\t\t\t\t \"MaxPool\":data[\"activation\"].split(\",\"),\n\t\t\t\t\t \"optimizer\":data[\"optimizer\"].split(\",\"),\n\t\t\t\t\t \"losses\":data[\"losses\"].split(\",\"),\n\t\t\t\t\t \"first_neuron\":[int(n) for n in data[\"first_layer\"].split(\",\")],\n\t\t\t\t\t \"shapes\": data[\"shapes\"].split(\",\"),\n\t\t\t\t\t \"hidden_layers\":[int(n) for n in data[\"hidden_layers\"].split(\",\")],\n\t\t\t\t\t \"dropout\": [float(n) for n in data[\"dropout\"].split(\",\")],\n\t\t\t\t\t \"lr\": [float(n) for n in data[\"learning_rate\"].split(\",\")],\n\t\t\t\t\t \"batch_size\": [int(n) for n in data[\"batch_size\"].split(\",\")],\n\t\t\t\t\t \"epochs\": [int(n) for n in data[\"epochs\"].split(\",\")]}\n\t\t\t\tparam_combinations = int(np.prod([len(x.split(',')) for x in p]))\n\t\t\t\tround_limit = self.roundLimit if not self.roundLimit else min(self.roundLimit, param_combinations)\n\t\t\t\tscan_object = talos.Scan(x=X_train,\n\t\t\t\t\t\t y=y_train,\n\t\t\t\t\t\t x_val = X_test,\n\t\t\t\t\t\t y_val = y_test,\n\t\t\t\t\t\t model = modelObj.CNNClassification,\n\t\t\t\t\t\t experiment_name='CNN',\n\t\t\t\t\t\t params=p,\n\t\t\t\t\t\t round_limit=round_limit,\n\t\t\t\t\t\t random_method=self.randomMethod\n\t\t\t\t\t )\n\t\t\t\tmatrix_type = 'val_acc'\n\t\t\t\tif self.scoreParam.lower() == 'accuracy':\n\t\t\t\t\tmatrix_type = 'val_acc'\n\t\t\t\telif(self.scoreParam.lower() == 'roc_auc'):\n\t\t\t\t\tmatrix_type = 'val_auc'\n\t\t\t\telif(self.scoreParam.lower() == 'recall'):\n\t\t\t\t\tmatrix_type = 'val_recall_m'\n\t\t\t\telif(self.scoreParam.lower() == 'precision'):\n\t\t\t\t\tmatrix_type = 'val_precision_m'\n\t\t\t\telif(self.scoreParam.lower() == 'f1_score'):\n\t\t\t\t\tmatrix_type = 'val_f1_m'\n\t\t\t\tanalyze_objectCNN = talos.Analyze(scan_object)\t\t\t\t\n\t\t\t\thighValAccCNN = analyze_objectCNN.high(matrix_type)\t\t\t\t\n\t\t\t\tdfCNN = \tanalyze_objectCNN.data\n\t\t\t\n\t\t\t\tnewdfCNN = dfCNN.loc[dfCNN[matrix_type] == highValAccCNN]\n\t\t\t\tif(len(newdfCNN) > 1):\n\t\t\t\t\tlowLoss = analyze_objectCNN.low('val_loss')\n\t\t\t\t\tnewdfCNN = newdfCNN.loc[newdfCNN['val_loss'] == lowLoss]\n\t\t\t\n\t\t\t\tbest_paramsCNN[\"numConvLayers\"] = list(newdfCNN[\"numConvLayers\"])\n\t\t\t\tbest_paramsCNN[\"MaxPool\"] = list(newdfCNN[\"MaxPool\"])\n\t\t\t\tbest_paramsCNN[\"activation\"] = list(newdfCNN[\"activation\"])\n\t\t\t\tbest_paramsCNN[\"optimizer\"] = list(newdfCNN[\"optimizer\"])\n\t\t\t\tbest_paramsCNN[\"losses\"] = list(newdfCNN[\"losses\"])\n\t\t\t\tbest_paramsCNN[\"first_layer\"] = list(newdfCNN[\"first_neuron\"])\n\t\t\t\tbest_paramsCNN[\"shapes\"] = list(newdfCNN[\"shapes\"])\n\t\t\t\tbest_paramsCNN[\"hidden_layers\"] = list(newdfCNN[\"hidden_layers\"])\n\t\t\t\tbest_paramsCNN[\"dropout\"] = list(newdfCNN[\"dropout\"])\n\t\t\t\tbest_paramsCNN[\"batch_size\"] = list(newdfCNN[\"batch_size\"])\n\t\t\t\tbest_paramsCNN[\"epochs\"] = list(newdfCNN[\"epochs\"])\n\t\t\t\tbest_paramsCNN[\"lr\"] = list(newdfCNN[\"lr\"])\n\t\t\t\tbest_paramsCNN[\"last_activation\"] = list(newdfCNN[\"last_activation\"])[0]\n\t\t\n\t\t\t\tbest_modelCNN = scan_object.best_model(metric='val_acc', asc=True)\n\t\t\t\ttry:\n\t\t\t\t\tif(len(best_paramsCNN[\"losses\"]) == 0):\n\t\t\t\t\t\tloss_matrix = 'binary_crossentropy'\n\t\t\t\t\telse:\n\t\t\t\t\t\tloss_matrix = best_paramsCNN[\"losses\"][0]\n\t\t\t\t\tif(len(best_paramsCNN[\"optimizer\"]) == 0):\n\t\t\t\t\t\toptimizer = 'Nadam'\n\t\t\t\t\telse:\n\t\t\t\t\t\toptimizer = best_paramsCNN[\"optimizer\"][0]\n\t\t\t\t\t\n\t\t\t\t\tif(best_paramsCNN[\"batch_size\"] == 0):\n\t\t\t\t\t\tbatchsize = 32\n\t\t\t\t\telse:\n\t\t\t\t\t\tbatchsize = best_paramsCNN[\"batch_size\"][0]\n\t\t\t\texcept:\n\t\t\t\t\tloss_matrix = 'binary_crossentropy'\n\t\t\t\t\toptimizer = 'Nadam'\n\t\t\t\t\tbatchsize = 32\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\tif self.scoreParam == 'accuracy':\n\t\t\t\t\tbest_modelCNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=['accuracy'])\n\t", "instruction": "", "output": "" }, { "input": "\t\t\telif self.scoreParam == 'recall':\n\t\t\t\t\tbest_modelCNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[recall_m])\n\t\t\t\telif self.scoreParam == 'precision':\n\t\t\t\t\tbest_modelCNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[precision_m])\n\t\t\t\telif self.scoreParam == 'roc_auc':\n\t\t\t\t\tbest_modelCNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[tf.keras.metrics.AUC()])\n\t\t\t\telif self.scoreParam == 'f1_score':\n\t\t\t\t\tbest_modelCNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[f1_m])\n\t\t\t\tself.log.info(\"----------> Score Matrix: \"+str(best_modelCNN.metrics_names))\n\t\t\t\tscoreCNN = best_modelCNN.evaluate(X1,y, batch_size=batchsize)\n\t\t\t\tself.log.info(\"----------> Score: \"+str(scoreCNN))\t\t\t\t\n\t\t\t\tself.log.info(\"----------> Model Params: \"+str(best_paramsCNN))\n\t\t\t\texecutionTime=time.time() - start\n\t\t\t\tself.log.info('----------> Total Execution: '+str(executionTime)+'\\\\n')\n\t\t\t\t\n\t\t\t\tXSNN = np.expand_dims(self.testX, axis=2)\n\t\t\t\t#predictedData = best_modelCNN.predict_classes(XSNN)\n\t\t\t\tpredictedData=np.argmax(best_modelCNN.predict(XSNN),axis=1)\n\t\t\t\t#predictedData = best_modelSNN.predict(self.testX)\n\t\t\t\tif 'accuracy' in str(self.scoreParam):\n\t\t\t\t\tscore = accuracy_score(self.testY,predictedData)\n\t\t\t\telif 'recall' in str(self.scoreParam):\n\t\t\t\t\tscore = recall_score(self.testY,predictedData, average='macro')\n\t\t\t\telif 'precision' in str(self.scoreParam):\n\t\t\t\t\tscore = precision_score(self.testY,predictedData,average='macro')\n\t\t\t\telif 'f1_score' in str(self.scoreParam):\n\t\t\t\t\tscore = f1_score(self.testY,predictedData, average='macro')\n\t\t\t\telif 'roc_auc' in str(self.scoreParam):\n\t\t\t\t\tscore = roc_auc_score(self.testY,predictedData,average=\"macro\")\n\t\t\t\tscore = round((score*100),2) \t\t\t\t\n\t\t\t\tself.log.info(\"----------> Testing Score: \"+str(score))\n\t\t\t\tscoreCNN[1] = score\n\t\t\t\t\n\t\t\t\tif(scoredetails != ''):\n\t\t\t\t\t\tscoredetails += ','\n\t\t\t\tscoredetails += '{\"Model\":\"Convolutional Neural Network (1D)\",\"FeatureEngineering\":\"'+str(self.best_feature_model)+'\",\"Score\":'+str(scoreCNN[1])+'}'\n\t\t\t\tself.log.info('Status:- |... DL Algorithm applied: Convolutional Neural Network (1D)')\n\t\t\t\tself.log.info('Status:- |... Score after hyperparameter tuning: '+str(round(score,2)))\n\t\t\tmodelScore = []\n\t\t\tif len(scoreSNN) != 0:\n\t\t\t\tmodelScore.append(scoreSNN[1])\n\t\t\tif len(scoreRNN) != 0:\n\t\t\t\tmodelScore.append(scoreRNN[1])\n\t\t\tif len(scoreRNNGRU) != 0:\n\t\t\t\tmodelScore.append(scoreRNNGRU[1])\n\t\t\tif len(scoreRNNLSTM) != 0:\n\t\t\t\tmodelScore.append(scoreRNNLSTM[1])\n\t\t\tif len(scoreCNN) != 0:\n\t\t\t\tmodelScore.append(scoreCNN[1])\n \n\t\t\tselectedModel = \"\"\n\t\t\tbest_params=\"\"\n\t\t\tif len(scoreSNN) != 0 and max(modelScore) == scoreSNN[1]:\n\t\t\t\tselectedModel = \"Neural Network\"\n\t\t\t\tbest_model = best_modelSNN\n\t\t\t\tbest_params = best_paramsSNN\n \t\t\t\t\n\t\t\telif len(scoreRNN) != 0 and max(modelScore) == scoreRNN[1]:\n\t\t\t\tselectedModel = \"Recurrent Neural Network\"\n\t\t\t\tbest_model = best_modelRNN\n\t\t\t\tbest_params = best_paramsRNN\n\n\t\t\telif len(scoreRNNGRU) != 0 and max(modelScore) == scoreRNNGRU[1]:\n\t\t\t\tselectedModel = \"Recurrent Neural Network (GRU)\"\n\t\t\t\tbest_model = best_modelRNNGRU\n\t\t\t\tbest_params = best_paramsRNNGRU\n \n\t\t\telif len(scoreRNNLSTM) != 0 and max(modelScore) == scoreRNNLSTM[1]:\n\t\t\t\tselectedModel = \"Recurrent Neural Network (LSTM)\"\n\t\t\t\tbest_model = best_modelRNNLSTM\n\t\t\t\tbest_params = best_paramsRNNLSTM\n \n\t\t\telif len(scoreCNN) != 0 and max(modelScore) == scoreCNN[1]:\n\t\t\t\tselectedModel = \"Convolutional Neural Network (1D)\"\n\t\t\t\tbest_model = best_modelCNN\n\t\t\t\tbest_params = best_paramsCNN\n\n\n\t\t\tmodelScore = max(modelScore)\n\t\t\texecutionTime=time.time() - start\n\t\t\tself.log.info(\"-------> ExecutionTime(sec) :\"+str(executionTime)+'\\\\n')\n\t\t\tself.log.info('Status:- |... Best Algorithm selected: '+str(selectedModel)+' '+str(round(modelScore,2)))\n\t\t\tself.log.info('-------> Best Params: '+str(best_params))\n\t\t\treturn selectedModel,modelScore,best_model,best_params,X1,XSNN,scoredetails,loss_matrix,optimizer\n\n\t\texcept Exception as inst:\n\t\t\tself.log.info( '\\\\n-----> classificationModel failed!!!.'+str(inst))\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno)) '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport json\nfrom pathlib import Path\nfrom AION.prediction_package.imports import importModule\nfrom AION.prediction_package import utility\nfrom AION.prediction_package.utility import TAB_CHAR\nfrom importlib.metadata import version\n\n\"\"\"\n This file provide the functionality which is common for most of the\n problem types deployment. \n\"\"\"\n\ndef main_code():\n return \"\"\"\nclass predict():\n\n def __init__(self):\n self.profiler = inputprofiler()\n self.selector = selector()\n self.trainer = trainer()\n self.formatter = output_format()\n\n def run(self, data):\n try:\n df = self._parse_data(data)\n raw_df = df.copy()\n df = self.profiler.run(df)\n df = self.selector.run(df)\n df = self.trainer.run(df)\n output = self.formatter.run(raw_df, df)\n print(\"predictions:\",output)\n return (output)\n except Exception as e:\n output = {\"status\":\"FAIL\",\"message\":str(e).strip('\"')}\n print(\"predictions:\",json.dumps(output))\n return (json.dumps(output))\n \n def _parse_data(self, data):\n file_path = Path(data)\n if file_path.suffix == \".tsv\":\n df = pd.read_csv(data,encoding='utf-8',sep='\\\\\\\\t',skipinitialspace = True,na_values=['-','?'])\n elif file_path.suffix in [\".csv\", \".dat\"]:\n df=pd.read_csv(data,encoding='utf-8',skipinitialspace = True,na_values=['-','?'])\n elif file_path.suffix in [\".gz\"] and file_path.stem.endswith('.csv'):\n df=pd.read_csv(data,encoding='utf-8',skipinitialspace = True,na_values=['-','?'])\n elif file_path.suffix == \".json\":\n with open(data,'r',encoding='utf-8') as f:\n jsonData = json.load(f)\n df = pd.json_normalize(jsonData)\n else:\n jsonData = json.loads(data)\n df = pd.json_normalize(jsonData)\n return df\n \nimport sys\nif __name__ == \"__main__\":\n\toutput = predict().run(sys.argv[1])\n \"\"\"\n\ndef profiler_code(params, indent=0):\n \"\"\"\n This will create the profiler file based on the config file.\n separated file is created as profiler is required for input drift also.\n \"\"\"\n imported_modules = [\n {'module': 'json', 'mod_from': None, 'mod_as': None},\n {'module': 'scipy', 'mod_from': None, 'mod_as': None},\n {'module': 'joblib', 'mod_from': None, 'mod_as': None},\n {'module': 'numpy', 'mod_from': None, 'mod_as': 'np'},\n {'module': 'pandas', 'mod_from': None, 'mod_as': 'pd'},\n {'module': 'Path', 'mod_from': 'pathlib', 'mod_as': None}\n ]\n importer = importModule()\n utility.import_modules(importer, imported_modules)\n code = \"\"\" \n\n\nclass inputprofiler():\n\"\"\"\n init_code = \"\"\"\n def __init__(self):\n\"\"\"\n if params.get('text_features'):\n imported_modules.append({'module':'importlib.util'})\n init_code += \"\"\"\n # preprocessing\n preprocess_path = Path(__file__).parent.parent/'model'/'preprocess_pipe.pkl'\n if not preprocess_path.exists():\n raise ValueError(f'Preprocess model file not found: {preprocess_path}')\n self.profiler = joblib.load(preprocess_path)\n\n\"\"\"\n run_code = \"\"\"\n def run(self,df):\n df = df.replace(r'^\\\\s*$', np.NaN, regex=True)\n\"\"\"\n if params.get('input_features_type'):\n imported_modules.append({'module':'dtype','mod_from':'numpy'})\n run_code += f\"\"\"\n df = df.astype({params.get('input_features_type')})\n\"\"\"\n if params.get('word2num_features'):\n imported_modules.append({'module':'w2n','mod_from':'word2number'})\n run_code += f\"\"\"\n def s2n(value):\n try:\n x=eval(value)\n return x\n except:\n try:\n return w2n.word_to_num(value)\n except:\n return np.nan \n df[{params['word2num_features']}] = df[{params['word2num_features']}].apply(lambda x: s2n(x))\"\"\"\n if params.get('unpreprocessed_columns'):\n run_code += f\"\"\"\n unpreprocessed_data = df['{params['unpreprocessed_columns'][0]}']\n df.drop(['{params['unpreprocessed_columns'][0]}'], axis=1,inplace=True)\n \"\"\"\n if params.get('force_numeric_conv'):\n run_code += f\"\"\"\n df[{params['force_numeric_conv']}] = df[{params['force_numeric_conv']}].apply(pd.to_numeric,errors='coerce')\"\"\"\n if params.get('conversion_method','').lower() == 'glove':\n code_text, modules = __profiler_glove_code(params)\n imported_modules.extend( modules)\n init_code += code_text\n elif params.get('conversion_method','').lower() == 'fasttext':\n init_code += __profiler_fasttext_code(params)\n run_code += __profiler_main_code(params)\n if params.get('unpreprocessed_columns'):\n run_code += f\"\"\"\n df['{params.get('unpreprocessed_columns')[0]}'] = unpreprocessed_data\n \"\"\"\n utility.import_modules(importer, imported_modules)\n import_code = importer.getCode()\n return import_code + code + init_code + run_code\n\ndef __profiler_glove_code(params, indent=2):\n modules = []\n modules.append({'module':'load_pretrained','mod_from':'text.Embedding'})\n modules.append({'module':'TextProcessing','mod_from':'text'})\n code = \"\"\"\nmodel_path = TextProcessing.checkAndDownloadPretrainedModel('glove')\nembed_size, pretrained_model = load_pretrained(model_path)\nself.profiler.set_params(text_process__vectorizer__external_model = pretrained_model)\n\"\"\"\n return code.replace('\\\\n', '\\\\n'+(indent * TAB_CHAR)), modules\n\ndef __profiler_fasttext_code(params, indent=2):\n code = \"\"\"\ndef get_pretrained_model_path():\n try:\n from AION.appbe.dataPath import DATA_DIR\n modelsPath = Path(DATA_DIR)/'PreTrainedModels'/'TextProcessing'\n except:\n modelsPath = Path('aion')/'PreTrainedModels'/'TextProcessing'\n \n if not modelsPath.exists():\n modelsPath.mkdir(parents=True, exist_ok=True)\n return modelsPath\nif not importlib.util.find_spec('fasttext'):\n raise ValueError('fastText not installed')\nelse:\n import os\n import fasttext\n import fasttext.util\n cwd = os.getcwd()\n os.chdir(get_pretrained_model_path())\n fasttext.util.download_model('en', if_exists='ignore')\n pretrained_model = fasttext.load_model('cc.en.300.bin')\n os.chdir(cwd)\nself.profiler.set_params(text_process__vectorizer__external_model = pretrained_model)\nself.profiler.set_params(text_process__vectorizer__external_model_type = 'binary')\n\"\"\"\n return code.replace('\\\\n', '\\\\n'+(indent * TAB_CHAR))\n\ndef __profiler_main_code(params, indent=2):\n code = f\"\"\"\ndf = self.profiler.transform(df)\ncolumns = {params['output_features']}\nif isinstance(df, scipy.sparse.spmatrix):\n df = pd.DataFrame(df.toarray(), columns=", "instruction": "", "output": "" }, { "input": "columns)\nelse:\n df = pd.DataFrame(df, columns=columns)\nreturn df\n\"\"\"\n return code.replace('\\\\n', '\\\\n'+(indent * TAB_CHAR))\n\ndef feature_selector_code( params, indent=0):\n modules = [\n {'module': 'pandas', 'mod_from': None, 'mod_as': 'pd'}\n ]\n code = \"\"\"\nclass selector():\n # this class \n def __init__(self):\n pass\n \n def run(self, df):\"\"\"\n code +=f\"\"\"\n return df[{params['output_features']}]\n\"\"\"\n return code, modules\n\ndef feature_reducer_code( params, indent=0):\n modules = [\n {'module': 'joblib', 'mod_from': None, 'mod_as': None},\n {'module': 'pandas', 'mod_from': None, 'mod_as': 'pd'},\n {'module': 'Path', 'mod_from': 'pathlib', 'mod_as': None}\n ]\n code = f\"\"\"\nclass selector():\n def __init__(self):\n reducer_file = (Path(__file__).parent/\"model\")/\"{params['reducer_file']}\"\n if not reducer_file.exists():\n raise ValueError(f'Failed to load Feature Engineering model file: {{reducer_file}}') \n self.model = joblib.load(reducer_file)\n\n def run(self, df):\n reducer_input = {params['input_features']}\n reducer_output = {params['output_features']}\n df = self.model.transform(df[reducer_input])\n return pd.DataFrame(df,columns=reducer_output)\n \"\"\"\n if indent:\n code = code.replace('\\\\n', '\\\\n'+(indent * TAB_CHAR))\n return code, modules\n\ndef create_feature_list(config=None, target_feature=None, deploy_path=None):\n featurelist = []\n if 'profiler' in config:\n if 'input_features_type' in config['profiler']:\n input_features = config['profiler']['input_features_type']\n for x in input_features:\n featurelt={}\n featurelt['feature'] = x\n if x == target_feature: \n featurelt['Type'] = 'Target'\n else:\n if input_features[x] in ['int','int64','float','float64']: \n featurelt['Type'] = 'Numeric'\n elif input_features[x] == 'object':\n featurelt['Type'] = 'Text'\n elif input_features[x] == 'category': \n featurelt['Type'] = 'Category' \n else:\n featurelt['Type'] = 'Unknown' \n featurelist.append(featurelt)\n \n featurefile = f\"\"\"\nimport json\ndef getfeatures():\n try:\n features = {featurelist}\n outputjson = {{\"status\":\"SUCCESS\",\"features\":features}}\n output = json.dumps(outputjson)\n print(\"Features:\",output)\n return(output)\n except Exception as e:\n output = {{\"status\":\"FAIL\",\"message\":str(e).strip(\\\\'\"\\\\')}}\n print(\"Features:\",json.dumps(output))\n return (json.dumps(output))\n \nif __name__ == \"__main__\":\n output = getfeatures()\n\"\"\"\n with open( deploy_path/'featureslist.py', 'wb') as f:\n f.write( str(featurefile).encode('utf8'))\n\ndef requirement_file(deploy_path,model,textFeatures,learner_type='ML'):\n modules = ['pandas','numpy','alibi','matplotlib','joblib','shap','ipython','category_encoders','scikit-learn','word2number','flask_restful','evidently','Flask-Cors']\n requires = ''\n for mod in modules:\n requires += f\"{mod}=={version(mod)}\\\\n\"\n if len(textFeatures) > 0:\n tmodules = ['spacy','nltk','textblob','demoji','beautifulsoup4','text-unidecode','pyspellchecker','contractions','protobuf']\n for mod in tmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\" \n if model == 'Extreme Gradient Boosting (XGBoost)':\n mmodules = ['xgboost']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\" \n if model == 'Light Gradient Boosting (LightGBM)':\n mmodules = ['lightgbm']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\" \n if model == 'Categorical Boosting (CatBoost)':\n mmodules = ['catboost']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\" \n if model.lower() == 'arima':\n mmodules = ['pmdarima']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\"\n if model.lower() == 'fbprophet':\n mmodules = ['prophet']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\" \n if model.lower() == 'lstm' or model.lower() == 'mlp' or learner_type =='DL':\n mmodules = ['tensorflow']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\" \n if model.lower() in ['cox', 'kaplanmeierfitter']: #bug 12833\n mmodules = ['lifelines']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\"\n if model.lower() == 'sentencetransformer': #bug 12833\n mmodules = ['sentence_transformers']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\" \n with open( deploy_path/'requirements.txt', 'wb') as f:\n f.write(str(requires).encode('utf8'))\n\ndef create_readme_file(deploy_path,modelfile,features):\n data = json.dumps([{x:x+'_value'} for x in features])\n backslash_data = data.replace('\"', '\\\\\\\\\"')\n content = f\"\"\"\n========== Files Structures ==========\n{modelfile} ------ Trained Model\naion_prediction.py --> Python package entry point\nscript/inputprofiler.py --> Profiling like FillNA and Category to Numeric\n\n========== How to call the model ==========\n============== From Windows Terminal ==========\npython aion_prediction.py \"{backslash_data}\"\n============== From Linux Terminal ==========\npython aion_prediction.py \"{data}\"\n\n============== Output ==========\n{{\"status\":\"SUCCESS\",\"data\":[{{\"Data1\":\"Value\",\"prediction\":\"Value\"}}]}} ## for single Row/Record\n{{\"status\":\"SUCCESS\",\"data\":[{{\"Data1\":\"Value\",\"prediction\":\"Value\"}},{{\"Data1\":\"Value\",\"prediction\":\"Value\"}}]}} ## For Multiple Row/Record\n{{\"status\":\"ERROR\",\"message\":\"description\"}} ## In Case Exception or Error\n \"\"\"\n filename = deploy_path/'readme.txt'\n with open(filename, 'w') as f:\n f.write(content)\n\ndef create_util_folder(deploy_path):\n import tarfile\n ext_path = Path(__file__).parent.parent/'utilities'\n for x in ext_path.iterdir():\n if x.suffix == '.tar':\n if x.name not in ['scikit_surprise-1.1.1.dist-info.tar','surprise.tar']:\n my_tar = tarfile.open(x)\n my_tar.extractall(deploy_path)\n my_tar.close()\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport platform\nimport json\nimport shutil\nimport logging\nimport sys\nfrom AionConfigManager import AionConfigManager\nfrom sklearn.externals import joblib\nclass edgeformats:\n def __init__(self,deploy_path):\n self.deploy_path = deploy_path\n self.edge_deploy_path = os.path.join(deploy_path,\"edge\")\n os.mkdir(self.edge_deploy_path) \n \n \n def converttoedgedeployment(self,saved_model,edge_format,xtrain,model_type,iterName,iterVersion,features,profiled_data_file):\n if edge_format == 'onnx':\n from skl2onnx import convert_sklearn\n from skl2onnx.common.data_types import FloatTensorType\n xtrain = xtrain[features]\n initial_type = [('float_input', FloatTensorType([None, xtrain.shape[1]]))]\n filename = os.path.join(self.deploy_path,saved_model) \t\t\n loaded_model = joblib.load(filename)\n onx = convert_sklearn(loaded_model, initial_types=initial_type)\n onnx_filename = os.path.join(self.edge_deploy_path, model_type + '_' + iterName + '_' + iterVersion + '.onnx')\n with open(onnx_filename, \"wb\") as f:\n f.write(onx.SerializeToString())\n self.createedgeruntimeFile(onnx_filename,profiled_data_file,features)\n \n def createedgeruntimeFile(self,onnx_filename,datafilepath,features):\n runtimefilecontent = ''\n runtimefilecontent += 'import pandas'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += 'import numpy'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += 'import sys'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += 'import onnxruntime as rt'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += 'def onnx_runtime_validation():'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' modelfile = r\"'+str(onnx_filename)+'\"'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' datafile = r\"'+str(datafilepath)+'\"'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' dataframe = pandas.read_csv(datafile)'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' dataframe = dataframe['+str(features)+']'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' df = dataframe.head(8)'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' dataset = df.values'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' sess = rt.InferenceSession(modelfile)'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' input_name = sess.get_inputs()[0].name'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' label_name = sess.get_outputs()[0].name'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' inputsize=sess.get_inputs()[0].shape'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' XYZ = dataset[:,0:inputsize[1]].astype(float)'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' pred_onx = sess.run([label_name], {input_name: XYZ.astype(numpy.float32)[0:8]})[0]'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' df[\\\\'predictions\\\\'] = pred_onx'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' result = df.to_json(orient=\"records\")'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' return(result)'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += 'if __name__ == \"__main__\":'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' output = onnx_runtime_validation()'\n runtimefilecontent += '\\\\n'\n runtimefilecontent += ' print(\"predictions:\",output)'\n filename = os.path.join(self.edge_deploy_path,'onnxvalidation.py')\n f = open(filename, \"w\")\n f.write(str(runtimefilecontent))\n f.close()\n \n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport platform\nimport json\nimport shutil\nimport logging\n\nclass aionPrediction:\n\n def __init__(self):\n self.log = logging.getLogger('eion') \n \n def create_optimus_prediction_file (self,classname,deploy_path,learner_type):\n self.predictionFile = 'import warnings'\n self.predictionFile += '\\\\n' \n self.predictionFile += 'warnings.filterwarnings(\"ignore\")'\n self.predictionFile += '\\\\n'\n self.predictionFile += 'import json'\n self.predictionFile += '\\\\n' \n self.predictionFile += 'import os'\n self.predictionFile += '\\\\n'\n self.predictionFile += 'import sys'\n self.predictionFile += '\\\\n' \n self.predictionFile += 'import pandas as pd'\n self.predictionFile += '\\\\n' \n self.predictionFile += 'from pandas import json_normalize'\n self.predictionFile += '\\\\n'\n self.predictionFile += 'from importlib import import_module'\n self.predictionFile += '\\\\n'\n self.predictionFile += 'import importlib.util'\n self.predictionFile += '\\\\n'\n self.predictionFile += 'class prediction:'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' def predict_from_json(self,json_data):'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' data = json.loads(json_data)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' output=self.predict(data)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' print(\"predictions:\",output)'\n self.predictionFile += '\\\\n'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' def predict_from_file(self,filename):'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' with open(filename,\\\\'r\\\\',encoding=\\\\'utf-8\\\\') as f:'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' data = json.load(f)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' output=self.predict(data)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' print(\"predictions:\",output)'\n self.predictionFile += '\\\\n'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' def predict(self,json_data):'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' try:'\n self.prediction", "instruction": "", "output": "" }, { "input": "File += '\\\\n'\n #self.predictionFile += ' jsonData = json.loads(json_data)'\n self.predictionFile += ' jsonData=json_data'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' model_obj = importlib.util.spec_from_file_location(\"module.name\", os.path.dirname(os.path.abspath(__file__))+\"/trained_model.py\")'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' model = importlib.util.module_from_spec(model_obj)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' model_obj.loader.exec_module(model)'\n self.predictionFile += '\\\\n'\n #if(learner_type != 'TextML'): \n self.predictionFile += ' profiler_obj = importlib.util.spec_from_file_location(\"module.name\", os.path.dirname(os.path.abspath(__file__))+\"/inputprofiler.py\")'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' inputprofiler = importlib.util.module_from_spec(profiler_obj)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' profiler_obj.loader.exec_module(inputprofiler)'\n self.predictionFile += '\\\\n'\n \n self.predictionFile += ' selector_obj = importlib.util.spec_from_file_location(\"module.name\", os.path.dirname(os.path.abspath(__file__))+\"/selector.py\")'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' selector = importlib.util.module_from_spec(selector_obj)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' selector_obj.loader.exec_module(selector)'\n self.predictionFile += '\\\\n'\n\n self.predictionFile += ' output_format_obj = importlib.util.spec_from_file_location(\"module.name\", os.path.dirname(os.path.abspath(__file__))+\"/output_format.py\")'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' output_format = importlib.util.module_from_spec(output_format_obj)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' output_format_obj.loader.exec_module(output_format)'\n self.predictionFile += '\\\\n'\n \n self.predictionFile += ' df = json_normalize(jsonData)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' df0 = df.copy()'\n self.predictionFile += '\\\\n'\n #if(learner_type != 'TextML'):\n self.predictionFile += ' profilerobj = inputprofiler.inputprofiler()'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' df = profilerobj.apply_profiler(df)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' selectobj = selector.selector()'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' df = selectobj.apply_selector(df)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' output = model.trained_model().predict(df,\"\")'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' outputobj = output_format.output_format()'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' output = outputobj.apply_output_format(df0,output)'\n #self.predictionFile += '\\\\n'\n #self.predictionFile += ' print(output)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' return output'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' except KeyError as e:'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' output = {\"status\":\"FAIL\",\"message\":str(e).strip(\\\\'\"\\\\')}'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' return json.dumps(output)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' except Exception as e:'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' output = {\"status\":\"FAIL\",\"message\":str(e).strip(\\\\'\"\\\\')}'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' return json.dumps(output)'\n self.predictionFile += '\\\\n'\n self.predictionFile += '\\\\n'\n self.predictionFile += 'if __name__ == \"__main__\":'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' predictobj = prediction()'\n self.predictionFile += '\\\\n' \n self.predictionFile += ' predictobj.predict_from_file(sys.argv[1])'\n self.predictionFile += '\\\\n' \n \n \n filename = os.path.join(deploy_path,'prediction.py')\n f = open(filename, \"wb\")\n f.write(str(self.predictionFile).encode('utf8'))\n f.close() \n \n def create_text_drift_file(self,deploy_path,features,target,model_type): #task-14549\n self.predictionFile = 'import warnings'\n self.predictionFile += '\\\\n' \n self.predictionFile += 'warnings.filterwarnings(\"ignore\")'\n self.predictionFile += '\\\\n'\n self.predictionFile += 'import json'\n self.predictionFile += '\\\\n' \n self.predictionFile += 'import os'\n self.predictionFile += '\\\\n'\n self.predictionFile += 'import sys'\n self.predictionFile += '\\\\n' \n self.predictionFile += 'import pandas as pd'\n self.predictionFile += '\\\\n'\n self.predictionFile += 'from monitoring import check_drift'\n self.predictionFile += '\\\\n'\n self.predictionFile += 'def drift(data):'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' try:'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' if os.path.splitext(data)[1] == \".json\":'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' with open(data,\\\\'r\\\\',encoding=\\\\'utf-8\\\\') as f:'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' jsonData = json.load(f)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' else:'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' jsonData = json.loads(data)' \n self.predictionFile += '\\\\n' \n self.predictionFile += ' jsonData[\\\\'features\\\\'] = \\\\''+\",\".join([feature for feature in features])+'\\\\''\n self.predictionFile += '\\\\n'\n self.predictionFile += ' jsonData[\\\\'target\\\\'] = \\\\''+target+'\\\\''\n self.predictionFile += '\\\\n'\n if model_type.lower() != 'timeseriesforecasting': #task 11997 \n self.predictionFile += ' htmlfilepath=evidently_details(jsonData)'\n self.predictionFile += '\\\\n' \n else: \n self.predictionFile += ' htmlfilepath=\\\\'\\\\'' \n self.predictionFile += '\\\\n' \n self.predictionFile += ' jsonData = json.dumps(jsonData)'\n self.predictionFile += '\\\\n' \n self.predictionFile += ' output = check_drift(jsonData)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' output = json.loads(output)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' output[\\\\'htmlPath\\\\'] = str(htmlfilepath)' \n self.predictionFile += '\\\\n'\n self.predictionFile += ' print(\"drift:\", json.dumps(output))'\n self.predictionFile += '\\\\n' \n self.predictionFile += ' return(output)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' except KeyError as e:'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' output = {\"status\":\"FAIL\",\"message\":str(e).strip(\\\\'\"\\\\')}'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' print(\"drift:\",json.dumps(output))'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' return (json.dumps(output))'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' except Exception as e:'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' output = {\"status\":\"FAIL\",\"message\":str(e).strip(\\\\'\"\\\\')}'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' print(\"drift:\",json.dumps(output))'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' return (json.dumps(output))'\n self.predictionFile += '\\\\n'\n if model_type.lower() != 'timeseriesforecasting': #task 11997 \n self.predictionFile += 'def evidently_details(deployJson):'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' features = deployJson[\\\\'features\\\\'].split(\\\\',\\\\')'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' target = deployJson[\\\\'target\\\\']'\n self.predictionFile += '\\\\n'\n self.predictionFile += \"\"\"\\\\\n try:\n from evidently.report import Report\n from evidently.metrics import TextDescriptorsDriftMetric, ColumnDriftMetric\n from evidently.pipeline.column_mapping import ColumnMapping\n from sklearn.preprocessing import LabelEncoder\n historicaldataFrame=pd.read_csv(deployJson['trainingDataLocation'],skipinitialspace = True,na_values=['-','?'])\n currentdataFrame=pd.read_csv(deployJson['currentDataLocation'],skipinitialspace = True,na_values=['-','?'])\n historicaldataFrame.columns = historicaldataFrame.columns.str.strip()\n currentdataFrame.columns = currentdataFrame.columns.str.strip() \n hdf = historicaldataFrame.dropna(subset=features)\n cdf = currentdataFrame.dropna(subset=features)\n hdf['Text_Features'] = hdf[features].apply(\"-\".join, axis=1)\n cdf['Text_Features'] = cdf[features].apply(\"-\".join, axis=1)\n hdf['target'] = historicaldataFrame[target]\n cdf['target'] = currentdataFrame[target]\n le = LabelEncoder()\n le.fit(hdf['target']) \n hdf['target'] = le.transform(hdf['target'])\n le.fit(cdf['target']) \n cdf['target'] = le.transform(cdf['target'])\n hd = hdf[['Text_Features', 'target']]\n cd = cdf[['Text_Features', 'target']]\n column_mapping = ColumnMapping()\n column_mapping.target = 'target'\n column_mapping.prediction = 'target'\n column_mapping.text_features = ['Text_Features']\n column_mapping.numerical_features = []\n column_mapping.categorical_features = []\n performance_report = Report(metrics=[ColumnDriftMetric('target'),TextDescriptorsDriftMetric(column_name='Text_Features')])\n performance_report.run(reference_data=hd, current_data=cd,column_mapping=column_mapping)\n report = os.path.join(os.path.dirname(os.path.abspath(__file__)),\"log\",\"My_report.html\")\n performance_report.save_html(report)\n return(report)\n except Exception as e:\n print('Error: ', e)\n return('NA')\"\"\" \n \n self.predictionFile += '\\\\n'\n self.predictionFile += 'if __name__ == \"__main__\":'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' output = drift(sys.argv[1])'\n filename = os.path.join(deploy_path,'aion_ipdrift.py')\n f = open(filename, \"wb\")\n f.write(str(self.predictionFile).encode('utf8'))\n f.close()\n\n def create_drift_file(self,deploy_path,features,target,model_type):\n self.predictionFile = 'import warnings'\n self.predictionFile += '\\\\n' \n self.predictionFile += 'warnings.filterwarnings(\"ignore\")'\n self.predictionFile += '\\\\n'\n self.predictionFile += 'import json'\n self.predictionFile += '\\\\n' \n self.predictionFile += 'import os'\n self.predictionFile += '\\\\n'\n self.predictionFile += 'import sys'\n self.predictionFile += '\\\\n' \n self.predictionFile += 'import pandas as pd'\n self.predictionFile += '\\\\n'\n self.predictionFile += 'from monitoring import check_drift'\n self.predictionFile += '\\\\n'\n self.predictionFile += 'from pandas import json_normalize'\n self.predictionFile += '\\\\n' \n self.predictionFile += 'from script.inputprofiler import inputprofiler'\n self.predictionFile += '\\\\n'\n self.predictionFile += 'def drift(data):'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' try:'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' if os.path.splitext(data)[1] == \".json\":'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' with open(data,\\\\'r\\\\',encoding=\\\\'utf-8\\\\') as f:'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' jsonData = json.load(f)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' else:'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' jsonData = json.loads(data)' \n self.predictionFile += '\\\\n' \n self.predictionFile += ' jsonData[\\\\'features\\\\'] = \\\\''+\",\".join([feature for feature in features])+'\\\\''\n self.predictionFile += '\\\\n'\n self.predictionFile += ' jsonData[\\\\'target\\\\'] = \\\\''+target+'\\\\''\n self.predictionFile += '\\\\n'\n if model_type.lower() != 'timeseriesforecasting': #task 11997 \n self.predictionFile += ' htmlfilepath=evidently_details(jsonData)'\n self.predictionFile += '\\\\n' \n else: \n self.predictionFile += ' htmlfilepath=\\\\'\\\\'' \n self.predictionFile += '\\\\n' \n self.predictionFile += ' jsonData = json.dumps(jsonData)'\n self.predictionFile += '\\\\n' \n self.predictionFile += ' output = check_drift(jsonData)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' output = json.loads(output)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' output[\\\\'htmlPath\\\\'] = str(htmlfilepath)' \n self.predictionFile += '\\\\n'\n self.predictionFile", "instruction": "", "output": "" }, { "input": "+= ' output = json.dumps(output)'\n self.predictionFile += '\\\\n'\n self.predictionFile += ' print(\"drift:\",output)'\n self.predictionFile += '\\\\n' \n self.predictionFile += ' return(output)'\n self", "instruction": "", "output": "" }, { "input": "as e:\n print(e)\n output = {\"status\":\"FAIL\",\"message\":str(e).strip('\"')}\n print(\"drift:\",json.dumps(output))\n return (json.dumps(output))\n except Exception as e:\n print(e)\n output = {\"status\":\"FAIL\",\"message\":str(e).strip('\"')}\n print(\"drift:\",json.dumps(output))\n return (json.dumps(output)) \nif __name__ == \"__main__\":\n output = odrift(sys.argv[1])\"\"\"\n \n filename = os.path.join(deploy_path,'aion_opdrift.py')\n f = open(filename, \"wb\")\n f.write(str(self.predictionFile).encode('utf8'))\n f.close()\n def create_classification_performance_file(self,deploy_path,features,target):\n features = \",\".join([feature for feature in features])\n self.predictionFile = \"\"\"\\\\\nimport pandas as pd\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport json\nimport os\nimport sys\nfrom pandas import json_normalize\nfrom evidently.report import Report\nfrom evidently.metric_preset import ClassificationPreset\nfrom evidently.pipeline.column_mapping import ColumnMapping\nfrom aion_predict import predict\ndef odrift(data):\n try:\n\"\"\"\n self.predictionFile += ' features = \\\\''+features+'\\\\''\n self.predictionFile += '\\\\n'\n self.predictionFile += ' target = \\\\''+target+'\\\\''\n self.predictionFile += '\\\\n'\n self.predictionFile +=\"\"\"\\\\\n if os.path.splitext(data)[1] == \".json\":\n with open(data,'r',encoding='utf-8') as f:\n jsonData = json.load(f)\n else:\n jsonData = json.loads(data) \n production = predict().run(jsonData['currentDataLocation'])\n reference = predict().run(jsonData['trainingDataLocation'])\n production = json.loads(production)\n reference = json.loads(reference)\n if (production['status'] == 'SUCCESS' and reference['status'] == 'SUCCESS'):\n production = production['data']\n production = json_normalize(production)\n reference = reference['data']\n reference = json_normalize(reference)\n production['target'] = production[target]\n reference['target'] = reference[target] \n column_mapping = ColumnMapping()\n column_mapping.target = target\n column_mapping.prediction = 'prediction'\n column_mapping.datetime = None\n column_mapping.numerical_features = features.split(',')\n model_performance_dashboard = Report(metrics = [ClassificationPreset()])\n model_performance_dashboard.run(reference_data =reference, current_data =production, column_mapping = column_mapping)\n report = os.path.join(os.path.dirname(os.path.abspath(__file__)),'log','performance.html')\n model_performance_dashboard.save_html(report)\n metrics_output = model_performance_dashboard.as_dict()\n output = {\"status\":\"SUCCESS\",\"htmlPath\":report, 'drift_details':metrics_output['metrics']} \n print(\"drift:\",json.dumps(output))\n return (json.dumps(output))\n else:\n output = {\"status\":\"SUCCESS\",\"htmlPath\":'NA'} \n print(\"drift:\",json.dumps(output))\n return (json.dumps(output)) \n \n except KeyError as e:\n print(e)\n output = {\"status\":\"FAIL\",\"message\":str(e).strip('\"')}\n print(\"drift:\",json.dumps(output))\n return (json.dumps(output))\n except Exception as e:\n print(e)\n output = {\"status\":\"FAIL\",\"message\":str(e).strip('\"')}\n print(\"drift:\",json.dumps(output))\n return (json.dumps(output))\n\nif __name__ == \"__main__\":\n output = odrift(sys.argv[1])\"\"\"\n \n filename = os.path.join(deploy_path,'aion_opdrift.py')\n f = open(filename, \"wb\")\n f.write(str(self.predictionFile).encode('utf8'))\n f.close()\n def create_model_service(self,deploy_path,serviceName,problemType):\n \n filedata = \"\"\"\nfrom flask import Flask, jsonify, request\nfrom flask_restful import Resource, Api\nfrom aion_predict import predict\"\"\"\n if problemType.lower() == 'classification' or problemType.lower() == 'regression':\n filedata += \"\"\" \nfrom aion_xai import local_analysis\nfrom aion_ipdrift import drift\nfrom aion_opdrift import odrift\"\"\"\n filedata += \"\"\"\nimport json\nimport os\nimport pandas as pd\nimport io\nimport argparse \nfrom pathlib import Path\nfrom flask_cors import CORS, cross_origin\napp = Flask(__name__)\n#cross origin resource from system arguments\nparser = argparse.ArgumentParser()\nparser.add_argument('-ip', '--ipaddress', help='IP Address') \nparser.add_argument('-p', '--port', help='Port Number') \nparser.add_argument(\"-cors\", type=str, required=False) \nd = vars(parser.parse_args())\n\nmodelPath = Path(__file__).parent\ntry:\n with open( (modelPath/'etc')/'display.json', 'r') as f:\n disp_data = json.load(f)\n is_explainable = not disp_data.get('textFeatures')\nexcept:\n disp_data = {}\n is_explainable = True\n\nif \"cors\" in d.keys(): \n if d[\"cors\"] != '' and d[\"cors\"] != None:\n d[\"cors\"] = [s.strip() for s in d[\"cors\"].split(\",\")]\n #cors = CORS(app, resources={r\"/AION/*\": {\"origins\": [\"http://localhost\", \"http://localhost:5000\"]}})\n cors = CORS(app, resources={r\"/AION/*\": {\"origins\": d[\"cors\"]}})\napi = Api(app)\nclass predictapi(Resource):\n def get(self):\n features = disp_data.get('modelFeatures')\n if features:\n msg=\\\\\"\"\"\nRequestType: POST\nContent-Type=application/json\nBody: {displaymsg}\n \\\\\"\"\".format(displaymsg={ x:'Value' for x in features})\n else:\n displaymsg='Data in JSON Format'\n return jsonify(displaymsg)\n\n def post(self): \n data = request.get_json() \n output = predict().run(json.dumps(data))\n return jsonify(json.loads(output))\n\nclass predictfileapi(Resource):\n def post(self): \n if 'file' in request.files:\n file = request.files['file']\n urlData = file.read()\n rawData = pd.read_csv(io.StringIO(urlData.decode('utf-8')))\n data = rawData.to_json(orient='records')\n output = predict().run(data)\n return jsonify(json.loads(output))\n else:\n displaymsg='File is mising'\n return jsonify(displaymsg)\n\n def get(self): \n msg=\\\\\"\"\"\nRequestType: POST\nBody:send file content in body\\\\\"\"\"\n return jsonify(msg) \n \"\"\"\n if problemType.lower() == 'classification' or problemType.lower() == 'regression':\n filedata += \"\"\" \nclass explainapi(Resource):\n def get(self):\n features = disp_data.get('modelFeatures')\n if features:\n msg=\\\\\"\"\"\nRequestType: POST\nContent-Type=application/json\nBody: {displaymsg}\n \\\\\"\"\".format(displaymsg={ x:'Value' for x in features})\n else:\n displaymsg='Data in JSON Format'\n return jsonify(displaymsg)\n\n def post(self):\n data = request.get_json()\n if is_explainable:\n output = local_analysis(json.dumps(data))\n else:\n output = json.dumps({\"status\":\"FAIL\",\"data\":\"explain api is not supported when text features are used for training\"})\n return jsonify(json.loads(output))\n \nclass monitoringapi(Resource):\n def get(self):\n return jsonify({'trainingDataLocation':'Training File Location','currentDataLocation':'production Location'})\n def post(self): \n data = request.get_json() \n output = drift(json.dumps(data))\n return jsonify(json.loads(output))\n\nclass performanceapi(Resource):\n def get(self):\n return jsonify({'trainingDataLocation':'Training File Location','currentDataLocation':'production Location'})\n def post(self): \n data = request.get_json() \n output = odrift(json.dumps(data))\n return jsonify(json.loads(output)) \n \"\"\"\n filedata += \"\"\" \napi.add_resource(predictapi, '/AION/{serviceName}/predict')\"\"\".format(serviceName=serviceName)\n filedata += \"\"\" \napi.add_resource(predictfileapi, '/AION/{serviceName}/predict_file')\"\"\".format(serviceName=serviceName)\n if problemType.lower() == 'classification' or problemType.lower() == 'regression':\n filedata += \"\"\" \napi.add_resource(explainapi, '/AION/{serviceName}/explain')\napi.add_resource(monitoringapi, '/AION/{serviceName}/monitoring')\napi.add_resource(performanceapi, '/AION/{serviceName}/performance')\"\"\".format(serviceName=serviceName)\n filedata += \"\"\"\nif __name__ == '__main__':\n args = parser.parse_args() \n app.run(args.ipaddress,port = args.port,debug = True)\"\"\"\n filename = os.path.join(deploy_path,'aion_service.py')\n f = open(filename, \"wb\")\n f.write(str(filedata).encode('utf8'))\n f.close()\n \n def create_regression_performance_file(self,deploy_path,features,target):\n features = \",\".join([feature for feature in features])\n self.predictionFile = \"\"\"\\\\\nimport pandas as pd\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport json\nimport os\nimport sys\nfrom pandas import json_normalize\nfrom evidently.report import Report\nfrom evidently.metric_preset import RegressionPreset\nfrom evidently.pipeline.column_mapping import ColumnMapping\nfrom aion_predict import predict\ndef odrift(data):\n try:\n\"\"\"\n self.predictionFile += ' features = \\\\''+features+'\\\\''\n self.predictionFile += '\\\\n'\n self.predictionFile += ' target = \\\\''+target+'\\\\''\n self.predictionFile += '\\\\n'\n self.predictionFile +=\"\"\"\\\\\n if os.path.splitext(data)[1] == \".json\":\n with open(data,'r',encoding='utf-8') as f:\n jsonData = json.load(f)\n else:\n jsonData = json.loads(data) \n production = predict().run(jsonData['currentDataLocation'])\n reference = predict().run(jsonData['trainingDataLocation'])\n production = json.loads(production)\n reference = json.loads(reference)\n if (production['status'] == 'SUCCESS' and reference['status'] == 'SUCCESS'):\n production = production['data']\n production = json_normalize(production)\n reference = reference['data']\n reference = json_normalize(reference)\n production['target'] = production[target]\n reference['target'] = reference[target] \n column_mapping = ColumnMapping()\n column_mapping.target = target\n column_mapping.prediction = 'prediction'\n column_mapping.datetime = None\n column_mapping.numerical_features = features.split(',')\n iris_model_performance_dashboard = Report(metrics=[RegressionPreset()])\n iris_model_performance_dashboard.run(reference_data = reference, current_data = production, column_mapping = column_mapping)\n report = os.path.join(os.path.dirname(os.path.abspath(__file__)),'log','performance.html')\n iris_model_performance_dashboard.save_html(report)\n metrics_output = iris_model_performance_dashboard.as_dict()\n output = {\"status\":\"SUCCESS\",\"htmlPath\":report, 'drift_details':metrics_output['metrics']} \n print(\"drift:\",json.dumps(output))\n return (json.dumps(output))\n else:\n output = {\"status\":\"SUCCESS\",\"htmlPath\":'NA'} \n print(\"drift:\",json.dumps(output))\n return (json.dumps(output)) \n \n except KeyError as e:\n print(e)\n output = {\"status\":\"FAIL\",\"message\":str(e).strip('\"')}\n print(\"drift:\",json.dumps(output))\n return (json.dumps(output))\n except Exception as e:\n print(e)\n output = {\"status\":\"FAIL\",\"message\":str(e).strip('\"')}\n print(\"drift:\",json.dumps(output))\n return (json.dumps(output))\n\nif __name__ == \"__main__\":\n output = odrift(sys.argv[1])\"\"\"\n \n filename = os.path.join(deploy_path,'aion_opdrift.py')\n f = open(filename, \"wb\")\n f.write(str(self.predictionFile).encode('utf8'))\n f.close()\n \n def create_regression_text_performance_file(self,deploy_path,features,target):\n features = \",\".join([feature for feature in features])\n self.predictionFile = \"\"\"\\\\\nimport pandas as pd\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport json\nimport os\nimport sys\nfrom pandas import json_normalize\nfrom aion_predict import predict\nfrom evidently.report import Report\nfrom evidently.pipeline.column_mapping import ColumnMapping\nfrom evidently.metric_preset import RegressionPreset\ndef odrift(data):\n try:\n\"\"\"\n self.predictionFile += ' features = \\\\''+features+'\\\\''\n self.predictionFile += '\\\\n'\n self.predictionFile += ' target = \\\\''+target+'\\\\''\n self.predictionFile += '\\\\n'\n self.predictionFile +=\"\"\"\\\\\n if os.path.splitext(data)[1] == \".json\":\n with open(data,'r',encoding='utf-8') as f:\n jsonData = json.load(f)\n else:\n jsonData = json.loads(data) \n production = predict().run(jsonData['currentDataLocation'])\n reference = predict().run(jsonData['trainingDataLocation'])\n production = json.loads(production)\n reference = json.loads(reference)\n if (production['status'] == 'SUCCESS' and reference['status'] == 'SUCCESS'):\n production = production['data']\n production = json_normalize(production)\n reference = reference['data']\n reference = json_normalize(reference)\n production['target'] = production[target]\n reference['target'] = reference[target] \n column_mapping = ColumnMapping()\n column_mapping.target = target\n column_mapping.prediction = 'prediction'\n column_mapping.datetime = None\n column_mapping.numerical_features = features.split(',')\n iris_model_performance_dashboard = Report(metrics=[RegressionPreset()])\n iris_model_performance_dashboard.run(reference_data=reference, current_data=production,column_mapping=column_mapping)\n report = os.path.join(os.path.dirname(os.path.abspath(__file__)),'log','performance.html')\n iris_model_performance_dashboard.save_html(report)\n metrics_output = iris_model_", "instruction": "", "output": "" }, { "input": "performance_dashboard.as_dict()\n output = {\"status\":\"SUCCESS\",\"htmlPath\":report, 'drift_details':metrics_output['metrics']} \n print(\"drift:\",json.dumps(output))\n return (json.dumps(output))\n else:\n output = {\"status\":\"SUCCESS\",\"htmlPath\":'NA'} \n print(\"drift:\",json.dumps(output))\n return (json.dumps(output)) \n \n except KeyError as e:\n print(e)\n output = {\"status\":\"FAIL\",\"message\":str(e).strip('\"')}\n print(\"drift:\",json.dumps(output))\n return (json.dumps(output))\n except Exception as e:\n print(e)\n output = {\"status\":\"FAIL\",\"message\":str(e).strip('\"')}\n print(\"drift:\",json.dumps(output))\n return (json.dumps(output))\n\nif __name__ == \"__main__\":\n output = odrift(sys.argv[1])\"\"\"\n \n filename = os.path.join(deploy_path,'aion_opdrift.py')\n f = open(filename, \"wb\")\n f.write(str(self.predictionFile).encode('utf8'))\n f.close()\n\n def create_publish_service(self,datalocation,usecaseid,version,problemType):\n filename = os.path.join(datalocation,'aion_publish_service.py')\n if not os.path.exists(filename):\n filedata = \"\"\" \nimport sys\nimport json\nimport time\nimport sqlite3\nimport argparse\nimport pandas as pd\nimport io\nfrom pathlib import Path\nfrom datetime import datetime\n\nfilename = Path(__file__).parent/'config.json'\nwith open (filename, \"r\") as f:\n data = json.loads(f.read())\nmodelVersion = str(data['version'])\nmodelPath = Path(__file__).parent/modelVersion\nsys.path.append(str(modelPath))\n\ntry:\n with open( (modelPath/'etc')/'display.json', 'r') as f:\n disp_data = json.load(f)\n is_explainable = not disp_data.get('textFeatures')\nexcept:\n disp_data = {}\n is_explainable = True\n \nfrom flask import Flask, jsonify, request\nfrom flask_restful import Resource, Api\nfrom flask_cors import CORS, cross_origin\nfrom flask import Response\nfrom aion_predict import predict \n\"\"\"\n if problemType.lower() == 'classification' or problemType.lower() == 'regression':\n filedata += \"\"\" \nfrom aion_ipdrift import drift\nfrom aion_opdrift import odrift\nif is_explainable:\n from aion_xai import local_analysis\n\"\"\"\n filedata += \"\"\"\ndataPath = Path(__file__).parent/'data'\ndataPath.mkdir(parents=True, exist_ok=True)\napp = Flask(__name__)\n#cross origin resource from system arguments\nparser = argparse.ArgumentParser()\nparser.add_argument('-ip', '--ipaddress', help='IP Address') \nparser.add_argument('-p', '--port', help='Port Number') \nparser.add_argument(\"-cors\", type=str, required=False) \nd = vars(parser.parse_args())\n\nif \"cors\" in d.keys(): \n if d[\"cors\"] != '' and d[\"cors\"] != None:\n d[\"cors\"] = [s.strip() for s in d[\"cors\"].split(\",\")]\n #cors = CORS(app, resources={r\"/AION/*\": {\"origins\": [\"http://localhost\", \"http://localhost:5000\"]}})\n cors = CORS(app, resources={r\"/AION/*\": {\"origins\": d[\"cors\"]}})\napi = Api(app)\n\nclass sqlite_db():\n def __init__(self, location, database_file=None):\n if not isinstance(location, Path):\n location = Path(location)\n if database_file:\n self.database_name = database_file\n else:\n self.database_name = location.stem + '.db'\n db_file = str(location/self.database_name) \n self.conn = sqlite3.connect(db_file)\n self.cursor = self.conn.cursor()\n self.tables = []\n\n def table_exists(self, name):\n if name in self.tables:\n return True\n elif name:\n query = f\"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}';\"\n listOfTables = self.cursor.execute(query).fetchall()\n if len(listOfTables) > 0 :\n self.tables.append(name)\n return True\n return False\n\n def read(self, table_name,condition=''):\n if condition == '':\n return pd.read_sql_query(f\"SELECT * FROM {table_name}\", self.conn)\n else:\n return pd.read_sql_query(f\"SELECT * FROM {table_name} WHERE {condition}\", self.conn)\n\n def create_table(self,name, columns, dtypes):\n query = f'CREATE TABLE IF NOT EXISTS {name} ('\n \n for column, data_type in zip(columns, dtypes):\n query += f\"'{column}' TEXT,\"\n query = query[:-1]\n query += ');'\n self.conn.execute(query)\n return True\n def update(self,table_name,updates,condition):\n update_query = f'UPDATE {table_name} SET {updates} WHERE {condition}'\n self.cursor.execute(update_query)\n self.conn.commit()\n return True \n def write(self,data, table_name):\n if not self.table_exists(table_name):\n self.create_table(table_name, data.columns, data.dtypes)\n tuple_data = list(data.itertuples(index=False, name=None))\n insert_query = f'INSERT INTO {table_name} VALUES('\n for i in range(len(data.columns)):\n insert_query += '?,'\n insert_query = insert_query[:-1] + ')'\n self.cursor.executemany(insert_query, tuple_data)\n self.conn.commit()\n return True\n \n def delete(self, name):\n pass\n def close(self):\n self.conn.close()\"\"\" \n filedata += \"\"\"\napp = Flask(__name__)\napi = Api(app)\n\nclass predictapi(Resource):\n\n def get(self):\n features = disp_data.get('modelFeatures')\n if features:\n msg=\\\\\"\"\"\nRequestType: POST\nContent-Type=application/json\nBody: {displaymsg}\n \\\\\"\"\".format(displaymsg={ x:'Value' for x in features})\n else:\n displaymsg='Data in JSON Format'\n return jsonify(displaymsg)\n \n def post(self): \n sqlite_dbObj = sqlite_db(dataPath,'data.db')\n if not sqlite_dbObj.table_exists('metrices'):\n data = {'noOfPredictCalls':'0','noOfDriftCalls':'0',\"noOfActualCalls\":'0',\"mid\":'0'}\n data = pd.DataFrame(data, index=[0])\n sqlite_dbObj.create_table('metrices',data.columns, data.dtypes) \n data = request.get_json() \n output = predict().run(json.dumps(data))\n outputobj = json.loads(output)\n if outputobj['status'] == 'SUCCESS':\n try:\n df2 = pd.read_json(json.dumps(outputobj['data']), orient ='records')\n if not sqlite_dbObj.table_exists('prodData'):\n sqlite_dbObj.create_table('prodData',df2.columns, df2.dtypes) \n sqlite_dbObj.write(df2,'prodData') \n except:\n pass\n try:\n data = sqlite_dbObj.read('metrices')\n #print(data)\n if len(data) == 0:\n data = [{'mid':'0','noOfPredictCalls':'1','noOfDriftCalls':'0',\"noOfActualCalls\":'0'}]\n data = pd.read_json(json.dumps(data), orient ='records')\n sqlite_dbObj.write(data,'metrices') \n else:\n noofPredictCalls = int(data['noOfPredictCalls'].iloc[0])+1 \n sqlite_dbObj.update('metrices',\"noOfPredictCalls = '\"+str(noofPredictCalls)+\"'\",\"mid = 0\") \n except Exception as e:\n print(e)\n pass \n return jsonify(json.loads(output))\nclass predictfileapi(Resource):\n def post(self): \n sqlite_dbObj = sqlite_db(dataPath,'data.db')\n if not sqlite_dbObj.table_exists('metrices'):\n data = {'noOfPredictCalls':'0','noOfDriftCalls':'0',\"noOfActualCalls\":'0',\"mid\":'0'}\n data = pd.DataFrame(data, index=[0])\n sqlite_dbObj.create_table('metrices',data.columns, data.dtypes) \n if 'file' in request.files:\n file = request.files['file']\n urlData = file.read()\n rawData = pd.read_csv(io.StringIO(urlData.decode('utf-8'))) \n data = rawData.to_json(orient='records')\n output = predict().run(data)\n outputobj = json.loads(output)\n if outputobj['status'] == 'SUCCESS':\n try:\n df2 = pd.read_json(json.dumps(outputobj['data']), orient ='records')\n if not sqlite_dbObj.table_exists('prodData'):\n sqlite_dbObj.create_table('prodData',df2.columns, df2.dtypes) \n sqlite_dbObj.write(df2,'prodData') \n except:\n pass\n try:\n data = sqlite_dbObj.read('metrices')\n #print(data)\n if len(data) == 0:\n data = [{'mid':'0','noOfPredictCalls':'1','noOfDriftCalls':'0',\"noOfActualCalls\":'0'}]\n data = pd.read_json(json.dumps(data), orient ='records')\n sqlite_dbObj.write(data,'metrices') \n else:\n noofPredictCalls = int(data['noOfPredictCalls'].iloc[0])+1 \n sqlite_dbObj.update('metrices',\"noOfPredictCalls = '\"+str(noofPredictCalls)+\"'\",\"mid = 0\") \n except Exception as e:\n print(e)\n pass \n return jsonify(json.loads(output)) \n else:\n output = {'status':'error','msg':'File is missing'}\n return jsonify(output)\n \"\"\"\n if problemType.lower() == 'classification' or problemType.lower() == 'regression':\n filedata += \"\"\" \nclass explainapi(Resource):\n\n def get(self):\n features = disp_data.get('modelFeatures')\n if features:\n msg=\\\\\"\"\"\nRequestType: POST\nContent-Type=application/json\nBody: {displaymsg}\n \\\\\"\"\".format(displaymsg={ x:'Value' for x in features})\n else:\n displaymsg='Data in JSON Format'\n return jsonify(displaymsg)\n\n def post(self):\n data = request.get_json()\n if is_explainable:\n output = local_analysis(json.dumps(data))\n else:\n output = json.dumps({\"status\":\"FAIL\",\"data\":\"explain api is not supported when text features are used for training\"})\n return jsonify(json.loads(output))\n\nclass monitoringapi(Resource):\n\n def get(self):\n return jsonify({'trainingDataLocation':'Training File Location','currentDataLocation':'production Location'})\n\n def post(self): \n sqlite_dbObj = sqlite_db(dataPath,'data.db') \n if not sqlite_dbObj.table_exists('monitoring'):\n data = {'status':'No Drift','Msg':'No Input Drift Found','RecordTime':'Time','version':'1'}\n data = pd.DataFrame(data, index=[0])\n sqlite_dbObj.create_table('monitoring',data.columns, data.dtypes) \n trainingDataPath = (modelPath/'data')/'preprocesseddata.csv.gz'\n if not sqlite_dbObj.table_exists('prodData'): \n return jsonify({'status':'Error','msg':'Prod data not available'}) \n data = sqlite_dbObj.read('prodData')\n filetimestamp = str(int(time.time()))\n dataFile = dataPath/('AION_' + filetimestamp+'.csv')\n data.to_csv(dataFile, index=False) \n data = request.get_json()\n data={'trainingDataLocation':trainingDataPath,'currentDataLocation':dataFile} \n output = drift(json.dumps(data))\n outputData = json.loads(output)\n status = outputData['status']\n \n if status == 'SUCCESS':\n Msg = str(outputData['data'])\n else:\n Msg = 'Error during drift analysis'\n now = datetime.now() # current date and time \n date_time = now.strftime(\"%m/%d/%Y, %H:%M:%S\")\n data = {'status':status,'Msg':Msg,'RecordTime':date_time,'version':modelVersion} \n data = pd.DataFrame(data, index=[0])\n sqlite_dbObj.write(data,'monitoring') \n return jsonify(json.loads(output))\"\"\"\n filedata += \"\"\" \n\nclass matricesapi(Resource):\n\n def get(self):\n sqlite_dbObj = sqlite_db(dataPath,'data.db') \n if sqlite_dbObj.table_exists('metrices'): \n df1 = sqlite_dbObj.read('metrices')\n else:\n df1 = pd.DataFrame()\n #print(df1) \n if sqlite_dbObj.table_exists('monitoring'): \n df2 = sqlite_dbObj.read('monitoring') \n else:\n df2 = pd.DataFrame() \n \n msg = {'Deployed Version':str(modelVersion)} \n \n if df1.shape[0] > 0: \n msg.update({'noOfPredictCalls':str(df1['noOfPredictCalls'].iloc[0])})\n else:\n msg.update({'noOfPredictCalls':'0'})\n driftDetails = [] \n for idx in reversed(df2.index):\n driftd = {'version':str(df2.version[idx]),'status':str(df2.status[idx]),'recordTime':str(df2.RecordTime[idx]),'msg':str(df2.Msg[idx])} \n driftDetails.append(driftd)\n msg.update({'driftDetails':driftDetails}) \n return jsonify(msg)\n\nclass performanceapi(Resource):\n\n def get(self):\n return jsonify({'trainingDataLocation':'Training File Location','currentDataLocation':'production Location'})\n\n def post(self): \n sqlite_dbObj = sqlite_db(dataPath,'data.db') \n if not sqlite_dbObj.table_exists('monitoring'):\n data = {'status':'No Drift','Msg':'No Input Drift Found','RecordTime':'Time','version':'1'}\n data = pd.DataFrame(data, index=[0])\n sqlite_dbObj.create_table('monitoring',data.columns, data.dtypes) \n trainingDataPath = (modelPath/'data')/'preprocesseddata.csv.gz'\n if not sqlite_dbObj.table_exists('", "instruction": "", "output": "" }, { "input": "prodData'): \n return jsonify({'status':'Error','msg':'Prod data not available'}) \n data = sqlite_dbObj.read('prodData')\n filetimestamp = str(int(time.time()))\n dataFile = dataPath/('AION_' + filetimestamp+'.csv')\n data.to_csv(dataFile, index=False) \n data = request.get_json()\n data={'trainingDataLocation':trainingDataPath,'currentDataLocation':dataFile} \n output = odrift(json.dumps(data))\n return jsonify(json.loads(output))\n \"\"\"\n filedata += \"\"\" \napi.add_resource(predictapi, '/AION/{serviceName}/predict')\napi.add_resource(predictfileapi, '/AION/{serviceName}/predict_file')\napi.add_resource(matricesapi, '/AION/{serviceName}/metrices')\"\"\".format(serviceName=usecaseid)\n if problemType.lower() == 'classification' or problemType.lower() == 'regression':\n filedata += \"\"\"\napi.add_resource(explainapi, '/AION/{serviceName}/explain')\napi.add_resource(monitoringapi, '/AION/{serviceName}/monitoring')\napi.add_resource(performanceapi, '/AION/{serviceName}/performance')\n\"\"\".format(serviceName=usecaseid)\n filedata += \"\"\"\nif __name__ == '__main__': \n args = parser.parse_args() \n app.run(args.ipaddress,port = args.port,debug = True)\"\"\"\n f = open(filename, \"wb\")\n f.write(str(filedata).encode('utf8'))\n f.close() \n data = {'version':version}\n filename = os.path.join(datalocation,'config.json') \n with open(filename, \"w\") as outfile:\n json.dump(data, outfile)\n outfile.close() #task 11190: Item based Recommender system---Usnish\nimport os\ndef generate_recommender_code(deployPath):\n code = \"\"\"\nimport pandas as pd\nimport numpy as np\nimport os\nITEMID = 'itemId'\nDATA_FOLDER = 'data'\nUSER_ITEM_MATRIX = 'user_item_matrix.csv'\nITEM_SIMILARITY_MATRIX = 'item_similarity_matrix.csv'\nRATING = 'rating'\nSIMILARITY_SCORE = 'similarity_score'\n\nclass collaborative_filter(object):\n def __init__(self):\n self.matrix = pd.read_csv(os.path.join(os.path.dirname(__file__), '..', DATA_FOLDER, USER_ITEM_MATRIX),index_col=0)\n self.matrix.index.name = ITEMID\n self.item_similarity_cosine = pd.read_csv(os.path.join(os.path.dirname(__file__), '..', DATA_FOLDER, ITEM_SIMILARITY_MATRIX))\n self.item_similarity_cosine.index.name = ITEMID\n self.item_similarity_cosine.columns.name = ITEMID\n def item_based_rec(self,picked_userid, number_of_recommendations,number_of_similar_items=5):\n import operator\n if not isinstance(picked_userid,str):\n picked_userid = str(picked_userid)\n if picked_userid not in self.matrix.columns:\n raise KeyError(\"UserID Does Not Exist\")\n # Movies that the target user has not watched\n try:\n picked_userid_unwatched = pd.DataFrame(self.matrix[picked_userid].isna()).reset_index()\n picked_userid_unwatched = picked_userid_unwatched[picked_userid_unwatched[picked_userid] == True][ITEMID].values.tolist()\n \n # Movies that the target user has watched\n picked_userid_watched = pd.DataFrame(self.matrix[picked_userid].dropna(axis=0, how='all') \\\\\n .sort_values(ascending=False)) \\\\\n .reset_index() \\\\\n .rename(columns={picked_userid: 'rating'})\n\n # Dictionary to save the unwatched movie and predicted rating pair\n rating_prediction = {}\n # Loop through unwatched movies\n for picked_movie in picked_userid_unwatched:\n if not isinstance(picked_movie,str):\n picked_movie = str(picked_movie)\n # Calculate the similarity score of the picked movie with other movies\n try:\n picked_movie_similarity_score = self.item_similarity_cosine[[picked_movie]].reset_index().rename(\n columns={picked_movie: SIMILARITY_SCORE})\n # Rank the similarities between the picked user watched movie and the picked unwatched movie.\n picked_userid_watched_similarity = pd.merge(left=picked_userid_watched,\n right=picked_movie_similarity_score,\n on=ITEMID,\n how='inner') \\\\\n .sort_values(SIMILARITY_SCORE, ascending=False)[\n :number_of_similar_items]\n # Calculate the predicted rating using weighted average of similarity scores and the ratings from picked user\n try:\n predicted_rating = round(np.average(picked_userid_watched_similarity[RATING],weights=picked_userid_watched_similarity[SIMILARITY_SCORE]), 6)\n except Exception as e:\n predicted_rating = 0\n # Save the predicted rating in the dictionary\n \n rating_prediction[picked_movie] = predicted_rating\n except Exception as e:\n rating_prediction[picked_movie] = 0\n # Return the top recommended movies\n\n return sorted(rating_prediction.items(), key=operator.itemgetter(1), reverse=True)[:number_of_recommendations]\n except Exception as e:\n print(e)\n raise KeyError(str(e))\n def predict(self,X):\n predictions = []\n for index,row in X.iterrows():\n score = self.item_based_rec(int(row[\"uid\"]),int(row[\"numberOfRecommendation\"]))\n df = pd.DataFrame(score,columns=['ItemId','Ratings'])\n predictions.append(df)\n return predictions\"\"\"\n filename = os.path.join(deployPath, 'script', 'item_recommendation.py')\n # print(deploy_path)\n f = open(filename, \"wb\")\n\n f.write(str(code).encode('utf8'))\n f.close()\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport pandas as pd\nimport numpy as np\nimport scipy \nimport warnings\nimport scipy.stats as st\nimport logging\nimport json\nclass inputdrift():\n\tdef __init__(self,conf):\n\t\tself.log = logging.getLogger('eion')\t\t\n\t\t\t\t\t\n\tdef get_input_drift(self,ndf,hdf,outputfolder):\n\t\tselectedColumns = self.features.split(',')\n\t\tdataalertcount=0\n\t\tdistributionChangeColumns=\"\"\n\t\tdistributionChangeMessage=[]\n\t\tfor i in range(0,len(selectedColumns)):\n\t\t\tdata1=hdf[selectedColumns[i]]\n\t\t\tdata2=ndf[selectedColumns[i]]\n\t\t\tif(data1.dtype !=\"str\" and data2.dtype !=\"str\" ):\n\t\t\t\tcumulativeData=data1.append(data2)\n\t\t\t\tteststaticValue=teststatic(self,data1,data2)\n\t\t\t\tif (teststaticValue < 0.05):\n\t\t\t\t\tdistributionName1,sse1=DistributionFinder(self,data1)\n\t\t\t\t\tdistributionName2,sse2=DistributionFinder(self,data2)\n\t\t\t\t\tif(distributionName1 == distributionName2):\n\t\t\t\t\t\tdataalertcount = dataalertcount\n\t\t\t\t\telse:\n\t\t\t\t\t\tdataalertcount = dataalertcount+1\n\t\t\t\t\t\tdistributionChangeColumns=distributionChangeColumns+selectedColumns[i]+\",\"\n\t\t\t\t\t\tchangedColumn = {}\n\t\t\t\t\t\tchangedColumn['Feature'] = selectedColumns[i]\n\t\t\t\t\t\tchangedColumn['KS_Training'] = teststaticValue\n\t\t\t\t\t\tchangedColumn['Training_Distribution'] = distributionName1\n\t\t\t\t\t\tchangedColumn['New_Distribution'] = distributionName2\n\t\t\t\t\t\tdistributionChangeMessage.append(changedColumn)\n \n\t\t\t\telse :\n\t\t\t\t\tdataalertcount = dataalertcount\n\n\t\t\telse :\n\t\t\t\tresponse =\"Selected Columns should be Numerical Values\"\n\t\t \t \n\t\t\tif(dataalertcount == 0):\n\t\t\t\tresultStatus=\"Model is working as expected\"\n\t\t\telse :\n\t\t\t\tresultStatus=json.dumps(distributionChangeMessage)\n\t\t\t\t\n\t\treturn(dataalertcount,resultStatus)\n\t\t\ndef DistributionFinder(self,data):\n\ttry:\n\t\tdistributionName =\"\"\n\t\tsse =0.0\n\t\tKStestStatic=0.0\n\t\tdataType=\"\"\n\t\tif(data.dtype == \"float64\"):\n\t\t\tdataType =\"Continuous\"\n\t\telif(data.dtype ==\"int\"):\n\t\t\tdataType=\"Discrete\"\n\t\telif(data.dtype ==\"int64\"):\n\t\t\tdataType=\"Discrete\"\t\n\t\tif(dataType == \"Discrete\"):\n\t\t\tdistributions= [st.bernoulli,st.binom,st.geom,st.nbinom,st.poisson] \n\t\t\tindex, counts = np.unique(data.astype(int),return_counts=True)\n\n\t\t\tif(len(index)>=2):\n\t\t\t\tbest_sse = np.inf\n\t\t\t\ty1=[]\n\t\t\t\ttotal=sum(counts)\n\t\t\t\tmean=float(sum(index*counts))/total\n\t\t\t\tvariance=float((sum(index**2*counts) -total*mean**2))/(total-1)\n\t\t\t\tdispersion=mean/float(variance)\n\t\t\t\ttheta=1/float(dispersion)\n\t\t\t\tr=mean*(float(theta)/1-theta)\n\n\t\t\t\tfor j in counts:\n\t\t\t\t\t\ty1.append(float(j)/total)\n\t\t\t\t\t\t\t\t\t\n\t\t\t\tpmf1=st.bernoulli.pmf(index,mean) \n\t\t\t\tpmf2=st.binom.pmf(index,len(index),p=mean/len(index))\n\t\t\t\tpmf3=st.geom.pmf(index,1/float(1+mean))\n\t\t\t\tpmf4=st.nbinom.pmf(index,mean,r)\n\t\t\t\tpmf5=st.poisson.pmf(index,mean)\n\n\t\t\t\tsse1 = np.sum(np.power(y1 - pmf1, 2.0))\n\t\t\t\tsse2 = np.sum(np.power(y1 - pmf2, 2.0))\n\t\t\t\tsse3 = np.sum(np.power(y1 - pmf3, 2.0))\n\t\t\t\tsse4 = np.sum(np.power(y1 - pmf4, 2.0))\n\t\t\t\tsse5 = np.sum(np.power(y1- pmf5, 2.0))\n\n\t\t\t\tsselist=[sse1,sse2,sse3,sse4,sse5]\n\n\t\t\t\tfor i in range(0,len(sselist)):\n\t\t\t\t if best_sse > sselist[i] > 0:\n\t\t\t\t\t best_distribution = distributions[i].name\n\t\t\t\t\t best_sse = sselist[i]\n\n\t\t\telif (len(index) == 1): \n\t\t\t\tbest_distribution = \"Constant Data-No Distribution\"\n\t\t\t\tbest_sse = 0.0\n\n\t\t\tdistributionName =best_distribution\n\t\t\tsse=best_sse \n\n\t\telif(dataType == \"Continuous\"): \n\t\t\t\t \n\t\t\tdistributions = [st.uniform,st.expon,st.weibull_max,st.weibull_min,st.chi,st.norm,st.lognorm,st.t,st.gamma,st.beta]\n\n\t\t\tbest_distribution = st.norm.name\n\t\t\tbest_sse = np.inf\n\t\t\tdatamin=data.min()\n\t\t\tdatamax=data.max()\n\t\t\tnrange=datamax-datamin\n\t\t\t\t \n\t\t\ty, x = np.histogram(data.astype(float), bins='auto', density=True)\n\t\t\tx = (x + np.roll(x, -1))[:-1] / 2.0\n\t\t\t\t\t\t\t\t\t\n\t\t\tfor distribution in distributions:\n\t\t\t\t\twith warnings.catch_warnings():\n\t\t\t\t\t\t\twarnings.filterwarnings('ignore')\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tparams = distribution.fit(data.astype(float))\n\t\t\t\t\t\t\t\t\t# Separate parts of parameters\n\t\t\t\t\t\t\targ = params[:-2]\n\t\t\t\t\t\t\tloc = params[-2]\n\t\t\t\t\t\t\tscale = params[-1]\n\n\t\t\t\t\t\t\t\t\t# Calculate fitted PDF and error with fit in distribution\n\t\t\t\t\t\t\tpdf = distribution.pdf(x, loc=loc, scale=scale, *arg)\n\t\t\t\t\t\t\tsse = np.sum(np.power(y - pdf, 2.0))\n\t\t\t\t\t\t\tif(best_sse >sse > 0):\n\t\t\t\t\t\t\t\t\tbest_distribution = distribution.name\n\t\t\t\t\t\t\t\t\tbest_sse = sse\n\n\t\t\tdistributionName =best_distribution\n\t\t\tsse=best_sse \n\texcept:\n\t\tresponse = str(sys.exc_info()[0])\n\t\tmessage='Job has Failed'+response\n\t\tprint(message)\n\treturn distributionName,sse\n\n##KStestStatic -pvalue finding \ndef teststatic(self,data1,data2):\n\ttry:\n\t\tteststatic =st.ks_2samp(data1,data2)\n\t\tpValue=0.0\n\t\tscipyVersion =scipy.__version__\n\t\tif(scipyVersion <= \"0.14.1\"):\n\t\t\tpValue =teststatic[1]\n\t\telse:\n\t\t\tpValue =teststatic.pvalue\n\texcept:\n\t\tresponse = str(sys.exc_info()[0])\n\t\tprint(\"Input Drift Job Failed \"+response)\n\treturn pValue\n\t\t\t\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Prop", "instruction": "", "output": "" }, { "input": "rietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport subprocess \nimport os \nimport glob\nimport sys\nimport python_minifier\ndef encrypt_files(path):\n cwd = os.getcwd()\n secure_path = os.path.join(path,'SecuredScripts')\n try:\n if not os.path.exists(secure_path):\n os.mkdir(secure_path)\n files = [f for f in glob.glob(path + \"/*.py\")]\n for file in files:\n #encrypted_file_details[0] = file\n #file = files[0]\n #print(file)\n #filename_w_dir = os.path.splitext(file)\n filename_w_ext = os.path.basename(file)\n filename, file_extension = os.path.splitext(filename_w_ext)\n file_folder_path = os.path.join(secure_path,filename)\n #print(file_folder_path)\n \n if not os.path.exists(file_folder_path):\n os.mkdir(file_folder_path)\n \n # Minify python source code\n minify_file = os.path.join(file_folder_path,filename+'_minify.py')\n pythonfolder,_ = os.path.split(sys.executable)\n pyminify_script = os.path.join(pythonfolder,'Scripts','pyminify.exe')\n minify_command = \"\\\\\"\"+sys.executable+\"\\\\\" \\\\\"\"+pyminify_script+ \"\\\\\" \\\\\"\" + file + \"\\\\\" > \\\\\"\" + minify_file+\"\\\\\"\"\n subprocess.call(minify_command, shell=True)\n # Change directory to folder path\n os.chdir(file_folder_path)\n \n # Obfuscate minified file\n pyarmor_script = os.path.join(pythonfolder,'Scripts','pyarmor.exe')\n obfusc_commmand = \"\\\\\"\"+sys.executable+\"\\\\\" \\\\\"\"+pyarmor_script+\"\\\\\" obfuscate \\\\\"\" + minify_file+\"\\\\\"\"\n #print(obfusc_commmand)\n subprocess.call(obfusc_commmand, shell=True)\n \n # Change directory to dist path\n obfusc_file = os.path.join(file_folder_path,'dist',filename+'_minify.py')\n #print(obfusc_file)\n chdirpath = os.path.join(file_folder_path,'dist')\n os.chdir(chdirpath)\n \n # Compress obfuscated file\n compressed_file = os.path.join(file_folder_path,'dist',filename+'_compressed.py')\n #print(compressed_file)\n pyminifier_script = os.path.join(pythonfolder,'Scripts','pyminifier.exe')\n compress_command = \"\\\\\"\"+sys.executable+\"\\\\\" \\\\\"\"+pyminifier_script+\"\\\\\" --gzip -o \\\\\"\" +compressed_file + \"\\\\\" \\\\\"\" + obfusc_file+\"\\\\\"\"\n #print(compress_command)\n subprocess.call(compress_command, shell=True)\n \n #compile_command = sys.executable+'-m py_compile \"' + compressed_file+'\"'\n #print(compile_command)\n #subprocess.call(compile_command , shell=True)\n #encrypted_file_details['compiled_file'] = file\n #compiled_file = os.path.join(file_folder_path,'dist','__pycache__',filename+'_compressed.cpython-37.pyc')\n #encrypted_file_details[1] = compiled_file\n #encrypted_file_list.append(encrypted_file_details)\n #encrypted_file = filename + '_compressed.cpython-37_encrypted.pyc'\n #encrypt_command = \"python \" + cwd + \"\\\\\\\\Encrypt_Key_Dcrypt.py \" + compiled_file + ' ' + encrypted_file + \" --g -e\"\n #print(encrypt_command)\n #subprocess.call(encrypt_command, shell=True)\n #encrypted_file_list += ']'\n #return(encrypted_file_list)\n os.chdir(path)\n except OSError as err:\n print (\"Creation of the directory %s failed \"+str(err))\n\n\n# Driver function \nif __name__==\"__main__\":\n path = sys.argv[1]\n encrypt_files(path)\n \n \n#(base) C:\\\\Himanshu\\\\DataPreprocessing>pyminify DataPreprocessing.py > DataPreprocessing_minify.py\n#Obfuscate\n#(base) C:\\\\Himanshu\\\\DataPreprocessing>pyarmor obfuscate C:\\\\Himanshu\\\\DataPreprocessing\\\\DataPreprocessing_minify.py\n#Compression\n#(base) C:\\\\Himanshu\\\\DataPreprocessing>pyminifier --gzip -o C:\\\\Himanshu\\\\DataPreprocessing\\\\dist\\\\DataPreprocessing_compressed.py C:\\\\Himanshu\\\\DataPreprocessing\\\\dist\\\\DataPreprocessing_minify.py\n#(base) C:\\\\Himanshu\\\\DataPreprocessing>cd dist\n#(base) C:\\\\Himanshu\\\\DataPreprocessing\\\\dist>python DataPreprocessing_compressed.py \"DocumentText\" \"Label\" 90 \".csv\" \"C:\\\\Himanshu\\\\DataAcquisition\\\\ClassificationDataNewBalanced.csv\"\n#Compiling compressed .py to .pyc file\n#(base) C:\\\\Himanshu\\\\DataPreprocessing\\\\dist>python -m py_compile DataPreprocessing_compressed.py\n#Encrypt .pyc file\n#(base) C:\\\\Himanshu\\\\DataPreprocessing\\\\dist>python C:\\\\Himanshu\\\\Encrypt_Key_Dcrypt.py C:\\\\Himanshu\\\\DataPreprocessing\\\\dist\\\\__pycache__\\\\DataPreprocessing_compressed.cpython-36.pyc DataPreprocessing_compressed.cpython-36_encrypted.pyc --g -e\n#Decrypt file\n#(base) C:\\\\Himanshu\\\\DataPreprocessing\\\\dist>python C:\\\\Himanshu\\\\Encrypt_Key_Dcrypt.py DataPreprocessing_compressed.cpython-36_encrypted.pyc DataPreprocessing_compressed.cpython-36_decrypted.pyc --d\n#Run decrypted file\n#(base) C:\\\\Himanshu\\\\DataPreprocessing\\\\dist>python DataPreprocessing_compressed.cpython-36_decrypted.pyc \"DocumentText\" \"Label\" 90 \".csv\" \"C:\\\\Himanshu\\\\DataAcquisition\\\\ClassificationDataNewBalanced.csv\" '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport shutil \nimport subprocess\nfrom os.path import expanduser\nimport platform\ndeploymentfolder = os.path.join(os.path.dirname(os.path.abspath(__file__)),'HCLT','AION','target')\nmodelname='AION_12'\nversion='1'\ndef createDockerImage(deploymentfolder,modelname,version,learner_type,textdata):\n modelPath = os.path.join(deploymentfolder)\n filename = os.path.join(deploymentfolder,'docker_image')\n modelservice = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','..','..','..','..','extensions','run_modelService.py')\n shellscript = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','..','..','..','..','extensions','start_modelservice.sh')\n aix = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','..','..','..','..','extensions','AIX-0.1-py3-none-any.whl')\n drift = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','..','..','..','..','extensions','Drift-0.1-py3-none-any.whl')\n sitepackage = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','..','..','..','..','extensions','site-packages')\n model_dockerSetup = os.path.join(os.path.dirname(os.path.abspath(__file__)),'dockersetup','docker_'+modelname + '_' + version)\n docker_setup = os.path.join(model_dockerSetup,modelname + '_' + version)\n model_sitepackage = os.path.join(model_dockerSetup,'site-packages')\n model_dockerSetupservicefile = os.path.join(model_dockerSetup,'run_modelService.py')\n model_dockershellscript = os.path.join(model_dockerSetup,'start_modelservice.sh')\n model_aix = os.path.join(model_dockerSetup,'AIX-0.1-py3-none-any.whl')\n model_drift = os.path.join(model_dockerSetup,'Drift-0.1-py3-none-any.whl')\n \n try:\n os.mkdir(model_dockerSetup) \n except Exception as e:\n print(\"Error in creating Setup directpry \"+str(e))\n pass\n shutil.copytree(modelPath, docker_setup)\n if textdata:\n shutil.copytree(sitepackage, model_sitepackage)\n modelpretrainpath=os.path.join(model_dockerSetup,'HCLT','AION','PreTrainedModels','TextProcessing')\n '''\n try:\n os.makedirs(modelpretrainpath, exist_ok=True)\n except Exception as e:\n print(\"Error in creating Setup directpry \"+str(e))\n pass\n '''\n home = expanduser(\"~\")\n if platform.system() == 'Windows':\n hostpretrainpath = os.path.join(home,'AppData','Local','HCLT','AION','PreTrainedModels','TextProcessing')\n else:\n hostpretrainpath = os.path.join(home,'HCLT','AION','PreTrainedModels','TextProcessing')\n shutil.copytree(hostpretrainpath, modelpretrainpath)\n \n shutil.copyfile(modelservice, model_dockerSetupservicefile)\n shutil.copyfile(shellscript, model_dockershellscript)\n shutil.copyfile(aix, model_aix)\n shutil.copyfile(drift,model_drift)\n try:\n os.mkdir(filename) \n except:\n pass\n requirementfilename = os.path.join(model_dockerSetup,'requirements.txt')\n installfilename = os.path.join(model_dockerSetup,'install.py')\n dockerfile = os.path.join(model_dockerSetup,'Dockerfile')\n dockerdata='FROM python:3.8-slim-buster'\n dockerdata+='\\\\n'\n if textdata:\n dockerdata+='WORKDIR /root'\n dockerdata+='\\\\n'\n dockerdata+='COPY HCLT HCLT'\n dockerdata+='\\\\n'\n dockerdata+='WORKDIR /app'\n dockerdata+='\\\\n'\n dockerdata+='COPY requirements.txt requirements.txt'\n dockerdata+='\\\\n'\n dockerdata+='COPY '+modelname+'_'+version+' '+modelname+'_'+version\n dockerdata+='\\\\n'\n if textdata:\n dockerdata+='COPY site-packages site-packages'\n dockerdata+='\\\\n'\n dockerdata+='COPY install.py install.py'\n dockerdata+='\\\\n'\n dockerdata+='COPY run_modelService.py run_modelService.py'\n dockerdata+='\\\\n'\n dockerdata+='COPY AIX-0.1-py3-none-any.whl AIX-0.1-py3-none-any.whl'\n dockerdata+='\\\\n'\n dockerdata+='COPY Drift-0.1-py3-none-any.whl Drift-0.1-py3-none-any.whl'\n dockerdata+='\\\\n'\n dockerdata+='COPY start_modelservice.sh start_modelservice.sh'\n dockerdata+='\\\\n'\n if textdata:\n dockerdata+='''RUN apt-get update \\\\\n && apt-get install -y build-essential manpages-dev \\\\ \n && python -m pip install --no-cache-dir --upgrade pip \\\\\n && python -m pip install --no-cache-dir pandas==1.2.4 \\\\\n && python -m pip install --no-cache-dir numpy==1.19.5 \\\\\n && python -m pip install --no-cache-dir joblib==1.0.1 \\\\\n && python -m pip install --no-cache-dir Cython==0.29.23 \\\\\n && mv site-packages/* /usr/local/lib/python3.8/site-packages \\\\\n && python -m pip install --no-cache-dir scipy==1.6.3 \\\\\n && python -m pip install --no-cache-dir AIX-0.1-py3-none-any.whl \\\\\n && python -m pip install --no-cache-dir Drift-0.1-py3-none-any.whl \\\\\n && python -m pip install --no-cache-dir scikit-learn==0.24.2 \\\\\n && python -m pip install --no-cache-dir spacy==2.2.3 \\\\\n && python -m pip install --no-cache-dir nltk==3.6.2 \\\\\n && python -m pip install --no-cache-dir textblob==0.15.3 \\\\\n && python -m pip install --no-cache-dir gensim==3.8.3 \\\\\n && python -m pip install --no-cache-dir demoji==1.1.0 \\\\\n && python -m pip install --no-cache-dir lxml==4.6.3 \\\\\n && python -m pip install --no-cache-dir Beautifulsoup4==4.9.3 \\\\\n && python -m pip install --no-cache-dir Unidecode==1.2.0 \\\\\n && python -m pip install --no-cache-dir pyspellchecker==0.6.2 \\\\\n && python -m pip install --no-cache-dir pycontractions==2.0.1 \\\\\n && python -m pip install --no-cache-dir tensorflow==2.4.1 \\\\\n && python -m pip install --no-cache-dir nltk==3.6.2 \\\\\n && python -m pip install --no-cache-dir -r requirements.txt \\\\\n && python install.py \\\\\n && chmod +x start_modelservice.sh\nENTRYPOINT [\"./start_modelservice.sh\"]\n'''\n else:\n dockerdata+='''RUN apt-get update \\\\\n && apt-get install -y build-essential manpages-dev \\\\ \n && python -m pip install --no-cache-dir --upgrade pip \\\\\n && python -m pip install --no-cache-dir pandas==1.2.4 \\\\\n && python -m pip install --no-cache-dir numpy==1.19.5 \\\\\n && python -m pip install --no-cache-dir joblib==1.0.1 \\\\\n && python -m pip install --no-cache-dir Cython==0.29.23 \\\\\n && python -m pip install --no-cache-dir scipy==1.6.3 \\\\\n && python -m pip install --no-cache-dir AIX-0.1-py3-none-any.whl \\\\\n && python -m pip install --no-cache-dir Drift-0.1-py3-none-any.wh", "instruction": "", "output": "" }, { "input": "l \\\\\n && python -m pip install --no-cache-dir scikit-learn==0.24.2 \\\\\n && python -m pip install --no-cache-dir -r requirements.txt \\\\\n && chmod +x start_modelservice.sh\nENTRYPOINT [\"./start_modelservice.sh\"]\n'''\n f = open(dockerfile, \"w\")\n f.write(str(dockerdata))\n f.close() \n requirementdata=''\n requirementdata+='word2number==1.1'\n if learner_type == 'DL':\n requirementdata+='\\\\n'\n requirementdata+='tensorflow==2.5.0'\n f = open(requirementfilename, \"w\")\n f.write(str(requirementdata))\n f.close()\n if textdata:\n installfile='''\nimport nltk\nimport ssl\ntry:\n _create_unverified_https_context = ssl._create_unverified_context\nexcept AttributeError:\n pass\nelse:\n ssl._create_default_https_context = _create_unverified_https_context\nnltk.download('punkt')\nnltk.download('wordnet')\nnltk.download('stopwords')\nnltk.download('averaged_perceptron_tagger')'''\n f = open(installfilename, \"w\")\n f.write(str(installfile))\n f.close()\n try:\n command = 'docker pull python:3.8-slim-buster'\n os.system(command);\n #subprocess.check_call([\"chmod\", \"+x\", \"start_modelservice.sh\"], cwd=model_dockerSetup) \n subprocess.check_call([\"docker\", \"build\", \"-t\",modelname.lower()+\":\"+version,\".\"], cwd=model_dockerSetup) \n subprocess.check_call([\"docker\", \"save\", \"-o\",modelname.lower()+\"_\"+version+\".tar\",modelname.lower()+\":\"+version], cwd=model_dockerSetup) \n dockerfilepath = os.path.join(model_dockerSetup,modelname.lower()+\"_\"+version+\".tar\")\n shutil.copyfile(dockerfilepath, os.path.join(filename,modelname.lower()+\"_\"+version+\".tar\")) \n shutil.rmtree(model_dockerSetup)\n return 'Success','SUCCESSFULLY'\n except Exception as e:\n print(\"Error: \"+str(e))\n shutil.rmtree(model_dockerSetup)\n return 'Error',str(e)\n \n#createDockerImage(deploymentfolder,modelname,version) '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nfrom pathlib import Path\nfrom AION.prediction_package.imports import importModule\nfrom AION.prediction_package.aion_prediction import aionPrediction\nfrom AION.prediction_package.utility import TAB_CHAR\nfrom AION.prediction_package import utility\nfrom AION.prediction_package import common\n\ndef file_header( usecase=''):\n return ''\n\nclass deployer():\n \"\"\"\n base deployer class which can be used to generate the deployemnt code.\n This class will be inherited by deployer specific to problem type.\n \"\"\"\n\n def __init__(self, params={}):\n if not params['paths']['deploy']:\n raise ValueError('Deploy path is not provided')\n self.deploy_path = Path(params['paths']['deploy'])\n if not self.deploy_path.exists():\n self.deploy_path.mkdir(parents=True, exist_ok=True)\n self.name = params.get('problem_type', '')\n self.params = params\n self.importer = importModule()\n self.feature_reducer = False\n \n def profiler_code(self):\n return common.profiler_code(self.params['profiler'])\n \n def feature_engg_code(self):\n if self.params['selector'].get('reducer',False):\n code, modules = common.feature_reducer_code(self.params['selector'])\n else:\n code, modules = common.feature_selector_code(self.params['selector'])\n utility.import_modules(self.importer, modules)\n return code\n \n def training_code(self):\n return common.training_code(self.params['training'])\n \n def formatter_code(self):\n return ''\n\n def run(self):\n \"\"\"\n run function will be called to start the deployment process.\n This function will create following files\n inputprofiler.py for preprocessing the input\n aion_predict.py for prediction\n model service file \n \"\"\"\n code = self.predict_code( )\n with open(self.deploy_path/'aion_predict.py', 'w') as f:\n f.write(code)\n profiler_code = self.profiler_code()\n with open(self.deploy_path/'script'/'inputprofiler.py', 'w') as f:\n f.write(profiler_code)\n self.create_model_service( )\n self.create_publish_service()\n self.create_idrift()\n self.create_odrift()\n common.create_feature_list(self.params, self.params['features']['target_feat'], self.deploy_path)\n common.requirement_file(self.deploy_path,self.params['training']['algo'],self.params['features']['text_feat'])\n common.create_readme_file(self.deploy_path, self.params['training']['model_file'], self.params['features']['input_feat'])\n self.create_utils_folder()\n \n def predict_code(self):\n imported_modules = [\n {'module': 'json', 'mod_from': None, 'mod_as': None},\n {'module': 'joblib', 'mod_from': None, 'mod_as': None},\n {'module': 'numpy', 'mod_from': None, 'mod_as': 'np'},\n {'module': 'pandas', 'mod_from': None, 'mod_as': 'pd'},\n {'module': 'Path', 'mod_from': 'pathlib', 'mod_as': None}\n ]\n\n utility.import_modules(self.importer, imported_modules)\n self.importer.addLocalModule(module='inputprofiler',mod_from='script.inputprofiler')\n code_text = \"\"\n code_text += self.feature_engg_code()\n code_text += self.training_code()\n code_text += self.formatter_code()\n code_text += common.main_code()\n\n code = file_header()\n code += self.importer.getCode()\n return code + code_text\n \n def create_model_service(self):\n service_name = '{}{}{}'.format(self.params['usecase_name'], '_' if self.params['usecase_ver'] != '' else '', self.params['usecase_ver'])\n obj = aionPrediction()\n obj.create_model_service(self.deploy_path, service_name, self.name)\n\n def create_publish_service(self):\n obj = aionPrediction()\n obj.create_publish_service(self.params['paths']['usecase'], self.params['usecase_name'],self.params['usecase_ver'], self.name)\n\n def create_idrift(self):\n pass\n \n def create_odrift(self):\n pass\n\n def create_utils_folder(self):\n common.create_util_folder(self.deploy_path)\n\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nfrom pathlib import Path\nfrom AION.prediction_package.imports import importModule\nfrom AION.prediction_package.aion_prediction import aionPrediction\nfrom AION.prediction_package.utility import TAB_CHAR\nfrom AION.prediction_package import utility\nfrom AION.prediction_package import common\nfrom AION.prediction_package.base import deployer\n\n\ndef is_supported(problem_type, algo=None):\n \"\"\"\n Return True if problem_type supported otherwise False\n \"\"\"\n supported = ['classification','regression','clustering','timeseriesforecasting','Text Similarity']\n return problem_type in supported\n \ndef get_deployer(problem_type, algo=None, params={}):\n \"\"\"\n Return deployer class object based on problem type\n Raise error if no class is associated with problem type \n \"\"\"\n params['problem_type'] = problem_type\n if problem_type == 'classification':\n return classification( params)\n elif problem_type == 'regression':\n return regression( params)\n elif problem_type == 'clustering':\n return clustering( params)\n elif problem_type == 'timeseriesforecasting':\n from AION.prediction_package.time_series import forecasting\n return forecasting.get_deployer( params)\n elif problem_type == 'Text Similarity':\n return textSimilarity( params)\n else:\n raise ValueError('deployment is not supported')\n \nclass classification( deployer):\n \n def __init__(self, params={}):\n super().__init__( params)\n self.feature_reducer = False\n if not self.name:\n self.name = 'classification'\n\n def create_idrift(self):\n obj = aionPrediction()\n if self.params['features']['text_feat']:\n obj.create_text_drift_file(self.deploy_path,self.params['features']['text_feat'],self.params['features']['target_feat'],self.name)\n else:\n obj.create_drift_file(self.deploy_path,self.params['features']['input_feat'],self.params['features']['target_feat'],self.name)\n\n def create_odrift(self):\n obj = aionPrediction()\n if self.params['features']['text_feat']:\n obj.create_classification_text_performance_file(self.deploy_path,self.params['features']['text_feat'],self.params['features']['target_feat']) \n else:\n obj.create_classification_performance_file(self.deploy_path,self.params['features']['input_feat'],self.params['features']['target_feat']) \n\n def training_code( self):\n self.importer.addModule(module='pandas',mod_as='pd')\n code = f\"\"\"\nclass trainer(): \n\"\"\"\n init_code, run_code = self._get_train_code()\n return code + init_code + run_code\n \n def _get_train_code(self): \n init_code = f\"\"\"\n def __init__( self):\n model_file = (Path(__file__).parent/\"model\")/\"{self.params['training']['model_file']}\"\n if not model_file.exists():\n raise ValueError(f'Trained model file not found: {{model_file}}')\"\"\"\n \n run_code = f\"\"\"\n def run(self, df):\\\\\n\"\"\"\n if self.params['training']['algo'] in ['Neural Network']:\n self.importer.addModule(module='load_model',mod_from='tensorflow.keras.models')\n init_code += f\"\"\"\n self.model = load_model(model_file)\n\"\"\"\n run_code += \"\"\"\n df = df.astype(np.float32)\n return pd.DataFrame(np.argmax(self.model.predict(df),axis=1))\n\"\"\" \n elif self.params['training']['algo'] in ['Neural Architecture Search']:\n self.importer.addModule(module='load_model',mod_from='tensorflow.keras.models')\n self.importer.addModule(module='autokeras',mod_as='ak')\n init_code += f\"\"\"\n self.model = load_model(model_file,custom_objects=ak.CUSTOM_OBJECTS)\n\"\"\"\n run_code += \"\"\"\n df = df.astype(np.float32)\n return pd.DataFrame(self.model.predict(df))\n\"\"\" \n elif self.params['training']['algo'] in ['Deep Q Network','Dueling Deep Q Network']:\n self.importer.addModule('joblib')\n self.importer.addModule(module='numpy',mod_as='np')\n self.importer.addModule(module='constant',mod_from='tensorflow')\n self.importer.addModule(module='time_step',mod_from='tf_agents.trajectories')\n init_code += f\"\"\"\n self.model = joblib.load(model_file)\n\"\"\"\n run_code += \"\"\"\n df = df.astype(np.float32)\n q, _ = self.model(np.array(df), step_type=constant([time_step.StepType.FIRST] * np.array(df).shape[0]), training=False)\n return pd.DataFrame(q.numpy())\n\"\"\" \n elif self.params['training']['algo'] in ['Convolutional Neural Network (1D)','Recurrent Neural Network','Recurrent Neural Network (GRU)','Recurrent Neural Network (LSTM)']:\n self.importer.addModule(module='numpy',mod_as='np')\n self.importer.addModule(module='load_model',mod_from='tensorflow.keras.models')\n init_code += f\"\"\"\n self.model = load_model(model_file)\n\"\"\"\n run_code += \"\"\"\n df = np.expand_dims(df, axis=2)\n df = df.astype(np.float32)\n return pd.DataFrame(np.argmax(self.model.predict(df),axis=1))\n\"\"\" \n else:\n self.importer.addModule(module='joblib')\n self.importer.addModule(module='numpy',mod_as='np')\n init_code += f\"\"\"\n self.model = joblib.load(model_file)\n\"\"\"\n run_code += \"\"\"\n df = df.astype(np.float32)\n return pd.DataFrame(self.model.predict_proba(df), columns=self.model.classes_)\n \"\"\"\n return init_code, run_code\n \n def formatter_code(self):\n self.importer.addModule('json')\n self.importer.addModule('joblib')\n self.importer.addModule('pandas', mod_as='pd')\n return \"\"\"\nclass output_format():\n\n def __init__(self):\n pass\n \n def run(self, raw_df, output):\n output = round(output,2)\n encoder_file = (Path(__file__).parent/\"model\")/\"label_encoder.pkl\"\n if encoder_file.exists():\n encoder = joblib.load(encoder_file)\n output.rename(columns=dict(zip(output.columns, encoder.inverse_transform(list(output.columns)))), inplace=True)\n raw_df['prediction'] = output.idxmax(axis=1)\n raw_df['probability'] = output.max(axis=1).round(2)\n raw_df['remarks'] = output.apply(lambda x: x.to_json(double_precision=2), axis=1)\n outputjson = raw_df", "instruction": "", "output": "" }, { "input": ".to_json(orient='records',double_precision=5)\n outputjson = {\"status\":\"SUCCESS\",\"data\":json.loads(outputjson)}\n return(json.dumps(outputjson))\n \"\"\"\n \nclass regression( deployer):\n \n def __init__(self, params={}):\n super().__init__( params)\n self.feature_reducer = False\n if not self.name:\n self.name = 'regression'\n \n def create_idrift(self):\n obj = aionPrediction()\n if self.params['features']['text_feat']:\n obj.create_text_drift_file(self.deploy_path,self.params['features']['text_feat'],self.params['features']['target_feat'],self.name)\n else:\n obj.create_drift_file(self.deploy_path,self.params['features']['input_feat'],self.params['features']['target_feat'],self.name)\n\n def create_odrift(self):\n obj = aionPrediction()\n if self.params['features']['text_feat']:\n obj.create_regression_text_performance_file(self.deploy_path,self.params['features']['text_feat'],self.params['features']['target_feat']) \n else:\n obj.create_regression_performance_file(self.deploy_path,self.params['features']['input_feat'],self.params['features']['target_feat']) \n\n def training_code( self):\n self.importer.addModule(module='pandas',mod_as='pd')\n code = f\"\"\"\nclass trainer(): \n\"\"\"\n init_code = f\"\"\"\n def __init__( self):\n model_file = (Path(__file__).parent/\"model\")/\"{self.params['training']['model_file']}\"\n if not model_file.exists():\n raise ValueError(f'Trained model file not found: {{model_file}}') \n\"\"\"\n run_code = f\"\"\"\n def run(self, df):\\\\\n\"\"\"\n if self.params['training']['algo'] in ['Neural Architecture Search']:\n self.importer.addModule(module='load_model',mod_from='tensorflow.keras.models')\n self.importer.addModule(module='autokeras',mod_as='ak')\n init_code += f\"\"\"\n self.model = load_model(model_file,custom_objects=ak.CUSTOM_OBJECTS)\n\"\"\"\n run_code += \"\"\"\n df = df.astype(np.float32)\n return self.model.predict(df).reshape(1, -1)\n\"\"\" \n elif self.params['training']['algo'] in ['Neural Network','Convolutional Neural Network (1D)','Recurrent Neural Network','Recurrent Neural Network (GRU)','Recurrent Neural Network (LSTM)']:\n self.importer.addModule(module='numpy',mod_as='np')\n self.importer.addModule(module='load_model',mod_from='tensorflow.keras.models')\n init_code += f\"\"\"\n self.model = load_model(model_file)\n\"\"\"\n run_code += \"\"\"\n df = np.expand_dims(df, axis=2)\n df = df.astype(np.float32)\n return self.model.predict(df).reshape(1, -1)\n\"\"\" \n else:\n self.importer.addModule('joblib')\n init_code += f\"\"\"\n self.model = joblib.load(model_file)\n\"\"\"\n run_code += \"\"\"\n df = df.astype(np.float32)\n return self.model.predict(df).reshape(1, -1)\n \"\"\"\n return code + init_code + run_code\n \n def formatter_code(self):\n self.importer.addModule('json')\n self.importer.addModule('pandas', mod_as='pd')\n return \"\"\"\nclass output_format():\n\n def __init__(self):\n pass\n \n def run(self, raw_df, output):\n raw_df['prediction'] = output[0]\n raw_df['prediction'] = raw_df['prediction'].round(2)\n outputjson = raw_df.to_json(orient='records',double_precision=5)\n outputjson = {\"status\":\"SUCCESS\",\"data\":json.loads(outputjson)}\n return(json.dumps(outputjson))\n \"\"\"\n\nclass clustering( deployer):\n \n def __init__(self, params={}):\n super().__init__( params)\n self.feature_reducer = False\n if not self.name:\n self.name = 'clustering'\n \n def training_code( self):\n self.importer.addModule('joblib')\n self.importer.addModule(module='pandas',mod_as='pd')\n code = f\"\"\"\nclass trainer(): \n\"\"\"\n init_code = f\"\"\"\n def __init__( self):\n model_file = (Path(__file__).parent/\"model\")/\"{self.params['training']['model_file']}\"\n if not model_file.exists():\n raise ValueError(f'Trained model file not found: {{model_file}}') \n\"\"\"\n run_code = f\"\"\"\n def run(self, df):\\\\\n\"\"\"\n if self.params['training']['algo'] == 'DBSCAN':\n init_code += f\"\"\"\n self.model = joblib.load(model_file)\n\"\"\"\n run_code += \"\"\"\n return self.model.fit_predict(df)\n\"\"\" \n else:\n init_code += f\"\"\"\n self.model = joblib.load(model_file)\n\"\"\"\n run_code += \"\"\"\n return self.model.predict(df).reshape(1, -1)\n \"\"\"\n return code + init_code + run_code\n \n def formatter_code(self):\n self.importer.addModule('json')\n self.importer.addModule('pandas', mod_as='pd')\n return \"\"\"\nclass output_format():\n\n def __init__(self):\n pass\n \n def run(self, raw_df, output):\n raw_df['prediction'] = output[0]\n raw_df['prediction'] = raw_df['prediction'].round(2)\n outputjson = raw_df.to_json(orient='records',double_precision=2)\n outputjson = {\"status\":\"SUCCESS\",\"data\":json.loads(outputjson)}\n return(json.dumps(outputjson))\n \"\"\"\n return code\n\nif __name__ == '__main__':\n config = {'usecase_name': 'AI0110', 'usecase_ver': '1', 'features': {'input_feat': ['v2'], 'target_feat': 'v1', 'text_feat': ['v2']}, 'paths': {'deploy': r'C:/Users/vashistah/AppData/Local/Programs/HCLTech/AION/data/target/AI0110/1', 'usecase': r'C:/Users/vashistah/AppData/Local/Programs/HCLTech/AION/data/target/AI0110'}, 'profiler': {'input_features': ['v2'], 'output_features': ['07xxxxxxxxx_vect', '08700621170150p_vect', '08702840625comuk_vect', '08718726270150gbpmtmsg18_vect', '1000s_vect', '10am7pm_vect', '10k_vect', '10p_vect', '10pmin_vect', '10ppm_vect', '11mths_vect', '125gift_vect', '12hrs_vect', '12mths_vect', '150p_vect', '150perwksub_vect', '150pm_vect', '150pmin_vect', '150pmsg_vect', '150pmsgrcvdhgsuite3422landsroww1j6hl_vect', '150pmtmsgrcvd18_vect', '150ppm_vect', '150ptone_vect', '150pwk_vect', '150week_vect', '16only_vect', '18only_vect', '1hr_vect', '1minmobsmorelkpobox177hp51fl_vect', '1st_vect', '1x150pwk_vect', '20p_vect', '20pmin_vect', '21st_vect', '220cm2_vect', '24hrs_vect', '25p_vect', '26th_vect', '2day_vect', '2find_vect', '2geva_vect', '2go_vect', '2marrow_vect', '2mrw_vect', '2nd_vect', '2nite_vect', '2optout_vect', '2p_vect', '2u_vect', '2waxsto_vect', '2wks_vect', '300p_vect', '31pmsg_vect', '3510i_vect', '3d_vect', '3g_vect', '3gbp_vect', '3hrs_vect', '3mins_vect', '3qxj9_vect', '3rd_vect', '3ss_vect', '3u_vect', '3uz_vect', '3wk_vect', '40gb_vect', '4a_vect', '4d_vect', '4eva_vect', '4get_vect', '4info_vect', '4mths_vect', '4th_vect', '4u_vect', '50p_vect', '5min_vect', '5pm_vect', '5wb_vect', '5we_vect', '60pmin_vect', '6hrs_vect', '6months_vect', '6pm_vect', '7250i_vect', '7ish_vect', '8am_vect', '8pm_vect', '8th_vect', '8wp_vect', '9ae_vect', '9ja_vect', '9pm_vect', '9t_vect', 'aathi_vect', 'abi_vect', 'ability_vect', 'abiola_vect', 'able_vect', 'abt_vect', 'abta_vect', 'aburo_vect', 'ac_vect', 'academic_vect', 'acc_vect', 'accept_vect', 'access_vect', 'accident_vect', 'accidentally_vect', 'accordingly_vect', 'account_vect', 'ache_vect', 'across_vect', 'acted_vect', 'action_vect', 'activate_vect', 'activities_vect', 'actor_vect', 'actual_vect', 'actually_vect', 'ad_vect', 'adam_vect', 'add_vect', 'added_vect', 'addicted_vect', 'addie_vect', 'address_vect', 'admin_vect', 'administrator_vect', 'admirer_vect', 'admit_vect', 'adore_vect', 'adoring_vect', 'ads_vect', 'adult_vect', 'advance_vect', 'adventure_vect', 'advice_vect', 'advise_vect', 'affair_vect', 'affairs_vect', 'affectionate_vect', 'afraid_vect', 'aft_vect', 'afternoon_vect', 'aftr_vect', 'agalla_vect', 'age_vect', 'age16_vect', 'ages_vect', 'ago_vect', 'agree_vect', 'ah_vect', 'aha_vect', 'ahead_vect', 'ahmad_vect', 'ai_vect', 'aight_vect', 'aint_vect', 'air_vect', 'airport_vect', 'airtel_vect', 'aiya_vect', 'aiyah_vect', 'aiyar_vect', 'aiyo_vect', 'al_vect', 'album_vect', 'alert_vect', 'alex_vect', 'alfie_vect', 'ali_vect', 'allah_vect', 'allow_vect', 'allowed_vect', 'almost_vect', 'alone_vect', 'along_vect', 'already_vect', 'alright_vect', 'alrite_vect', 'also_vect', 'always_vect', 'alwys_vect', 'amazing_vect', 'american_vect', 'among_vect', 'amount_vect', 'amp_vect', 'amt_vect', 'andros_vect', 'angry_vect', 'annie_vect', 'anniversary_vect', 'announcement_vect', 'anot_vect', 'another_vect', 'ans_vect', 'ansr_vect', 'answer_vect', 'answered_vect', 'answering_vect', 'answers_vect', 'anthony_vect', 'anti_vect', 'anybody_vect', 'anymore_vect', 'anyone_vect', 'anything_vect', 'anytime_vect', 'anyway_vect', 'anyways_vect', 'apartment_vect', 'app_vect', 'apparently_vect', 'applebees_vect', 'apply_vect', 'appointment_vect', 'appreciate_vect', 'appreciated_vect', 'approx_vect', 'apps_vect', 'appt_vect', 'april_vect', 'ar_vect', 'arcade_vect', 'ard_vect', 'area_vect', 'argh_vect', 'argument_vect', 'arm_vect', 'armand_vect', 'arms_vect', 'around_vect', 'arrange_vect', 'arrested_vect', 'arrive_vect', 'arsenal_vect', 'art_vect', 'arun_vect', 'asap_vect', 'ashley_vect', 'ask_vect', 'askd_vect', 'asked_vect', 'askin_vect', 'asking_vect', 'asks_vect', 'asleep_vect', 'ass_vect', 'assume_vect', 'ate_vect', 'atlanta_vect', 'atlast_vect', 'atm_vect', 'attached_vect', 'attempt_vect', 'attend_vect', 'auction_vect', 'august_vect', 'aunt_vect', 'aunty_vect', 'auto_vect', 'av_vect', 'available_vect', 'avatar_vect', 'ave_vect', 'avent_vect', 'avoid_vect', 'await_vect', 'awaiting_vect', 'awake_vect', 'award_vect', 'awarded_vect', 'away_vect', 'awesome_vect', 'aww_vect', 'b4_vect', 'ba_vect', 'babe_vect', 'babes_vect', 'babies_vect', 'baby_vect', 'back_vect', 'bad_vect', 'bag_vect', 'bags_vect', 'bahamas_vect', 'bak_vect', 'balance_vect', 'bank_vect', 'banks_vect', 'bar_vect', 'barely_vect', 'basic_vect', 'basically_vect', 'bat_vect', 'bath_vect', 'bathe_vect', 'bathing_vect', 'b", "instruction": "", "output": "" }, { "input": "attery_vect', 'bay_vect', 'bb_vect', 'bc_vect', 'bck_vect', 'bcoz_vect', 'bday_vect', 'be_vect', 'bears_vect', 'beautiful_vect', 'beauty_vect', 'bec_vect', 'become_vect', 'becoz_vect', 'bed_vect', 'bedrm_vect', 'bedroom_vect', 'beer_vect', 'befor_vect', 'beg_vect', 'begin_vect', 'behave_vect', 'behind_vect', 'bein_vect', 'believe_vect', 'bell_vect', 'belly_vect', 'belovd_vect', 'best_vect', 'bet_vect', 'better_vect', 'beyond_vect', 'bf_vect', 'bid_vect', 'bids_vect', 'big_vect', 'bigger_vect', 'biggest_vect', 'bill_vect', 'billed_vect', 'billion_vect', 'bills_vect', 'bin_vect', 'biola_vect', 'birds_vect', 'birla_vect', 'birth_vect', 'birthdate_vect', 'birthday_vect', 'bishan_vect', 'bit_vect', 'bitch_vect', 'bite_vect', 'black_vect', 'blackberry_vect', 'blah_vect', 'blake_vect', 'blank_vect', 'bleh_vect', 'bless_vect', 'blessing_vect', 'bloo_vect', 'blood_vect', 'bloody_vect', 'blue_vect', 'bluetooth_vect', 'bluff_vect', 'boat_vect', 'body_vect', 'bold_vect', 'bone_vect', 'bonus_vect', 'boo_vect', 'book_vect', 'booked_vect', 'booking_vect', 'books_vect', 'boost_vect', 'booty_vect', 'bored_vect', 'boring_vect', 'born_vect', 'boss_vect', 'boston_vect', 'bother_vect', 'bottom_vect', 'bought_vect', 'bout_vect', 'bowl_vect', 'box_vect', 'box326_vect', 'box334sk38ch_vect', 'box97n7qp_vect', 'boy_vect', 'boye_vect', 'boyfriend_vect', 'boys_vect', 'boytoy_vect', 'brah_vect', 'brand_vect', 'bread_vect', 'break_vect', 'breathe_vect', 'bright_vect', 'brilliant_vect', 'bring_vect', 'bringing_vect', 'brings_vect', 'british_vect', 'bro_vect', 'broad_vect', 'broke_vect', 'broken_vect', 'bros_vect', 'brothas_vect', 'brother_vect', 'brought_vect', 'bruv_vect', 'bslvyl_vect', 'bt_vect', 'btnationalrate_vect', 'btw_vect', 'bucks_vect', 'bud_vect', 'budget_vect', 'buff_vect', 'buffet_vect', 'bugis_vect', 'building_vect', 'buns_vect', 'burger_vect', 'burns_vect', 'bus_vect', 'buses_vect', 'business_vect', 'busy_vect', 'butt_vect', 'buy_vect', 'buying_vect', 'buzz_vect', 'bx420_vect', 'bx420ip45we_vect', 'bye_vect', 'ca_vect', 'cabin_vect', 'cafe_vect', 'cake_vect', 'cal_vect', 'calculation_vect', 'calicut_vect', 'california_vect', 'call_vect', 'call2optout674_vect', 'callback_vect', 'callcost_vect', 'called_vect', 'caller_vect', 'callers_vect', 'callertune_vect', 'callin_vect', 'calling_vect', 'calls_vect', 'calls\u00e5_vect', 'cam_vect', 'camcorder_vect', 'came_vect', 'camera_vect', 'cameravideo_vect', 'campus_vect', 'can_vect', 'canada_vect', 'canal_vect', 'canary_vect', 'cancel_vect', 'cancelled_vect', 'cancer_vect', 'cant_vect', 'captain_vect', 'car_vect', 'card_vect', 'cardiff_vect', 'care_vect', 'cared_vect', 'career_vect', 'careful_vect', 'carefully_vect', 'caring_vect', 'carlos_vect', 'caroline_vect', 'cars_vect', 'cartoon_vect', 'case_vect', 'cash_vect', 'cashbalance_vect', 'cashin_vect', 'castor_vect', 'cat_vect', 'catch_vect', 'catching_vect', 'caught_vect', 'cause_vect', 'cbe_vect', 'cc_vect', 'cd_vect', 'cdgt_vect', 'cds_vect', 'celebrate_vect', 'celebration_vect', 'cell_vect', 'center_vect', 'centre_vect', 'certainly_vect', 'cha_vect', 'chain_vect', 'challenge_vect', 'chance_vect', 'change_vect', 'changed_vect', 'changes_vect', 'channel_vect', 'character_vect', 'charge_vect', 'charged_vect', 'charges_vect', 'charity_vect', 'charles_vect', 'chase_vect', 'chasing_vect', 'chat_vect', 'chatting_vect', 'cheap_vect', 'cheaper_vect', 'cheat_vect', 'chechi_vect', 'check_vect', 'checked_vect', 'checking_vect', 'cheers_vect', 'chennai_vect', 'cherish_vect', 'chest_vect', 'chicken_vect', 'chikku_vect', 'child_vect', 'childish_vect', 'children_vect', 'chill_vect', 'chillin_vect', 'china_vect', 'chinese_vect', 'chip_vect', 'chocolate_vect', 'choice_vect', 'choose_vect', 'chosen_vect', 'christ_vect', 'christmas_vect', 'church_vect', 'cine_vect', 'cinema_vect', 'citizen_vect', 'city_vect', 'claim_vect', 'claims_vect', 'claire_vect', 'class_vect', 'classes_vect', 'clean_vect', 'cleaning_vect', 'clear_vect', 'clearly_vect', 'click_vect', 'clock_vect', 'close_vect', 'closed_vect', 'closer_vect', 'closes_vect', 'clothes_vect', 'club_vect', 'cn_vect', 'co_vect', 'coast_vect', 'coat_vect', 'cochin_vect', 'code_vect', 'coffee_vect', 'coin_vect', 'coins_vect', 'cold_vect', 'colleagues_vect', 'collect_vect', 'collected_vect', 'collecting_vect', 'collection_vect', 'college_vect', 'colour_vect', 'come_vect', 'comedy_vect', 'comes_vect', 'comin_vect', 'coming_vect', 'commercial_vect', 'common_vect', 'community_vect', 'comp_vect', 'company_vect', 'competition_vect', 'complete_vect', 'completed_vect', 'completely_vect', 'complimentary_vect', 'computer_vect', 'concentrate_vect', 'concert_vect', 'conditions_vect', 'conducts_vect', 'confidence_vect', 'confirm_vect', 'congrats_vect', 'congratulations_vect', 'connection_vect', 'consider_vect', 'considering_vect', 'constant_vect', 'constantly_vect', 'contact_vect', 'contacted_vect', 'contacts_vect', 'content_vect', 'contents_vect', 'continue_vect', 'contract_vect', 'control_vect', 'convey_vect', 'convinced_vect', 'cool_vect', 'coping_vect', 'copy_vect', 'cornwall_vect', 'correct_vect', 'cos_vect', 'cost_vect', 'costa_vect', 'costs_vect', 'cost\u00e5_vect', 'could_vect', 'count_vect', 'countin_vect', 'country_vect', 'couple_vect', 'course_vect', 'cover_vect', 'coz_vect', 'cr9_vect', 'cramps_vect', 'crave_vect', 'crazy_vect', 'created_vect', 'credit_vect', 'credited_vect', 'credits_vect', 'creepy_vect', 'crisis_vect', 'crore_vect', 'cross_vect', 'croydon_vect', 'cruise_vect', 'cry_vect', 'cs_vect', 'csbcm4235wc1n3xx_vect', 'csstop_vect', 'cud_vect', 'cuddling_vect', 'cum_vect', 'cup_vect', 'curious_vect', 'current_vect', 'currently_vect', 'cust_vect', 'custcare_vect', 'custcare08718720201_vect', 'custom_vect', 'customer_vect', 'customers_vect', 'cut_vect', 'cute_vect', 'cutting_vect', 'cuz_vect', 'cw25wx_vect', 'da_vect', 'dad_vect', 'daddy_vect', 'daily_vect', 'damn_vect', 'dance_vect', 'dancing_vect', 'dare_vect', 'dark_vect', 'darlin_vect', 'darling_vect', 'darren_vect', 'dat_vect', 'date_vect', 'dates_vect', 'dating_vect', 'dave_vect', 'day_vect', 'days_vect', 'de_vect', 'dead_vect', 'deal_vect', 'dealer_vect', 'dealing_vect', 'dear_vect', 'dearly_vect', 'death_vect', 'decide_vect', 'decided_vect', 'decimal_vect', 'decision_vect', 'deep_vect', 'def_vect', 'definite_vect', 'definitely_vect', 'del_vect', 'delete_vect', 'deleted_vect', 'delhi_vect', 'deliver_vect', 'delivered_vect', 'deliveredtomorrow_vect', 'delivery_vect', 'dem_vect', 'demand_vect', 'den_vect', 'denis_vect', 'department_vect', 'depends_vect', 'depressed_vect', 'derek_vect', 'desires_vect', 'desperate_vect', 'details_vect', 'dey_vect', 'dhoni_vect', 'dial_vect', 'dick_vect', 'dictionary_vect', 'didn_vect', 'didnt_vect', 'didt_vect', 'die_vect', 'died_vect', 'diet_vect', 'different_vect', 'difficult_vect', 'digital_vect', 'dignity_vect', 'din_vect', 'dinner_vect', 'dint_vect', 'direct_vect', 'directly_vect', 'dirty_vect', 'dis_vect', 'discount_vect', 'discuss_vect', 'dislikes_vect', 'display_vect', 'distance_vect', 'distract_vect', 'disturb_vect', 'division_vect', 'dload_vect', 'dnt_vect', 'doc_vect', 'docs_vect', 'doctor_vect', 'doesnt_vect', 'dog_vect', 'dogging_vect', 'doggy_vect', 'doin_vect', 'dollars_vect', 'don_vect', 'done_vect', 'dont_vect', 'don\u00e5\u00f5t_vect', 'door_vect', 'dorm_vect', 'double_vect', 'dough_vect', 'download_vect', 'downloads_vect', 'draw_vect', 'dream_vect', 'dreams_vect', 'dress_vect', 'dressed_vect', 'dresser_vect', 'drink_vect', 'drinking_vect', 'drinks_vect', 'drive_vect', 'driver_vect', 'drivin_vect', 'driving_vect', 'drop_vect', 'dropped_vect', 'drug_vect', 'drugs_vect', 'drunk_vect', 'dry_vect', 'ds_vect', 'dubsack_vect', 'dude_vect', 'due_vect', 'dun_vect', 'dunno_vect', 'durban_vect', 'dvd_vect', 'earlier_vect', 'early_vect', 'earth_vect', 'easier_vect', 'easily_vect', 'east_vect', 'easter_vect', 'easy_vect', 'eat_vect', 'eaten_vect', 'eatin_vect', 'eating_vect', 'ebay_vect', 'ec2a_vect', 'ee_vect', 'eek_vect', 'eerie_vect', 'effects_vect', 'eg_vect', 'egg_vect', 'eggs_vect', 'eh_vect', 'eight_vect', 'either_vect', 'ela_vect', 'electricity_vect', 'else_vect', 'elsewhere_vect', 'em_vect', 'email_vect', 'embarassed_vect', 'empty_vect', 'end_vect', 'ended_vect', 'ending_vect', 'ends_vect', 'enemy_vect', 'energy_vect', 'eng_vect', 'engin_vect', 'england_vect', 'english_vect', 'enjoy_vect', 'enjoyed_vect', 'enough_vect', 'enter_vect', 'entered_vect', 'entitled_vect', 'entry_vect', 'enuff_vect', 'envelope_vect', 'er_vect', 'erm_vect', 'escape_vect', 'especially_vect', 'esplanade_vect', 'eta_vect', 'etc_vect', 'euro_vect', 'euro2004_vect', 'europe_vect', 'eve_vect', 'eveb_vect', 'even_vect', 'evening_vect', 'event_vect', 'ever_vect', 'every_vect', 'everybody_vect', 'everyday_vect',", "instruction": "", "output": "" }, { "input": "'everyone_vect', 'everything_vect', 'everywhere_vect', 'evn_vect', 'evng_vect', 'ex_vect', 'exact_vect', 'exactly_vect', 'exam_vect', 'exams_vect', 'excellent_vect', 'except_vect', 'exciting_vect', 'excuse_vect', 'excuses_vect', 'executive_vect', 'exeter_vect', 'exhausted_vect', 'expect_vect', 'expecting_vect', 'expensive_vect', 'experience_vect', 'expired_vect', 'expires_vect', 'explain_vect', 'explicit_vect', 'explosive_vect', 'express_vect', 'extra_vect', 'eye_vect', 'eyes_vect', 'fa_vect', 'fab_vect', 'face_vect', 'facebook_vect', 'fact_vect', 'faggy_vect', 'failed_vect', 'fair_vect', 'faith_vect', 'fall_vect', 'falls_vect', 'family_vect', 'fan_vect', 'fancies_vect', 'fancy_vect', 'fantasies_vect', 'fantastic_vect', 'fantasy_vect', 'far_vect', 'farm_vect', 'fast_vect', 'faster_vect', 'fat_vect', 'father_vect', 'fathima_vect', 'fault_vect', 'fave_vect', 'favorite_vect', 'favour_vect', 'favourite_vect', 'fb_vect', 'feb_vect', 'february_vect', 'feel_vect', 'feelin_vect', 'feeling_vect', 'feels_vect', 'fees_vect', 'feet_vect', 'fell_vect', 'felt_vect', 'fetch_vect', 'fever_vect', 'field_vect', 'fifteen_vect', 'fight_vect', 'fighting_vect', 'figure_vect', 'file_vect', 'files_vect', 'fill_vect', 'filling_vect', 'fills_vect', 'film_vect', 'final_vect', 'finally_vect', 'find_vect', 'fine_vect', 'fingers_vect', 'finish_vect', 'finished_vect', 'first_vect', 'fit_vect', 'fix_vect', 'fixed_vect', 'flag_vect', 'flaked_vect', 'flash_vect', 'flat_vect', 'flight_vect', 'flights_vect', 'flirt_vect', 'floor_vect', 'flower_vect', 'fml_vect', 'fo_vect', 'follow_vect', 'followed_vect', 'following_vect', 'fone_vect', 'food_vect', 'fool_vect', 'football_vect', 'force_vect', 'foreign_vect', 'forever_vect', 'forevr_vect', 'forget_vect', 'forgets_vect', 'forgiven_vect', 'forgot_vect', 'format_vect', 'forums_vect', 'forward_vect', 'forwarded_vect', 'found_vect', 'four_vect', 'fr_vect', 'fran_vect', 'freak_vect', 'free_vect', 'freefone_vect', 'freemsg_vect', 'freephone_vect', 'freezing_vect', 'fren_vect', 'frens_vect', 'fret_vect', 'fri_vect', 'friday_vect', 'friend_vect', 'friends_vect', 'friendship_vect', 'fringe_vect', 'frm_vect', 'frnd_vect', 'frnds_vect', 'frndship_vect', 'fuck_vect', 'fuckin_vect', 'fucking_vect', 'ful_vect', 'full_vect', 'fullonsmscom_vect', 'fun_vect', 'funny_vect', 'future_vect', 'fyi_vect', 'gal_vect', 'gals_vect', 'game_vect', 'games_vect', 'gang_vect', 'gap_vect', 'gaps_vect', 'garage_vect', 'garbage_vect', 'gary_vect', 'gas_vect', 'gautham_vect', 'gave_vect', 'gay_vect', 'gd_vect', 'ge_vect', 'gee_vect', 'geeee_vect', 'geeeee_vect', 'gender_vect', 'generally_vect', 'genius_vect', 'gentle_vect', 'gentleman_vect', 'gently_vect', 'germany_vect', 'get_vect', 'gets_vect', 'gettin_vect', 'getting_vect', 'gf_vect', 'gibbs_vect', 'gift_vect', 'gim_vect', 'girl_vect', 'girls_vect', 'gist_vect', 'giv_vect', 'give_vect', 'given_vect', 'gives_vect', 'giving_vect', 'glad_vect', 'gn_vect', 'go_vect', 'goal_vect', 'god_vect', 'goes_vect', 'goin_vect', 'going_vect', 'gold_vect', 'gon_vect', 'gona_vect', 'gone_vect', 'good_vect', 'goodmorning_vect', 'goodnight_vect', 'goodnite_vect', 'google_vect', 'gorgeous_vect', 'gossip_vect', 'got_vect', 'goto_vect', 'gotten_vect', 'govtinstituitions_vect', 'gr8_vect', 'grace_vect', 'gram_vect', 'grand_vect', 'granite_vect', 'gravity_vect', 'great_vect', 'green_vect', 'greet_vect', 'greetings_vect', 'grins_vect', 'grl_vect', 'ground_vect', 'group_vect', 'gt_vect', 'guaranteed_vect', 'gud_vect', 'gudnite_vect', 'guess_vect', 'guessing_vect', 'guide_vect', 'guilty_vect', 'guy_vect', 'guys_vect', 'gym_vect', 'ha_vect', 'haf_vect', 'haha_vect', 'hai_vect', 'hair_vect', 'haiz_vect', 'half_vect', 'halloween_vect', 'ham_vect', 'hand_vect', 'handed_vect', 'handle_vect', 'hands_vect', 'handset_vect', 'hanging_vect', 'happen_vect', 'happened_vect', 'happening_vect', 'happens_vect', 'happiness_vect', 'happy_vect', 'hard_vect', 'hardcore_vect', 'hardly_vect', 'harry_vect', 'hate_vect', 'hav_vect', 'havent_vect', 'haven\u00e5\u00f5t_vect', 'havin_vect', 'head_vect', 'headache_vect', 'headin_vect', 'heads_vect', 'hear_vect', 'heard_vect', 'heart_vect', 'heavy_vect', 'hee_vect', 'height_vect', 'held_vect', 'helen_vect', 'hell_vect', 'hella_vect', 'hello_vect', 'help_vect', 'help08712400602450p_vect', 'helpline_vect', 'hence_vect', 'henry_vect', 'heri_vect', 'herlove_vect', 'hes_vect', 'hex_vect', 'hey_vect', 'hgsuite3422lands_vect', 'hi_vect', 'hide_vect', 'high_vect', 'hill_vect', 'hint_vect', 'hip_vect', 'history_vect', 'hit_vect', 'hiya_vect', 'hl_vect', 'hlp_vect', 'hmm_vect', 'hmmm_vect', 'hmv_vect', 'ho_vect', 'hockey_vect', 'hol_vect', 'hold_vect', 'holder_vect', 'holding_vect', 'holiday_vect', 'holla_vect', 'hols_vect', 'holy_vect', 'home_vect', 'honey_vect', 'hook_vect', 'hop_vect', 'hope_vect', 'hoped_vect', 'hopefully_vect', 'hoping_vect', 'horny_vect', 'horo_vect', 'horrible_vect', 'hospital_vect', 'hospitals_vect', 'hostel_vect', 'hot_vect', 'hotel_vect', 'hotels_vect', 'hour_vect', 'hours_vect', 'house_vect', 'housemaid_vect', 'however_vect', 'hows_vect', 'howz_vect', 'hr_vect', 'hrishi_vect', 'hrs_vect', 'http_vect', 'hubby_vect', 'hug_vect', 'huh_vect', 'hun_vect', 'hungry_vect', 'hunny_vect', 'hurry_vect', 'hurt_vect', 'hurting_vect', 'hurts_vect', 'husband_vect', 'hv_vect', 'hw_vect', 'hyde_vect', 'iam_vect', 'ibhltd_vect', 'ibiza_vect', 'ic_vect', 'ice_vect', 'id_vect', 'idea_vect', 'ideal_vect', 'ideas_vect', 'identifier_vect', 'idiot_vect', 'idk_vect', 'ignore_vect', 'ikea_vect', 'il_vect', 'ill_vect', 'im_vect', 'imagine_vect', 'imma_vect', 'immediately_vect', 'imp_vect', 'important_vect', 'impossible_vect', 'improved_vect', 'in2_vect', 'inc_vect', 'inches_vect', 'incident_vect', 'include_vect', 'including_vect', 'inclusive_vect', 'inconsiderate_vect', 'indeed_vect', 'india_vect', 'indian_vect', 'indians_vect', 'indicate_vect', 'infections_vect', 'infernal_vect', 'info_vect', 'inform_vect', 'information_vect', 'informed_vect', 'innings_vect', 'insha_vect', 'inside_vect', 'instantly_vect', 'instead_vect', 'instructions_vect', 'insurance_vect', 'intelligent_vect', 'interest_vect', 'interested_vect', 'interesting_vect', 'interflora_vect', 'internet_vect', 'intro_vect', 'invest_vect', 'invite_vect', 'invited_vect', 'inviting_vect', 'iouri_vect', 'ip4_vect', 'ipod_vect', 'irritating_vect', 'iscoming_vect', 'ish_vect', 'island_vect', 'islands_vect', 'isnt_vect', 'issue_vect', 'issues_vect', 'it_vect', 'italian_vect', 'its_vect', 'itz_vect', 'it\u00e5\u00f5s_vect', 'ive_vect', 'iz_vect', 'izzit_vect', 'i\u00e5\u00f5m_vect', 'jacket_vect', 'jamster_vect', 'jan_vect', 'january_vect', 'jason_vect', 'java_vect', 'jay_vect', 'jazz_vect', 'jealous_vect', 'jeans_vect', 'jen_vect', 'jenny_vect', 'jess_vect', 'jesus_vect', 'jiayin_vect', 'jiu_vect', 'jo_vect', 'joanna_vect', 'job_vect', 'jogging_vect', 'john_vect', 'join_vect', 'joined_vect', 'joining_vect', 'joke_vect', 'jokes_vect', 'jokin_vect', 'joking_vect', 'jolly_vect', 'joy_vect', 'jsco_vect', 'jst_vect', 'juan_vect', 'juicy_vect', 'july_vect', 'june_vect', 'jus_vect', 'juz_vect', 'k52_vect', 'kadeem_vect', 'kaiez_vect', 'kallis_vect', 'kano_vect', 'kappa_vect', 'karaoke_vect', 'kate_vect', 'kay_vect', 'kb_vect', 'ke_vect', 'keep_vect', 'keeping_vect', 'keeps_vect', 'kent_vect', 'kept_vect', 'kerala_vect', 'key_vect', 'keys_vect', 'ki_vect', 'kick_vect', 'kid_vect', 'kidding_vect', 'kids_vect', 'kidz_vect', 'kind_vect', 'kinda_vect', 'kindly_vect', 'king_vect', 'kiss_vect', 'kisses_vect', 'kk_vect', 'knackered_vect', 'knew_vect', 'knock_vect', 'know_vect', 'knowing_vect', 'knows_vect', 'knw_vect', 'kz_vect', 'l8r_vect', 'la_vect', 'lab_vect', 'ladies_vect', 'lady_vect', 'lag_vect', 'laid_vect', 'land_vect', 'landline_vect', 'langport_vect', 'language_vect', 'laptop_vect', 'lar_vect', 'largest_vect', 'last_vect', 'late_vect', 'later_vect', 'latest_vect', 'latr_vect', 'laugh_vect', 'laughing_vect', 'law_vect', 'lazy_vect', 'ldn_vect', 'ldnw15h_vect', 'le_vect', 'lead_vect', 'learn_vect', 'least_vect', 'leave_vect', 'leaves_vect', 'leaving_vect', 'lect_vect', 'lecture_vect', 'left_vect', 'legal_vect', 'legs_vect', 'leh_vect', 'lei_vect', 'lem_vect', 'less_vect', 'lesson_vect', 'lessons_vect', 'let_vect', 'lets_vect', 'letter_vect', 'letters_vect', 'liao_vect', 'library_vect', 'lick_vect', 'licks_vect', 'lido_vect', 'lie_vect', 'lies_vect', 'life_vect', 'lifetime_vect', 'lift_vect', 'light_vect', 'lik_vect', 'like_vect', 'liked_vect', 'likely_vect', 'likes_vect', 'lil_vect',", "instruction": "", "output": "" }, { "input": "'line_vect', 'linerental_vect', 'lines_vect', 'link_vect', 'lion_vect', 'lionm_vect', 'lionp_vect', 'lions_vect', 'lip_vect', 'list_vect', 'listen_vect', 'listening_vect', 'literally_vect', 'little_vect', 'live_vect', 'liverpool_vect', 'living_vect', 'lk_vect', 'll_vect', 'lmao_vect', 'lo_vect', 'loads_vect', 'loan_vect', 'loans_vect', 'local_vect', 'locations_vect', 'lock_vect', 'log_vect', 'login_vect', 'logo_vect', 'logopic_vect', 'lol_vect', 'london_vect', 'lonely_vect', 'long_vect', 'longer_vect', 'look_vect', 'lookatme_vect', 'looked_vect', 'lookin_vect', 'looking_vect', 'looks_vect', 'lor_vect', 'lose_vect', 'losing_vect', 'loss_vect', 'lost_vect', 'lot_vect', 'lotr_vect', 'lots_vect', 'lou_vect', 'loud_vect', 'lounge_vect', 'lousy_vect', 'lovable_vect', 'love_vect', 'loved_vect', 'lovely_vect', 'loveme_vect', 'lover_vect', 'loverboy_vect', 'lovers_vect', 'loves_vect', 'loving_vect', 'low_vect', 'lower_vect', 'loyal_vect', 'loyalty_vect', 'ls15hb_vect', 'lt_vect', 'ltd_vect', 'luck_vect', 'lucky_vect', 'lucy_vect', 'lunch_vect', 'luv_vect', 'lux_vect', 'luxury_vect', 'lyf_vect', 'lyfu_vect', 'lyk_vect', 'm227xy_vect', 'm26_vect', 'm263uz_vect', 'm8s_vect', 'mac_vect', 'machan_vect', 'macho_vect', 'mad_vect', 'madam_vect', 'made_vect', 'mag_vect', 'maga_vect', 'magical_vect', 'mah_vect', 'mail_vect', 'mailbox_vect', 'main_vect', 'maintain_vect', 'major_vect', 'make_vect', 'makes_vect', 'makin_vect', 'making_vect', 'malaria_vect', 'male_vect', 'mall_vect', 'man_vect', 'managed_vect', 'management_vect', 'many_vect', 'map_vect', 'march_vect', 'mark_vect', 'market_vect', 'marriage_vect', 'married_vect', 'marry_vect', 'masters_vect', 'match_vect', 'matches_vect', 'mate_vect', 'mates_vect', 'matrix3_vect', 'matter_vect', 'max10mins_vect', 'maximize_vect', 'max\u00e5_vect', 'may_vect', 'mayb_vect', 'maybe_vect', 'mca_vect', 'mcat_vect', 'meal_vect', 'mean_vect', 'meaning_vect', 'means_vect', 'meant_vect', 'meanwhile_vect', 'med_vect', 'medical_vect', 'medicine_vect', 'meds_vect', 'meet_vect', 'meetin_vect', 'meeting_vect', 'meh_vect', 'mei_vect', 'member_vect', 'members_vect', 'men_vect', 'menu_vect', 'merry_vect', 'mess_vect', 'message_vect', 'messaged_vect', 'messages_vect', 'messaging_vect', 'met_vect', 'mid_vect', 'middle_vect', 'midnight_vect', 'mids_vect', 'might_vect', 'miles_vect', 'milk_vect', 'min_vect', 'mind_vect', 'mine_vect', 'mini_vect', 'minimum_vect', 'minor_vect', 'mins_vect', 'minute_vect', 'minutes_vect', 'minuts_vect', 'miracle_vect', 'mis_vect', 'miserable_vect', 'miss_vect', 'missed_vect', 'missin_vect', 'missing_vect', 'mistake_vect', 'mistakes_vect', 'mite_vect', 'mm_vect', 'mmm_vect', 'mmmm_vect', 'mmmmmm_vect', 'mnths_vect', 'mo_vect', 'moan_vect', 'mob_vect', 'mobile_vect', 'mobiles_vect', 'mobilesdirect_vect', 'mobilesvary_vect', 'mobileupd8_vect', 'mobno_vect', 'moby_vect', 'mode_vect', 'model_vect', 'module_vect', 'modules_vect', 'moji_vect', 'mojibiola_vect', 'mokka_vect', 'mom_vect', 'moment_vect', 'moments_vect', 'moms_vect', 'mon_vect', 'monday_vect', 'money_vect', 'monkeys_vect', 'mono_vect', 'month_vect', 'monthly_vect', 'months_vect', 'mood_vect', 'moon_vect', 'moral_vect', 'morn_vect', 'morning_vect', 'mostly_vect', 'mother_vect', 'motorola_vect', 'mouth_vect', 'move_vect', 'moved_vect', 'movie_vect', 'movies_vect', 'moving_vect', 'mp3_vect', 'mr_vect', 'mrng_vect', 'mrt_vect', 'msg_vect', 'msgs_vect', 'mths_vect', 'mu_vect', 'much_vect', 'mum_vect', 'mummy_vect', 'murder_vect', 'murdered_vect', 'murderer_vect', 'music_vect', 'must_vect', 'muz_vect', 'na_vect', 'nag_vect', 'nah_vect', 'naked_vect', 'name_vect', 'name1_vect', 'name2_vect', 'named_vect', 'names_vect', 'nan_vect', 'nap_vect', 'nasdaq_vect', 'nat_vect', 'national_vect', 'natural_vect', 'nature_vect', 'naughty_vect', 'nb_vect', 'nd_vect', 'ne_vect', 'near_vect', 'nearly_vect', 'necessarily_vect', 'necklace_vect', 'ned_vect', 'need_vect', 'needed_vect', 'needs_vect', 'neither_vect', 'net_vect', 'netcollex_vect', 'network_vect', 'networks_vect', 'neva_vect', 'never_vect', 'new_vect', 'newest_vect', 'news_vect', 'next_vect', 'ni8_vect', 'nice_vect', 'nigeria_vect', 'night_vect', 'nights_vect', 'nimya_vect', 'nite_vect', 'no1_vect', 'nobody_vect', 'noe_vect', 'nokia_vect', 'nokias_vect', 'noline_vect', 'none_vect', 'noon_vect', 'nope_vect', 'norm_vect', 'norm150ptone_vect', 'normal_vect', 'normally_vect', 'northampton_vect', 'note_vect', 'nothin_vect', 'nothing_vect', 'notice_vect', 'noun_vect', 'nowadays_vect', 'nt_vect', 'ntt_vect', 'ntwk_vect', 'num_vect', 'number_vect', 'numbers_vect', 'nuther_vect', 'nvm_vect', 'nw_vect', 'nxt_vect', 'nyc_vect', 'nydc_vect', 'nyt_vect', 'o2_vect', 'obviously_vect', 'odi_vect', 'offer_vect', 'offers_vect', 'office_vect', 'official_vect', 'officially_vect', 'ofice_vect', 'often_vect', 'oh_vect', 'oi_vect', 'oic_vect', 'ok_vect', 'okay_vect', 'okey_vect', 'okie_vect', 'ola_vect', 'old_vect', 'omg_vect', 'omw_vect', 'one_vect', 'ones_vect', 'oni_vect', 'online_vect', 'onto_vect', 'onwards_vect', 'oooh_vect', 'oops_vect', 'open_vect', 'opening_vect', 'operator_vect', 'opinion_vect', 'opportunity_vect', 'opt_vect', 'option_vect', 'optout_vect', 'or2stoptxt_vect', 'orange_vect', 'oranges_vect', 'orchard_vect', 'order_vect', 'ordered_vect', 'oredi_vect', 'original_vect', 'oru_vect', 'os_vect', 'oso_vect', 'others_vect', 'otherwise_vect', 'otside_vect', 'outside_vect', 'outstanding_vect', 'outta_vect', 'ovulation_vect', 'oz_vect', 'pa_vect', 'pack_vect', 'package_vect', 'page_vect', 'pages_vect', 'paid_vect', 'pain_vect', 'painful_vect', 'painting_vect', 'panic_vect', 'paper_vect', 'papers_vect', 'paperwork_vect', 'parco_vect', 'parent_vect', 'parents_vect', 'paris_vect', 'park_vect', 'parked_vect', 'parking_vect', 'part_vect', 'partner_vect', 'partnership_vect', 'party_vect', 'pass_vect', 'passed_vect', 'password_vect', 'past_vect', 'pattern_vect', 'patty_vect', 'pay_vect', 'paying_vect', 'payment_vect', 'payoh_vect', 'pc_vect', 'peace_vect', 'pence_vect', 'people_vect', 'per_vect', 'perfect_vect', 'period_vect', 'person_vect', 'personal_vect', 'pete_vect', 'petey_vect', 'pg_vect', 'philosophy_vect', 'phoenix_vect', 'phone_vect', 'phones_vect', 'photo_vect', 'photos_vect', 'pic_vect', 'pick_vect', 'picked_vect', 'picking_vect', 'pics_vect', 'picsfree1_vect', 'picture_vect', 'pictures_vect', 'pie_vect', 'pieces_vect', 'pig_vect', 'pilates_vect', 'pin_vect', 'pink_vect', 'piss_vect', 'pissed_vect', 'pix_vect', 'pizza_vect', 'place_vect', 'places_vect', 'plan_vect', 'planned_vect', 'planning_vect', 'plans_vect', 'play_vect', 'played_vect', 'player_vect', 'players_vect', 'playing_vect', 'please_vect', 'pleased_vect', 'pleasure_vect', 'plenty_vect', 'pls_vect', 'plus_vect', 'plz_vect', 'pm_vect', 'po_vect', 'pobox_vect', 'pobox334_vect', 'pobox36504w45wq_vect', 'pobox45w2tg150p_vect', 'pobox84_vect', 'pod_vect', 'point_vect', 'points_vect', 'poker_vect', 'pole_vect', 'police_vect', 'politicians_vect', 'poly_vect', 'polyphonic_vect', 'polys_vect', 'pongal_vect', 'poor_vect', 'pop_vect', 'popped_vect', 'porn_vect', 'possession_vect', 'possible_vect', 'post_vect', 'postcard_vect', 'postcode_vect', 'posted_vect', 'posts_vect', 'potential_vect', 'potter_vect', 'pound_vect', 'pounds_vect', 'pouts_vect', 'power_vect', 'ppl_vect', 'pple_vect', 'ppm_vect', 'prabha_vect', 'practice_vect', 'practicing_vect', 'pray_vect', 'prefer_vect', 'premier_vect', 'prepare_vect', 'prescription_vect', 'present_vect', 'press_vect', 'pretty_vect', 'prey_vect', 'price_vect', 'prince_vect', 'princess_vect', 'print_vect', 'privacy_vect', 'private_vect', 'prize_vect', 'prob_vect', 'probably_vect', 'problem_vect', 'problems_vect', 'process_vect', 'processed_vect', 'prof_vect', 'profit_vect', 'program_vect', 'project_vect', 'prolly_vect', 'promise_vect', 'promises_vect', 'promo_vect', 'proof_vect', 'properly_vect', 'prospects_vect', 'provided_vect', 'ps_vect', 'ptbo_vect', 'pub_vect', 'pull_vect', 'purchase_vect', 'purity_vect', 'purpose_vect', 'push_vect', 'pushes_vect', 'pussy_vect', 'put_vect', 'puttin_vect', 'putting_vect', 'qatar_vect', 'quality_vect', 'queen_vect', 'ques_vect', 'question_vect', 'questions_vect', 'quick_vect', 'quickly_vect', 'quiet_vect', 'quit_vect', 'quite_vect', 'quiz_vect', 'quote_vect', 'quoting_vect', 'racing_vect', 'radio_vect', 'railway_vect', 'rain_vect', 'raining_vect', 'raise_vect', 'rakhesh_vect', 'rally_vect', 'ran_vect', 'random_vect', 'randomly_vect', 'randy_vect', 'rang_vect', 'range_vect', 'ranjith_vect', 'rate_vect', 'rates_vect', 'rather_vect', 'rays_vect', 'rcvd_vect', 'rd_vect', '", "instruction": "", "output": "" }, { "input": "re_vect', 'reach_vect', 'reached_vect', 'reaching_vect', 'reaction_vect', 'read_vect', 'readers_vect', 'reading_vect', 'ready_vect', 'real_vect', 'realise_vect', 'reality_vect', 'realized_vect', 'really_vect', 'realy_vect', 'reason_vect', 'reasonable_vect', 'reasons_vect', 'reboot_vect', 'recd_vect', 'receipt_vect', 'receive_vect', 'received_vect', 'receiving_vect', 'recent_vect', 'recently_vect', 'recession_vect', 'record_vect', 'records_vect', 'recovery_vect', 'red_vect', 'ref_vect', 'reference_vect', 'reg_vect', 'regards_vect', 'register_vect', 'registered_vect', 'regret_vect', 'regular_vect', 'relation_vect', 'relax_vect', 'released_vect', 'rem_vect', 'remain_vect', 'remains_vect', 'remember_vect', 'remembered_vect', 'remembr_vect', 'remind_vect', 'reminder_vect', 'remove_vect', 'rent_vect', 'rental_vect', 'rentl_vect', 'repair_vect', 'repeat_vect', 'replied_vect', 'reply_vect', 'replying_vect', 'report_vect', 'representative_vect', 'request_vect', 'requests_vect', 'research_vect', 'resend_vect', 'respect_vect', 'respond_vect', 'responding_vect', 'response_vect', 'responsibility_vect', 'rest_vect', 'restaurant_vect', 'result_vect', 'results_vect', 'retrieve_vect', 'return_vect', 'returned_vect', 'returns_vect', 'reveal_vect', 'revealed_vect', 'review_vect', 'revision_vect', 'reward_vect', 'rhythm_vect', 'rice_vect', 'rich_vect', 'ride_vect', 'right_vect', 'rights_vect', 'ring_vect', 'ringtone_vect', 'ringtones_vect', 'rite_vect', 'river_vect', 'road_vect', 'roads_vect', 'roast_vect', 'rock_vect', 'rocks_vect', 'rofl_vect', 'roger_vect', 'role_vect', 'ron_vect', 'room_vect', 'roommate_vect', 'roommates_vect', 'rooms_vect', 'rose_vect', 'round_vect', 'row_vect', 'roww1j6hl_vect', 'roww1jhl_vect', 'royal_vect', 'rply_vect', 'rs_vect', 'rstm_vect', 'ru_vect', 'rub_vect', 'rude_vect', 'rule_vect', 'run_vect', 'running_vect', 'runs_vect', 'rush_vect', 'sacrifice_vect', 'sad_vect', 'sae_vect', 'safe_vect', 'said_vect', 'salam_vect', 'salary_vect', 'sale_vect', 'salon_vect', 'sam_vect', 'santa_vect', 'sar_vect', 'sarasota_vect', 'sarcastic_vect', 'sary_vect', 'sat_vect', 'sathya_vect', 'saturday_vect', 'savamob_vect', 'save_vect', 'saved_vect', 'saw_vect', 'say_vect', 'saying_vect', 'says_vect', 'scared_vect', 'scary_vect', 'sch_vect', 'schedule_vect', 'school_vect', 'schools_vect', 'science_vect', 'scold_vect', 'score_vect', 'scores_vect', 'scotland_vect', 'scream_vect', 'screaming_vect', 'scrounge_vect', 'se_vect', 'sea_vect', 'search_vect', 'searching_vect', 'season_vect', 'seat_vect', 'sec_vect', 'second_vect', 'seconds_vect', 'secret_vect', 'secretary_vect', 'secs_vect', 'sed_vect', 'see_vect', 'seeing_vect', 'seem_vect', 'seemed_vect', 'seems_vect', 'seen_vect', 'selected_vect', 'selection_vect', 'self_vect', 'sell_vect', 'selling_vect', 'sells_vect', 'sem_vect', 'semester_vect', 'sen_vect', 'send_vect', 'sender_vect', 'sending_vect', 'sense_vect', 'sent_vect', 'sentence_vect', 'sept_vect', 'series_vect', 'serious_vect', 'seriously_vect', 'service_vect', 'services_vect', 'serving_vect', 'set_vect', 'setting_vect', 'settings_vect', 'settle_vect', 'settled_vect', 'seven_vect', 'several_vect', 'sex_vect', 'sexy_vect', 'sh_vect', 'sha_vect', 'shall_vect', 'share_vect', 'shd_vect', 'sheets_vect', 'shes_vect', 'shesil_vect', 'shining_vect', 'ship_vect', 'shipping_vect', 'shirt_vect', 'shirts_vect', 'shit_vect', 'shld_vect', 'shocking_vect', 'shoot_vect', 'shop_vect', 'shoppin_vect', 'shopping_vect', 'short_vect', 'shorter_vect', 'shortly_vect', 'shot_vect', 'shoving_vect', 'show_vect', 'shower_vect', 'showing_vect', 'shows_vect', 'shu_vect', 'shuhui_vect', 'shy_vect', 'si_vect', 'sick_vect', 'side_vect', 'sighs_vect', 'sight_vect', 'sign_vect', 'signing_vect', 'silence_vect', 'silent_vect', 'silver_vect', 'sim_vect', 'simple_vect', 'simply_vect', 'since_vect', 'sing_vect', 'singing_vect', 'single_vect', 'singles_vect', 'sipix_vect', 'sir_vect', 'sis_vect', 'sister_vect', 'sit_vect', 'site_vect', 'sitting_vect', 'situation_vect', 'siva_vect', 'six_vect', 'size_vect', 'sk3_vect', 'sk38xh_vect', 'skilgme_vect', 'skip_vect', 'sky_vect', 'skype_vect', 'skyped_vect', 'slap_vect', 'slave_vect', 'sleep_vect', 'sleepin_vect', 'sleeping_vect', 'sleepy_vect', 'slept_vect', 'slice_vect', 'slide_vect', 'slightly_vect', 'slip_vect', 'slippers_vect', 'slo_vect', 'slots_vect', 'slow_vect', 'slowly_vect', 'small_vect', 'smashed_vect', 'smile_vect', 'smiles_vect', 'smiling_vect', 'smoke_vect', 'smoking_vect', 'sms_vect', 'smth_vect', 'sn_vect', 'snake_vect', 'snow_vect', 'social_vect', 'sofa_vect', 'soft_vect', 'software_vect', 'sol_vect', 'some1_vect', 'somebody_vect', 'someone_vect', 'somethin_vect', 'something_vect', 'sometimes_vect', 'somewhere_vect', 'song_vect', 'songs_vect', 'sony_vect', 'sonyericsson_vect', 'soon_vect', 'sooner_vect', 'sore_vect', 'sorry_vect', 'sort_vect', 'sorting_vect', 'sound_vect', 'sounds_vect', 'south_vect', 'sp_vect', 'space_vect', 'spanish_vect', 'speak_vect', 'speaking_vect', 'special_vect', 'specialcall_vect', 'specially_vect', 'speed_vect', 'spend_vect', 'spending_vect', 'spent_vect', 'spk_vect', 'spoke_vect', 'spoken_vect', 'spook_vect', 'sport_vect', 'sports_vect', 'spree_vect', 'spring_vect', 'sptv_vect', 'sry_vect', 'st_vect', 'staff_vect', 'stamps_vect', 'stand_vect', 'standard_vect', 'standing_vect', 'star_vect', 'staring_vect', 'start_vect', 'started_vect', 'starting_vect', 'starts_vect', 'starwars3_vect', 'statement_vect', 'station_vect', 'stay_vect', 'stayed_vect', 'staying_vect', 'std_vect', 'steam_vect', 'step_vect', 'steve_vect', 'stick_vect', 'sticky_vect', 'still_vect', 'stock_vect', 'stockport_vect', 'stomach_vect', 'stomps_vect', 'stones_vect', 'stop_vect', 'stopped_vect', 'stops_vect', 'store_vect', 'stores_vect', 'story_vect', 'str_vect', 'straight_vect', 'stranger_vect', 'street_vect', 'stress_vect', 'strike_vect', 'strong_vect', 'strongbuy_vect', 'stuck_vect', 'student_vect', 'study_vect', 'studying_vect', 'stuff_vect', 'stupid_vect', 'style_vect', 'stylish_vect', 'sub_vect', 'subpoly_vect', 'subs_vect', 'subscribe6gbpmnth_vect', 'subscribed_vect', 'subscriber_vect', 'subscription_vect', 'success_vect', 'successful_vect', 'successfully_vect', 'sucks_vect', 'sue_vect', 'sufficient_vect', 'suggest_vect', 'suite_vect', 'suits_vect', 'sum1_vect', 'summer_vect', 'sun_vect', 'sunday_vect', 'sunlight_vect', 'sunny_vect', 'sunshine_vect', 'suntec_vect', 'sup_vect', 'super_vect', 'superb_vect', 'superior_vect', 'supervisor_vect', 'supply_vect', 'support_vect', 'suppose_vect', 'supposed_vect', 'suprman_vect', 'sura_vect', 'sure_vect', 'surely_vect', 'surfing_vect', 'surprise_vect', 'surprised_vect', 'survey_vect', 'sux_vect', 'suzy_vect', 'sw7_vect', 'sw73ss_vect', 'sweet_vect', 'swing_vect', 'system_vect', 'ta_vect', 'tablets_vect', 'tahan_vect', 'take_vect', 'taken_vect', 'takes_vect', 'takin_vect', 'taking_vect', 'talent_vect', 'talk_vect', 'talking_vect', 'tampa_vect', 'tape_vect', 'tariffs_vect', 'tat_vect', 'taunton_vect', 'taylor_vect', 'tb_vect', 'tc_vect', 'tcrw1_vect', 'tcs_vect', 'tea_vect', 'teach_vect', 'teacher_vect', 'teaches_vect', 'team_vect', 'tear_vect', 'tease_vect', 'teasing_vect', 'tech_vect', 'technical_vect', 'tee_vect', 'teeth_vect', 'tel_vect', 'telephone_vect', 'tell_vect', 'telling_vect', 'tells_vect', 'telugu_vect', 'temple_vect', 'ten_vect', 'tenants_vect', 'tenerife_vect', 'tension_vect', 'term_vect', 'terms_vect', 'terrible_vect', 'test_vect', 'testing_vect', 'text_vect', 'texted_vect', 'texting_vect', 'textoperator_vect', 'texts_vect', 'th_vect', 'thangam_vect', 'thank_vect', 'thanks_vect', 'thanksgiving_vect', 'thanx_vect', 'that_vect', 'thats_vect', 'that\u00e5\u00f5s_vect', 'the_vect', 'theatre_vect', 'themob_vect', 'theory_vect', 'thesis_vect', 'thgt_vect', 'thing_vect', 'things_vect', 'think_vect', 'thinkin_vect', 'thinking_vect', 'thinks_vect', 'thk_vect', 'thnk_vect', 'tho_vect', 'though_vect', 'thought_vect', 'three_vect', 'throat_vect', 'throw_vect', 'thru_vect', 'tht_vect', 'thts_vect', 'thurs_vect', 'thursday_vect', 'tick_vect', 'ticket_vect', 'tickets_vect', 'tight_vect', 'tihs_vect', 'til_vect', 'till_vect', 'time_vect', 'times_vect', 'timing_vect', 'tired_vect', 'tirunelvali_vect', 'tirupur_vect', 'tissco_vect', 'tkts_vect', 'tm_vect', 'tming_vect', 'tmobile_vect', 'tmr_vect', 'tncs_vect', 'toa_vect', 'toclaim_vect', 'today_vect', 'todays_vect', 'tog_vect', 'together_vect', 'tok_vect', 'told_vect', 'tomarrow_vect', 'tomo_vect', 'tomorrow_vect', 'tone_vect', 'tones_vect', 'tones2youcouk_vect', 'tonight_vect', 'tonite_vect', 'took_vect', 'tool_vect', 'tooo_vect', 'toot_vect', 'top_vect', 'topic_vect', 'torch_vect', 'toshiba_vect', 'tot_vect', 'total_vect', 'totally_vect', 'touch_vect', 'tough_vect', 'tour_vect', 'towards_vect', 'town_vect', 'track", "instruction": "", "output": "" }, { "input": "_vect', 'trade_vect', 'traffic_vect', 'train_vect', 'training_vect', 'transaction_vect', 'transfer_vect', 'transport_vect', 'travel_vect', 'treat_vect', 'treated_vect', 'tried_vect', 'trip_vect', 'trips_vect', 'trouble_vect', 'true_vect', 'truffles_vect', 'truly_vect', 'trust_vect', 'truth_vect', 'try_vect', 'trying_vect', 'ts_vect', 'tscs_vect', 'tscs087147403231winawk_vect', 'tt_vect', 'ttyl_vect', 'tues_vect', 'tuesday_vect', 'tuition_vect', 'turn_vect', 'turning_vect', 'turns_vect', 'tv_vect', 'twelve_vect', 'twice_vect', 'two_vect', 'txt_vect', 'txtauction_vect', 'txtin_vect', 'txting_vect', 'txtno_vect', 'txts_vect', 'txtstop_vect', 'tyler_vect', 'type_vect', 'tyrone_vect', 'u4_vect', 'ubi_vect', 'ufind_vect', 'ugh_vect', 'uh_vect', 'uk_vect', 'uks_vect', 'ultimatum_vect', 'umma_vect', 'unable_vect', 'uncle_vect', 'understand_vect', 'understanding_vect', 'understood_vect', 'underwear_vect', 'unemployed_vect', 'uni_vect', 'unique_vect', 'university_vect', 'unless_vect', 'unlimited_vect', 'unnecessarily_vect', 'unredeemed_vect', 'unsold_vect', 'unsub_vect', 'unsubscribe_vect', 'upd8_vect', 'update_vect', 'updatenow_vect', 'upgrade_vect', 'upload_vect', 'upset_vect', 'upstairs_vect', 'ur_vect', 'ure_vect', 'urgent_vect', 'urgnt_vect', 'url_vect', 'urn_vect', 'urself_vect', 'us_vect', 'usb_vect', 'use_vect', 'used_vect', 'user_vect', 'usf_vect', 'using_vect', 'usual_vect', 'usually_vect', 'vale_vect', 'valentine_vect', 'valentines_vect', 'valid_vect', 'valid12hrs_vect', 'valuable_vect', 'value_vect', 'valued_vect', 'vary_vect', 've_vect', 'vegas_vect', 'verify_vect', 'version_vect', 'via_vect', 'vid_vect', 'video_vect', 'videochat_vect', 'videophones_vect', 'vijay_vect', 'vikky_vect', 'village_vect', 'violated_vect', 'violence_vect', 'vip_vect', 'virgin_vect', 'visit_vect', 'vivek_vect', 'vl_vect', 'voda_vect', 'vodafone_vect', 'vodka_vect', 'voice_vect', 'voicemail_vect', 'vomit_vect', 'vote_vect', 'voucher_vect', 'vouchers_vect', 'vry_vect', 'vth_vect', 'w45wq_vect', 'wa_vect', 'wah_vect', 'wait_vect', 'waited_vect', 'waitin_vect', 'waiting_vect', 'wake_vect', 'waking_vect', 'wales_vect', 'walk_vect', 'walked_vect', 'walking_vect', 'walmart_vect', 'wan_vect', 'wana_vect', 'want_vect', 'wanted_vect', 'wanting_vect', 'wants_vect', 'wap_vect', 'warm_vect', 'warner_vect', 'waste_vect', 'wasted_vect', 'wat_vect', 'watch_vect', 'watching_vect', 'water_vect', 'wats_vect', 'way_vect', 'wc1n3xx_vect', 'we_vect', 'weak_vect', 'wear_vect', 'wearing_vect', 'weather_vect', 'web_vect', 'website_vect', 'wed_vect', 'wedding_vect', 'wednesday_vect', 'wee_vect', 'weed_vect', 'week_vect', 'weekend_vect', 'weekends_vect', 'weekly_vect', 'weeks_vect', 'weigh_vect', 'weight_vect', 'weird_vect', 'welcome_vect', 'well_vect', 'welp_vect', 'wen_vect', 'went_vect', 'west_vect', 'wet_vect', 'what_vect', 'whatever_vect', 'whats_vect', 'whenever_vect', 'whenevr_vect', 'wherever_vect', 'whether_vect', 'white_vect', 'whn_vect', 'whole_vect', 'whos_vect', 'whose_vect', 'wid_vect', 'widelivecomindex_vect', 'wif_vect', 'wife_vect', 'wil_vect', 'willing_vect', 'win_vect', 'wind_vect', 'wine_vect', 'winner_vect', 'winning_vect', 'wins_vect', 'wipro_vect', 'wisdom_vect', 'wise_vect', 'wish_vect', 'wishes_vect', 'wishing_vect', 'wit_vect', 'within_vect', 'without_vect', 'wiv_vect', 'wk_vect', 'wkend_vect', 'wkg_vect', 'wkly_vect', 'wks_vect', 'wld_vect', 'wml_vect', 'wn_vect', 'wnt_vect', 'wo_vect', 'woke_vect', 'woken_vect', 'woman_vect', 'women_vect', 'wonder_vect', 'wonderful_vect', 'wondering_vect', 'wont_vect', 'woot_vect', 'word_vect', 'words_vect', 'work_vect', 'workin_vect', 'working_vect', 'works_vect', 'world_vect', 'worried_vect', 'worries_vect', 'worry_vect', 'worse_vect', 'worst_vect', 'worth_vect', 'wot_vect', 'would_vect', 'wow_vect', 'write_vect', 'wrong_vect', 'wtf_vect', 'wud_vect', 'wuld_vect', 'wun_vect', 'www4tcbiz_vect', 'wwwcomuknet_vect', 'wwwetlpcoukexpressoffer_vect', 'wwwgetzedcouk_vect', 'wwwldewcom_vect', 'wwwldewcom1win150ppmx3age16_vect', 'wwwmovietriviatv_vect', 'wwwringtonescouk_vect', 'wwwsmsconet_vect', 'wwwtxttowincouk_vect', 'wwwurawinnercom_vect', 'wylie_vect', 'xchat_vect', 'xmas_vect', 'xuhui_vect', 'xx_vect', 'xxx_vect', 'xxxx_vect', 'xxxxx_vect', 'xy_vect', 'ya_vect', 'yahoo_vect', 'yan_vect', 'yar_vect', 'yay_vect', 'yck_vect', 'yeah_vect', 'year_vect', 'years_vect', 'yelling_vect', 'yellow_vect', 'yep_vect', 'yes_vect', 'yest_vect', 'yesterday_vect', 'yet_vect', 'yetunde_vect', 'yijue_vect', 'ym_vect', 'yo_vect', 'yoga_vect', 'yogasana_vect', 'yor_vect', 'you_vect', 'yr_vect', 'yrs_vect', 'yummy_vect', 'yun_vect', 'yuo_vect', 'yup_vect', 'zed_vect', 'zindgi_vect', '\u00ec\u00ef_vect', '\u00fb\u00f2_vect'], 'input_features_type': {'v2': 'O'}, 'word2num_features': [], 'unpreprocessed_columns': [], 'force_numeric_conv': [], 'conversion_method': 'TF_IDF'}, 'selector': {'reducer': False, 'reducer_file': '', 'input_features': ['v2'], 'output_features': ['07xxxxxxxxx_vect', '08700621170150p_vect', '08702840625comuk_vect', '08718726270150gbpmtmsg18_vect', '1000s_vect', '10am7pm_vect', '10k_vect', '10p_vect', '10pmin_vect', '10ppm_vect', '11mths_vect', '125gift_vect', '12hrs_vect', '12mths_vect', '150p_vect', '150perwksub_vect', '150pm_vect', '150pmin_vect', '150pmsg_vect', '150pmsgrcvdhgsuite3422landsroww1j6hl_vect', '150pmtmsgrcvd18_vect', '150ppm_vect', '150ptone_vect', '150pwk_vect', '150week_vect', '16only_vect', '18only_vect', '1hr_vect', '1minmobsmorelkpobox177hp51fl_vect', '1st_vect', '1x150pwk_vect', '20p_vect', '20pmin_vect', '21st_vect', '220cm2_vect', '24hrs_vect', '25p_vect', '26th_vect', '2day_vect', '2find_vect', '2geva_vect', '2go_vect', '2marrow_vect', '2mrw_vect', '2nd_vect', '2nite_vect', '2optout_vect', '2p_vect', '2u_vect', '2waxsto_vect', '2wks_vect', '300p_vect', '31pmsg_vect', '3510i_vect', '3d_vect', '3g_vect', '3gbp_vect', '3hrs_vect', '3mins_vect', '3qxj9_vect', '3rd_vect', '3ss_vect', '3u_vect', '3uz_vect', '3wk_vect', '40gb_vect', '4a_vect', '4d_vect', '4eva_vect', '4get_vect', '4info_vect', '4mths_vect', '4th_vect', '4u_vect', '50p_vect', '5min_vect', '5pm_vect', '5wb_vect', '5we_vect', '60pmin_vect', '6hrs_vect', '6months_vect', '6pm_vect', '7250i_vect', '7ish_vect', '8am_vect', '8pm_vect', '8th_vect', '8wp_vect', '9ae_vect', '9ja_vect', '9pm_vect', '9t_vect', 'aathi_vect', 'abi_vect', 'ability_vect', 'abiola_vect', 'able_vect', 'abt_vect', 'abta_vect', 'aburo_vect', 'ac_vect', 'academic_vect', 'acc_vect', 'accept_vect', 'access_vect', 'accident_vect', 'accidentally_vect', 'accordingly_vect', 'account_vect', 'ache_vect', 'across_vect', 'acted_vect', 'action_vect', 'activate_vect', 'activities_vect', 'actor_vect', 'actual_vect', 'actually_vect', 'ad_vect', 'adam_vect', 'add_vect', 'added_vect', 'addicted_vect', 'addie_vect', 'address_vect', 'admin_vect', 'administrator_vect', 'admirer_vect', 'admit_vect', 'adore_vect', 'adoring_vect', 'ads_vect', 'adult_vect', 'advance_vect', 'adventure_vect', 'advice_vect', 'advise_vect', 'affair_vect', 'affairs_vect', 'affectionate_vect', 'afraid_vect', 'aft_vect', 'afternoon_vect', 'aftr_vect', 'agalla_vect', 'age_vect', 'age16_vect', 'ages_vect', 'ago_vect', 'agree_vect', 'ah_vect', 'aha_vect', 'ahead_vect', 'ahmad_vect', 'ai_vect', 'aight_vect', 'aint_vect', 'air_vect', 'airport_vect', 'airtel_vect', 'aiya_vect', 'aiyah_vect', 'aiyar_vect', 'aiyo_vect', 'al_vect', 'album_vect', 'alert_vect', 'alex_vect', 'alfie_vect', 'ali_vect', 'allah_vect', 'allow_vect', 'allowed_vect', 'almost_vect', 'alone_vect', 'along_vect', 'already_vect', 'alright_vect', 'alrite_vect', 'also_vect', 'always_vect', 'alwys_vect', 'amazing_vect', 'american_vect', 'among_vect', 'amount_vect', 'amp_vect', 'amt_vect', 'andros_vect', 'angry_vect', 'annie_vect', 'anniversary_vect', 'announcement_vect', 'anot_vect', 'another_vect', 'ans_vect', 'ansr_vect', 'answer_vect', 'answered_vect', 'answering_vect', 'answers_vect', 'anthony_vect', 'anti_vect', 'anybody_vect', 'anymore_vect', 'anyone_vect', 'anything_vect', 'anytime_vect', 'anyway_vect', 'anyways_vect', 'apartment_vect', 'app_vect', 'apparently_vect', 'applebees_vect', 'apply_vect', 'appointment_vect', 'appreciate_vect', 'appreciated_vect', 'approx_vect', 'apps_vect', 'appt_vect', '", "instruction": "", "output": "" }, { "input": "april_vect', 'ar_vect', 'arcade_vect', 'ard_vect', 'area_vect', 'argh_vect', 'argument_vect', 'arm_vect', 'armand_vect', 'arms_vect', 'around_vect', 'arrange_vect', 'arrested_vect', 'arrive_vect', 'arsenal_vect', 'art_vect', 'arun_vect', 'asap_vect', 'ashley_vect', 'ask_vect', 'askd_vect', 'asked_vect', 'askin_vect', 'asking_vect', 'asks_vect', 'asleep_vect', 'ass_vect', 'assume_vect', 'ate_vect', 'atlanta_vect', 'atlast_vect', 'atm_vect', 'attached_vect', 'attempt_vect', 'attend_vect', 'auction_vect', 'august_vect', 'aunt_vect', 'aunty_vect', 'auto_vect', 'av_vect', 'available_vect', 'avatar_vect', 'ave_vect', 'avent_vect', 'avoid_vect', 'await_vect', 'awaiting_vect', 'awake_vect', 'award_vect', 'awarded_vect', 'away_vect', 'awesome_vect', 'aww_vect', 'b4_vect', 'ba_vect', 'babe_vect', 'babes_vect', 'babies_vect', 'baby_vect', 'back_vect', 'bad_vect', 'bag_vect', 'bags_vect', 'bahamas_vect', 'bak_vect', 'balance_vect', 'bank_vect', 'banks_vect', 'bar_vect', 'barely_vect', 'basic_vect', 'basically_vect', 'bat_vect', 'bath_vect', 'bathe_vect', 'bathing_vect', 'battery_vect', 'bay_vect', 'bb_vect', 'bc_vect', 'bck_vect', 'bcoz_vect', 'bday_vect', 'be_vect', 'bears_vect', 'beautiful_vect', 'beauty_vect', 'bec_vect', 'become_vect', 'becoz_vect', 'bed_vect', 'bedrm_vect', 'bedroom_vect', 'beer_vect', 'befor_vect', 'beg_vect', 'begin_vect', 'behave_vect', 'behind_vect', 'bein_vect', 'believe_vect', 'bell_vect', 'belly_vect', 'belovd_vect', 'best_vect', 'bet_vect', 'better_vect', 'beyond_vect', 'bf_vect', 'bid_vect', 'bids_vect', 'big_vect', 'bigger_vect', 'biggest_vect', 'bill_vect', 'billed_vect', 'billion_vect', 'bills_vect', 'bin_vect', 'biola_vect', 'birds_vect', 'birla_vect', 'birth_vect', 'birthdate_vect', 'birthday_vect', 'bishan_vect', 'bit_vect', 'bitch_vect', 'bite_vect', 'black_vect', 'blackberry_vect', 'blah_vect', 'blake_vect', 'blank_vect', 'bleh_vect', 'bless_vect', 'blessing_vect', 'bloo_vect', 'blood_vect', 'bloody_vect', 'blue_vect', 'bluetooth_vect', 'bluff_vect', 'boat_vect', 'body_vect', 'bold_vect', 'bone_vect', 'bonus_vect', 'boo_vect', 'book_vect', 'booked_vect', 'booking_vect', 'books_vect', 'boost_vect', 'booty_vect', 'bored_vect', 'boring_vect', 'born_vect', 'boss_vect', 'boston_vect', 'bother_vect', 'bottom_vect', 'bought_vect', 'bout_vect', 'bowl_vect', 'box_vect', 'box326_vect', 'box334sk38ch_vect', 'box97n7qp_vect', 'boy_vect', 'boye_vect', 'boyfriend_vect', 'boys_vect', 'boytoy_vect', 'brah_vect', 'brand_vect', 'bread_vect', 'break_vect', 'breathe_vect', 'bright_vect', 'brilliant_vect', 'bring_vect', 'bringing_vect', 'brings_vect', 'british_vect', 'bro_vect', 'broad_vect', 'broke_vect', 'broken_vect', 'bros_vect', 'brothas_vect', 'brother_vect', 'brought_vect', 'bruv_vect', 'bslvyl_vect', 'bt_vect', 'btnationalrate_vect', 'btw_vect', 'bucks_vect', 'bud_vect', 'budget_vect', 'buff_vect', 'buffet_vect', 'bugis_vect', 'building_vect', 'buns_vect', 'burger_vect', 'burns_vect', 'bus_vect', 'buses_vect', 'business_vect', 'busy_vect', 'butt_vect', 'buy_vect', 'buying_vect', 'buzz_vect', 'bx420_vect', 'bx420ip45we_vect', 'bye_vect', 'ca_vect', 'cabin_vect', 'cafe_vect', 'cake_vect', 'cal_vect', 'calculation_vect', 'calicut_vect', 'california_vect', 'call_vect', 'call2optout674_vect', 'callback_vect', 'callcost_vect', 'called_vect', 'caller_vect', 'callers_vect', 'callertune_vect', 'callin_vect', 'calling_vect', 'calls_vect', 'calls\u00e5_vect', 'cam_vect', 'camcorder_vect', 'came_vect', 'camera_vect', 'cameravideo_vect', 'campus_vect', 'can_vect', 'canada_vect', 'canal_vect', 'canary_vect', 'cancel_vect', 'cancelled_vect', 'cancer_vect', 'cant_vect', 'captain_vect', 'car_vect', 'card_vect', 'cardiff_vect', 'care_vect', 'cared_vect', 'career_vect', 'careful_vect', 'carefully_vect', 'caring_vect', 'carlos_vect', 'caroline_vect', 'cars_vect', 'cartoon_vect', 'case_vect', 'cash_vect', 'cashbalance_vect', 'cashin_vect', 'castor_vect', 'cat_vect', 'catch_vect', 'catching_vect', 'caught_vect', 'cause_vect', 'cbe_vect', 'cc_vect', 'cd_vect', 'cdgt_vect', 'cds_vect', 'celebrate_vect', 'celebration_vect', 'cell_vect', 'center_vect', 'centre_vect', 'certainly_vect', 'cha_vect', 'chain_vect', 'challenge_vect', 'chance_vect', 'change_vect', 'changed_vect', 'changes_vect', 'channel_vect', 'character_vect', 'charge_vect', 'charged_vect', 'charges_vect', 'charity_vect', 'charles_vect', 'chase_vect', 'chasing_vect', 'chat_vect', 'chatting_vect', 'cheap_vect', 'cheaper_vect', 'cheat_vect', 'chechi_vect', 'check_vect', 'checked_vect', 'checking_vect', 'cheers_vect', 'chennai_vect', 'cherish_vect', 'chest_vect', 'chicken_vect', 'chikku_vect', 'child_vect', 'childish_vect', 'children_vect', 'chill_vect', 'chillin_vect', 'china_vect', 'chinese_vect', 'chip_vect', 'chocolate_vect', 'choice_vect', 'choose_vect', 'chosen_vect', 'christ_vect', 'christmas_vect', 'church_vect', 'cine_vect', 'cinema_vect', 'citizen_vect', 'city_vect', 'claim_vect', 'claims_vect', 'claire_vect', 'class_vect', 'classes_vect', 'clean_vect', 'cleaning_vect', 'clear_vect', 'clearly_vect', 'click_vect', 'clock_vect', 'close_vect', 'closed_vect', 'closer_vect', 'closes_vect', 'clothes_vect', 'club_vect', 'cn_vect', 'co_vect', 'coast_vect', 'coat_vect', 'cochin_vect', 'code_vect', 'coffee_vect', 'coin_vect', 'coins_vect', 'cold_vect', 'colleagues_vect', 'collect_vect', 'collected_vect', 'collecting_vect', 'collection_vect', 'college_vect', 'colour_vect', 'come_vect', 'comedy_vect', 'comes_vect', 'comin_vect', 'coming_vect', 'commercial_vect', 'common_vect', 'community_vect', 'comp_vect', 'company_vect', 'competition_vect', 'complete_vect', 'completed_vect', 'completely_vect', 'complimentary_vect', 'computer_vect', 'concentrate_vect', 'concert_vect', 'conditions_vect', 'conducts_vect', 'confidence_vect', 'confirm_vect', 'congrats_vect', 'congratulations_vect', 'connection_vect', 'consider_vect', 'considering_vect', 'constant_vect', 'constantly_vect', 'contact_vect', 'contacted_vect', 'contacts_vect', 'content_vect', 'contents_vect', 'continue_vect', 'contract_vect', 'control_vect', 'convey_vect', 'convinced_vect', 'cool_vect', 'coping_vect', 'copy_vect', 'cornwall_vect', 'correct_vect', 'cos_vect', 'cost_vect', 'costa_vect', 'costs_vect', 'cost\u00e5_vect', 'could_vect', 'count_vect', 'countin_vect', 'country_vect', 'couple_vect', 'course_vect', 'cover_vect', 'coz_vect', 'cr9_vect', 'cramps_vect', 'crave_vect', 'crazy_vect', 'created_vect', 'credit_vect', 'credited_vect', 'credits_vect', 'creepy_vect', 'crisis_vect', 'crore_vect', 'cross_vect', 'croydon_vect', 'cruise_vect', 'cry_vect', 'cs_vect', 'csbcm4235wc1n3xx_vect', 'csstop_vect', 'cud_vect', 'cuddling_vect', 'cum_vect', 'cup_vect', 'curious_vect', 'current_vect', 'currently_vect', 'cust_vect', 'custcare_vect', 'custcare08718720201_vect', 'custom_vect', 'customer_vect', 'customers_vect', 'cut_vect', 'cute_vect', 'cutting_vect', 'cuz_vect', 'cw25wx_vect', 'da_vect', 'dad_vect', 'daddy_vect', 'daily_vect', 'damn_vect', 'dance_vect', 'dancing_vect', 'dare_vect', 'dark_vect', 'darlin_vect', 'darling_vect', 'darren_vect', 'dat_vect', 'date_vect', 'dates_vect', 'dating_vect', 'dave_vect', 'day_vect', 'days_vect', 'de_vect', 'dead_vect', 'deal_vect', 'dealer_vect', 'dealing_vect', 'dear_vect', 'dearly_vect', 'death_vect', 'decide_vect', 'decided_vect', 'decimal_vect', 'decision_vect', 'deep_vect', 'def_vect', 'definite_vect', 'definitely_vect', 'del_vect', 'delete_vect', 'deleted_vect', 'delhi_vect', 'deliver_vect', 'delivered_vect', 'deliveredtomorrow_vect', 'delivery_vect', 'dem_vect', 'demand_vect', 'den_vect', 'denis_vect', 'department_vect', 'depends_vect', 'depressed_vect', 'derek_vect', 'desires_vect', 'desperate_vect', 'details_vect', 'dey_vect', 'dhoni_vect', 'dial_vect', 'dick_vect', 'dictionary_vect', 'didn_vect', 'didnt_vect', 'didt_vect', 'die_vect', 'died_vect', 'diet_vect', 'different_vect', 'difficult_vect', 'digital_vect', 'dignity_vect', 'din_vect', 'dinner_vect', 'dint_vect', 'direct_vect', 'directly_vect', 'dirty_vect', 'dis_vect', 'discount_vect', 'discuss_vect', 'dislikes_vect', 'display_vect', 'distance_vect', 'distract_vect', 'disturb_vect', 'division_vect', 'dload_vect', 'dnt_vect', 'doc_vect', 'docs_vect', 'doctor_vect', 'doesnt_vect', 'dog_vect', 'dogging_vect', 'doggy_vect', 'doin_vect', 'dollars_vect', 'don_vect', 'done_vect', 'dont_vect', 'don\u00e5\u00f5t_vect', 'door_vect', 'dorm_vect', 'double_vect', 'dough_vect', 'download_vect', 'downloads_vect', 'draw_vect', 'dream_vect', 'dreams_vect', 'dress_vect', 'dressed_vect', 'dresser_vect', 'drink_vect', 'drinking_vect', 'drinks_vect', 'drive_vect', 'driver_vect', 'drivin_vect', 'driving_vect', 'drop_vect', 'dropped_vect', 'drug_vect', 'drugs_vect', 'drunk_vect', 'dry_vect', 'ds_vect', 'dubsack_ve", "instruction": "", "output": "" }, { "input": "ct', 'dude_vect', 'due_vect', 'dun_vect', 'dunno_vect', 'durban_vect', 'dvd_vect', 'earlier_vect', 'early_vect', 'earth_vect', 'easier_vect', 'easily_vect', 'east_vect', 'easter_vect', 'easy_vect', 'eat_vect', 'eaten_vect', 'eatin_vect', 'eating_vect', 'ebay_vect', 'ec2a_vect', 'ee_vect', 'eek_vect', 'eerie_vect', 'effects_vect', 'eg_vect', 'egg_vect', 'eggs_vect', 'eh_vect', 'eight_vect', 'either_vect', 'ela_vect', 'electricity_vect', 'else_vect', 'elsewhere_vect', 'em_vect', 'email_vect', 'embarassed_vect', 'empty_vect', 'end_vect', 'ended_vect', 'ending_vect', 'ends_vect', 'enemy_vect', 'energy_vect', 'eng_vect', 'engin_vect', 'england_vect', 'english_vect', 'enjoy_vect', 'enjoyed_vect', 'enough_vect', 'enter_vect', 'entered_vect', 'entitled_vect', 'entry_vect', 'enuff_vect', 'envelope_vect', 'er_vect', 'erm_vect', 'escape_vect', 'especially_vect', 'esplanade_vect', 'eta_vect', 'etc_vect', 'euro_vect', 'euro2004_vect', 'europe_vect', 'eve_vect', 'eveb_vect', 'even_vect', 'evening_vect', 'event_vect', 'ever_vect', 'every_vect', 'everybody_vect', 'everyday_vect', 'everyone_vect', 'everything_vect', 'everywhere_vect', 'evn_vect', 'evng_vect', 'ex_vect', 'exact_vect', 'exactly_vect', 'exam_vect', 'exams_vect', 'excellent_vect', 'except_vect', 'exciting_vect', 'excuse_vect', 'excuses_vect', 'executive_vect', 'exeter_vect', 'exhausted_vect', 'expect_vect', 'expecting_vect', 'expensive_vect', 'experience_vect', 'expired_vect', 'expires_vect', 'explain_vect', 'explicit_vect', 'explosive_vect', 'express_vect', 'extra_vect', 'eye_vect', 'eyes_vect', 'fa_vect', 'fab_vect', 'face_vect', 'facebook_vect', 'fact_vect', 'faggy_vect', 'failed_vect', 'fair_vect', 'faith_vect', 'fall_vect', 'falls_vect', 'family_vect', 'fan_vect', 'fancies_vect', 'fancy_vect', 'fantasies_vect', 'fantastic_vect', 'fantasy_vect', 'far_vect', 'farm_vect', 'fast_vect', 'faster_vect', 'fat_vect', 'father_vect', 'fathima_vect', 'fault_vect', 'fave_vect', 'favorite_vect', 'favour_vect', 'favourite_vect', 'fb_vect', 'feb_vect', 'february_vect', 'feel_vect', 'feelin_vect', 'feeling_vect', 'feels_vect', 'fees_vect', 'feet_vect', 'fell_vect', 'felt_vect', 'fetch_vect', 'fever_vect', 'field_vect', 'fifteen_vect', 'fight_vect', 'fighting_vect', 'figure_vect', 'file_vect', 'files_vect', 'fill_vect', 'filling_vect', 'fills_vect', 'film_vect', 'final_vect', 'finally_vect', 'find_vect', 'fine_vect', 'fingers_vect', 'finish_vect', 'finished_vect', 'first_vect', 'fit_vect', 'fix_vect', 'fixed_vect', 'flag_vect', 'flaked_vect', 'flash_vect', 'flat_vect', 'flight_vect', 'flights_vect', 'flirt_vect', 'floor_vect', 'flower_vect', 'fml_vect', 'fo_vect', 'follow_vect', 'followed_vect', 'following_vect', 'fone_vect', 'food_vect', 'fool_vect', 'football_vect', 'force_vect', 'foreign_vect', 'forever_vect', 'forevr_vect', 'forget_vect', 'forgets_vect', 'forgiven_vect', 'forgot_vect', 'format_vect', 'forums_vect', 'forward_vect', 'forwarded_vect', 'found_vect', 'four_vect', 'fr_vect', 'fran_vect', 'freak_vect', 'free_vect', 'freefone_vect', 'freemsg_vect', 'freephone_vect', 'freezing_vect', 'fren_vect', 'frens_vect', 'fret_vect', 'fri_vect', 'friday_vect', 'friend_vect', 'friends_vect', 'friendship_vect', 'fringe_vect', 'frm_vect', 'frnd_vect', 'frnds_vect', 'frndship_vect', 'fuck_vect', 'fuckin_vect', 'fucking_vect', 'ful_vect', 'full_vect', 'fullonsmscom_vect', 'fun_vect', 'funny_vect', 'future_vect', 'fyi_vect', 'gal_vect', 'gals_vect', 'game_vect', 'games_vect', 'gang_vect', 'gap_vect', 'gaps_vect', 'garage_vect', 'garbage_vect', 'gary_vect', 'gas_vect', 'gautham_vect', 'gave_vect', 'gay_vect', 'gd_vect', 'ge_vect', 'gee_vect', 'geeee_vect', 'geeeee_vect', 'gender_vect', 'generally_vect', 'genius_vect', 'gentle_vect', 'gentleman_vect', 'gently_vect', 'germany_vect', 'get_vect', 'gets_vect', 'gettin_vect', 'getting_vect', 'gf_vect', 'gibbs_vect', 'gift_vect', 'gim_vect', 'girl_vect', 'girls_vect', 'gist_vect', 'giv_vect', 'give_vect', 'given_vect', 'gives_vect', 'giving_vect', 'glad_vect', 'gn_vect', 'go_vect', 'goal_vect', 'god_vect', 'goes_vect', 'goin_vect', 'going_vect', 'gold_vect', 'gon_vect', 'gona_vect', 'gone_vect', 'good_vect', 'goodmorning_vect', 'goodnight_vect', 'goodnite_vect', 'google_vect', 'gorgeous_vect', 'gossip_vect', 'got_vect', 'goto_vect', 'gotten_vect', 'govtinstituitions_vect', 'gr8_vect', 'grace_vect', 'gram_vect', 'grand_vect', 'granite_vect', 'gravity_vect', 'great_vect', 'green_vect', 'greet_vect', 'greetings_vect', 'grins_vect', 'grl_vect', 'ground_vect', 'group_vect', 'gt_vect', 'guaranteed_vect', 'gud_vect', 'gudnite_vect', 'guess_vect', 'guessing_vect', 'guide_vect', 'guilty_vect', 'guy_vect', 'guys_vect', 'gym_vect', 'ha_vect', 'haf_vect', 'haha_vect', 'hai_vect', 'hair_vect', 'haiz_vect', 'half_vect', 'halloween_vect', 'ham_vect', 'hand_vect', 'handed_vect', 'handle_vect', 'hands_vect', 'handset_vect', 'hanging_vect', 'happen_vect', 'happened_vect', 'happening_vect', 'happens_vect', 'happiness_vect', 'happy_vect', 'hard_vect', 'hardcore_vect', 'hardly_vect', 'harry_vect', 'hate_vect', 'hav_vect', 'havent_vect', 'haven\u00e5\u00f5t_vect', 'havin_vect', 'head_vect', 'headache_vect', 'headin_vect', 'heads_vect', 'hear_vect', 'heard_vect', 'heart_vect', 'heavy_vect', 'hee_vect', 'height_vect', 'held_vect', 'helen_vect', 'hell_vect', 'hella_vect', 'hello_vect', 'help_vect', 'help08712400602450p_vect', 'helpline_vect', 'hence_vect', 'henry_vect', 'heri_vect', 'herlove_vect', 'hes_vect', 'hex_vect', 'hey_vect', 'hgsuite3422lands_vect', 'hi_vect', 'hide_vect', 'high_vect', 'hill_vect', 'hint_vect', 'hip_vect', 'history_vect', 'hit_vect', 'hiya_vect', 'hl_vect', 'hlp_vect', 'hmm_vect', 'hmmm_vect', 'hmv_vect', 'ho_vect', 'hockey_vect', 'hol_vect', 'hold_vect', 'holder_vect', 'holding_vect', 'holiday_vect', 'holla_vect', 'hols_vect', 'holy_vect', 'home_vect', 'honey_vect', 'hook_vect', 'hop_vect', 'hope_vect', 'hoped_vect', 'hopefully_vect', 'hoping_vect', 'horny_vect', 'horo_vect', 'horrible_vect', 'hospital_vect', 'hospitals_vect', 'hostel_vect', 'hot_vect', 'hotel_vect', 'hotels_vect', 'hour_vect', 'hours_vect', 'house_vect', 'housemaid_vect', 'however_vect', 'hows_vect', 'howz_vect', 'hr_vect', 'hrishi_vect', 'hrs_vect', 'http_vect', 'hubby_vect', 'hug_vect', 'huh_vect', 'hun_vect', 'hungry_vect', 'hunny_vect', 'hurry_vect', 'hurt_vect', 'hurting_vect', 'hurts_vect', 'husband_vect', 'hv_vect', 'hw_vect', 'hyde_vect', 'iam_vect', 'ibhltd_vect', 'ibiza_vect', 'ic_vect', 'ice_vect', 'id_vect', 'idea_vect', 'ideal_vect', 'ideas_vect', 'identifier_vect', 'idiot_vect', 'idk_vect', 'ignore_vect', 'ikea_vect', 'il_vect', 'ill_vect', 'im_vect', 'imagine_vect', 'imma_vect', 'immediately_vect', 'imp_vect', 'important_vect', 'impossible_vect', 'improved_vect', 'in2_vect', 'inc_vect', 'inches_vect', 'incident_vect', 'include_vect', 'including_vect', 'inclusive_vect', 'inconsiderate_vect', 'indeed_vect', 'india_vect', 'indian_vect', 'indians_vect', 'indicate_vect', 'infections_vect', 'infernal_vect', 'info_vect', 'inform_vect', 'information_vect', 'informed_vect', 'innings_vect', 'insha_vect', 'inside_vect', 'instantly_vect', 'instead_vect', 'instructions_vect', 'insurance_vect', 'intelligent_vect', 'interest_vect', 'interested_vect', 'interesting_vect', 'interflora_vect', 'internet_vect', 'intro_vect', 'invest_vect', 'invite_vect', 'invited_vect', 'inviting_vect', 'iouri_vect', 'ip4_vect', 'ipod_vect', 'irritating_vect', 'iscoming_vect', 'ish_vect', 'island_vect', 'islands_vect', 'isnt_vect', 'issue_vect', 'issues_vect', 'it_vect', 'italian_vect', 'its_vect', 'itz_vect', 'it\u00e5\u00f5s_vect', 'ive_vect', 'iz_vect', 'izzit_vect', 'i\u00e5\u00f5m_vect', 'jacket_vect', 'jamster_vect', 'jan_vect', 'january_vect', 'jason_vect', 'java_vect', 'jay_vect', 'jazz_vect', 'jealous_vect', 'jeans_vect', 'jen_vect', 'jenny_vect', 'jess_vect', 'jesus_vect', 'jiayin_vect', 'jiu_vect', 'jo_vect', 'joanna_vect', 'job_vect', 'jogging_vect', 'john_vect', 'join_vect', 'joined_vect', 'joining_vect', 'joke_vect', 'jokes_vect', 'jokin_vect', 'joking_vect', 'jolly_vect', 'joy_vect', 'jsco_vect', 'jst_vect', 'juan_vect', 'juicy_vect', 'july_vect', 'june_vect', 'jus_vect', 'juz_vect', 'k52_vect', 'kadeem_vect', 'kaiez_vect', 'kallis_vect', 'kano_vect', 'kappa_vect', 'karaoke_vect', 'kate_vect', 'kay_vect', 'kb_vect', 'ke_vect', 'keep_vect', 'keeping_vect', 'keeps_vect', 'kent_vect', 'kept_vect', 'kerala_vect', 'key_vect', 'keys_vect', 'ki_vect', 'kick_vect', 'kid_vect', 'kidding_vect', 'kids_vect', 'kidz_vect', 'kind_ve", "instruction": "", "output": "" }, { "input": "ct', 'kinda_vect', 'kindly_vect', 'king_vect', 'kiss_vect', 'kisses_vect', 'kk_vect', 'knackered_vect', 'knew_vect', 'knock_vect', 'know_vect', 'knowing_vect', 'knows_vect', 'knw_vect', 'kz_vect', 'l8r_vect', 'la_vect', 'lab_vect', 'ladies_vect', 'lady_vect', 'lag_vect', 'laid_vect', 'land_vect', 'landline_vect', 'langport_vect', 'language_vect', 'laptop_vect', 'lar_vect', 'largest_vect', 'last_vect', 'late_vect', 'later_vect', 'latest_vect', 'latr_vect', 'laugh_vect', 'laughing_vect', 'law_vect', 'lazy_vect', 'ldn_vect', 'ldnw15h_vect', 'le_vect', 'lead_vect', 'learn_vect', 'least_vect', 'leave_vect', 'leaves_vect', 'leaving_vect', 'lect_vect', 'lecture_vect', 'left_vect', 'legal_vect', 'legs_vect', 'leh_vect', 'lei_vect', 'lem_vect', 'less_vect', 'lesson_vect', 'lessons_vect', 'let_vect', 'lets_vect', 'letter_vect', 'letters_vect', 'liao_vect', 'library_vect', 'lick_vect', 'licks_vect', 'lido_vect', 'lie_vect', 'lies_vect', 'life_vect', 'lifetime_vect', 'lift_vect', 'light_vect', 'lik_vect', 'like_vect', 'liked_vect', 'likely_vect', 'likes_vect', 'lil_vect', 'line_vect', 'linerental_vect', 'lines_vect', 'link_vect', 'lion_vect', 'lionm_vect', 'lionp_vect', 'lions_vect', 'lip_vect', 'list_vect', 'listen_vect', 'listening_vect', 'literally_vect', 'little_vect', 'live_vect', 'liverpool_vect', 'living_vect', 'lk_vect', 'll_vect', 'lmao_vect', 'lo_vect', 'loads_vect', 'loan_vect', 'loans_vect', 'local_vect', 'locations_vect', 'lock_vect', 'log_vect', 'login_vect', 'logo_vect', 'logopic_vect', 'lol_vect', 'london_vect', 'lonely_vect', 'long_vect', 'longer_vect', 'look_vect', 'lookatme_vect', 'looked_vect', 'lookin_vect', 'looking_vect', 'looks_vect', 'lor_vect', 'lose_vect', 'losing_vect', 'loss_vect', 'lost_vect', 'lot_vect', 'lotr_vect', 'lots_vect', 'lou_vect', 'loud_vect', 'lounge_vect', 'lousy_vect', 'lovable_vect', 'love_vect', 'loved_vect', 'lovely_vect', 'loveme_vect', 'lover_vect', 'loverboy_vect', 'lovers_vect', 'loves_vect', 'loving_vect', 'low_vect', 'lower_vect', 'loyal_vect', 'loyalty_vect', 'ls15hb_vect', 'lt_vect', 'ltd_vect', 'luck_vect', 'lucky_vect', 'lucy_vect', 'lunch_vect', 'luv_vect', 'lux_vect', 'luxury_vect', 'lyf_vect', 'lyfu_vect', 'lyk_vect', 'm227xy_vect', 'm26_vect', 'm263uz_vect', 'm8s_vect', 'mac_vect', 'machan_vect', 'macho_vect', 'mad_vect', 'madam_vect', 'made_vect', 'mag_vect', 'maga_vect', 'magical_vect', 'mah_vect', 'mail_vect', 'mailbox_vect', 'main_vect', 'maintain_vect', 'major_vect', 'make_vect', 'makes_vect', 'makin_vect', 'making_vect', 'malaria_vect', 'male_vect', 'mall_vect', 'man_vect', 'managed_vect', 'management_vect', 'many_vect', 'map_vect', 'march_vect', 'mark_vect', 'market_vect', 'marriage_vect', 'married_vect', 'marry_vect', 'masters_vect', 'match_vect', 'matches_vect', 'mate_vect', 'mates_vect', 'matrix3_vect', 'matter_vect', 'max10mins_vect', 'maximize_vect', 'max\u00e5_vect', 'may_vect', 'mayb_vect', 'maybe_vect', 'mca_vect', 'mcat_vect', 'meal_vect', 'mean_vect', 'meaning_vect', 'means_vect', 'meant_vect', 'meanwhile_vect', 'med_vect', 'medical_vect', 'medicine_vect', 'meds_vect', 'meet_vect', 'meetin_vect', 'meeting_vect', 'meh_vect', 'mei_vect', 'member_vect', 'members_vect', 'men_vect', 'menu_vect', 'merry_vect', 'mess_vect', 'message_vect', 'messaged_vect', 'messages_vect', 'messaging_vect', 'met_vect', 'mid_vect', 'middle_vect', 'midnight_vect', 'mids_vect', 'might_vect', 'miles_vect', 'milk_vect', 'min_vect', 'mind_vect', 'mine_vect', 'mini_vect', 'minimum_vect', 'minor_vect', 'mins_vect', 'minute_vect', 'minutes_vect', 'minuts_vect', 'miracle_vect', 'mis_vect', 'miserable_vect', 'miss_vect', 'missed_vect', 'missin_vect', 'missing_vect', 'mistake_vect', 'mistakes_vect', 'mite_vect', 'mm_vect', 'mmm_vect', 'mmmm_vect', 'mmmmmm_vect', 'mnths_vect', 'mo_vect', 'moan_vect', 'mob_vect', 'mobile_vect', 'mobiles_vect', 'mobilesdirect_vect', 'mobilesvary_vect', 'mobileupd8_vect', 'mobno_vect', 'moby_vect', 'mode_vect', 'model_vect', 'module_vect', 'modules_vect', 'moji_vect', 'mojibiola_vect', 'mokka_vect', 'mom_vect', 'moment_vect', 'moments_vect', 'moms_vect', 'mon_vect', 'monday_vect', 'money_vect', 'monkeys_vect', 'mono_vect', 'month_vect', 'monthly_vect', 'months_vect', 'mood_vect', 'moon_vect', 'moral_vect', 'morn_vect', 'morning_vect', 'mostly_vect', 'mother_vect', 'motorola_vect', 'mouth_vect', 'move_vect', 'moved_vect', 'movie_vect', 'movies_vect', 'moving_vect', 'mp3_vect', 'mr_vect', 'mrng_vect', 'mrt_vect', 'msg_vect', 'msgs_vect', 'mths_vect', 'mu_vect', 'much_vect', 'mum_vect', 'mummy_vect', 'murder_vect', 'murdered_vect', 'murderer_vect', 'music_vect', 'must_vect', 'muz_vect', 'na_vect', 'nag_vect', 'nah_vect', 'naked_vect', 'name_vect', 'name1_vect', 'name2_vect', 'named_vect', 'names_vect', 'nan_vect', 'nap_vect', 'nasdaq_vect', 'nat_vect', 'national_vect', 'natural_vect', 'nature_vect', 'naughty_vect', 'nb_vect', 'nd_vect', 'ne_vect', 'near_vect', 'nearly_vect', 'necessarily_vect', 'necklace_vect', 'ned_vect', 'need_vect', 'needed_vect', 'needs_vect', 'neither_vect', 'net_vect', 'netcollex_vect', 'network_vect', 'networks_vect', 'neva_vect', 'never_vect', 'new_vect', 'newest_vect', 'news_vect', 'next_vect', 'ni8_vect', 'nice_vect', 'nigeria_vect', 'night_vect', 'nights_vect', 'nimya_vect', 'nite_vect', 'no1_vect', 'nobody_vect', 'noe_vect', 'nokia_vect', 'nokias_vect', 'noline_vect', 'none_vect', 'noon_vect', 'nope_vect', 'norm_vect', 'norm150ptone_vect', 'normal_vect', 'normally_vect', 'northampton_vect', 'note_vect', 'nothin_vect', 'nothing_vect', 'notice_vect', 'noun_vect', 'nowadays_vect', 'nt_vect', 'ntt_vect', 'ntwk_vect', 'num_vect', 'number_vect', 'numbers_vect', 'nuther_vect', 'nvm_vect', 'nw_vect', 'nxt_vect', 'nyc_vect', 'nydc_vect', 'nyt_vect', 'o2_vect', 'obviously_vect', 'odi_vect', 'offer_vect', 'offers_vect', 'office_vect', 'official_vect', 'officially_vect', 'ofice_vect', 'often_vect', 'oh_vect', 'oi_vect', 'oic_vect', 'ok_vect', 'okay_vect', 'okey_vect', 'okie_vect', 'ola_vect', 'old_vect', 'omg_vect', 'omw_vect', 'one_vect', 'ones_vect', 'oni_vect', 'online_vect', 'onto_vect', 'onwards_vect', 'oooh_vect', 'oops_vect', 'open_vect', 'opening_vect', 'operator_vect', 'opinion_vect', 'opportunity_vect', 'opt_vect', 'option_vect', 'optout_vect', 'or2stoptxt_vect', 'orange_vect', 'oranges_vect', 'orchard_vect', 'order_vect', 'ordered_vect', 'oredi_vect', 'original_vect', 'oru_vect', 'os_vect', 'oso_vect', 'others_vect', 'otherwise_vect', 'otside_vect', 'outside_vect', 'outstanding_vect', 'outta_vect', 'ovulation_vect', 'oz_vect', 'pa_vect', 'pack_vect', 'package_vect', 'page_vect', 'pages_vect', 'paid_vect', 'pain_vect', 'painful_vect', 'painting_vect', 'panic_vect', 'paper_vect', 'papers_vect', 'paperwork_vect', 'parco_vect', 'parent_vect', 'parents_vect', 'paris_vect', 'park_vect', 'parked_vect', 'parking_vect', 'part_vect', 'partner_vect', 'partnership_vect', 'party_vect', 'pass_vect', 'passed_vect', 'password_vect', 'past_vect', 'pattern_vect', 'patty_vect', 'pay_vect', 'paying_vect', 'payment_vect', 'payoh_vect', 'pc_vect', 'peace_vect', 'pence_vect', 'people_vect', 'per_vect', 'perfect_vect', 'period_vect', 'person_vect', 'personal_vect', 'pete_vect', 'petey_vect', 'pg_vect', 'philosophy_vect', 'phoenix_vect', 'phone_vect', 'phones_vect', 'photo_vect', 'photos_vect', 'pic_vect', 'pick_vect', 'picked_vect', 'picking_vect', 'pics_vect', 'picsfree1_vect', 'picture_vect', 'pictures_vect', 'pie_vect', 'pieces_vect', 'pig_vect', 'pilates_vect', 'pin_vect', 'pink_vect', 'piss_vect', 'pissed_vect', 'pix_vect', 'pizza_vect', 'place_vect', 'places_vect', 'plan_vect', 'planned_vect', 'planning_vect', 'plans_vect', 'play_vect', 'played_vect', 'player_vect', 'players_vect', 'playing_vect', 'please_vect', 'pleased_vect', 'pleasure_vect', 'plenty_vect', 'pls_vect', 'plus_vect', 'plz_vect', 'pm_vect', 'po_vect', 'pobox_vect', 'pobox334_vect', 'pobox36504w45wq_vect', 'pobox45w2tg150p_vect', 'pobox84_vect', 'pod_vect', 'point_vect', 'points_vect', 'poker_vect', 'pole_vect', 'police_vect', 'politicians_vect', 'poly_vect', 'polyphonic_vect', 'polys_vect', 'pongal_vect', 'poor_vect', 'pop_vect', 'popped_vect', 'porn_vect', 'possession_vect', 'possible_vect', 'post_vect', 'postcard_vect', 'postcode_vect', 'posted_vect', 'posts_vect', 'potential_vect', 'potter_vect', 'pound_vect', 'pounds_vect', 'pouts_vect', 'power_vect', 'ppl_vect', 'pple_vect', 'ppm_vect', 'prabha_vect', 'practice_vect', 'practicing_vect', 'pray_vect', 'prefer_vect', 'premier_vect', 'prepare_vect', 'pres", "instruction": "", "output": "" }, { "input": "cription_vect', 'present_vect', 'press_vect', 'pretty_vect', 'prey_vect', 'price_vect', 'prince_vect', 'princess_vect', 'print_vect', 'privacy_vect', 'private_vect', 'prize_vect', 'prob_vect', 'probably_vect', 'problem_vect', 'problems_vect', 'process_vect', 'processed_vect', 'prof_vect', 'profit_vect', 'program_vect', 'project_vect', 'prolly_vect', 'promise_vect', 'promises_vect', 'promo_vect', 'proof_vect', 'properly_vect', 'prospects_vect', 'provided_vect', 'ps_vect', 'ptbo_vect', 'pub_vect', 'pull_vect', 'purchase_vect', 'purity_vect', 'purpose_vect', 'push_vect', 'pushes_vect', 'pussy_vect', 'put_vect', 'puttin_vect', 'putting_vect', 'qatar_vect', 'quality_vect', 'queen_vect', 'ques_vect', 'question_vect', 'questions_vect', 'quick_vect', 'quickly_vect', 'quiet_vect', 'quit_vect', 'quite_vect', 'quiz_vect', 'quote_vect', 'quoting_vect', 'racing_vect', 'radio_vect', 'railway_vect', 'rain_vect', 'raining_vect', 'raise_vect', 'rakhesh_vect', 'rally_vect', 'ran_vect', 'random_vect', 'randomly_vect', 'randy_vect', 'rang_vect', 'range_vect', 'ranjith_vect', 'rate_vect', 'rates_vect', 'rather_vect', 'rays_vect', 'rcvd_vect', 'rd_vect', 're_vect', 'reach_vect', 'reached_vect', 'reaching_vect', 'reaction_vect', 'read_vect', 'readers_vect', 'reading_vect', 'ready_vect', 'real_vect', 'realise_vect', 'reality_vect', 'realized_vect', 'really_vect', 'realy_vect', 'reason_vect', 'reasonable_vect', 'reasons_vect', 'reboot_vect', 'recd_vect', 'receipt_vect', 'receive_vect', 'received_vect', 'receiving_vect', 'recent_vect', 'recently_vect', 'recession_vect', 'record_vect', 'records_vect', 'recovery_vect', 'red_vect', 'ref_vect', 'reference_vect', 'reg_vect', 'regards_vect', 'register_vect', 'registered_vect', 'regret_vect', 'regular_vect', 'relation_vect', 'relax_vect', 'released_vect', 'rem_vect', 'remain_vect', 'remains_vect', 'remember_vect', 'remembered_vect', 'remembr_vect', 'remind_vect', 'reminder_vect', 'remove_vect', 'rent_vect', 'rental_vect', 'rentl_vect', 'repair_vect', 'repeat_vect', 'replied_vect', 'reply_vect', 'replying_vect', 'report_vect', 'representative_vect', 'request_vect', 'requests_vect', 'research_vect', 'resend_vect', 'respect_vect', 'respond_vect', 'responding_vect', 'response_vect', 'responsibility_vect', 'rest_vect', 'restaurant_vect', 'result_vect', 'results_vect', 'retrieve_vect', 'return_vect', 'returned_vect', 'returns_vect', 'reveal_vect', 'revealed_vect', 'review_vect', 'revision_vect', 'reward_vect', 'rhythm_vect', 'rice_vect', 'rich_vect', 'ride_vect', 'right_vect', 'rights_vect', 'ring_vect', 'ringtone_vect', 'ringtones_vect', 'rite_vect', 'river_vect', 'road_vect', 'roads_vect', 'roast_vect', 'rock_vect', 'rocks_vect', 'rofl_vect', 'roger_vect', 'role_vect', 'ron_vect', 'room_vect', 'roommate_vect', 'roommates_vect', 'rooms_vect', 'rose_vect', 'round_vect', 'row_vect', 'roww1j6hl_vect', 'roww1jhl_vect', 'royal_vect', 'rply_vect', 'rs_vect', 'rstm_vect', 'ru_vect', 'rub_vect', 'rude_vect', 'rule_vect', 'run_vect', 'running_vect', 'runs_vect', 'rush_vect', 'sacrifice_vect', 'sad_vect', 'sae_vect', 'safe_vect', 'said_vect', 'salam_vect', 'salary_vect', 'sale_vect', 'salon_vect', 'sam_vect', 'santa_vect', 'sar_vect', 'sarasota_vect', 'sarcastic_vect', 'sary_vect', 'sat_vect', 'sathya_vect', 'saturday_vect', 'savamob_vect', 'save_vect', 'saved_vect', 'saw_vect', 'say_vect', 'saying_vect', 'says_vect', 'scared_vect', 'scary_vect', 'sch_vect', 'schedule_vect', 'school_vect', 'schools_vect', 'science_vect', 'scold_vect', 'score_vect', 'scores_vect', 'scotland_vect', 'scream_vect', 'screaming_vect', 'scrounge_vect', 'se_vect', 'sea_vect', 'search_vect', 'searching_vect', 'season_vect', 'seat_vect', 'sec_vect', 'second_vect', 'seconds_vect', 'secret_vect', 'secretary_vect', 'secs_vect', 'sed_vect', 'see_vect', 'seeing_vect', 'seem_vect', 'seemed_vect', 'seems_vect', 'seen_vect', 'selected_vect', 'selection_vect', 'self_vect', 'sell_vect', 'selling_vect', 'sells_vect', 'sem_vect', 'semester_vect', 'sen_vect', 'send_vect', 'sender_vect', 'sending_vect', 'sense_vect', 'sent_vect', 'sentence_vect', 'sept_vect', 'series_vect', 'serious_vect', 'seriously_vect', 'service_vect', 'services_vect', 'serving_vect', 'set_vect', 'setting_vect', 'settings_vect', 'settle_vect', 'settled_vect', 'seven_vect', 'several_vect', 'sex_vect', 'sexy_vect', 'sh_vect', 'sha_vect', 'shall_vect', 'share_vect', 'shd_vect', 'sheets_vect', 'shes_vect', 'shesil_vect', 'shining_vect', 'ship_vect', 'shipping_vect', 'shirt_vect', 'shirts_vect', 'shit_vect', 'shld_vect', 'shocking_vect', 'shoot_vect', 'shop_vect', 'shoppin_vect', 'shopping_vect', 'short_vect', 'shorter_vect', 'shortly_vect', 'shot_vect', 'shoving_vect', 'show_vect', 'shower_vect', 'showing_vect', 'shows_vect', 'shu_vect', 'shuhui_vect', 'shy_vect', 'si_vect', 'sick_vect', 'side_vect', 'sighs_vect', 'sight_vect', 'sign_vect', 'signing_vect', 'silence_vect', 'silent_vect', 'silver_vect', 'sim_vect', 'simple_vect', 'simply_vect', 'since_vect', 'sing_vect', 'singing_vect', 'single_vect', 'singles_vect', 'sipix_vect', 'sir_vect', 'sis_vect', 'sister_vect', 'sit_vect', 'site_vect', 'sitting_vect', 'situation_vect', 'siva_vect', 'six_vect', 'size_vect', 'sk3_vect', 'sk38xh_vect', 'skilgme_vect', 'skip_vect', 'sky_vect', 'skype_vect', 'skyped_vect', 'slap_vect', 'slave_vect', 'sleep_vect', 'sleepin_vect', 'sleeping_vect', 'sleepy_vect', 'slept_vect', 'slice_vect', 'slide_vect', 'slightly_vect', 'slip_vect', 'slippers_vect', 'slo_vect', 'slots_vect', 'slow_vect', 'slowly_vect', 'small_vect', 'smashed_vect', 'smile_vect', 'smiles_vect', 'smiling_vect', 'smoke_vect', 'smoking_vect', 'sms_vect', 'smth_vect', 'sn_vect', 'snake_vect', 'snow_vect', 'social_vect', 'sofa_vect', 'soft_vect', 'software_vect', 'sol_vect', 'some1_vect', 'somebody_vect', 'someone_vect', 'somethin_vect', 'something_vect', 'sometimes_vect', 'somewhere_vect', 'song_vect', 'songs_vect', 'sony_vect', 'sonyericsson_vect', 'soon_vect', 'sooner_vect', 'sore_vect', 'sorry_vect', 'sort_vect', 'sorting_vect', 'sound_vect', 'sounds_vect', 'south_vect', 'sp_vect', 'space_vect', 'spanish_vect', 'speak_vect', 'speaking_vect', 'special_vect', 'specialcall_vect', 'specially_vect', 'speed_vect', 'spend_vect', 'spending_vect', 'spent_vect', 'spk_vect', 'spoke_vect', 'spoken_vect', 'spook_vect', 'sport_vect', 'sports_vect', 'spree_vect', 'spring_vect', 'sptv_vect', 'sry_vect', 'st_vect', 'staff_vect', 'stamps_vect', 'stand_vect', 'standard_vect', 'standing_vect', 'star_vect', 'staring_vect', 'start_vect', 'started_vect', 'starting_vect', 'starts_vect', 'starwars3_vect', 'statement_vect', 'station_vect', 'stay_vect', 'stayed_vect', 'staying_vect', 'std_vect', 'steam_vect', 'step_vect', 'steve_vect', 'stick_vect', 'sticky_vect', 'still_vect', 'stock_vect', 'stockport_vect', 'stomach_vect', 'stomps_vect', 'stones_vect', 'stop_vect', 'stopped_vect', 'stops_vect', 'store_vect', 'stores_vect', 'story_vect', 'str_vect', 'straight_vect', 'stranger_vect', 'street_vect', 'stress_vect', 'strike_vect', 'strong_vect', 'strongbuy_vect', 'stuck_vect', 'student_vect', 'study_vect', 'studying_vect', 'stuff_vect', 'stupid_vect', 'style_vect', 'stylish_vect', 'sub_vect', 'subpoly_vect', 'subs_vect', 'subscribe6gbpmnth_vect', 'subscribed_vect', 'subscriber_vect', 'subscription_vect', 'success_vect', 'successful_vect', 'successfully_vect', 'sucks_vect', 'sue_vect', 'sufficient_vect', 'suggest_vect', 'suite_vect', 'suits_vect', 'sum1_vect', 'summer_vect', 'sun_vect', 'sunday_vect', 'sunlight_vect', 'sunny_vect', 'sunshine_vect', 'suntec_vect', 'sup_vect', 'super_vect', 'superb_vect', 'superior_vect', 'supervisor_vect', 'supply_vect', 'support_vect', 'suppose_vect', 'supposed_vect', 'suprman_vect', 'sura_vect', 'sure_vect', 'surely_vect', 'surfing_vect', 'surprise_vect', 'surprised_vect', 'survey_vect', 'sux_vect', 'suzy_vect', 'sw7_vect', 'sw73ss_vect', 'sweet_vect', 'swing_vect', 'system_vect', 'ta_vect', 'tablets_vect', 'tahan_vect', 'take_vect', 'taken_vect', 'takes_vect', 'takin_vect', 'taking_vect', 'talent_vect', 'talk_vect', 'talking_vect', 'tampa_vect', 'tape_vect', 'tariffs_vect', 'tat_vect', 'taunton_vect', 'taylor_vect', 'tb_vect', 'tc_vect', 'tcrw1_vect', 'tcs_vect', 'tea_vect', 'teach_vect', 'teacher_vect', 'teaches_vect', 'team_vect', 'tear_vect', 'tease_vect', 'teasing_vect', 'tech_vect', 'technical_vect', 'tee_vect', 'teeth_vect', 'tel_vect', 'telephone_vect', 'tell_vect', 'telling_vect', 'tells_vect', 'telugu_vect', 'temple_vect', 'ten_vect', 'tenants_vect', 'tenerife_vect', 'tension_vect', 'term_vect', 'terms_vect', 'terrible_vect', 'test_vect', 'testing_vect', 'text_vect', 'texted_vect', 'texting_vect', 'textoperator_vect', 'texts_vect', 'th_vect', 'thangam_vect', 'thank_vect', 'thanks_vect', 'thanksgiving_vect', 'thanx_vect', 'that_vect', 'thats_vect', 'that\u00e5\u00f5s_vect', 'the_vect', 'theatre_vect', 'themob_", "instruction": "", "output": "" }, { "input": "vect', 'theory_vect', 'thesis_vect', 'thgt_vect', 'thing_vect', 'things_vect', 'think_vect', 'thinkin_vect', 'thinking_vect', 'thinks_vect', 'thk_vect', 'thnk_vect', 'tho_vect', 'though_vect', 'thought_vect', 'three_vect', 'throat_vect', 'throw_vect', 'thru_vect', 'tht_vect', 'thts_vect', 'thurs_vect', 'thursday_vect', 'tick_vect', 'ticket_vect', 'tickets_vect', 'tight_vect', 'tihs_vect', 'til_vect', 'till_vect', 'time_vect', 'times_vect', 'timing_vect', 'tired_vect', 'tirunelvali_vect', 'tirupur_vect', 'tissco_vect', 'tkts_vect', 'tm_vect', 'tming_vect', 'tmobile_vect', 'tmr_vect', 'tncs_vect', 'toa_vect', 'toclaim_vect', 'today_vect', 'todays_vect', 'tog_vect', 'together_vect', 'tok_vect', 'told_vect', 'tomarrow_vect', 'tomo_vect', 'tomorrow_vect', 'tone_vect', 'tones_vect', 'tones2youcouk_vect', 'tonight_vect', 'tonite_vect', 'took_vect', 'tool_vect', 'tooo_vect', 'toot_vect', 'top_vect', 'topic_vect', 'torch_vect', 'toshiba_vect', 'tot_vect', 'total_vect', 'totally_vect', 'touch_vect', 'tough_vect', 'tour_vect', 'towards_vect', 'town_vect', 'track_vect', 'trade_vect', 'traffic_vect', 'train_vect', 'training_vect', 'transaction_vect', 'transfer_vect', 'transport_vect', 'travel_vect', 'treat_vect', 'treated_vect', 'tried_vect', 'trip_vect', 'trips_vect', 'trouble_vect', 'true_vect', 'truffles_vect', 'truly_vect', 'trust_vect', 'truth_vect', 'try_vect', 'trying_vect', 'ts_vect', 'tscs_vect', 'tscs087147403231winawk_vect', 'tt_vect', 'ttyl_vect', 'tues_vect', 'tuesday_vect', 'tuition_vect', 'turn_vect', 'turning_vect', 'turns_vect', 'tv_vect', 'twelve_vect', 'twice_vect', 'two_vect', 'txt_vect', 'txtauction_vect', 'txtin_vect', 'txting_vect', 'txtno_vect', 'txts_vect', 'txtstop_vect', 'tyler_vect', 'type_vect', 'tyrone_vect', 'u4_vect', 'ubi_vect', 'ufind_vect', 'ugh_vect', 'uh_vect', 'uk_vect', 'uks_vect', 'ultimatum_vect', 'umma_vect', 'unable_vect', 'uncle_vect', 'understand_vect', 'understanding_vect', 'understood_vect', 'underwear_vect', 'unemployed_vect', 'uni_vect', 'unique_vect', 'university_vect', 'unless_vect', 'unlimited_vect', 'unnecessarily_vect', 'unredeemed_vect', 'unsold_vect', 'unsub_vect', 'unsubscribe_vect', 'upd8_vect', 'update_vect', 'updatenow_vect', 'upgrade_vect', 'upload_vect', 'upset_vect', 'upstairs_vect', 'ur_vect', 'ure_vect', 'urgent_vect', 'urgnt_vect', 'url_vect', 'urn_vect', 'urself_vect', 'us_vect', 'usb_vect', 'use_vect', 'used_vect', 'user_vect', 'usf_vect', 'using_vect', 'usual_vect', 'usually_vect', 'vale_vect', 'valentine_vect', 'valentines_vect', 'valid_vect', 'valid12hrs_vect', 'valuable_vect', 'value_vect', 'valued_vect', 'vary_vect', 've_vect', 'vegas_vect', 'verify_vect', 'version_vect', 'via_vect', 'vid_vect', 'video_vect', 'videochat_vect', 'videophones_vect', 'vijay_vect', 'vikky_vect', 'village_vect', 'violated_vect', 'violence_vect', 'vip_vect', 'virgin_vect', 'visit_vect', 'vivek_vect', 'vl_vect', 'voda_vect', 'vodafone_vect', 'vodka_vect', 'voice_vect', 'voicemail_vect', 'vomit_vect', 'vote_vect', 'voucher_vect', 'vouchers_vect', 'vry_vect', 'vth_vect', 'w45wq_vect', 'wa_vect', 'wah_vect', 'wait_vect', 'waited_vect', 'waitin_vect', 'waiting_vect', 'wake_vect', 'waking_vect', 'wales_vect', 'walk_vect', 'walked_vect', 'walking_vect', 'walmart_vect', 'wan_vect', 'wana_vect', 'want_vect', 'wanted_vect', 'wanting_vect', 'wants_vect', 'wap_vect', 'warm_vect', 'warner_vect', 'waste_vect', 'wasted_vect', 'wat_vect', 'watch_vect', 'watching_vect', 'water_vect', 'wats_vect', 'way_vect', 'wc1n3xx_vect', 'we_vect', 'weak_vect', 'wear_vect', 'wearing_vect', 'weather_vect', 'web_vect', 'website_vect', 'wed_vect', 'wedding_vect', 'wednesday_vect', 'wee_vect', 'weed_vect', 'week_vect', 'weekend_vect', 'weekends_vect', 'weekly_vect', 'weeks_vect', 'weigh_vect', 'weight_vect', 'weird_vect', 'welcome_vect', 'well_vect', 'welp_vect', 'wen_vect', 'went_vect', 'west_vect', 'wet_vect', 'what_vect', 'whatever_vect', 'whats_vect', 'whenever_vect', 'whenevr_vect', 'wherever_vect', 'whether_vect', 'white_vect', 'whn_vect', 'whole_vect', 'whos_vect', 'whose_vect', 'wid_vect', 'widelivecomindex_vect', 'wif_vect', 'wife_vect', 'wil_vect', 'willing_vect', 'win_vect', 'wind_vect', 'wine_vect', 'winner_vect', 'winning_vect', 'wins_vect', 'wipro_vect', 'wisdom_vect', 'wise_vect', 'wish_vect', 'wishes_vect', 'wishing_vect', 'wit_vect', 'within_vect', 'without_vect', 'wiv_vect', 'wk_vect', 'wkend_vect', 'wkg_vect', 'wkly_vect', 'wks_vect', 'wld_vect', 'wml_vect', 'wn_vect', 'wnt_vect', 'wo_vect', 'woke_vect', 'woken_vect', 'woman_vect', 'women_vect', 'wonder_vect', 'wonderful_vect', 'wondering_vect', 'wont_vect', 'woot_vect', 'word_vect', 'words_vect', 'work_vect', 'workin_vect', 'working_vect', 'works_vect', 'world_vect', 'worried_vect', 'worries_vect', 'worry_vect', 'worse_vect', 'worst_vect', 'worth_vect', 'wot_vect', 'would_vect', 'wow_vect', 'write_vect', 'wrong_vect', 'wtf_vect', 'wud_vect', 'wuld_vect', 'wun_vect', 'www4tcbiz_vect', 'wwwcomuknet_vect', 'wwwetlpcoukexpressoffer_vect', 'wwwgetzedcouk_vect', 'wwwldewcom_vect', 'wwwldewcom1win150ppmx3age16_vect', 'wwwmovietriviatv_vect', 'wwwringtonescouk_vect', 'wwwsmsconet_vect', 'wwwtxttowincouk_vect', 'wwwurawinnercom_vect', 'wylie_vect', 'xchat_vect', 'xmas_vect', 'xuhui_vect', 'xx_vect', 'xxx_vect', 'xxxx_vect', 'xxxxx_vect', 'xy_vect', 'ya_vect', 'yahoo_vect', 'yan_vect', 'yar_vect', 'yay_vect', 'yck_vect', 'yeah_vect', 'year_vect', 'years_vect', 'yelling_vect', 'yellow_vect', 'yep_vect', 'yes_vect', 'yest_vect', 'yesterday_vect', 'yet_vect', 'yetunde_vect', 'yijue_vect', 'ym_vect', 'yo_vect', 'yoga_vect', 'yogasana_vect', 'yor_vect', 'you_vect', 'yr_vect', 'yrs_vect', 'yummy_vect', 'yun_vect', 'yuo_vect', 'yup_vect', 'zed_vect', 'zindgi_vect', '\u00ec\u00ef_vect', '\u00fb\u00f2_vect']}, 'training': {'algo': 'Logistic Regression', 'model_file': 'AI0110_1.sav'}}\n deployer = get_deployer('classification',params=config)\n deployer.run( ) '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\n\nTAB_CHAR = ' ' * 4\n\ndef import_modules(importer, modules_list):\n for module in modules_list:\n mod_from = module.get('mod_from',None)\n mod_as = module.get('mod_as',None)\n importer.addModule(module['module'], mod_from=mod_from, mod_as=mod_as)\n \n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport platform\nimport sys\nimport subprocess\nimport glob\nimport shutil\nimport time\nfrom aion_deployment.EncryptPythonSourceCode import encrypt_files\nimport json\ndef encrypt(alldirs):\n\tfor dir in alldirs:\n\t\ttry:\n\t\t\tencrypt_files(dir)\n\t\texcept Exception as error_obj:\n\t\t\tprint(\"Exception in encrypting\", error_obj)\n\t\tprint(\"-\"*50)\ndef replace_by_compressed(alldirs):\n\tfor dir in alldirs:\n\t\ttry:\n\t\t\t#print(\"Processing dir\", dir)\n\t\t\tfiles = [f for f in glob.glob(dir + \"/*.py\")]\n\t\t\tsecure_path = os.path.join(dir, 'SecuredScripts')\n\t\t\ttime.sleep(6)\n\t\t\tfor file in files:\n\t\t\t\ttry:\n\t\t\t\t\tfilename_w_ext = os.path.basename(file)\n\t\t\t\t\tfilename, file_extension = os.path.splitext(filename_w_ext)\n\t\t\t\t\tif filename == \"__init__\":\n\t\t\t\t\t\tcontinue\t\n\t\t\t\t\t#print(\"Processing file\", file)\n\t\t\t\t\tfile_folder_path = os.path.join(secure_path, filename, 'dist')\n\t\t\t\t\tcompressed_file_path = os.path.join(file_folder_path, filename+'_compressed.py')\n\t\t\t\t\tshutil.copy(compressed_file_path, dir)\n\t\t\t\t\tos.remove(file)\n\t\t\t\t\tnew_compressed_file_path = os.path.join(dir, filename+'_compressed.py')\n\t\t\t\t\ttarget_file_path = os.path.join(dir, filename_w_ext)\n\t\t\t\t\tos.rename(new_compressed_file_path, target_file_path)\n\t\t\t\t\tif filename == 'aion_prediction':\n\t\t\t\t\t\tshutil.copytree(os.path.join(file_folder_path, 'pytransform'), os.path.join(dir, 'pytransform'))\n\t\t\t\texcept Exception as error_obj:\n\t\t\t\t\tprint(\"Exception in file \", error_obj)\n\t\t\tshutil.rmtree(secure_path)\n\t\texcept Exception as error_obj:\n\t\t\tprint(\"Exception in dir \", error_obj)\n\ndef start_Obfuscate(path):\n\tproject_path = path\n\tsubdirs = [dI for dI in os.listdir(project_path) if os.path.isdir(os.path.join(project_path,dI))]\n\talldirs = [\n\t\tproject_path,\n\t]\n\tfor subdir in subdirs:\n\t\tif(subdir != 'pytransform'):\n\t\t\talldirs.append(os.path.join(project_path, subdir))\n\tencrypt(alldirs)\n\treplace_by_compressed(alldirs)\n\t\nif __name__==\"__main__\":\n\tproject_path = sys.argv[1]\n\tprint(\"project_path\", project_path)\n\tsubdirs = [dI for dI in os.listdir(project_path) if os.path.isdir(os.path.join(project_path,dI))]\n\talldirs = [\n\t\tproject_path,\n\t]\n\tfor subdir in subdirs:\n\t\talldirs.append(os.", "instruction": "", "output": "" }, { "input": "path.join(project_path, subdir))\n\tencrypt(alldirs)\n\tprint(\"*\"*50)\n\treplace_by_compressed(alldirs)\n\n\n# python eion_compress.py \"C:\\\\Users\\\\ashwani.s\\\\Desktop\\\\22April\\\\22April\\\\Mohita\" \"C:\\\\Users\\\\ashwani.s\\\\Desktop\\\\eion\\\\eion\" > logfile.log\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os,sys\nimport platform\nimport json\nimport shutil\nimport logging\nfrom pathlib import Path\nfrom prediction_package import production \nfrom prediction_package import prediction_transformation as cs\n\nclass DeploymentManager:\n def __init__(self):\n self.requirementfile=''\n self.modelfile=''\n self.s2i_environmentfile=''\n self.selectorfile=''\n self.profilerfile=''\n self.readmepackagename=''\n self.pythonpackage=''\n self.log = logging.getLogger('eion')\n\n def include_import_file(self,learner_type,method,scoreParam,model_type,model):\n if((learner_type == 'DL') or (learner_type == 'TextDL')):\n self.modelfile += 'from tensorflow.keras.models import load_model'\n self.modelfile += '\\\\n'\n self.modelfile += 'from tensorflow.keras import backend as K'\n self.modelfile += '\\\\n'\n self.modelfile += 'import tensorflow as tf'\n self.modelfile += '\\\\n'\n if (learner_type == 'ML' and model_type.lower()=='anomaly_detection' and model.lower() == 'autoencoder'):\n self.modelfile += 'import joblib'\n self.modelfile += '\\\\n'\n self.modelfile += 'import os'\n self.modelfile += '\\\\n'\n self.modelfile += 'import pandas as pd'\n self.modelfile += '\\\\n'\n self.modelfile += 'import numpy as np'\n self.modelfile += '\\\\n'\n self.modelfile += 'from pathlib import Path'\n self.modelfile += '\\\\n'\n self.modelfile += 'import tensorflow as tf'\n self.modelfile += '\\\\n'\n self.modelfile += 'from keras.models import load_model'\n self.modelfile += '\\\\n'\n self.modelfile += 'import warnings'\n self.modelfile += '\\\\n'\n self.modelfile += 'from sklearn.preprocessing import StandardScaler'\n self.modelfile += '\\\\n'\n self.modelfile += 'warnings.filterwarnings(\"ignore\")'\n self.modelfile += '\\\\n'\n if(learner_type == 'ImageClassification'):\n self.modelfile += 'import os'\n self.modelfile += '\\\\n'\n self.modelfile += 'from tensorflow.keras.models import Sequential'\n self.modelfile += '\\\\n'\n self.modelfile += 'from tensorflow.keras.layers import Dense, Dropout, Flatten'\n self.modelfile += '\\\\n'\n self.modelfile += 'from tensorflow.keras.preprocessing import image'\n self.modelfile += '\\\\n'\n self.modelfile += 'import numpy as np'\n self.modelfile += '\\\\n'\n self.modelfile += 'import tensorflow as tf'\n self.modelfile += '\\\\n'\n self.modelfile += 'from tensorflow.keras.layers import Input'\n self.modelfile += '\\\\n'\n self.modelfile += 'from tensorflow.keras.models import Model'\n self.modelfile += '\\\\n'\n self.modelfile += 'from tensorflow.keras.optimizers import Adam'\n self.modelfile += '\\\\n'\n self.modelfile += 'import cv2'\n self.modelfile += '\\\\n'\n if(learner_type == 'objectDetection'):\n self.modelfile += 'import os\\\\n'\n self.modelfile += 'from object_detection.utils import label_map_util\\\\n'\n self.modelfile += 'from object_detection.utils import config_util\\\\n'\n self.modelfile += 'from object_detection.utils import visualization_utils as viz_utils\\\\n'\n self.modelfile += 'from object_detection.builders import model_builder\\\\n'\n self.modelfile += 'import tensorflow as tf\\\\n'\n self.modelfile += 'import numpy as np\\\\n'\n self.modelfile += 'from PIL import Image\\\\n'\n self.modelfile += 'import matplotlib.pyplot as plt\\\\n'\n self.modelfile += 'import pandas as pd\\\\n'\n self.modelfile += 'from pathlib import Path\\\\n'\n if(learner_type == 'Text Similarity'):\n self.modelfile += 'from tensorflow.keras.models import load_model'\n self.modelfile += '\\\\n'\n self.modelfile += 'from tensorflow.keras import backend as K'\n self.modelfile += '\\\\n'\n self.modelfile += 'from tensorflow.keras.preprocessing.sequence import pad_sequences'\n self.modelfile += '\\\\n'\n self.modelfile += 'from tensorflow.keras.preprocessing.text import Tokenizer'\n self.modelfile += '\\\\n'\n self.modelfile += 'import tensorflow as tf'\n self.modelfile += '\\\\n'\n if(model == 'Neural Architecture Search'):\n self.modelfile += 'from tensorflow.keras.models import load_model'\n self.modelfile += '\\\\n'\n self.modelfile += 'from tensorflow.keras import backend as K'\n self.modelfile += '\\\\n'\n self.modelfile += 'import tensorflow as tf'\n self.modelfile += '\\\\n'\n self.modelfile += 'import joblib'\n self.modelfile += '\\\\n'\n self.modelfile += 'import os'\n self.modelfile += '\\\\n'\n self.modelfile += 'import pandas as pd'\n self.modelfile += '\\\\n'\n self.modelfile += 'from sklearn.decomposition import LatentDirichletAllocation\\\\n'\n self.modelfile += 'import numpy as np\\\\n'\n self.modelfile += 'from pathlib import Path\\\\n'\n if model.lower() == 'deep q network' or model.lower() == 'dueling deep q network':\n self.modelfile += 'from tensorflow import constant'\n self.modelfile += '\\\\n'\n self.modelfile += 'from tf_agents.trajectories import time_step'\n self.modelfile += '\\\\n'\n self.requirementfile += 'tensorflow==2.5.0'\n if model.lower() == 'lstm' or model.lower() == 'mlp':\n self.modelfile += 'from tensorflow.keras.models import load_model'\n self.modelfile += '\\\\n'\n self.requirementfile += 'tensorflow==2.5.0'\n if(learner_type == 'Text Similarity'):\n self.modelfile += 'def cosine_distance(vests):'\n self.modelfile += '\\\\n';\n self.modelfile += ' x, y = vests'\n self.modelfile += '\\\\n';\n self.modelfile += ' x = K.l2_normalize(x, axis=-1)'\n self.modelfile += '\\\\n';\n self.modelfile += ' y = K.l2_normalize(y, axis=-1)'\n self.modelfile += '\\\\n';\n self.modelfile += ' return -K.mean(x * y, axis=-1, keepdims=True)'\n self.modelfile += '\\\\n';\n self.modelfile += 'def cos_dist_output_shape(shapes):'\n self.modelfile += '\\\\n';\n self.modelfile += ' shape1, shape2 = shapes'\n self.modelfile += '\\\\n';\n self.modelfile += ' return (shape1[0],1)'\n self.modelfile += '\\\\n';\n\n if(learner_type == 'TextDL' or learner_type == 'DL'):\n if(scoreParam.lower() == 'recall' or scoreParam.lower() == 'f1_score'):\n self.modelfile += 'def recall_m(y_true, y_pred):'\n self.modelfile += '\\\\n';\n self.modelfile += ' true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))'\n self.modelfile += '\\\\n';\n self.modelfile += ' possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))'\n self.modelfile += '\\\\n';\n self.modelfile += ' recall = true_positives / (possible_positives + K.epsilon())'\n self.modelfile += '\\\\n';\n self.modelfile += ' return recall'\n self.modelfile += '\\\\n';\n if(scoreParam.lower() == 'precision' or scoreParam.lower() == 'f1_score'):\n self.modelfile += 'def precision_m(y_true, y_pred):'\n self.modelfile += '\\\\n';\n self.modelfile += ' true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))'\n self.modelfile += '\\\\n';\n self.modelfile += ' predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))'\n self.modelfile += '\\\\n';\n self.modelfile += ' precision = true_positives / (predicted_positives + K.epsilon())'\n self.modelfile += '\\\\n';\n self.modelfile += ' return precision'\n self.modelfile += '\\\\n';\n if(scoreParam.lower() == 'f1_score'):\n self.modelfile += 'def f1_m(y_true, y_pred):'\n self.modelfile += '\\\\n';\n self.modelfile += ' precision = precision_m(y_true, y_pred)'\n self.modelfile += '\\\\n';\n self.modelfile += ' recall = recall_m(y_true, y_pred)'\n self.modelfile += '\\\\n';\n self.modelfile += ' return 2*((precision*recall)/(precision+recall+K.epsilon()))'\n self.modelfile += '\\\\n';\n if(scoreParam.lower() == 'rmse'):\n self.modelfile += 'def rmse_m(y_true, y_pred):'\n self.modelfile += '\\\\n';\n self.modelfile += ' return K.sqrt(K.mean(K.square(y_pred - y_true), axis=-1))'\n self.modelfile += '\\\\n';\n if(scoreParam.lower() =='r2'):\n self.modelfile += 'def r_square(y_true, y_pred):'\n self.modelfile += '\\\\n';\n self.modelfile += ' SS_res = K.sum(K.square(y_true-y_pred))'\n self.modelfile += '\\\\n';\n self.modelfile += ' SS_tot = K.sum(K.square(y_true-K.mean(y_true)))'\n self.modelfile += '\\\\n';\n self.modelfile += ' return (1 - SS_res/(SS_tot+K.epsilon()))'\n self.modelfile += '\\\\n';\n if(learner_type.lower() in ['similarityidentification','contextualsearch']):\n self.modelfile += 'from pathlib import Path\\\\n'\n if model_type == 'BM25':\n self.modelfile += 'from rank_bm25 import BM25Okapi\\\\n'\n elif scoreParam == 'VectorDB Cosine':\n self.modelfile += 'import chromadb\\\\n'\n else:\n self.modelfile += 'from sklearn.metrics.pairwise import cosine_similarity\\\\n'\n\n self.pythonpackage += '========== Python Packags Requires ========='\n self.pythonpackage += '\\\\n'\n self.pythonpackage += 'scikit-learn'\n self.pythonpackage += '\\\\n'\n self.pythonpackage += 'scipy'\n self.pythonpackage += '\\\\n'\n self.pythonpackage += 'numpy'\n self.pythonpackage += '\\\\n'\n if((learner_type == 'DL') or (learner_type =='TextDL')):\n self.modelfile += 'import numpy as np'\n self.modelfile += '\\\\n'\n self.requirementfile += 'scikit-learn==0.21.3'\n self.requirementfile += '\\\\n'\n self.requirementfile += 'scipy==1.3.3'\n self.requirementfile += '\\\\n'\n self.requirementfile += 'numpy==1.17.4'\n self.requirementfile += '\\\\n'\n\n if(learner_type == 'TextML'):\n self.requirementfile += 'spacy==2.2.3'\n self.requirementfile += '\\\\n'\n self.requirementfile += 'https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.2.0/en_core_web_sm-2.2.0.tar.gz'\n self.requirementfile += '\\\\n'\n\n if(learner_type == 'DL' or learner_type == 'TextDL'):\n self.requirementfile += 'keras==2.3.1'\n self.requirementfile += '\\\\n'\n self.requirementfile += 'tensorflow==2.0.0b1'\n self.requirementfile += '\\\\n'\n\n if(learner_type == 'RecommenderSystem'):\n self.requirementfile += 'surprise'\n self.requirementfile += '\\\\n'\n if(method == 'package'):\n self.modelfile += 'import surprise'\n self.modelfile += '\\\\n'\n self.modelfile += 'import statsmodels'\n self.modelfile += '\\\\n'\n self.requirementfile += 'statsmodels==0.10.2'\n self.requirementfile += '\\\\n'\n\n def crate_readme_file(self,deploy_path,modelfile,features,method,single_file=False):\n self.readme='========== Files Structures =========='\n self.readme+='\\\\n'\n self.readme+=modelfile+' ------ Trained Model'\n self.readme+='\\\\n'\n self.readme+='aion_prediction.py --> Python package entry point'\n self.readme+='\\\\n'\n if not single_file:\n self.readme+='script/inputprofiler.py --> Profiling like FillNA and Category to Numeric'\n self.readme+='\\\\n'\n self.readme+='script/selector.py --> Feature Selection'\n self.readme+='\\\\n'\n self.readme+='script/trained_model.py --> Read the model file and call the prediction'\n self.readme+='\\\\n'\n self.readme+='script/output_format.py --> Output formatter file'\n self.readme+='\\\\n'\n self.readme+= self.pythonpackage\n self.", "instruction": "", "output": "" }, { "input": "readme+= '========== How to call the model =========='\n self.readme+='\\\\n'\n self.readme+= '============== From Windows Terminal =========='\n self.readme+='\\\\n'\n if method == 'optimus_package':\n self.readme += 'python aion_prediction.py filename.json'\n self.readme +='\\\\n'\n self.readme += '========== Embedded Methods =========='\n self.readme +='\\\\n'\n self.readme += 'Function Name: predict_from_json - When input is Json Data'\n self.readme +='\\\\n'\n self.readme += 'Function Name: predict_from_file - When input is Json File'\n self.readme +='\\\\n'\n else:\n callpython = 'python aion_prediction.py \"[{'\n for x in features:\n if(callpython != 'python prediction.py \"[{'):\n callpython += ','\n callpython += '\\\\\\\\\\\\\"'+str(x)+'\\\\\\\\\\\\\"'+':'+'\\\\\\\\\\\\\"'+str(x)+'_value'+'\\\\\\\\\\\\\"'\n callpython += '}]\"'\n self.readme += callpython\n self.readme+='\\\\n'\n self.readme+= '============== From Linux Terminal =========='\n self.readme+='\\\\n'\n callpython = 'python aion_prediction.py \\\\'[{'\n temp =callpython\n for x in features:\n if(callpython != temp):\n callpython += ','\n callpython += '\"'+str(x)+'\"'+':'+'\"'+str(x)+'_value'+'\"'\n callpython += '}]\\\\''\n self.readme += callpython\n self.readme+='\\\\n'\n self.readme+= '============== Output =========='\n self.readme+='\\\\n'\n self.readme+= '{\"status\":\"SUCCESS\",\"data\":[{\"Data1\":\"Value\",\"prediction\":\"Value\"}]}' ## For Single Row/Record'\n self.readme+='\\\\n'\n self.readme+= '{\"status\":\"SUCCESS\",\"data\":[{\"Data1\":\"Value\",\"prediction\":\"Value\"},{\"Data1\":\"Value\",\"prediction\":\"Value\"}]} ## For Multiple Row/Record'\n self.readme+='\\\\n'\n self.readme+= '{\"status\":\"ERROR\",\"message\":\"description\"} ## In Case Exception or Error'\n self.readme+='\\\\n'\n #print(self.readme)\n filename = os.path.join(deploy_path,'readme.txt')\n self.log.info('-------> Readme File Location: '+filename)\n f = open(filename, \"wb\")\n f.write(str(self.readme).encode('utf8'))\n f.close()\n def create_class(self,classname):\n #self.modelfile += 'class '+classname+'(object):'\n self.modelfile += 'class trained_model(object):'\n self.modelfile += '\\\\n'\n\n def profiler_code(self,model_type,model,output_columns, features, text_feature,wordToNumericFeatures=[], deploy={},datetimeFeature=''):\n profiler = deploy.get('profiler',{})\n if isinstance(features, str):\n features = features.split(',')\n code = f\"\"\"\nimport scipy\nimport joblib\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\n\"\"\"\n if text_feature:\n code += \"\"\"\nimport importlib.util\\\\n\"\"\"\n\n if wordToNumericFeatures:\n code += \"\"\"\nfrom word2number import w2n\n\ndef s2n(value):\n try:\n x=eval(value)\n return x\n except:\n try:\n return w2n.word_to_num(value)\n except:\n return np.nan \n\"\"\"\n if 'code' in deploy.get('preprocess',{}).keys():\n code += deploy['preprocess']['code']\n\n if profiler.get('conversion_method','').lower() == 'glove':\n code += \"\"\"\nclass inputprofiler(object):\n\n def __init__(self):\n self.model = None\n preprocess_path = Path(__file__).parent.parent/'model'/'preprocess_pipe.pkl'\n\n if preprocess_path.exists():\n self.model = joblib.load(preprocess_path)\n from text.Embedding import load_pretrained\n from text import TextProcessing\n model_path = TextProcessing.checkAndDownloadPretrainedModel('glove')\n embed_size, loaded_model = load_pretrained(model_path)\n self.model.set_params(text_process__vectorizer__external_model = loaded_model)\n else:\n raise ValueError('Preprocess model not found')\n\n def apply_profiler(self,df):\n df = df.replace(r'^\\\\s*$', np.NaN, regex=True)\n\"\"\"\n elif profiler.get('conversion_method','').lower() == 'fasttext':\n code += \"\"\"\ndef get_pretrained_model_path():\n try:\n from AION.appbe.dataPath import DATA_DIR\n modelsPath = Path(DATA_DIR)/'PreTrainedModels'/'TextProcessing'\n except:\n modelsPath = Path('aion')/'PreTrainedModels'/'TextProcessing'\n \n if not modelsPath.exists():\n modelsPath.mkdir(parents=True, exist_ok=True)\n return modelsPath\n\nclass inputprofiler(object):\n\n def __init__(self):\n self.model = None\n preprocess_path = Path(__file__).parent.parent/'model'/'preprocess_pipe.pkl'\n\n if preprocess_path.exists():\n self.model = joblib.load(preprocess_path)\n if not importlib.util.find_spec('fasttext'):\n raise ValueError('fastText not installed')\n else:\n import os\n import fasttext\n import fasttext.util\n cwd = os.getcwd()\n os.chdir(get_pretrained_model_path())\n fasttext.util.download_model('en', if_exists='ignore')\n loaded_model = fasttext.load_model('cc.en.300.bin')\n os.chdir(cwd)\n self.model.set_params(text_process__vectorizer__external_model = loaded_model)\n self.model.set_params(text_process__vectorizer__external_model_type = 'binary')\n else:\n raise ValueError('Preprocess model not found')\n\n def apply_profiler(self,df):\n df = df.replace(r'^\\\\s*$', np.NaN, regex=True)\n\"\"\"\n else:\n code += \"\"\"\nclass inputprofiler(object):\n\n def __init__(self):\n self.model = None\n preprocess_path = Path(__file__).parent.parent/'model'/'preprocess_pipe.pkl'\n if preprocess_path.exists():\n self.model = joblib.load(preprocess_path)\n else:\n raise ValueError('Preprocess model not found')\n\n def apply_profiler(self,df):\n df = df.replace(r'^\\\\s*$', np.NaN, regex=True)\n\"\"\"\n if 'code' in deploy.get('preprocess',{}).keys():\n code += \" df = preprocess( df)\\\\n\"\n if wordToNumericFeatures:\n code += f\"\"\"\n df[{wordToNumericFeatures}] = df[{wordToNumericFeatures}].apply(lambda x: s2n(x))\"\"\"\n if profiler.get('unpreprocessed_columns'):\n code += f\"\"\"\n unpreprocessed_data = df['{profiler['unpreprocessed_columns'][0]}']\n df.drop(['{profiler['unpreprocessed_columns'][0]}'], axis=1,inplace=True)\n \"\"\"\n if profiler.get('force_numeric_conv'):\n code += f\"\"\"\n df[{profiler['force_numeric_conv']}] = df[{profiler['force_numeric_conv']}].apply(pd.to_numeric,errors='coerce')\n \"\"\"\n code += f\"\"\"\n if self.model:\n df = self.model.transform(df)\"\"\"\n code += f\"\"\" \n columns = {output_columns}\n if isinstance(df, scipy.sparse.spmatrix):\n df = pd.DataFrame(df.toarray(), columns=columns)\n else:\n df = pd.DataFrame(df, columns=columns)\n \"\"\"\n ##The below if loop for avoiding unpreprocessed column variable storing which is not used for anomaly detection\n if model_type.lower() == 'anomaly_detection' and datetimeFeature != '' and datetimeFeature.lower() != 'na':\n pass\n else:\n if profiler.get('unpreprocessed_columns'):\n code += f\"\"\"\n df['{profiler.get('unpreprocessed_columns')[0]}'] = unpreprocessed_data\n \"\"\"\n if model_type.lower() == 'anomaly_detection' and datetimeFeature != '' and datetimeFeature.lower() != 'na':\n ##This below set_index is wrong, because we drop datetimefeature before profiling and doing set_index. So commented now.\n # code += f\"\"\"\n # df.set_index('{datetimeFeature}', inplace=True)\"\"\"\n code += f\"\"\"\n return(df,'{datetimeFeature}')\\\\n\"\"\"\n else:\n code += f\"\"\"\n return(df)\"\"\"\n return code\n\n\n def no_profiling_code(self, features):\n if isinstance(features, str):\n features = features.split(',')\n return f\"\"\"\nimport pandas as pd\nimport numpy as np\n\nclass inputprofiler(object):\n\n def apply_profiler(self,df):\n df = df.replace(r'^\\\\s*$', np.NaN, regex=True)\n return df[{features}]\n \"\"\"\n\n def create_profiler_file(self,learner_type,deploy_path,profiler,features,numericToLabel_json,column_merge_flag,text_features,preprocessing_pipe,firstDocFeature,secondDocFeature,normalizer,normFeatures,wordToNumericFeatures,conversion_method,model_type,preprocess_pipe,preprocess_out_columns, label_encoder,model, config=None,datetimeFeature=''):\n filename = str(Path(deploy_path)/'script'/'inputprofiler.py')\n if 'profiler' in config:\n if model_type == 'BM25':\n code = self.profiler_code(model_type,model,['tokenize'],features, text_features,config['profiler']['word2num_features'])\n elif model == 'KaplanMeierFitter':\n code = self.no_profiling_code(features)\n elif model.lower() in ['arima', 'fbprophet']: #task 12627\n code = self.no_profiling_code('noofforecasts')\n else:\n code = self.profiler_code(model_type,model,config['profiler']['output_features'],features, text_features,config['profiler']['word2num_features'],config,datetimeFeature)\n if code:\n with open(filename,'w',encoding=\"utf-8\") as f:\n f.write(code)\n self.log.info('-------> Profiler File Location :'+filename)\n return\n self.profilerfile += 'import pandas as pd'\n self.profilerfile += '\\\\n'\n self.profilerfile += 'import joblib'\n self.profilerfile += '\\\\n'\n self.profilerfile += 'import os'\n self.profilerfile += '\\\\n'\n self.profilerfile += 'from word2number import w2n'\n self.profilerfile += '\\\\n'\n\n self.profilerfile += 'import numpy as np'\n self.profilerfile += '\\\\nfrom pathlib import Path\\\\n'\n #print(\"1\")\n #print(profiler)\n if(learner_type == 'Text Similarity' or len(text_features) > 0):\n self.profilerfile += 'from text import TextProcessing'\n self.profilerfile += '\\\\n'\n self.profilerfile += 'def textCleaning(textCorpus):'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' textProcessor = TextProcessing.TextProcessing()'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' textCorpus = textProcessor.transform(textCorpus)'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' return(textCorpus)'\n self.profilerfile += '\\\\n'\n\n self.profilerfile += 'class inputprofiler(object):'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' def s2n(self,value):'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' try:'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' x=eval(value)'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' return x'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' except:'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' try:'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' return w2n.word_to_num(value)'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' except:'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' return np.nan '\n self.profilerfile += '\\\\n'\n self.profilerfile += ' def apply_profiler(self,df):'\n self.profilerfile += '\\\\n'\n if(len(wordToNumericFeatures) > 0):\n for w2nFeature in wordToNumericFeatures:\n if w2nFeature not in features:\n continue\n self.profilerfile += \" df['\"+w2nFeature+\"']=df['\"+w2nFeature+\"'].apply(lambda x: self.s2n(x))\"\n self.profilerfile += '\\\\n'\n self.profilerfile += \" df = df.replace(r'^\\\\s*$', np.NaN, regex=True)\"\n self.profilerfile += '\\\\n'\n self.profilerfile += ' try:'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' df.dropna(how=\"all\",axis=1,inplace=True)'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' except:'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' df.fillna(0)'\n self.profilerfile += '\\\\n'\n\n if model_type.lower() != 'timeseriesforecasting': #task 11997\n self.profilerfile += ' preprocess_path = Path(__file__).parent.parent/\"model\"/\"preprocess_pipe.pkl\"\\\\n'\n self.profilerfile += ' if preprocess_path.exists():\\\\n'\n self.profilerfile += ' model = joblib.load(preprocess_path)\\\\n'\n if model_type.lower()=='anomaly_detection' and model.lower() == 'autoencoder':\n self.profilerfile += f\" df[{features}] = model.transform(df[{features}])\\\\n\"\n else:\n self.profilerfile += f\" df = model.transform(df)\\\\n\"\n if 'operation' in profiler:\n y = profiler['operation']\n for action in y:\n feature = action['feature']\n #if feature not in features:\n", "instruction": "", "output": "" }, { "input": " # continue\n operation = action['Action']\n if(operation == 'Drop'):\n self.profilerfile += \" if '\"+feature+\"' in df.columns:\"\n self.profilerfile += '\\\\n'\n self.profilerfile += \" df.drop(columns=['\"+feature+\"'],inplace = True)\"\n self.profilerfile += '\\\\n'\n if(operation == 'FillValue'):\n self.profilerfile += \" if '\"+feature+\"' in df.columns:\"\n self.profilerfile += '\\\\n'\n fvalue = action['value']\n self.profilerfile += \" df['\"+feature+\"'] = df['\"+feature+\"'].fillna(value='\"+fvalue+\"')\"\n self.profilerfile += '\\\\n'\n if(operation == 'Encoder'):\n value = action['value']\n value = value.replace(\"\\\\n\", \"\\\\\\\\n\")\n self.profilerfile += \" if '\"+feature+\"' in df.columns:\"\n self.profilerfile += '\\\\n'\n self.profilerfile += \" le_dict=\"+str(value)\n self.profilerfile += '\\\\n'\n self.profilerfile += \" df['\"+feature+\"'] = df['\"+feature+\"'].apply(lambda x: le_dict.get(x,-1))\"\n self.profilerfile += '\\\\n'\n self.profilerfile += \" if -1 in df['\"+feature+\"'].values:\"\n self.profilerfile += '\\\\n'\n self.profilerfile += \" raise Exception('Category value of \"+feature+\" not present in training data')\"\n self.profilerfile += '\\\\n'\n if 'conversion' in profiler:\n catergoryConverton = profiler['conversion']\n #print(catergoryConverton)\n if (catergoryConverton['categoryEncoding'].lower() in ['targetencoding','onehotencoding']) and ('features' in catergoryConverton):\n self.profilerfile += \" encoder = joblib.load(os.path.join(os.path.dirname(__file__),'..','model','categoryEncoder.pkl'))\"\n self.profilerfile += '\\\\n'\n self.profilerfile += \" CategoryFeatures = \"+str(catergoryConverton['features'])\n self.profilerfile += '\\\\n'\n if catergoryConverton['categoryEncoding'].lower() == 'onehotencoding':\n self.profilerfile += \" transformed_data = encoder.transform(df[CategoryFeatures]).toarray()\"\n self.profilerfile += '\\\\n'\n self.profilerfile += \" feature_labels = encoder.get_feature_names(CategoryFeatures)\"\n self.profilerfile += '\\\\n'\n self.profilerfile += \" transformed_data = pd.DataFrame(transformed_data,columns=feature_labels) \"\n self.profilerfile += '\\\\n'\n else:\n self.profilerfile += \" transformed_data = encoder.transform(df[CategoryFeatures])\"\n self.profilerfile += '\\\\n'\n self.profilerfile += \" dataColumns=list(df.columns)\"\n self.profilerfile += '\\\\n'\n self.profilerfile += \" nonNormFeatures=list(set(dataColumns) - set(CategoryFeatures))\"\n self.profilerfile += '\\\\n'\n self.profilerfile += \" dataArray=df[nonNormFeatures]\"\n self.profilerfile += '\\\\n'\n self.profilerfile += \" df = pd.concat([dataArray, transformed_data],axis=1)\"\n self.profilerfile += '\\\\n'\n y = json.loads(numericToLabel_json)\n\n for feature_details in y:\n feature = feature_details['feature']\n if feature not in features:\n continue\n label = feature_details['Labels']\n bins = feature_details['Bins']\n self.profilerfile += \" if '\"+feature+\"' in df.columns:\"\n self.profilerfile += '\\\\n'\n self.profilerfile += \" cut_bins=\"+str(bins)\n self.profilerfile += '\\\\n'\n self.profilerfile += \" cut_labels=\"+str(label)\n self.profilerfile += '\\\\n'\n self.profilerfile += \" df['\"+feature+\"'] = pd.cut(df['\"+feature+\"'],bins=cut_bins,labels=cut_labels)\"\n self.profilerfile += '\\\\n'\n self.profilerfile += \" df['\"+feature+\"'] = df['\"+feature+\"'].fillna(value=0)\"\n self.profilerfile += '\\\\n'\n\n if(len(text_features) > 0):\n if(len(text_features) > 1):\n self.profilerfile += ' merge_features = '+str(text_features)\n self.profilerfile += '\\\\n'\n self.profilerfile += ' df[\\\\'combined\\\\'] = df[merge_features].apply(lambda row: \\\\' \\\\'.join(row.values.astype(str)), axis=1)'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' features = [\\\\'combined\\\\']'\n self.profilerfile += '\\\\n'\n else:\n self.profilerfile += \" features = \"+str(text_features)\n self.profilerfile += '\\\\n'\n if model_type == 'BM25':\n self.profilerfile += \"\"\"\\\\\n df_text = df[features[0]]\n pipe = joblib.load(os.path.join(os.path.dirname(__file__),'..','model','{preprocessing_pipe}'))\n df['tokenize'] = pipe.transform(df_text)\\\\n\"\"\".format(preprocessing_pipe=preprocessing_pipe)\n elif conversion_method == 'sentenceTransformer':\n self.profilerfile += \"\"\"\\\\\n df_text = df[features[0]]\n from sentence_transformers import SentenceTransformer\n model = SentenceTransformer(\\\\'sentence-transformers/msmarco-distilroberta-base-v2\\\\')\n df_vect = model.encode(df_text)\n for empCol in {text_features}:\n df = df.drop(columns=[empCol])\n if isinstance(df_vect, np.ndarray):\n df1 = pd.DataFrame(df_vect)\n else:\n df1 = pd.DataFrame(df_vect.toarray(),columns = pipe.named_steps[\\\\'vectorizer\\\\'].get_feature_names())\n df1 = df1.add_suffix(\\\\'_vect\\\\')\n df = pd.concat([df, df1],axis=1)\\\\n\"\"\".format(preprocessing_pipe=preprocessing_pipe, text_features=text_features)\n else:\n self.profilerfile += \"\"\"\\\\\n df_text = df[features[0]]\n pipe = joblib.load(os.path.join(os.path.dirname(__file__),'..','model','{preprocessing_pipe}'))\n df_vect=pipe.transform(df_text)\n for empCol in {text_features}:\n df = df.drop(columns=[empCol])\n if isinstance(df_vect, np.ndarray):\n df1 = pd.DataFrame(df_vect)\n else:\n df1 = pd.DataFrame(df_vect.toarray(),columns = pipe.named_steps[\\\\'vectorizer\\\\'].get_feature_names())\n df1 = df1.add_suffix(\\\\'_vect\\\\')\n df = pd.concat([df, df1],axis=1)\\\\n\"\"\".format(preprocessing_pipe=preprocessing_pipe, text_features=text_features)\n\n if(learner_type == 'Text Similarity'):\n self.profilerfile += ' df[\\\\''+firstDocFeature+'\\\\'] = textCleaning(df[\\\\''+firstDocFeature+'\\\\'])'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' df[\\\\''+secondDocFeature+'\\\\'] = textCleaning(df[\\\\''+secondDocFeature+'\\\\'])'\n self.profilerfile += '\\\\n'\n if len(normFeatures) > 0 and normalizer != '':\n self.profilerfile += \" normFeatures = \"+str(normFeatures)\n self.profilerfile += '\\\\n'\n self.profilerfile += ' normalizepipe = joblib.load(os.path.join(os.path.dirname(os.path.abspath(__file__)),\\\\'..\\\\',\\\\'model\\\\',\\\\''+normalizer+'\\\\'))'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' dataColumns=list(df.columns)'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' nonNormFeatures=list(set(dataColumns) - set(normFeatures))'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' dataframe=df[normFeatures]'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' transDf = normalizepipe.transform(dataframe)'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' nontransDF=df[nonNormFeatures].values'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' dataColumns=normFeatures+nonNormFeatures'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' scaledDf = pd.DataFrame(np.hstack((transDf, nontransDF)),columns=dataColumns)'\n self.profilerfile += '\\\\n'\n self.profilerfile += ' df=scaledDf'\n self.profilerfile += '\\\\n'\n else:\n self.profilerfile += ' df=df.dropna()\\\\n'\n self.profilerfile += ' return(df)'\n filename = os.path.join(deploy_path,'script','inputprofiler.py')\n self.log.info('-------> Profiler File Location :'+filename)\n f = open(filename, \"w\",encoding=\"utf-8\")\n f.write(str(self.profilerfile))\n f.close()\n\n def isEnglish(self, s):\n try:\n s.encode(encoding='utf-8').decode('ascii')\n except UnicodeDecodeError:\n return False\n else:\n return True\n\n def create_selector_file(self,deploy_path,features,pcaModel_pickle_file,bpca_features,apca_features,textFeatures,nonNumericFeatures,numericalFeatures,profiler,targetFeature, model_type,model,config=None):\n cs.create_selector_file(self,deploy_path,features,pcaModel_pickle_file,bpca_features,apca_features,textFeatures,nonNumericFeatures,numericalFeatures,profiler,targetFeature, model_type,model,config)\n\n def create_init_function_for_regression(self,modelfile):\n self.modelfile += ' def __init__(self):'\n self.modelfile += '\\\\n'\n self.modelfile += \" self.model = joblib.load(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'))\"\n self.modelfile += '\\\\n'\n\n def create_init_function_for_classification(self,modelfile,classes,learner_type,scoreParam,loss_matrix,optimizer,preprocessing_pipe,modelName,model_type,imageconfig):\n cs.create_init_function_for_classification(self,modelfile,classes,learner_type,scoreParam,loss_matrix,optimizer,preprocessing_pipe,modelName,model_type,imageconfig)\n\n def create_predict_proba(self,learner_type,method):\n self.modelfile += ' def predict(self,X,features_names):'\n self.modelfile += '\\\\n'\n self.modelfile += ' return self.model.predict_proba(X)'\n\n def create_forcast(self,method,no_of_prediction):\n self.modelfile += ' def predict(self,X,features_names):'\n self.modelfile += '\\\\n'\n self.modelfile += ' no_of_prediction = '+str(no_of_prediction)\n self.modelfile += '\\\\n'\n self.modelfile += ' lag_order = self.model.k_ar'\n self.modelfile += '\\\\n'\n self.modelfile += ' return self.model.forecast(X.values[-lag_order:],steps=no_of_prediction)'\n\n def create_predict(self,learner_type,method,model,model_type,threshold,firstDocFeature,secondDocFeature,padding_length,optimizationmethod,sessonal_freq,additional_regressors,feature,modelFeatures,indexFeature,lag_order,scalertransformationFile,datetimeFeature,scoreParam=None):\n scorePrm = scoreParam\n cs.create_predict(self,learner_type,method,model,model_type,threshold,firstDocFeature,secondDocFeature,padding_length,optimizationmethod,sessonal_freq,additional_regressors,feature,modelFeatures,indexFeature,lag_order,scalertransformationFile,datetimeFeature,scorePrm)\n\n def save_model_deploy(self,outputfolder,modelname):\n #filename = outputfolder+modelname+'.py'\n filename = os.path.join(outputfolder,'script','trained_model.py')\n self.log.info('-------> Model File Location :'+filename)\n f = open(filename, \"w\",encoding=\"utf-8\")\n f.write(str(self.modelfile))\n f.close()\n\n def create_TextCleaner(self,outputfolder):\n profilerPath = os.path.join(outputfolder,'profiler')\n try:\n os.makedirs(profilerPath)\n except OSError:\n self.log.info(\"ProfilePath Folder Already Exists\")\n\n try:\n textprofileFileLocation = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','profiler','textDataProfiler.py')\n initFileLocation = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','profiler','__init__.py')\n shutil.copy2(textprofileFileLocation,profilerPath)\n shutil.copy2(initFileLocation,profilerPath)\n '''\n if(platform.system() == 'Windows'):\n shutil.copy2(os.path.dirname(os.path.abspath(__file__))+'\\\\\\\\..\\\\\\\\profiler\\\\\\\\textDataProfiler.py',profilerPath)\n shutil.copy2(os.path.dirname(os.path.abspath(__file__))+'\\\\\\\\..\\\\\\\\profiler\\\\\\\\__init__.py',profilerPath)\n else:\n shutil.copy2(os.path.dirname(os.path.abspath(__file__))+'/../profiler/textDataProfiler.py',profilerPath)\n shutil.copy2(os.path.dirname(os.path.abspath(__file__))+'/../profiler/__init__.py',profilerPath)\n '''\n except OSError:\n self.log.info(\"Copy to Profiler Path Failed\")\n\n def listToString(self,s):\n str1='['\n for feature in s:\n if(str1 != '['):\n str1 += ','\n str1 += '\"'+feature+'\"'\n str1+=']'\n return str1\n\n", "instruction": "", "output": "" }, { "input": " def print_files(self):\n self.log.info(self.modelfile)\n\n def create_util_folder(self, deploy_path,learner_type):\n import tarfile\n ext_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..','utilities'))\n for x in os.listdir(ext_path):\n if x.endswith('.tar'):\n if x not in ['scikit_surprise-1.1.1.dist-info.tar','surprise.tar']:\n tarPackage = os.path.join(ext_path, x)\n my_tar = tarfile.open(tarPackage)\n my_tar.extractall(deploy_path)\n my_tar.close()\n else:\n if learner_type == 'RecommenderSystem':\n tarPackage = os.path.join(ext_path, x)\n my_tar = tarfile.open(tarPackage)\n my_tar.extractall(deploy_path)\n my_tar.close()\n def deploy_model(self,deploy_name,deployJson,learner_type,model_type,model,scoreParam,saved_model,deploy_path,features,profiler,datalocation,output_label,column_merge_flag,textFeatures,numericalFeatures,nonNumericFeatures,preprocessing_pipe,numericToLabel_json,threshold,loss_matrix,optimizer,firstDocFeature,secondDocFeature,padding_length,trained_data_file,dictDiffCount,targetFeature,normalizer,normFeatures,pcaModel_pickle_file,bpca_features,apca_features,optimizationmethod,deployFolder,iterName,iterVersion,wordToNumericFeatures,imageconfig,sessonal_freq,additional_regressors,grouperbyjson,rowfilterexpression,xtrain,profiled_data_file,conversion_method,modelFeatures,indexFeature,lag_order,scalertransformationFile,no_of_prediction,preprocess_pipe,preprocess_out_columns, label_encoder,datetimeFeature,usecaseLocation,config=None):\n try:\n serviceName = '{}{}{}'.format(iterName, '_' if iterVersion != '' else '', iterVersion)\n self.log.info('-------> Deploy Location :'+deploy_path)\n if production.is_supported(model_type.lower()):\n if learner_type == 'Text Similarity':\n coder = production.get_deployer(learner_type)\n coder.create_file(deploy_path, preprocessing_pipe, saved_model, firstDocFeature, secondDocFeature)\n elif model_type.lower() in ['classification', 'regression','clustering','timeseriesforecasting']:\n params = {}\n params['usecase_name']= iterName\n params['usecase_ver']= iterVersion\n params['features']={}\n params['features']['input_feat'] = config['profiler']['input_features']\n params['features']['target_feat'] = targetFeature\n params['features']['text_feat'] = textFeatures\n params['paths']={}\n params['paths']['deploy'] = Path(deploy_path)\n params['paths']['usecase'] = params['paths']['deploy'].parent\n params['profiler']=config['profiler']\n if 'code' in config.get('preprocess',{}).keys():\n params['profiler']['preprocess']=config['preprocess']\n params['selector']={}\n params['selector']['reducer']=True if pcaModel_pickle_file else False\n params['selector']['reducer_file']=pcaModel_pickle_file\n if pcaModel_pickle_file:\n params['selector']['input_features']=bpca_features\n params['selector']['output_features']=apca_features\n else:\n params['selector']['input_features']=config['profiler']['input_features']\n params['selector']['output_features']=features\n params['training']={}\n params['training']['algo']= model\n params['training']['model_file']=saved_model\n if model_type.lower() == 'timeseriesforecasting':\n if params['training']['algo'] in ['LSTM','MLP','ENCODER_DECODER_LSTM_MVI_UVO']:\n params['training']['lag_order'] = int(lag_order)\n params['training']['scaler_file'] = Path(scalertransformationFile).name\n elif params['training']['algo'] == 'VAR':\n params['training']['dictDiffCount'] = dictDiffCount\n params['training']['no_of_prediction'] = no_of_prediction\n elif params['training']['algo'] == 'FBPROPHET':\n params['training']['sessonal_freq'] = sessonal_freq\n params['training']['additional_regressors'] = additional_regressors\n self.log.info(params)\n deployer = production.get_deployer(model_type.lower(), params=params)\n deployer.run( )\n self.log.info('Status:- |... Model deployment files created')\n self.log.info('Status:- |... Model deployment completed')\n return\n\n else:\n # for output_formatter.py\n from prediction_package.output_formatter import outputFormatter\n outputObj = outputFormatter()\n outputObj.crate_output_format_file(deploy_path, learner_type, model_type, model, output_label,\n threshold, trained_data_file, dictDiffCount, targetFeature, features,datetimeFeature)\n #for aion_predict.py\n from prediction_package.aion_prediction import aionPrediction\n predictionObj = aionPrediction()\n # print(deploy_path)\n predictionObj.create_prediction_file(deploy_name, deploy_path, learner_type, grouperbyjson,rowfilterexpression,model_type,datetimeFeature)\n # for aion_service.py\n predictionObj.create_model_service(deploy_path, serviceName, model_type)\n # for aion_publish.py\n predictionObj.create_publish_service(usecaseLocation, iterName, iterVersion, model_type)\n if learner_type.lower()==\"recommendersystem\":\n # Task 11190---\n #For recommender system\n from prediction_package.recommender_code import generate_recommender_code\n generate_recommender_code(deploy_path)\n return\n #self.create_TextCleaner(deploy_path)\n if(len(textFeatures) > 0):\n self.create_TextCleaner(deploy_path)\n\n self.include_import_file(learner_type,deployJson['method'],scoreParam, model_type,model)\n\n if((learner_type == 'TS' and model.lower() not in ['lstm','mlp','var']) or learner_type == 'RecommenderSystem'):\n features=[]\n\n self.create_class(deploy_name)\n\n if len(bpca_features) != 0:\n self.create_profiler_file(learner_type,deploy_path,profiler,bpca_features,numericToLabel_json,column_merge_flag,textFeatures,preprocessing_pipe,firstDocFeature,secondDocFeature,normalizer,normFeatures,wordToNumericFeatures,conversion_method,model_type,preprocess_pipe,preprocess_out_columns, label_encoder, model, config,datetimeFeature)\n else:\n self.create_profiler_file(learner_type,deploy_path,profiler,features,numericToLabel_json,column_merge_flag,textFeatures,preprocessing_pipe,firstDocFeature,secondDocFeature,normalizer,normFeatures,wordToNumericFeatures,conversion_method,model_type,preprocess_pipe,preprocess_out_columns, label_encoder, model, config,datetimeFeature)\n\n self.create_selector_file(deploy_path,features,pcaModel_pickle_file,bpca_features,apca_features,textFeatures,nonNumericFeatures,numericalFeatures,profiler,targetFeature,model_type, model,config)\n self.create_init_function_for_classification(saved_model,'classes',learner_type,scoreParam,loss_matrix,optimizer,preprocessing_pipe,model,model_type,imageconfig)\n except Exception as e:\n print(e)\n import traceback\n exception_type, exception_object, exception_traceback = sys.exc_info()\n filename = exception_traceback.tb_frame.f_code.co_filename\n line_number = exception_traceback.tb_lineno\n\n self.log.info(\"Exception type: \", exception_type)\n self.log.info(\"File name: \", filename)\n self.log.info(\"Line number: \", line_number)\n self.log.info(\"multivariate model build error traceback: \\\\n\"+str(traceback.print_exc()))\n raise Exception(e)\n #print(model)\n if(model.lower() == 'var'):\n self.log.info(\"Create Forecast Function\")\n self.create_forcast(deployJson['method'],no_of_prediction)\n else:\n self.create_predict(learner_type,deployJson['method'],model,model_type,threshold,firstDocFeature,secondDocFeature,padding_length,optimizationmethod,sessonal_freq,additional_regressors,features,modelFeatures,indexFeature,lag_order,scalertransformationFile,datetimeFeature,scoreParam)\n self.save_model_deploy(deploy_path,deploy_name)\n\n\n if(len(textFeatures) > 0):\n if model_type.lower() == 'classification' or model_type.lower() == 'regression' or model_type.lower() == 'timeseriesforecasting':\n predictionObj.create_text_drift_file(deploy_path,textFeatures,targetFeature,model_type)\n if model_type.lower() == 'classification':\n predictionObj.create_classification_text_performance_file(deploy_path,textFeatures,targetFeature)\n elif model_type.lower() == 'regression':\n predictionObj.create_regression_text_performance_file(deploy_path,textFeatures,targetFeature)\n\n else: \n if model_type.lower() == 'classification' or model_type.lower() == 'regression' or model_type.lower() == 'timeseriesforecasting': #task 11997\n predictionObj.create_drift_file(deploy_path,features,targetFeature,model_type)\n if model_type.lower() == 'classification':\n predictionObj.create_classification_performance_file(deploy_path,features,targetFeature)\n elif model_type.lower() == 'regression':\n predictionObj.create_regression_performance_file(deploy_path,features,targetFeature)\n\n self.log.info('Status:- |... Model deployment files created')\n self.crate_readme_file(deploy_path,saved_model,features,deployJson['method'])\n from prediction_package.requirements import requirementfile\n requirementfile(deploy_path,model,textFeatures,learner_type)\n os.chdir(deploy_path)\n textdata = False\n if(learner_type == 'Text Similarity' or len(textFeatures) > 0):\n textdata = True\n self.create_util_folder(deploy_path,learner_type)\n self.log.info('Status:- |... Model deployment completed')\n\n\n def deployTSum(self,deploy_path,preTrainedModellocation):\n def create_predict(preTrainedModellocation):\n\n text = f\"\"\"\nimport sys\nimport json \ndef predict(data):\n try:\n import pandas as pd\n import numpy as np\n from pathlib import Path\n keywordsFile =Path(__file__).parent/'data'/'keywordDataBase.csv'\n outputSumFile =Path(__file__).parent/'data'/'summarizedOutput.csv'\n fileName=data\n #print(\"fileName---\",fileName)\n inputDataFileFrame = pd.DataFrame()\n inputDataFileFrame['Sentences']=\"\"\n rowIndex=0\n if fileName.endswith(\".pdf\"):\n from pypdf import PdfReader\n reader = PdfReader(fileName)\n number_of_pages = len(reader.pages)\n text=\"\"\n textOutputForFile=\"\" \n OrgTextOutputForFile=\"\" \n for i in range(number_of_pages) :\n page = reader.pages[i]\n text1 = page.extract_text()\n text=text+text1\n import nltk\n tokens = nltk.sent_tokenize(text)\n for sentence in tokens:\n sentence=sentence.replace(\"\\\\\\\\n\", \" \") \n if (len(sentence.split()) < 4 ) or (len(str(sentence.split(',')).split()) < 8)or (any(chr.isdigit() for chr in sentence)) :\n continue\n inputDataFileFrame.at[rowIndex,'Sentences']=str(sentence.strip()) \n rowIndex=rowIndex+1\n if fileName.endswith(\".txt\"):\n data=[]\n with open(fileName, \"r\",encoding=\"utf-8\") as f:\n data.append(f.read())\n str1 = \"\"\n for ele in data:\n str1 += ele\n sentences=str1.split(\".\")\n count=0\n for sentence in sentences:\n count += 1\n inputDataFileFrame.at[rowIndex,'Sentences']=str(sentence.strip())\n rowIndex=rowIndex+1\n inputDataFileFrame['LabelByKw']=0 \n #print(inputDataFileFrame)\n keywordsFileFrame=pd.read_csv(keywordsFile,encoding='utf-8')\n Keyword_list = keywordsFileFrame['Keyword'].tolist()\n for i in inputDataFileFrame.index:\n for x in Keyword_list:\n if (str(inputDataFileFrame[\"Sentences\"][i])).lower().find(x) != -1:\n inputDataFileFrame['LabelByKw'][i]=1\n break\n import pickle\n from sklearn.preprocessing import LabelEncoder\n pkl_filename='classificationModel.sav'\n pkl_filename =Path(__file__).parent/'model'/'classificationModel.sav'\n with open(pkl_filename, 'rb') as file:\n pickle_model = pickle.load(file)\n testsample=inputDataFileFrame[[\"Sentences\"]]\n labelencoder = LabelEncoder()\n testsample[\"Sentences\"] = labelencoder.fit_transform(testsample[\"Sentences\"])\n y_predicted = pickle_model.predict_proba(testsample)\n\n df=pd.DataFrame({{\"SectionName\":np.nan,\"Sentences\":np.nan, \"Predicted_Prob\":y_predicted[:,1]}})\n df['LabelByModel']=df['Predicted_Prob'].apply(lambda x: 0 if x <= 0.5 else 1 )\n inputDataFileFrame['LabelByModel']= df['LabelByModel']\n textToSum=\"\"\n for i in inputDataFileFrame.index:\n if (inputDataFileFrame['LabelByModel'][i] or inputDataFileFrame['LabelByKw'][i]) :\n textToSum=textToSum+\" \"+inputDataFileFrame[\"Sentences\"][i]\n stdir=r\"{preTrainedModellocation}\" \n stdir = stdir.replace('\\\\\\\\\\\\\\\\', '\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\')\n from transformers import AutoTokenizer, AutoModelForSeq2SeqLM\n modelbert = AutoModelForSeq2SeqLM.from_pretrained(stdir,local_files_only=True)\n tokenizer = AutoTokenizer.from_pretrained(stdir,local_files_only=True)\n inputs = tokenizer(\"summarize: \" + textToSum, return_tensors=\"pt\", max_length=512, truncation=True)\n outputs = modelbert.generate(inputs", "instruction": "", "output": "" }, { "input": "[\"input_ids\"], max_length=512, min_length=140, length_penalty=2.0, num_beams=4, early_stopping=True)\n summarizedOutputOfSection= tokenizer.decode(outputs[0])\n summarizedOutputOfSection=summarizedOutputOfSection.replace(\"\",\"\")\n summarizedOutputOfSection=summarizedOutputOfSection.replace(\"\",\"\")\n sumDatadata = [summarizedOutputOfSection]\n df = pd.DataFrame(sumDatadata, columns=['textSum'])\n df.to_csv(outputSumFile,encoding='utf-8')\n outputjson = {{\"status\":\"SUCCESS\",\"msg\":\"Press Download button to download summarized output\",\"data\":summarizedOutputOfSection}} \n print(\"predictions:\",json.dumps(outputjson))\n return (json.dumps(outputjson))\n except KeyError as e:\n output = {{\"status\":\"FAIL\",\"message\":str(e).strip('\"')}}\n print(\"predictions:\",json.dumps(output))\n return (json.dumps(output))\n except Exception as e:\n output = {{\"status\":\"FAIL\",\"message\":str(e).strip('\"')}}\n print(\"predictions:\",json.dumps(output))\n return (json.dumps(output))\n \nif __name__ == \"__main__\":\n output = predict(sys.argv[1])\n \"\"\"\n return text\n deploy_path = Path(deploy_path)\n aion_prediction = deploy_path/'aion_predict.py'\n\n with open(aion_prediction, 'w') as f:\n f.write(create_predict(preTrainedModellocation))\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom importlib.metadata import version\nimport sys\n\n \nclass importModule():\n\n def __init__(self):\n self.importModule = {}\n self.stdlibModule = []\n self.localModule = {}\n \n def addLocalModule(self,module, mod_from=None, mod_as=None):\n if module == '*':\n if module not in self.localModule.keys():\n self.localModule[module]= [mod_from]\n else:\n self.localModule[module].append(mod_from)\n elif module not in self.localModule.keys():\n self.localModule[module] = {'from':mod_from, 'as':mod_as}\n \n def addModule(self, module, mod_from=None, mod_as=None):\n if module not in self.importModule.keys():\n self.importModule[module] = {'from':mod_from, 'as':mod_as}\n if module in sys.stdlib_module_names:\n self.stdlibModule.append(module)\n elif isinstance(self.importModule[module], list):\n if mod_as not in [x['as'] for x in self.importModule[module]]:\n self.importModule[module].append({'from':mod_from, 'as':mod_as})\n elif mod_as not in [x['from'] for x in self.importModule[module]]:\n self.importModule[module].append({'from':mod_from, 'as':mod_as})\n elif mod_as != self.importModule[module]['as']:\n as_list = [self.importModule[module]]\n as_list.append({'from':mod_from, 'as':mod_as})\n self.importModule[module] = as_list\n elif mod_from != self.importModule[module]['from']:\n as_list = [self.importModule[module]]\n as_list.append({'from':mod_from, 'as':mod_as})\n self.importModule[module] = as_list\n\n def getModules(self):\n return (self.importModule, self.stdlibModule)\n \n def getBaseModule(self, extra_importers=[]):\n modules_alias = { 'sklearn':'scikit-learn', \n 'genetic_selection':'sklearn-genetic',\n 'google': 'google-cloud-storage',\n 'azure':'azure-storage-file-datalake'}\n local_modules = {'AIX':'/app/AIX-0.1-py3-none-any.whl'}\n modules = []\n require = \"\"\n if extra_importers:\n extra_importers = [importer.importModule for importer in extra_importers if isinstance(importer, importModule)]\n importers_module = [self.importModule] + extra_importers\n for importer_module in importers_module:\n for k,v in importer_module.items():\n if v['from']:\n mod = v['from'].split('.')[0]\n else:\n mod = k\n if mod in modules_alias.keys():\n mod = modules_alias[mod]\n modules.append(mod)\n modules = list(set(modules))\n for mod in modules:\n try:\n if mod in local_modules.keys():\n require += f\"{local_modules[mod]}\\\\n\"\n else:\n require += f\"{mod}=={version(mod)}\\\\n\"\n except :\n if mod not in sys.stdlib_module_names:\n raise \n return require\n\n def getCode(self):\n def to_string(k, v):\n mod = ''\n if v['from']:\n mod += 'from {} '.format(v['from'])\n mod += 'import {}'.format(k)\n if v['as']:\n mod += ' as {} '.format(v['as'])\n return mod\n \n modules = \"\"\n local_modules = \"\"\n std_lib_modules = \"\"\n third_party_modules = \"\"\n for k,v in self.importModule.items():\n if k in self.stdlibModule:\n std_lib_modules = std_lib_modules + '\\\\n' + to_string(k, v)\n elif isinstance(v, dict):\n third_party_modules = third_party_modules + '\\\\n' + to_string(k, v)\n elif isinstance(v, list):\n for alias in v:\n third_party_modules = third_party_modules + '\\\\n' + to_string(k, alias)\n for k,v in self.localModule.items():\n if k != '*':\n local_modules = local_modules + '\\\\n' + to_string(k, v)\n else:\n for mod_from in v:\n local_modules = local_modules + '\\\\n' + f'from {mod_from} import {k}'\n if std_lib_modules:\n modules = modules + \"\\\\n#Standard Library modules\" + std_lib_modules\n if third_party_modules:\n modules = modules + \"\\\\n\\\\n#Third Party modules\" + third_party_modules\n if local_modules:\n modules = modules + \"\\\\n\\\\n#local modules\" + local_modules + '\\\\n'\n return modules\n\n def copyCode(self, importer):\n self.importModule, self.stdlibModule = importer.getModules()\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os,sys\nimport platform\nimport json\nimport shutil\nimport logging\nfrom pathlib import Path\n\ndef create_selector_file(self,deploy_path,features,pcaModel_pickle_file,bpca_features,apca_features,textFeatures,nonNumericFeatures,numericalFeatures,profiler,targetFeature, model_type,model,config=None):\n self.selectorfile += 'import pandas as pd'\n self.selectorfile += '\\\\n'\n self.selectorfile += 'import joblib'\n self.selectorfile += '\\\\n'\n self.selectorfile += 'import os'\n self.selectorfile += '\\\\n'\n self.selectorfile += 'import numpy as np'\n self.selectorfile += '\\\\n'\n self.selectorfile += 'class selector(object):'\n self.selectorfile += '\\\\n'\n self.selectorfile += ' def apply_selector(self,df):'\n self.selectorfile += '\\\\n'\n if pcaModel_pickle_file != '':\n self.selectorfile += \" pcaModel = joblib.load(os.path.join(os.path.dirname(__file__),'..','model','\"+pcaModel_pickle_file+\"'))\" \n self.selectorfile += '\\\\n'\n self.selectorfile += ' bpca_features = '+str(bpca_features)\n self.selectorfile += '\\\\n'\n self.selectorfile += ' apca_features = '+str(apca_features)\n self.selectorfile += '\\\\n'\n self.selectorfile += ' df = pcaModel.transform(df[bpca_features])'\n self.selectorfile += '\\\\n'\n self.selectorfile += ' df = pd.DataFrame(df,columns=apca_features)'\n self.selectorfile += '\\\\n'\n if(len(features) != 0) and model_type != 'BM25':\n if model_type.lower()!='anomaly_detection' and model.lower() != 'autoencoder':\n self.selectorfile += ' df = df['+str(features)+']'\n self.selectorfile += '\\\\n'\n self.selectorfile += ' return(df)'\n filename = os.path.join(deploy_path,'script','selector.py') \n f = open(filename, \"wb\")\n self.log.info('-------> Feature Selector File Location :'+filename)\n f.write(str(self.selectorfile).encode('utf8'))\n f.close() \n featurefile = 'import json' \n featurefile +='\\\\n' \n featurefile += 'def getfeatures():' \n featurefile +='\\\\n'\n featurefile +=' try:' \n featurefile +='\\\\n'\n featurelist = []\n if 'profiler' in config:\n if 'input_features_type' in config['profiler']:\n inputfeatures = config['profiler']['input_features_type']\n for x in inputfeatures:\n featurelt={}\n featurelt['feature'] = x\n print(x,inputfeatures[x])\n if x == targetFeature: \n featurelt['Type'] = 'Target'\n else:\n if inputfeatures[x] in ['int','int64','float','float64']: \n featurelt['Type'] = 'Numeric'\n elif inputfeatures[x] == 'object':\n featurelt['Type'] = 'Text'\n elif inputfeatures[x] == 'category': \n featurelt['Type'] = 'Category' \n else:\n featurelt['Type'] = 'Unknown' \n featurelist.append(featurelt)\n \n featurefile +=' features = '+str(featurelist)\n featurefile +='\\\\n'\n featurefile +=' outputjson = {\"status\":\"SUCCESS\",\"features\":features}'\n featurefile +='\\\\n'\n featurefile +=' output = json.dumps(outputjson)' \n featurefile +='\\\\n'\n featurefile +=' print(\"Features:\",output)' \n featurefile +='\\\\n'\n featurefile +=' return(output)' \n featurefile +='\\\\n'\n featurefile +=' except Exception as e:' \n featurefile +='\\\\n'\n featurefile +=' output = {\"status\":\"FAIL\",\"message\":str(e).strip(\\\\'\"\\\\')}'\n featurefile +='\\\\n'\n featurefile +=' print(\"Features:\",json.dumps(output))' \n featurefile +='\\\\n'\n featurefile +=' return (json.dumps(output))' \n featurefile +='\\\\n'\n featurefile +='if __name__ == \"__main__\":' \n featurefile +='\\\\n'\n featurefile +=' output = getfeatures()' \n filename = os.path.join(deploy_path,'featureslist.py') \n f = open(filename, \"wb\")\n f.write(str(featurefile).encode('utf8'))\n f.close() \n\ndef create_init_function_for_classification(self,modelfile,classes,learner_type,scoreParam,loss_matrix,optimizer,preprocessing_pipe,modelName,model_type,imageconfig):\n self.modelfile += ' def __init__(self):'\n self.modelfile += '\\\\n'\n if (learner_type == 'ML' and model_type.lower()=='anomaly_detection' and modelName.lower()==\"autoencoder\"):\n modelfile=modelfile.replace('.sav','')\n self.modelfile+=\" self.model = tf.keras.models.load_model(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'))\"\n self.modelfile += '\\\\n'\n elif(learner_type == 'TextDL' or learner_type == 'DL'):\n if modelName.lower() == 'googlemodelsearch':\n self.modelfile += ' import autokeras as ak'\n self.modelfile += '\\\\n'\n self.modelfile += \" self.model = load_model(os.path.join(os.path.dirname(__file__),'..','model','modelsearch_rootdir','saved_model_onnx.onnx'))\" \n self.modelfile += '\\\\n' \n else:\n if scoreParam == 'recall':\n self.modelfile += \" self.model = load_model(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'),custom_objects={'recall': recall_m},compile=False)\"\n self.modelfile += '\\\\n'\n self.modelfile += ' self.model.compile(loss=\\\\''+loss_matrix+'\\\\',optimizer=\\\\''+optimizer+'\\\\', metrics=[recall_m])'\n self.modelfile += '\\\\n'\n elif scoreParam == 'precision':\n self.modelfile += \" self.model = load_model(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'),custom_objects={'precision': precision_m},compile=False)\"\n self.modelfile += '\\\\n'\n self.modelfile += ' self.model.compile(loss=\\\\''+loss_matrix+'\\\\',optimizer=\\\\''+optimizer+'\\\\', metrics=[precision_m])'\n self.modelfile += '\\\\n'\n elif scoreParam == 'roc_auc':\n self.modelfile += \" self.model = load_model(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'),compile=False)\"\n self.modelfile += '\\\\n'\n self.modelfile += ' self.model.compile(loss=\\\\''+loss_matrix+'\\\\',optimizer=\\\\''+optimizer+'\\\\', metrics=[tf.keras.metrics.AUC()])'\n self.modelfile += '\\\\n'\n elif scoreParam == 'f1_score':\n self.modelfile += \" self.model = load_model(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'),custom_objects={'f1_score': f1_m},", "instruction": "", "output": "" }, { "input": "compile=False)\"\n self.modelfile += '\\\\n'\n self.modelfile += ' self.model.compile(loss=\\\\''+loss_matrix+'\\\\',optimizer=\\\\''+optimizer+'\\\\', metrics=[f1_m])'\n self.modelfile += '\\\\n'\n elif scoreParam == 'r2':\n self.modelfile += \" self.model = load_model(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'),custom_objects={'r2': r_square},compile=False)\"\n self.modelfile += '\\\\n'\n self.modelfile += ' self.model.compile(loss=\\\\''+loss_matrix+'\\\\',optimizer=\\\\''+optimizer+'\\\\', metrics=[r_square])'\n self.modelfile += '\\\\n'\n elif scoreParam == 'rmse':\n self.modelfile += \" self.model = load_model(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'),custom_objects={'rmse': rmse_m},compile=False)\"\n self.modelfile += '\\\\n'\n self.modelfile += ' self.model.compile(loss=\\\\''+loss_matrix+'\\\\',optimizer=\\\\''+optimizer+'\\\\', metrics=[rmse_m])'\n self.modelfile += '\\\\n'\n elif scoreParam == 'mse':\n self.modelfile += \" self.model = load_model(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'))\"\n self.modelfile += '\\\\n'\n elif scoreParam == 'mae':\n self.modelfile += \" self.model = load_model(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'))\" \n self.modelfile += '\\\\n'\n \n elif scoreParam == 'accuracy':\n self.modelfile += \" self.model = load_model(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'))\" \n self.modelfile += '\\\\n'\n else:\n self.modelfile += \" self.model = load_model(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'))\" \n self.modelfile += '\\\\n'\n elif(learner_type == 'Text Similarity'):\n self.modelfile += \" self.preprocessing = joblib.load(os.path.join(os.path.dirname(__file__),'..','model','\"+preprocessing_pipe+\"'))\"\n self.modelfile += '\\\\n'\n self.modelfile += \" self.model = load_model(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'), custom_objects={'cosine_distance': cosine_distance, 'cos_dist_output_shape': cos_dist_output_shape})\"\n self.modelfile += '\\\\n'\n elif(learner_type in ['similarityIdentification','contextualSearch']):\n if scoreParam == 'VectorDB Cosine':\n vectorfiledbname = 'trainingdataVecDB'\n self.modelfile += f\"\\\\\n \\\\n persist_directory = os.path.join(os.path.dirname(__file__),'..','data')\\\\\n \\\\n client = chromadb.PersistentClient(path=persist_directory)\\\\\n \\\\n self.collection_name = '{vectorfiledbname}'\\\\\n \\\\n self.collection = client.get_collection(self.collection_name)\\\\n\"\n\n else:\n self.modelfile += \" self.train_input = pd.read_csv(os.path.join(os.path.dirname(__file__),'..','data','trainingdata.csv'))\\\\n\\\\n\"\n elif(learner_type == 'ImageClassification'):\n self.modelfile += ' self.config='+str(imageconfig) \n self.modelfile += '\\\\n'\n if(modelName.lower() == 'densenet'):\n self.modelfile += ' baseModel = tf.keras.applications.DenseNet121(weights=\"imagenet\", include_top=False, input_tensor=Input(shape=(self.config[\\\\'img_width\\\\'],self.config[\\\\'img_height\\\\'],self.config[\\\\'img_channel\\\\'])))'\n else:\n self.modelfile += ' baseModel = tensorflow.keras.applications.InceptionV3(weights=\"imagenet\", include_top=False, input_tensor=Input(shape=(self.config[\\\\'img_width\\\\'],self.config[\\\\'img_height\\\\'],self.config[\\\\'img_channel\\\\'])))'\n self.modelfile += '\\\\n'\n self.modelfile += ' headModel = baseModel.output'\n self.modelfile += '\\\\n'\n self.modelfile += ' headModel = Flatten(name=\"flatten\")(headModel)'\n self.modelfile += '\\\\n'\n self.modelfile += ' headModel = Dense(1024, activation=\\\\'relu\\\\')(headModel)'\n self.modelfile += '\\\\n'\n self.modelfile += ' headModel = Dropout(0.5)(headModel)'\n self.modelfile += '\\\\n'\n self.modelfile += ' headModel = Dense(2, activation=\\\\'sigmoid\\\\')(headModel)'\n self.modelfile += '\\\\n'\n self.modelfile += ' headModel = self.model = Model(inputs=baseModel.input, outputs=headModel)'\n self.modelfile += '\\\\n'\n self.modelfile += ' opt = Adam(lr=self.config[\\\\'lr\\\\'])'\n self.modelfile += '\\\\n'\n self.modelfile += ' self.model.compile(loss=\"binary_crossentropy\", optimizer=opt, metrics=[\"accuracy\"])'\n self.modelfile += '\\\\n'\n self.modelfile += \" self.model.load_weights(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'))\"\n self.modelfile += '\\\\n'\n elif(learner_type == 'objectDetection'):\n self.modelfile += \" self.MODEL_LOCATION = os.path.join(os.path.dirname(__file__),'..','model')\\\\n\"\n self.modelfile += ' PATH_TO_CFG = self.MODEL_LOCATION+\"/export/pipeline.config\"\\\\n'\n self.modelfile += ' PATH_TO_CKPT = self.MODEL_LOCATION+\"/export/checkpoint/\"\\\\n'\n self.modelfile += ' PATH_TO_LABELS = self.MODEL_LOCATION+\"/export/label_map.pbtxt\"\\\\n'\n self.modelfile += ' configs = config_util.get_configs_from_pipeline_file(PATH_TO_CFG)\\\\n'\n self.modelfile += ' self.detection_model = model_builder.build(model_config=configs[\"model\"], is_training=False)\\\\n'\n self.modelfile += ' ckpt = tf.compat.v2.train.Checkpoint(model=self.detection_model)\\\\n'\n self.modelfile += ' ckpt.restore(os.path.join(PATH_TO_CKPT, \"ckpt-0\")).expect_partial()\\\\n'\n self.modelfile += ' self.category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS,\\\\\n use_display_name=True)\\\\n'\n elif learner_type == 'TS' and (modelName.lower() == 'lstm' or modelName.lower() == 'mlp'): \n self.modelfile += \" self.model = load_model(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'))\"\n self.modelfile += '\\\\n'\n elif modelName.lower() == 'neural architecture search':\n self.modelfile += ' import autokeras as ak'\n self.modelfile += '\\\\n'\n self.modelfile += \" self.model = load_model(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'),custom_objects=ak.CUSTOM_OBJECTS)\" \n self.modelfile += '\\\\n' \n else:\n self.modelfile += \" self.model = joblib.load(os.path.join(os.path.dirname(__file__),'..','model','\"+modelfile+\"'))\"\n self.modelfile += '\\\\n'\n \ndef create_predict(self,learner_type,method,model,model_type,threshold,firstDocFeature,secondDocFeature,padding_length,optimizationmethod,sessonal_freq,additional_regressors,feature,modelFeatures,indexFeature,lag_order,scalertransformationFile,datetimeFeature,scoreParam=None):\n self.modelfile += ' def predict(self,X,features_names):'\n self.modelfile += '\\\\n'\n \n if (learner_type == 'ML' and model_type.lower()=='anomaly_detection' and model.lower()==\"autoencoder\"): \n \n self.modelfile += f\" X=X[{feature}]\\\\n\"\n self.modelfile += f\" X = np.asarray(X).astype('float32')\\\\n\" \n self.modelfile += f\" reconstructed = self.model.predict(X)\\\\n\"\n self.modelfile += f\" predict_loss = tf.keras.losses.mae(reconstructed,X)\\\\n\"\n self.modelfile += ' max_threshold = np.mean(predict_loss) + 2*np.std(predict_loss)\\\\n'\n self.modelfile += ' min_threshold = np.mean(predict_loss) - 2*np.std(predict_loss)\\\\n'\n self.modelfile += ' prediction_df = pd.DataFrame()\\\\n'\n self.modelfile += ' prediction_df[\"loss\"] = predict_loss\\\\n'\n self.modelfile += ' prediction_df[\"max_threshold\"] = max_threshold\\\\n'\n self.modelfile += ' prediction_df[\"min_threshold\"] = min_threshold\\\\n'\n self.modelfile += ' prediction_df[\"anomaly\"] = np.where((prediction_df[\"loss\"] > prediction_df[\"max_threshold\"]) | (prediction_df[\"loss\"] <= prediction_df[\"min_threshold\"]), True, False)\\\\n'\n self.modelfile += ' return prediction_df\\\\n'\n \n \n elif(learner_type == 'RecommenderSystem'):\n self.modelfile += ' predictions = []'\n self.modelfile += '\\\\n'\n self.modelfile += ' for index,row in X.iterrows():'\n self.modelfile += '\\\\n'\n self.modelfile += ' score = self.model.predict(int(row[\"uid\"]),int(row[\"iid\"]))'\n self.modelfile += '\\\\n'\n self.modelfile += ' predictions.append(score.est)'\n self.modelfile += '\\\\n'\n self.modelfile += ' return predictions' \n elif(learner_type in ['similarityIdentification','contextualSearch']):\n tfeatures = list(modelFeatures.split(\",\"))\n if indexFeature != '' and indexFeature != 'NA':\n ifeatures = indexFeature.split(\",\")\n for ifes in ifeatures: \n if ifes not in tfeatures:\n tfeatures.append(ifes) \n if model_type == 'BM25':\n self.modelfile += f\"\\\\n\\\\\n tokenized_corpus =[doc.split(' ') for doc in self.train_input.tokenize]\\\\n\\\\\n bm25 = BM25Okapi(tokenized_corpus)\\\\n\\\\\n tokenized_query = [doc.split(' ') for doc in X.tokenize]\\\\n\\\\\n logcnt = 5\\\\n\\\\\n output = []\\\\n\\\\\n for query in tokenized_query:\\\\n\\\\\n doc_scores = bm25.get_scores(query)\\\\n\\\\\n related_docs_indices = np.argsort(doc_scores)[::-1][:logcnt]\\\\n\\\\\n x = self.train_input[{tfeatures}].loc[self.train_input.index[related_docs_indices]]\\\\n\\\\\n x['Score'] = doc_scores[related_docs_indices]\\\\n\\\\\n x['Score'] = round(x['Score'],2).astype(str)+'%'\\\\n\\\\\n output.append(x)\\\\n\\\\\n return output\\\\n\"\n elif scoreParam == 'VectorDB Cosine':\n featuresVecDB = modelFeatures.split(\",\")\n self.modelfile += ' logcnt = 5\\\\n'\n self.modelfile += f\" columns = {featuresVecDB}\\\\n\"\n self.modelfile += f\"\\\\\n \\\\n output = []\\\\\n \\\\n for rowindex, row in X.iterrows():\\\\\n \\\\n queryembedding = X.iloc[rowindex:rowindex+1].to_numpy()\\\\\n \\\\n results = self.collection.query(\\\\\n \\\\n query_embeddings=queryembedding.tolist(),\\\\\n \\\\n n_results=logcnt\\\\\n \\\\n )\\\\\n \\\\n x = pd.DataFrame(columns=columns)\\\\\n \\\\n for i in range(0, len(results['ids'][0])):\\\\\n \\\\n documentAry = results['documents'][0][i]\\\\\n \\\\n documentAry = documentAry.split(' ~&~ ')\\\\\n \\\\n for j in range(0, len(documentAry)):\\\\\n \\\\n x.at[i,columns[j]] = documentAry[j]\\\\\n \\\\n x.at[i,'Score'] = results['distances'][0][i]\\\\\n \\\\n output.append(x)\\\\\n \\\\n return output\"\n else:\n self.modelfile += ' columns = self.train_input.columns.tolist()\\\\n'\n self.modelfile += ' logcnt = 5\\\\n'\n self.modelfile += f\" train_input = self.train_input[{tfeatures}]\\\\n\"\n for tf in tfeatures:\n self.modelfile += f\" columns.remove('{tf}')\\\\n\"\n self.modelfile += f\"\\\\\n \\\\n results = cosine_similarity(self.train_input[columns],X)\\\\\n \\\\n output = []\\\\\n \\\\n for i in range(results.shape[1]):\\\\\n \\\\n related_docs_indices = results[:,i].argsort(axis=0)[:-(int(logcnt) + 1):-1]\\\\\n \\\\n x=self.train_input[{tfeatures}].loc[self.train_input.index[related_docs_indices]]\\\\\n \\\\n scores = []\\\\\n \\\\n for j in range(0,logcnt):\\\\\n \\\\n scores.append(str(round((results[related_docs_indices][j][i])*100))+'%')\\\\\n \\\\n x['Score'] = scores\\\\\n \\\\n output.append(x)\\\\\n \\\\n return output\"\n elif(learner_type == 'Text Similarity'):\n self.modelfile += ' X[\"'+firstDocFeature+'\"] = X[\"'+firstDocFeature+'\"].astype(str)'\n self.modelfile += '\\\\n' \n self.modelfile += ' X[\"'+secondDocFeature+'\"] = X[\"'+secondDocFeature+'\"].astype(str)'\n self.modelfile += '\\\\n' \n self.modelfile += ' test_sentence1 = self.preprocessing.texts_to_sequences(X[\"'+firstDocFeature+'\"].values)' ", "instruction": "", "output": "" }, { "input": "\n self.modelfile += '\\\\n' \n self.modelfile += ' test_sentence2 = self.preprocessing.texts_to_sequences(X[\"'+secondDocFeature+'\"].values)' \n self.modelfile += '\\\\n'\n self.modelfile += ' test_sentence1 = pad_sequences(test_sentence1, maxlen='+str(padding_length)+', padding=\\\\'post\\\\')' \n self.modelfile += '\\\\n'\n self.modelfile += ' test_sentence2 = pad_sequences(test_sentence2, maxlen='+str(padding_length)+', padding=\\\\'post\\\\')' \n self.modelfile += '\\\\n'\n self.modelfile += ' prediction = self.model.predict([test_sentence1, test_sentence2 ])' \n self.modelfile += '\\\\n'\n self.modelfile += ' return(prediction)' \n self.modelfile += '\\\\n'\n elif(learner_type == 'ImageClassification'): \n self.modelfile += ' predictions = []' \n self.modelfile += '\\\\n'\n self.modelfile += ' for index, row in X.iterrows(): ' \n self.modelfile += '\\\\n'\n self.modelfile += ' img = cv2.imread(row[\\\\'imagepath\\\\'])' \n self.modelfile += '\\\\n'\n self.modelfile += ' img = cv2.resize(img, (self.config[\\\\'img_width\\\\'],self.config[\\\\'img_height\\\\']))' \n self.modelfile += '\\\\n'\n self.modelfile += ' img = image.img_to_array(img)' \n self.modelfile += '\\\\n'\n self.modelfile += ' img = np.expand_dims(img, axis=0)' \n self.modelfile += '\\\\n'\n self.modelfile += ' img = img/255' \n self.modelfile += '\\\\n'\n self.modelfile += ' prediction = self.model.predict(img)' \n self.modelfile += '\\\\n'\n self.modelfile += ' prediction = np.argmax(prediction,axis=1)' \n self.modelfile += '\\\\n'\n self.modelfile += ' predictions.append(prediction[0])' \n self.modelfile += '\\\\n'\n self.modelfile += ' return(predictions)' \n self.modelfile += '\\\\n'\n elif(learner_type == 'objectDetection'): \n self.modelfile += ' @tf.function\\\\n'\n self.modelfile += ' def detect_fn(image):\\\\n'\n self.modelfile += ' image, shapes = self.detection_model.preprocess(image)\\\\n'\n self.modelfile += ' prediction_dict = self.detection_model.predict(image, shapes)\\\\n'\n self.modelfile += ' detections = self.detection_model.postprocess(prediction_dict, shapes)\\\\n'\n self.modelfile += ' return detections\\\\n'\n self.modelfile += ' def load_image_into_numpy_array(path):\\\\n'\n self.modelfile += ' return np.array(Image.open(path))\\\\n'\n self.modelfile += ' imageLocation = []\\\\n'\n self.modelfile += ' for i, row in X.iterrows():\\\\n'\n self.modelfile += ' if (\"confidance\" in row) and row[\"confidance\"] <= 1.0:\\\\n'\n self.modelfile += ' confidance = row[\"confidance\"]\\\\n'\n self.modelfile += ' else:\\\\n'\n self.modelfile += ' confidance = 0.8\\\\n'\n self.modelfile += ' imageName = str(Path(row[\"imagepath\"]).stem)+\"_output\"+str(Path(row[\"imagepath\"]).suffix)\\\\n'\n self.modelfile += ' image_np = load_image_into_numpy_array(row[\"imagepath\"])\\\\n'\n self.modelfile += ' input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)\\\\n'\n self.modelfile += ' detections = detect_fn(input_tensor)\\\\n'\n self.modelfile += ' num_detections = int(detections.pop(\"num_detections\"))\\\\n'\n self.modelfile += ' detections = {key: value[0, :num_detections].numpy()\\\\n\\\\\n for key, value in detections.items()}\\\\n'\n self.modelfile += ' detections[\"num_detections\"] = num_detections\\\\n'\n self.modelfile += ' detections[\"detection_classes\"] = detections[\"detection_classes\"].astype(np.int64)\\\\n'\n self.modelfile += ' label_id_offset = 1\\\\n'\n self.modelfile += ' image_np_with_detections = image_np.copy()\\\\n'\n self.modelfile += ' viz_utils.visualize_boxes_and_labels_on_image_array(\\\\n\\\\\n image_np_with_detections,\\\\n\\\\\n detections[\"detection_boxes\"],\\\\n\\\\\n detections[\"detection_classes\"]+label_id_offset,\\\\n\\\\\n detections[\"detection_scores\"],\\\\n\\\\\n self.category_index,\\\\n\\\\\n use_normalized_coordinates=True,\\\\n\\\\\n max_boxes_to_draw=200,\\\\n\\\\\n min_score_thresh=confidance,\\\\n\\\\\n agnostic_mode=False)\\\\n'\n\n self.modelfile += ' plt.figure()\\\\n'\n self.modelfile += ' plt.imsave(os.path.join(self.MODEL_LOCATION,imageName), image_np_with_detections)\\\\n'\n self.modelfile += ' imageLocation.append(os.path.join(self.MODEL_LOCATION,imageName))\\\\n'\n self.modelfile += ' plt.show()\\\\n'\n self.modelfile += ' return imageLocation\\\\n'\n else:\n if(learner_type == 'DL' and model != 'Neural Network'):\n self.modelfile += ' X = np.expand_dims(X, axis=2)' \n self.modelfile += '\\\\n' \n if(learner_type == 'TextDL'):\n self.modelfile += ' return pd.DataFrame(np.argmax(self.model.predict(X),axis=1))'\n self.modelfile += '\\\\n'\n elif(learner_type == 'TextML'):\n self.modelfile += ' return pd.DataFrame(self.model.predict_proba(X),columns=self.model.classes_)'\n self.modelfile += '\\\\n'\n elif(learner_type == 'DL' and model_type == 'Classification'):\n self.modelfile += ' X = X.astype(np.float32)'\n self.modelfile += '\\\\n' \n self.modelfile += ' return pd.DataFrame(np.argmax(self.model.predict(X),axis=1))'\n self.modelfile += '\\\\n'\n else:\n if(model_type == 'Classification' or model_type == 'TLClassification'):\n if model == 'Neural Architecture Search':\n self.modelfile += ' X = X.astype(np.float32)'\n self.modelfile += '\\\\n' \n self.modelfile += ' return pd.DataFrame(self.model.predict(X))'\n self.modelfile += '\\\\n'\n else: \n if optimizationmethod == 'genetic':\n self.modelfile += '\\\\n'\n self.modelfile += ' try:'\n self.modelfile += '\\\\n'\n self.modelfile += ' return pd.DataFrame(self.model.predict_proba(X))'\n self.modelfile += '\\\\n'\n self.modelfile += ' except:'\n self.modelfile += '\\\\n'\n self.modelfile += ' return pd.DataFrame(self.model.predict(X))'\n else:\n self.modelfile += ' X = X.astype(np.float32)'\n self.modelfile += '\\\\n'\n if model.lower() == 'deep q network' or model.lower() == 'dueling deep q network': \n self.modelfile += ' q, _ = self.model(np.array(X), step_type=constant([time_step.StepType.FIRST] * np.array(X).shape[0]), training=False)'\n self.modelfile += '\\\\n'\n self.modelfile += ' return pd.DataFrame(q.numpy())' \n else:\n self.modelfile += ' return pd.DataFrame(self.model.predict_proba(X), columns=self.model.classes_)'\n self.modelfile += '\\\\n'\n elif model_type == 'Regression' and model == 'NAS':\n self.modelfile += \\\\\n\"\"\"\n X = X.astype(np.float32)\n return self.model.predict(X)\n\"\"\" \n elif(learner_type == 'TS'):\n if model.lower() == 'fbprophet':\n self.modelfile += ' sessonal_freq=\"'+str(sessonal_freq)+'\"'\n self.modelfile += '\\\\n'\n self.modelfile += ' ts_prophet_future = self.model.make_future_dataframe(periods=int(X[\"noofforecasts\"][0]),freq=sessonal_freq,include_history = False)'\n self.modelfile += '\\\\n'\n if (additional_regressors):\n self.modelfile += '\\\\n'\n self.modelfile += ' additional_regressors='+str(additional_regressors)\n self.modelfile += '\\\\n'\n self.modelfile += ' ts_prophet_future[additional_regressors] = dataFrame[additional_regressors]'\n self.modelfile += '\\\\n'\n self.modelfile += ' ts_prophet_future.reset_index(drop=True)'\n self.modelfile += '\\\\n'\n self.modelfile += ' ts_prophet_future=ts_prophet_future.dropna()'\n self.modelfile += '\\\\n'\n self.modelfile += ' train_forecast = self.model.predict(ts_prophet_future)'\n self.modelfile += '\\\\n'\n self.modelfile += ' prophet_forecast_tail=train_forecast[[\\\\'ds\\\\', \\\\'yhat\\\\', \\\\'yhat_lower\\\\',\\\\'yhat_upper\\\\']].tail( int(X[\"noofforecasts\"][0]))'\n self.modelfile += '\\\\n'\n self.modelfile += ' return(prophet_forecast_tail)'\n elif model.lower() == 'lstm' or model.lower() == 'mlp':\n self.modelfile += ' lag_order='+str(lag_order)\n self.modelfile += '\\\\n'\n self.modelfile += ' xt = X.values'\n self.modelfile += '\\\\n' \n scalertransformationFile = scalertransformationFile.split('\\\\\\\\')[-1]\n self.modelfile += ' loaded_scaler_model = joblib.load(os.path.join(os.path.dirname(__file__),\\\\'..\\\\',\\\\'model\\\\',\\\\''+scalertransformationFile+'\\\\'))' \n self.modelfile += '\\\\n' \n self.modelfile += ' xt = xt.astype(\\\\'float32\\\\')'\n self.modelfile += '\\\\n' \n self.modelfile += ' xt = loaded_scaler_model.transform(xt)' \n self.modelfile += '\\\\n' \n self.modelfile += ' noOfPredictions = 10'\n self.modelfile += '\\\\n' \n self.modelfile += ' pred_data = xt'\n self.modelfile += '\\\\n' \n self.modelfile += ' y_future = []'\n self.modelfile += '\\\\n'\n self.modelfile += ' for i in range(noOfPredictions):'\n self.modelfile += '\\\\n' \n if len(feature) == 1:\n self.modelfile += ' pred_data = pred_data[-lag_order:]'\n self.modelfile += '\\\\n'\n if model.lower() == 'mlp':\n self.modelfile += ' pred_data = pred_data.reshape((1,lag_order))'\n else:\n self.modelfile += ' pred_data = pred_data.reshape((1,lag_order,1))' \n self.modelfile += '\\\\n'\n self.modelfile += ' pred = self.model.predict(pred_data)' \n self.modelfile += '\\\\n'\n self.modelfile += ' predoutput = loaded_scaler_model.inverse_transform(pred) ' \n self.modelfile += '\\\\n' \n self.modelfile += ' y_future.append(predoutput.flatten()[-1])' \n self.modelfile += '\\\\n' \n self.modelfile += ' pred_data = np.append(pred_data,pred)' \n self.modelfile += '\\\\n'\n self.modelfile += ' pred = pd.DataFrame(index=range(0,len(y_future)),columns='+str(feature)+')' \n self.modelfile += '\\\\n'\n self.modelfile += ' for i in range(0, len(y_future)):' \n self.modelfile += '\\\\n' \n self.modelfile += ' pred.iloc[i] = y_future[i]'\n self.modelfile += '\\\\n'\n self.modelfile += ' return pred'\n else:\n self.modelfile += ' pdata = pred_data[-lag_order:]'\n self.modelfile += '\\\\n'\n self.modelfile += ' pdata = pdata.reshape((1,lag_order,'+str(len(feature))+'))'\n self.modelfile += '\\\\n'\n self.modelfile += ' pred = self.model.predict(pdata)' \n self.modelfile += '\\\\n'\n self.modelfile += ' predoutput = loaded_scaler_model.inverse_transform(pred) ' \n self.modelfile += '\\\\n' \n self.modelfile += ' y_future.append(predoutput)' \n self.modelfile += '\\\\n' \n self.modelfile += ' pred_data = np.append(pred_data,pred,axis=0)' \n self.modelfile += '\\\\n'\n self.modelfile += ' pred = pd.DataFrame(index=range(0,len(y_future)),columns='+str(feature)+')' \n self.modelfile += '\\\\n'\n", "instruction": "", "output": "" }, { "input": " self.modelfile += ' for i in range(0, len(y_future)):' \n self.modelfile += '\\\\n' \n self.modelfile += ' pred.iloc[i] = y_future[i]'\n self.modelfile += '\\\\n'\n self.modelfile += ' return pred' \n else:\n self.modelfile += ' return self.model.predict(n_periods=int(X[\"noofforecasts\"][0]))' \n else: \n if model == 'KaplanMeierFitter':\n self.modelfile += '\\\\n'\n self.modelfile += ' res = self.model.predict(X[\\\\''+feature[0]+'\\\\'].astype(int))'\n self.modelfile += '\\\\n'\n self.modelfile += ' if isinstance(res, pd.DataFrame):\\\\n'\n self.modelfile += ' return res.values.reshape(1,-1)\\\\n'\n self.modelfile += ' else:\\\\n'\n self.modelfile += ' return np.array([res])\\\\n'\n elif model == 'COX':\n self.modelfile += ' res = []\\\\n'\n self.modelfile += ' for idx,row in X.iterrows():\\\\n'\n self.modelfile += ' res.append(self.model.predict_survival_function(X, times=row[self.model.duration_col])[idx].values[0])\\\\n'\n self.modelfile += ' return pd.DataFrame(res)'\n #self.modelfile += ' return self.model.predict_survival_function(X, times=X[self.model.duration_col])'\n self.modelfile += '\\\\n' \n elif(learner_type == 'DL' and model_type in ['Classification','Regression']):\n self.modelfile += ' X = X.astype(np.float32)'\n self.modelfile += '\\\\n' \n self.modelfile += ' return self.model.predict(X).reshape(1, -1)'\n self.modelfile += '\\\\n'\n elif (model_type == 'Clustering' and model == 'DBSCAN'):\n self.modelfile += ' return self.model.fit_predict(X)'\n elif(model_type.lower() == 'anomaly_detection' and model.lower() == 'dbscan'): \n self.modelfile += \" pred=self.model.fit_predict(X)\\\\n\"\n self.modelfile += \" X.loc[:,'cluster'] = self.model.labels_ \\\\n\" \n self.modelfile += ' return X\\\\n'\n elif model_type.lower() == 'anomaly_detection':\n self.modelfile += ' X = X.astype(np.float32)\\\\n'\n self.modelfile += ' return self.model.predict(X)' \n else:\n if model_type != 'Clustering':\n self.modelfile += ' X = X.astype(np.float32)'\n self.modelfile += '\\\\n' \n #self.modelfile += ' return self.model.predict(X).reshape(1, -1)'\n self.modelfile += \\\\\n\"\"\"\n if isinstance(self.model, LatentDirichletAllocation):\n output = np.matrix(self.model.transform(X)).argmax(axis=1)\n return output.flatten().tolist()\n return self.model.predict(X).reshape(1, -1)\n\"\"\"\n \n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nfrom importlib.metadata import version\nimport sys\nimport os\ndef requirementfile(deploy_path,model,textFeatures,learner_type):\n print('hola', model)\n modules = ['pandas','numpy','alibi','matplotlib','joblib','shap','ipython','category_encoders','scikit-learn','word2number','flask_restful','evidently','Flask-Cors']\n requires = ''\n for mod in modules:\n requires += f\"{mod}=={version(mod)}\\\\n\"\n if len(textFeatures) > 0:\n tmodules = ['spacy','nltk','textblob','demoji','beautifulsoup4','text-unidecode','pyspellchecker','contractions','protobuf']\n for mod in tmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\" \n if model == 'Extreme Gradient Boosting (XGBoost)':\n mmodules = ['xgboost']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\" \n if model == 'Light Gradient Boosting (LightGBM)':\n mmodules = ['lightgbm']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\" \n if model == 'Categorical Boosting (CatBoost)':\n mmodules = ['catboost']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\" \n if model.lower() == 'arima':\n mmodules = ['pmdarima']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\"\n if model.lower() == 'fbprophet':\n mmodules = ['prophet']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\" \n if model.lower() == 'lstm' or model.lower() == 'mlp' or learner_type =='DL':\n mmodules = ['tensorflow']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\" \n if model.lower() in ['cox', 'kaplanmeierfitter']: #bug 12833\n mmodules = ['lifelines']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\"\n if model.lower() == 'sentencetransformer': #bug 12833\n mmodules = ['sentence_transformers']\n for mod in mmodules:\n requires += f\"{mod}=={version(mod)}\\\\n\" \n filename = os.path.join(deploy_path,'requirements.txt')\n f = open(filename, \"wb\")\n f.write(str(requires).encode('utf8'))\n f.close() \n \n \n \n \n \n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport platform\nimport json\nimport shutil\nimport logging\n\nclass outputFormatter:\n def __init__(self):\n self.log = logging.getLogger('eion')\n self.log.info('========> Inside Output Formatter') \n \n def crate_output_format_file(self,deploy_path,learner_type,modelType,model,output_label,threshold,trained_data_file,dictDiffCount,targetFeature,features,datetimeFeature):\n self.output_formatfile = 'import json' \n self.output_formatfile += '\\\\n'\n self.output_formatfile += 'import numpy as np'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += 'import pandas as pd'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += 'import os'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += 'from pathlib import Path'\n self.output_formatfile += '\\\\n'\n if((model.lower() in ['autoencoder','dbscan']) and modelType.lower()==\"anomaly_detection\"):\n self.output_formatfile += 'from script.aion_granularity import aion_gettimegranularity'\n self.output_formatfile += '\\\\n'\n \n self.output_formatfile += 'class output_format(object):'\n self.output_formatfile += '\\\\n'\n if(model == 'VAR'):\n self.output_formatfile += ' def invertTransformation(self,predictions):'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' datasetdf = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath(__file__)),\"..\",\"data\",\"trainingdata.csv\"))'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' dictDiffCount = '+str(dictDiffCount)\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' targetFeature = \"'+str(targetFeature)+'\"'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' columns = targetFeature.split(\",\")'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' pred = pd.DataFrame(index=range(0,len(predictions)),columns=columns)'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' for j in range(0,len(columns)):'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' for i in range(0, len(predictions)):'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' pred.iloc[i][j] = round(predictions[i][j],2)'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' prediction = pred'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' for col in columns:'\n self.output_formatfile += '\\\\n' \n self.output_formatfile += ' if col in dictDiffCount:'\n self.output_formatfile += '\\\\n' \n self.output_formatfile += ' if dictDiffCount[col]==2:'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' prediction[col] = (datasetdf[col].iloc[-1]-datasetdf[col].iloc[-2]) + prediction[col].cumsum()'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' prediction[col] = datasetdf[col].iloc[-1] + prediction[col].cumsum()'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' prediction = pred'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' return(prediction)'\n self.output_formatfile += '\\\\n'\n self.log.info(\"op:modelType: \\\\n\"+str(modelType))\n if((model.lower() in ['autoencoder','dbscan']) and modelType.lower()==\"anomaly_detection\"):\n # if modelType == 'anomaly_detection':\n self.output_formatfile += ' def find_point_subsequence_anomalies(self,datetime_column,dataframe=None):' \n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' try:' \n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' dataframe[datetime_column] = pd.to_datetime(dataframe[datetime_column]) '\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' aion_gettimegranularity_obj=aion_gettimegranularity(dataframe,datetime_column) '\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' anomaly_info_df=aion_gettimegranularity_obj.get_granularity() '\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' except Exception as e:'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' print(f\"find_point_subsequence_anomalies,: aion_gettimegranularity err msg:{e} \")\\\\n'\n self.output_formatfile += ' return anomaly_info_df'\n self.output_formatfile += '\\\\n'\n if((model.lower() in ['autoencoder','dbscan']) and modelType.lower()==\"anomaly_detection\"): \n if (datetimeFeature!='' and datetimeFeature!='NA'):\n self.output_formatfile += ' def apply_output_format(self,df,modeloutput,datetimeFeature):'\n self.output_formatfile += '\\\\n'\n else:\n self.output_formatfile += ' def apply_output_format(self,df,modeloutput):' \n self.output_formatfile += '\\\\n'\n else:\n self.output_formatfile += ' def apply_output_format(self,df,modeloutput):' \n self.output_formatfile += '\\\\n'\n \n if modelType.lower() == 'classification':\n self.output_formatfile += ' modeloutput = round(modeloutput,2)'\n self.output_formatfile += '\\\\n'\n \n \n if(learner_type == 'ImageClassification'):\n if(str(output_label) != '{}'):\n inv_mapping_dict = {v: k for k, v in output_label.items()}\n self.output_formatfile += ' le_dict = '+ str(inv_mapping_dict)\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' predictions = []'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' for x in modeloutput:'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' x = le_dict[x]'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' predictions.append(x)'\n self.output_formatfile += '\\\\n'\n else:\n self.output_formatfile += ' predictions=modeloutput'\n self.output_formatfile += '\\\\n' \n self.output_formatfile += ' df[\\\\'prediction\\\\'] = predictions'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' outputjson = df.to_json(orient=\\\\'records\\\\')'\n self.output_formatfile += '\\\\n' \n self.output_formatfile += ' outputjson = {\"status\":\"SUCCESS\",\"data\":json.loads(outputjson)}'\n self.output_formatfile += '\\\\n' \n elif(learner_type == 'Text Similarity'):\n self.output_formatfile += ' df[\\\\'prediction\\\\'] = np.where(modeloutput > '+str(threshold)+',1,0)'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' df[\\\\'probability\\\\'] = modeloutput'\n self.output_formatfile += '\\\\n'\n self.output_formatfile += ' outputjson = df.to_json(orient=\\\\'records\\\\',double_precision=2)'\n self.output_formatfile += '\\\\n'\n self.output_formatfile", "instruction": "", "output": "" }, { "input": "+= ' outputjson = {\"status\":\"SUCCESS\",\"data\":json.loads(outputjson)}'\n self.output_formatfile += '\\\\n'\n elif(learner_type == 'TS'):\n if(model == 'VAR'):\n self.output_formatfile += ' modeloutput = ", "instruction": "", "output": "" }, { "input": "YRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nfrom pathlib import Path\nfrom AION.prediction_package.imports import importModule\nfrom AION.prediction_package.aion_prediction import aionPrediction\nfrom AION.prediction_package.utility import TAB_CHAR\nfrom AION.prediction_package import utility\nfrom AION.prediction_package.base import deployer\nfrom AION.prediction_package import common\nimport numpy as np\n\n\n\n\ndef get_deployer( params):\n\n if params['training']['algo'] == 'ARIMA':\n return arima(params)\n elif params['training']['algo'] == 'LSTM':\n return lstm(params)\n elif params['training']['algo'] == 'ENCODER_DECODER_LSTM_MVI_UVO':\n return lstmencdec_mviuvo(params)\n elif params['training']['algo'] == 'MLP':\n return mlp(params)\n elif params['training']['algo'] == 'VAR':\n return var(params)\n elif params['training']['algo'] == 'FBPROPHET':\n return fbprophet(params)\n else:\n raise ValueError(f\"Algorithm {params['training']['algo']} for time series forecasting is not supported\")\n\ndef _profiler_code(params, importer):\n \"\"\"\n This will create the profiler file based on the config file.\n separated file is created as profiler is required for input drift also.\n \"\"\"\n imported_modules = [\n {'module': 'json', 'mod_from': None, 'mod_as': None},\n {'module': 'scipy', 'mod_from': None, 'mod_as': None},\n {'module': 'joblib', 'mod_from': None, 'mod_as': None},\n {'module': 'numpy', 'mod_from': None, 'mod_as': 'np'},\n {'module': 'pandas', 'mod_from': None, 'mod_as': 'pd'},\n {'module': 'Path', 'mod_from': 'pathlib', 'mod_as': None}\n ]\n utility.import_modules(importer, imported_modules)\n if 'code' in params['profiler'].get('preprocess',{}).keys():\n code = params['profiler']['preprocess']['code']\n else:\n code = \"\"\n code += \"\"\" \n\nclass inputprofiler():\n \"\"\"\n init_code = \"\"\"\n def __init__(self):\n \"\"\"\n init_code += \"\"\"\n # preprocessing\n preprocess_path = Path(__file__).parent.parent/'model'/'preprocess_pipe.pkl'\n if not preprocess_path.exists():\n raise ValueError(f'Preprocess model file not found: {preprocess_path}')\n self.profiler = joblib.load(preprocess_path)\n \"\"\"\n run_code = \"\"\"\n def run(self,df):\n df = df.replace(r'^\\\\s*$', np.NaN, regex=True)\n \"\"\"\n if 'code' in params['profiler'].get('preprocess',{}).keys():\n run_code += \"\"\"\n df = preprocess( df)\"\"\"\n if params['profiler'].get('unpreprocessed_columns'):\n run_code += f\"\"\"\n unpreprocessed_data = df['{params['profiler']['unpreprocessed_columns'][0]}']\n df.drop(['{params['profiler']['unpreprocessed_columns'][0]}'], axis=1,inplace=True)\n \"\"\"\n if params['profiler'].get('force_numeric_conv'):\n run_code += f\"\"\"\n df[{params['profiler']['force_numeric_conv']}] = df[{params['profiler']['force_numeric_conv']}].apply(pd.to_numeric,errors='coerce')\"\"\"\n run_code += _profiler_main_code(params)\n if params['profiler'].get('unpreprocessed_columns'):\n run_code += f\"\"\"\n df['{params['profiler'].get('unpreprocessed_columns')[0]}'] = unpreprocessed_data\n\"\"\"\n run_code += \"\"\" return df\n\"\"\"\n utility.import_modules(importer, imported_modules)\n import_code = importer.getCode()\n return import_code + code + init_code + run_code\n\ndef _profiler_main_code(params):\n code = f\"\"\"\n df = self.profiler.transform(df)\n columns = {params['profiler']['output_features']}\n if isinstance(df, scipy.sparse.spmatrix):\n df = pd.DataFrame(df.toarray(), columns=columns)\n else:\n df = pd.DataFrame(df, columns=columns)\n \"\"\"\n return code\n\nclass arima( deployer):\n \n def __init__(self, params={}):\n super().__init__( params)\n self.name = 'timeseriesforecasting'\n \n def profiler_code( self):\n imported_modules = [\n {'module': 'numpy', 'mod_from': None, 'mod_as': 'np'},\n {'module': 'pandas', 'mod_from': None, 'mod_as': 'pd'},\n ]\n importer = importModule()\n utility.import_modules(importer, imported_modules)\n code = \"\"\" \n\n\nclass inputprofiler():\n\n def __init__(self):\n pass\n \n def run( self,df):\n df = df.replace(r'^\\\\s*$', np.NaN, regex=True)\n return df[['noofforecasts']]\n\"\"\"\n return importer.getCode() + code\n\n def feature_engg_code(self):\n self.importer.addModule(module='pandas',mod_as='pd')\n return f\"\"\"\nclass selector():\n\n def __init__(self):\n pass\n \n def run(self, df):\n return df\n\"\"\"\n def training_code( self):\n self.importer.addModule(module='pandas',mod_as='pd')\n self.importer.addModule(module='Path',mod_from='pathlib')\n self.importer.addModule(module='numpy',mod_as='np')\n self.importer.addModule(module='joblib')\n return f\"\"\"\nclass trainer():\n\n def __init__(self):\n model_file = (Path(__file__).parent/\"model\")/\"{self.params['training']['model_file']}\"\n if not model_file.exists():\n raise ValueError(f'Trained model file not found: {{model_file}}')\n self.model = joblib.load(model_file)\n \n def run(self,df):\n return self.model.predict(n_periods=int(df[\"noofforecasts\"][0]))\n \"\"\"\n\n def formatter_code(self):\n self.importer.addModule('json')\n self.importer.addModule('pandas', mod_as='pd')\n return \"\"\"\n\nclass output_format():\n\n def __init__( self):\n pass\n \n def run(self,raw_df,df):\n df = df.round(2)\n df = json.dumps(df.tolist())\n outputjson = {\"status\":\"SUCCESS\",\"data\":eval(df)}\n return(json.dumps(outputjson))\n\"\"\"\n\nclass lstm( deployer):\n \n def __init__(self, params={}):\n super().__init__( params)\n self.name = 'timeseriesforecasting'\n \n def profiler_code(self):\n importer = importModule()\n return _profiler_code( self.params, importer)\n\n def training_code( self):\n self.importer.addModule(module='pandas',mod_as='pd')\n self.importer.addModule(module='Path',mod_from='pathlib')\n code = f\"\"\"\nclass trainer(): \n\"\"\"\n init_code, run_code = self._get_train_code()\n return code + init_code + run_code\n\n def _get_train_code(self): \n self.importer.addModule(module='load_model',mod_from='tensorflow.keras.models')\n init_code = f\"\"\"\n def __init__( self):\n model_file = (Path(__file__).parent/\"model\")/\"{self.params['training']['model_file']}\"\n if not model_file.exists():\n raise ValueError(f'Trained model file not found: {{model_file}}')\n self.model = load_model(model_file)\n \"\"\"\n \n run_code = f\"\"\"\n def run(self, df):\n lag_order={self.params['training']['lag_order']}\n xt = df.values\n scaler_file = (Path(__file__).parent/\"model\")/\"{self.params['training']['scaler_file']}\"\n if not scaler_file.exists():\n raise ValueError(f'Scaling file not found: {{scaler_file}}')\n loaded_scaler_model = joblib.load(scaler_file)\n xt = xt.astype('float32')\n xt = loaded_scaler_model.transform(xt)\n noOfPredictions = 10\n pred_data = xt\n y_future = []\n for i in range(noOfPredictions):\n\"\"\"\n if len(self.params['selector']['output_features']) == 1:\n run_code += f\"\"\"\n pred_data = pred_data[-lag_order:]\n pred_data = pred_data.reshape((1,lag_order,1))\n pred = self.model.predict(pred_data)\n predoutput = loaded_scaler_model.inverse_transform(pred) \n y_future.append(predoutput.flatten()[-1])\n pred_data = np.append(pred_data,pred)\n pred = pd.DataFrame(index=range(0,len(y_future)),columns={self.params['selector']['output_features']})\n for i in range(0, len(y_future)):\n pred.iloc[i] = y_future[i]\n return pred\n\"\"\"\n else:\n run_code += f\"\"\"\n pdata = pred_data[-lag_order:]\n pdata = pdata.reshape((1,lag_order,{len(self.params['selector']['output_features'])}))\n pred = self.model.predict(pdata)\n predoutput = loaded_scaler_model.inverse_transform(pred)\n y_future.append(predoutput)\n pred_data = np.append(pred_data,pred,axis=0)\n pred = pd.DataFrame(index=range(0,len(y_future)),columns={self.params['selector']['output_features']})\n for i in range(0, len(y_future)):\n pred.iloc[i] = y_future[i]\n return pred\n\"\"\"\n return init_code, run_code\n\n def formatter_code(self):\n self.importer.addModule('json')\n self.importer.addModule('pandas', mod_as='pd')\n return \"\"\"\n\nclass output_format():\n\n def __init__( self):\n pass\n \n def run(self,raw_df,df):\n df = df.round(2)\n df = df.to_json(orient='records')\n outputjson = {\"status\":\"SUCCESS\",\"data\":json.loads(df)}\n return(json.dumps(outputjson))\n\"\"\"\n\nclass lstmencdec_mviuvo( deployer):\n \n def __init__(self, params={}):\n super().__init__( params)\n self.name = 'timeseriesforecasting'\n outputFeatrues = params['profiler']['output_features']\n self.targetColIndx = outputFeatrues.index(params['features']['target_feat'])\n selectedColDict = params['selector']['output_features']\n self.selectedCols = list()\n for col in selectedColDict:\n self.selectedCols.append(col)\n \n def profiler_code(self):\n importer = importModule()\n return _profiler_code( self.params, importer)\n\n def training_code( self):\n self.importer.addModule(module='pandas',mod_as='pd')\n self.importer.addModule(module='Path',mod_from='pathlib')\n code = f\"\"\"\nclass trainer(): \n\"\"\"\n init_code, run_code = self._get_train_code()\n return code + init_code + run_code\n\n def _get_train_code(self): \n self.importer.addModule(module='load_model',mod_from='tensorflow.keras.models')\n init_code = f\"\"\"\n def __init__( self):\n model_file = (Path(__file__).parent/\"model\")/\"{self.params['training']['model_file']}\"\n if not model_file.exists():\n raise ValueError(f'Trained model file not found: {{model_file}}')\n self.model = load_model(model_file)\n \"\"\"\n \n run_code = f\"\"\"\n def run(self, df):\n targetColIndx = {self.targetColIndx}\n lag_order={self.params['training']['lag_order']}\n xt = df.values\n scaler_file = (Path(__file__).parent/\"model\")/\"{self.params['training']['scaler_file']}\"\n if not scaler_file.exists():\n raise ValueError(f'Scaling file not found: {{scaler_file}}')\n loaded_scaler_model = joblib.load(scaler_file)\n xt = xt.astype('float32')\n xt = loaded_scaler_model.transform(xt)\n noOfPredictions = 10\n pred_data = xt\n y_future = []\n pdata = pred_data[-lag_order:]\n pdata = pdata.reshape((1,lag_order,{len(self.params['selector']['output_features'])}))\n pred = self.model.predict(pdata)\n pred_1d = pred.ravel()\n pdata_2d = pdata.ravel().reshape(len(pdata) * lag_order, {len(self.params['selector']['output_features'])})\n pdata_2d[:,targetColIndx] = pred_1d\n pred_2d_inv = loaded_scaler_model.inverse_transform(pdata_2d) \n predout = pred_2d_inv[:, targetColIndx] \n predout = predout.reshape(len(pred_1d),1) \n pred = pd.DataFrame(index=range(0,len(predout)),columns=['{self.params['features']['target_feat']}'])\n for i in range(0, len(predout)):\n pred.iloc[i] = predout[i]\n return pred\n\"\"\"\n return init_code, run_code\n \n def feature_engg_code(self):\n self.importer.addModule(module='pandas',mod_as='pd')\n \n return f\"\"\"\nclass selector():\n\n def __init__(self):\n pass\n \n def run(self, df):\n return df[{self.selectedCols}]\n\"\"\"\n\n def formatter_code(self):\n self.importer.addModule('json')\n self.importer.addModule('pandas', mod_as='pd')\n return \"\"\"\n\nclass output_format():\n\n def __init__( self):\n pass\n \n def run(self,raw_df,df):\n df = df.round(2)\n df = df.to_json(orient='records')\n outputjson", "instruction": "", "output": "" }, { "input": "= {\"status\":\"SUCCESS\",\"data\":json.loads(df)}\n return(json.dumps(outputjson))\n\"\"\"\n\nclass mlp( lstm):\n \n def __init__(self, params={}):\n super().__init__( params)\n self.name = 'timeseriesforecasting'\n\n def training_code( self):", "instruction": "", "output": "" }, { "input": "modelname']= str(modelname)\n\t\tself.displayjson['preprocessedData'] = str(original_data_file)\n\t\tself.displayjson['nrows'] = str(nrows)\n\t\tself.displayjson['ncols'] = str(ncols)\n\t\tself.displayjson['saved_model'] = str(saved_model)\n\t\tself.displayjson['scoreParam'] = str(scoreParam)\n\t\tself.displayjson['labelMaps'] = eval(str(labelMaps))\n\t\tself.original_data_file = original_data_file\n\t\tself.displayjson['featureReduction'] = featureReduction \n\t\tif featureReduction == 'True':\n\t\t\tself.displayjson['reduction_data_file'] = reduction_data_file\n\t\telse:\n\t\t\tself.displayjson['reduction_data_file'] = ''\n\t\tself.pred_filename = predicted_data_file\n\t\tself.profiled_data_file = profiled_data_file\n\t\tself.displayjson['predictedData'] = predicted_data_file\n\t\tself.displayjson['postprocessedData'] = profiled_data_file\n\t\t#self.trained_data_file = trained_data_file\n\t\t#self.displayjson['trainingData'] = trained_data_file\n\t\t#self.displayjson['categorialFeatures']=categoricalFeatures\n\t\t#self.displayjson['discreteFeatures']=discreteFeatures\n\t\t#self.displayjson['continuousFeatures']=numericContinuousFeatures\n\t\t#y = json.dumps(self.displayjson)\n\t\t#print(y)\n\t\tself.labelMaps = labelMaps\n\t\tself.log = logging.getLogger('eion')\n\t\t\n\tdef visualizationrecommandsystem(self):\n\t\ttry:\n\t\t\timport tensorflow.keras.utils as kutils\n\t\t\tdatasetid = self.visualizationJson['datasetid']\n\t\t\tself.log.info('\\\\n================== Data Profiling Details==================')\n\t\t\tdatacolumns=list(self.dataframe.columns)\n\t\t\tself.log.info('================== Data Profiling Details End ==================\\\\n')\n\t\t\tself.log.info('================== Features Correlation Details ==================\\\\n')\n\t\t\tself.log.info('\\\\n================== Model Performance Analysis ==================')\n\t\t\tif os.path.exists(self.pred_filename):\n\t\t\t\ttry: \n\t\t\t\t\tstatus,df=read_df_compressed(self.pred_filename)\n\t\t\t\t\tif self.modeltype == 'Classification' or self.modeltype == 'ImageClassification' or self.modeltype == 'anomaly_detection':\n\t\t\t\t\t\ty_actual = df['actual'].values\n\t\t\t\t\t\ty_predict = df['predict'].values\n\t\t\t\t\t\ty_actual = kutils.to_categorical(y_actual)\n\t\t\t\t\t\ty_predict = kutils.to_categorical(y_predict)\n\t\t\t\t\t\tclasses = df.actual.unique()\n\t\t\t\t\t\tn_classes = y_actual.shape[1]\n\t\t\t\t\t\tself.log.info('-------> ROC AUC CURVE')\n\t\t\t\t\t\troc_curve_dict = []\n\t\t\t\t\t\tfor i in classes:\n\t\t\t\t\t\t\ttry:\t\n\t\t\t\t\t\t\t\tclassname = i\n\t\t\t\t\t\t\t\tif str(self.labelMaps) != '{}':\n\t\t\t\t\t\t\t\t\tinv_map = {v: k for k, v in self.labelMaps.items()}\n\t\t\t\t\t\t\t\t\tclassname = inv_map[i]\n\t\t\t\t\t\t\t\tfpr, tpr, threshold = metrics.roc_curve(y_actual[:,i],y_predict[:,i])\n\t\t\t\t\t\t\t\troc_auc = metrics.auc(fpr, tpr)\n\t\t\t\t\t\t\t\tclass_roc_auc_curve = {}\n\t\t\t\t\t\t\t\tclass_roc_auc_curve['class'] = str(classname)\n\t\t\t\t\t\t\t\tfprstring = ','.join(str(v) for v in fpr)\n\t\t\t\t\t\t\t\ttprstring = ','.join(str(v) for v in tpr)\n\t\t\t\t\t\t\t\tclass_roc_auc_curve['FP'] = str(fprstring)\n\t\t\t\t\t\t\t\tclass_roc_auc_curve['TP'] = str(tprstring)\n\t\t\t\t\t\t\t\troc_curve_dict.append(class_roc_auc_curve)\n\t\t\t\t\t\t\t\tself.log.info('----------> Class: '+str(classname))\n\t\t\t\t\t\t\t\tself.log.info('------------> ROC_AUC: '+str(roc_auc))\n\t\t\t\t\t\t\t\tself.log.info('------------> False Positive Rate (x Points): '+str(fpr))\n\t\t\t\t\t\t\t\tself.log.info('------------> True Positive Rate (y Points): '+str(tpr))\n\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\tself.displayjson['ROC_AUC_CURVE'] = roc_curve_dict\n\t\t\t\t\t\t\tself.log.info('-------> Precision Recall CURVE')\n\t\t\t\t\t\t\tprecision_recall_curve_dict = []\n\t\t\t\t\t\tfor i in range(n_classes):\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tlr_precision, lr_recall, threshold = metrics.precision_recall_curve(y_actual[:,i],y_predict[:,i])\n\t\t\t\t\t\t\t\tclassname = i\n\t\t\t\t\t\t\t\tif str(self.labelMaps) != '{}':\n\t\t\t\t\t\t\t\t\tinv_map = {v: k for k, v in self.labelMaps.items()}\n\t\t\t\t\t\t\t\t\tclassname = inv_map[i]\n\t\t\t\t\t\t\t\troc_auc = metrics.auc(lr_recall,lr_precision)\n\t\t\t\t\t\t\t\tclass_precision_recall_curve = {}\n\t\t\t\t\t\t\t\tclass_precision_recall_curve['class'] = str(classname)\n\t\t\t\t\t\t\t\tPrecisionstring = ','.join(str(round(v,2)) for v in lr_precision)\n\t\t\t\t\t\t\t\tRecallstring = ','.join(str(round(v,2)) for v in lr_recall)\n\t\t\t\t\t\t\t\tclass_precision_recall_curve['Precision'] = str(Precisionstring)\n\t\t\t\t\t\t\t\tclass_precision_recall_curve['Recall'] = str(Recallstring)\n\t\t\t\t\t\t\t\tprecision_recall_curve_dict.append(class_precision_recall_curve)\n\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\n\t\t\t\t\t\t\tself.log.info('----------> Class: '+str(classname))\n\t\t\t\t\t\t\tself.log.info('------------> ROC_AUC: '+str(roc_auc))\n\t\t\t\t\t\t\tself.log.info('------------> Recall (x Points): '+str(lr_precision))\n\t\t\t\t\t\t\tself.log.info('------------> Precision (y Points): '+str(lr_recall))\n\t\t\t\t\t\tself.displayjson['PRECISION_RECALL_CURVE'] = precision_recall_curve_dict\n\t\t\t\t\t\tstatus,predictdataFrame=read_df_compressed(self.displayjson['predictedData'])\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tself.log.info('================== Error in Calculation ROC_AUC/Recall Precision Curve '+str(e))\n\t\t\tself.log.info('================== Model Performance Analysis End ==================\\\\n')\n\t\t\tself.log.info('\\\\n================== For Descriptive Analysis of Model Features ==================')\n\n\t\t\t\n\t\t\toutputfile = os.path.join(self.jsondeployPath,'etc','display.json')\n\t\t\twith open(outputfile, 'w') as fp:\n\t\t\t\tjson.dump(self.displayjson, fp)\n\t\t\tself.log.info('================== For Descriptive Analysis of Model Features End ==================\\\\n')\t\t\n\t\texcept Exception as inst:\n\t\t\tself.log.info('Visualization Failed !....'+str(inst))\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\t\n\tdef drawlinechart(self,xcolumn,ycolumn,deploy_path,datasetid):\n\t\ttitle = 'aion_visualization_'+xcolumn+\"_\"+ycolumn+\"_linechart\"\n\t\tyaxisname = 'Average '+ycolumn\n\t\tdatasetindex = datasetid\t\t\n\t\tvisulizationjson = '[{\"_id\": \"543234\",\"_type\": \"visualization\",\"_source\": {\"title\": \"'+title+'\",'\n\t\tvisulizationjson = visulizationjson+'\"visState\": \"{\\\\\\\\\"title\\\\\\\\\":\\\\\\\\\"'+title+'\\\\\\\\\",'\t\t\n\t\tvisulizationjson = visulizationjson+'\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"line\\\\\\\\\",\\\\\\\\\"params\\\\\\\\\":{\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"line\\\\\\\\\",\\\\\\\\\"grid\\\\\\\\\":{\\\\\\\\\"categoryLines\\\\\\\\\":false,\\\\\\\\\"style\\\\\\\\\":{\\\\\\\\\"color\\\\\\\\\":\\\\\\\\\"#eee\\\\\\\\\"}},\\\\\\\\\"categoryAxes\\\\\\\\\":[{\\\\\\\\\"id\\\\\\\\\":\\\\\\\\\"CategoryAxis-1\\\\\\\\\",\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"category\\\\\\\\\",\\\\\\\\\"position\\\\\\\\\":\\\\\\\\\"bottom\\\\\\\\\",\\\\\\\\\"show\\\\\\\\\":true,\\\\\\\\\"style\\\\\\\\\":{},\\\\\\\\\"scale\\\\\\\\\":{\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"linear\\\\\\\\\"},\\\\\\\\\"labels\\\\\\\\\":{\\\\\\\\\"show\\\\\\\\\":true,\\\\\\\\\"truncate\\\\\\\\\":100},\\\\\\\\\"title\\\\\\\\\":{}}],\\\\\\\\\"valueAxes\\\\\\\\\":[{\\\\\\\\\"id\\\\\\\\\":\\\\\\\\\"ValueAxis-1\\\\\\\\\",\\\\\\\\\"name\\\\\\\\\":\\\\\\\\\"LeftAxis-1\\\\\\\\\",\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"value\\\\\\\\\",\\\\\\\\\"position\\\\\\\\\":\\\\\\\\\"left\\\\\\\\\",\\\\\\\\\"show\\\\\\\\\":true,\\\\\\\\\"style\\\\\\\\\":{},\\\\\\\\\"scale\\\\\\\\\":{\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"linear\\\\\\\\\",\\\\\\\\\"mode\\\\\\\\\":\\\\\\\\\"normal\\\\\\\\\"},\\\\\\\\\"labels\\\\\\\\\":{\\\\\\\\\"show\\\\\\\\\":true,\\\\\\\\\"rotate\\\\\\\\\":0,\\\\\\\\\"filter\\\\\\\\\":false,\\\\\\\\\"truncate\\\\\\\\\":100},\\\\\\\\\"title\\\\\\\\\":'\t\t\n\t\tvisulizationjson = visulizationjson+'{\\\\\\\\\"text\\\\\\\\\":\\\\\\\\\"'+yaxisname+'\\\\\\\\\"}}],\\\\\\\\\"seriesParams\\\\\\\\\":[{\\\\\\\\\"show\\\\\\\\\":\\\\\\\\\"true\\\\\\\\\",\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"line\\\\\\\\\",\\\\\\\\\"mode\\\\\\\\\":\\\\\\\\\"normal\\\\\\\\\",\\\\\\\\\"data\\\\\\\\\":'\n\t\tvisulizationjson = visulizationjson+'{\\\\\\\\\"label\\\\\\\\\":\\\\\\\\\"'+yaxisname+'\\\\\\\\\",\\\\\\\\\"id\\\\\\\\\":\\\\\\\\\"1\\\\\\\\\"},\\\\\\\\\"valueAxis\\\\\\\\\":\\\\\\\\\"ValueAxis-1\\\\\\\\\",\\\\\\\\\"drawLinesBetweenPoints\\\\\\\\\":true,\\\\\\\\\"showCircles\\\\\\\\\":true}],\\\\\\\\\"addTooltip\\\\\\\\\":true,\\\\\\\\\"addLegend\\\\\\\\\":true,\\\\\\\\\"legendPosition\\\\\\\\\":\\\\\\\\\"right\\\\\\\\\",\\\\\\\\\"times\\\\\\\\\":[],\\\\\\\\\"addTimeMarker\\\\\\\\\":false},\\\\\\\\\"aggs\\\\\\\\\":[{\\\\\\\\\"id\\\\\\\\\":\\\\\\\\\"1\\\\\\\\\",\\\\\\\\\"enabled\\\\\\\\\":true,\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"avg\\\\\\\\\",\\\\\\\\\"schema\\\\\\\\\":\\\\\\\\\"metric\\\\\\\\\",\\\\\\\\\"params\\\\\\\\\":{\\\\\\\\\"field\\\\\\\\\":\\\\\\\\\"'+str(ycolumn)+'\\\\\\\\\"}},{\\\\\\\\\"id\\\\\\\\\":\\\\\\\\\"2\\\\\\\\\",\\\\\\\\\"enabled\\\\\\\\\":true,\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"terms\\\\\\\\\",\\\\\\\\\"schema\\\\\\\\\":\\\\\\\\\"segment\\\\\\\\\",\\\\\\\\\"params\\\\\\\\\":{\\\\\\\\\"field\\\\\\\\\":\\\\\\\\\"'+xcolumn+'\\\\\\\\\",\\\\\\\\\"size\\\\\\\\\":100,\\\\\\\\\"order\\\\\\\\\":\\\\\\\\\"desc\\\\\\\\\",\\\\\\\\\"orderBy\\\\\\\\\":\\\\\\\\\"1\\\\\\\\\",\\\\\\\\\"otherBucket\\\\\\\\\":false,\\\\\\\\\"otherBucketLabel\\\\\\\\\":\\\\\\\\\"Other\\\\\\\\\",\\\\\\\\\"missingBucket\\\\\\\\\":false,\\\\\\\\\"missingBucketLabel\\\\\\\\\":\\\\\\\\\"Missing\\\\\\\\\"}}]}\",\"uiStateJSON\": \"{}\", \"description\": \"\",\"version\": 1,\"kibanaSavedObjectMeta\": {\"searchSourceJSON\": \"{\\\\\\\\\"index\\\\\\\\\":\\\\\\\\\"'+datasetindex+'\\\\\\\\\",\\\\\\\\\"query\\\\\\\\\":{\\\\\\\\\"query\\\\\\\\\":\\\\\\\\\"\\\\\\\\\",\\\\\\\\\"language\\\\\\\\\":\\\\\\\\\"lucene\\\\\\\\\"},\\\\\\\\\"filter\\\\\\\\\":[]}\"}},\"_migrationVersion\": {\"visualization\": \"6.7.2\"}}]'\n\t\tfilename = deploy_path+title+'.json'\n\t\tf = open(filename, \"w\")\n\t\tf.write(str(visulizationjson))\n\t\tf.close()\n\n\tdef drawbarchart(self,xcolumn,ycolumn,deploy_path,datasetid):\n\t\ttitle = 'aion_visualization_'+xcolumn+\"_\"+ycolumn+\"_barchart\"\n\t\tyaxisname = 'Average '+ycolumn\n\t\tdatasetindex = datasetid\n\t\tvisulizationjson = '[{\"_id\": \"123456\",\"_type\": \"visualization\",\"_source\": {\"title\":\"'+title+'\",'\n\t\tvisulizationjson = visulizationjson+'\"visState\": \"{\\\\\\\\\"title\\\\\\\\\":\\\\\\\\\"'+title+'\\\\\\\\\",'\n\t\tvisulizationjson = visulizationjson+'\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"histogram\\\\\\\\\",\\\\\\\\\"params\\\\\\\\\":{\\\\\\\\\"addLegend\\\\\\\\\":true,\\\\\\\\\"addTimeMarker\\\\\\\\\":false,\\\\\\\\\"addTooltip\\\\\\\\\":true,\\\\\\\\\"categoryAxes\\\\\\\\\":[{\\\\\\\\\"id\\\\\\\\\":\\\\\\\\\"CategoryAxis-1\\\\\\\\\",\\\\\\\\\"labels\\\\\\\\\":{\\\\\\\\\"show\\\\\\\\\":true,\\\\\\\\\"truncate\\\\\\\\\":100},\\\\\\\\\"position\\\\\\\\\":\\\\\\\\\"bottom\\\\\\\\\",\\\\\\\\\"scale\\\\\\\\\":{\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"linear\\\\\\\\\"},\\\\\\\\\"show\\\\\\\\\":true,\\\\\\\\\"style\\\\\\\\\":{},\\\\\\\\\"title\\\\\\\\\":{},\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"category\\\\\\\\\"}],\\\\\\\\\"grid\\\\\\\\\":{\\\\\\\\\"categoryLines\\\\\\\\\":false,\\\\\\\\\"style\\\\\\\\\":{\\\\\\\\\"color\\\\\\\\\":\\\\\\\\\"#eee\\\\\\\\\"}},\\\\\\\\\"legendPosition\\\\\\\\\":\\\\\\\\\"right\\\\\\\\\",\\\\\\\\\"seriesParams\\\\\\\\\":[{\\\\\\\\\"data\\\\\\\\\":{\\\\\\\\\"id\\\\\\\\\":\\\\\\\\\"1\\\\\\\\\",'\n\t\tvisulizationjson = visulizationjson+'\\\\\\\\\"label\\\\\\\\\":\\\\\\\\\"'+yaxisname+'\\\\\\\\\"},'\n\t\tvisulizationjson = visulizationjson+'\\\\\\\\\"drawLinesBetweenPoints\\\\\\\\\":true,\\\\\\\\\"mode\\\\\\\\\":\\\\\\\\\"stacked\\\\\\\\\",\\\\\\\\\"show\\\\\\\\\":\\\\\\\\\"true\\\\\\\\\",\\\\\\\\\"showCircles\\\\\\\\\":true,\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"histogram\\\\\\\\\",\\\\\\\\\"valueAxis\\\\\\\\\":\\\\\\\\\"ValueAxis-1\\\\\\\\\"}],\\\\\\\\\"times\\\\\\\\\":[],\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"histogram\\\\\\\\\",\\\\\\\\\"valueAxes\\\\\\\\\":[{\\\\\\\\\"id\\\\\\\\\":\\\\\\\\\"ValueAxis-1\\\\\\\\\",\\\\\\\\\"labels\\\\\\\\\":{\\\\\\\\\"filter\\\\\\\\\":false,\\\\\\\\\"rotate\\\\\\\\\":0,\\\\\\\\\"show\\\\\\\\\":true,\\\\\\\\\"truncate\\\\\\\\\":100},\\\\\\\\\"name\\\\\\\\\":\\\\\\\\\"LeftAxis-1\\\\\\\\\",\\\\\\\\\"position\\\\\\\\\":\\\\\\\\\"left\\\\\\\\\",\\\\\\\\\"scale\\\\\\\\\":{\\\\\\\\\"mode\\\\\\\\\":\\\\\\\\\"normal\\\\\\\\\",\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"linear\\\\\\\\\"},\\\\\\\\\"show\\\\\\\\\":true,\\\\\\\\\"style\\\\\\\\\":{},\\\\\\\\\"title\\\\\\\\\":'\n\t\tvisulizationjson = visulizationjson+'{\\\\\\\\\"text\\\\\\\\\":\\\\\\\\\"'+yaxisname+'\\\\\\\\\"},'\n\t\tvisulizationjson = visulizationjson+'\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"value\\\\\\\\\"}]},\\\\\\\\\"aggs\\\\\\\\\":[{\\\\\\\\\"id\\\\\\\\\":\\\\\\\\\"1\\\\\\\\\",\\\\\\\\\"enabled\\\\\\\\\":true,\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"avg\\\\\\\\\",\\\\\\\\\"schema\\\\\\\\\":\\\\\\\\\"metric\\\\\\\\\",\\\\\\\\\"params\\\\\\\\\":{\\\\\\\\\"field\\\\\\\\\":\\\\\\\\\"'+str(xcolumn)+'\\\\\\\\\"}},{\\\\\\\\\"id\\\\\\\\\":\\\\\\\\\"2\\\\\\\\\",\\\\\\\\\"enabled\\\\\\\\\":true,\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"terms\\\\\\\\\",\\\\\\\\\"schema\\\\\\\\\":\\\\\\\\\"segment\\\\\\\\\",\\\\\\\\\"params\\\\\\\\\":", "instruction": "", "output": "" }, { "input": "{\\\\\\\\\"field\\\\\\\\\":\\\\\\\\\"'+ycolumn+'\\\\\\\\\",\\\\\\\\\"size\\\\\\\\\":100,\\\\\\\\\"order\\\\\\\\\":\\\\\\\\\"asc\\\\\\\\\",\\\\\\\\\"orderBy\\\\\\\\\":\\\\\\\\\"1\\\\\\\\\",\\\\\\\\\"otherBucket\\\\\\\\\":false,\\\\\\\\\"otherBucketLabel\\\\\\\\\":\\\\\\\\\"Other\\\\\\\\\",\\\\\\\\\"missingBucket\\\\\\\\\":false,\\\\\\\\\"missingBucketLabel\\\\\\\\\":\\\\\\\\\"Missing\\\\\\\\\"}}]}\",\"uiStateJSON\":\"{}\",\"description\": \"\",\"version\": 1,\"kibanaSavedObjectMeta\": {'\n\t\tvisulizationjson = visulizationjson+'\"searchSourceJSON\": \"{\\\\\\\\\"index\\\\\\\\\":\\\\\\\\\"'+datasetindex+'\\\\\\\\\",\\\\\\\\\"query\\\\\\\\\":{\\\\\\\\\"language\\\\\\\\\":\\\\\\\\\"lucene\\\\\\\\\",\\\\\\\\\"query\\\\\\\\\":\\\\\\\\\"\\\\\\\\\"},\\\\\\\\\"filter\\\\\\\\\":[]}\"}},\"_migrationVersion\":{\"visualization\": \"6.7.2\"}}]'\n\t\tfilename = deploy_path+title+'.json'\n\t\tf = open(filename, \"w\")\n\t\tf.write(str(visulizationjson))\n\t\tf.close()\n\n\tdef drawpiechart(self,xcolumn,deploy_path,datasetid):\n\t\ttitle = 'aion_visualization_'+xcolumn+\"_piechart\"\n\t\tdatasetindex = datasetid\n\t\tvisulizationjson = '[{\"_id\": \"123456\",\"_type\": \"visualization\",\"_source\": {\"title\":\"'+title+'\",'\n\t\tvisulizationjson = visulizationjson+'\"visState\": \"{\\\\\\\\\"title\\\\\\\\\":\\\\\\\\\"'+title+'\\\\\\\\\",'\n\t\tvisulizationjson = visulizationjson+'\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"pie\\\\\\\\\",\\\\\\\\\"params\\\\\\\\\":{\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"pie\\\\\\\\\",\\\\\\\\\"addTooltip\\\\\\\\\":true,\\\\\\\\\"addLegend\\\\\\\\\":true,\\\\\\\\\"legendPosition\\\\\\\\\":\\\\\\\\\"right\\\\\\\\\",\\\\\\\\\"isDonut\\\\\\\\\":true,\\\\\\\\\"labels\\\\\\\\\":{\\\\\\\\\"show\\\\\\\\\":false,\\\\\\\\\"values\\\\\\\\\":true,\\\\\\\\\"last_level\\\\\\\\\":true,\\\\\\\\\"truncate\\\\\\\\\":100}},\\\\\\\\\"aggs\\\\\\\\\":[{\\\\\\\\\"id\\\\\\\\\":\\\\\\\\\"1\\\\\\\\\",\\\\\\\\\"enabled\\\\\\\\\":true,\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"count\\\\\\\\\",\\\\\\\\\"schema\\\\\\\\\":\\\\\\\\\"metric\\\\\\\\\",\\\\\\\\\"params\\\\\\\\\":{}},{\\\\\\\\\"id\\\\\\\\\":\\\\\\\\\"2\\\\\\\\\",\\\\\\\\\"enabled\\\\\\\\\":true,\\\\\\\\\"type\\\\\\\\\":\\\\\\\\\"terms\\\\\\\\\",\\\\\\\\\"schema\\\\\\\\\":\\\\\\\\\"segment\\\\\\\\\",\\\\\\\\\"params\\\\\\\\\":{\\\\\\\\\"field\\\\\\\\\":\\\\\\\\\"'+xcolumn+'\\\\\\\\\",\\\\\\\\\"size\\\\\\\\\":100,\\\\\\\\\"order\\\\\\\\\":\\\\\\\\\"asc\\\\\\\\\",\\\\\\\\\"orderBy\\\\\\\\\":\\\\\\\\\"1\\\\\\\\\",\\\\\\\\\"otherBucket\\\\\\\\\":false,\\\\\\\\\"otherBucketLabel\\\\\\\\\":\\\\\\\\\"Other\\\\\\\\\",\\\\\\\\\"missingBucket\\\\\\\\\":false,\\\\\\\\\"missingBucketLabel\\\\\\\\\":\\\\\\\\\"Missing\\\\\\\\\"}}]}\",'\n\t\tvisulizationjson = visulizationjson+'\"uiStateJSON\": \"{}\",\"description\": \"\",\"version\": 1,\"kibanaSavedObjectMeta\": {\"searchSourceJSON\":\"{\\\\\\\\\"index\\\\\\\\\":\\\\\\\\\"'+datasetid+'\\\\\\\\\",\\\\\\\\\"query\\\\\\\\\":{\\\\\\\\\"query\\\\\\\\\":\\\\\\\\\"\\\\\\\\\",\\\\\\\\\"language\\\\\\\\\":\\\\\\\\\"lucene\\\\\\\\\"},\\\\\\\\\"filter\\\\\\\\\":[]}\"}},\"_migrationVersion\": {\"visualization\": \"6.7.2\"}}]'\n\t\tfilename = deploy_path+title+'.json'\n\t\tf = open(filename, \"w\")\n\t\tf.write(str(visulizationjson))\n\t\tf.close()\t\n\t\t\n\tdef get_confusion_matrix(self,df):\n\t\tsetOfyTrue = set(df['actual'])\n\t\tunqClassLst = list(setOfyTrue)\n\t\tif(str(self.labelMaps) != '{}'):\n\t\t\tinv_mapping_dict = {v: k for k, v in self.labelMaps.items()}\n\t\t\tunqClassLst2 = (pd.Series(unqClassLst)).map(inv_mapping_dict)\n\t\t\tunqClassLst2 = list(unqClassLst2)\n\t\telse:\n\t\t\tunqClassLst2 = \tunqClassLst\n\t\tindexName = []\n\t\tcolumnName = []\n\t\tfor item in unqClassLst2:\n\t\t\tindexName.append(\"act:\"+str(item))\n\t\t\tcolumnName.append(\"pre:\"+str(item))\n\t\tresult = pd.DataFrame(confusion_matrix(df['actual'], df['predict'], labels = unqClassLst),index = indexName, columns = columnName)\n\t\tresultjson = result.to_json(orient='index')\n\t\treturn(resultjson)\n\t\t\n\tdef DistributionFinder(self,data):\n\t\ttry:\n\t\t\t\n\t\t\tdistributionName =\"\"\n\t\t\tsse =0.0\n\t\t\tKStestStatic=0.0\n\t\t\tdataType=\"\"\n\t\t\tif(data.dtype == \"float64\"):\n\t\t\t\tdataType =\"Continuous\"\n\t\t\telif(data.dtype ==\"int\" or data.dtype ==\"int64\"):\n\t\t\t\tdataType=\"Discrete\"\n\t\t\t\t\t \n\t\t\tif(dataType == \"Discrete\"):\n\t\t\t\tdistributions= [st.bernoulli,st.binom,st.geom,st.nbinom,st.poisson] \n\t\t\t\tindex, counts = np.unique(abs(data.astype(int)),return_counts=True)\n\n\t\t\t\tif(len(index)>=2):\n\t\t\t\t\tbest_sse = np.inf\n\t\t\t\t\ty1=[]\n\t\t\t\t\ttotal=sum(counts)\n\t\t\t\t\tmean=float(sum(index*counts))/total\n\t\t\t\t\tvariance=float((sum(index**2*counts) -total*mean**2))/(total-1)\n\t\t\t\t\tdispersion=mean/float(variance)\n\t\t\t\t\ttheta=1/float(dispersion)\n\t\t\t\t\tr=mean*(float(theta)/1-theta)\n\n\t\t\t\t\tfor j in counts:\n\t\t\t\t\t\t\ty1.append(float(j)/total)\n\t\t\t\t\t\t\t\n\t\t\t\t\tpmf1=st.bernoulli.pmf(index,mean) \n\t\t\t\t\tpmf2=st.binom.pmf(index,len(index),p=mean/len(index))\n\t\t\t\t\tpmf3=st.geom.pmf(index,1/float(1+mean))\n\t\t\t\t\tpmf4=st.nbinom.pmf(index,mean,r)\n\t\t\t\t\tpmf5=st.poisson.pmf(index,mean)\n\n\t\t\t\t\tsse1 = np.sum(np.power(y1 - pmf1, 2.0))\n\t\t\t\t\tsse2 = np.sum(np.power(y1 - pmf2, 2.0))\n\t\t\t\t\tsse3 = np.sum(np.power(y1 - pmf3, 2.0))\n\t\t\t\t\tsse4 = np.sum(np.power(y1 - pmf4, 2.0))\n\t\t\t\t\tsse5 = np.sum(np.power(y1- pmf5, 2.0))\n\n\t\t\t\t\tsselist=[sse1,sse2,sse3,sse4,sse5]\n\t\t\t\t\tfor i in range(0,len(sselist)):\n\t\t\t\t\t if best_sse > sselist[i] > 0:\n\t\t\t\t\t\t best_distribution = distributions[i].name\n\t\t\t\t\t\t best_sse = sselist[i]\n\n\t\t\t\telif (len(index) == 1): \n\t\t\t\t\tbest_distribution = \"Constant Data-No Distribution\"\n\t\t\t\t\tbest_sse = 0.0\n\n\t\t\t\tdistributionName =best_distribution\n\t\t\t\tsse=best_sse \n\n\t\t\telif(dataType == \"Continuous\"): \n\t\t\t\t\t \n\t\t\t\tdistributions = [st.uniform,st.expon,st.weibull_max,st.weibull_min,st.chi,st.norm,st.lognorm,st.t,st.gamma,st.beta]\n\n\t\t\t\tbest_distribution = st.norm.name\n\t\t\t\tbest_sse = np.inf\n\t\t\t\tdatamin=data.min()\n\t\t\t\tdatamax=data.max()\n\t\t\t\tnrange=datamax-datamin\n\t\t\t\t\t \n\t\t\t\ty, x = np.histogram(data.astype(float), bins='auto', density=True)\n\t\t\t\tx = (x + np.roll(x, -1))[:-1] / 2.0\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tfor distribution in distributions:\n\t\t\t\t\t\twith warnings.catch_warnings():\n\t\t\t\t\t\t\t\twarnings.filterwarnings('ignore')\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tparams = distribution.fit(data.astype(float))\n\t\t\t\t\t\t\t\t\t\t# Separate parts of parameters\n\t\t\t\t\t\t\t\targ = params[:-2]\n\t\t\t\t\t\t\t\tloc = params[-2]\n\t\t\t\t\t\t\t\tscale = params[-1]\n\n\t\t\t\t\t\t\t\t\t\t# Calculate fitted PDF and error with fit in distribution\n\t\t\t\t\t\t\t\tpdf = distribution.pdf(x, loc=loc, scale=scale, *arg)\n\t\t\t\t\t\t\t\tsse = np.sum(np.power(y - pdf, 2.0))\n\t\t\t\t\t\t\t\tif(best_sse >sse > 0):\n\t\t\t\t\t\t\t\t\t\tbest_distribution = distribution.name\n\t\t\t\t\t\t\t\t\t\tbest_sse = sse\n\n\t\t\t\tdistributionName =best_distribution\n\t\t\t\tsse=best_sse \n\t\texcept:\n\t\t\tresponse = str(sys.exc_info()[0])\n\t\t\tmessage='Job has Failed'+response\n\t\t\tprint(message)\n\t\treturn distributionName,sse\n\n\t\t\t\t\n\t\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n''' \"\"\"The utils module contains the get_rng function.\"\"\"\n\n\nimport numbers\n\nimport numpy as np\n\n\ndef get_rng(random_state):\n \"\"\"Return a 'validated' RNG.\n\n If random_state is None, use RandomState singleton from numpy. Else if\n it's an integer, consider it's a seed and initialized an rng with that\n seed. If it's already an rng, return it.\n \"\"\"\n if random_state is None:\n return np.random.mtrand._rand\n elif isinstance(random_state, (numbers.Integral, np.integer)):\n return np.random.RandomState(random_state)\n if isinstance(random_state, np.random.RandomState):\n return random_state\n raise ValueError(\n \"Wrong random state. Expecting None, an int or a numpy \"\n \"RandomState instance, got a \"\n \"{}\".format(type(random_state))\n )\n \"\"\"This module contains built-in datasets that can be automatically\ndownloaded.\"\"\"\n\nimport errno\nimport os\nimport zipfile\nfrom collections import namedtuple\n\nfrom os.path import join\nfrom urllib.request import urlretrieve\n\n\ndef get_dataset_dir():\n \"\"\"Return folder where downloaded datasets and other data are stored.\n Default folder is ~/.surprise_data/, but it can also be set by the\n environment variable ``SURPRISE_DATA_FOLDER``.\n \"\"\"\n\n folder = os.environ.get(\n \"SURPRISE_DATA_FOLDER\", os.path.expanduser(\"~\") + \"/.surprise_data/\"\n )\n try:\n os.makedirs(folder)\n except OSError as e:\n if e.errno != errno.EEXIST:\n # reraise exception if folder does not exist and creation failed.\n raise\n\n return folder\n\n\n# a builtin dataset has\n# - an url (where to download it)\n# - a path (where it is located on the filesystem)\n# - the parameters of the corresponding reader\nBuiltinDataset = namedtuple(\"BuiltinDataset\", [\"url\", \"path\", \"reader_params\"])\n\nBUILTIN_DATASETS = {\n \"ml-100k\": BuiltinDataset(\n url=\"https://files.grouplens.org/datasets/movielens/ml-100k.zip\",\n path=join(get_dataset_dir(), \"ml-100k/ml-100k/u.data\"),\n reader_params=dict(\n line_format=\"user item rating timestamp\", rating_scale=(1, 5), sep=\"\\\\t\"\n ),\n ),\n \"ml-1m\": BuiltinDataset(\n url=\"https://files.grouplens.org/datasets/movielens/ml-1m.zip\",\n path=join(get_dataset_dir(), \"ml-1m/ml-1m/ratings.dat\"),\n reader_params=dict(\n line_format=\"user item rating timestamp\", rating_scale=(1, 5), sep=\"::\"\n ),\n ),\n \"jester\": BuiltinDataset(\n url=\"https://eigentaste.berkeley.edu/dataset/archive/jester_dataset_2.zip\",\n path=join(get_dataset_dir(), \"jester/jester_ratings.dat\"),\n reader_params=dict(line_format=\"user item rating\", rating_scale=(-10, 10)),\n ),\n}\n\n\ndef download_builtin_dataset(name):\n\n dataset = BUILTIN_DATASETS[name]\n\n print(\"Trying to download dataset from \" + dataset.url + \"...\")\n tmp_file_path = join(get_dataset_dir(), \"tmp.zip\")\n urlretrieve(dataset.url, tmp_file_path)\n\n with zipfile.ZipFile(tmp_file_path, \"r\") as tmp_zip:\n tmp_zip.extractall(join(get_dataset_dir(), name))\n\n os.remove(tmp_file_path)\n print(\"Done! Dataset\", name, \"has been saved to\", join(get_dataset_dir(), name))\n \"\"\"\nThe :mod:`dump ` module defines the :func:`dump` function.\n\"\"\"\n\nimport pickle\n\n\ndef dump(file_name, predictions=None, algo=None, verbose=0):\n \"\"\"A basic wrapper around Pickle to serialize a list of prediction and/or\n an algorithm on drive.\n\n What is dumped is a dictionary with keys ``'predictions'`` and ``'algo'``.\n\n Args:\n file_name(str): The name (with full path) specifying where to dump the\n predictions.\n predictions(list of :obj:`Prediction\\\\\n `): The\n predictions to dump.\n algo(:class:`Algorithm\\\\\n `, optional):\n The algorithm to dump.\n verbose(int): Level of verbosity. If ``1``, then a message indicates\n that the dumping went successfully. Default is ``0``.\n \"\"\"\n\n dump_obj = {\"predictions\": predictions, \"algo\": algo}\n pickle.dump(dump_obj, open(file_name, \"wb\"), protocol=pickle.HIGHEST_PROTOCOL)\n\n if verbose:\n print(\"The dump has been saved as file\", file_name)\n\n\ndef load(file_name):\n \"\"\"A basic wrapper around Pickle to deser", "instruction": "", "output": "" }, { "input": "ialize a list of prediction and/or\n an algorithm that were dumped on drive using :func:`dump()\n `.\n\n Args:\n file_name(str): The path of the file from which the algorithm is\n to be loaded\n\n Returns:\n A tuple ``(predictions, algo)`` where ``predictions`` is a list of\n :class:`Prediction\n ` objects and\n ``algo`` is an :class:`Algorithm\n ` object. Depending\n on what was dumped, some of these may be ``None``.\n\n \"\"\"\n\n dump_obj = pickle.load(open(file_name, \"rb\"))\n\n return dump_obj[\"predictions\"], dump_obj[\"algo\"]\n #!/usr/bin/env python\n\nimport argparse\nimport os\nimport random as rd\nimport shutil\nimport sys\n\nimport numpy as np\n\nimport surprise.dataset as dataset\nfrom surprise import __version__\nfrom surprise.builtin_datasets import get_dataset_dir\nfrom surprise.dataset import Dataset\nfrom surprise.model_selection import cross_validate, KFold, PredefinedKFold\n\nfrom surprise.prediction_algorithms import (\n BaselineOnly,\n CoClustering,\n KNNBaseline,\n KNNBasic,\n KNNWithMeans,\n NMF,\n NormalPredictor,\n SlopeOne,\n SVD,\n SVDpp,\n)\nfrom surprise.reader import Reader # noqa\n\n\ndef main():\n class MyParser(argparse.ArgumentParser):\n \"\"\"A parser which prints the help message when an error occurs. Taken from\n https://stackoverflow.com/questions/4042452/display-help-message-with-python-argparse-when-script-is-called-without-any-argu.\"\"\" # noqa\n\n def error(self, message):\n sys.stderr.write(\"error: %s\\\\n\" % message)\n self.print_help()\n sys.exit(2)\n\n parser = MyParser(\n description=\"Evaluate the performance of a rating prediction \"\n + \"algorithm \"\n + \"on a given dataset using cross validation. You can use a built-in \"\n + \"or a custom dataset, and you can choose to automatically split the \"\n + \"dataset into folds, or manually specify train and test files. \"\n + \"Please refer to the documentation page \"\n + \"(https://surprise.readthedocs.io/) for more details.\",\n epilog=\"\"\"Example:\\\\n\n surprise -algo SVD -params \"{'n_epochs': 5, 'verbose': True}\"\n -load-builtin ml-100k -n-folds 3\"\"\",\n )\n\n algo_choices = {\n \"NormalPredictor\": NormalPredictor,\n \"BaselineOnly\": BaselineOnly,\n \"KNNBasic\": KNNBasic,\n \"KNNBaseline\": KNNBaseline,\n \"KNNWithMeans\": KNNWithMeans,\n \"SVD\": SVD,\n \"SVDpp\": SVDpp,\n \"NMF\": NMF,\n \"SlopeOne\": SlopeOne,\n \"CoClustering\": CoClustering,\n }\n\n parser.add_argument(\n \"-algo\",\n type=str,\n choices=algo_choices,\n help=\"The prediction algorithm to use. \"\n + \"Allowed values are \"\n + \", \".join(algo_choices.keys())\n + \".\",\n metavar=\"\",\n )\n\n parser.add_argument(\n \"-params\",\n type=str,\n metavar=\"\",\n default=\"{}\",\n help=\"A kwargs dictionary that contains all the \"\n + \"algorithm parameters.\"\n + \"Example: \\\\\"{'n_epochs': 10}\\\\\".\",\n )\n\n parser.add_argument(\n \"-load-builtin\",\n type=str,\n dest=\"load_builtin\",\n metavar=\"\",\n default=\"ml-100k\",\n help=\"The name of the built-in dataset to use.\"\n + \"Allowed values are \"\n + \", \".join(dataset.BUILTIN_DATASETS.keys())\n + \". Default is ml-100k.\",\n )\n\n parser.add_argument(\n \"-load-custom\",\n type=str,\n dest=\"load_custom\",\n metavar=\"\",\n default=None,\n help=\"A file path to custom dataset to use. \"\n + \"Ignored if \"\n + \"-loadbuiltin is set. The -reader parameter needs \"\n + \"to be set.\",\n )\n\n parser.add_argument(\n \"-folds-files\",\n type=str,\n dest=\"folds_files\",\n metavar=\"\",\n default=None,\n help=\"A list of custom train and test files. \"\n + \"Ignored if -load-builtin or -load-custom is set. \"\n \"The -reader parameter needs to be set.\",\n )\n\n parser.add_argument(\n \"-reader\",\n type=str,\n metavar=\"\",\n default=None,\n help=\"A Reader to read the custom dataset. Example: \"\n + \"\\\\\"Reader(line_format='user item rating timestamp',\"\n + \" sep='\\\\\\\\t')\\\\\"\",\n )\n\n parser.add_argument(\n \"-n-folds\",\n type=int,\n dest=\"n_folds\",\n metavar=\"\",\n default=5,\n help=\"The number of folds for cross-validation. \" + \"Default is 5.\",\n )\n\n parser.add_argument(\n \"-seed\",\n type=int,\n metavar=\"\",\n default=None,\n help=\"The seed to use for RNG. \" + \"Default is the current system time.\",\n )\n\n parser.add_argument(\n \"--with-dump\",\n dest=\"with_dump\",\n action=\"store_true\",\n help=\"Dump the algorithm \"\n + \"results in a file (one file per fold). \"\n + \"Default is False.\",\n )\n\n parser.add_argument(\n \"-dump-dir\",\n dest=\"dump_dir\",\n type=str,\n metavar=\"\",\n default=None,\n help=\"Where to dump the files. Ignored if \"\n + \"with-dump is not set. Default is \"\n + os.path.join(get_dataset_dir(), \"dumps/\"),\n )\n\n parser.add_argument(\n \"--clean\",\n dest=\"clean\",\n action=\"store_true\",\n help=\"Remove the \" + get_dataset_dir() + \" directory and exit.\",\n )\n\n parser.add_argument(\"-v\", \"--version\", action=\"version\", version=__version__)\n\n args = parser.parse_args()\n\n if args.clean:\n folder = get_dataset_dir()\n shutil.rmtree(folder)\n print(\"Removed\", folder)\n exit()\n\n # setup RNG\n rd.seed(args.seed)\n np.random.seed(args.seed)\n\n # setup algorithm\n params = eval(args.params)\n if args.algo is None:\n parser.error(\"No algorithm was specified.\")\n algo = algo_choices[args.algo](**params)\n\n # setup dataset\n if args.load_custom is not None: # load custom and split\n if args.reader is None:\n parser.error(\"-reader parameter is needed.\")\n reader = eval(args.reader)\n data = Dataset.load_from_file(args.load_custom, reader=reader)\n cv = KFold(n_splits=args.n_folds, random_state=args.seed)\n\n elif args.folds_files is not None: # load from files\n if args.reader is None:\n parser.error(\"-reader parameter is needed.\")\n reader = eval(args.reader)\n folds_files = args.folds_files.split()\n folds_files = [\n (folds_files[i], folds_files[i + 1])\n for i in range(0, len(folds_files) - 1, 2)\n ]\n data = Dataset.load_from_folds(folds_files=folds_files, reader=reader)\n cv = PredefinedKFold()\n\n else: # load builtin dataset and split\n data = Dataset.load_builtin(args.load_builtin)\n cv = KFold(n_splits=args.n_folds, random_state=args.seed)\n\n cross_validate(algo, data, cv=cv, verbose=True)\n\n\nif __name__ == \"__main__\":\n main()\n \"\"\"\nThe :mod:`dataset ` module defines the :class:`Dataset` class\nand other subclasses which are used for managing datasets.\n\nUsers may use both *built-in* and user-defined datasets (see the\n:ref:`getting_started` page for examples). Right now, three built-in datasets\nare available:\n\n* The `movielens-100k `_ dataset.\n* The `movielens-1m `_ dataset.\n* The `Jester `_ dataset 2.\n\nBuilt-in datasets can all be loaded (or downloaded if you haven't already)\nusing the :meth:`Dataset.load_builtin` method.\nSummary:\n\n.. autosummary::\n :nosignatures:\n\n Dataset.load_builtin\n Dataset.load_from_file\n Dataset.load_from_folds\n\"\"\"\n\n\nimport itertools\nimport os\nimport sys\nfrom collections import defaultdict\n\nfrom .builtin_datasets import BUILTIN_DATASETS, download_builtin_dataset\n\nfrom .reader import Reader\nfrom .trainset import Trainset\n\n\nclass Dataset:\n \"\"\"Base class for loading datasets.\n\n Note that you should never instantiate the :class:`Dataset` class directly\n (same goes for its derived classes), but instead use one of the three\n available methods for loading datasets.\"\"\"\n\n def __init__(self, reader):\n\n self.reader = reader\n\n @classmethod\n def load_builtin(cls, name=\"ml-100k\", prompt=True):\n \"\"\"Load a built-in dataset.\n\n If the dataset has not already been loaded, it will be downloaded and\n saved. You will have to split your dataset using the :meth:`split\n ` method. See an example in the :ref:`User\n Guide `.\n\n Args:\n name(:obj:`string`): The name of the built-in dataset to load.\n Accepted values are 'ml-100k', 'ml-1m', and 'jester'.\n Default is 'ml-100k'.\n prompt(:obj:`bool`): Prompt before downloading if dataset is not\n already on disk.\n Default is True.\n\n Returns:\n A :obj:`Dataset` object.\n\n Raises:\n ValueError: If the ``name`` parameter is incorrect.\n \"\"\"\n\n try:\n dataset = BUILTIN_DATASETS[name]\n except KeyError:\n raise ValueError(\n \"unknown dataset \"\n + name\n + \". Accepted values are \"\n + \", \".join(BUILTIN_DATASETS.keys())\n + \".\"\n )\n\n # if dataset does not exist, offer to download it\n if not os.path.isfile(dataset.path):\n answered = not prompt\n while not answered:\n print(\n \"Dataset \" + name + \" could not be found. Do you want \"\n \"to download it? [Y/n] \",\n end=\"\",\n )\n choice = input().lower()\n\n if choice in [\"yes\", \"y\", \"\", \"omg this is so nice of you!!\"]:\n answered = True\n elif choice in [\"no\", \"n\", \"hell no why would i want that?!\"]:\n answered = True\n print(\"Ok then, I'm out!\")\n sys.exit()\n\n download_builtin_dataset(name)\n\n reader = Reader(**dataset.reader_params)\n\n return cls.load_from_file(file_path=dataset.path, reader=reader)\n\n @classmethod\n def load_from_file(cls, file_path, reader):\n \"\"\"Load a dataset from a (custom) file.\n\n Use this if you want to use a custom dataset and all of the ratings are\n stored in one file. You will have to split your dataset using the\n :meth:`split ` method. See an example in the\n :ref:`User Guide `.\n\n\n Args:\n file_path(:obj:`string`): The path to the file containing ratings.\n reader(:obj:`Reader `): A reader to read\n the file.\n \"\"\"\n\n return DatasetAutoFolds(ratings_file=file_path, reader=reader)\n\n @classmethod\n def load_from_folds(cls, folds_files, reader):\n \"\"\"Load a dataset where folds (for cross-validation) are predefined by\n some files.\n\n The purpose of this method is to cover a common use case where a\n dataset is already split into predefined folds, such as the\n movielens-100k dataset which defines files u1.base, u1.test, u2.base,\n u2.test, etc... It can also be used when you don't want to perform\n cross-validation but still want to specify your training and testing\n data (which comes down to 1-fold cross-validation anyway). See an\n example in the :ref:`User Guide `.\n\n\n Args:\n folds_files(:obj:`iterable` of :obj:`tuples`): The list of the\n folds. A fold is a tuple of the form ``(path_to_train_file,\n path_to_test_file)``.\n reader(:obj:`Reader `): A reader to read\n the files.\n\n \"\"\"\n\n return DatasetUserFolds(folds_files=folds_files, reader=reader)\n\n @classmethod\n def load_from_df(cls, df, reader):\n \"\"\"Load a dataset from a pandas dataframe.\n\n Use this if you want to use a custom dataset that is stored in a pandas\n dataframe. See the :ref:`User Guide` for an\n example.\n\n Args:\n df(`Dataframe`): The dataframe containing the ratings. It must have\n three columns, corresponding to the user (raw) ids, the item\n (raw) ids, and the ratings, in this order.\n reader(:obj:`Reader `): A reader to read\n the file. Only the ``rating_scale`` field needs to be\n specified.\n \"\"\"\n\n return DatasetAutoFolds(reader=reader, df=df)\n\n def read_ratings(self, file_name):\n \"\"\"Return a list of ratings (user, item, rating, timestamp) read from\n file_name\"\"\"\n\n with open(os.path.expanduser(file_name)) as f:\n raw_ratings = [\n self.reader.parse_line(line)\n for line in itertools.islice(f, self.reader.skip_lines, None)\n ]\n return raw_ratings\n\n def construct_trainset(self, raw_trainset):\n\n raw2inner_id_users = {}\n raw2inner_id_items = {}\n\n current_u_index = 0\n current_i_index = 0\n\n ur = defaultdict(list)\n ir = default", "instruction": "", "output": "" }, { "input": "dict(list)\n\n # user raw id, item raw id, translated rating, time stamp\n for urid, irid, r, timestamp in raw_trainset:\n try:\n uid = raw2inner_id_users[urid]\n except KeyError:\n uid = current_u_index\n raw2inner_id_users[urid] = current_u_index\n current_u_index += 1\n try:\n iid = raw2inner_id_items[irid]\n except KeyError:\n iid = current_i_index\n raw2inner_id_items[irid] = current_i_index\n current_i_index += 1\n\n ur[uid].append((iid, r))\n ir[iid].append((uid, r))\n\n n_users = len(ur) # number of users\n n_items = len(ir) # number of items\n n_ratings = len(raw_trainset)\n\n trainset = Trainset(\n ur,\n ir,\n n_users,\n n_items,\n n_ratings,\n self.reader.rating_scale,\n raw2inner_id_users,\n raw2inner_id_items,\n )\n\n return trainset\n\n def construct_testset(self, raw_testset):\n\n return [(ruid, riid, r_ui_trans) for (ruid, riid, r_ui_trans, _) in raw_testset]\n\n\nclass DatasetUserFolds(Dataset):\n \"\"\"A derived class from :class:`Dataset` for which folds (for\n cross-validation) are predefined.\"\"\"\n\n def __init__(self, folds_files=None, reader=None):\n\n Dataset.__init__(self, reader)\n self.folds_files = folds_files\n\n # check that all files actually exist.\n for train_test_files in self.folds_files:\n for f in train_test_files:\n if not os.path.isfile(os.path.expanduser(f)):\n raise ValueError(\"File \" + str(f) + \" does not exist.\")\n\n\nclass DatasetAutoFolds(Dataset):\n \"\"\"A derived class from :class:`Dataset` for which folds (for\n cross-validation) are not predefined. (Or for when there are no folds at\n all).\"\"\"\n\n def __init__(self, ratings_file=None, reader=None, df=None):\n\n Dataset.__init__(self, reader)\n self.has_been_split = False # flag indicating if split() was called.\n\n if ratings_file is not None:\n self.ratings_file = ratings_file\n self.raw_ratings = self.read_ratings(self.ratings_file)\n elif df is not None:\n self.df = df\n self.raw_ratings = [\n (uid, iid, float(r), None)\n for (uid, iid, r) in self.df.itertuples(index=False)\n ]\n else:\n raise ValueError(\"Must specify ratings file or dataframe.\")\n\n def build_full_trainset(self):\n \"\"\"Do not split the dataset into folds and just return a trainset as\n is, built from the whole dataset.\n\n User can then query for predictions, as shown in the :ref:`User Guide\n `.\n\n Returns:\n The :class:`Trainset `.\n \"\"\"\n\n return self.construct_trainset(self.raw_ratings)\n from pkg_resources import get_distribution\n\nfrom . import dump, model_selection\nfrom .builtin_datasets import get_dataset_dir\n\nfrom .dataset import Dataset\n\nfrom .prediction_algorithms import (\n AlgoBase,\n BaselineOnly,\n CoClustering,\n KNNBaseline,\n KNNBasic,\n KNNWithMeans,\n KNNWithZScore,\n NMF,\n NormalPredictor,\n Prediction,\n PredictionImpossible,\n SlopeOne,\n SVD,\n SVDpp,\n)\nfrom .reader import Reader\nfrom .trainset import Trainset\n\n__all__ = [\n \"AlgoBase\",\n \"NormalPredictor\",\n \"BaselineOnly\",\n \"KNNBasic\",\n \"KNNWithMeans\",\n \"KNNBaseline\",\n \"SVD\",\n \"SVDpp\",\n \"NMF\",\n \"SlopeOne\",\n \"CoClustering\",\n \"PredictionImpossible\",\n \"Prediction\",\n \"Dataset\",\n \"Reader\",\n \"Trainset\",\n \"dump\",\n \"KNNWithZScore\",\n \"get_dataset_dir\",\n \"model_selection\",\n]\n\n__version__ = get_distribution(\"scikit-surprise\").version\n \"\"\"This module contains the Trainset class.\"\"\"\n\n\nimport numpy as np\n\n\nclass Trainset:\n \"\"\"A trainset contains all useful data that constitute a training set.\n\n It is used by the :meth:`fit()\n ` method of every\n prediction algorithm. You should not try to build such an object on your\n own but rather use the :meth:`Dataset.folds()\n ` method or the\n :meth:`DatasetAutoFolds.build_full_trainset()\n ` method.\n\n Trainsets are different from :class:`Datasets `.\n You can think of a :class:`Dataset ` as the raw\n data, and Trainsets as higher-level data where useful methods are defined.\n Also, a :class:`Dataset ` may be comprised of\n multiple Trainsets (e.g. when doing cross validation).\n\n\n Attributes:\n ur(:obj:`defaultdict` of :obj:`list`): The users ratings. This is a\n dictionary containing lists of tuples of the form ``(item_inner_id,\n rating)``. The keys are user inner ids.\n ir(:obj:`defaultdict` of :obj:`list`): The items ratings. This is a\n dictionary containing lists of tuples of the form ``(user_inner_id,\n rating)``. The keys are item inner ids.\n n_users: Total number of users :math:`|U|`.\n n_items: Total number of items :math:`|I|`.\n n_ratings: Total number of ratings :math:`|R_{train}|`.\n rating_scale(tuple): The minimum and maximal rating of the rating\n scale.\n global_mean: The mean of all ratings :math:`\\\\\\\\mu`.\n \"\"\"\n\n def __init__(\n self,\n ur,\n ir,\n n_users,\n n_items,\n n_ratings,\n rating_scale,\n raw2inner_id_users,\n raw2inner_id_items,\n ):\n\n self.ur = ur\n self.ir = ir\n self.n_users = n_users\n self.n_items = n_items\n self.n_ratings = n_ratings\n self.rating_scale = rating_scale\n self._raw2inner_id_users = raw2inner_id_users\n self._raw2inner_id_items = raw2inner_id_items\n self._global_mean = None\n # inner2raw dicts could be built right now (or even before) but they\n # are not always useful so we wait until we need them.\n self._inner2raw_id_users = None\n self._inner2raw_id_items = None\n\n def knows_user(self, uid):\n \"\"\"Indicate if the user is part of the trainset.\n\n A user is part of the trainset if the user has at least one rating.\n\n Args:\n uid(int): The (inner) user id. See :ref:`this\n note`.\n Returns:\n ``True`` if user is part of the trainset, else ``False``.\n \"\"\"\n\n return uid in self.ur\n\n def knows_item(self, iid):\n \"\"\"Indicate if the item is part of the trainset.\n\n An item is part of the trainset if the item was rated at least once.\n\n Args:\n iid(int): The (inner) item id. See :ref:`this\n note`.\n Returns:\n ``True`` if item is part of the trainset, else ``False``.\n \"\"\"\n\n return iid in self.ir\n\n def to_inner_uid(self, ruid):\n \"\"\"Convert a **user** raw id to an inner id.\n\n See :ref:`this note`.\n\n Args:\n ruid(str): The user raw id.\n\n Returns:\n int: The user inner id.\n\n Raises:\n ValueError: When user is not part of the trainset.\n \"\"\"\n\n try:\n return self._raw2inner_id_users[ruid]\n except KeyError:\n raise ValueError(\"User \" + str(ruid) + \" is not part of the trainset.\")\n\n def to_raw_uid(self, iuid):\n \"\"\"Convert a **user** inner id to a raw id.\n\n See :ref:`this note`.\n\n Args:\n iuid(int): The user inner id.\n\n Returns:\n str: The user raw id.\n\n Raises:\n ValueError: When ``iuid`` is not an inner id.\n \"\"\"\n\n if self._inner2raw_id_users is None:\n self._inner2raw_id_users = {\n inner: raw for (raw, inner) in self._raw2inner_id_users.items()\n }\n\n try:\n return self._inner2raw_id_users[iuid]\n except KeyError:\n raise ValueError(str(iuid) + \" is not a valid inner id.\")\n\n def to_inner_iid(self, riid):\n \"\"\"Convert an **item** raw id to an inner id.\n\n See :ref:`this note`.\n\n Args:\n riid(str): The item raw id.\n\n Returns:\n int: The item inner id.\n\n Raises:\n ValueError: When item is not part of the trainset.\n \"\"\"\n\n try:\n return self._raw2inner_id_items[riid]\n except KeyError:\n raise ValueError(\"Item \" + str(riid) + \" is not part of the trainset.\")\n\n def to_raw_iid(self, iiid):\n \"\"\"Convert an **item** inner id to a raw id.\n\n See :ref:`this note`.\n\n Args:\n iiid(int): The item inner id.\n\n Returns:\n str: The item raw id.\n\n Raises:\n ValueError: When ``iiid`` is not an inner id.\n \"\"\"\n\n if self._inner2raw_id_items is None:\n self._inner2raw_id_items = {\n inner: raw for (raw, inner) in self._raw2inner_id_items.items()\n }\n\n try:\n return self._inner2raw_id_items[iiid]\n except KeyError:\n raise ValueError(str(iiid) + \" is not a valid inner id.\")\n\n def all_ratings(self):\n \"\"\"Generator function to iterate over all ratings.\n\n Yields:\n A tuple ``(uid, iid, rating)`` where ids are inner ids (see\n :ref:`this note `).\n \"\"\"\n\n for u, u_ratings in self.ur.items():\n for i, r in u_ratings:\n yield u, i, r\n\n def build_testset(self):\n \"\"\"Return a list of ratings that can be used as a testset in the\n :meth:`test() `\n method.\n\n The ratings are all the ratings that are in the trainset, i.e. all the\n ratings returned by the :meth:`all_ratings()\n ` generator. This is useful in\n cases where you want to to test your algorithm on the trainset.\n \"\"\"\n\n return [\n (self.to_raw_uid(u), self.to_raw_iid(i), r)\n for (u, i, r) in self.all_ratings()\n ]\n\n def build_anti_testset(self, fill=None):\n \"\"\"Return a list of ratings that can be used as a testset in the\n :meth:`test() `\n method.\n\n The ratings are all the ratings that are **not** in the trainset, i.e.\n all the ratings :math:`r_{ui}` where the user :math:`u` is known, the\n item :math:`i` is known, but the rating :math:`r_{ui}` is not in the\n trainset. As :math:`r_{ui}` is unknown, it is either replaced by the\n :code:`fill` value or assumed to be equal to the mean of all ratings\n :meth:`global_mean `.\n\n Args:\n fill(float): The value to fill unknown ratings. If :code:`None` the\n global mean of all ratings :meth:`global_mean\n ` will be used.\n\n Returns:\n A list of tuples ``(uid, iid, fill)`` where ids are raw ids.\n \"\"\"\n fill = self.global_mean if fill is None else float(fill)\n\n anti_testset = []\n for u in self.all_users():\n user_items = {j for (j, _) in self.ur[u]}\n anti_testset += [\n (self.to_raw_uid(u), self.to_raw_iid(i), fill)\n for i in self.all_items()\n if i not in user_items\n ]\n return anti_testset\n\n def all_users(self):\n \"\"\"Generator function to iterate over all users.\n\n Yields:\n Inner id of users.\n \"\"\"\n return range(self.n_users)\n\n def all_items(self):\n \"\"\"Generator function to iterate over all items.\n\n Yields:\n Inner id of items.\n \"\"\"\n return range(self.n_items)\n\n @property\n def global_mean(self):\n if self._global_mean is None:\n self._global_mean = np.mean([r for (_, _, r) in self.all_ratings()])\n\n return self._global_mean\n \"\"\"This module contains the Reader class.\"\"\"\n\n\nfrom .builtin_datasets import BUILTIN_DATASETS\n\n\nclass Reader:\n \"\"\"The Reader class is used to parse a file containing ratings.\n\n Such a file is assumed to specify only one rating per line, and each line\n needs to respect the following structure: ::\n\n user ; item ; rating ; [timestamp]\n\n where the order of the fields and the separator (here ';') may be\n arbitrarily defined (see below). brackets indicate that the timestamp\n field is optional.\n\n For each built-in dataset, Surprise also provides predefined readers which\n are useful if you want to use a custom dataset that has the same format as\n a built-in one (see the ``name`` parameter).\n\n\n Args:\n name(:obj:`string`, optional): If specified, a Reader for one of the\n built-in datasets is returned and any other parameter is ignored.\n Accepted values are 'ml-100k', 'ml-1m', and 'jester'. Default\n is ``None``.\n line_format(:obj:`string`): The fields names, in the order at which\n they are encountered on a line. Please note that ``line_format`` is\n", "instruction": "", "output": "" }, { "input": " always space-separated (use the ``sep`` parameter). Default is\n ``'user item rating'``.\n sep(char): the separator between fields. Example : ``';'``.\n rating_scale(:obj:`tuple`, optional): The rating scale used for every\n rating. Default is ``(1, 5)``.\n skip_lines(:obj:`int`, optional): Number of lines to skip at the\n beginning of the file. Default is ``0``.\n\n \"\"\"\n\n def __init__(\n self,\n name=None,\n line_format=\"user item rating\",\n sep=None,\n rating_scale=(1, 5),\n skip_lines=0,\n ):\n\n if name:\n try:\n self.__init__(**BUILTIN_DATASETS[name].reader_params)\n except KeyError:\n raise ValueError(\n \"unknown reader \"\n + name\n + \". Accepted values are \"\n + \", \".join(BUILTIN_DATASETS.keys())\n + \".\"\n )\n else:\n self.sep = sep\n self.skip_lines = skip_lines\n self.rating_scale = rating_scale\n\n lower_bound, higher_bound = rating_scale\n\n splitted_format = line_format.split()\n\n entities = [\"user\", \"item\", \"rating\"]\n if \"timestamp\" in splitted_format:\n self.with_timestamp = True\n entities.append(\"timestamp\")\n else:\n self.with_timestamp = False\n\n # check that all fields are correct\n if any(field not in entities for field in splitted_format):\n raise ValueError(\"line_format parameter is incorrect.\")\n\n self.indexes = [splitted_format.index(entity) for entity in entities]\n\n def parse_line(self, line):\n \"\"\"Parse a line.\n\n Ratings are translated so that they are all strictly positive.\n\n Args:\n line(str): The line to parse\n\n Returns:\n tuple: User id, item id, rating and timestamp. The timestamp is set\n to ``None`` if it does no exist.\n \"\"\"\n\n line = line.split(self.sep)\n try:\n if self.with_timestamp:\n uid, iid, r, timestamp = (line[i].strip() for i in self.indexes)\n else:\n uid, iid, r = (line[i].strip() for i in self.indexes)\n timestamp = None\n\n except IndexError:\n raise ValueError(\n \"Impossible to parse line. Check the line_format\" \" and sep parameters.\"\n )\n\n return uid, iid, float(r), timestamp\n \"\"\"\nThe :mod:`surprise.accuracy` module provides tools for computing accuracy\nmetrics on a set of predictions.\n\nAvailable accuracy metrics:\n\n.. autosummary::\n :nosignatures:\n\n rmse\n mse\n mae\n fcp\n\"\"\"\n\nfrom collections import defaultdict\n\nimport numpy as np\n\n\ndef rmse(predictions, verbose=True):\n \"\"\"Compute RMSE (Root Mean Squared Error).\n\n .. math::\n \\\\\\\\text{RMSE} = \\\\\\\\sqrt{\\\\\\\\frac{1}{|\\\\\\\\hat{R}|} \\\\\\\\sum_{\\\\\\\\hat{r}_{ui} \\\\\\\\in\n \\\\\\\\hat{R}}(r_{ui} - \\\\\\\\hat{r}_{ui})^2}.\n\n Args:\n predictions (:obj:`list` of :obj:`Prediction\\\\\n `):\n A list of predictions, as returned by the :meth:`test()\n ` method.\n verbose: If True, will print computed value. Default is ``True``.\n\n\n Returns:\n The Root Mean Squared Error of predictions.\n\n Raises:\n ValueError: When ``predictions`` is empty.\n \"\"\"\n\n if not predictions:\n raise ValueError(\"Prediction list is empty.\")\n\n mse = np.mean(\n [float((true_r - est) ** 2) for (_, _, true_r, est, _) in predictions]\n )\n rmse_ = np.sqrt(mse)\n\n if verbose:\n print(f\"RMSE: {rmse_:1.4f}\")\n\n return rmse_\n\n\ndef mse(predictions, verbose=True):\n \"\"\"Compute MSE (Mean Squared Error).\n\n .. math::\n \\\\\\\\text{MSE} = \\\\\\\\frac{1}{|\\\\\\\\hat{R}|} \\\\\\\\sum_{\\\\\\\\hat{r}_{ui} \\\\\\\\in\n \\\\\\\\hat{R}}(r_{ui} - \\\\\\\\hat{r}_{ui})^2.\n\n Args:\n predictions (:obj:`list` of :obj:`Prediction\\\\\n `):\n A list of predictions, as returned by the :meth:`test()\n ` method.\n verbose: If True, will print computed value. Default is ``True``.\n\n\n Returns:\n The Mean Squared Error of predictions.\n\n Raises:\n ValueError: When ``predictions`` is empty.\n \"\"\"\n\n if not predictions:\n raise ValueError(\"Prediction list is empty.\")\n\n mse_ = np.mean(\n [float((true_r - est) ** 2) for (_, _, true_r, est, _) in predictions]\n )\n\n if verbose:\n print(f\"MSE: {mse_:1.4f}\")\n\n return mse_\n\n\ndef mae(predictions, verbose=True):\n \"\"\"Compute MAE (Mean Absolute Error).\n\n .. math::\n \\\\\\\\text{MAE} = \\\\\\\\frac{1}{|\\\\\\\\hat{R}|} \\\\\\\\sum_{\\\\\\\\hat{r}_{ui} \\\\\\\\in\n \\\\\\\\hat{R}}|r_{ui} - \\\\\\\\hat{r}_{ui}|\n\n Args:\n predictions (:obj:`list` of :obj:`Prediction\\\\\n `):\n A list of predictions, as returned by the :meth:`test()\n ` method.\n verbose: If True, will print computed value. Default is ``True``.\n\n\n Returns:\n The Mean Absolute Error of predictions.\n\n Raises:\n ValueError: When ``predictions`` is empty.\n \"\"\"\n\n if not predictions:\n raise ValueError(\"Prediction list is empty.\")\n\n mae_ = np.mean([float(abs(true_r - est)) for (_, _, true_r, est, _) in predictions])\n\n if verbose:\n print(f\"MAE: {mae_:1.4f}\")\n\n return mae_\n\n\ndef fcp(predictions, verbose=True):\n \"\"\"Compute FCP (Fraction of Concordant Pairs).\n\n Computed as described in paper `Collaborative Filtering on Ordinal User\n Feedback `_ by Koren\n and Sill, section 5.2.\n\n Args:\n predictions (:obj:`list` of :obj:`Prediction\\\\\n `):\n A list of predictions, as returned by the :meth:`test()\n ` method.\n verbose: If True, will print computed value. Default is ``True``.\n\n\n Returns:\n The Fraction of Concordant Pairs.\n\n Raises:\n ValueError: When ``predictions`` is empty.\n \"\"\"\n\n if not predictions:\n raise ValueError(\"Prediction list is empty.\")\n\n predictions_u = defaultdict(list)\n nc_u = defaultdict(int)\n nd_u = defaultdict(int)\n\n for u0, _, r0, est, _ in predictions:\n predictions_u[u0].append((r0, est))\n\n for u0, preds in predictions_u.items():\n for r0i, esti in preds:\n for r0j, estj in preds:\n if esti > estj and r0i > r0j:\n nc_u[u0] += 1\n if esti >= estj and r0i < r0j:\n nd_u[u0] += 1\n\n nc = np.mean(list(nc_u.values())) if nc_u else 0\n nd = np.mean(list(nd_u.values())) if nd_u else 0\n\n try:\n fcp = nc / (nc + nd)\n except ZeroDivisionError:\n raise ValueError(\n \"cannot compute fcp on this list of prediction. \"\n + \"Does every user have at least two predictions?\"\n )\n\n if verbose:\n print(f\"FCP: {fcp:1.4f}\")\n\n return fcp\n from abc import ABC, abstractmethod\nfrom itertools import product\n\nimport numpy as np\nfrom joblib import delayed, Parallel\n\nfrom ..dataset import DatasetUserFolds\nfrom ..utils import get_rng\n\nfrom .split import get_cv\nfrom .validation import fit_and_score\n\n\nclass BaseSearchCV(ABC):\n \"\"\"Base class for hyper parameter search with cross-validation.\"\"\"\n\n @abstractmethod\n def __init__(\n self,\n algo_class,\n measures=[\"rmse\", \"mae\"],\n cv=None,\n refit=False,\n return_train_measures=False,\n n_jobs=1,\n pre_dispatch=\"2*n_jobs\",\n joblib_verbose=0,\n ):\n\n self.algo_class = algo_class\n self.measures = [measure.lower() for measure in measures]\n self.cv = cv\n\n if isinstance(refit, str):\n if refit.lower() not in self.measures:\n raise ValueError(\n \"It looks like the measure you want to use \"\n \"with refit ({}) is not in the measures \"\n \"parameter\"\n )\n\n self.refit = refit.lower()\n\n elif refit is True:\n self.refit = self.measures[0]\n\n else:\n self.refit = False\n\n self.return_train_measures = return_train_measures\n self.n_jobs = n_jobs\n self.pre_dispatch = pre_dispatch\n self.joblib_verbose = joblib_verbose\n\n def _parse_options(self, params):\n # As sim_options and bsl_options are dictionaries, they require a\n # special treatment.\n\n if \"sim_options\" in params:\n sim_options = params[\"sim_options\"]\n sim_options_list = [\n dict(zip(sim_options, v)) for v in product(*sim_options.values())\n ]\n params[\"sim_options\"] = sim_options_list\n\n if \"bsl_options\" in params:\n bsl_options = params[\"bsl_options\"]\n bsl_options_list = [\n dict(zip(bsl_options, v)) for v in product(*bsl_options.values())\n ]\n params[\"bsl_options\"] = bsl_options_list\n\n return params\n\n def fit(self, data):\n \"\"\"Runs the ``fit()`` method of the algorithm for all parameter\n combinations, over different splits given by the ``cv`` parameter.\n\n Args:\n data (:obj:`Dataset `): The dataset on\n which to evaluate the algorithm, in parallel.\n \"\"\"\n\n if self.refit and isinstance(data, DatasetUserFolds):\n raise ValueError(\n \"refit cannot be used when data has been \"\n \"loaded with load_from_folds().\"\n )\n\n cv = get_cv(self.cv)\n\n delayed_list = (\n delayed(fit_and_score)(\n self.algo_class(**params),\n trainset,\n testset,\n self.measures,\n self.return_train_measures,\n )\n for params, (trainset, testset) in product(\n self.param_combinations, cv.split(data)\n )\n )\n out = Parallel(\n n_jobs=self.n_jobs,\n pre_dispatch=self.pre_dispatch,\n verbose=self.joblib_verbose,\n )(delayed_list)\n\n (test_measures_dicts, train_measures_dicts, fit_times, test_times) = zip(*out)\n\n # test_measures_dicts is a list of dict like this:\n # [{'mae': 1, 'rmse': 2}, {'mae': 2, 'rmse': 3} ...]\n # E.g. for 5 splits, the first 5 dicts are for the first param\n # combination, the next 5 dicts are for the second param combination,\n # etc...\n # We convert it into a dict of list:\n # {'mae': [1, 2, ...], 'rmse': [2, 3, ...]}\n # Each list is still of size n_parameters_combinations * n_splits.\n # Then, reshape each list to have 2-D arrays of shape\n # (n_parameters_combinations, n_splits). This way we can easily compute\n # the mean and std dev over all splits or over all param comb.\n test_measures = dict()\n train_measures = dict()\n new_shape = (len(self.param_combinations), cv.get_n_folds())\n for m in self.measures:\n test_measures[m] = np.asarray([d[m] for d in test_measures_dicts])\n test_measures[m] = test_measures[m].reshape(new_shape)\n if self.return_train_measures:\n train_measures[m] = np.asarray([d[m] for d in train_measures_dicts])\n train_measures[m] = train_measures[m].reshape(new_shape)\n\n cv_results = dict()\n best_index = dict()\n best_params = dict()\n best_score = dict()\n best_estimator = dict()\n for m in self.measures:\n # cv_results: set measures for each split and each param comb\n for split in range(cv.get_n_folds()):\n cv_results[f\"split{split}_test_{m}\"] = test_measures[m][:, split]\n if self.return_train_measures:\n cv_results[f\"split{split}_train_{m}\"] = train_measures[m][:, split]\n\n # cv_results: set mean and std over all splits (testset and\n # trainset) for each param comb\n mean_test_measures = test_measures[m].mean(axis=1)\n cv_results[f\"mean_test_{m}\"] = mean_test_measures\n cv_results[f\"std_test_{m}\"] = test_measures[m].std(axis=1)\n if self.return_train_measures:\n mean_train_measures = train_measures[m].mean(axis=1)\n cv_results[f\"mean_train_{m}\"] = mean_train_measures\n cv_results[f\"std_train_{m}\"] = train_measures[m].std(axis=1)\n\n # cv_results: set rank of each param comb\n # also set best_index, and best_xxxx attributes\n indices = cv_results[f\"mean_test_{m}\"].argsort()\n cv_results[f\"rank_test_{m}\"] = np.empty_like(indices)\n if m in (\"mae\", \"rmse\", \"mse\"):\n cv_results[f\"rank_test_{m}\"][indices] = (\n np.arange(len(ind", "instruction": "", "output": "" }, { "input": "ices)) + 1\n ) # sklearn starts at 1 as well\n best_index[m] = mean_test_measures.argmin()\n elif m in (\"fcp\",):\n cv_results[f\"rank_test_{m}\"][indices] = np.arange(len(indices), 0, -1)\n best_index[m] = mean_test_measures.argmax()\n best_params[m] = self.param_combinations[best_index[m]]\n best_score[m] = mean_test_measures[best_index[m]]\n best_estimator[m] = self.algo_class(**best_params[m])\n\n # Cv results: set fit and train times (mean, std)\n fit_times = np.array(fit_times).reshape(new_shape)\n test_times = np.array(test_times).reshape(new_shape)\n for s, times in zip((\"fit\", \"test\"), (fit_times, test_times)):\n cv_results[f\"mean_{s}_time\"] = times.mean(axis=1)\n cv_results[f\"std_{s}_time\"] = times.std(axis=1)\n\n # cv_results: set params key and each param_* values\n cv_results[\"params\"] = self.param_combinations\n for param in self.param_combinations[0]:\n cv_results[\"param_\" + param] = [\n comb[param] for comb in self.param_combinations\n ]\n\n if self.refit:\n best_estimator[self.refit].fit(data.build_full_trainset())\n\n self.best_index = best_index\n self.best_params = best_params\n self.best_score = best_score\n self.best_estimator = best_estimator\n self.cv_results = cv_results\n\n def test(self, testset, verbose=False):\n \"\"\"Call ``test()`` on the estimator with the best found parameters\n (according the the ``refit`` parameter). See :meth:`AlgoBase.test()\n `.\n\n Only available if ``refit`` is not ``False``.\n \"\"\"\n\n if not self.refit:\n raise ValueError(\"refit is False, cannot use test()\")\n\n return self.best_estimator[self.refit].test(testset, verbose)\n\n def predict(self, *args):\n \"\"\"Call ``predict()`` on the estimator with the best found parameters\n (according the the ``refit`` parameter). See :meth:`AlgoBase.predict()\n `.\n\n Only available if ``refit`` is not ``False``.\n \"\"\"\n\n if not self.refit:\n raise ValueError(\"refit is False, cannot use predict()\")\n\n return self.best_estimator[self.refit].predict(*args)\n\n\nclass GridSearchCV(BaseSearchCV):\n \"\"\"The :class:`GridSearchCV` class computes accuracy metrics for an\n algorithm on various combinations of parameters, over a cross-validation\n procedure. This is useful for finding the best set of parameters for a\n prediction algorithm. It is analogous to `GridSearchCV\n `_ from scikit-learn.\n\n See an example in the :ref:`User Guide `.\n\n Args:\n algo_class(:obj:`AlgoBase \\\\\n `): The class\n of the algorithm to evaluate.\n param_grid(dict): Dictionary with algorithm parameters as keys and\n list of values as keys. All combinations will be evaluated with\n desired algorithm. Dict parameters such as ``sim_options`` require\n special treatment, see :ref:`this note`.\n measures(list of string): The performance measures to compute. Allowed\n names are function names as defined in the :mod:`accuracy\n ` module. Default is ``['rmse', 'mae']``.\n cv(cross-validation iterator, int or ``None``): Determines how the\n ``data`` parameter will be split (i.e. how trainsets and testsets\n will be defined). If an int is passed, :class:`KFold\n ` is used with the\n appropriate ``n_splits`` parameter. If ``None``, :class:`KFold\n ` is used with\n ``n_splits=5``.\n refit(bool or str): If ``True``, refit the algorithm on the whole\n dataset using the set of parameters that gave the best average\n performance for the first measure of ``measures``. Other measures\n can be used by passing a string (corresponding to the measure\n name). Then, you can use the ``test()`` and ``predict()`` methods.\n ``refit`` can only be used if the ``data`` parameter given to\n ``fit()`` hasn't been loaded with :meth:`load_from_folds()\n `. Default is ``False``.\n return_train_measures(bool): Whether to compute performance measures on\n the trainsets. If ``True``, the ``cv_results`` attribute will\n also contain measures for trainsets. Default is ``False``.\n n_jobs(int): The maximum number of parallel training procedures.\n\n - If ``-1``, all CPUs are used.\n - If ``1`` is given, no parallel computing code is used at all,\\\\\n which is useful for debugging.\n - For ``n_jobs`` below ``-1``, ``(n_cpus + n_jobs + 1)`` are\\\\\n used. For example, with ``n_jobs = -2`` all CPUs but one are\\\\\n used.\n\n Default is ``1``.\n pre_dispatch(int or string): Controls the number of jobs that get\n dispatched during parallel execution. Reducing this number can be\n useful to avoid an explosion of memory consumption when more jobs\n get dispatched than CPUs can process. This parameter can be:\n\n - ``None``, in which case all the jobs are immediately created\\\\\n and spawned. Use this for lightweight and fast-running\\\\\n jobs, to avoid delays due to on-demand spawning of the\\\\\n jobs.\n - An int, giving the exact number of total jobs that are\\\\\n spawned.\n - A string, giving an expression as a function of ``n_jobs``,\\\\\n as in ``'2*n_jobs'``.\n\n Default is ``'2*n_jobs'``.\n joblib_verbose(int): Controls the verbosity of joblib: the higher, the\n more messages.\n\n Attributes:\n best_estimator (dict of AlgoBase):\n Using an accuracy measure as key, get the algorithm that gave the\n best accuracy results for the chosen measure, averaged over all\n splits.\n best_score (dict of floats):\n Using an accuracy measure as key, get the best average score\n achieved for that measure.\n best_params (dict of dicts):\n Using an accuracy measure as key, get the parameters combination\n that gave the best accuracy results for the chosen measure (on\n average).\n best_index (dict of ints):\n Using an accuracy measure as key, get the index that can be used\n with ``cv_results`` that achieved the highest accuracy for that\n measure (on average).\n cv_results (dict of arrays):\n A dict that contains accuracy measures over all splits, as well as\n train and test time for each parameter combination. Can be imported\n into a pandas `DataFrame` (see :ref:`example\n `).\n \"\"\"\n\n def __init__(\n self,\n algo_class,\n param_grid,\n measures=[\"rmse\", \"mae\"],\n cv=None,\n refit=False,\n return_train_measures=False,\n n_jobs=1,\n pre_dispatch=\"2*n_jobs\",\n joblib_verbose=0,\n ):\n\n super().__init__(\n algo_class=algo_class,\n measures=measures,\n cv=cv,\n refit=refit,\n return_train_measures=return_train_measures,\n n_jobs=n_jobs,\n pre_dispatch=pre_dispatch,\n joblib_verbose=joblib_verbose,\n )\n\n self.param_grid = self._parse_options(param_grid.copy())\n self.param_combinations = [\n dict(zip(self.param_grid, v)) for v in product(*self.param_grid.values())\n ]\n\n\nclass RandomizedSearchCV(BaseSearchCV):\n \"\"\"The :class:`RandomizedSearchCV` class computes accuracy metrics for an\n algorithm on various combinations of parameters, over a cross-validation\n procedure. As opposed to GridSearchCV, which uses an exhaustive\n combinatorial approach, RandomizedSearchCV samples randomly from the\n parameter space. This is useful for finding the best set of parameters\n for a prediction algorithm, especially using a coarse to fine approach.\n It is analogous to `RandomizedSearchCV `_ from\n scikit-learn.\n\n See an example in the :ref:`User Guide `.\n\n Args:\n algo_class(:obj:`AlgoBase \\\\\n `): The class\n of the algorithm to evaluate.\n param_distributions(dict): Dictionary with algorithm parameters as\n keys and distributions or lists of parameters to try. Distributions\n must provide a rvs method for sampling (such as those from\n scipy.stats.distributions). If a list is given, it is sampled\n uniformly. Parameters will be sampled n_iter times.\n n_iter(int): Number of times parameter settings are sampled. Default is\n ``10``.\n measures(list of string): The performance measures to compute. Allowed\n names are function names as defined in the :mod:`accuracy\n ` module. Default is ``['rmse', 'mae']``.\n cv(cross-validation iterator, int or ``None``): Determines how the\n ``data`` parameter will be split (i.e. how trainsets and testsets\n will be defined). If an int is passed, :class:`KFold\n ` is used with the\n appropriate ``n_splits`` parameter. If ``None``, :class:`KFold\n ` is used with\n ``n_splits=5``.\n refit(bool or str): If ``True``, refit the algorithm on the whole\n dataset using the set of parameters that gave the best average\n performance for the first measure of ``measures``. Other measures\n can be used by passing a string (corresponding to the measure\n name). Then, you can use the ``test()`` and ``predict()`` methods.\n ``refit`` can only be used if the ``data`` parameter given to\n ``fit()`` hasn't been loaded with :meth:`load_from_folds()\n `. Default is ``False``.\n return_train_measures(bool): Whether to compute performance measures on\n the trainsets. If ``True``, the ``cv_results`` attribute will\n also contain measures for trainsets. Default is ``False``.\n n_jobs(int): The maximum number of parallel training procedures.\n\n - If ``-1``, all CPUs are used.\n - If ``1`` is given, no parallel computing code is used at all,\\\\\n which is useful for debugging.\n - For ``n_jobs`` below ``-1``, ``(n_cpus + n_jobs + 1)`` are\\\\\n used. For example, with ``n_jobs = -2`` all CPUs but one are\\\\\n used.\n\n Default is ``1``.\n pre_dispatch(int or string): Controls the number of jobs that get\n dispatched during parallel execution. Reducing this number can be\n useful to avoid an explosion of memory consumption when more jobs\n get dispatched than CPUs can process. This parameter can be:\n\n - ``None``, in which case all the jobs are immediately created\\\\\n and spawned. Use this for lightweight and fast-running\\\\\n jobs, to avoid delays due to on-demand spawning of the\\\\\n jobs.\n - An int, giving the exact number of total jobs that are\\\\\n spawned.\n - A string, giving an expression as a function of ``n_jobs``,\\\\\n as in ``'2*n_jobs'``.\n\n Default is ``'2*n_jobs'``.\n random_state(int, RandomState or None): Pseudo random number\n generator seed used for random uniform sampling from lists of\n possible values instead of scipy.stats distributions. If int,\n ``random_state`` is the seed used by the random number generator.\n If ``RandomState`` instance, ``random_state`` is the random number\n generator. If ``None``, the random number generator is the\n RandomState instance used by ``np.random``. Default is ``None``.\n joblib_verbose(int): Controls the verbosity of joblib: the higher, the\n more messages.\n\n Attributes:\n best_estimator (dict of AlgoBase):\n Using an accuracy measure as key, get the algorithm that gave the\n best accuracy results for the chosen measure, averaged over all\n splits.\n best_score (dict of floats):\n Using an accuracy measure as key, get the best average score\n achieved for that measure.\n best_params (dict of dicts):\n Using an accuracy measure as key, get the parameters combination\n that gave the best accuracy results for the chosen measure (on\n average).\n best_index (dict of ints):\n Using an accuracy measure as key, get the index that can be used\n with ``cv_results`` that achieved the highest accuracy for that\n measure (on average).\n cv_results (dict of arrays):\n A dict that contains accuracy measures over all splits, as well as\n train and test time for each parameter combination. Can be imported\n into a pandas `DataFrame` (see :ref:`example\n `).\n \"\"\"\n\n def __init__(\n self,\n algo_class,\n param_distributions,\n n_iter=10,\n measures=[\"rmse\", \"mae\"],\n cv=None,\n refit=False,\n return_train_measures=False,\n n_jobs=1,\n pre_dispatch=\"2*n_jobs\",\n random_state=None,\n joblib_verbose=0,\n ):\n\n super().__init__(\n algo_class=algo_class,\n measures=measures,\n cv=cv,\n refit=refit,\n return_train_measures=return_train_measures,\n n_jobs=n_jobs,\n pre_dispatch=pre_dispatch,\n joblib_verbose=joblib_verbose,\n )\n\n self.n_iter = n_iter\n self.random_state = random_state\n self.param_distributions = self._parse_options(param_distributions.copy())\n self.param_combinations = self._sample_parameters(\n self.param_distributions, self.n_iter, self.random_state\n )\n\n @staticmethod\n def _sample_parameters(param_distributions, n_iter, random_state=None):\n \"\"\"Samples ``n_iter`` parameter combinations from\n ``param_distributions`` using ``random_state`` as a seed.\n\n Non-deterministic iterable over random candidate combinations for\n hyper-parameter search. If all parameters are presented as a list,\n sampling without replacement is performed. If at least one parameter\n is given as a", "instruction": "", "output": "" }, { "input": "distribution, sampling with replacement is used.\n It is highly recommended to use continuous distributions for continuous\n parameters.\n\n Note that before SciPy 0.16, the ``scipy.stats.distributions`` do not\n accept a custom RNG instance and always use the singleton RNG from\n ``numpy.random``. Hence setting ``random_state`` will not guarantee a\n deterministic iteration whenever ``scipy.stats`` distributions are used\n to define the parameter search space. Deterministic behavior is however\n guaranteed from SciPy 0.16 onwards.\n\n Args:\n param_distributions(dict): Dictionary where the keys are\n parameters and values are distributions from which a parameter\n is to be sampled. Distributions either have to provide a\n ``rvs`` function to sample from them, or can be given as a list\n of values, where a uniform distribution is assumed.\n n_iter(int): Number of parameter settings produced.\n Default is ``10``.\n random_state(int, RandomState instance or None):\n Pseudo random number generator seed used for random uniform\n sampling from lists of possible values instead of scipy.stats\n distributions. If ``None``, the random number generator is the\n random state instance used by np.random. Default is ``None``.\n\n Returns:\n combos(list): List of parameter dictionaries with sampled values.\n \"\"\"\n\n # check if all distributions are given as lists\n # if so, sample without replacement\n all_lists = np.all(\n [not hasattr(v, \"rvs\") for v in param_distributions.values()]\n )\n rnd = get_rng(random_state)\n\n # sort for reproducibility\n items = sorted(param_distributions.items())\n\n if all_lists:\n # create exhaustive combinations\n param_grid = [\n dict(zip(param_distributions, v))\n for v in product(*param_distributions.values())\n ]\n combos = np.random.choice(param_grid, n_iter, replace=False)\n\n else:\n combos = []\n for _ in range(n_iter):\n params = dict()\n for k, v in items:\n if hasattr(v, \"rvs\"):\n params[k] = v.rvs(random_state=rnd)\n else:\n params[k] = v[rnd.randint(len(v))]\n combos.append(params)\n\n return combos\n \"\"\"\nThe validation module contains the cross_validate function, inspired from\nthe mighty scikit learn.\n\"\"\"\n\nimport time\n\nimport numpy as np\nfrom joblib import delayed, Parallel\n\nfrom .. import accuracy\n\nfrom .split import get_cv\n\n\ndef cross_validate(\n algo,\n data,\n measures=[\"rmse\", \"mae\"],\n cv=None,\n return_train_measures=False,\n n_jobs=1,\n pre_dispatch=\"2*n_jobs\",\n verbose=False,\n):\n \"\"\"\n Run a cross validation procedure for a given algorithm, reporting accuracy\n measures and computation times.\n\n See an example in the :ref:`User Guide `.\n\n Args:\n algo(:obj:`AlgoBase \\\\\n `):\n The algorithm to evaluate.\n data(:obj:`Dataset `): The dataset on which\n to evaluate the algorithm.\n measures(list of string): The performance measures to compute. Allowed\n names are function names as defined in the :mod:`accuracy\n ` module. Default is ``['rmse', 'mae']``.\n cv(cross-validation iterator, int or ``None``): Determines how the\n ``data`` parameter will be split (i.e. how trainsets and testsets\n will be defined). If an int is passed, :class:`KFold\n ` is used with the\n appropriate ``n_splits`` parameter. If ``None``, :class:`KFold\n ` is used with\n ``n_splits=5``.\n return_train_measures(bool): Whether to compute performance measures on\n the trainsets. Default is ``False``.\n n_jobs(int): The maximum number of folds evaluated in parallel.\n\n - If ``-1``, all CPUs are used.\n - If ``1`` is given, no parallel computing code is used at all,\\\\\n which is useful for debugging.\n - For ``n_jobs`` below ``-1``, ``(n_cpus + n_jobs + 1)`` are\\\\\n used. For example, with ``n_jobs = -2`` all CPUs but one are\\\\\n used.\n\n Default is ``1``.\n pre_dispatch(int or string): Controls the number of jobs that get\n dispatched during parallel execution. Reducing this number can be\n useful to avoid an explosion of memory consumption when more jobs\n get dispatched than CPUs can process. This parameter can be:\n\n - ``None``, in which case all the jobs are immediately created\\\\\n and spawned. Use this for lightweight and fast-running\\\\\n jobs, to avoid delays due to on-demand spawning of the\\\\\n jobs.\n - An int, giving the exact number of total jobs that are\\\\\n spawned.\n - A string, giving an expression as a function of ``n_jobs``,\\\\\n as in ``'2*n_jobs'``.\n\n Default is ``'2*n_jobs'``.\n verbose(int): If ``True`` accuracy measures for each split are printed,\n as well as train and test times. Averages and standard deviations\n over all splits are also reported. Default is ``False``: nothing is\n printed.\n\n Returns:\n dict: A dict with the following keys:\n\n - ``'test_*'`` where ``*`` corresponds to a lower-case accuracy\n measure, e.g. ``'test_rmse'``: numpy array with accuracy values\n for each testset.\n\n - ``'train_*'`` where ``*`` corresponds to a lower-case accuracy\n measure, e.g. ``'train_rmse'``: numpy array with accuracy values\n for each trainset. Only available if ``return_train_measures`` is\n ``True``.\n\n - ``'fit_time'``: numpy array with the training time in seconds for\n each split.\n\n - ``'test_time'``: numpy array with the testing time in seconds for\n each split.\n\n \"\"\"\n\n measures = [m.lower() for m in measures]\n\n cv = get_cv(cv)\n\n delayed_list = (\n delayed(fit_and_score)(algo, trainset, testset, measures, return_train_measures)\n for (trainset, testset) in cv.split(data)\n )\n out = Parallel(n_jobs=n_jobs, pre_dispatch=pre_dispatch)(delayed_list)\n\n (test_measures_dicts, train_measures_dicts, fit_times, test_times) = zip(*out)\n\n test_measures = dict()\n train_measures = dict()\n ret = dict()\n for m in measures:\n # transform list of dicts into dict of lists\n # Same as in GridSearchCV.fit()\n test_measures[m] = np.asarray([d[m] for d in test_measures_dicts])\n ret[\"test_\" + m] = test_measures[m]\n if return_train_measures:\n train_measures[m] = np.asarray([d[m] for d in train_measures_dicts])\n ret[\"train_\" + m] = train_measures[m]\n\n ret[\"fit_time\"] = fit_times\n ret[\"test_time\"] = test_times\n\n if verbose:\n print_summary(\n algo,\n measures,\n test_measures,\n train_measures,\n fit_times,\n test_times,\n cv.n_splits,\n )\n\n return ret\n\n\ndef fit_and_score(algo, trainset, testset, measures, return_train_measures=False):\n \"\"\"Helper method that trains an algorithm and compute accuracy measures on\n a testset. Also report train and test times.\n\n Args:\n algo(:obj:`AlgoBase \\\\\n `):\n The algorithm to use.\n trainset(:obj:`Trainset `): The trainset.\n testset(:obj:`testset`): The testset.\n measures(list of string): The performance measures to compute. Allowed\n names are function names as defined in the :mod:`accuracy\n ` module.\n return_train_measures(bool): Whether to compute performance measures on\n the trainset. Default is ``False``.\n\n Returns:\n tuple: A tuple containing:\n\n - A dictionary mapping each accuracy metric to its value on the\n testset (keys are lower case).\n\n - A dictionary mapping each accuracy metric to its value on the\n trainset (keys are lower case). This dict is empty if\n return_train_measures is False.\n\n - The fit time in seconds.\n\n - The testing time in seconds.\n \"\"\"\n\n start_fit = time.time()\n algo.fit(trainset)\n fit_time = time.time() - start_fit\n start_test = time.time()\n predictions = algo.test(testset)\n test_time = time.time() - start_test\n\n if return_train_measures:\n train_predictions = algo.test(trainset.build_testset())\n\n test_measures = dict()\n train_measures = dict()\n for m in measures:\n f = getattr(accuracy, m.lower())\n test_measures[m] = f(predictions, verbose=0)\n if return_train_measures:\n train_measures[m] = f(train_predictions, verbose=0)\n\n return test_measures, train_measures, fit_time, test_time\n\n\ndef print_summary(\n algo, measures, test_measures, train_measures, fit_times, test_times, n_splits\n):\n \"\"\"Helper for printing the result of cross_validate.\"\"\"\n\n print(\n \"Evaluating {} of algorithm {} on {} split(s).\".format(\n \", \".join(m.upper() for m in measures), algo.__class__.__name__, n_splits\n )\n )\n print()\n\n row_format = \"{:<18}\" + \"{:<8}\" * (n_splits + 2)\n s = row_format.format(\n \"\", *[f\"Fold {i + 1}\" for i in range(n_splits)] + [\"Mean\"] + [\"Std\"]\n )\n s += \"\\\\n\"\n s += \"\\\\n\".join(\n row_format.format(\n key.upper() + \" (testset)\",\n *[f\"{v:1.4f}\" for v in vals]\n + [f\"{np.mean(vals):1.4f}\"]\n + [f\"{np.std(vals):1.4f}\"],\n )\n for (key, vals) in test_measures.items()\n )\n if train_measures:\n s += \"\\\\n\"\n s += \"\\\\n\".join(\n row_format.format(\n key.upper() + \" (trainset)\",\n *[f\"{v:1.4f}\" for v in vals]\n + [f\"{np.mean(vals):1.4f}\"]\n + [f\"{np.std(vals):1.4f}\"],\n )\n for (key, vals) in train_measures.items()\n )\n s += \"\\\\n\"\n s += row_format.format(\n \"Fit time\",\n *[f\"{t:.2f}\" for t in fit_times]\n + [f\"{np.mean(fit_times):.2f}\"]\n + [f\"{np.std(fit_times):.2f}\"],\n )\n s += \"\\\\n\"\n s += row_format.format(\n \"Test time\",\n *[f\"{t:.2f}\" for t in test_times]\n + [f\"{np.mean(test_times):.2f}\"]\n + [f\"{np.std(test_times):.2f}\"],\n )\n print(s)\n from .search import GridSearchCV, RandomizedSearchCV\nfrom .split import (\n KFold,\n LeaveOneOut,\n PredefinedKFold,\n RepeatedKFold,\n ShuffleSplit,\n train_test_split,\n)\n\nfrom .validation import cross_validate\n\n__all__ = [\n \"KFold\",\n \"ShuffleSplit\",\n \"train_test_split\",\n \"RepeatedKFold\",\n \"LeaveOneOut\",\n \"PredefinedKFold\",\n \"cross_validate\",\n \"GridSearchCV\",\n \"RandomizedSearchCV\",\n]\n \"\"\"\nThe :mod:`model_selection.split` module\ncontains various cross-validation iterators. Design and tools are inspired from\nthe mighty scikit learn.\n\nThe available iterators are:\n\n.. autosummary::\n :nosignatures:\n\n KFold\n RepeatedKFold\n ShuffleSplit\n LeaveOneOut\n PredefinedKFold\n\nThis module also contains a function for splitting datasets into trainset and\ntestset:\n\n.. autosummary::\n :nosignatures:\n\n train_test_split\n\n\"\"\"\n\nimport numbers\nfrom collections import defaultdict\nfrom itertools import chain\nfrom math import ceil, floor\n\nimport numpy as np\n\nfrom ..utils import get_rng\n\n\ndef get_cv(cv):\n \"\"\"Return a 'validated' CV iterator.\"\"\"\n\n if cv is None:\n return KFold(n_splits=5)\n if isinstance(cv, numbers.Integral):\n return KFold(n_splits=cv)\n if hasattr(cv, \"split\") and not isinstance(cv, str):\n return cv # str have split\n\n raise ValueError(\n \"Wrong CV object. Expecting None, an int or CV iterator, \"\n \"got a {}\".format(type(cv))\n )\n\n\nclass KFold:\n \"\"\"A basic cross-validation iterator.\n\n Each fold is used once as a testset while the k - 1 remaining folds are\n used for training.\n\n See an example in the :ref:`User Guide `.\n\n Args:\n n_splits(int): The number of folds.\n random_state(int, RandomState instance from numpy, or ``None``):\n Determines the RNG that will be used for determining the folds. If\n int, ``random_state`` will be used as a seed for a new RNG. This is\n useful to get the same splits over multiple calls to ``split()``.\n If RandomState instance, this same instance is used as RNG. If\n ``None``, the current RNG from numpy is used. ``random_state`` is\n only used if ``shuffle`` is ``True``. Default is ``None``.\n shuffle(bool): Whether to shuffle the ratings in the ``data`` parameter\n of the ``split()`` method. Shuffling is not done in-place. Default\n is ``True``.\n \"\"\"\n\n def __init__(self, n_splits=5, random_state=None, shuffle=True):\n\n self.n_splits = n_splits\n self.shuffle = shuffle\n self.random_state = random_state\n\n def split(self, data):\n \"\"\"Generator function to iterate over trainsets and testsets.\n\n Args:\n data(:obj:`Dataset`): The data containing\n ratings that will be divided into trainsets and testsets.\n\n Yields:\n tuple of (trainset, testset)", "instruction": "", "output": "" }, { "input": "\n \"\"\"\n\n if self.n_splits > len(data.raw_ratings) or self.n_splits < 2:\n raise ValueError(\n \"Incorrect value for n_splits={}. \"\n \"Must be >=2 and less than the number \"\n \"of ratings\".format(len(data.raw_ratings))\n )\n\n # We use indices to avoid shuffling the original data.raw_ratings list.\n indices = np.arange(len(data.raw_ratings))\n\n if self.shuffle:\n get_rng(self.random_state).shuffle(indices)\n\n start, stop = 0, 0\n for fold_i in range(self.n_splits):\n start = stop\n stop += len(indices) // self.n_splits\n if fold_i < len(indices) % self.n_splits:\n stop += 1\n\n raw_trainset = [\n data.raw_ratings[i] for i in chain(indices[:start], indices[stop:])\n ]\n raw_testset = [data.raw_ratings[i] for i in indices[start:stop]]\n\n trainset = data.construct_trainset(raw_trainset)\n testset = data.construct_testset(raw_testset)\n\n yield trainset, testset\n\n def get_n_folds(self):\n\n return self.n_splits\n\n\nclass RepeatedKFold:\n \"\"\"\n Repeated :class:`KFold` cross validator.\n\n Repeats :class:`KFold` n times with different randomization in each\n repetition.\n\n See an example in the :ref:`User Guide `.\n\n Args:\n n_splits(int): The number of folds.\n n_repeats(int): The number of repetitions.\n random_state(int, RandomState instance from numpy, or ``None``):\n Determines the RNG that will be used for determining the folds. If\n int, ``random_state`` will be used as a seed for a new RNG. This is\n useful to get the same splits over multiple calls to ``split()``.\n If RandomState instance, this same instance is used as RNG. If\n ``None``, the current RNG from numpy is used. ``random_state`` is\n only used if ``shuffle`` is ``True``. Default is ``None``.\n shuffle(bool): Whether to shuffle the ratings in the ``data`` parameter\n of the ``split()`` method. Shuffling is not done in-place. Default\n is ``True``.\n \"\"\"\n\n def __init__(self, n_splits=5, n_repeats=10, random_state=None):\n\n self.n_repeats = n_repeats\n self.random_state = random_state\n self.n_splits = n_splits\n\n def split(self, data):\n \"\"\"Generator function to iterate over trainsets and testsets.\n\n Args:\n data(:obj:`Dataset`): The data containing\n ratings that will be divided into trainsets and testsets.\n\n Yields:\n tuple of (trainset, testset)\n \"\"\"\n\n rng = get_rng(self.random_state)\n\n for _ in range(self.n_repeats):\n cv = KFold(n_splits=self.n_splits, random_state=rng, shuffle=True)\n yield from cv.split(data)\n\n def get_n_folds(self):\n\n return self.n_repeats * self.n_splits\n\n\nclass ShuffleSplit:\n \"\"\"A basic cross-validation iterator with random trainsets and testsets.\n\n Contrary to other cross-validation strategies, random splits do not\n guarantee that all folds will be different, although this is still very\n likely for sizeable datasets.\n\n See an example in the :ref:`User Guide `.\n\n Args:\n n_splits(int): The number of folds.\n test_size(float or int ``None``): If float, it represents the\n proportion of ratings to include in the testset. If int,\n represents the absolute number of ratings in the testset. If\n ``None``, the value is set to the complement of the trainset size.\n Default is ``.2``.\n train_size(float or int or ``None``): If float, it represents the\n proportion of ratings to include in the trainset. If int,\n represents the absolute number of ratings in the trainset. If\n ``None``, the value is set to the complement of the testset size.\n Default is ``None``.\n random_state(int, RandomState instance from numpy, or ``None``):\n Determines the RNG that will be used for determining the folds. If\n int, ``random_state`` will be used as a seed for a new RNG. This is\n useful to get the same splits over multiple calls to ``split()``.\n If RandomState instance, this same instance is used as RNG. If\n ``None``, the current RNG from numpy is used. ``random_state`` is\n only used if ``shuffle`` is ``True``. Default is ``None``.\n shuffle(bool): Whether to shuffle the ratings in the ``data`` parameter\n of the ``split()`` method. Shuffling is not done in-place. Setting\n this to `False` defeats the purpose of this iterator, but it's\n useful for the implementation of :func:`train_test_split`. Default\n is ``True``.\n \"\"\"\n\n def __init__(\n self,\n n_splits=5,\n test_size=0.2,\n train_size=None,\n random_state=None,\n shuffle=True,\n ):\n\n if n_splits <= 0:\n raise ValueError(\n \"n_splits = {} should be strictly greater than \" \"0.\".format(n_splits)\n )\n if test_size is not None and test_size <= 0:\n raise ValueError(\n \"test_size={} should be strictly greater than \" \"0\".format(test_size)\n )\n\n if train_size is not None and train_size <= 0:\n raise ValueError(\n \"train_size={} should be strictly greater than \" \"0\".format(train_size)\n )\n\n self.n_splits = n_splits\n self.test_size = test_size\n self.train_size = train_size\n self.random_state = random_state\n self.shuffle = shuffle\n\n def validate_train_test_sizes(self, test_size, train_size, n_ratings):\n\n if test_size is not None and test_size >= n_ratings:\n raise ValueError(\n \"test_size={} should be less than the number of \"\n \"ratings {}\".format(test_size, n_ratings)\n )\n\n if train_size is not None and train_size >= n_ratings:\n raise ValueError(\n \"train_size={} should be less than the number of\"\n \" ratings {}\".format(train_size, n_ratings)\n )\n\n if np.asarray(test_size).dtype.kind == \"f\":\n test_size = ceil(test_size * n_ratings)\n\n if train_size is None:\n train_size = n_ratings - test_size\n elif np.asarray(train_size).dtype.kind == \"f\":\n train_size = floor(train_size * n_ratings)\n\n if test_size is None:\n test_size = n_ratings - train_size\n\n if train_size + test_size > n_ratings:\n raise ValueError(\n \"The sum of train_size and test_size ({}) \"\n \"should be smaller than the number of \"\n \"ratings {}.\".format(train_size + test_size, n_ratings)\n )\n\n return int(train_size), int(test_size)\n\n def split(self, data):\n \"\"\"Generator function to iterate over trainsets and testsets.\n\n Args:\n data(:obj:`Dataset`): The data containing\n ratings that will be divided into trainsets and testsets.\n\n Yields:\n tuple of (trainset, testset)\n \"\"\"\n\n test_size, train_size = self.validate_train_test_sizes(\n self.test_size, self.train_size, len(data.raw_ratings)\n )\n rng = get_rng(self.random_state)\n\n for _ in range(self.n_splits):\n\n if self.shuffle:\n permutation = rng.permutation(len(data.raw_ratings))\n else:\n permutation = np.arange(len(data.raw_ratings))\n\n raw_trainset = [data.raw_ratings[i] for i in permutation[:test_size]]\n raw_testset = [\n data.raw_ratings[i]\n for i in permutation[test_size : (test_size + train_size)]\n ]\n\n trainset = data.construct_trainset(raw_trainset)\n testset = data.construct_testset(raw_testset)\n\n yield trainset, testset\n\n def get_n_folds(self):\n\n return self.n_splits\n\n\ndef train_test_split(\n data, test_size=0.2, train_size=None, random_state=None, shuffle=True\n):\n \"\"\"Split a dataset into trainset and testset.\n\n See an example in the :ref:`User Guide `.\n\n Note: this function cannot be used as a cross-validation iterator.\n\n Args:\n data(:obj:`Dataset `): The dataset to split\n into trainset and testset.\n test_size(float or int ``None``): If float, it represents the\n proportion of ratings to include in the testset. If int,\n represents the absolute number of ratings in the testset. If\n ``None``, the value is set to the complement of the trainset size.\n Default is ``.2``.\n train_size(float or int or ``None``): If float, it represents the\n proportion of ratings to include in the trainset. If int,\n represents the absolute number of ratings in the trainset. If\n ``None``, the value is set to the complement of the testset size.\n Default is ``None``.\n random_state(int, RandomState instance from numpy, or ``None``):\n Determines the RNG that will be used for determining the folds. If\n int, ``random_state`` will be used as a seed for a new RNG. This is\n useful to get the same splits over multiple calls to ``split()``.\n If RandomState instance, this same instance is used as RNG. If\n ``None``, the current RNG from numpy is used. ``random_state`` is\n only used if ``shuffle`` is ``True``. Default is ``None``.\n shuffle(bool): Whether to shuffle the ratings in the ``data``\n parameter. Shuffling is not done in-place. Default is ``True``.\n \"\"\"\n ss = ShuffleSplit(\n n_splits=1,\n test_size=test_size,\n train_size=train_size,\n random_state=random_state,\n shuffle=shuffle,\n )\n return next(ss.split(data))\n\n\nclass LeaveOneOut:\n \"\"\"Cross-validation iterator where each user has exactly one rating in the\n testset.\n\n Contrary to other cross-validation strategies, ``LeaveOneOut`` does not\n guarantee that all folds will be different, although this is still very\n likely for sizeable datasets.\n\n See an example in the :ref:`User Guide `.\n\n Args:\n n_splits(int): The number of folds.\n random_state(int, RandomState instance from numpy, or ``None``):\n Determines the RNG that will be used for determining the folds. If\n int, ``random_state`` will be used as a seed for a new RNG. This is\n useful to get the same splits over multiple calls to ``split()``.\n If RandomState instance, this same instance is used as RNG. If\n ``None``, the current RNG from numpy is used. ``random_state`` is\n only used if ``shuffle`` is ``True``. Default is ``None``.\n min_n_ratings(int): Minimum number of ratings for each user in the\n trainset. E.g. if ``min_n_ratings`` is ``2``, we are sure each user\n has at least ``2`` ratings in the trainset (and ``1`` in the\n testset). Other users are discarded. Default is ``0``, so some\n users (having only one rating) may be in the testset and not in the\n trainset.\n \"\"\"\n\n def __init__(self, n_splits=5, random_state=None, min_n_ratings=0):\n\n self.n_splits = n_splits\n self.random_state = random_state\n self.min_n_ratings = min_n_ratings\n\n def split(self, data):\n \"\"\"Generator function to iterate over trainsets and testsets.\n\n Args:\n data(:obj:`Dataset`): The data containing\n ratings that will be divided into trainsets and testsets.\n\n Yields:\n tuple of (trainset, testset)\n \"\"\"\n\n # map ratings to the users ids\n user_ratings = defaultdict(list)\n for uid, iid, r_ui, _ in data.raw_ratings:\n user_ratings[uid].append((uid, iid, r_ui, None))\n\n rng = get_rng(self.random_state)\n\n for _ in range(self.n_splits):\n # for each user, randomly choose a rating and put it in the\n # testset.\n raw_trainset, raw_testset = [], []\n for uid, ratings in user_ratings.items():\n if len(ratings) > self.min_n_ratings:\n i = rng.randint(0, len(ratings))\n raw_testset.append(ratings[i])\n raw_trainset += [\n rating for (j, rating) in enumerate(ratings) if j != i\n ]\n\n if not raw_trainset:\n raise ValueError(\n \"Could not build any trainset. Maybe \" \"min_n_ratings is too high?\"\n )\n trainset = data.construct_trainset(raw_trainset)\n testset = data.construct_testset(raw_testset)\n\n yield trainset, testset\n\n def get_n_folds(self):\n\n return self.n_splits\n\n\nclass PredefinedKFold:\n \"\"\"A cross-validation iterator to when a dataset has been loaded with the\n :meth:`load_from_folds `\n method.\n\n See an example in the :ref:`User Guide `.\n \"\"\"\n\n def split(self, data):\n \"\"\"Generator function to iterate over trainsets and testsets.\n\n Args:\n data(:obj:`Dataset`): The data containing\n ratings that will be divided into trainsets and testsets.\n\n Yields:\n tuple of (trainset, testset)\n \"\"\"\n\n self.n_splits = len(data.folds_files)\n for train_file, test_file in data.folds_files:\n\n raw_trainset = data.read_ratings(train_file)\n raw_testset = data.read_ratings(test_file)\n trainset = data.construct_trainset(raw_trainset)\n testset = data.construct_testset(raw_testset)\n\n yield train", "instruction": "", "output": "" }, { "input": "set, testset\n\n def get_n_folds(self):\n\n return self.n_splits\n \"\"\"\nthe :mod:`knns` module includes some k-NN inspired algorithms.\n\"\"\"\n\nimport heapq\n\nimport numpy as np\n\nfrom .algo_base import AlgoBase\n\nfrom .predictions import PredictionImpossible\n\n\n# Important note: as soon as an algorithm uses a similarity measure, it should\n# also allow the bsl_options parameter because of the pearson_baseline\n# similarity. It can be done explicitly (e.g. KNNBaseline), or implicetely\n# using kwargs (e.g. KNNBasic).\n\n\nclass SymmetricAlgo(AlgoBase):\n \"\"\"This is an abstract class aimed to ease the use of symmetric algorithms.\n\n A symmetric algorithm is an algorithm that can can be based on users or on\n items indifferently, e.g. all the algorithms in this module.\n\n When the algo is user-based x denotes a user and y an item. Else, it's\n reversed.\n \"\"\"\n\n def __init__(self, sim_options={}, verbose=True, **kwargs):\n\n AlgoBase.__init__(self, sim_options=sim_options, **kwargs)\n self.verbose = verbose\n\n def fit(self, trainset):\n\n AlgoBase.fit(self, trainset)\n\n ub = self.sim_options[\"user_based\"]\n self.n_x = self.trainset.n_users if ub else self.trainset.n_items\n self.n_y = self.trainset.n_items if ub else self.trainset.n_users\n self.xr = self.trainset.ur if ub else self.trainset.ir\n self.yr = self.trainset.ir if ub else self.trainset.ur\n\n return self\n\n def switch(self, u_stuff, i_stuff):\n \"\"\"Return x_stuff and y_stuff depending on the user_based field.\"\"\"\n\n if self.sim_options[\"user_based\"]:\n return u_stuff, i_stuff\n else:\n return i_stuff, u_stuff\n\n\nclass KNNBasic(SymmetricAlgo):\n \"\"\"A basic collaborative filtering algorithm.\n\n The prediction :math:`\\\\\\\\hat{r}_{ui}` is set as:\n\n .. math::\n \\\\\\\\hat{r}_{ui} = \\\\\\\\frac{\n \\\\\\\\sum\\\\\\\\limits_{v \\\\\\\\in N^k_i(u)} \\\\\\\\text{sim}(u, v) \\\\\\\\cdot r_{vi}}\n {\\\\\\\\sum\\\\\\\\limits_{v \\\\\\\\in N^k_i(u)} \\\\\\\\text{sim}(u, v)}\n\n or\n\n .. math::\n \\\\\\\\hat{r}_{ui} = \\\\\\\\frac{\n \\\\\\\\sum\\\\\\\\limits_{j \\\\\\\\in N^k_u(i)} \\\\\\\\text{sim}(i, j) \\\\\\\\cdot r_{uj}}\n {\\\\\\\\sum\\\\\\\\limits_{j \\\\\\\\in N^k_u(i)} \\\\\\\\text{sim}(i, j)}\n\n depending on the ``user_based`` field of the ``sim_options`` parameter.\n\n Args:\n k(int): The (max) number of neighbors to take into account for\n aggregation (see :ref:`this note `). Default is\n ``40``.\n min_k(int): The minimum number of neighbors to take into account for\n aggregation. If there are not enough neighbors, the prediction is\n set to the global mean of all ratings. Default is ``1``.\n sim_options(dict): A dictionary of options for the similarity\n measure. See :ref:`similarity_measures_configuration` for accepted\n options.\n verbose(bool): Whether to print trace messages of bias estimation,\n similarity, etc. Default is True.\n \"\"\"\n\n def __init__(self, k=40, min_k=1, sim_options={}, verbose=True, **kwargs):\n\n SymmetricAlgo.__init__(self, sim_options=sim_options, verbose=verbose, **kwargs)\n self.k = k\n self.min_k = min_k\n\n def fit(self, trainset):\n\n SymmetricAlgo.fit(self, trainset)\n self.sim = self.compute_similarities()\n\n return self\n\n def estimate(self, u, i):\n\n if not (self.trainset.knows_user(u) and self.trainset.knows_item(i)):\n raise PredictionImpossible(\"User and/or item is unknown.\")\n\n x, y = self.switch(u, i)\n\n neighbors = [(self.sim[x, x2], r) for (x2, r) in self.yr[y]]\n k_neighbors = heapq.nlargest(self.k, neighbors, key=lambda t: t[0])\n\n # compute weighted average\n sum_sim = sum_ratings = actual_k = 0\n for (sim, r) in k_neighbors:\n if sim > 0:\n sum_sim += sim\n sum_ratings += sim * r\n actual_k += 1\n\n if actual_k < self.min_k:\n raise PredictionImpossible(\"Not enough neighbors.\")\n\n est = sum_ratings / sum_sim\n\n details = {\"actual_k\": actual_k}\n return est, details\n\n\nclass KNNWithMeans(SymmetricAlgo):\n \"\"\"A basic collaborative filtering algorithm, taking into account the mean\n ratings of each user.\n\n The prediction :math:`\\\\\\\\hat{r}_{ui}` is set as:\n\n .. math::\n \\\\\\\\hat{r}_{ui} = \\\\\\\\mu_u + \\\\\\\\frac{ \\\\\\\\sum\\\\\\\\limits_{v \\\\\\\\in N^k_i(u)}\n \\\\\\\\text{sim}(u, v) \\\\\\\\cdot (r_{vi} - \\\\\\\\mu_v)} {\\\\\\\\sum\\\\\\\\limits_{v \\\\\\\\in\n N^k_i(u)} \\\\\\\\text{sim}(u, v)}\n\n or\n\n .. math::\n \\\\\\\\hat{r}_{ui} = \\\\\\\\mu_i + \\\\\\\\frac{ \\\\\\\\sum\\\\\\\\limits_{j \\\\\\\\in N^k_u(i)}\n \\\\\\\\text{sim}(i, j) \\\\\\\\cdot (r_{uj} - \\\\\\\\mu_j)} {\\\\\\\\sum\\\\\\\\limits_{j \\\\\\\\in\n N^k_u(i)} \\\\\\\\text{sim}(i, j)}\n\n depending on the ``user_based`` field of the ``sim_options`` parameter.\n\n\n Args:\n k(int): The (max) number of neighbors to take into account for\n aggregation (see :ref:`this note `). Default is\n ``40``.\n min_k(int): The minimum number of neighbors to take into account for\n aggregation. If there are not enough neighbors, the neighbor\n aggregation is set to zero (so the prediction ends up being\n equivalent to the mean :math:`\\\\\\\\mu_u` or :math:`\\\\\\\\mu_i`). Default is\n ``1``.\n sim_options(dict): A dictionary of options for the similarity\n measure. See :ref:`similarity_measures_configuration` for accepted\n options.\n verbose(bool): Whether to print trace messages of bias estimation,\n similarity, etc. Default is True.\n \"\"\"\n\n def __init__(self, k=40, min_k=1, sim_options={}, verbose=True, **kwargs):\n\n SymmetricAlgo.__init__(self, sim_options=sim_options, verbose=verbose, **kwargs)\n\n self.k = k\n self.min_k = min_k\n\n def fit(self, trainset):\n\n SymmetricAlgo.fit(self, trainset)\n self.sim = self.compute_similarities()\n\n self.means = np.zeros(self.n_x)\n for x, ratings in self.xr.items():\n self.means[x] = np.mean([r for (_, r) in ratings])\n\n return self\n\n def estimate(self, u, i):\n\n if not (self.trainset.knows_user(u) and self.trainset.knows_item(i)):\n raise PredictionImpossible(\"User and/or item is unknown.\")\n\n x, y = self.switch(u, i)\n\n neighbors = [(x2, self.sim[x, x2], r) for (x2, r) in self.yr[y]]\n k_neighbors = heapq.nlargest(self.k, neighbors, key=lambda t: t[1])\n\n est = self.means[x]\n\n # compute weighted average\n sum_sim = sum_ratings = actual_k = 0\n for (nb, sim, r) in k_neighbors:\n if sim > 0:\n sum_sim += sim\n sum_ratings += sim * (r - self.means[nb])\n actual_k += 1\n\n if actual_k < self.min_k:\n sum_ratings = 0\n\n try:\n est += sum_ratings / sum_sim\n except ZeroDivisionError:\n pass # return mean\n\n details = {\"actual_k\": actual_k}\n return est, details\n\n\nclass KNNBaseline(SymmetricAlgo):\n \"\"\"A basic collaborative filtering algorithm taking into account a\n *baseline* rating.\n\n\n The prediction :math:`\\\\\\\\hat{r}_{ui}` is set as:\n\n .. math::\n \\\\\\\\hat{r}_{ui} = b_{ui} + \\\\\\\\frac{ \\\\\\\\sum\\\\\\\\limits_{v \\\\\\\\in N^k_i(u)}\n \\\\\\\\text{sim}(u, v) \\\\\\\\cdot (r_{vi} - b_{vi})} {\\\\\\\\sum\\\\\\\\limits_{v \\\\\\\\in\n N^k_i(u)} \\\\\\\\text{sim}(u, v)}\n\n or\n\n\n .. math::\n \\\\\\\\hat{r}_{ui} = b_{ui} + \\\\\\\\frac{ \\\\\\\\sum\\\\\\\\limits_{j \\\\\\\\in N^k_u(i)}\n \\\\\\\\text{sim}(i, j) \\\\\\\\cdot (r_{uj} - b_{uj})} {\\\\\\\\sum\\\\\\\\limits_{j \\\\\\\\in\n N^k_u(i)} \\\\\\\\text{sim}(i, j)}\n\n depending on the ``user_based`` field of the ``sim_options`` parameter. For\n the best predictions, use the :func:`pearson_baseline\n ` similarity measure.\n\n This algorithm corresponds to formula (3), section 2.2 of\n :cite:`Koren:2010`.\n\n Args:\n k(int): The (max) number of neighbors to take into account for\n aggregation (see :ref:`this note `). Default is\n ``40``.\n min_k(int): The minimum number of neighbors to take into account for\n aggregation. If there are not enough neighbors, the neighbor\n aggregation is set to zero (so the prediction ends up being\n equivalent to the baseline). Default is ``1``.\n sim_options(dict): A dictionary of options for the similarity\n measure. See :ref:`similarity_measures_configuration` for accepted\n options. It is recommended to use the :func:`pearson_baseline\n ` similarity measure.\n\n bsl_options(dict): A dictionary of options for the baseline estimates\n computation. See :ref:`baseline_estimates_configuration` for\n accepted options.\n verbose(bool): Whether to print trace messages of bias estimation,\n similarity, etc. Default is True.\n\n \"\"\"\n\n def __init__(\n self, k=40, min_k=1, sim_options={}, bsl_options={}, verbose=True, **kwargs\n ):\n\n SymmetricAlgo.__init__(\n self,\n sim_options=sim_options,\n bsl_options=bsl_options,\n verbose=verbose,\n **kwargs\n )\n\n self.k = k\n self.min_k = min_k\n\n def fit(self, trainset):\n\n SymmetricAlgo.fit(self, trainset)\n self.bu, self.bi = self.compute_baselines()\n self.bx, self.by = self.switch(self.bu, self.bi)\n self.sim = self.compute_similarities()\n\n return self\n\n def estimate(self, u, i):\n\n est = self.trainset.global_mean\n if self.trainset.knows_user(u):\n est += self.bu[u]\n if self.trainset.knows_item(i):\n est += self.bi[i]\n\n x, y = self.switch(u, i)\n\n if not (self.trainset.knows_user(u) and self.trainset.knows_item(i)):\n return est\n\n neighbors = [(x2, self.sim[x, x2], r) for (x2, r) in self.yr[y]]\n k_neighbors = heapq.nlargest(self.k, neighbors, key=lambda t: t[1])\n\n # compute weighted average\n sum_sim = sum_ratings = actual_k = 0\n for (nb, sim, r) in k_neighbors:\n if sim > 0:\n sum_sim += sim\n nb_bsl = self.trainset.global_mean + self.bx[nb] + self.by[y]\n sum_ratings += sim * (r - nb_bsl)\n actual_k += 1\n\n if actual_k < self.min_k:\n sum_ratings = 0\n\n try:\n est += sum_ratings / sum_sim\n except ZeroDivisionError:\n pass # just baseline again\n\n details = {\"actual_k\": actual_k}\n return est, details\n\n\nclass KNNWithZScore(SymmetricAlgo):\n \"\"\"A basic collaborative filtering algorithm, taking into account\n the z-score normalization of each user.\n\n The prediction :math:`\\\\\\\\hat{r}_{ui}` is set as:\n\n .. math::\n \\\\\\\\hat{r}_{ui} = \\\\\\\\mu_u + \\\\\\\\sigma_u \\\\\\\\frac{ \\\\\\\\sum\\\\\\\\limits_{v \\\\\\\\in N^k_i(u)}\n \\\\\\\\text{sim}(u, v) \\\\\\\\cdot (r_{vi} - \\\\\\\\mu_v) / \\\\\\\\sigma_v} {\\\\\\\\sum\\\\\\\\limits_{v\n \\\\\\\\in N^k_i(u)} \\\\\\\\text{sim}(u, v)}\n\n or\n\n .. math::\n \\\\\\\\hat{r}_{ui} = \\\\\\\\mu_i + \\\\\\\\sigma_i \\\\\\\\frac{ \\\\\\\\sum\\\\\\\\limits_{j \\\\\\\\in N^k_u(i)}\n \\\\\\\\text{sim}(i, j) \\\\\\\\cdot (r_{uj} - \\\\\\\\mu_j) / \\\\\\\\sigma_j} {\\\\\\\\sum\\\\\\\\limits_{j\n \\\\\\\\in N^k_u(i)} \\\\\\\\text{sim}(i, j)}\n\n depending on the ``user_based`` field of the ``sim_options`` parameter.\n\n If :math:`\\\\\\\\sigma` is 0, than the overall sigma is used in that case.\n\n Args:\n k(int): The (max) number of neighbors to take into account for\n aggregation (see :ref:`this note `). Default is\n ``40``.\n min_k(int): The minimum number of neighbors to take into account for\n aggregation. If there are not enough neighbors, the neighbor\n aggregation is set to zero (so the prediction ends up being\n equivalent to the mean :math:`\\\\\\\\mu_u` or :math:`\\\\\\\\mu_i`). Default is\n ``1``.\n sim_options(dict): A dictionary of options for the similarity\n measure. See :ref:`similarity_measures_configuration` for accepted\n options.\n verbose(bool): Whether to print trace messages of bias estimation,\n similarity, etc. Default is True.\n \"\"\"\n\n def __init__(self, k=40, min_k=1, sim_options={}, verbose=True, **kwargs):\n\n SymmetricAlgo.__init__(self, sim_options=sim_options, verbose=verbose, **kwargs)\n\n self.k = k\n self.min_k = min_k\n\n def fit(self, trainset):\n\n SymmetricAlgo.fit(self, trainset)\n\n self.means = np.zeros(self.n_x)\n self.sig", "instruction": "", "output": "" }, { "input": "mas = np.zeros(self.n_x)\n # when certain sigma is 0, use overall sigma\n self.overall_sigma = np.std([r for (_, _, r) in self.trainset.all_ratings()])\n\n for x, ratings in self.xr.items():\n self.means[x] = np.mean([r for (_, r) in ratings])\n sigma = np.std([r for (_, r) in ratings])\n self.sigmas[x] = self.overall_sigma if sigma == 0.0 else sigma\n\n self.sim = self.compute_similarities()\n\n return self\n\n def estimate(self, u, i):\n\n if not (self.trainset.knows_user(u) and self.trainset.knows_item(i)):\n raise PredictionImpossible(\"User and/or item is unknown.\")\n\n x, y = self.switch(u, i)\n\n neighbors = [(x2, self.sim[x, x2], r) for (x2, r) in self.yr[y]]\n k_neighbors = heapq.nlargest(self.k, neighbors, key=lambda t: t[1])\n\n est = self.means[x]\n\n # compute weighted average\n sum_sim = sum_ratings = actual_k = 0\n for (nb, sim, r) in k_neighbors:\n if sim > 0:\n sum_sim += sim\n sum_ratings += sim * (r - self.means[nb]) / self.sigmas[nb]\n actual_k += 1\n\n if actual_k < self.min_k:\n sum_ratings = 0\n\n try:\n est += sum_ratings / sum_sim * self.sigmas[x]\n except ZeroDivisionError:\n pass # return mean\n\n details = {\"actual_k\": actual_k}\n return est, details\n \"\"\" Algorithm predicting a random rating.\n\"\"\"\n\n\nimport numpy as np\n\nfrom .algo_base import AlgoBase\n\n\nclass NormalPredictor(AlgoBase):\n \"\"\"Algorithm predicting a random rating based on the distribution of the\n training set, which is assumed to be normal.\n\n The prediction :math:`\\\\\\\\hat{r}_{ui}` is generated from a normal distribution\n :math:`\\\\\\\\mathcal{N}(\\\\\\\\hat{\\\\\\\\mu}, \\\\\\\\hat{\\\\\\\\sigma}^2)` where :math:`\\\\\\\\hat{\\\\\\\\mu}` and\n :math:`\\\\\\\\hat{\\\\\\\\sigma}` are estimated from the training data using Maximum\n Likelihood Estimation:\n\n .. math::\n \\\\\\\\hat{\\\\\\\\mu} &= \\\\\\\\frac{1}{|R_{train}|} \\\\\\\\sum_{r_{ui} \\\\\\\\in R_{train}}\n r_{ui}\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n \\\\\\\\hat{\\\\\\\\sigma} &= \\\\\\\\sqrt{\\\\\\\\sum_{r_{ui} \\\\\\\\in R_{train}}\n \\\\\\\\frac{(r_{ui} - \\\\\\\\hat{\\\\\\\\mu})^2}{|R_{train}|}}\n \"\"\"\n\n def __init__(self):\n\n AlgoBase.__init__(self)\n\n def fit(self, trainset):\n\n AlgoBase.fit(self, trainset)\n\n num = sum(\n (r - self.trainset.global_mean) ** 2\n for (_, _, r) in self.trainset.all_ratings()\n )\n denum = self.trainset.n_ratings\n self.sigma = np.sqrt(num / denum)\n\n return self\n\n def estimate(self, *_):\n\n return np.random.normal(self.trainset.global_mean, self.sigma)\n \"\"\"\nThe :mod:`surprise.prediction_algorithms.algo_base` module defines the base\nclass :class:`AlgoBase` from which every single prediction algorithm has to\ninherit.\n\"\"\"\nimport heapq\n\nfrom .. import similarities as sims\nfrom .optimize_baselines import baseline_als, baseline_sgd\nfrom .predictions import Prediction, PredictionImpossible\n\n\nclass AlgoBase:\n \"\"\"Abstract class where is defined the basic behavior of a prediction\n algorithm.\n\n Keyword Args:\n baseline_options(dict, optional): If the algorithm needs to compute a\n baseline estimate, the ``baseline_options`` parameter is used to\n configure how they are computed. See\n :ref:`baseline_estimates_configuration` for usage.\n \"\"\"\n\n def __init__(self, **kwargs):\n\n self.bsl_options = kwargs.get(\"bsl_options\", {})\n self.sim_options = kwargs.get(\"sim_options\", {})\n if \"user_based\" not in self.sim_options:\n self.sim_options[\"user_based\"] = True\n\n def fit(self, trainset):\n \"\"\"Train an algorithm on a given training set.\n\n This method is called by every derived class as the first basic step\n for training an algorithm. It basically just initializes some internal\n structures and set the self.trainset attribute.\n\n Args:\n trainset(:obj:`Trainset `) : A training\n set, as returned by the :meth:`folds\n ` method.\n\n Returns:\n self\n \"\"\"\n\n self.trainset = trainset\n\n # (re) Initialise baselines\n self.bu = self.bi = None\n\n return self\n\n def predict(self, uid, iid, r_ui=None, clip=True, verbose=False):\n \"\"\"Compute the rating prediction for given user and item.\n\n The ``predict`` method converts raw ids to inner ids and then calls the\n ``estimate`` method which is defined in every derived class. If the\n prediction is impossible (e.g. because the user and/or the item is\n unknown), the prediction is set according to\n :meth:`default_prediction()\n `.\n\n Args:\n uid: (Raw) id of the user. See :ref:`this note`.\n iid: (Raw) id of the item. See :ref:`this note`.\n r_ui(float): The true rating :math:`r_{ui}`. Optional, default is\n ``None``.\n clip(bool): Whether to clip the estimation into the rating scale.\n For example, if :math:`\\\\\\\\hat{r}_{ui}` is :math:`5.5` while the\n rating scale is :math:`[1, 5]`, then :math:`\\\\\\\\hat{r}_{ui}` is\n set to :math:`5`. Same goes if :math:`\\\\\\\\hat{r}_{ui} < 1`.\n Default is ``True``.\n verbose(bool): Whether to print details of the prediction. Default\n is False.\n\n Returns:\n A :obj:`Prediction\\\\\n ` object\n containing:\n\n - The (raw) user id ``uid``.\n - The (raw) item id ``iid``.\n - The true rating ``r_ui`` (:math:`r_{ui}`).\n - The estimated rating (:math:`\\\\\\\\hat{r}_{ui}`).\n - Some additional details about the prediction that might be useful\n for later analysis.\n \"\"\"\n\n # Convert raw ids to inner ids\n try:\n iuid = self.trainset.to_inner_uid(uid)\n except ValueError:\n iuid = \"UKN__\" + str(uid)\n try:\n iiid = self.trainset.to_inner_iid(iid)\n except ValueError:\n iiid = \"UKN__\" + str(iid)\n\n details = {}\n try:\n est = self.estimate(iuid, iiid)\n\n # If the details dict was also returned\n if isinstance(est, tuple):\n est, details = est\n\n details[\"was_impossible\"] = False\n\n except PredictionImpossible as e:\n est = self.default_prediction()\n details[\"was_impossible\"] = True\n details[\"reason\"] = str(e)\n\n # clip estimate into [lower_bound, higher_bound]\n if clip:\n lower_bound, higher_bound = self.trainset.rating_scale\n est = min(higher_bound, est)\n est = max(lower_bound, est)\n\n pred = Prediction(uid, iid, r_ui, est, details)\n\n if verbose:\n print(pred)\n\n return pred\n\n def default_prediction(self):\n \"\"\"Used when the ``PredictionImpossible`` exception is raised during a\n call to :meth:`predict()\n `. By\n default, return the global mean of all ratings (can be overridden in\n child classes).\n\n Returns:\n (float): The mean of all ratings in the trainset.\n \"\"\"\n\n return self.trainset.global_mean\n\n def test(self, testset, verbose=False):\n \"\"\"Test the algorithm on given testset, i.e. estimate all the ratings\n in the given testset.\n\n Args:\n testset: A test set, as returned by a :ref:`cross-validation\n itertor` or by the\n :meth:`build_testset() `\n method.\n verbose(bool): Whether to print details for each predictions.\n Default is False.\n\n Returns:\n A list of :class:`Prediction\\\\\n ` objects\n that contains all the estimated ratings.\n \"\"\"\n\n # The ratings are translated back to their original scale.\n predictions = [\n self.predict(uid, iid, r_ui_trans, verbose=verbose)\n for (uid, iid, r_ui_trans) in testset\n ]\n return predictions\n\n def compute_baselines(self):\n \"\"\"Compute users and items baselines.\n\n The way baselines are computed depends on the ``bsl_options`` parameter\n passed at the creation of the algorithm (see\n :ref:`baseline_estimates_configuration`).\n\n This method is only relevant for algorithms using :func:`Pearson\n baseline similarity` or the\n :class:`BaselineOnly\n ` algorithm.\n\n Returns:\n A tuple ``(bu, bi)``, which are users and items baselines.\"\"\"\n\n # Firt of, if this method has already been called before on the same\n # trainset, then just return. Indeed, compute_baselines may be called\n # more than one time, for example when a similarity metric (e.g.\n # pearson_baseline) uses baseline estimates.\n if self.bu is not None:\n return self.bu, self.bi\n\n method = dict(als=baseline_als, sgd=baseline_sgd)\n\n method_name = self.bsl_options.get(\"method\", \"als\")\n\n try:\n if getattr(self, \"verbose\", False):\n print(\"Estimating biases using\", method_name + \"...\")\n self.bu, self.bi = method[method_name](self)\n return self.bu, self.bi\n except KeyError:\n raise ValueError(\n \"Invalid method \"\n + method_name\n + \" for baseline computation.\"\n + \" Available methods are als and sgd.\"\n )\n\n def compute_similarities(self):\n \"\"\"Build the similarity matrix.\n\n The way the similarity matrix is computed depends on the\n ``sim_options`` parameter passed at the creation of the algorithm (see\n :ref:`similarity_measures_configuration`).\n\n This method is only relevant for algorithms using a similarity measure,\n such as the :ref:`k-NN algorithms `.\n\n Returns:\n The similarity matrix.\"\"\"\n\n construction_func = {\n \"cosine\": sims.cosine,\n \"msd\": sims.msd,\n \"pearson\": sims.pearson,\n \"pearson_baseline\": sims.pearson_baseline,\n }\n\n if self.sim_options[\"user_based\"]:\n n_x, yr = self.trainset.n_users, self.trainset.ir\n else:\n n_x, yr = self.trainset.n_items, self.trainset.ur\n\n min_support = self.sim_options.get(\"min_support\", 1)\n\n args = [n_x, yr, min_support]\n\n name = self.sim_options.get(\"name\", \"msd\").lower()\n if name == \"pearson_baseline\":\n shrinkage = self.sim_options.get(\"shrinkage\", 100)\n bu, bi = self.compute_baselines()\n if self.sim_options[\"user_based\"]:\n bx, by = bu, bi\n else:\n bx, by = bi, bu\n\n args += [self.trainset.global_mean, bx, by, shrinkage]\n\n try:\n if getattr(self, \"verbose\", False):\n print(f\"Computing the {name} similarity matrix...\")\n sim = construction_func[name](*args)\n if getattr(self, \"verbose\", False):\n print(\"Done computing similarity matrix.\")\n return sim\n except KeyError:\n raise NameError(\n \"Wrong sim name \"\n + name\n + \". Allowed values \"\n + \"are \"\n + \", \".join(construction_func.keys())\n + \".\"\n )\n\n def get_neighbors(self, iid, k):\n \"\"\"Return the ``k`` nearest neighbors of ``iid``, which is the inner id\n of a user or an item, depending on the ``user_based`` field of\n ``sim_options`` (see :ref:`similarity_measures_configuration`).\n\n As the similarities are computed on the basis of a similarity measure,\n this method is only relevant for algorithms using a similarity measure,\n such as the :ref:`k-NN algorithms `.\n\n For a usage example, see the :ref:`FAQ `.\n\n Args:\n iid(int): The (inner) id of the user (or item) for which we want\n the nearest neighbors. See :ref:`this note`.\n\n k(int): The number of neighbors to retrieve.\n\n Returns:\n The list of the ``k`` (inner) ids of the closest users (or items)\n to ``iid``.\n \"\"\"\n\n if self.sim_options[\"user_based\"]:\n all_instances = self.trainset.all_users\n else:\n all_instances = self.trainset.all_items\n others = [(x, self.sim[iid, x]) for x in all_instances() if x != iid]\n others = heapq.nlargest(k, others, key=lambda tple: tple[1])\n k_nearest_neighbors = [j for (j, _) in others]\n\n return k_nearest_neighbors\n \"\"\"\nThe :mod:`surprise.prediction_algorithms.predictions` module defines the\n:class:`Prediction` named tuple and the :class:`PredictionImpossible`\nexception.\n\"\"\"\n\n\nfrom collections import namedtuple\n\n\nclass PredictionImpossible(Exception):\n r\"\"\"Exception raised when a prediction is impossible.\n\n When raised, the estimation :math:`\\\\hat{r}_{ui}` is set to the global mean\n of all ratings :math:`\\\\mu`.\n \"\"\"\n\n pass\n\n\nclass Prediction(namedtuple(\"Prediction\", [\"uid\", \"iid\", \"r_ui\", \"est\", \"details\"])):\n \"\"\"A named tuple for storing the results of a prediction.\n\n It's wrapped in a class, but only for documentation and printing purposes.\n\n Args:\n uid: The (raw) user id. See :ref:`this", "instruction": "", "output": "" }, { "input": "note`.\n iid: The (raw) item id. See :ref:`this note`.\n r_ui(float): The true rating :math:`r_{ui}`.\n est(float): The estimated rating :math:`\\\\\\\\hat{r}_{ui}`.\n details (dict): Stores additional details about the prediction that\n might be useful for later analysis.\n \"\"\"\n\n __slots__ = () # for memory saving purpose.\n\n def __str__(self):\n s = f\"user: {self.uid:<10} \"\n s += f\"item: {self.iid:<10} \"\n if self.r_ui is not None:\n s += f\"r_ui = {self.r_ui:1.2f} \"\n else:\n s += \"r_ui = None \"\n s += f\"est = {self.est:1.2f} \"\n s += str(self.details)\n\n return s\n \"\"\"\nThe :mod:`prediction_algorithms` package includes the prediction algorithms\navailable for recommendation.\n\nThe available prediction algorithms are:\n\n.. autosummary::\n :nosignatures:\n\n random_pred.NormalPredictor\n baseline_only.BaselineOnly\n knns.KNNBasic\n knns.KNNWithMeans\n knns.KNNWithZScore\n knns.KNNBaseline\n matrix_factorization.SVD\n matrix_factorization.SVDpp\n matrix_factorization.NMF\n slope_one.SlopeOne\n co_clustering.CoClustering\n\"\"\"\n\nfrom .algo_base import AlgoBase\nfrom .baseline_only import BaselineOnly\nfrom .co_clustering import CoClustering\nfrom .knns import KNNBaseline, KNNBasic, KNNWithMeans, KNNWithZScore\nfrom .matrix_factorization import NMF, SVD, SVDpp\n\nfrom .predictions import Prediction, PredictionImpossible\nfrom .random_pred import NormalPredictor\nfrom .slope_one import SlopeOne\n\n__all__ = [\n \"AlgoBase\",\n \"NormalPredictor\",\n \"BaselineOnly\",\n \"KNNBasic\",\n \"KNNBaseline\",\n \"KNNWithMeans\",\n \"SVD\",\n \"SVDpp\",\n \"NMF\",\n \"SlopeOne\",\n \"CoClustering\",\n \"PredictionImpossible\",\n \"Prediction\",\n \"KNNWithZScore\",\n]\n \"\"\"\nThis class implements the baseline estimation.\n\"\"\"\n\nfrom .algo_base import AlgoBase\n\n\nclass BaselineOnly(AlgoBase):\n r\"\"\"Algorithm predicting the baseline estimate for given user and item.\n\n :math:`\\\\hat{r}_{ui} = b_{ui} = \\\\mu + b_u + b_i`\n\n If user :math:`u` is unknown, then the bias :math:`b_u` is assumed to be\n zero. The same applies for item :math:`i` with :math:`b_i`.\n\n See section 2.1 of :cite:`Koren:2010` for details.\n\n Args:\n bsl_options(dict): A dictionary of options for the baseline estimates\n computation. See :ref:`baseline_estimates_configuration` for\n accepted options.\n verbose(bool): Whether to print trace messages of bias estimation,\n similarity, etc. Default is True.\n \"\"\"\n\n def __init__(self, bsl_options={}, verbose=True):\n\n AlgoBase.__init__(self, bsl_options=bsl_options)\n self.verbose = verbose\n\n def fit(self, trainset):\n\n AlgoBase.fit(self, trainset)\n self.bu, self.bi = self.compute_baselines()\n\n return self\n\n def estimate(self, u, i):\n\n est = self.trainset.global_mean\n if self.trainset.knows_user(u):\n est += self.bu[u]\n if self.trainset.knows_item(i):\n est += self.bi[i]\n\n return est\n import os\nimport traceback\nimport sys\nprint(\"before function process\")\ndef process(version):\n print(\"inside fun process\")\n currentDirectory = os.path.dirname(os.path.abspath(__file__))\n print(currentDirectory)\n try:\n from os.path import expanduser\n import platform\n import subprocess\n import sys\n import demoji\n try:\n print('Downloading NLTK additional packages...')\n import nltk \n nltk.download('punkt')\n nltk.download('wordnet')\n nltk.download('stopwords')\n nltk.download('averaged_perceptron_tagger')\n except Exception as e:\n print('NLTK Error: '+str(e))\n pass\n from appbe.dataPath import DATA_DIR\n \n import shutil\n import importlib\n\n license_path = DATA_DIR\n if os.path.isdir(license_path) == False:\n os.makedirs(license_path)\n\n import warnings\n warnings.filterwarnings(\"ignore\")\n \n LicenseFolder = os.path.join(license_path,'License')\n if os.path.isdir(LicenseFolder) == False:\n os.makedirs(LicenseFolder)\n\n\n sqlite_path = os.path.join(license_path,'sqlite')\n if os.path.isdir(sqlite_path) == False:\n os.makedirs(sqlite_path)\n pretrainedModel_path = os.path.join(license_path,'PreTrainedModels')\n if os.path.isdir(pretrainedModel_path) == False:\n os.makedirs(pretrainedModel_path)\n config_path = os.path.join(license_path,'config')\n if os.path.isdir(config_path) == False:\n os.makedirs(config_path)\n target_path = os.path.join(license_path,'target')\n if os.path.isdir(target_path) == False:\n os.makedirs(target_path)\n data_path = os.path.join(license_path,'storage')\n if os.path.isdir(data_path) == False:\n os.makedirs(data_path)\n log_path = os.path.join(license_path,'logs')\n if os.path.isdir(log_path) == False:\n os.makedirs(log_path)\n\n\n configFolder = \tos.path.join(currentDirectory,'..','config')\n for file in os.listdir(configFolder):\n if file.endswith(\".var\"):\n os.remove(os.path.join(configFolder,file))\n versionfile = os.path.join(configFolder,str(version)+'.var') \n with open(versionfile, 'w') as fp:\n pass\n \n manage_path = os.path.join(currentDirectory,'..','aion.py')\n print('Setting up Django Environment for AION User Interface')\n proc = subprocess.Popen([sys.executable, manage_path, \"-m\",\"migrateappfe\"],stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n (stdout, stderr) = proc.communicate()\n if proc.returncode != 0:\n err_string = stderr.decode('utf8')\n import re\n result = re.search(\"No module named '(.*)'\", err_string)\n if 'ModuleNotFoundError' in err_string:\n print('\\\\n\"{}\" module is missing. The dependencies of AION were not installed properly. Uninstall and reinstall AION'.format(result.group(1)))\n else:\n print('\\\\nThe dependencies of AION were not installed properly. Uninstall and reinstall AION')\n raise Exception(err_string)\n else:\n print('AION User Interface successfully set')\n print('--------------AION Installed Successfully--------------')\n except Exception as e:\n print(e)\n f = open(os.path.join(currentDirectory, 'workspace_error_logs.txt'), \"w\")\n f.write(str(traceback.format_exc()))\n f.close()\n pass\n\nif __name__ == \"__main__\":\n process(sys.argv[1]) import os\nimport traceback\n\ndef process(version):\n currentDirectory = os.path.dirname(os.path.abspath(__file__))\n try:\n import win32com.client\n from os.path import expanduser\n import platform\n import subprocess\n import sys\n import demoji\n try:\n print('Downloading NLTK additional packages...')\n import nltk \n nltk.download('punkt')\n nltk.download('wordnet')\n nltk.download('stopwords')\n nltk.download('averaged_perceptron_tagger')\n except Exception as e:\n print('NLTK Error: '+str(e))\n pass\n from appbe.dataPath import DATA_DIR\n from win32com.shell import shell, shellcon\n import shutil\n import importlib\n\n license_path = DATA_DIR\n if os.path.isdir(license_path) == False:\n os.makedirs(license_path)\n\n import warnings\n warnings.filterwarnings(\"ignore\")\n \n LicenseFolder = os.path.join(license_path,'License')\n if os.path.isdir(LicenseFolder) == False:\n os.makedirs(LicenseFolder)\n\n\n sqlite_path = os.path.join(license_path,'sqlite')\n if os.path.isdir(sqlite_path) == False:\n os.makedirs(sqlite_path)\n pretrainedModel_path = os.path.join(license_path,'PreTrainedModels')\n if os.path.isdir(pretrainedModel_path) == False:\n os.makedirs(pretrainedModel_path)\n config_path = os.path.join(license_path,'config')\n if os.path.isdir(config_path) == False:\n os.makedirs(config_path)\n target_path = os.path.join(license_path,'target')\n if os.path.isdir(target_path) == False:\n os.makedirs(target_path)\n data_path = os.path.join(license_path,'storage')\n if os.path.isdir(data_path) == False:\n os.makedirs(data_path)\n log_path = os.path.join(license_path,'logs')\n if os.path.isdir(log_path) == False:\n os.makedirs(log_path)\n\n\n configFolder = \tos.path.join(currentDirectory,'..','config')\n for file in os.listdir(configFolder):\n if file.endswith(\".var\"):\n os.remove(os.path.join(configFolder,file))\n versionfile = os.path.join(configFolder,str(version)+'.var') \n with open(versionfile, 'w') as fp:\n pass\n \n manage_path = os.path.join(currentDirectory,'..','aion.py')\n print('Setting up Django Environment for AION User Interface')\n proc = subprocess.Popen([sys.executable, manage_path, \"-m\",\"migrateappfe\"],stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n (stdout, stderr) = proc.communicate()\n if proc.returncode != 0:\n err_string = stderr.decode('utf8')\n import re\n result = re.search(\"No module named '(.*)'\", err_string)\n if 'ModuleNotFoundError' in err_string:\n print('\\\\n\"{}\" module is missing. The dependencies of AION were not installed properly. Uninstall and reinstall AION'.format(result.group(1)))\n else:\n print('\\\\nThe dependencies of AION were not installed properly. Uninstall and reinstall AION')\n raise Exception(err_string)\n else:\n print('AION User Interface successfully set')\n desktop = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0)\n #desktop = os.path.expanduser('~/Desktop')\n path = os.path.join(desktop, 'Explorer {0}.lnk'.format(version))\n target = os.path.normpath(os.path.join(currentDirectory,'..', 'sbin', 'AION_Explorer.bat'))\n icon = os.path.join(currentDirectory,'icons','aion.ico')\n shell = win32com.client.Dispatch(\"WScript.Shell\")\n shortcut = shell.CreateShortCut(path)\n shortcut.Targetpath = '\"'+target+'\"'\n shortcut.WorkingDirectory = currentDirectory\n #shortcut.WorkingDirectory = os.path.dirname(__file__)\n shortcut.IconLocation = icon\n shortcut.WindowStyle = 1 # 7 - Minimized, 3 - Maximized, 1 - Normal\n shortcut.save()\n path = os.path.join(desktop, 'Shell {0}.lnk'.format(version)) \n target = os.path.normpath(os.path.join(currentDirectory,'..','sbin', 'AION_Shell.bat'))\n icon = os.path.join(currentDirectory,'icons','aion_shell.ico')\n shell = win32com.client.Dispatch(\"WScript.Shell\")\n shortcut = shell.CreateShortCut(path)\n shortcut.Targetpath = '\"'+target+'\"'\n shortcut.WorkingDirectory = currentDirectory\n #shortcut.WorkingDirectory = os.path.dirname(__file__)\n shortcut.IconLocation = icon\n shortcut.WindowStyle = 1 # 7 - Minimized, 3 - Maximized, 1 - Normal\n shortcut.save()\n print('--------------AION Installed Successfully--------------')\n except Exception as e:\n print(e)\n f = open(os.path.join(currentDirectory, 'workspace_error_logs.txt'), \"w\")\n f.write(str(traceback.format_exc()))\n f.close()\n pass\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\n# -*- coding: utf-8 -*-\n# -*- coding: utf-8 -*-\nimport logging\nlogging.getLogger('tensorflow').disabled = True\nimport json\nimport mlflow\nimport mlflow.sklearn\nimport mlflow.sagemaker as mfs\n# from sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split\n# from sklearn import datasets\nimport time\nimport numpy as np\n# Load dataset\n# from sklearn.datasets import load_iris\nimport pickle\n# Load the pickled model\n# from matplotlib import pyplot\nimport sys\nimport os\nimport boto3\nimport subprocess\nimport os.path\nfrom os.path import expanduser\nimport platform\nfrom pathlib import Path\n\n\nclass aionMlopsService:\n def __init__(self,model,mlflowtosagemakerDeploy,mlflowtosagemakerPushOnly,mlflowtosagemakerPushImageName,mlflowtosagemakerdeployModeluri,experiment_name,mlflow_modelname,awsaccesskey_id,awssecretaccess_key,aws_session_token,mlflow_container_name,aws_region,aws_id,iam_sagemakerfullaccess_arn,sm_app_name,sm_deploy_option,delete_ecr_repository,ecrRepositoryName):\n try:\n self.model=model", "instruction": "", "output": "" }, { "input": "\n self.mlflowtosagemakerDeploy=mlflowtosagemakerDeploy\n self.mlflowtosagemakerPushOnly=str(mlflowtosagemakerPushOnly)\n self.mlflowtosagemakerPushImageName=str(mlflowtosagemakerPushImageName)\n self.mlflowtosagemakerdeployModeluri=str(mlflowtosagemakerdeployModeluri)\n self.experiment_name=experiment_name\n self.mlflow_modelname=mlflow_modelname\n self.awsaccesskey_id=awsaccesskey_id\n self.awssecretaccess_key=awssecretaccess_key\n self.aws_session_token=aws_session_token\n self.mlflow_container_name=mlflow_container_name\n self.aws_region=aws_region\n self.aws_id=aws_id\n self.iam_sagemakerfullaccess_arn=iam_sagemakerfullaccess_arn\n self.sm_app_name=sm_app_name\n self.sm_deploy_option=sm_deploy_option\n self.delete_ecr_repository=delete_ecr_repository\n self.ecrRepositoryName=ecrRepositoryName\n \n from appbe.dataPath import LOG_LOCATION \n sagemakerLogLocation = LOG_LOCATION\n \n try:\n os.makedirs(sagemakerLogLocation)\n except OSError as e:\n if (os.path.exists(sagemakerLogLocation)):\n pass\n else:\n raise OSError('sagemakerLogLocation error.')\n \n self.sagemakerLogLocation=str(sagemakerLogLocation)\n \n \n filename_mlops = 'mlopslog_'+str(int(time.time()))\n filename_mlops=filename_mlops+'.log'\n # filename = 'mlopsLog_'+Time()\n filepath = os.path.join(self.sagemakerLogLocation, filename_mlops) \n logging.basicConfig(filename=filepath, format='%(message)s',filemode='w') \n # logging.basicConfig(filename=\"uq_logging.log\", format='%(asctime)s %(message)s',filemode='w') \n # logging.basicConfig(filename=\"uq_logging.log\", format=' %(message)s',filemode='w')\n # logging.basicConfig(filename='uq_logging.log', encoding='utf-8', level=logging.INFO)\n self.log = logging.getLogger('aionMLOps')\n self.log.setLevel(logging.DEBUG)\n # mlflow.set_experiment(self.experiment_name) \n \n except Exception as e:\n self.log.info(' '+str(e))\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n self.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\n def mlflowSetPath(self,path):\n track_dir=os.path.join(path,'mlruns')\n uri=\"file:\"+str(Path(track_dir))\n return uri\n \n #Currently not used this delete ecr repository option\n def ecr_repository_delete(self,rep_name):\n # import subprocess\n client = boto3.client('ecr')\n repositories = client.describe_repositories()\n ecr_delete_rep=client.delete_repository(registryId=self.aws_id,repositoryName=self.ecrRepositoryName,force=True)\n mlflow_ecr_delete=subprocess.run(['aws', 'ecr', 'delete-repository','--repository-name',rep_name,'||','true'])\n self.log.info('Success: deleted aws ecr repository which contains mlops image.')\n\n def check_sm_deploy_status(self,app_name):\n sage_client = boto3.client('sagemaker', region_name=self.aws_region)\n endpoint_description = sage_client.describe_endpoint(EndpointName=app_name)\n endpoint_status = endpoint_description[\"EndpointStatus\"]\n try:\n failure_reason=endpoint_description[\"FailureReason\"]\n self.log.info(\"sagemaker end point creation failure reason is: \"+str(failure_reason))\n except:\n pass\n endpoint_status=str(endpoint_status)\n return endpoint_status\n \n def invoke_sm_endpoint(self,app_name, input_json):\n client = boto3.session.Session().client(\"sagemaker-runtime\", self.aws_region)\n \n response = client.invoke_endpoint(\n EndpointName=app_name,\n Body=input_json,\n ContentType='application/json; format=pandas-split',\n )\n # preds = response['Body'].read().decode(\"ascii\")\n preds = response['Body'].read().decode(\"ascii\")\n preds = json.loads(preds)\n # print(\"preds: {}\".format(preds))\n return preds\n \n def predict_sm_app_endpoint(self,X_test):\n #print(X_test)\n import pandas as pd\n prediction=None\n AWS_ACCESS_KEY_ID=str(self.awsaccesskey_id)\n AWS_SECRET_ACCESS_KEY=str(self.awssecretaccess_key)\n AWS_SESSION_TOKEN=str(self.aws_session_token)\n region = str(self.aws_region)\n #Existing model deploy options\n # mlflowtosagemakerPushImageName=str(self.mlflowtosagemakerPushImageName)\n # mlflowtosagemakerdeployModeluri=str(self.mlflowtosagemakerdeployModeluri)\n try:\n import subprocess\n cmd = 'aws configure set region_name '+region\n os.system(cmd)\n cmd = 'aws configure set aws_access_key_id '+AWS_ACCESS_KEY_ID\n os.system(cmd)\n cmd = 'aws configure set aws_secret_access_key '+AWS_SECRET_ACCESS_KEY\n os.system(cmd)\n '''\n aws_region=subprocess.run(['aws', 'configure', 'set','region_name',region])\n aws_accesskeyid=subprocess.run(['aws', 'configure', 'set','aws_access_key_id',AWS_ACCESS_KEY_ID])\n aws_secretaccesskey=subprocess.run(['aws', 'configure', 'set','aws_secret_access_key',AWS_SECRET_ACCESS_KEY])\n '''\n except:\n pass\n #Create a session for aws communication using aws boto3 lib\n # s3_client = boto3.client('ecr',aws_access_key_id=AWS_ACCESS_KEY_ID,aws_secret_access_key=AWS_SECRET_ACCESS_KEY,aws_session_token=AWS_SESSION_TOKEN,region_name=region)\n # s3 = boto3.resource('ecr', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key= AWS_SECRET_ACCESS_KEY)\n session = boto3.Session(aws_access_key_id=AWS_ACCESS_KEY_ID,aws_secret_access_key=AWS_SECRET_ACCESS_KEY,aws_session_token=AWS_SESSION_TOKEN,region_name=region)\n\n #X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=2)\n # query_input = pd.DataFrame(X_test).iloc[[1,5]].to_json(orient=\"split\")\n try:\n query_input = pd.DataFrame(X_test).to_json(orient=\"split\")\n #print(query_input)\n prediction = self.invoke_sm_endpoint(app_name=self.sm_app_name, input_json=query_input)\n # self.log.info(\"sagemaker end point Prediction: \\\\n\"+str(prediction))\n \n except Exception as e:\n print(e)\n return prediction\n \n \n def deleteSagemakerApp(self,app_name,region):\n # import mlflow.sagemaker as mfs\n #\tregion = 'ap-south-1'\n #\tapp_name = 'aion-demo-app'\n mfs.delete(app_name=app_name,region_name=region, archive=False,synchronous=True, timeout_seconds=300) \n # print(\"AION mlops sagemaker application endpoint is deleted....\\\\n\")\n self.log.info('AION mlops sagemaker application endpoint is deleted, application name is: '+str(app_name))\n \n def deployModel2sagemaker(self,mlflow_container_name,tag_id,model_path):\n \n region = str(self.aws_region)\n aws_id = str(self.aws_id)\n iam_sagemakerfullaccess_arn = str(self.iam_sagemakerfullaccess_arn)\n app_name = str(self.sm_app_name)\n \n model_uri = str(model_path)\n app_status=False\n mlflow_root_dir = None\n try:\n os.chdir(str(self.sagemakerLogLocation))\n mlflow_root_dir = os.getcwd()\n self.log.info('mlflow root dir: '+str(mlflow_root_dir))\n except:\n self.log.info(\"path issue.\")\n \n try:\n c_status=self.check_sm_deploy_status(app_name)\n #if ((c_status == \"Failed\") or (c_status == \"OutOfService\")):\n if ((c_status == \"Failed\") or (c_status.lower() == \"failed\")):\n app_status=False\n self.log.info(\"Sagemaker endpoint status: Failed.\\\\n\")\n mfs.delete(app_name=app_name,region_name=region, archive=False,synchronous=True, timeout_seconds=300)\n elif ((c_status.lower() == \"inservice\") or (c_status == \"InService\")):\n app_status=True\n self.log.info(\"Sagemaker endpoint status: InService. Running sagemaker endpoint name: \\\\n\"+str(app_name)) \n else:\n app_status=False\n pass\n except:\n # print(\"deploy status error.\\\\n\") \n pass\n \n #aws ecr model app_name should contain only [[a-zA-Z0-9-]]\n import re \n if app_name:\n pattern = re.compile(\"[A-Za-z0-9-]+\")\n # if found match (entire string matches pattern)\n if pattern.fullmatch(app_name) is not None:\n #print(\"Found match: \")\n pass\n else: \n app_name = 'aion-demo-app'\n else:\n app_name = 'aion-demo-app'\n \n mlflow_image=mlflow_container_name+':'+tag_id\n image_url = aws_id + '.dkr.ecr.' + region + '.amazonaws.com/' + mlflow_image\n deploy_option=\"create\"\n self.log.info('deploy_option: \\\\n'+str(deploy_option))\n if (deploy_option.lower() == \"create\"):\n # Other deploy modes: mlflow.sagemaker.DEPLOYMENT_MODE_ADD,mlflow.sagemaker.DEPLOYMENT_MODE_REPLACE\n if not (app_status):\n try:\n mfs.deploy(app_name=app_name,model_uri=model_uri,region_name=region,mode=\"create\",execution_role_arn=iam_sagemakerfullaccess_arn,image_url=image_url)\n self.log.info('sagemaker endpoint created and model deployed. Application name is: \\\\n'+str(app_name))\n except:\n self.log.info('Creating end point application issue.Please check the connection and aws credentials \\\\n')\n else:\n self.log.info('Sagemaker application with user endpoint name already running.Please check. Please delete the old endpoint with same name.\\\\n')\n \n \n elif (deploy_option.lower() == \"delete\"):\n # import mlflow.sagemaker as mfs\n # #\tregion = 'ap-south-1'\n # #\tapp_name = 'aion-demo-app'\n # mfs.delete(app_name=app_name,region_name=region, archive=False,synchronous=True, timeout_seconds=300) \n # print(\"Mlflow sagemaker application endpoint is deleted....\\\\n\")\n # self.log.info('Mlflow sagemaker application endpoint is deleted, application name is: '+str(app_name))\n pass\n elif (deploy_option.lower() == \"add\"):\n pass\n elif (deploy_option.lower() == \"replace\"):\n pass\n else:\n pass\n \n return app_status\n \n def mlflow2sagemaker_deploy(self):\n self.log.info(' ')\n deploy_status=False\n app_name = str(self.sm_app_name)\n self.log.info('Sagemaker Application Name: '+str(app_name))\n \n uri_mlflow=self.mlflowSetPath(self.sagemakerLogLocation)\n mlflow.set_tracking_uri(uri_mlflow)\n mlops_trackuri=mlflow.get_tracking_uri()\n mlops_trackuri=str(mlops_trackuri)\n self.log.info('mlops tracking uri: '+str(mlops_trackuri))\n localhost_deploy=False\n try:\n #Loading aion model to deploy in sagemaker\n mlflow.set_experiment(self.experiment_name)\n self.log.info('Endpoint Name: '+str(self.experiment_name))\n # Assume, the model already loaded from joblib in aionmlflow2smInterface.py file. \n aionmodel2deploy=self.model\n # run_id = None\n # experiment_id=None\n \n \n # Use the loaded pickled model to make predictions\n # pred = knn_from_pickle.predict(X_test)\n with mlflow.start_run(run_name='AIONMLOps') as run:\n \n # aionmodel2deploy.fit(X_train, y_train)\n # predictions = aionmodel2deploy.predict(X_test)\n mlflow.sklearn.log_model(aionmodel2deploy, self.mlflow_modelname) \n run_id = run.info.run_uuid\n experiment_id = run.info.experiment_id\n self.log.info('AION mlops experiment run_id: '+str(run_id))\n self.log.info('AION mlops experiment experiment_id: '+str(experiment_id))\n self.log.info('AION mlops experiment model_name: '+str(self.mlflow_modelname))\n artifact_uri = {mlflow.get_artifact_uri()}\n # print(\"1.artifact_uri: \\\\n\",artifact_uri)\n mlflow.end_run()\n #If we need, we can check the mlflow experiments.\n # try: \n # mlflow_client = mlflow.tracking.MlflowClient('./mlruns')\n # exp_list = mlflow_client.list_experiments()\n # except:\n # pass\n #print(\"mlflow exp_list: \\\\n\",exp_list)\n mlflow_modelname=str(self.mlflow_modelname)\n \n m", "instruction": "", "output": "" }, { "input": "lops_trackuri=mlops_trackuri.replace('file:','')\n mlops_trackuri=str(mlops_trackuri)\n # mlflow_root_dir = os.getcwd()\n mlflow_root_dir = None\n try:\n os.chdir(str(self.sagemakerLogLocation))\n mlflow_root_dir = os.getcwd()\n self.log.info('mlflow root dir: '+str(mlflow_root_dir))\n except:\n self.log.info(\"path issue.\")\n model_path = 'mlruns/%s/%s/artifacts/%s' % (experiment_id, run_id,self.mlflow_modelname)\n # model_path=mlops_trackuri+'\\\\\\\\%s\\\\\\\\%s\\\\\\\\artifacts\\\\\\\\%s' % (experiment_id, run_id,mlflow_modelname)\n self.log.info(\"local host aion mlops model_path is: \"+str(model_path))\n time.sleep(2)\n \n \n #print(\"Environment variable setup in the current working dir for aws sagemaker cli connection... \\\\n\") \n self.log.info('Environment variable setup in the current working dir for aws sagemaker cli connection... \\\\n ')\n AWS_ACCESS_KEY_ID=str(self.awsaccesskey_id)\n AWS_SECRET_ACCESS_KEY=str(self.awssecretaccess_key)\n AWS_SESSION_TOKEN=str(self.aws_session_token)\n region = str(self.aws_region)\n #Existing model deploy options\n mlflowtosagemakerPushImageName=str(self.mlflowtosagemakerPushImageName)\n mlflowtosagemakerdeployModeluri=str(self.mlflowtosagemakerdeployModeluri)\n import subprocess\n cmd = 'aws configure set region_name '+region\n os.system(cmd)\n cmd = 'aws configure set aws_access_key_id '+AWS_ACCESS_KEY_ID\n os.system(cmd)\n cmd = 'aws configure set aws_secret_access_key '+AWS_SECRET_ACCESS_KEY\n os.system(cmd)\n #Create a session for aws communication using aws boto3 lib\n # s3_client = boto3.client('ecr',aws_access_key_id=AWS_ACCESS_KEY_ID,aws_secret_access_key=AWS_SECRET_ACCESS_KEY,aws_session_token=AWS_SESSION_TOKEN,region_name=region)\n # s3 = boto3.resource('ecr', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key= AWS_SECRET_ACCESS_KEY)\n session = boto3.Session(aws_access_key_id=AWS_ACCESS_KEY_ID,aws_secret_access_key=AWS_SECRET_ACCESS_KEY,aws_session_token=AWS_SESSION_TOKEN,region_name=region)\n # session = boto3.session.Session(\n # aws_access_key_id=AWS_ACCESS_KEY_ID,\n # aws_secret_access_key=AWS_SECRET_ACCESS_KEY,\n # aws_session_token=AWS_SESSION_TOKEN\n # )\n # awsclient = session.resource('ecr')\n # s3 = session.resource('s3')\n self.log.info('aws environment variable setup done... \\\\n')\n try:\n os.chdir(mlflow_root_dir)\n except FileNotFoundError:\n self.log.info('Directory does not exist. '+str(mlflow_root_dir))\n except NotADirectoryError:\n self.log.info('model_path is not a directory. '+str(mlflow_root_dir))\n except PermissionError:\n self.log.info('Issue in permissions to change to model dir. '+str(mlflow_root_dir))\n\n mlflow_container_name=str(self.mlflow_container_name)\n mlflow_version=mlflow.__version__\n tag_id=mlflow_version\n \n \n if (self.mlflowtosagemakerPushOnly.lower() == \"true\"):\n self.log.info('Selected option is \\\\n')\n aws_id=str(self.aws_id)\n arn=str(self.iam_sagemakerfullaccess_arn)\n mlflow_image=mlflow_container_name+':'+tag_id\n image_url = aws_id+'.dkr.ecr.'+region+'.amazonaws.com/'+mlflow_image\n # print(\"image_url:========= \\\\n\",image_url)\n deploy_status=True\n try:\n model_path=mlflowtosagemakerdeployModeluri\n # ##We need to run mlflow docker container command in the artifacts->model directory inside mlruns.\n self.log.info('Deploy existing model container-Model path given by user: '+str(model_path))\n try:\n os.chdir(model_path)\n except FileNotFoundError:\n self.log.info('Directory does not exist. '+str(model_path))\n except NotADirectoryError:\n self.log.info('model_path is not a directory. '+str(model_path))\n except PermissionError:\n self.log.info('Issue in permissions to change to model dir. '+str(model_path))\n \n try:\n mfs.push_image_to_ecr(image=mlflowtosagemakerPushImageName)\n deploy_status=True\n self.log.info('AION mlops pushed the docker container to aws ecr. \\\\n ')\n except:\n self.log.info(\"error in pushing existing container to ecr.\\\\n\")\n deploy_status=False\n\n \n time.sleep(2)\n #Now,change the working dir to root dir,because now deploy needs full mlruns to model name dir.\n try:\n \t# print(\" Changing directory to mlflow root dir....\\\\n\")\n \tos.chdir(mlflow_root_dir)\n except FileNotFoundError:\n self.log.info('model path is not a directory. '+str(mlflow_root_dir))\n except NotADirectoryError:\n self.log.info('model path is not a directory. '+str(mlflow_root_dir))\n \t# print(\"{0} is not a directory\".format(mlflow_root_dir)) \n except PermissionError:\n self.log.info('Issue in permissions to change to model dir. '+str(mlflow_root_dir))\n \n # self.deployModel2sagemaker(mlflowtosagemakerPushImageName,tag_id,mlflowtosagemakerdeployModeluri)\n try:\n if (deploy_status):\n self.deployModel2sagemaker(mlflowtosagemakerPushImageName,tag_id,mlflowtosagemakerdeployModeluri)\n self.log.info('AION creates docker container and push the container into aws ecr.. ')\n time.sleep(2)\n except:\n self.log.info('AION deploy error.check connection and aws config parameters. ')\n deploy_status=False\n # self.log.info('model deployed in sagemaker. ')\n except Exception as e:\n self.log.info('AION mlops failed to push docker container in aws ecr, check configuration parameters. \\\\n'+str(e))\n elif (self.mlflowtosagemakerPushOnly.lower() == \"false\"):\n if (self.mlflowtosagemakerDeploy.lower() == \"true\"):\n self.log.info('Selected option is \\\\n')\n deploy_status=True\n try:\n # ##We need to run mlflow docker container command in the artifacts->model directory inside mlruns.\n try:\n os.chdir(model_path)\n except FileNotFoundError:\n self.log.info('Directory does not exist. '+str(model_path))\n except NotADirectoryError:\n self.log.info('model_path is not a directory. '+str(model_path))\n except PermissionError:\n self.log.info('Issue in permissions to change to model dir. '+str(model_path))\n try:\n mlflow_container_push=subprocess.run(['mlflow', 'sagemaker', 'build-and-push-container','--build','--push','--container',mlflow_container_name])\n self.log.info('AION mlops creates docker container and push the container into aws ecr.. ')\n deploy_status=True\n time.sleep(2)\n except:\n self.log.info('error in pushing aion model container to sagemaker, please check the connection between local host to aws server.')\n deploy_status=False\n self.log.info('Now deploying the model container to sagemaker starts....\\\\n ')\n # Once docker push completes, again going back to mlflow parent dir for deployment\n #Now,change the working dir to root dir,because now deploy needs full mlruns to model name dir.\n try:\n \tos.chdir(mlflow_root_dir)\n except FileNotFoundError:\n self.log.info('model_path does not exist. '+str(mlflow_root_dir))\n except NotADirectoryError:\n self.log.info('model_path is not a directory. '+str(mlflow_root_dir))\n except PermissionError:\n self.log.info('Issue in permissions to change to model dir. '+str(mlflow_root_dir))\n \n # app_name = str(self.sm_app_name)\n try:\n if (deploy_status):\n self.deployModel2sagemaker(mlflow_container_name,tag_id,model_path)\n except:\n self.log.info('mlops deploy error.check connection')\n deploy_status=False\n \n except Exception as e:\n exc = {\"status\":\"FAIL\",\"message\":str(e).strip('\"')}\n out_exc = json.dumps(exc)\n self.log.info('mlflow failed to creates docker container please check the aws iam,ecr permission setup, aws id access_key,secret key values for aion.\\\\n')\n \n elif(self.mlflowtosagemakerDeploy.lower() == \"false\"):\n deploy_status=False\n localhost_deploy=True\n self.log.info('Selected option is \\\\n')\n self.log.info(\"User selected create-Deploy sagemaker option as False,\")\n self.log.info(\"Creates the AION mlops-sagemaker container locally starting,but doesn't push into aws ecr and deploy in sagemaker. Check the container in docker repository. \")\n try:\n # ##We need to run AION mlops docker container command in the artifacts->model directory inside mlruns.\n try:\n os.chdir(model_path)\n self.log.info('After change to AION mlops model dir, cwd: '+str(model_path))\n except FileNotFoundError:\n self.log.info('Directory does not exist. '+str(model_path))\n except NotADirectoryError:\n self.log.info('model_path is not a directory. '+str(model_path))\n except PermissionError:\n self.log.info('Issue in permissions to change to model dir. '+str(model_path))\n \n # mlflow_container_local=subprocess.run(['AION mlops', 'sagemaker', 'build-and-push-container','--build','--no-push','--container',mlflow_container_name])\n \n try:\n if not (deploy_status):\n mlflow_container_local=subprocess.run(['mlflow', 'sagemaker', 'build-and-push-container','--build','--no-push','--container',mlflow_container_name])\n self.log.info('AION creates local host bsed docker container and push the container local docker repository. Check with command.\\\\n ')\n localhost_deploy=True\n time.sleep(2)\n except:\n self.log.info('error in pushing aion model container to sagemaker, please check the connection between local host to aws server.')\n deploy_status=False\n localhost_deploy=False\n \n # print(\"AION mlops creates docker container and push the container into aws ecr.\\\\n\")\n self.log.info('AION mlops creates docker container and stored locally... ')\n time.sleep(2)\n except Exception as e:\n localhost_deploy=False\n # print(\"mlflow failed to creates docker container please check the aws iam,ecr permission setup, aws id access_key,secret key values for aion.\\\\n\")\n self.log.info('AION mlops failed to creates docker container in local machine.\\\\n'+str(e)) \n else:\n self.log.info('Deploy option not selected, Please check. ')\n localhost_deploy=False\n deploy_status=False\n else:\n pass\n \n \n \n \n \n localhost_container_status=\"Notdeployed\" \n mlflow2sm_deploy_status=\"Notdeployed\"\n if localhost_deploy:\n localhost_container_status=\"success\"\n mlflow2sm_deploy_status=\"Notdeployed\"\n # print(\"AION creates local docker container successfully.Please check in docker repository.\")\n self.log.info(\"AION creates local docker container successfully.Please check in docker repository.\")\n # else:\n # localhost_container_status=\"failed\"\n # # print(\"AION failed to create local docker container successfully.Please check in docker repository.\")\n # self.log.info(\"AION failed to create local docker container successfully.Please check in docker repository.\")\n \n if (deploy_status):\n # Finally checking whether mlops model is deployed to sagemaker or not.\n app_name = str(self.sm_app_name)\n deploy_s = self.check_sm_deploy_status(app_name)\n if (deploy_s == \"InService\"):\n # print(\"AION mlops model is deployed at aws sagemaker, use application name(app_name) and region to access.\\\\n\")\n self.log.info('AION mlops model is deployed at aws sagemaker, use application name(app_name) and region to access.\\\\n'+str(app_name))\n mlflow2sm_deploy_status=\"success\"\n localhost_container_status=\"Notdeployed\"\n else:\n # print(\"AION Mlflow model not able to deploy at aws sagemaker\\\\n\")\n self.log.info('AION mlops model not able to deploy at aws sagemaker.\\\\n')\n mlflow2sm_deploy_status=\"failed\"\n localhost_container_status=\"Notdeployed\"\n \n # else:\n # mlflow2sm_deploy_status=\"None\"\n \n \n return mlflow2sm_deploy_status,localhost_container_status\n \n except Exception as inst:\n exc = {\"status\":\"FAIL\",\"message\":str(inst).strip('\"')}\n out_exc = json.dumps(exc)\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via", "instruction": "", "output": "" }, { "input": "any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n''' '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport socket\nimport os\nimport rsa\nfrom os.path import expanduser\nfrom pathlib import Path\nimport requests\nimport platform\nfrom appbe.dataPath import DATA_DIR\nimport socket\nimport getmac\nimport subprocess\nimport sys\nimport json\nfrom datetime import datetime\nimport binascii\ncomputername = socket.getfqdn()\nglobal_key = '''\n-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAzJcxqRiUpp7CzViyqNlYaeyceDh5y6Ib4SoxoyNkN3+k0q+cr1lb\nk0KdWTtHIVqH1wsLYofYjpB7X2RN0KYTv8VfwmfQNrpFEbiRz4gcAeuxGCPgGaue\nN1ttujQMWHWCcY+UH5Voh8YUfkW8P+T3zxvr1d30D+kVBJC59y/31JvTzr3Bw/T+\nNYv6xiienYiEYtm9d5ATioEwZOXaQBrtVvRmqcod5A1h4kn1ZauLX2Ph8H4TAuit\nNLtw6xUCJNumphP7xdU+ca6P6a6eaLprgKhvky+nz16u9/AC2AazRQHKWf8orS6b\nfw16JDCRs0zU4mTQLCjkUUt0edOaRhUtcQIDAQAB\n-----END RSA PUBLIC KEY-----\n'''\n\nquarter_key = '''\n-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAmKzOJxVEV9ulA+cjfxguAduLMD47OWjLcEAEmEuK8vR4O5f6e2h1\n08NniGC+nkwqmM00U7JTVBkqnt9S/JgE3pAH2xwfWda2OvXNWisWmOQdqB0+XRHh\nNXsIG3yRk/sMlDpe7MJIyM5ADSu01PLn9FZTfmMq7lEp32tAf71cuUE/dwuWSvEQ\nWK2hn1L4D97O43XCd7FHtMSHfgtjdcCFgX9IRgWLKC8Bm3q5qcqF4v3cHuYTj3V9\nnjxPtRqPg6HJFiJrm9AX5bUEHAvbTcw4wAmsNTRQHPvVB+Lc+yGh5x8crhKjNB01\ngdB5I3a4mPO7dKvadR6Mr28trr0Ff5t2HQIDAQAB\n-----END RSA PUBLIC KEY-----\n'''\n\nhalfYear_key='''\n-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAgrGNwl8CNYQmVxi8/GEgPjfL5aEmyPkDyaJb9h4hZDSZCeeKd7Rv\nwwhuRTdBBfOp0bQ7QS7NYMg38Xlc3x85I9RnxdQdDKn2nRuvG0hG3wMBFy/DCSXF\ntXbDjJkLijAhqcBNu8m+a2Gtn14ShC7TbcfY4iVXho3WFUrn0xq6S5ducqWCsLJh\nR+TNImCaMICqfoAzEDGC3ojO5Hi3vJmmyK5CVp6bt4wLRATQjcp1ujGW4Uv4kEgp\n7TR077c226v1KOdKdyZPHJzT1MKwZrG2Gdluk3/Y1apbwyGzYqFdTCOAB+mE73Dn\nwFXURgDJQmaU2oxxaA13WRcELpnirm+aIwIDAQAB\n-----END RSA PUBLIC KEY-----\n'''\noneYear_key='''\n-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEA3GLqn+vkKn3fTNH3Bbb3Lq60pCoe+mn0KPz74Bp7p5OkZAUe14pP\nTcf/UqdPwiENhSCseWtfZmfKDK8qYRHJ5xW02+AhHPPdiacS45X504/lGG3q/4SG\nZgaFhMDvX+IH/ZH+qqbU3dRQhXJCCrAVAa7MonzM6yPiVeS2SdpMkNg1VDR1oTLB\nPn+qSV6CnkK1cYtWCRQ23GH2Ru7fc09r7m8hVcifKJze84orpHC5FX0WScQuR8h/\nfs1IbGkxTOxP8vplUj/cd4JjUxgd+w+8R4kcoPhdGZF5UGeZA8xMERzQLvh+4Ui0\nKIvz5/iyKB/ozaeSG0OMwDAk3WDEnb1WqQIDAQAB\n-----END RSA PUBLIC KEY-----\n'''\nfull_key='''\n-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAhqfNMuYYLdVrePhkO9rU/qT6FgolzI0YyzIJ2OeJE+++JioYm6nn\nohQU32iiE0DZlCCLrHJXOOIAz2Op80goX0lxtngyxVUPsiB5CI77sAC7x6K3anJ0\nelpnQCC0+xV2ZL5eIMNQHLe+X6wJl/HGWqkUlxKpWr4/kBEB4EisW60OePfhntIN\n4OUJ7iEq+sDdOM5WazJIXeNV1cig4i6057GE3k5ITcQUmw17DZu2+dqkIscckaG+\nt5SF7Qnvt4IY8IeQp2htx3yD+CJCV0u2uKwoSFMGJn3OWdaixC3+eojyMXmfAWtQ\nEe9NLNNaTCMIvQ8BeItJLQs2Htw3bZNMvwIDAQAB\n-----END RSA PUBLIC KEY-----\n'''\ndef validate_key_Pair(privatepath,publickey):\n\twith open(privatepath, 'rb') as privatefile:\n\t\tkeydata = privatefile.read()\n\tprivatefile.close()\n\ttry:\n\t\tprivkey = rsa.PrivateKey.load_pkcs1(keydata,'PEM')\n\t\tdata = 'Validate Global License'\n\t\tsignature = rsa.sign(data.encode('utf-8'), privkey, 'SHA-1')\n\t\tpubkey = rsa.PublicKey.load_pkcs1(publickey)\n\texcept:\n\t\treturn False\n\ttry:\n\t\trsa.verify(data.encode('utf-8'), signature, pubkey)\n\t\treturn True\n\texcept Exception as e:\n\t\treturn False\n\t\t\ndef updateDRecord(licensepath):\n\tdomain_license_path = os.path.join(DATA_DIR,'License','license_domain.lic')\n\tif(os.path.isfile(licensepath)):\n\t\twith open(licensepath, 'rb') as f:\n\t\t\tlicensekey = f.read()\n\t\tf.close()\n\t\twith open(domain_license_path, 'wb') as f:\n\t\t\tf.write(licensekey)\n\t\tf.close()\n\t\tif(validate_key_Pair(domain_license_path,global_key)):\n\t\t\treturn True,'Valid Domain License'\n\t\telse:\n\t\t\treturn False,'Invalid Domain License'\n\telse:\n\t\treturn False,'File Not Exists'\n\ndef generateLicenseKey(userKey):\n record = {'UserKey':userKey}\n record = json.dumps(record)\n status = 'Error'\n url = 'https://qw7e33htlk.execute-api.ap-south-1.amazonaws.com/default/aion_license'\n try:\n response = requests.post(url, data=record,headers={\"x-api-key\":\"3cQKRkKA4S57pYrkFp1Dd9jRXt4xnFoB9iqhAQRM\",\"Content-Type\":\"application/json\",})\n if response.status_code == 200:\n outputStr=response.content\n outputStr = outputStr.decode('utf-8','ignore')\n outputStr = outputStr.strip()\n license_dict = json.loads(str(outputStr))\n if license_dict['status'] == 'success':\n status = 'Success'\n licenseKey = license_dict['msg']\n else:\n status = 'Error'\n licenseKey = ''\n else:\n status = 'Error'\n licenseKey = ''\n except Exception as inst:\n print(inst)\n status = 'Error'\n licenseKey = ''\n msg = {'status':status,'key':userKey,'licenseKey':licenseKey,'link':''} \n return msg\ndef updateRecord(licensepath):\n\tcurrentDirectory = os.path.dirname(os.path.abspath(__file__))\n\tlicense_path = os.path.join(currentDirectory,'..','lic','license.lic') \n\tif(os.path.isfile(licensepath)):\n\t\twith open(licensepath, 'rb') as f:\n\t\t\tlicensekey = f.read()\n\t\tf.close()\n\t\twith open(license_path, 'wb') as f:\n\t\t\tf.write(licensekey)\n\t\tf.close()\n\t\tstatus,msg = check_domain_license()\n\t\tif status:\n\t\t\tstatus,msg = getdaysfromstartdate()\n\t\t\tif status:\n\t\t\t\tstatus,msg = check_days_license(int(msg))\n\t\treturn status,msg\n\telse:\n\t\treturn False,'File Not Exists'\n\t\t\n\t\t\ndef check_domain_license():\n\tif 'CORP.HCL.IN' in computername:\n\t\treturn True,'HCL Domain'\n\telse:\n\t\treturn True,'HCL Domain'\n\t\t\t\ndef diff_month(d1, d2):\n\treturn (d1.year - d2.year) * 12 + d1.month - d2.month\n\n\ndef getdaysfromstartdate():\n\tcurrentDirectory = os.path.dirname(os.path.abspath(__file__))\n\tstartdatePath = os.path.join(currentDirectory,'..','lic','startdate.txt') \n\t\n\tif(os.path.isfile(startdatePath)):\n\t\twith open(startdatePath, \"rb\") as fl:\n\t\t\tencrypted_message = fl.read()\n\t\tfl.close()\n\n\t\tprivkey = '''-----BEGIN RSA PRIVATE KEY-----\nMIIEqwIBAAKCAQEAm75ZwaepuxGJjU1Slk1+IUO2E49Hy8i9dym5FUaBRyTRH6R+\nGTF1kcpd+1QinIZDMIdsmAc95Y8pTufxY30QxCkOhVASitSQWHS/IiWQHmsTJwdr\n38lqZnQQloOt/iPlhcavbxu/yKFzwBmp+nM+ErDTnCBh6EGCGrw1xWF30T2IBpmp\nWwMEoqZsFV69RzwQAw39KG1KCxi5uscrB62YPgUdlT2b4Yaa90egQhGLLVdnKvhP\nORiGT9omCH90Dkm1oMMQ0Y2JBLezgXa/bunSqtTBxEwzlwUAX2JJcanFYrzKy2OL\nxzwNRlWUXilZ4R/1RHAgUdNyKbYxZqc24MApoQIDAQABAoIBAQCHZ/i7gNz10qqH\n2qkqGlfF7gvYd6MRTwdDGlhbYgA17ZGP9EDaAIFabtpFEAJDmgvCnotQpkMvWcet\nXcUmHW89TQDd8R8d6u9QqLggpQ3nFGsDbNViLMjAKLrfUb8tjOIZ7ANNE5ArjAuK\nAgYhxJ48O9bPD+xvtLwip95PHxMMz1CF0vxrpCinvPdeC3HzcnLNZWN3ustbph/4\nTx8mrKDpAVIHVYVbY4CMtm7NbIBYdyR9Lokc4zBg/OTuLo+0QRVJ3GHAN6cGxTwY\nvLwN9iBBHyn9WBp5NIOSoCdob7+ce8y+X8yHmVhwRCfcrYphzfFNfP7SPNzV1dLs\ndFybn/h9AoGJALCOC7ss+PBXy5WrWVNRPzFO7KrJDl5q7s/gMk0PkB4i4XOKHDTl\nMhHZXhxp84HwpphwNxPHvpFe3pVZwwoe8LH1neoodlLOF0Kuk3jENh6cMhKFvcZ+\ngxaBxGSCOXF/U307mh0i4AafClhVjxtLgBW5iJSVA9Brc7ZqVwxlUP7aYGzReIE1\nuEMCeQDh0vq8NteUlkM/wpNzrHHqgtEzePbTYa+QcTm4xhARHR/cO+E0/mZIfltw\n3NVWCIalMia+aKnvRHqHy/cQfEo2Uv/h8oARWnbrvicMRTwYL0w2GrP0f+aG0RqQ\nmsLMzS3kp6szhM7C99reFxdlxJoWBKkp94psOksCgYkApB01zGRudkK17EcdvjPc\nsMHzfoFryNpPaI23VChuR4UW2mZ797NAypSqRXE7OALxaOuOVuWqP8jW0C9i/Cps\nhI+SnZHFAw2tU3+hd3Wz9NouNUd6c2MwCSDQ5LikGttHSTa49/JuGdmGLTxCzRVu\nV0NiMPMfW4I2Sk8", "instruction": "", "output": "" }, { "input": "o4U3gbzWgwiYohLrhrwJ5ANun/7IB2lIykvk7B3g1nZzRYDIk\nEFpuI3ppWA8NwOUUoj/zksycQ9tx5Pn0JCMKKgYXsS322ozc3B6o3AoSC5GpzDH4\nUnAOwavvC0ZZNeoEX6ok8TP7EL3EOYW8s4zIa0KFgPac0Q0+T4tFhMG9qW+PWwhy\nOxeo3wKBiCQ8LEgmHnXZv3UZvwcikj6oCrPy8fnhp5RZl2DPPlaqf3vokE6W5oEo\nLIKcWKvth3EU7HRKwYgaznj/Mw55aETx31R0FiXMG266B4V7QWPF/KuaR0GBsYfu\n+edGXQCnLgooKlMtQLdL5mcLXHc9x/0Z0iYEejJtbjcGR87WylSNaCH3hH703iQ=\n-----END RSA PRIVATE KEY-----\n\t\t'''\n\t\tprivkey = rsa.PrivateKey.load_pkcs1(privkey,'PEM')\n\t\tdecrypted_message = rsa.decrypt(encrypted_message, privkey)\n\t\tdecrypted_message = decrypted_message.decode()\n\t\timport datetime\n\t\tstart_time = datetime.datetime.strptime(decrypted_message, '%Y-%m-%d')\n\t\t\n\t\tcurrent_date = datetime.datetime.today().strftime('%Y-%m-%d')\n\t\tcurrent_date = datetime.datetime.strptime(current_date, '%Y-%m-%d')\n\t\t\n\t\tMonths = diff_month(current_date,start_time)\n\t\treturn True,Months\n\telse:\n\t\treturn False,'Start Date Not Exists'\ndef check_days_license(months):\n\tcurrentDirectory = os.path.dirname(os.path.abspath(__file__))\n\tlicense_path = os.path.join(currentDirectory,'..','lic','license.lic')\n\tif(os.path.isfile(license_path)):\n\t\tif(validate_key_Pair(license_path,full_key)):\t\n\t\t\treturn True,'Valid License'\n\t\telif(validate_key_Pair(license_path,oneYear_key)):\n\t\t\tif months <= 12:\n\t\t\t\treturn True,'Valid License'\n\t\t\telse:\n\t\t\t\treturn False,'License for AI.ON has expired. Please contact ERS Research for renewal.'\n\t\telif(validate_key_Pair(license_path,halfYear_key)):\n\t\t\tif months <= 6:\n\t\t\t\treturn True,'Valid License'\n\t\t\telse:\n\t\t\t\treturn False,'License for AI.ON has expired. Please contact ERS Research for renewal.'\n\t\telif(validate_key_Pair(license_path,quarter_key)):\t\n\t\t\tif months <= 3:\n\t\t\t\treturn True,'Valid License'\n\t\t\telse:\n\t\t\t\treturn False,'License for AI.ON has expired. Please contact ERS Research for renewal.'\n\t\telse:\n\t\t\treturn False,'Invalid License'\n\telse:\n\t\treturn False,'License Not exists.Please contact ERS Research for renewal.'\n\ndef checklicense():\n import binascii\n license_path = os.path.join(DATA_DIR,'License','license.lic')\n if(os.path.isfile(license_path)):\n try:\n with open(license_path, 'r') as privatefile:\n license_key = privatefile.read()\n privatefile.close()\n encrypted_message = binascii.unhexlify(license_key.encode())\n privkey = '''-----BEGIN RSA PRIVATE KEY-----\n MIIEqQIBAAKCAQEAhqfNMuYYLdVrePhkO9rU/qT6FgolzI0YyzIJ2OeJE+++JioY\n m6nnohQU32iiE0DZlCCLrHJXOOIAz2Op80goX0lxtngyxVUPsiB5CI77sAC7x6K3\n anJ0elpnQCC0+xV2ZL5eIMNQHLe+X6wJl/HGWqkUlxKpWr4/kBEB4EisW60OePfh\n ntIN4OUJ7iEq+sDdOM5WazJIXeNV1cig4i6057GE3k5ITcQUmw17DZu2+dqkIscc\n kaG+t5SF7Qnvt4IY8IeQp2htx3yD+CJCV0u2uKwoSFMGJn3OWdaixC3+eojyMXmf\n AWtQEe9NLNNaTCMIvQ8BeItJLQs2Htw3bZNMvwIDAQABAoIBAGGmuRnrYaeDeWAO\n CmqZxRMyQybOjyDrRgq9rAR/zJoHp8b3ikcBDTkuBQELWVZLFj7k50XU2cono9zC\n cxI5xwVrNqrUOkV+7VYJVJzPTFkT/xnEt+zbOfstKmmIDpdzthtTLuHlomhhHA83\n rPFi5a0Dpynz35suEnm6ONxx4ICONa3xkQ51ALm8EEsdJ+qRQhi2HLTF/OVZMxSa\n A2DlFd4ChOEbYaN63xVCDxPXe9BfeHd/Rnim9x4xL9i2RL+mhARUy/ZP6LMHIPk7\n NxTrGr4TuE/ETg8FZ3cywSnwsMlcplXo8Ar+5ths2XKxbmH1TI/vuQV1r7r0IeqV\n F4W/xOkCgYkAiDQy7/WyJWuT+rQ+gOjSUumXgWE3HO+vJAsy05cTZFSs+nUE4ctn\n FnvbBIRuClSr3zhcTtjaEaVnZ2OmGfOoAq0cvaXSlxqEs2456WQBf9oPHnvJEV07\n AIqzo2EuDvGUh/bkFN3+djRRL9usNNplYA8jU3OQHGdeaS15ZikT+ZkQLXoHE0Oh\n vQJ5AP0W9Qouvc9jXRhjNNOWmgt+JiHw/oQts/LUWJ2T4UJ7wKAqGwsmgf0NbF2p\n aZ6AbMc7dHzCb52iLJRxlmlkJYzg449t0MgQVxTKQ5viIAdjkRBCIY2++GcYXb6k\n 6tUnF0Vm2kpffYUb5Lx5JoUE6IhMP0mEv3jKKwKBiCmvoC9lCUL+q+m9JKwbldOe\n fqowcMfAa+AiNUohIORCLjbxfa8Fq+VrvtqhFXS/+WJ2Q3o2UHe6Ie24x+uFcVRw\n Wy2IBO4ORbMM91iBLRxORvZTeHSCDj7aNKS6Z3hXY9hBLglc8DaJSJfXKdt7RC+k\n MnGmGuM2l+Sk8FTeGaj4ucTRZjz1JBkCeQDhNSV1GyShv4xeoCCoy1FmOqmZ+EWy\n vqxqv1PfXHDM5SwCGZWY9XokAGbWbWLjvOmO27QLNEV34pCCwxSR0aCsXI2B2rk2\n 3Xtvr5A7zRqtGIdEDWSoKjAGJSN9+mhQpglKI3zJQ3GBGdIPeEqzgSud5SNHu01a\n IaMCgYgyoxtqdWi90iE75/x+uIVGJRdHtWoL2dr8Ixu1bOMjKCR8gjneSRTqI1tA\n lbRH5K/jg6iccB/pQmBcIPIubF10Nv/ZQV760WK/h6ue2hOCaBLWT8EQEEfBfnp+\n 9rfBfNQIQIkBFTfGIHXUUPb9sJgDP1boUxcqxr9bpKUrs1EMkUd+PrvpHIj2\n -----END RSA PRIVATE KEY-----\n '''\n privkey = rsa.PrivateKey.load_pkcs1(privkey,'PEM')\n decrypted_message = rsa.decrypt(encrypted_message, privkey)\n msg = decrypted_message.decode().split('####')\n product = msg[0] \n computernameLicense = msg[1]\n computername = socket.getfqdn()\n licenseValid = False \n if product.lower() == 'aion':\n if computernameLicense == computername:\n uuidlicense = msg[3]\n uuid = guid()\n if uuidlicense == uuid:\n current_date = datetime.now()\n license_expiry_date = msg[5]\n license_expiry_date = datetime.strptime(license_expiry_date,'%Y-%m-%d %H:%M:%S')\n if current_date > license_expiry_date:\n return False,'License Expire'\n else: \n return True,''\n return False,'License Error'\n except Exception as e:\n print(e)\n return False,'License Error'\n else:\n return False,'Generate License'\ndef generate_record_key(product,version):\n computername = socket.getfqdn()\n macaddress = getmac.get_mac_address()\n license_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')\n try:\n user = os.getlogin()\n except:\n user = 'NA'\n uuid = guid()\n msg = product+'###'+version+'###'+computername+'###'+macaddress+'###'+user+'###'+sys.platform+'###'+uuid+'###'+license_date\n pkeydata='''-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAm75ZwaepuxGJjU1Slk1+IUO2E49Hy8i9dym5FUaBRyTRH6R+GTF1\nkcpd+1QinIZDMIdsmAc95Y8pTufxY30QxCkOhVASitSQWHS/IiWQHmsTJwdr38lq\nZnQQloOt/iPlhcavbxu/yKFzwBmp+nM+ErDTnCBh6EGCGrw1xWF30T2IBpmpWwME\noqZsFV69RzwQAw39KG1KCxi5uscrB62YPgUdlT2b4Yaa90egQhGLLVdnKvhPORiG\nT9omCH90Dkm1oMMQ0Y2JBLezgXa/bunSqtTBxEwzlwUAX2JJcanFYrzKy2OLxzwN\nRlWUXilZ4R/1RHAgUdNyKbYxZqc24MApoQIDAQAB\n-----END RSA PUBLIC KEY-----\n'''\n pubkey = rsa.PublicKey.load_pkcs1(pkeydata)\n encrypted_message = rsa.encrypt(msg.encode(), pubkey)\n encrypted_message = binascii.hexlify(encrypted_message).decode()\n return(encrypted_message)\n\ndef run(cmd):\n try:\n return subprocess.run(cmd, shell=True, capture_output=True, check=True, encoding=\"utf-8\").stdout.strip()\n except Exception as e:\n print(e)\n return None\n\ndef guid():\n if sys.platform == 'darwin':\n return run(\n \"ioreg -d2 -c IOPlatformExpertDevice | awk -F\\\\\\\\\\\\\" '/IOPlatformUUID/{print $(NF-1)}'\",\n )\n\n if sys.platform == 'win32' or sys.platform == 'cygwin' or sys.platform == 'msys':\n return run('wmic csproduct get uuid').split('\\\\n')[2].strip()\n\n if sys.platform.startswith('linux'):\n return run('cat /var/lib/dbus/machine-id') or \\\\\n run('cat /etc/machine-id')\n\n if sys.platform.startswith('openbsd') or sys.platform.startswith('freebsd'):\n return run('cat /etc/hostid') or \\\\\n run('kenv -q smbios.system.uuid')\n\n \ndef updateLicense(licensekey):\n license_folder = os.path.join(DATA_DIR,'License')\n license_folder = Path(license_folder)\n license_folder.mkdir(parents=True, exist_ok=True)\n license_file = license_folder/'license.lic'\n with open(license_file, \"w\") as fl:\n fl.write(licensekey)\n fl.close()\n\n \ndef enterRecord(version):\n validLicense,msg = checklicense()\n if not validLicense:\n key = generate_record_key('AION',version)\n msg = {'status':msg,'key':key,'licenseKey':'','link':''}\n return validLicense,msg\n\t\t\t '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n''' '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport sys\nimport json\nimport datetime,time,timeit\nimport itertools\n\n#Sci-Tools imports\n\nimport numpy as np\nimport pandas as pd\nimport math\nfrom statsmodels.tsa.stattools import adfuller\nfrom scipy.stats.stats import pearsonr\nfrom numpy import cumsum, log, polyfit, sqrt, std, subtract\nfrom numpy.random import randn\n#SDP1 class import\nfrom feature_engineering.featureImportance import featureImp\nfrom sklearn.feature_selection", "instruction": "", "output": "" }, { "input": "import VarianceThreshold\nimport logging\n\nclass featureReducer():\n\tdef __init__(self):\n\t\tself.pandasNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n\t\tself.log = logging.getLogger('eion')\n\tdef startReducer(self,df,data_columns,target,var_threshold):\n\t\tself.log.info('\\\\n---------- Feature Reducer Start ----------')\n\t\tdataframe = df\n\t\tcolumns=data_columns\n\t\ttarget = target\n\t\tcorrThreshold=1.0\n\t\tcategoricalFeatures=[]\n\t\tnonNumericFeatures=[]\n\t\tconstFeatures=[]\n\t\tqconstantColumns=[]\n\t\tDtypesDic={}\n\t\tnumericFeatures=[]\n\t\tnonNumericalFeatures=[]\n\t\tsimilarFeatureGroups=[]\n\t\ttry:\n\t\t\tdataFDtypes=self.dataFramecolType(dataframe)\n\t\t\tfor item in dataFDtypes: \n\t\t\t\tDtypesDic[item[0]] = item[1]\n\t\t\t\tif item[1] in self.pandasNumericDtypes:\n\t\t\t\t\tnumericFeatures.append(item[0])\n\t\t\t\telse:\n\t\t\t\t\tnonNumericFeatures.append(item[0])\n\t\t\t#Checking for constant data features\n\t\t\tfor col in columns:\n\t\t\t\ttry:\n\t\t\t\t\tdistCount = len(dataframe[col].unique())\n\t\t\t\t\tif(distCount == 1):\n\t\t\t\t\t\tconstFeatures.append(col)\n\t\t\t\texcept Exception as inst:\n\t\t\t\t\tself.log.info('Unique Testing Fail for Col '+str(col))\n\n\t\t\tnumericalDataCols,nonNumericalDataCols = [],[]\n\t\t\t#Removing constant data features\n\t\t\tif(len(constFeatures) != 0):\n\t\t\t\tself.log.info( '-------> Constant Features: '+str(constFeatures))\n\t\t\t\tnumericalDataCols = list(set(numericFeatures) - set(constFeatures))\n\t\t\t\tnonNumericalDataCols = list(set(nonNumericFeatures) - set(constFeatures))\n\t\t\telse:\n\t\t\t\tnumericalDataCols = list(set(numericFeatures))\n\t\t\t\tnonNumericalDataCols = list(set(nonNumericFeatures))\n\t\t\tif(len(numericalDataCols) > 1):\n\t\t\t\tif var_threshold !=0:\n\t\t\t\t\tqconstantFilter = VarianceThreshold(threshold=var_threshold)\n\t\t\t\t\ttempDf=df[numericalDataCols]\n\t\t\t\t\tqconstantFilter.fit(tempDf)\n\t\t\t\t\tqconstantColumns = [column for column in numericalDataCols if column not in tempDf.columns[qconstantFilter.get_support()]]\n\n\t\t\t\t\tif(len(qconstantColumns) != 0):\n\t\t\t\t\t\tif target != '' and target in qconstantColumns:\n\t\t\t\t\t\t\tqconstantColumns.remove(target)\n\t\t\t\t\tself.log.info( '-------> Low Variant Features: '+str(qconstantColumns))\n\t\t\t\t\tself.log.info('Status:- |... Low variance feature treatment done: '+str(len(qconstantColumns))+' low variance features found')\n\t\t\t\t\tnumericalDataCols = list(set(numericalDataCols) - set(qconstantColumns))\n\t\t\telse:\n\t\t\t\tself.log.info('Status:- |... Low variance feature treatment done: Found zero or 1 numeric feature')\n #Minimum of two columns required for data integration\n\t\t\tif(len(numericalDataCols) > 1):\n\t\t\t\tnumColPairs = list(itertools.product(numericalDataCols, numericalDataCols))\n\t\t\t\tnoDupList = []\n\t\t\t\tfor item in numColPairs:\n\t\t\t\t\tif(item[0] != item[1]):\n\t\t\t\t\t\tnoDupList.append(item)\n\t\t\t\tnumColPairs = noDupList\n\t\t\t\ttempArray = []\n\t\t\t\tfor item in numColPairs:\n\t\t\t\t\ttempCorr = np.abs(dataframe[item[0]].corr(dataframe[item[1]]))\n\t\t\t\t\tif(tempCorr > corrThreshold):\n\t\t\t\t\t\ttempArray.append(item[0])\n\t\t\t\ttempArray = np.unique(tempArray)\n\t\t\t\tnonsimilarNumericalCols = list(set(numericalDataCols) - set(tempArray))\n\t\t\t\t'''\n\t\t\t\tNotes:\n\t\t\t\ttempArray: List of all similar/equal data features\n\t\t\t\tnonsimilarNumericalCols: List of all non-correlatable data features\n\t\t\t\t'''\n\t\t\t\t#Grouping similar/equal features\n\t\t\t\tgroupedFeatures = []\n\t\t\t\tif(len(numericalDataCols) != len(nonsimilarNumericalCols)):\n\t\t\t\t\t#self.log.info( '-------> Similar/Equal Features: Not Any')\n #Correlation dictionary\n\t\t\t\t\tcorrDic = {}\n\t\t\t\t\tfor feature in tempArray:\n\t\t\t\t\t\ttemp = []\n\t\t\t\t\t\tfor col in tempArray:\n\t\t\t\t\t\t\ttempCorr = np.abs(dataframe[feature].corr(dataframe[col]))\n\t\t\t\t\t\t\ttemp.append(tempCorr)\n\t\t\t\t\t\tcorrDic[feature] = temp\n #Similar correlation dataframe\n\t\t\t\t\tcorrDF = pd.DataFrame(corrDic,index = tempArray)\n\t\t\t\t\tcorrDF.loc[:,:] = np.tril(corrDF, k=-1)\n\t\t\t\t\talreadyIn = set()\n\t\t\t\t\tsimilarFeatures = []\n\t\t\t\t\tfor col in corrDF:\n\t\t\t\t\t\tperfectCorr = corrDF[col][corrDF[col] > corrThreshold].index.tolist()\n\t\t\t\t\t\tif perfectCorr and col not in alreadyIn:\n\t\t\t\t\t\t\talreadyIn.update(set(perfectCorr))\n\t\t\t\t\t\t\tperfectCorr.append(col)\n\t\t\t\t\t\t\tsimilarFeatures.append(perfectCorr)\n\t\t\t\t\tself.log.info( '-------> No Similar/Equal Features: '+str(len(similarFeatures)))\n\t\t\t\t\tfor i in range(0,len(similarFeatures)):\n\t\t\t\t\t\tsimilarFeatureGroups.append(similarFeatures[i])\n\t\t\t\t\t\t#self.log.info((str(i+1)+' '+str(similarFeatures[i])))\n\t\t\t\t\tself.log.info('-------> Similar/Equal Features: '+str(similarFeatureGroups))\n\t\t\t\t\tself.log.info('-------> Non Similar Features :'+str(nonsimilarNumericalCols))\n\t\t\t\t\tupdatedSimFeatures = []\n\t\t\t\t\tfor items in similarFeatures:\n\t\t\t\t\t\tif(target != '' and target in items):\n\t\t\t\t\t\t\tfor p in items:\n\t\t\t\t\t\t\t\tupdatedSimFeatures.append(p)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tupdatedSimFeatures.append(items[0])\n\t\t\t\t\tnewTempFeatures = list(set(updatedSimFeatures + nonsimilarNumericalCols))\n\t\t\t\t\tupdatedNumFeatures = newTempFeatures\n\t\t\t\t\t#self.log.info( '\\\\n <--- Merged similar/equal features into one ---> ')\n\t\t\t\t\tupdatedFeatures = list(set(newTempFeatures + nonNumericalDataCols))\n\t\t\t\t\tself.log.info('Status:- |... Similar feature treatment done: '+str(len(similarFeatures))+' similar features found')\n\t\t\t\telse:\n\t\t\t\t\tupdatedNumFeatures = numericalDataCols\n\t\t\t\t\tupdatedFeatures = list(set(columns) - set(constFeatures)-set(qconstantColumns))\n\t\t\t\t\tself.log.info( '-------> Similar/Equal Features: Not Any')\n\t\t\t\t\tself.log.info('Status:- |... Similar feature treatment done: No similar features found')\n\t\t\telse:\n\t\t\t\tupdatedNumFeatures = numericalDataCols\n\t\t\t\tupdatedFeatures = list(set(columns) - set(constFeatures)-set(qconstantColumns))\n\t\t\t\tself.log.info( '\\\\n-----> Need minimum of two numerical features for data integration.')\n\t\t\t\tself.log.info('Status:- |... Similar feature treatment done: Found zero or 1 numeric feature')\n\t\t\tself.log.info('---------- Feature Reducer End ----------\\\\n')\n\n\t\t\treturn updatedNumFeatures,updatedFeatures,similarFeatureGroups\n\t\texcept Exception as inst:\n\t\t\tself.log.info(\"feature Reducer failed \"+str(inst))\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\treturn [],[]\n\t\t\t\n\tdef dataFramecolType(self,dataFrame):\n\t\tdataFDtypes=[]\n\t\ttry:\n\t\t\tdataColumns=list(dataFrame.columns)\n\t\t\tfor i in dataColumns:\n\t\t\t\tdataType=dataFrame[i].dtypes\n\t\t\t\tdataFDtypes.append(tuple([i,str(dataType)]))\n\t\t\treturn dataFDtypes\n\t\texcept:\n\t\t\tself.log.info(\"error in dataFramecolyType\")\n\t\t\treturn dataFDtypes\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\n\n#System imports\nimport os\nimport sys\nimport json\nimport datetime,time,timeit\nimport itertools\n\n#Sci-Tools imports\n\nimport numpy as np\nimport pandas as pd\nimport math\n\n\nfrom sklearn.metrics import normalized_mutual_info_score\nfrom sklearn.feature_selection import f_regression,mutual_info_regression\nfrom sklearn.feature_selection import chi2,f_classif,mutual_info_classif\n\nimport scipy.stats\nfrom scipy.stats import pearsonr, spearmanr, pointbiserialr, f_oneway, kendalltau, chi2_contingency\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\nimport logging\n\ndef getHigherSignificanceColName(featureDict, colname1, colname2):\n\t\tif featureDict[colname1] Change Target Type to Categorial as user defined')\n\t\t\t\n\t\t\tif problem_type.lower() == 'regression' and targetType == 'categorical':\n\t\t\t\ttargetType = 'continuous'\n\t\t\t\tself.log.info( '-------> Change Target Type to Continuous as user defined')\n\t\t\tself.log.info( '-------> Target Type: '+str(targetType))\n\t\t\t\n\t\t\timpFeatures=[]\n\t\t\t\n\t\t\t\n\t\t\tcatFeature = []\n\t\t\tnumFeature = []\n\t\t\t\n\t\t\tcatFeatureXYcat = []\n\t\t\tnumFeatureXYcat = []\n\t\t\tcatFeatureXYnum= []\n\t\t\tnumFeatureXYnum = []\n\t\t\t\n\t\t\tdropFeatureCat= []\n\t\t\tdropFeatureNum = []\n\t\t\t\n\t\t\tfeatureDict = {}\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\tif targetType ==\"categorical\":\n\t\t\t\t\n\t\t\t\tif len(categoricalFeatures) !=0:\n\t\t\t\t\t# input vs target\n\t\t\t\t\t# chi-square\n\t\t\t\t\tfor col in categoricalFeatures: \n\t\t\t\t\t\tcontingency = pd.crosstab(dataframe[col], targetData)\n\t\t\t\t\t\tstat, p, dof, expected = chi2_contingency(contingency)\n\t\t\t\t\t\tif p <= pValThTarget:\n\t\t\t\t\t\t\tcatFeatureXYcat.append(col)\t # categorical feature xy when target is cat\n\t\t\t\t\t\t\tfeatureDict[col] = p\n\t\t\t\t\t\n\t\t\t\t\t#input vs input \n\t\t\t\t\t# chi_square \n\t\t\t\t\tif len(catFeatureXYcat) != 0:\n\t\t\t\t\t\tlength = len(catFeatureXYcat)\n\t\t\t\t\t\tfor i in range(length):\n\t\t\t\t\t\t\tfor j in range(i+1, length):\n\t\t\t\t\t\t\t\tcontingency = pd.crosstab(dataframe[catFeatureXYcat[i]], dataframe[catFeatureXYcat[j]])\n\t\t\t\t\t\t\t\tstat, p, dof, expected = chi2_contingency(contingency)\n\t\t\t\t\t\t\t\tif p > pValThInput:\n\t\t\t\t\t\t\t\t\thighSignificanceColName = getHigherSignificanceColName(featureDict, catFeatureXYcat[i], catFeatureXYcat[j])\n\t\t\t\t\t\t\t\t\tdropFeatureCat.append(highSignificanceColName)\n\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\n\t\t\t\t\tcatFeature = list(set(catFeatureXYcat) - set(dropFeatureCat))\n\t\t\t\t\tfeatureDict.clear()\n\t\t\t\t\tdropFeatureCat.clear()\n\t\t\t\tif len(quantFeatures) !=0:\n\t\t\t\t\t# input vs target\n\t\t\t\t\t# one way anova\n\t\t\t\t\tfor col in quantFeatures:\n\t\t\t\t\t\tCategoryGroupLists = dataframe.groupby(target)[col].apply(list)\n\t\t\t\t\t\tAnovaResults = f_oneway(*CategoryGroupLists)\n\t\t\t\t\t\tif AnovaResults[1] <= pValThTarget:\n", "instruction": "", "output": "" }, { "input": "\t\t\t\t\t\t\tnumFeatureXYcat.append(col)\t\t #numeric feature xy when target is cat\n\t\t\t\t\t\t\tfeatureDict[col] = AnovaResults[1]\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t#input vs input \n\t\t\t\t\t# preason/spearman/ols\t\t\t\t # numeric feature xx when target is cat\n\t\t\t\t\tif len(numFeatureXYcat) != 0:\n\t\t\t\t\t\tdf_xx = dataframe[numFeatureXYcat]\n\t\t\t\t\t\trows, cols = df_xx.shape\n\t\t\t\t\t\tflds = list(df_xx.columns)\n\n\t\t\t\t\t\t\n\t\t\t\t\t\tcorr_pearson = df_xx.corr(method='pearson').values\n\t\t\t\t\t\tcorr_spearman = df_xx.corr(method='spearman').values\n\n\n\t\t\t\t\t\tfor i in range(cols):\n\t\t\t\t\t\t\tfor j in range(i+1, cols):\n\t\t\t\t\t\t\t\tif corr_pearson[i,j] > -corrThInput and corr_pearson[i,j] < corrThInput:\n\t\t\t\t\t\t\t\t\tif corr_spearman[i,j] > -corrThInput and corr_spearman[i,j] < corrThInput:\n\t\t\t\t\t\t\t\t\t\t#f = \"'\"+flds[i]+\"'\"+' ~ '+\"'\"+flds[j]+\"'\"\n\t\t\t\t\t\t\t\t\t\t#reg = smf.ols(formula=f, data=dataframe).fit() \n\t\t\t\t\t\t\t\t\t\ttmpdf = pd.DataFrame({'x':dataframe[flds[j]], 'y':dataframe[flds[i]]})\n\t\t\t\t\t\t\t\t\t\treg = smf.ols('y~x', data=tmpdf).fit()\n\t\t\t\t\t\t\t\t\t\tif len(reg.pvalues) > 1 and reg.pvalues[1] > pValThInput:\n\t\t\t\t\t\t\t\t\t\t\thighSignificanceColName = getHigherSignificanceColName(featureDict, flds[i], flds[j])\n\t\t\t\t\t\t\t\t\t\t\tdropFeatureNum.append(highSignificanceColName)\n\t\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\thighSignificanceColName = getHigherSignificanceColName(featureDict, flds[i], flds[j])\n\t\t\t\t\t\t\t\t\t\tdropFeatureNum.append(highSignificanceColName)\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\thighSignificanceColName = getHigherSignificanceColName(featureDict, flds[i], flds[j])\n\t\t\t\t\t\t\t\t\tdropFeatureNum.append(highSignificanceColName)\n\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\n\n\t\t\t\t\tnumFeature =\tlist(set(numFeatureXYcat) - set(dropFeatureNum))\t\t\n\t\t\t\t\tdropFeatureNum.clear()\n\t\t\t\t\tfeatureDict.clear()\n\t\t\t\t\n\t\t\t\timpFeatures = numFeature+catFeature\n\t\t\t\thCorrFeatures=list(set((impFeatures)))\n\t\t\t\t\n\t\t\t\t\n\t\t\telse: # targetType ==\"continuous\":\n\t\t\t\tif len(categoricalFeatures) !=0:\n\t\t\t\t\t# input vs target\n\t\t\t\t\t# Anova \n\t\t\t\t\tfor col in categoricalFeatures:\n\t\t\t\t\t\t#f = target+' ~ C('+col+')'\t\t\t\t\t\n\t\t\t\t\t\t#model = smf.ols(f, data=dataframe).fit()\n\t\t\t\t\t\t#table = sm.stats.anova_lm(model, typ=2)\n\t\t\t\t\t\ttmpdf = pd.DataFrame({'x':dataframe[col], 'y':dataframe[target]})\n\t\t\t\t\t\tmodel = smf.ols('y~x', data=tmpdf).fit()\n\t\t\t\t\t\ttable = sm.stats.anova_lm(model, typ=2)\n\t\t\t\t\t\tif table['PR(>F)'][0] <= pValThTarget:\n\t\t\t\t\t\t\tcatFeatureXYnum.append(col)\t\t\t\t\t #categorical feature xy when target is numeric\t\n\t\t\t\t\t\t\tfeatureDict[col]=table['PR(>F)'][0]\n\t\t\t\t\t#input vs input \n\t\t\t\t\t# chi_square\n\t\t\t\t\tif len(catFeatureXYnum) != 0:\n\t\t\t\t\t\tlength = len(catFeatureXYnum)\n\t\t\t\t\t\tfor i in range(length):\n\t\t\t\t\t\t\tfor j in range(i+1, length):\n\t\t\t\t\t\t\t\tcontingency = pd.crosstab(dataframe[catFeatureXYnum[i]], dataframe[catFeatureXYnum[j]])\n\t\t\t\t\t\t\t\tstat, p, dof, expected = chi2_contingency(contingency)\n\t\t\t\t\t\t\t\tif p > pValThInput:\n\t\t\t\t\t\t\t\t\thighSignificanceColName = getHigherSignificanceColName(featureDict, catFeatureXYnum[i], catFeatureXYnum[j])\n\t\t\t\t\t\t\t\t\tdropFeatureCat.append(highSignificanceColName)\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\tcatFeature = list(set(catFeatureXYnum) - set(dropFeatureCat))\n\t\t\t\t\tdropFeatureCat.clear()\n\t\t\t\t\tfeatureDict.clear()\n\t\t\t\tif len(quantFeatures) !=0:\n\t\t\t\t\t# input vs target\n\t\t\t\t\t# preason/spearman/ols\n\t\t\t\t\tfor col in quantFeatures:\n\t\t\t\t\t\tpearson_corr = pearsonr(dataframe[col], targetData)\n\t\t\t\t\t\tcoef = round(pearson_corr[0],5)\n\t\t\t\t\t\tp_value = round(pearson_corr[1],5)\n\t\t\t\t\t\tif coef > -corrThTarget and coef < corrThTarget:\n\t\t\t\t\t\t\tspearman_corr = spearmanr(dataframe[col], targetData)\n\t\t\t\t\t\t\tcoef = round(spearman_corr[0],5)\n\t\t\t\t\t\t\tp_value = round(spearman_corr[1],5)\n\t\t\t\t\t\t\tif coef > -corrThTarget and coef < corrThTarget:\n\t\t\t\t\t\t\t\t#f = target+' ~ '+col\n\t\t\t\t\t\t\t\t#reg = smf.ols(formula=f, data=dataframe).fit() \n\t\t\t\t\t\t\t\ttmpdf = pd.DataFrame({'x':dataframe[col], 'y':dataframe[target]})\n\t\t\t\t\t\t\t\treg = smf.ols('y~x', data=tmpdf).fit()\n\t\t\t\t\t\t\t\tif len(reg.pvalues) > 1 and reg.pvalues[1] <= pValThTarget:\n\t\t\t\t\t\t\t\t\tnumFeatureXYnum.append(col)\t\t # numeric feature xx when target is numeric\n\t\t\t\t\t\t\t\t\tfeatureDict[col]=reg.pvalues[1]\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tnumFeatureXYnum.append(col)\n\t\t\t\t\t\t\t\tfeatureDict[col]=p_value\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tnumFeatureXYnum.append(col) \n\t\t\t\t\t\t\tfeatureDict[col]=p_value\n\t\t\t\t\t#input vs input \n\t\t\t\t\t# preason/spearman/ols\n\t\t\t\t\tif len(numFeatureXYnum) != 0:\n\t\t\t\t\t\tdf_xx = dataframe[numFeatureXYnum]\n\t\t\t\t\t\trows, cols = df_xx.shape\n\t\t\t\t\t\tflds = list(df_xx.columns)\n\t\t\t\t\t\tcorr_pearson = df_xx.corr(method='pearson').values\n\t\t\t\t\t\tcorr_spearman = df_xx.corr(method='spearman').values\n\n\n\t\t\t\t\t\tfor i in range(cols):\n\t\t\t\t\t\t\tfor j in range(i+1, cols):\n\t\t\t\t\t\t\t\tif corr_pearson[i,j] > -corrThInput and corr_pearson[i,j] < corrThInput:\n\t\t\t\t\t\t\t\t\tif corr_spearman[i,j] > -corrThInput and corr_spearman[i,j] < corrThInput:\n\t\t\t\t\t\t\t\t\t\t#f = flds[i]+' ~ '+flds[j]\n\t\t\t\t\t\t\t\t\t\t#reg = smf.ols(formula=f, data=dataframe).fit() \n\t\t\t\t\t\t\t\t\t\ttmpdf = pd.DataFrame({'x':dataframe[flds[j]], 'y':dataframe[flds[i]]})\n\t\t\t\t\t\t\t\t\t\treg = smf.ols('y~x', data=tmpdf).fit()\n\n\t\t\t\t\t\t\t\t\t\tif len(reg.pvalues) > 1 and reg.pvalues[1] > pValThInput:\n\t\t\t\t\t\t\t\t\t\t\thighSignificanceColName = getHigherSignificanceColName(featureDict, flds[i], flds[j])\n\t\t\t\t\t\t\t\t\t\t\tdropFeatureNum.append(highSignificanceColName)\n\t\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\thighSignificanceColName = getHigherSignificanceColName(featureDict, flds[i], flds[j])\n\t\t\t\t\t\t\t\t\t\tdropFeatureNum.append(highSignificanceColName)\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\thighSignificanceColName = getHigherSignificanceColName(featureDict, flds[i], flds[j])\n\t\t\t\t\t\t\t\t\tdropFeatureNum.append(highSignificanceColName)\n\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\n\t\t\t\t\tnumFeature = list(set(numFeatureXYnum) - set(dropFeatureNum))\t\t\t\n\t\t\t\t\tfeatureDict.clear()\n\t\t\t\t\tdropFeatureNum.clear()\n\t\t\t\t\n\t\t\t\timpFeatures = numFeature+catFeature\n\t\t\t\thCorrFeatures=list(set(impFeatures))\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\treturn hCorrFeatures,targetType\n\t\texcept Exception as inst:\n\t\t\tself.log.info( '\\\\n--> Failed calculating feature importance '+str(inst))\n\t\t\thCorrFeatures=[]\n\t\t\ttargetType=''\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\tself.log.info('\\\\n--> Taking all the features as highest correlation features')\n\t\t\thCorrFeatures = list(dataframe.columns) \n\t\t\treturn hCorrFeatures,targetType\t\t\t\t\n\t\t\t\n\t\t\t\n\tdef FFImp(self,df,contFeatures,discreteFeatures,nonNumericFeatures,categoricalFeatures,dTypesDic,target,pValTh,corrTh,categoricalMaxLabel,problem_type,maxClasses):\n\t\t'''\n\t\tInput: dataframe, numeric continuous features, numeric discrete features\n\t\tOutput: feature importance dictionary\n\t\t'''\n\t\ttry:\n\t\t\tdataframe =df\n\t\t\tcontiFeatures= contFeatures\n\t\t\tdiscreteFeatures = discreteFeatures\n\t\t\tnonNumeric = nonNumericFeatures\n\t\t\tcategoricalFeatures=categoricalFeatures\n\t\t\tself.dTypesDic = dTypesDic\n\t\t\tnumericFeatures = contiFeatures + discreteFeatures+categoricalFeatures\n\t\t\tquantFeatures=discreteFeatures+contiFeatures\n\t\t\tscorrDict={}\n\t\t\tfScoreDict={}\n\t\t\tpcorrDict={}\n\t\t\tmiDict={}\n\t\t\ttargetData=dataframe[target]\n\t\t\tdata=dataframe[numericFeatures]\n\t\t\tnUnique=len(targetData.unique().tolist())\n\t\t\tnRows=targetData.shape[0]\n\t\t\t'''\n\t\t\tprint(\"\\\\n ===> nUnique :\")\n\t\t\tprint(nUnique)\n\t\t\tprint(\"\\\\n ===> nRows :\")\n\t\t\tprint(nRows)\n\t\t\tprint(\"\\\\n ===> cFRatio :\")\n\t\t\tprint(cFRatio)\n\t\t\tprint(\"\\\\n ===> nUnique/nRows :\")\n\t\t\t'''\n\t\t\t#calratio = nUnique\n\t\t\t\n\t\t\tself.log.info( '-------> Target Column Unique Stats: '+str(nUnique)+' nRows: '+str(nRows)+' Unique:'+str(nUnique))\n\t\t\t#sys.exit()\n\t\t\tif nUnique <= categoricalMaxLabel:\n\t\t\t\ttargetType=\"categorical\"\n\t\t\telse:\n\t\t\t\ttargetType=\"continuous\"\n\t\t\t\n\t\t\tif problem_type.lower() == 'classification' and targetType == 'continuous':\n\t\t\t\ttargetType = 'categorical'\n\t\t\t\tself.log.info( '-------> Change Target Type to Categorial as user defined')\n\t\t\t\n\t\t\tif problem_type.lower() == 'regression' and targetType == 'categorical':\n\t\t\t\ttargetType = 'continuous'\n\t\t\t\tself.log.info( '-------> Change Target Type to Continuous as user defined')\n\t\t\tself.log.info( '-------> Target Type: '+str(targetType))\n\t\t\timpFeatures=[]\n\t\t\tfeatureImpDict={}\n\t\t\tif targetType ==\"categorical\":\n\t\t\t\ttry:\n\t\t\t\t\tif len(categoricalFeatures) !=0:\n\t\t\t\t\t\tcategoricalData=dataframe[categoricalFeatures]\n\t\t\t\t\t\tchiSqCategorical=chi2(categoricalData,targetData)[1]\n\t\t\t\t\t\tcorrSeries=pd.Series(chiSqCategorical, index=categoricalFeatures)\n\t\t\t\t\t\timpFeatures.append(corrSeries[corrSeriescorrTh].index.tolist())\t\t\t\t\t\t\n\t\t\t\t\t\tfeatureImpDict['anovaPValue']=fClassSeries.to_dict()\n\t\t\t\t\t\tfeatureImpDict['MIScore']=miClassSeries.to_dict()\t\n\t\t\t\t\texcept MemoryError as inst:\n\t\t\t\t\t\tself.log.info( '-------> MemoryError in feature selection. '+str(inst))\n\t\t\t\t\t\t\n\t\t\t\tpearsonScore=dataframe.corr()\n\t\t\t\t\n\t\t\t\ttargetPScore=abs(pearsonScore[target])\n\t\t\t\timpFeatures.append(targetPScore[targetPScorecorrTh].index.tolist())\t\t\t\t\t\t\n\t\t\t\t\t\tfeatureImpDict['anovaPValue']=fregSeries.to_dict()\n\t\t\t\t\t\tfeatureImpDict['MIScore']=miregSeries.to_dict()\t\t\t\t\t\t\t\n\t\t\t\t\texcept MemoryError as inst:\n\t\t\t\t\t\tself.log.info( '-------> MemoryError in feature selection. '+str(inst))\n\t\t\t\t\n\t\t\t\tpearsonScore=dataframe.corr()\n\t\t\t\ttargetPScore=abs(pearsonScore[target])\n\t\t\t\timpFeatures.append(targetPScore[targetPScore Failed calculating feature importance '+str(inst))\n\t\t\thCorrFeatures=[]\n\t\t\ttargetType=''\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\n\t\t\treturn hCorrFeatures,targetType\n\n\t'''\n\tImportance degree\n\tComputes set of relational parameters\n\tpearson correlation, mutual information\n\t'''\n\tdef importanceDegree(self,dataframe,feature1,feature2):\n\t\ttry:\n\t\t\ttempList = []\n\t\t\t#Parameter 1: pearson correlation\n\t\t\tpcorr = self.pearsonCoff(dataframe,feature1,feature2)\n\t\t\ttempList.append(pcorr)\n\t\t\t#Parameter 2: mutual information\n\t\t\t#Testing\n\t\t\tmi = self.mutualInfo(dataframe,feature1,feature2,self.dTypesDic)\n\t\t\ttempList.append(mi)\n\t\t\t#return the highest parameter\n\t\t\treturn np.max(tempList)\n\t\texcept:\n\t\t\treturn 0.0\n\n\t'''\n\tCompute pearson correlation\n\t'''\n\tdef pearsonCoff(self,dataframe,feature1,feature2):\n\t\ttry:\n\t\t\tvalue=dataframe[feature1].corr(dataframe[feature2])\n\t\t\treturn np.abs(value)\n\t\texcept:\n\t\t\treturn 0.0\n\n\t'''\n\tCompute mutual information\n\t'''\n\tdef mutualInfo(self,dataframe,feature1,feature2,typeDic):\n\t\ttry:\n\t\t\tnumType = {'int64': 'discrete','int32' : 'discrete','int16' : 'discrete','float16' : 'continuous','float32' : 'continuous','float64' : 'continuous'}\n\t\t\tfeatureType1 = numType[typeDic[feature1]]\n\t\t\tfeatureType2 = numType[typeDic[feature2]]\n\t\t\tbufferList1=dataframe[feature1].values.tolist()\n\t\t\tbufferList2=dataframe[feature2].values.tolist()\n\t\t\t#Case 1: Only if both are discrete\n\t\t\tif(featureType1 == 'discrete' and featureType2 == 'discrete'):\n\t\t\t\ttempResult = discreteMI(bufferList1,bufferList2)\n\t\t\t\treturn np.mean(tempResult)\n\t\t\t#Case 2: If one of the features is continuous\n\t\t\telif(featureType1 == 'continuous' and featureType2 == 'discrete'):\n\t\t\t\ttempResult = self.categoricalMI(bufferList1,bufferList2)\n\t\t\t\treturn np.mean(tempResult)\n\t\t\telse:\n\t\t\t\ttempResult = self.continuousMI(bufferList1,bufferList2)\n\t\t\t\treturn np.mean(tempResult)\n\t\texcept:\n\t\t\treturn 0.0\n\n\t\n\tdef continuousMI(self,bufferList1,bufferList2):\n\t\tmi = 0.0\n\t\t#Using mutual info regression from feature selection\n\t\tmi = mutual_info_regression(self.vec(bufferList1),bufferList2)\n\t\treturn mi\n\t\t\n\tdef categoricalMI(self,bufferList1,bufferList2):\n\t\tmi = 0.0\n\t\t#Using mutual info classification from feature selection\n\t\tmi = mutual_info_classif(self.vec(bufferList1),bufferList2)\n\t\treturn mi\n\n\tdef discreteMI(self,bufferList1,bufferList2):\n\t\tmi = 0.0\n\t\t#Using scikit normalized mutual information function\n\t\tmi = normalized_mutual_info_score(bufferList1,bufferList2)\n\t\treturn mi\n\n\tdef vec(self,x):\n\t\treturn [[i] for i in x]\n\t\n\t\n\t\n\t\t\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n''' '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport sys\nimport json\nimport datetime,time,timeit\nimport itertools\n\n#Sci-Tools imports\n\nimport numpy as np\nimport pandas as pd\nimport math\nfrom statsmodels.tsa.stattools import adfuller\nfrom scipy.stats.stats import pearsonr\nfrom numpy import cumsum, log, polyfit, sqrt, std, subtract\nfrom numpy.random import randn\n\nfrom sklearn.metrics import normalized_mutual_info_score\nfrom sklearn.feature_selection import mutual_info_regression\nimport logging\n\n#SDP1 class import\nfrom feature_engineering.featureImportance import featureImp\nfrom feature_engineering.featureReducer import featureReducer\nfrom sklearn.linear_model import Lasso, LogisticRegression\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.decomposition import PCA\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.decomposition import FactorAnalysis\nfrom sklearn.decomposition import FastICA\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.feature_selection import RFE\n\ndef ranking(ranks, names, order=1):\n minmax = MinMaxScaler()\n ranks = minmax.fit_transform(order*np.array([ranks]).T).T[0]\n ranks = map(lambda x: round(x,2), ranks)\n return dict(zip(names, ranks))\n\n# noinspection PyPep8Naming\nclass featureSelector():\n\tdef __init__(self):\n\t\tself.pandasNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n\t\tself.log = logging.getLogger('eion')\n\t\t\n\tdef startSelector(self,df,conf_json,textFeatures,targetFeature,problem_type):\n\t\ttry:\n\t\t\tcategoricalMaxLabel = int(conf_json['categoryMaxLabel'])\t\t\n\t\t\tpca='None'\n\t\t\tpcaReducerStatus = conf_json['featureEngineering']['PCA']\n\t\t\tsvdReducerStatus = conf_json['featureEngineering']['SVD']\n\t\t\tfactorReducerStatus = conf_json['featureEngineering']['FactorAnalysis']\n\t\t\ticaReducerStatus = conf_json['featureEngineering']['ICA']\n\t\t\tnfeatures=float(conf_json['featureEngineering']['numberofComponents'])\n\t\t\tstatisticalConfig = conf_json['statisticalConfig']\n\t\t\tcorrThresholdInput = float(statisticalConfig.get('correlationThresholdFeatures',0.50))\n\t\t\tcorrThresholdTarget = float(statisticalConfig.get('correlationThresholdTarget',0.85))\n\t\t\tpValThresholdInput = float(statisticalConfig.get('pValueThresholdFeatures',0.05))\n\t\t\tpValThresholdTarget = float(statisticalConfig.get('pValueThresholdTarget',0.04))\n\t\t\tvarThreshold = float(statisticalConfig.get('varianceThreshold',0.01))\n\t\t\tallFeaturesSelector = conf_json['featureSelection']['allFeatures']\n\t\t\tcorrelationSelector = conf_json['featureSelection']['statisticalBased'] \n\t\t\tmodelSelector = conf_json['featureSelection']['modelBased']\n\t\t\tfeatureSelectionMethod = conf_json['selectionMethod']['featureSelection']\n\t\t\tfeatureEngineeringSelector = conf_json['selectionMethod']['featureEngineering'] \n\t\t\tif featureSelectionMethod == 'True':\n\t\t\t\tfeatureEngineeringSelector = 'False' \n\t\t\t\n\t\t\t# if feature engineering is true then we check weather PCA is true or svd is true. By default we will run PCA\n\t\t\tif featureEngineeringSelector == 'True':\n\t\t\t\tif pcaReducerStatus == 'True':\n\t\t\t\t\tsvdReducerStatus = 'False'\n\t\t\t\t\tfactorReducerStatus=='False'\n\t\t\t\t\ticaReducerStatus == 'False'\n\t\t\t\telif svdReducerStatus == 'True':\n\t\t\t\t\tpcaReducerStatus = 'False'\n\t\t\t\t\tfactorReducerStatus=='False'\n\t\t\t\t\ticaReducerStatus == 'False'\n\t\t\t\telif factorReducerStatus=='True':\n\t\t\t\t\tpcaReducerStatus=='False'\n\t\t\t\t\tsvdReducerStatus=='False'\n\t\t\t\t\ticaReducerStatus=='False'\n\t\t\t\telif icaReducerStatus=='True':\n\t\t\t\t\tpcaReducerStatus==\"False\"\n\t\t\t\t\tsvdReducerStatus==\"False\"\n\t\t\t\t\tfactorReducerStatus==\"False\"\n\t\t\t\telse:\n\t\t\t\t\tpcaReducerStatus = 'True'\n\t\t\tif featureSelectionMethod == 'False' and featureEngineeringSelector == 'False': \n\t\t\t\tfeatureSelectionMethod = 'True'\n\t\t\tif featureSelectionMethod == 'True':\n\t\t\t\tif modelSelector == 'False' and correlationSelector == 'False' and allFeaturesSelector == 'False':\n\t\t\t\t\tmodelSelector = 'True' \n\t\t\treductionMethod = 'na'\n\t\t\tbpca_features = []\n\t\t\t#nfeatures = 0\n\t\t\t\n\t\t\tif 'maxClasses' in conf_json:\n\t\t\t\tmaxclasses = int(conf_json['maxClasses'])\n\t\t\telse:\n\t\t\t\tmaxClasses = 20\n\t\t\ttarget = targetFeature\n\t\t\tself.log.info('-------> Feature: '+str(target))\n\t\t\tdataFrame = df\n\t\t\tpThresholdInput=pValThresholdInput\n\t\t\tpThresholdTarget=pValThresholdTarget\n\t\t\tcThresholdInput=corrThresholdInput\n\t\t\tcThresholdTarget=corrThresholdTarget\n\t\t\tnumericDiscreteFeatures=[]\n\t\t\tsimilarGruops=[]\n\t\t\tnumericContinuousFeatures=[]\n\t\t\tcategoricalFeatures=[]\n\t\t\tnonNumericFeatures=[]\n\t\t\tapca_features = []\n\t\t\tdTypesDic={}\n\t\t\tdataColumns = list(dataFrame.columns)\n\t\t\tfeatures_list = list(dataFrame.columns)\n\t\t\tmodelselectedFeatures=[]\n\t\t\ttopFeatures=[]\n\t\t\tallFeatures=[]\n\t\t\ttargetType=\"\"\n\t\t\t# just to make sure feature engineering is false\n\t\t\t#print(svdReducerStatus)\n\t\t\tif featureEngineeringSelector.lower() == 'false' and correlationSelector.lower() == \"true\" and len(textFeatures) <= 0:\n\t\t\t\treducerObj=featureReducer()\n\t\t\t\tself.log.info(featureReducer.__doc__)\n\t\t\t\tself.log.info('Status:- |... Feature reduction started')\n\t\t\t\tupdatedNumericFeatures,updatedFeatures,similarGruops=reducerObj.startReducer(dataFrame,dataColumns,target,varThreshold)\n\t\t\t\tif len(updatedFeatures) <= 1:\n\t\t\t\t\tself.log.info('=======================================================')\n\t\t\t\t\tself.log.info('Most of the features are of low variance. Use Model based feature engineering for better result')\n\t\t\t\t\tself.log.info('=======================================================')\n\t\t\t\t\traise Exception('Most of the features are of low variance. Use Model based feature engineering for better result')\n\t\t\t\tdataFrame=dataFrame[updatedFeatures]\n\t\t\t\tdataColumns=list(dataFrame.columns)\n\t\t\t\tself.log.info('Status:- |... Feature reduction completed')\n\t\t\telif (pcaReducerStatus.lower() == \"true\" or svdReducerStatus.lower() == 'true' or factorReducerStatus.lower() == 'true' or icaReducerStatus.lower()==", "instruction": "", "output": "" }, { "input": "'true') and featureEngineeringSelector.lower() == 'true':\n\t\t\t\t# check is PCA or SVD is true\n\t\t\t\tpcaColumns=[]\n\t\t\t\t#print(svdReducerStatus.lower())\n\t\t\t\tif target != \"\":\n\t\t\t\t\tdataColumns.remove(target)\n\t\t\t\t\ttargetArray=df[target].values\n\t\t\t\t\ttargetArray.shape = (len(targetArray), 1)\n\t\t\t\tif pcaReducerStatus.lower() == \"true\":\n\t\t\t\t\tif nfeatures == 0:\n\t\t\t\t\t\tpca = PCA(n_components='mle',svd_solver = 'full')\n\t\t\t\t\telif nfeatures < 1:\n\t\t\t\t\t\tpca = PCA(n_components=nfeatures,svd_solver = 'full')\n\t\t\t\t\telse:\n\t\t\t\t\t\tpca = PCA(n_components=int(nfeatures))\n\t\t\t\t\tpca.fit(df[dataColumns])\n\t\t\t\t\tbpca_features = dataColumns.copy()\n\t\t\t\t\tpcaArray=pca.transform(df[dataColumns])\n\t\t\t\t\tmethod = 'PCA'\n\t\t\t\telif svdReducerStatus.lower() == 'true':\n\t\t\t\t\tif nfeatures < 2:\n\t\t\t\t\t\tnfeatures = 2\n\t\t\t\t\tpca = TruncatedSVD(n_components=int(nfeatures), n_iter=7, random_state=42)\n\t\t\t\t\tpca.fit(df[dataColumns])\n\t\t\t\t\tbpca_features = dataColumns.copy()\n\t\t\t\t\tpcaArray=pca.transform(df[dataColumns])\n\t\t\t\t\tmethod = 'SVD'\n\t\t\t\telif factorReducerStatus.lower()=='true':\n\t\t\t\t\tif int(nfeatures) == 0:\n\t\t\t\t\t\tpca=FactorAnalysis()\n\t\t\t\t\telse: \n\t\t\t\t\t\tpca=FactorAnalysis(n_components=int(nfeatures))\n\t\t\t\t\tpca.fit(df[dataColumns])\n\t\t\t\t\tbpca_features = dataColumns.copy()\n\t\t\t\t\tpcaArray=pca.transform(df[dataColumns])\n\t\t\t\t\tmethod = 'FactorAnalysis'\n\t\t\t\telif icaReducerStatus.lower()=='true':\n\t\t\t\t\tif int(nfeatures) == 0:\n\t\t\t\t\t\tpca=FastICA()\n\t\t\t\t\telse: \n\t\t\t\t\t\tpca=FastICA(n_components=int(nfeatures))\n\t\t\t\t\tpca.fit(df[dataColumns])\n\t\t\t\t\tbpca_features = dataColumns.copy()\n\t\t\t\t\tpcaArray=pca.transform(df[dataColumns])\n\t\t\t\t\tmethod = 'IndependentComponentAnalysis'\n\t\t\t\tpcaDF=pd.DataFrame(pcaArray)\n\t\t\t\t#print(pcaDF)\n\t\t\t\tfor i in range(len(pcaDF.columns)):\n\t\t\t\t\tpcaColumns.append(method+str(i))\n\t\t\t\ttopFeatures=pcaColumns\n\t\t\t\tapca_features= pcaColumns.copy()\n\t\t\t\tif target != '':\n\t\t\t\t\tpcaColumns.append(target)\n\t\t\t\t\tscaledDf = pd.DataFrame(np.hstack((pcaArray, targetArray)),columns=pcaColumns)\n\t\t\t\telse:\n\t\t\t\t\tscaledDf = pd.DataFrame(pcaArray,columns=pcaColumns) \n\t\t\t\tself.log.info(\"<--- dataframe after dimensionality reduction using \"+method)\n\t\t\t\tself.log.info(scaledDf.head())\n\t\t\t\tdataFrame=scaledDf\n\t\t\t\tdataColumns=list(dataFrame.columns)\n\t\t\t\tself.log.info('Status:- |... Feature reduction started')\n\t\t\t\tself.log.info('Status:- |... '+method+' done')\t\n\t\t\t\tself.log.info('Status:- |... Feature reduction completed')\n\t\t\t\n\t\t\tself.numofCols = dataFrame.shape[1]\n\t\t\tself.numOfRows = dataFrame.shape[0]\n\t\t\t\t\n\t\t\tdataFDtypes=[]\n\t\t\tfor i in dataColumns:\n\t\t\t\tdataType=dataFrame[i].dtypes\n\t\t\t\tdataFDtypes.append(tuple([i,str(dataType)]))\n\t\t\t#Categoring datatypes\n\t\t\tfor item in dataFDtypes:\n\t\t\t\tdTypesDic[item[0]] = item[1]\n\t\t\t\tif item[0] != target:\n\t\t\t\t\tif item[1] in ['int16', 'int32', 'int64'] :\n\t\t\t\t\t\tnumericDiscreteFeatures.append(item[0])\n\t\t\t\t\telif item[1] in ['float16', 'float32', 'float64']:\n\t\t\t\t\t\tnumericContinuousFeatures.append(item[0])\n\t\t\t\t\telse:\n\t\t\t\t\t\tnonNumericFeatures.append(item[0])\n\t\t\tself.numOfRows = dataFrame.shape[0]\t\t\n\t\t\t''' \n\t\t\tcFRatio = 0.01\n\t\t\tif(self.numOfRows < 1000):\n\t\t\t\tcFRatio = 0.2\n\t\t\telif(self.numOfRows < 10000):\n\t\t\t\tcFRatio = 0.1\n\t\t\telif(self.numOfRows < 100000):\n\t\t\t\tcFRatio = 0.01 \n\t\t\t''' \n\t\t\tfor i in numericDiscreteFeatures:\n\t\t\t\tnUnique=len(dataFrame[i].unique().tolist())\n\t\t\t\tnRows=self.numOfRows\n\t\t\t\tif nUnique <= categoricalMaxLabel:\n\t\t\t\t\tcategoricalFeatures.append(i)\n\n\t\t\tfor i in numericContinuousFeatures:\n\t\t\t\tnUnique=len(dataFrame[i].unique().tolist())\n\t\t\t\tnRows=self.numOfRows\n\t\t\t\tif nUnique <= categoricalMaxLabel:\n\t\t\t\t\tcategoricalFeatures.append(i)\t\t\t\n\t\t\t\t\t\n\t\t\tdiscreteFeatures=list(set(numericDiscreteFeatures)-set(categoricalFeatures))\n\t\t\tnumericContinuousFeatures=list(set(numericContinuousFeatures)-set(categoricalFeatures))\n\t\t\tself.log.info('-------> Numerical continuous features :'+(str(numericContinuousFeatures))[:500])\n\t\t\tself.log.info('-------> Numerical discrete features :'+(str(discreteFeatures))[:500])\n\t\t\tself.log.info('-------> Non numerical features :'+(str(nonNumericFeatures))[:500])\n\t\t\tself.log.info('-------> Categorical Features :'+(str(categoricalFeatures))[:500])\n\t\t\t\n\t\t\tif target !=\"\" and featureEngineeringSelector.lower() == \"false\" and correlationSelector.lower() == \"true\":\n\t\t\t\tself.log.info('\\\\n------- Feature Based Correlation Analysis Start ------')\n\t\t\t\tstart = time.time()\n\t\t\t\tfeatureImpObj = featureImp()\n\t\t\t\ttopFeatures,targetType= featureImpObj.FFImpNew(dataFrame,numericContinuousFeatures,discreteFeatures,nonNumericFeatures,categoricalFeatures,dTypesDic,target,pThresholdInput,pThresholdTarget,cThresholdInput,cThresholdTarget,categoricalMaxLabel,problem_type,maxClasses)\n\t\t\t\t#topFeatures,targetType= featureImpObj.FFImp(dataFrame,numericContinuousFeatures,discreteFeatures,nonNumericFeatures,categoricalFeatures,dTypesDic,target,pThreshold,cThreshold,categoricalMaxLabel,problem_type,maxClasses)\n\t\t\t\tself.log.info('-------> Highly Correlated Features Using Correlation Techniques'+(str(topFeatures))[:500])\n\t\t\t\texecutionTime=time.time() - start\n\t\t\t\tself.log.info('-------> Time Taken: '+str(executionTime))\n\t\t\t\tself.log.info('Status:- |... Correlation based feature selection done: '+str(len(topFeatures))+' out of '+str(len(dataColumns))+' selected')\n\t\t\t\tself.log.info('------- Feature Based Correlation Analysis End ------>\\\\n')\n\t\t\tif targetType == '':\n\t\t\t\tif problem_type.lower() == 'classification':\n\t\t\t\t\ttargetType = 'categorical'\n\t\t\t\t\t\n\t\t\t\tif problem_type.lower() == 'regression':\n\t\t\t\t\ttargetType = 'continuous'\n\t\t\t\t\t\n \n\t\t\tif target !=\"\" and featureEngineeringSelector.lower() == \"false\" and modelSelector.lower() == \"true\":\n\t\t\t\tself.log.info('\\\\n------- Model Based Correlation Analysis Start -------')\n\t\t\t\tstart = time.time()\n\t\t\t\tupdatedFeatures = dataColumns\n\t\t\t\tupdatedFeatures.remove(target)\n\t\t\t\t#targetType = problem_type.lower() \n\t\t\t\tmodelselectedFeatures=[]\n\t\t\t\tif targetType == 'categorical':\n\t\t\t\t\ttry:\n\t\t\t\t\t\txtrain=dataFrame[updatedFeatures]\n\t\t\t\t\t\tytrain=dataFrame[target]\n\n\t\t\t\t\t\tetc = ExtraTreesClassifier(n_estimators=100)\n\n\t\t\t\t\t\tetc.fit(xtrain, ytrain)\n\t\t\t\t\t\trfe = RFE(etc, n_features_to_select=1, verbose =0 )\n\t\t\t\t\t\trfe.fit(xtrain, ytrain)\n\t\t\t\t\t\t# total list of features\n\t\t\t\t\t\tranks = {}\n\t\t\t\t\t\tranks[\"RFE_LR\"] = ranking(list(map(float, rfe.ranking_)), dataColumns, order=-1)\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor item in ranks[\"RFE_LR\"]:\n\t\t\t\t\t\t\tif ranks[\"RFE_LR\"][item]>0.30: #threshold as 30%\n\t\t\t\t\t\t\t\tmodelselectedFeatures.append(item)\n\t\t\t\t\t\tmodelselectedFeatures = list(modelselectedFeatures)\n\t\t\t\t\t\tself.log.info('-------> Highly Correlated Features Using Treeclassifier + RFE: '+(str(modelselectedFeatures))[:500])\t\t\t\t\t\t\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tself.log.info('---------------->'+str(e))\n\t\t\t\t\t\tselector = SelectFromModel(ExtraTreesClassifier())\n\t\t\t\t\t\txtrain=dataFrame[updatedFeatures]\n\t\t\t\t\t\tytrain=dataFrame[target]\n\t\t\t\t\t\tselector.fit(xtrain,ytrain)\n\t\t\t\t\t\tmodelselectedFeatures = xtrain.columns[(selector.get_support())].tolist()\n\t\t\t\t\t\tself.log.info('-------> Highly Correlated Features Using Treeclassifier: '+(str(modelselectedFeatures))[:500])\n\t\t\t\telse:\n\t\t\t\t\ttry:\n\t\t\t\t\t\txtrain=dataFrame[updatedFeatures]\n\t\t\t\t\t\tytrain=dataFrame[target]\n\t\t\t\t\t\tls = Lasso()\n\t\t\t\t\t\tls.fit(xtrain, ytrain)\n\t\t\t\t\t\trfe = RFE(ls, n_features_to_select=1, verbose = 0 )\n\t\t\t\t\t\trfe.fit(xtrain, ytrain)\n\t\t\t\t\t\t# total list of features\n\t\t\t\t\t\tranks = {}\n\t\t\t\t\t\tranks[\"RFE_LR\"] = ranking(list(map(float, rfe.ranking_)), dataColumns, order=-1)\n\n\t\t\t\t\t\tfor item in ranks[\"RFE_LR\"]:\n\t\t\t\t\t\t\tif ranks[\"RFE_LR\"][item]>0.30: #threshold as 30%\n\t\t\t\t\t\t\t\tmodelselectedFeatures.append(item)\n\t\t\t\t\t\tmodelselectedFeatures = list(modelselectedFeatures)\n\t\t\t\t\t\tself.log.info('-------> Highly Correlated Features Using LASSO + RFE: '+(str(modelselectedFeatures))[:500])\t\t\t\t\t\t\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tself.log.info('---------------->'+str(e))\n\t\t\t\t\t\tselector = SelectFromModel(Lasso())\n\t\t\t\t\t\txtrain=dataFrame[updatedFeatures]\n\t\t\t\t\t\tytrain=dataFrame[target]\n\t\t\t\t\t\tselector.fit(xtrain,ytrain)\n\t\t\t\t\t\tmodelselectedFeatures = xtrain.columns[(selector.get_support())].tolist()\n\t\t\t\t\t\tself.log.info('-------> Highly Correlated Features Using LASSO: '+(str(modelselectedFeatures))[:500])\n\t\t\t\texecutionTime=time.time() - start\n\t\t\t\tself.log.info('-------> Time Taken: '+str(executionTime))\n\t\t\t\tself.log.info('Status:- |... Model based feature selection done: '+str(len(modelselectedFeatures))+' out of '+str(len(dataColumns))+' selected')\n\t\t\t\tself.log.info('--------- Model Based Correlation Analysis End -----\\\\n')\n \n\t\t\tif target !=\"\" and featureEngineeringSelector.lower() == \"false\" and allFeaturesSelector.lower() == \"true\":\n\t\t\t\tallFeatures = features_list\t\n\t\t\t\tif target != '':\n\t\t\t\t\tallFeatures.remove(target) \n\t\t\t\t#print(allFeatures)\n\t\t\tif len(topFeatures) == 0 and len(modelselectedFeatures) == 0 and len(allFeatures) == 0:\n\t\t\t\tallFeatures = features_list \n \n\t\t\treturn dataFrame,target,topFeatures,modelselectedFeatures,allFeatures,targetType,similarGruops,numericContinuousFeatures,discreteFeatures,nonNumericFeatures,categoricalFeatures,pca,bpca_features,apca_features,featureEngineeringSelector\n\t\texcept Exception as inst:\n\t\t\tself.log.info('Feature selector failed: '+str(inst))\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\n\t\t\t\n\t\t\t\n\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n''' \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property", "instruction": "", "output": "" }, { "input": "of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\" \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\nimport json\n\nclass transformer():\n \n def __init__(self, indent=0, tab_size=4):\n self.df_name = 'df'\n self.tab = ' ' * tab_size\n self.codeText = \"\"\n self.transformers = []\n self.TxCols = []\n self.imputers = {}\n self.input_files = {}\n self.output_files = {}\n self.function_code = ''\n self.addInputFiles({'inputData' : 'rawData.dat', 'metaData' : 'modelMetaData.json','log' : 'aion.log','trainData' : 'transformedData.dat','testData' : 'test.dat','preprocessor' : 'preprocessor.pkl'})\n \n def addInputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def addOutputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def getInputFiles(self): \n text = 'IOFiles = '\n if not self.input_files:\n text += '{ }'\n else:\n text += json.dumps(self.input_files, indent=4)\n return text\n \n def getOutputFiles(self):\n text = 'output_file = '\n if not self.output_files:\n text += '{ }'\n else:\n text += json.dumps(self.output_files, indent=4)\n return text\n \n def getInputOutputFiles(self, indent=0):\n text = '\\\\n'\n text += self.getInputFiles()\n if indent:\n text = text.replace('\\\\n', self.tab * indent + '\\\\n')\n return text\n \n def __addValidateConfigCode(self):\n text = \"\\\\n\\\\\n \\\\ndef validateConfig():\\\\\n \\\\n config_file = Path(__file__).parent/'config.json'\\\\\n \\\\n if not Path(config_file).exists():\\\\\n \\\\n raise ValueError(f'Config file is missing: {config_file}')\\\\\n \\\\n config = read_json(config_file)\\\\\n \\\\n return config\"\n return text\n\n def getPrefixModules(self):\n modules = [\n {'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'pandas', 'mod_as':'pd'}\n ,{'module':'numpy', 'mod_as':'np'}\n ,{'module':'scipy'}\n ]\n return modules\n \n def addPrefixCode(self, indent=1):\n self.codeText += \"\"\"\ndef transformation(log):\n config = validateConfig() \n targetPath = Path('aion')/config['targetPath'] \n if not targetPath.exists(): \n raise ValueError(f'targetPath does not exist') \n meta_data_file = targetPath/IOFiles['metaData'] \n if meta_data_file.exists(): \n meta_data = read_json(meta_data_file) \n else: \n raise ValueError(f'Configuration file not found: {meta_data_file}') \n log_file = targetPath/IOFiles['log'] \n log = logger(log_file, mode='a', logger_name=Path(__file__).parent.stem) \n dataLoc = targetPath/IOFiles['inputData'] \n if not dataLoc.exists(): \n return {'Status':'Failure','Message':'Data location does not exists.'} \n status = dict() \n df = read_data(dataLoc) \n log.log_dataframe(df) \n target_feature = config['target_feature']\n if config['test_ratio'] == 0.0:\n train_data = df\n test_data = pd.DataFrame()\n else:\n \"\"\"\n def getSuffixModules(self):\n modules = [{'module':'pandas','mod_as':'pd'}\n ,{'module':'json'}\n ,{'module':'joblib'}\n ]\n return modules\n \n def addSuffixCode(self,encoder=False, indent=1):\n self.codeText += \"\"\"\n train_data, preprocess_pipe, label_encoder = profilerObj.transform()\n if not preprocess_pipe:\n raise ValueError('Pipeline not created')\n joblib.dump(preprocess_pipe, targetPath/IOFiles['preprocessor'])\n test_data.reset_index(inplace=True) \n\n \"\"\"\n if encoder:\n self.codeText += \"\"\"\n joblib.dump(label_encoder, targetPath/IOFiles['targetEncoder'])\n if not test_data.empty:\n ytest = label_encoder.transform(test_data[target_feature])\n \"\"\"\n else:\n self.codeText += \"\"\"\n if not test_data.empty:\n ytest = test_data[target_feature]\n \"\"\"\n self.codeText += \"\"\"\n test_data.astype(profilerObj.train_features_type)\n test_data = preprocess_pipe.transform(test_data)\n if isinstance(test_data, scipy.sparse.spmatrix):\n test_data = test_data.toarray()\n preprocess_out_columns = train_data.columns.tolist()\n preprocess_out_columns.remove(target_feature)\n write_data(train_data,targetPath/IOFiles['trainData'],index=False)\n if isinstance( test_data, np.ndarray):\n test_data = pd.DataFrame(test_data, columns=preprocess_out_columns)\n test_data[target_feature] = ytest\n \n write_data(test_data,targetPath/IOFiles['testData'],index=False)\n \n log.log_dataframe(train_data) \n status = {'Status':'Success','trainData':IOFiles['trainData'],'testData':IOFiles['testData']} \n meta_data['transformation'] = {}\n meta_data['transformation']['cat_features'] = train_data.select_dtypes('category').columns.tolist()\n meta_data['transformation']['preprocessor'] = IOFiles['preprocessor']\n meta_data['transformation']['preprocess_out_columns'] = preprocess_out_columns\n \"\"\"\n if encoder:\n self.codeText += \"\"\"\n meta_data['transformation']['target_encoder'] = IOFiles['targetEncoder']\n \"\"\"\n self.codeText += \"\"\"\n meta_data['transformation']['Status'] = status \n write_json(meta_data, str(targetPath/IOFiles['metaData'])) \n log.info(f\"Transformed data saved at {targetPath/IOFiles['trainData']}\") \n log.info(f'output: {status}') \n return json.dumps(status)\n \"\"\"\n def getMainCodeModules(self):\n modules = [{'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'sys'}\n ,{'module':'json'}\n ,{'module':'logging'}\n ,{'module':'argparse'}\n ]\n return modules\n \n def addMainCode(self, indent=1):\n self.codeText += \"\\\\n\\\\\n \\\\nif __name__ == '__main__':\\\\\n \\\\n log = None\\\\\n \\\\n try:\\\\\n \\\\n print(transformation(log))\\\\\n \\\\n except Exception as e:\\\\\n \\\\n if log:\\\\\n \\\\n log.error(e, exc_info=True)\\\\\n \\\\n status = {'Status':'Failure','Message':str(e)}\\\\\n \\\\n print(json.dumps(status))\"\n \n def addValidateConfigCode(self, indent=1):\n self.function_code += self.__addValidateConfigCode()\n\n def addLocalFunctionsCode(self):\n self.addValidateConfigCode()\n\n def addStatement(self, statement, indent=1):\n self.codeText += '\\\\n' + self.tab * indent + statement\n\n def getCode(self, indent=1):\n return self.function_code + '\\\\n' + self.codeText\n \n def getDFName(self):\n return self.df_name\n\nclass data_profiler():\n\n def __init__(self, importer, text_features=False):\n self.importer = importer\n self.codeText = \"\"\n self.text_features = text_features\n \n def addStatement(self, statement, indent=1):\n self.codeText += '\\\\n' + self.tab * indent + statement\n\n def get_module_import_statement(self, mod):\n text = \"\"\n if not mod.get('module', None):\n return text\n if mod.get('mod_from', None):\n text += f\"from {mod['mod_from']} \"\n text += f\"import {mod['module']} \"\n if mod.get('mod_as', None):\n text += f\"as {mod['mod_as']}\"\n text += \"\\\\n\"\n return text\n \n def get_import_modules(self):\n profiler_importes = [\n {'module': 'scipy', 'mod_from': None, 'mod_as': None},\n {'module': 'numpy', 'mod_from': None, 'mod_as': 'np'},\n {'module': 'Path', 'mod_from': 'pathlib', 'mod_as': None},\n {'module': 'pandas', 'mod_from': None, 'mod_as': 'pd'},\n {'module': 'w2n', 'mod_from': 'word2number', 'mod_as': None},\n {'module': 'LabelEncoder', 'mod_from': 'sklearn.preprocessing', 'mod_as': None },\n {'module': 'OrdinalEncoder', 'mod_from': 'sklearn.preprocessing', 'mod_as': None },\n {'module': 'OneHotEncoder', 'mod_from': 'sklearn.preprocessing', 'mod_as': None },\n {'module': 'SimpleImputer', 'mod_from': 'sklearn.impute', 'mod_as': None },\n {'module': 'KNNImputer', 'mod_from': 'sklearn.impute', 'mod_as': None },\n {'module': 'Pipeline', 'mod_from': 'sklearn.pipeline', 'mod_as': None },\n {'module': 'FeatureUnion', 'mod_from': 'sklearn.pipeline', 'mod_as': None },\n {'module': 'MinMaxScaler', 'mod_from': 'sklearn.preprocessing', 'mod_as': None },\n {'module': 'StandardScaler', 'mod_from': 'sklearn.preprocessing', 'mod_as': None },\n {'module': 'PowerTransformer', 'mod_from': 'sklearn.preprocessing', 'mod_as': None },\n {'module': 'ColumnTransformer', 'mod_from': 'sklearn.compose', 'mod_as': None },\n {'module': 'TransformerMixin', 'mod_from': 'sklearn.base', 'mod_as': None },\n {'module': 'IsolationForest', 'mod_from': 'sklearn.ensemble', 'mod_as': None },\n {'module': 'TargetEncoder', 'mod_from': 'category_encoders', 'mod_as': None }\n ]\n if self.text_features:\n profiler_importes.append({'module': 'textProfiler', 'mod_from': 'text.textProfiler', 'mod_as': None })\n profiler_importes.append({'module': 'textCombine', 'mod_from': 'text.textProfiler', 'mod_as': None })\n return profiler_importes\n \n def get_importer(self):\n return self.importer\n \n def get_code(self):\n common_importes = self.get_import_modules()\n for module in common_importes:\n mod_name = module['module']\n mod_from = module.get('mod_from', None)\n mod_as = module.get('mod_as', None)\n if module['module'] in ['textProfiler','textCombine']:\n self.importer.addLocalModule(mod_name, mod_from=mod_from, mod_as=mod_as)\n else:\n self.importer.addModule(mod_name, mod_from=mod_from, mod_as=mod_as)\n\n self.codeText += \"\"\"\nSTR_TO_CAT_CONVERSION_LEN_MAX = 10\nlog_suffix = f'[{Path(__file__).stem}] '\n\ntarget_encoding_method_change = {'targetencoding': 'labelencoding'}\n\nsupported_method = {\n 'fillNa':\n {\n 'categorical' : ['mode','zero','na'],\n 'numeric' : ['median','mean','knnimputer','zero','drop','na'],\n },\n 'categoryEncoding': ['labelencoding','targetencoding','onehotencoding','na','none'],\n 'normalization': ['standardscaler','minmax','lognormal', 'na','none'],\n 'outlier_column_wise': ['iqr','zscore', 'disable'],\n 'outlierOperation': ['dropdata', 'average', 'nochange']\n }\n \ndef findiqrOutlier(df):\n Q1 = df.quantile(0.25)\n Q3 = df.quantile(0.75)\n IQR = Q3 - Q1\n index = ~((df < (Q1 - 1.5 * IQR)) |(df > (Q3 + 1.5 * IQR)))\n return index\n \ndef findzscoreOutlier(df):\n z = np.abs(scipy.stats.zscore(df))\n index = (z < 3)\n return index\n \ndef findiforestOutlier(df):\n isolation_forest = IsolationForest(n_estimators=100)\n isolation_forest.fit(df)\n y_pred_train = isolation_forest.predict(df)\n return y_pred_train == 1\n\ndef get_one_true_option(d, default_value=None):\n\tif isinstance(d, dict):\n\t\tfor k,v in d.items():\n\t\t\tif (isinstance(v, str) and v.lower() == 'true') or (isinstance(v, bool) and v == True):\n\t\t\t\treturn k\n\treturn default_value\n\ndef get_boolean(value):\n if (isinstance(value, str) and value.lower() == 'true') or (isinstance(value, bool) and value == True):\n return True\n else:\n return False\n \nclass profiler():\n\n def __init__(self, xtrain, ytrain=None, target=None, encode_target = True, config={}, keep_unprocessed=[], log=None):\n if not isinstance(xtrain, pd.DataFrame):\n raise ValueError(f'{log_su", "instruction": "", "output": "" }, { "input": "ffix}supported data type is pandas.DataFrame but provide data is of {type(xtrain)} type')\n if xtrain.empty:\n raise ValueError(f'{log_suffix}Data frame is empty')\n if target and target in xtrain.columns:\n self.target = xtrain[target]\n xtrain.drop(target, axis=1, inplace=True)\n self.target_name = target\n elif ytrain:\n self.target = ytrain\n self.target_name = 'target'\n else:\n self.target = pd.Series()\n self.target_name = None\n self.encode_target = encode_target\n self.label_encoder = None\n keep_unprocessed = [x for x in keep_unprocessed if x in xtrain.columns]\n if keep_unprocessed:\n self.unprocessed = xtrain[keep_unprocessed]\n self.data = xtrain.drop(keep_unprocessed, axis=1)\n else:\n self.data = xtrain \n self.unprocessed = pd.DataFrame()\n self.colm_type = {}\n for colm, infer_type in zip(self.data.columns, self.data.dtypes):\n self.colm_type[colm] = infer_type\n self.numeric_feature = []\n self.cat_feature = []\n self.text_feature = []\n self.wordToNumericFeatures = []\n self.added_features = []\n self.pipeline = []\n self.dropped_features = {}\n self.train_features_type={}\n self.__update_type()\n self.config = config\n self.featureDict = config.get('featureDict', [])\n self.output_columns = []\n self.feature_expender = []\n self.text_to_num = {}\n if log:\n self.log = log\n else:\n self.log = logging.getLogger('eion')\n self.type_conversion = {}\n\n def log_dataframe(self, msg=None): \n import io \n buffer = io.StringIO() \n self.data.info(buf=buffer) \n if msg: \n log_text = f'Data frame after {msg}:' \n else: \n log_text = 'Data frame:' \n log_text += '\\\\\\\\n\\\\\\\\t'+str(self.data.head(2)).replace('\\\\\\\\n','\\\\\\\\n\\\\\\\\t') \n log_text += ('\\\\\\\\n\\\\\\\\t' + buffer.getvalue().replace('\\\\\\\\n','\\\\\\\\n\\\\\\\\t')) \n self.log.info(log_text)\n\n def transform(self):\n if self.is_target_available():\n if self.target_name:\n self.log.info(f\"Target feature name: '{self.target_name}'\")\n self.log.info(f\"Target feature size: {len(self.target)}\")\n else:\n self.log.info(f\"Target feature not present\")\n self.log_dataframe()\n try:\n self.process()\n except Exception as e: \n self.log.error(e, exc_info=True)\n raise\n pipe = FeatureUnion(self.pipeline)\n self.log.info(pipe)\n process_data = pipe.fit_transform(self.data, y=self.target)\n self.update_output_features_names(pipe)\n if isinstance(process_data, scipy.sparse.spmatrix):\n process_data = process_data.toarray() \n df = pd.DataFrame(process_data, columns=self.output_columns)\n \n if self.is_target_available() and self.target_name:\n df[self.target_name] = self.target\n if not self.unprocessed.empty:\n df[self.unprocessed.columns] = self.unprocessed\n self.log_numerical_fill()\n self.log_categorical_fill()\n self.log_normalization()\n return df, pipe, self.label_encoder\n \n def log_type_conversion(self):\n if self.log:\n self.log.info('----------- Inspecting Features -----------')\n self.log.info('----------- Type Conversion -----------')\n count = 0\n for k, v in self.type_conversion.items():\n if v[0] != v[1]:\n self.log.info(f'{k} -> from {v[0]} to {v[1]} : {v[2]}')\n self.log.info('Status:- |... Feature inspection done')\n \n def check_config(self):\n removeDuplicate = self.config.get('removeDuplicate', False)\n self.config['removeDuplicate'] = get_boolean(removeDuplicate)\n self.config['misValueRatio'] = float(self.config.get('misValueRatio', '1.0'))\n self.config['numericFeatureRatio'] = float(self.config.get('numericFeatureRatio', '1.0'))\n self.config['categoryMaxLabel'] = int(self.config.get('categoryMaxLabel', '20'))\n featureDict = self.config.get('featureDict', [])\n if isinstance(featureDict, dict):\n self.config['featureDict'] = []\n if isinstance(featureDict, str):\n self.config['featureDict'] = []\n \n def process(self):\n #remove duplicate not required at the time of prediction\n self.check_config()\n self.remove_constant_feature()\n self.remove_empty_feature(self.config['misValueRatio'])\n self.remove_index_features()\n self.drop_na_target()\n if self.config['removeDuplicate']:\n self.drop_duplicate()\n self.check_categorical_features()\n self.string_to_numeric()\n self.process_target()\n self.train_features_type = dict(zip(self.data.columns, self.data.dtypes))\n self.parse_process_step_config()\n self.process_drop_fillna()\n #self.log_type_conversion()\n self.update_num_fill_dict()\n #print(self.num_fill_method_dict)\n self.update_cat_fill_dict()\n self.create_pipeline()\n self.text_pipeline(self.config)\n self.apply_outlier()\n self.log.info(self.process_method)\n self.log.info(self.train_features_type)\n \n def is_target_available(self):\n return (isinstance(self.target, pd.Series) and not self.target.empty) or len(self.target)\n \n def process_target(self, operation='encode', arg=None):\n if self.encode_target:\n if self.is_target_available():\n self.label_encoder = LabelEncoder()\n self.target = self.label_encoder.fit_transform(self.target)\n return self.label_encoder\n return None\n \n def is_target_column(self, column):\n return column == self.target_name\n \n def fill_default_steps(self):\n \n num_fill_method = get_one_true_option(self.config.get('numericalFillMethod',None))\n normalization_method = get_one_true_option(self.config.get('normalization',None))\n for colm in self.numeric_feature:\n if num_fill_method:\n self.fill_missing_value_method(colm, num_fill_method.lower())\n if normalization_method:\n self.fill_normalizer_method(colm, normalization_method.lower())\n \n cat_fill_method = get_one_true_option(self.config.get('categoricalFillMethod',None))\n cat_encode_method = get_one_true_option(self.config.get('categoryEncoding',None))\n for colm in self.cat_feature:\n if cat_fill_method:\n self.fill_missing_value_method(colm, cat_fill_method.lower())\n if cat_encode_method:\n self.fill_encoder_value_method(colm, cat_encode_method.lower(), default=True)\n \n def parse_process_step_config(self):\n self.process_method = {}\n user_provided_data_type = {}\n for feat_conf in self.featureDict:\n colm = feat_conf.get('feature', '')\n if not self.is_target_column(colm):\n if colm in self.data.columns:\n user_provided_data_type[colm] = feat_conf['type']\n if user_provided_data_type:\n self.update_user_provided_type(user_provided_data_type)\n \n self.fill_default_steps()\n for feat_conf in self.featureDict:\n colm = feat_conf.get('feature', '')\n if not self.is_target_column(colm):\n if colm in self.data.columns:\n if feat_conf.get('fillMethod', None):\n self.fill_missing_value_method(colm, feat_conf['fillMethod'].lower())\n if feat_conf.get('categoryEncoding', None):\n self.fill_encoder_value_method(colm, feat_conf['categoryEncoding'].lower())\n if feat_conf.get('normalization', None):\n self.fill_normalizer_method(colm, feat_conf['normalization'].lower())\n if feat_conf.get('outlier', None):\n self.fill_outlier_method(colm, feat_conf['outlier'].lower())\n if feat_conf.get('outlierOperation', None):\n self.fill_outlier_process(colm, feat_conf['outlierOperation'].lower())\n \n \n def update_output_features_names(self, pipe):\n columns = self.output_columns\n start_index = {}\n for feat_expender in self.feature_expender:\n if feat_expender:\n step_name = list(feat_expender.keys())[0]\n index = list(feat_expender.values())[0]\n for transformer_step in pipe.transformer_list:\n if transformer_step[1].steps[-1][0] in step_name:\n start_index[index] = {transformer_step[1].steps[-1][0]: transformer_step[1].steps[-1][1].get_feature_names()}\n if start_index:\n index_shifter = 0\n for key,value in start_index.items():\n for k,v in value.items():\n if k == 'vectorizer':\n v = [f'{x}_vect' for x in v] \n key = key + index_shifter\n self.output_columns[key:key] = v\n index_shifter += len(v)\n self.added_features = [*self.added_features, *v]\n \n \n def text_pipeline(self, conf_json):\n if self.text_feature:\n pipeList = []\n max_features = 2000\n text_pipe = Pipeline([ \n ('selector', ColumnTransformer([\n (\"selector\", \"passthrough\", self.text_feature)\n ], remainder=\"drop\")),\n (\"text_fillNa\",SimpleImputer(strategy='constant', fill_value='')),\n (\"merge_text_feature\", textCombine())])\n obj = textProfiler()\n pipeList = obj.textProfiler(conf_json, pipeList, max_features)\n last_step = \"merge_text_feature\"\n for pipe_elem in pipeList:\n text_pipe.steps.append((pipe_elem[0], pipe_elem[1]))\n last_step = pipe_elem[0]\n text_transformer = ('text_process', text_pipe)\n self.pipeline.append(text_transformer)\n self.feature_expender.append({last_step:len(self.output_columns)})\n \n def create_pipeline(self):\n num_pipe = {}\n for k,v in self.num_fill_method_dict.items():\n for k1,v1 in v.items():\n if k1 and k1 != 'none':\n num_pipe[f'{k}_{k1}'] = Pipeline([\n ('selector', ColumnTransformer([\n (\"selector\", \"passthrough\", v1)\n ], remainder=\"drop\")),\n (k, self.get_num_imputer(k)),\n (k1, self.get_num_scaler(k1))\n ])\n else:\n num_pipe[f'{k}_{k1}'] = Pipeline([\n ('selector', ColumnTransformer([\n (\"selector\", \"passthrough\", v1)\n ], remainder=\"drop\")),\n (k, self.get_num_imputer(k))\n ])\n self.output_columns.extend(v1)\n cat_pipe = {}\n for k,v in self.cat_fill_method_dict.items():\n for k1,v1 in v.items():\n cat_pipe[f'{k}_{k1}'] = Pipeline([\n ('selector', ColumnTransformer([\n (\"selector\", \"passthrough\", v1)\n ], remainder=\"drop\")),\n (k, self.get_cat_imputer(k)),\n (k1, self.get_cat_encoder(k1))\n ])\n if k1 not in ['onehotencoding']:\n self.output_columns.extend(v1)\n else:\n self.feature_expender.append({k1:len(self.output_columns)})\n for key, pipe in num_pipe.items(): \n self.pipeline.append((key, pipe))\n for key, pipe in cat_pipe.items(): \n self.pipeline.append((key, pipe))\n if not self.unprocessed.empty:\n self.pipeline.append(Pipeline([\n ('selector', ColumnTransformer([\n (\"selector\", \"passthrough\", self.unprocessed.columns)\n ], remainder=\"drop\"))]))\n\n \"Drop: feature during training but replace with zero during prediction \"\n def process_drop_fillna(self):\n drop_column = []\n if 'numFill' in self.process_method.keys():\n for col, method in self.process_method['numFill'].items():\n if method == 'drop':\n self.process_method['numFill'][col] = 'zero'\n drop_column.append(col)\n if 'catFill' in self.process_method.keys():\n for col, method in self.process_method['catFill'].items():\n if method == 'drop':\n self.process_method['catFill'][col] = 'zero'\n drop_column.append(col)\n if drop_column:\n self.data.dropna(subset=drop_column, inplace=True)\n\n def update_num_fill_dict(self):\n self.num_fill_method_dict = {}\n if 'numFill' in self.process_method.keys():\n for f in supported_method['fillNa']['numeric']:\n self.num_fill_method_dict[f] = {}\n for en in supported_method['normalization']:\n self.num_fill_method_dict[f][en] = []\n for col in self.numeric_feature:\n numFillDict = self.process_method.get('numFill',{})\n normalizationDict = self.process_method.get('normalization',{})\n if f == numFillDict.get(col, '') and en == normalizationDict.get(col,''):\n self.num_fill_method_dict[f][en].append(col)\n if not self.num_fill_method_dict[f][en] :\n del self", "instruction": "", "output": "" }, { "input": ".num_fill_method_dict[f][en]\n if not self.num_fill_method_dict[f]:\n del self.num_fill_method_dict[f]\n\n def update_cat_fill_dict(self):\n self.cat_fill_method_dict = {}\n if 'catFill' in self.process_method.keys():\n for f in supported_method['fillNa']['categorical']:\n self.cat_fill_method_dict[f] = {}\n for en in supported_method['categoryEncoding']:\n self.cat_fill_method_dict[f][en] = []\n for col in self.cat_feature:\n catFillDict = self.process_method.get('catFill',{})\n catEncoderDict = self.process_method.get('catEncoder',{})\n if f == catFillDict.get(col, '') and en == catEncoderDict.get(col,''):\n self.cat_fill_method_dict[f][en].append(col)\n if not self.cat_fill_method_dict[f][en] :\n del self.cat_fill_method_dict[f][en]\n if not self.cat_fill_method_dict[f]:\n del self.cat_fill_method_dict[f]\n\n\n def __update_type(self):\n self.numeric_feature = self.data.select_dtypes(include='number').columns.tolist()\n self.cat_feature = self.data.select_dtypes(include='category').columns.tolist()\n self.date_time = self.data.select_dtypes(include='datetime').columns.tolist()\n self.text_feature = self.data.select_dtypes(include='object').columns.tolist()\n \n def update_user_provided_type(self, data_types):\n allowed_types = ['numerical','categorical', 'text','date','index']\n type_mapping = {'numerical': np.dtype('float'), 'float': np.dtype('float'),'categorical': 'category', 'text':np.dtype('object'),'date':'datetime64[ns]','index': np.dtype('int64'),}\n mapped_type = {k:type_mapping[v] for k,v in data_types.items()}\n #self.log.info(mapped_type)\n self.update_type(mapped_type, 'user provided data type')\n \n def get_type(self, as_list=False):\n if as_list:\n return [self.colm_type.values()]\n else:\n return self.colm_type\n \n def update_type(self, data_types={}, reason=''):\n invalid_features = [x for x in data_types.keys() if x not in self.data.columns]\n if invalid_features:\n valid_feat = list(set(data_types.keys()) - set(invalid_features))\n valid_feat_type = {k:v for k,v in data_types if k in valid_feat}\n else:\n valid_feat_type = data_types\n for k,v in valid_feat_type.items():\n if v != self.colm_type[k].name:\n try:\n self.data.astype({k:v})\n self.colm_type.update({k:self.data[k].dtype})\n self.type_conversion[k] = (self.colm_type[k] , v, 'Done', reason)\n except:\n self.type_conversion[k] = (self.colm_type[k] , v, 'Fail', reason)\n self.data = self.data.astype(valid_feat_type)\n self.__update_type()\n \n def string_to_numeric(self):\n def to_number(x):\n try:\n return w2n.word_to_num(x)\n except:\n return np.nan\n for col in self.text_feature:\n col_values = self.data[col].copy()\n col_values = pd.to_numeric(col_values, errors='coerce')\n if col_values.count() >= (self.config['numericFeatureRatio'] * len(col_values)):\n self.text_to_num[col] = 'float64'\n self.wordToNumericFeatures.append(col)\n if self.text_to_num:\n columns = list(self.text_to_num.keys())\n self.data[columns] = self.data[columns].apply(lambda x: to_number(x))\n self.update_type(self.text_to_num)\n self.log.info('----------- Inspecting Features -----------')\n for col in self.text_feature:\n self.log.info(f'-------> Feature : {col}')\n if col in self.text_to_num:\n self.log.info('----------> Numeric Status :Yes')\n self.log.info('----------> Data Type Converting to numeric :Yes')\n else:\n self.log.info('----------> Numeric Status :No')\n self.log.info(f'\\\\\\\\nStatus:- |... Feature inspection done for numeric data: {len(self.text_to_num)} feature(s) converted to numeric')\n self.log.info(f'\\\\\\\\nStatus:- |... Feature word to numeric treatment done: {self.text_to_num}')\n self.log.info('----------- Inspecting Features End -----------')\n \n def check_categorical_features(self):\n num_data = self.data.select_dtypes(include='number')\n num_data_unique = num_data.nunique()\n num_to_cat_col = {}\n for i, value in enumerate(num_data_unique):\n if value < self.config['categoryMaxLabel']:\n num_to_cat_col[num_data_unique.index[i]] = 'category'\n if num_to_cat_col:\n self.update_type(num_to_cat_col, 'numerical to categorical')\n str_to_cat_col = {}\n str_data = self.data.select_dtypes(include='object')\n str_data_unique = str_data.nunique()\n for i, value in enumerate(str_data_unique):\n if value < self.config['categoryMaxLabel']:\n str_to_cat_col[str_data_unique.index[i]] = 'category'\n for colm in str_data.columns:\n if self.data[colm].str.len().max() < STR_TO_CAT_CONVERSION_LEN_MAX:\n str_to_cat_col[colm] = 'category'\n if str_to_cat_col:\n self.update_type(str_to_cat_col, 'text to categorical') \n \n def drop_features(self, features=[], reason='unspecified'):\n if isinstance(features, str):\n features = [features]\n feat_to_remove = [x for x in features if x in self.data.columns]\n if feat_to_remove:\n self.data.drop(feat_to_remove, axis=1, inplace=True)\n for feat in feat_to_remove:\n self.dropped_features[feat] = reason \n self.log_drop_feature(feat_to_remove, reason)\n self.__update_type()\n \n def drop_duplicate(self):\n index = self.data.duplicated(keep='first')\n if index.sum():\n self.remove_rows(index, 'duplicate rows')\n \n def drop_na_target(self):\n if self.is_target_available():\n self.remove_rows(self.target.isna(), 'null target values')\n\n def log_drop_feature(self, columns, reason):\n self.log.info(f'---------- Dropping {reason} features ----------')\n self.log.info(f'\\\\\\\\nStatus:- |... {reason} feature treatment done: {len(columns)} {reason} feature(s) found')\n self.log.info(f'-------> Drop Features: {columns}')\n self.log.info(f'Data Frame Shape After Dropping (Rows,Columns): {self.data.shape}')\n \n def log_normalization(self):\n if self.process_method.get('normalization', None):\n self.log.info(f'\\\\\\\\nStatus:- !... Normalization treatment done')\n for method in supported_method['normalization']:\n cols = []\n for col, m in self.process_method['normalization'].items():\n if m == method:\n cols.append(col)\n if cols and method != 'none':\n self.log.info(f'Running {method} on features: {cols}')\n\n def log_numerical_fill(self):\n if self.process_method.get('numFill', None):\n self.log.info(f'\\\\\\\\nStatus:- !... Fillna for numeric feature done')\n for method in supported_method['fillNa']['numeric']:\n cols = []\n for col, m in self.process_method['numFill'].items():\n if m == method:\n cols.append(col)\n if cols:\n self.log.info(f'-------> Running {method} on features: {cols}')\n\n def log_categorical_fill(self):\n if self.process_method.get('catFill', None):\n self.log.info(f'\\\\\\\\nStatus:-!... FillNa for categorical feature done')\n for method in supported_method['fillNa']['categorical']:\n cols = []\n for col, m in self.process_method['catFill'].items():\n if m == method:\n cols.append(col)\n if cols:\n self.log.info(f'-------> Running {method} on features: {cols}')\n \n def remove_constant_feature(self):\n unique_values = self.data.nunique()\n constant_features = []\n for i, value in enumerate(unique_values):\n if value == 1:\n constant_features.append(unique_values.index[i])\n if constant_features:\n self.drop_features(constant_features, \"constant\")\n for i in constant_features:\n try:\n self.numeric_feature.remove(i)\n except ValueError:\n pass \n try:\n self.cat_feature.remove(i)\n except ValueError:\n pass\n \n def remove_empty_feature(self, misval_ratio=1.0):\n missing_ratio = self.data.isnull().sum() / len(self.data)\n missing_ratio = {k:v for k,v in zip(self.data.columns, missing_ratio)}\n empty_features = [k for k,v in missing_ratio.items() if v > misval_ratio]\n if empty_features:\n self.drop_features(empty_features, \"empty\")\n for i in empty_features:\n try:\n self.numeric_feature.remove(i)\n except ValueError:\n pass\n try:\n self.cat_feature.remove(i)\n except:\n pass\n\n def remove_index_features(self):\n index_feature = []\n \n for feat in self.numeric_feature:\n if self.data[feat].nunique() == len(self.data):\n if (self.data[feat].sum()- sum(self.data.index) == (self.data.iloc[0][feat]-self.data.index[0])*len(self.data)):\n index_feature.append(feat)\n self.drop_features(index_feature, \"index\")\n for i in index_feature:\n try:\n self.numeric_feature.remove(i)\n except ValueError:\n pass\n try:\n self.cat_feature.remove(i)\n except:\n pass \n\n def fill_missing_value_method(self, colm, method):\n if colm in self.numeric_feature:\n if method in supported_method['fillNa']['numeric']:\n if 'numFill' not in self.process_method.keys():\n self.process_method['numFill'] = {}\n if method == 'na' and self.process_method['numFill'].get(colm, None):\n pass # don't overwrite\n else:\n self.process_method['numFill'][colm] = method\n if colm in self.cat_feature:\n if method in supported_method['fillNa']['categorical']:\n if 'catFill' not in self.process_method.keys():\n self.process_method['catFill'] = {}\n if method == 'na' and self.process_method['catFill'].get(colm, None):\n pass\n else:\n self.process_method['catFill'][colm] = method\n \n def check_encoding_method(self, method, colm,default=False):\n if not self.is_target_available() and (method.lower() == list(target_encoding_method_change.keys())[0]):\n method = target_encoding_method_change[method.lower()]\n if default:\n self.log.info(f\"Applying Label encoding instead of Target encoding on feature '{colm}' as target feature is not present\")\n return method\n \n def fill_encoder_value_method(self,colm, method, default=False):\n if colm in self.cat_feature:\n if method.lower() in supported_method['categoryEncoding']:\n if 'catEncoder' not in self.process_method.keys():\n self.process_method['catEncoder'] = {}\n if method == 'na' and self.process_method['catEncoder'].get(colm, None):\n pass\n else:\n self.process_method['catEncoder'][colm] = self.check_encoding_method(method, colm,default)\n else:\n self.log.info(f\"-------> categorical encoding method '{method}' is not supported. supported methods are {supported_method['categoryEncoding']}\")\n\n def fill_normalizer_method(self,colm, method):\n if colm in self.numeric_feature:\n if method in supported_method['normalization']:\n if 'normalization' not in self.process_method.keys():\n self.process_method['normalization'] = {}\n if (method == 'na' or method == 'none') and self.process_method['normalization'].get(colm, None):\n pass\n else:\n self.process_method['normalization'][colm] = method\n else:\n self.log.info(f\"-------> Normalization method '{method}' is not supported. supported methods are {supported_method['normalization']}\")\n\n def apply_outlier(self):\n inlier_indices = np.array([True] * len(self.data)) \n if self.process_method.get('outlier', None):\n self.log.info('-------> Feature wise outlier detection:')\n for k,v in self.process_method['outlier'].items():\n if k in self.numeric_feature:\n if v == 'iqr':\n index = findiqrOutlier(self.data[k])\n elif v == 'zscore':\n index = findzscoreOutlier(self.data[k])\n elif v == 'disable':\n index = None\n if k in self.process_method['outlierOperation'].keys():\n if self.process_method['outlierOperation'][k] == 'dropdata':\n inlier_indices = np.logical_and(inlier_indices, index)\n elif self.process_method['outlierOperation'][k] == 'average':\n mean = self.data[k].mean()\n index = ~index\n self.data.loc[index,[k]] = mean\n self.log.info(f'-------> {k}: Replaced by Mean {mean}: total replacement {index.sum()}')\n elif self.process_method['outlierOperation']", "instruction": "", "output": "" }, { "input": "[k] == 'nochange' and v != 'disable':\n self.log.info(f'-------> Total outliers in \"{k}\": {(~index).sum()}')\n if self.config.get('outlierDetection',None):\n if self.config['outlierDetection'].get('IsolationForest','False') == 'True':\n index = findiforestOutlier(self.data[self.numeric_feature])\n inlier_indices = np.logical_and(inlier_indices, index)\n self.log.info(f'-------> Numeric feature based Outlier detection(IsolationForest):')\n if inlier_indices.sum() != len(self.data):\n self.remove_rows( inlier_indices == False, 'outlier detection')\n self.log.info('Status:- |... Outlier treatment done')\n self.log.info(f'-------> Data Frame Shape After Outlier treatment (Rows,Columns): {self.data.shape}')\n\n def remove_rows(self, indices, msg=''):\n if indices.sum():\n indices = ~indices\n if len(indices) != len(self.data):\n raise ValueError('Data Frame length mismatch')\n self.data = self.data[indices]\n self.data.reset_index(drop=True, inplace=True)\n if self.is_target_available():\n self.target = self.target[indices]\n if isinstance(self.target, pd.Series):\n self.target.reset_index(drop=True, inplace=True)\n if not self.unprocessed.empty:\n self.unprocessed = self.unprocessed[indices]\n self.unprocessed.reset_index(drop=True, inplace=True)\n self.log.info(f'-------> {msg} dropped rows count: {(indices == False).sum()}')\n \n def fill_outlier_method(self,colm, method):\n if colm in self.numeric_feature:\n if method in supported_method['outlier_column_wise']:\n if 'outlier' not in self.process_method.keys():\n self.process_method['outlier'] = {}\n if method != 'Disable':\n self.process_method['outlier'][colm] = method\n else:\n self.log.info(f\"-------> outlier detection method '{method}' is not supported for column wise. supported methods are {supported_method['outlier_column_wise']}\")\n\n def fill_outlier_process(self,colm, method):\n if colm in self.numeric_feature:\n if method in supported_method['outlierOperation']:\n if 'outlierOperation' not in self.process_method.keys():\n self.process_method['outlierOperation'] = {}\n self.process_method['outlierOperation'][colm] = method\n else:\n self.log.info(f\"-------> outlier process method '{method}' is not supported for column wise. supported methods are {supported_method['outlieroperation']}\")\n \n def get_cat_imputer(self,method):\n if method == 'mode':\n return SimpleImputer(strategy='most_frequent')\n elif method == 'zero':\n return SimpleImputer(strategy='constant', fill_value=0)\n \n def get_cat_encoder(self,method):\n if method == 'labelencoding':\n return OrdinalEncoder(handle_unknown=\"error\")\n elif method == 'onehotencoding':\n return OneHotEncoder(sparse=False,handle_unknown=\"error\")\n elif method == 'targetencoding':\n if not self.is_target_available():\n raise ValueError('Can not apply Target Encoding when target feature is not present')\n return TargetEncoder(handle_unknown='error')\n\n def get_num_imputer(self,method):\n if method == 'mode':\n return SimpleImputer(strategy='most_frequent')\n elif method == 'mean':\n return SimpleImputer(strategy='mean')\n elif method == 'median':\n return SimpleImputer(strategy='median')\n elif method == 'knnimputer':\n return KNNImputer()\n elif method == 'zero':\n return SimpleImputer(strategy='constant', fill_value=0)\n \n def get_num_scaler(self,method):\n if method == 'minmax':\n return MinMaxScaler()\n elif method == 'standardscaler':\n return StandardScaler()\n elif method == 'lognormal':\n return PowerTransformer(method='yeo-johnson', standardize=False)\n \"\"\"\n return self.codeText\n \n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\nimport json\n\nclass selector():\n\n def __init__(self, indent=0, tab_size=4):\n self.tab = \" \"*tab_size\n self.codeText = f\"\\\\n\\\\ndef featureSelector(log):\"\n self.pipe = 'pipe'\n self.code_generated = False\n self.input_files = {}\n self.output_files = {}\n self.function_code = ''\n self.addInputFiles({'inputData' : 'transformedData.dat', 'metaData' : 'modelMetaData.json','log' : 'aion.log','outputData' : 'featureEngineeredData.dat'})\n\n def addInputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def addOutputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def getInputFiles(self): \n text = 'IOFiles = '\n if not self.input_files:\n text += '{ }'\n else:\n text += json.dumps(self.input_files, indent=4)\n return text\n \n def getOutputFiles(self):\n text = 'output_file = '\n if not self.output_files:\n text += '{ }'\n else:\n text += json.dumps(self.output_files, indent=4)\n return text\n \n def getInputOutputFiles(self, indent=0):\n text = '\\\\n'\n text += self.getInputFiles()\n if indent:\n text = text.replace('\\\\n', self.tab * indent + '\\\\n')\n return text\n \n def __addValidateConfigCode(self):\n text = \"\\\\n\\\\\n \\\\ndef validateConfig():\\\\\n \\\\n config_file = Path(__file__).parent/'config.json'\\\\\n \\\\n if not Path(config_file).exists():\\\\\n \\\\n raise ValueError(f'Config file is missing: {config_file}')\\\\\n \\\\n config = read_json(config_file)\\\\\n \\\\n return config\"\n return text\n\n def addMainCode(self):\n self.codeText += \"\\\\n\\\\\n \\\\nif __name__ == '__main__':\\\\\n \\\\n log = None\\\\\n \\\\n try:\\\\\n \\\\n print(featureSelector(log))\\\\\n \\\\n except Exception as e:\\\\\n \\\\n if log:\\\\\n \\\\n log.error(e, exc_info=True)\\\\\n \\\\n status = {'Status':'Failure','Message':str(e)}\\\\\n \\\\n print(json.dumps(status))\\\\\n \"\n def addValidateConfigCode(self, indent=1):\n self.function_code += self.__addValidateConfigCode()\n\n def addStatement(self, statement, indent=1):\n self.codeText += '\\\\n' + self.tab * indent + statement\n \n def getCode(self):\n return self.function_code + '\\\\n' + self.codeText\n\n def addLocalFunctionsCode(self):\n self.addValidateConfigCode()\n \n\n def getPrefixModules(self):\n modules = [{'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'pandas', 'mod_as':'pd'}\n ]\n return modules\n \n def addPrefixCode(self, indent=1):\n self.codeText += \"\\\\\n \\\\n config = validateConfig()\\\\\n \\\\n targetPath = Path('aion')/config['targetPath']\\\\\n \\\\n if not targetPath.exists():\\\\\n \\\\n raise ValueError(f'targetPath does not exist')\\\\\n \\\\n meta_data_file = targetPath/IOFiles['metaData']\\\\\n \\\\n if meta_data_file.exists():\\\\\n \\\\n meta_data = read_json(meta_data_file)\\\\\n \\\\n else:\\\\\n \\\\n raise ValueError(f'Configuration file not found: {meta_data_file}')\\\\\n \\\\n log_file = targetPath/IOFiles['log']\\\\\n \\\\n log = logger(log_file, mode='a', logger_name=Path(__file__).parent.stem)\\\\\n \\\\n dataLoc = targetPath/IOFiles['inputData']\\\\\n \\\\n if not dataLoc.exists():\\\\\n \\\\n return {'Status':'Failure','Message':'Data location does not exists.'}\\\\\n \\\\n\\\\\n \\\\n status = dict()\\\\\n \\\\n df = pd.read_csv(dataLoc)\\\\\n \\\\n prev_step_output = meta_data['transformation']\"\n\n def getSuffixModules(self):\n modules = [{'module':'platform'}\n ,{'module':'time'}\n ]\n return modules\n \n def addSuffixCode(self, indent=1):\n self.codeText += \"\\\\n\\\\\n \\\\n csv_path = str(targetPath/IOFiles['outputData'])\\\\\n \\\\n write_data(df, csv_path,index=False)\\\\\n \\\\n status = {'Status':'Success','DataFilePath':IOFiles['outputData'],'total_features':total_features, 'selected_features':selected_features}\\\\\n \\\\n log.info(f'Selected data saved at {csv_path}')\\\\\n \\\\n meta_data['featureengineering']['Status'] = status\\\\\n \\\\n write_json(meta_data, str(targetPath/IOFiles['metaData']))\\\\\n \\\\n log.info(f'output: {status}')\\\\\n \\\\n return json.dumps(status)\"\n\n def getMainCodeModules(self):\n modules = [{'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'sys'}\n ,{'module':'json'}\n ,{'module':'logging'}\n ,{'module':'argparse'}\n ]\n return modules\n \n def add_variable(self, name, value, indent=1):\n if isinstance(value, str):\n self.codeText += f\"\\\\n{self.tab * indent}{name} = '{value}'\"\n else:\n self.codeText += f\"\\\\n{self.tab * indent}{name} = {value}\"\n \n def addStatement(self, statement, indent=1):\n self.codeText += f\"\\\\n{self.tab * indent}{statement}\"\n \n def modelBased(self, problem_type, indent=1):\n if problem_type == 'classification':\n self.codeText += f\"\\\\n{self.tab * indent}selector = SelectFromModel(ExtraTreesClassifier())\"\n self.codeText += f\"\\\\n{self.tab * indent}selector()\"\n if problem_type == 'regression':\n self.codeText += f\"\\\\n{self.tab * indent}pipe = Pipeline([('selector', SelectFromModel(Lasso()))])\"\n self.codeText += f\"\\\\n{self.tab * indent}selector.fit(df[train_features],df[target_feature])\"\n self.codeText += f\"\\\\n{self.tab * indent}selected_features = [x for x,y in zip(train_features, selector.get_support()) if y]\"\n self.codeText += f\"\\\\n{self.tab * indent}df = df[selected_features + [target_feature]]\"\n \n def featureReductionBased(self, reducer, n_components, indent=1):\n if reducer == 'pca':\n if n_components == 0:\n self.codeText += f\"\\\\n{self.tab * indent}pipe = Pipeline([('selector', PCA(n_components='mle',svd_solver = 'full'))])\"\n elif n_components < 1:\n self.codeText += f\"\\\\n{self.tab * indent}pipe = Pipeline([('selector', PCA(n_components={n_components},svd_solver = 'full'))])\"\n else:\n self.codeText += f\"\\\\n{self.tab * indent}pipe = Pipeline([('selector', PCA(n_components=int({n_components})))])\"\n self.codeText += \"pipe.fit_transform(df)\"\n\n def getPipe(self):\n return self.pipe\n \n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nimport json\n\nclass learner():\n\n def __init__(self, problem_type=\"classification\", target_feature=\"\", sample_method=None,indent=0, tab_size=4):\n self.tab = \" \"*tab_size\n self.df_name = 'df'\n self.problem_type = problem_type\n self.target_feature = target_feature\n self.search_space = []\n self.codeText = f\"\\\\ndef train(log):\"\n self.input_files = {}\n self.output_files = {}\n self.function_code = ''\n self.addInputFiles({'inputData' : 'featureEngineeredData.dat','testData' : 'test.dat', 'metaData' : 'modelMetaData.json','monitor':'monitoring.json','log' : 'aion.log'})\n\n def addInputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def addOutputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def getInputFiles(self): \n text = 'IOFiles = '\n if not self.input_files:\n text += '{ }'\n else:\n text += json.dumps(self.input_files, indent=4)\n return text\n \n def getOutputFiles(self):\n text = 'output_file = '\n if not self.output_files:\n text += '{ }'\n else:\n text += json.dumps(self.output_files, indent=4)\n return text\n \n def getInputOutputFiles(self, indent=0):\n text = '\\\\n'\n text += self.getInputFiles()\n if indent:\n text = text.replace('\\\\n', self.tab * indent + '\\\\n')\n return text\n \n def __addValidateConfigCode(self):\n text = \"\\\\n\\\\\n \\\\ndef validateConfig():\\\\\n \\\\n config_file = Path(__file__).parent/'config.", "instruction": "", "output": "" }, { "input": "json'\\\\\n \\\\n if not Path(config_file).exists():\\\\\n \\\\n raise ValueError(f'Config file is missing: {config_file}')\\\\\n \\\\n config = read_json(config_file)\\\\\n \\\\n return config\"\n return text\n\n def __addSaveModelCode(self):\n text = \"\\\\n\\\\\n \\\\ndef save_model( experiment_id, estimator, features, metrices, params,tags, scoring):\\\\\n \\\\n # mlflow log model, metrices and parameters\\\\\n \\\\n with mlflow.start_run(experiment_id = experiment_id, run_name = model_name):\\\\\n \\\\n return logMlflow(params, metrices, estimator, tags, model_name.split('_')[0])\"\n return text\n\n def addStatement(self, statement, indent=1):\n self.codeText += '\\\\n' + self.tab * indent + statement\n \n def getCode(self):\n return self.function_code + '\\\\n' + self.codeText\n\n def addLocalFunctionsCode(self):\n self.function_code += self.__addValidateConfigCode()\n self.function_code += self.__addSaveModelCode()\n\n def getPrefixModules(self):\n modules = [{'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'pandas', 'mod_as':'pd'}\n ]\n return modules\n \n def addPrefixCode(self, indent=1):\n self.codeText += \"\\\\\n \\\\n config = validateConfig()\\\\\n \\\\n targetPath = Path('aion')/config['targetPath']\\\\\n \\\\n if not targetPath.exists():\\\\\n \\\\n raise ValueError(f'targetPath does not exist')\\\\\n \\\\n meta_data_file = targetPath/IOFiles['metaData']\\\\\n \\\\n if meta_data_file.exists():\\\\\n \\\\n meta_data = read_json(meta_data_file)\\\\\n \\\\n else:\\\\\n \\\\n raise ValueError(f'Configuration file not found: {meta_data_file}')\\\\\n \\\\n log_file = targetPath/IOFiles['log']\\\\\n \\\\n log = logger(log_file, mode='a', logger_name=Path(__file__).parent.stem)\\\\\n \\\\n dataLoc = targetPath/IOFiles['inputData']\\\\\n \\\\n if not dataLoc.exists():\\\\\n \\\\n return {'Status':'Failure','Message':'Data location does not exists.'}\\\\\n \\\\n\\\\\n \\\\n status = dict()\\\\\n \\\\n usecase = config['targetPath']\\\\\n \\\\n df = pd.read_csv(dataLoc)\\\\\n \\\\n prev_step_output = meta_data['featureengineering']['Status']\"\n\n def getSuffixModules(self):\n modules = [{'module':'platform'}\n ,{'module':'time'}\n ,{'module':'mlflow'}\n ]\n return modules\n def add_100_trainsize_code(self):\n self.codeText +=\"\\\\n\\\\\n \\\\n else:\\\\\n \\\\n test_score = train_score\\\\\n \\\\n metrices = {}\"\n def addSuffixCode(self, indent=1):\n self.codeText += \"\\\\n\\\\\n \\\\n meta_data['training'] = {}\\\\\n \\\\n meta_data['training']['features'] = features\\\\\n \\\\n scoring = config['scoring_criteria']\\\\\n \\\\n tags = {'estimator_name': model_name}\\\\\n \\\\n monitoring_data = read_json(targetPath/IOFiles['monitor'])\\\\\n \\\\n mlflow_default_config = {'artifacts_uri':'','tracking_uri_type':'','tracking_uri':'','registry_uri':''}\\\\\n \\\\n mlflow_client, experiment_id = mlflow_create_experiment(monitoring_data.get('mlflow_config',mlflow_default_config), targetPath, usecase)\\\\\n \\\\n run_id = save_model(experiment_id, estimator,features, metrices,best_params,tags,scoring)\\\\\n \\\\n write_json(meta_data, targetPath/IOFiles['metaDataOutput'])\\\\\n \\\\n write_json({'scoring_criteria': scoring, 'metrices':metrices, 'param':best_params}, targetPath/IOFiles['performance'])\\\\\n \\\\n\\\\\n \\\\n # return status\\\\\n \\\\n status = {'Status':'Success','mlflow_run_id':run_id,'FeaturesUsed':features,'test_score':metrices['test_score'],'train_score':metrices['train_score']}\\\\\n \\\\n log.info(f'Test score: {test_score}')\\\\\n \\\\n log.info(f'Train score: {train_score}')\\\\\n \\\\n log.info(f'MLflow run id: {run_id}')\\\\\n \\\\n log.info(f'output: {status}')\\\\\n \\\\n return json.dumps(status)\"\n\n def getMainCodeModules(self):\n modules = [{'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'sys'}\n ,{'module':'json'}\n ,{'module':'logging'}\n ]\n return modules\n\n def addMainCode(self, indent=1):\n self.codeText += \"\\\\n\\\\\n \\\\nif __name__ == '__main__':\\\\\n \\\\n log = None\\\\\n \\\\n try:\\\\\n \\\\n print(train(log))\\\\\n \\\\n except Exception as e:\\\\\n \\\\n if log:\\\\\n \\\\n log.error(e, exc_info=True)\\\\\n \\\\n status = {'Status':'Failure','Message':str(e)}\\\\\n \\\\n print(json.dumps(status))\\\\\n \"\n\n def add_variable(self, name, value, indent=1):\n if isinstance(value, str):\n self.codeText += f\"\\\\n{self.tab * indent}{name} = '{value}'\"\n else:\n self.codeText += f\"\\\\n{self.tab * indent}{name} = {value}\"\n \n def addStatement(self, statement, indent=1):\n self.codeText += f\"\\\\n{self.tab * indent}{statement}\"\n \n def add_search_space_w(self, algoritms):\n for model, params in algoritms.items():\n d = {'clf': f\"[{model}()]\"}\n for k,v in params.items():\n if isinstance(v, str):\n d[f'clf__{k}']=f\"'{v}'\"\n else:\n d[f'clf__{k}']= f\"{v}\"\n self.search_space.append(d)\n \n def add_search_space(self, indent=1):\n self.codeText += f\"\\\\n{self.tab}search_space = config['search_space']\"\n \n def add_train_test_split(self, train_feature, target_feature,test_ratio, indent=1):\n self.codeText += \"\\\\n\\\\n # split the data for training\\\\\n \\\\n selected_features = prev_step_output['selected_features']\\\\\n \\\\n target_feature = config['target_feature']\\\\\n \\\\n train_features = prev_step_output['total_features'].copy()\\\\\n \\\\n train_features.remove(target_feature)\\\\\n \\\\n X_train = df[train_features]\\\\\n \\\\n y_train = df[target_feature]\\\\\n \\\\n if config['test_ratio'] > 0.0:\\\\\n \\\\n test_data = read_data(targetPath/IOFiles['testData'])\\\\\n \\\\n X_test = test_data[train_features]\\\\\n \\\\n y_test = test_data[target_feature]\\\\\n \\\\n else:\\\\\n \\\\n X_test = pd.DataFrame()\\\\\n \\\\n y_test = pd.DataFrame()\"\n \n def add_model_fit(self, estimator, optimizer, selector_method, importer, indent=1):\n # need to adjust the indent\n importer.addModule('importlib')\n importer.addModule('operator')\n text = f\"\\\\n features = selected_features['{selector_method}']\\\\\n \\\\n estimator = {estimator}()\\\\\n \\\\n param = config['algorithms']['{estimator}']\"\n if optimizer == 'GridSearchCV':\n text += \"\\\\n grid = GridSearchCV(estimator, param,cv=config['optimization_param']['trainTestCVSplit'])\\\\\n \\\\n grid.fit(X_train[features], y_train)\\\\\n \\\\n train_score = grid.best_score_ * 100\\\\\n \\\\n best_params = grid.best_params_\\\\\n \\\\n estimator = grid.best_estimator_\"\n elif optimizer == 'GeneticSelectionCV':\n text += \"\\\\n grid = GeneticSelectionCV(estimator, scoring=scorer, n_generations=config['optimization_param']['iterations'],cv=config['optimization_param']['trainTestCVSplit'],n_population=config['optimization_param']['geneticparams']['n_population'],crossover_proba=config['optimization_param']['geneticparams']['crossover_proba'],mutation_proba=config['optimization_param']['geneticparams']['mutation_proba'],crossover_independent_proba=config['optimization_param']['geneticparams']['crossover_independent_proba'],mutation_independent_proba=config['optimization_param']['geneticparams']['mutation_independent_proba'],tournament_size=config['optimization_param']['geneticparams']['tournament_size'],n_gen_no_change=config['optimization_param']['geneticparams']['n_gen_no_change'])\\\\\n \\\\n grid.fit(X_train[features], y_train)\\\\\n \\\\n train_score = grid.score(X_train[features], y_train)\\\\\n \\\\n best_params = grid.estimator_.get_params()\\\\\n \\\\n estimator = grid.estimator_\"\n else:\n text += f\"\\\\n grid = {optimizer}(estimator, param, scoring=scorer, n_iter=config['optimization_param']['iterations'],cv=config['optimization_param']['trainTestCVSplit'])\\\\\n \\\\n grid.fit(X_train[features], y_train)\\\\\n \\\\n train_score = grid.best_score_ * 100\\\\\n \\\\n best_params = grid.best_params_\\\\\n \\\\n estimator = grid.best_estimator_\"\n self.codeText += text\n \n def addLearner(self, model_name, params, importer, indent=1):\n importer.addModule('Pipeline', mod_from='sklearn.pipeline')\n importer.addModule('ColumnTransformer', mod_from='sklearn.compose')\n importer.addModule('confusion_matrix', mod_from='sklearn.metrics')\n model_params = []\n for k,v in params.items():\n if isinstance(v, str):\n model_params.append(f\"{k}='{v}'\")\n else:\n model_params.append(f\"{k}={v}\")\n model_params = \",\".join(model_params)\n self.codeText += self.getTransformer()\n text = f\"\\\\n{self.tab * indent}pipeline = Pipeline(steps = [('preprocessor', preprocessor),('learner',{model_name}({model_params}))])\"\n self.codeText += text\n self.codeText += self.splitTargetFeature(importer)\n if self.balancing:\n self.codeText += self.balancingCode(importer)\n self.codeText += self.fitModelCode(importer)\n \n def splitTargetFeature(self, importer, indent=1):\n importer.addModule('train_test_split', mod_from='sklearn.model_selection')\n return f\"\\\\n{self.tab * indent}target = df['{self.target_feature}']\\\\\n \\\\n{self.tab * indent}df = df.drop(['{self.target_feature}'], axis=1)\\\\\n \\\\n{self.tab * indent}X_train, X_test, y_train, y_test = train_test_split(df,target, train_size = percentage/100.0)\"\n \n def getCode_remove(self, model_name=None, indent=1):\n return self.codeText\n \n def getDFName(self):\n return self.df_name\n \n def copyCode(self, learner):\n self.codeText = learner.getCode()\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\nimport json\n\nclass tabularDataReader():\n\n def __init__(self, tab_size=4):\n self.tab = ' ' * tab_size\n self.function_code = ''\n self.codeText = ''\n self.code_generated = False\n \n def getInputFiles(self):\n IOFiles = {\n\t\t\t\"rawData\": \"rawData.dat\",\n\t\t\t\"metaData\" : \"modelMetaData.json\",\n\t\t\t\"log\" : \"aion.log\",\n\t\t\t\"outputData\" : \"rawData.dat\",\n\t\t\t\"monitoring\":\"monitoring.json\",\n\t\t\t\"prodData\": \"prodData\",\n\t\t\t\"prodDataGT\":\"prodDataGT\" \n\t\t}\n text = 'IOFiles = '\n if not IOFiles:\n text += '{ }'\n else:\n text += json.dumps(IOFiles, indent=4)\n return text\n \n def getOutputFiles(self):\n output_files = {\n 'metaData' : 'modelMetaData.json',\n 'log' : 'aion.log',\n 'outputData' : 'rawData.dat'\n }\n text = 'output_file = '\n if not output_files:\n text += '{ }'\n else:\n text += json.dumps(output_files, indent=4)\n return text\n \n def getInputOutputFiles(self, indent=0):\n text = '\\\\n'\n text += self.getInputFiles()\n if indent:\n text = text.replace('\\\\n', self.tab * indent + '\\\\n')\n return text\n \n def __addValidateConfigCode(self):\n text = \"\\\\n\\\\\n \\\\ndef validateConfig():\\\\\n \\\\n config_file = Path(__file__).parent/'config.json'\\\\\n \\\\n if not Path(config_file).exists():\\\\\n \\\\n raise ValueError(f'Config file is missing: {config_file}')\\\\\n \\\\n config = read_json(config_file)\\\\\n\t\t\\\\n if not config['targetPath']:\\\\\n \\\\n raise ValueError(f'Target Path is not configured')\\\\\n \\\\n return config\"\n return text\n\n def addMainCode(self):\n self.codeText += \"\\\\n\\\\\n \\\\nif __name__ == '__main__':\\\\\n \\\\n log = None\\\\\n \\\\n try:\\\\\n \\\\n print(load_data(log))\\\\\n \\\\n except Exception as e:\\\\\n \\\\n if log:\\\\\n \\\\n log.getLogger().error(e, exc_info=True)\\\\\n \\\\n status = {'Status':'Failure','Message':str(e)}\\\\\n \\\\n print(json.dumps(status))\\\\\n \\\\n raise Exception(str(e))\\\\\n \"\n def addLoadDataCode(self):\n self.codeText += \"\"\"\n#This function will read the data and save the data on persistent storage \ndef load_data(log): \n config = validateConfig()", "instruction": "", "output": "" }, { "input": "\n targetPath = Path('aion')/config['targetPath'] \n targetPath.mkdir(parents=True, exist_ok=True)\t\n log_file = targetPath/IOFiles['log'] \n log = logger(log_file, mode='a', logger_name=Path(__file__).parent.stem)\n monitoring = targetPath/IOFiles['monitoring']\t\n if monitoring.exists(): \n monitoringStatus = read_json(monitoring)\n if monitoringStatus['dataLocation'] == '' and monitoringStatus['driftStatus'] != 'No Drift':\n reader = dataReader(reader_type=monitoring_data.get('prod_db_type','sqlite'),target_path=targetPath, config=config.get('db_config',None))\n \n raw_data_location = targetPath/IOFiles['rawData']\t\t\n if reader.file_exists(IOFiles['prodData']) and reader.file_exists(IOFiles['prodDataGT']): \t\t\n predicted_data = reader.read(IOFiles['prodData'])\n actual_data = reader.read(IOFiles['prodDataGT'])\n common_col = [k for k in predicted_data.columns.tolist() if k in actual_data.columns.tolist()]\t\t\t\t\n mergedRes = pd.merge(actual_data, predicted_data, on =common_col,how = 'inner')\n raw_data_path = pd.read_csv(raw_data_location)\t\t\t\n df = pd.concat([raw_data_path,mergedRes])\n else:\n raise ValueError(f'Prod Data not found')\t\t\t\n elif monitoringStatus['dataLocation'] == '':\n raise ValueError(f'Data Location does not exist')\n else:\n if 's3' in monitoringStatus.keys():\n input_reader = dataReader(reader_type='s3',target_path=None, config=monitoringStatus['s3'])\n log.info(f\"Downloading '{monitoringStatus['s3']['file_name']}' from s3 bucket '{monitoringStatus['s3']['bucket_name']}'\")\n df = input_reader.read(monitoringStatus['s3']['file_name'])\n else:\n location = monitoringStatus['dataLocation']\n log.info(f'Dataset path: {location}')\n df = read_data(location)\n else:\n raise ValueError(f'Monitoring.json does not exist')\t\t\n\n status = {} \n output_data_path = targetPath/IOFiles['outputData'] \n log.log_dataframe(df) \n required_features = list(set(config['selected_features'] + [config['target_feature']])) \n log.info('Dataset features required: ' + ','.join(required_features)) \n missing_features = [x for x in required_features if x not in df.columns.tolist()] \n if missing_features: \n raise ValueError(f'Some feature/s is/are missing: {missing_features}') \n log.info('Removing unused features: '+','.join(list(set(df.columns) - set(required_features)))) \n df = df[required_features] \n log.info(f'Required features: {required_features}') \n try: \n log.info(f'Saving Dataset: {str(output_data_path)}') \n write_data(df, output_data_path, index=False) \n status = {'Status':'Success','DataFilePath':IOFiles['outputData'],'Records':len(df)} \n except: \n raise ValueError('Unable to create data file') \n \n meta_data_file = targetPath/IOFiles['metaData'] \n meta_data = dict() \n meta_data['load_data'] = {} \n meta_data['load_data']['selected_features'] = [x for x in config['selected_features'] if x != config['target_feature']] \n meta_data['load_data']['Status'] = status \n write_json(meta_data, meta_data_file) \n output = json.dumps(status) \n log.info(output) \n return output\n\"\"\"\n def addValidateConfigCode(self, indent=1):\n self.function_code += self.__addValidateConfigCode()\n\n def generateCode(self):\n self.addValidateConfigCode()\n self.addLoadDataCode()\n self.addMainCode()\n self.code_generated = True\n \n def addStatement(self, statement, indent=1):\n self.codeText += '\\\\n' + self.tab * indent + statement\n \n def getCode(self):\n if not self.code_generated:\n self.generateCode()\n return self.function_code + '\\\\n' + self.codeText\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\nimport json\n\nclass register():\n\n def __init__(self, importer, indent=0, tab_size=4):\n self.tab = \" \"*tab_size\n self.codeText = \"\"\n self.function_code = \"\"\n self.importer = importer\n self.input_files = {}\n self.output_files = {}\n self.addInputFiles({'log' : 'aion.log', 'metaData' : 'modelMetaData.json','model' : 'model.pkl', 'performance': 'performance.json','production':'production.json','monitor':'monitoring.json'})\n \n def addInputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def addOutputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def getInputFiles(self): \n text = 'IOFiles = '\n if not self.input_files:\n text += '{ }'\n else:\n text += json.dumps(self.input_files, indent=4)\n return text\n \n def getOutputFiles(self):\n text = 'output_file = '\n if not self.output_files:\n text += '{ }'\n else:\n text += json.dumps(self.output_files, indent=4)\n return text\n \n def getInputOutputFiles(self, indent=0):\n text = '\\\\n'\n text += self.getInputFiles()\n if indent:\n text = text.replace('\\\\n', self.tab * indent + '\\\\n')\n return text\n \n def code_imports(self):\n modules = [{'module':'sys'}\n ,{'module':'json'}\n ,{'module':'time'}\n ,{'module':'platform'}\n ,{'module':'tempfile'}\n ,{'module':'sqlite3'}\n ,{'module':'mlflow'}\n ,{'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'ViewType', 'mod_from':'mlflow.entities'}\n ,{'module':'MlflowClient', 'mod_from':'mlflow.tracking'}\n ,{'module':'ModelVersionStatus', 'mod_from':'mlflow.entities.model_registry.model_version_status'}\n ]\n self.import_modules(modules)\n\n def import_module(self, module, mod_from=None, mod_as=None):\n self.importer.addModule(module, mod_from=mod_from, mod_as=mod_as)\n \n def import_modules(self, modules):\n if isinstance(modules, list):\n for mod in modules:\n if isinstance(mod, dict):\n self.importer.addModule(mod['module'], mod_from= mod.get('mod_from', None), mod_as=mod.get('mod_as', None))\n\n def getImportCode(self):\n return self.importer.getCode()\n\n def __addValidateConfigCode(self, models=None):\n text = \"\\\\n\\\\\n \\\\ndef validateConfig():\\\\\n \\\\n config_file = Path(__file__).parent/'config.json'\\\\\n \\\\n if not Path(config_file).exists():\\\\\n \\\\n raise ValueError(f'Config file is missing: {config_file}')\\\\\n \\\\n config = read_json(config_file)\\\\\n\t\t\\\\n return config\\\\\n\t\t\"\n return text\n \n def addLocalFunctionsCode(self, models):\n self.function_code += self.__addValidateConfigCode(models)\n \n def addPrefixCode(self, indent=1):\n self.code_imports()\n self.codeText += \"\\\\n\\\\\n \\\\ndef __merge_logs(log_file_sequence,path, files):\\\\\n \\\\n if log_file_sequence['first'] in files:\\\\\n \\\\n with open(path/log_file_sequence['first'], 'r') as f:\\\\\n \\\\n main_log = f.read()\\\\\n \\\\n files.remove(log_file_sequence['first'])\\\\\n \\\\n for file in files:\\\\\n \\\\n with open(path/file, 'r') as f:\\\\\n \\\\n main_log = main_log + f.read()\\\\\n \\\\n (path/file).unlink()\\\\\n \\\\n with open(path/log_file_sequence['merged'], 'w') as f:\\\\\n \\\\n f.write(main_log)\\\\\n \\\\n\\\\\n \\\\ndef merge_log_files(folder, models):\\\\\n \\\\n log_file_sequence = {\\\\\n \\\\n 'first': 'aion.log',\\\\\n \\\\n 'merged': 'aion.log'\\\\\n \\\\n }\\\\\n \\\\n log_file_suffix = '_aion.log'\\\\\n \\\\n log_files = [x+log_file_suffix for x in models if (folder/(x+log_file_suffix)).exists()]\\\\\n \\\\n log_files.append(log_file_sequence['first'])\\\\\n \\\\n __merge_logs(log_file_sequence, folder, log_files)\\\\\n \\\\n\\\\\n \\\\ndef register_model(targetPath,models,usecasename, meta_data):\\\\\n \\\\n register = mlflow_register(targetPath, usecasename, meta_data)\\\\\n \\\\n register.setup_registration()\\\\\n \\\\n\\\\\n \\\\n runs_with_score = register.get_unprocessed_runs(models)\\\\\n \\\\n best_run = register.get_best_run(runs_with_score)\\\\\n \\\\n register.update_unprocessed(runs_with_score)\\\\\n \\\\n return register.register_model(models, best_run)\\\\\n \\\\n\\\\\n \\\\ndef register(log):\\\\\n \\\\n config = validateConfig()\\\\\n \\\\n targetPath = Path('aion')/config['targetPath']\\\\\n \\\\n models = config['models']\\\\\n \\\\n merge_log_files(targetPath, models)\\\\\n \\\\n meta_data_file = targetPath/IOFiles['metaData']\\\\\n \\\\n if meta_data_file.exists():\\\\\n \\\\n meta_data = read_json(meta_data_file)\\\\\n \\\\n else:\\\\\n \\\\n raise ValueError(f'Configuration file not found: {meta_data_file}')\\\\\n \\\\n usecase = config['targetPath']\\\\\n \\\\n # enable logging\\\\\n \\\\n log_file = targetPath/IOFiles['log']\\\\\n \\\\n log = logger(log_file, mode='a', logger_name=Path(__file__).parent.stem)\\\\\n \\\\n register_model_name = register_model(targetPath,models,usecase, meta_data)\\\\\n \\\\n status = {'Status':'Success','Message':f'Model Registered: {register_model_name}'}\\\\\n \\\\n log.info(f'output: {status}')\\\\\n \\\\n return json.dumps(status)\"\n\n def getMainCodeModules(self):\n modules = [{'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'sys'}\n ,{'module':'os'} \n ,{'module':'json'}\n ,{'module':'logging'}\n ,{'module':'shutil'}\n ,{'module':'argparse'}\n ]\n return modules\n \n def addMainCode(self, models, indent=1):\n self.codeText += \"\\\\n\\\\\n\t\t\\\\nif __name__ == '__main__':\\\\\n \\\\n log = None\\\\\n \\\\n try:\\\\\n \\\\n print(register(log))\\\\\n \\\\n except Exception as e:\\\\\n \\\\n if log:\\\\\n \\\\n log.error(e, exc_info=True)\\\\\n \\\\n status = {'Status':'Failure','Message':str(e)}\\\\\n \\\\n print(json.dumps(status))\"\n \n def addStatement(self, statement, indent=1):\n self.codeText += f\"\\\\n{self.tab * indent}{statement}\"\n \n def query_with_quetes_code(self, decs=True, indent=1):\n return \"\"\"\\\\n{first_indentation}def __get_unprocessed_runs_sorted(self):\n{indentation}query = \"tags.processed = 'no'\"\n{indentation}runs = self.client.search_runs(\n{indentation} experiment_ids=self.experiment_id,\n{indentation} filter_string=query,\n{indentation} run_view_type=ViewType.ACTIVE_ONLY,\n{indentation} order_by=['metrics.test_score {0}']\n{indentation})\n{indentation}return runs\\\\n\"\"\".format('DESC' if decs else 'ASC', first_indentation=indent*self.tab, indentation=(1+indent)*self.tab)\n \n\n def addClassCode(self, smaller_is_better=False):\n self.codeText += \"\\\\\n \\\\nclass mlflow_register():\\\\\n \\\\n\\\\\n \\\\n def __init__(self, input_path, model_name, meta_data):\\\\\n \\\\n self.input_path = Path(input_path).resolve()\\\\\n \\\\n self.model_name = model_name\\\\\n \\\\n self.meta_data = meta_data\\\\\n \\\\n self.logger = logging.getLogger('ModelRegister')\\\\\n \\\\n self.client = None\\\\\n \\\\n self.monitoring_data = read_json(self.input_path/IOFiles['monitor'])\\\\\n \\\\n mlflow_default_config = {'artifacts_uri':'','tracking_uri_type':'','tracking_uri':'','registry_uri':''}\\\\\n \\\\n if not self.monitoring_data.get('mlflow_config',False):\\\\\n \\\\n self.monitoring_data['mlflow_config'] = mlflow_default_config\\\\\n \\\\n\\\\\n \\\\n def setup_registration(self):\\\\\n \\\\n tracking_uri, artifact_uri, registry_uri = get_mlflow_uris(self.monitoring_data['mlflow_config'],self.input_path)\\\\\n \\\\n self.logger.info(f'MLflow tracking uri: {tracking_uri}')\\\\\n \\\\n self.logger.info(f'MLflow registry uri: {registry_uri}')\\\\\n \\\\n mlflow.set_tracking_uri(tracking_uri)\\\\\n \\\\n mlflow.set_registry_uri(registry_uri)\\\\\n \\\\n self.client = mlflow.tracking.MlflowClient(\\\\\n \\\\n tracking_uri=tracking_uri,\\\\\n \\\\n registry_uri=reg", "instruction": "", "output": "" }, { "input": "istry_uri,\\\\\n \\\\n )\\\\\n \\\\n self.experiment_id = self.client.get_experiment_by_name(self.model_name).experiment_id\\\\\n \\\\n\"\n self.codeText += self.query_with_quetes_code(smaller_is_better == False)\n self.codeText += \"\\\\\n \\\\n def __log_unprocessed_runs(self, runs):\\\\\n \\\\n self.logger.info('Unprocessed runs:')\\\\\n \\\\n for run in runs:\\\\\n \\\\n self.logger.info('\t{}: {}'.format(run.info.run_id,run.data.metrics['test_score']))\\\\\n \\\\n\\\\\n \\\\n def get_unprocessed_runs(self, model_path):\\\\\n \\\\n unprocessed_runs = self.__get_unprocessed_runs_sorted()\\\\\n \\\\n if not unprocessed_runs:\\\\\n \\\\n raise ValueError('Registering fail: No new trained model')\\\\\n \\\\n self.__log_unprocessed_runs( unprocessed_runs)\\\\\n \\\\n return unprocessed_runs\\\\\n \\\\n\\\\\n \\\\n def __wait_until_ready(self, model_name, model_version):\\\\\n \\\\n client = MlflowClient()\\\\\n \\\\n for _ in range(10):\\\\\n \\\\n model_version_details = self.client.get_model_version(\\\\\n \\\\n name=model_name,\\\\\n \\\\n version=model_version,\\\\\n \\\\n )\\\\\n \\\\n status = ModelVersionStatus.from_string(model_version_details.status)\\\\\n \\\\n if status == ModelVersionStatus.READY:\\\\\n \\\\n break\\\\\n \\\\n time.sleep(1)\\\\\n \\\\n\\\\\n \\\\n def __create_model(self, run):\\\\\n \\\\n artifact_path = 'model'\\\\\n \\\\n model_uri = 'runs:/{run_id}/{artifact_path}'.format(run_id=run.info.run_id, artifact_path=artifact_path)\\\\\n \\\\n self.logger.info(f'Registering model (run id): {run.info.run_id}')\\\\\n \\\\n model_details = mlflow.register_model(model_uri=model_uri, name=self.model_name)\\\\\n \\\\n self.__wait_until_ready(model_details.name, model_details.version)\\\\\n \\\\n self.client.set_tag(run.info.run_id, 'registered', 'yes' )\\\\\n \\\\n state_transition = self.client.transition_model_version_stage(\\\\\n \\\\n name=model_details.name,\\\\\n \\\\n version=model_details.version,\\\\\n \\\\n stage='Production',\\\\\n \\\\n )\\\\\n \\\\n self.logger.info(state_transition)\\\\\n \\\\n return model_details\\\\\n \\\\n\\\\\n \\\\n def get_best_run(self, models):\\\\\n \\\\n return models[0]\\\\\n \\\\n\\\\\n \\\\n def __validate_config(self):\\\\\n \\\\n try:\\\\\n \\\\n load_data_loc = self.meta_data['load_data']['Status']['DataFilePath']\\\\\n \\\\n except KeyError:\\\\\n \\\\n raise ValueError('DataIngestion step output is corrupted')\\\\\n \\\\n\\\\\n \\\\n def __mlflow_log_transformer_steps(self, best_run):\\\\\n \\\\n run_id = best_run.info.run_id\\\\\n \\\\n meta_data = read_json(self.input_path/(best_run.data.tags['mlflow.runName']+'_'+IOFiles['metaData']))\\\\\n \\\\n self.__validate_config()\\\\\n \\\\n with mlflow.start_run(run_id):\\\\\n \\\\n if 'transformation' in meta_data.keys():\\\\\n \\\\n if 'target_encoder' in meta_data['transformation'].keys():\\\\\n \\\\n source_loc = meta_data['transformation']['target_encoder']\\\\\n \\\\n mlflow.log_artifact(str(self.input_path/source_loc))\\\\\n \\\\n meta_data['transformation']['target_encoder'] = Path(source_loc).name\\\\\n \\\\n if 'preprocessor' in meta_data['transformation'].keys():\\\\\n \\\\n source_loc = meta_data['transformation']['preprocessor']\\\\\n \\\\n mlflow.log_artifact(str(self.input_path/source_loc))\\\\\n \\\\n meta_data['transformation']['preprocessor'] = Path(source_loc).name\\\\\n \\\\n\\\\\n \\\\n write_json(meta_data, self.input_path/IOFiles['metaData'])\\\\\n \\\\n mlflow.log_artifact(str(self.input_path/IOFiles['metaData']))\\\\\n \\\\n\\\\\n \\\\n def __update_processing_tag(self, processed_runs):\\\\\n \\\\n self.logger.info('Changing status to processed:')\\\\\n \\\\n for run in processed_runs:\\\\\n \\\\n self.client.set_tag(run.info.run_id, 'processed', 'yes')\\\\\n \\\\n self.logger.info(f'\trun id: {run.info.run_id}')\\\\\n \\\\n\\\\\n \\\\n def update_unprocessed(self, runs):\\\\\n \\\\n return self.__update_processing_tag( runs)\\\\\n \\\\n\\\\\n \\\\n def __force_register(self, best_run):\\\\\n \\\\n self.__create_model( best_run)\\\\\n \\\\n self.__mlflow_log_transformer_steps( best_run)\\\\\n \\\\n production_json = self.input_path/IOFiles['production']\\\\\n \\\\n production_model = {'Model':best_run.data.tags['mlflow.runName'],'runNo':self.monitoring_data['runNo'],'score':best_run.data.metrics['test_score']}\\\\\n \\\\n write_json(production_model, production_json)\\\\\n \\\\n database_path = self.input_path/(self.input_path.stem + '.db')\\\\\n \\\\n if database_path.exists():\\\\\n \\\\n database_path.unlink()\\\\\n \\\\n return best_run.data.tags['mlflow.runName']\\\\\n \\\\n\\\\\n \\\\n def __get_register_model_score(self):\\\\\n \\\\n reg = self.client.list_registered_models()\\\\\n \\\\n if not reg:\\\\\n \\\\n return '', 0\\\\\n \\\\n run_id = reg[0].latest_versions[0].run_id\\\\\n \\\\n run = self.client.get_run(run_id)\\\\\n \\\\n score = run.data.metrics['test_score']\\\\\n \\\\n return run_id, score\\\\\n \\\\n\\\\\n \\\\n def register_model(self, models, best_run):\\\\\n \\\\n return self.__force_register(best_run)\"\n \n def local_functions_code(self, smaller_is_better=True, indent=1):\n if smaller_is_better:\n min_max = 'min'\n else:\n min_max = 'max'\n self.codeText += \"\\\\ndef validate_config(deploy_dict):\\\\\n \\\\n try:\\\\\n \\\\n load_data_loc = deploy_dict['load_data']['Status']['DataFilePath']\\\\\n \\\\n except KeyError:\\\\\n \\\\n raise ValueError('DataIngestion step output is corrupted')\\\\\n \\\\n\\\\\n \\\\ndef get_digest(fname):\\\\\n \\\\n import hashlib\\\\\n \\\\n hash_algo = hashlib.sha256()\\\\\n \\\\n with open(fname, 'rb') as f:\\\\\n \\\\n for chunk in iter(lambda: f.read(2 ** 20), b''):\\\\\n \\\\n hash_algo.update(chunk)\\\\\n \\\\n return hash_algo.hexdigest()\\\\\n \\\\n\"\n \n def getCode(self, indent=1):\n return self.function_code + '\\\\n' + self.codeText\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nclass global_function():\n\n def __init__(self, tab_size=4):\n self.tab = ' ' * tab_size\n self.codeText = \"\"\n self.available_functions = {\n 'iqr':{'name':'iqrOutlier','code':f\"\\\\n\\\\ndef iqrOutlier(df):\\\\\n \\\\n{self.tab}Q1 = df.quantile(0.25)\\\\\n \\\\n{self.tab}Q3 = df.quantile(0.75)\\\\\n \\\\n{self.tab}IQR = Q3 - Q1\\\\\n \\\\n{self.tab}index = ~((df < (Q1 - 1.5 * IQR)) |(df > (Q3 + 1.5 * IQR))).any(axis=1)\\\\\n \\\\n{self.tab}return index\"},\n 'zscore':{'name':'zscoreOutlier','imports':[{'mod':'stats','mod_from':'scipy'},{'mod':'numpy'}],'code':f\"\\\\n\\\\ndef zscoreOutlier(df):\\\\\n \\\\n{self.tab}z = numpy.abs(stats.zscore(df))\\\\\n \\\\n{self.tab}index = (z < 3).all(axis=1)\\\\\n \\\\n{self.tab}return index\"},\n 'iforest':{'name':'iforestOutlier','imports':[{'mod':'IsolationForest','mod_from':'sklearn.ensemble'}],'code':f\"\\\\n\\\\ndef iforestOutlier(df):\\\\\n \\\\n{self.tab}from sklearn.ensemble import IsolationForest\\\\\n \\\\n{self.tab}isolation_forest = IsolationForest(n_estimators=100)\\\\\n \\\\n{self.tab}isolation_forest.fit(df)\\\\\n \\\\n{self.tab}y_pred_train = isolation_forest.predict(df)\\\\\n \\\\n{self.tab}return y_pred_train == 1\"},\n 'minMaxImputer':{'name':'minMaxImputer','code':f\"\\\\n\\\\nclass minMaxImputer(TransformerMixin):\\\\\n \\\\n{self.tab}def __init__(self, strategy='max'):\\\\\n \\\\n{self.tab}{self.tab}self.strategy = strategy\\\\\n \\\\n{self.tab}def fit(self, X, y=None):\\\\\n \\\\n{self.tab}{self.tab}self.feature_names_in_ = X.columns\\\\\n \\\\n{self.tab}{self.tab}if self.strategy == 'min':\\\\\n \\\\n{self.tab}{self.tab}{self.tab}self.statistics_ = X.min()\\\\\n \\\\n{self.tab}{self.tab}else:\\\\\n \\\\n{self.tab}{self.tab}{self.tab}self.statistics_ = X.max()\\\\\n \\\\n{self.tab}{self.tab}return self\\\\\n \\\\n{self.tab}def transform(self, X):\\\\\n \\\\n{self.tab}{self.tab}import numpy\\\\\n \\\\n{self.tab}{self.tab}return numpy.where(X.isna(), self.statistics_, X)\"},\n 'DummyEstimator':{'name':'DummyEstimator','code':f\"\\\\n\\\\nclass DummyEstimator(BaseEstimator):\\\\\n \\\\n{self.tab}def fit(self): pass\\\\\n \\\\n{self.tab}def score(self): pass\"},\n 'start_reducer':{'name':'start_reducer','imports':[{'mod':'itertools'},{'mod':'numpy','mod_as':'np'},{'mod':'pandas','mod_as':'pd'},{'mod':'VarianceThreshold','mod_from':'sklearn.feature_selection'}], 'code':\"\"\"\ndef start_reducer(df,target_feature,corr_threshold=0.85,var_threshold=0.05):\n\n qconstantColumns = []\n train_features = df.columns.tolist()\n train_features.remove(target_feature)\n df = df.loc[:, (df != df.iloc[0]).any()] #remove constant feature\n numeric_features = df.select_dtypes(include='number').columns.tolist()\n non_numeric_features = df.select_dtypes(exclude='number').columns.tolist()\n if numeric_features and var_threshold:\n qconstantFilter = VarianceThreshold(threshold=var_threshold)\n tempDf=df[numeric_features]\n qconstantFilter.fit(tempDf)\n qconstantColumns = [column for column in numeric_features if column not in tempDf.columns[qconstantFilter.get_support()]]\n if target_feature in qconstantColumns:\n qconstantColumns.remove(target_feature)\n numeric_features = list(set(numeric_features) - set(qconstantColumns))\n if numeric_features:\n numColPairs = list(itertools.product(numeric_features, numeric_features))\n for item in numColPairs:\n if(item[0] == item[1]):\n numColPairs.remove(item)\n tempArray = []\n for item in numColPairs:\n tempCorr = np.abs(df[item[0]].corr(df[item[1]]))\n if(tempCorr > corr_threshold):\n tempArray.append(item[0])\n tempArray = np.unique(tempArray).tolist()\n nonsimilarNumericalCols = list(set(numeric_features) - set(tempArray))\n groupedFeatures = []\n if tempArray:\n corrDic = {}\n for feature in tempArray:\n temp = []\n for col in tempArray:\n tempCorr = np.abs(df[feature].corr(df[col]))\n temp.append(tempCorr)\n corrDic[feature] = temp\n #Similar correlation df\n corrDF = pd.DataFrame(corrDic,index = tempArray)\n corrDF.loc[:,:] = np.tril(corrDF, k=-1)\n alreadyIn = set()\n similarFeatures = []\n for col in corrDF:\n perfectCorr = corrDF[col][corrDF[col] > corr_threshold].index.tolist()\n if perfectCorr and col not in alreadyIn:\n alreadyIn.update(set(perfectCorr))\n perfectCorr.append(col)\n similarFeatures.append(perfectCorr)\n updatedSimFeatures = []\n for items in similarFeatures:\n if(target_feature != '' and target_feature in items):\n for p in items:\n updatedSimFeatures.append(p)\n else:\n updatedSimFeatures.append(items[0])\n newTempFeatures = list(set(updatedSimFeatures + nonsimilarNumericalCols))\n updatedFeatures = list(set(newTempFeatures + non_numeric_features))\n else:\n updatedFeatures = list(set(df.columns) -set(qconstantColumns))\n else:\n updatedFeatures = list(set(df.columns) -set(qconstantColumns))\n return updatedFeatures\n \"\"\"},\n 'feature_importance_class':{'name':'feature_importance_class','code':\"\\\\n\\\\\n \\\\ndef feature_importance_class(df, numeric_features, cat_features,target_feature,", "instruction": "", "output": "" }, { "input": "pValTh,corrTh):\\\\\n \\\\n import pandas as pd\\\\\n \\\\n from sklearn.feature_selection import chi2\\\\\n \\\\n from sklearn.feature_selection import f_classif\\\\\n \\\\n from sklearn.feature_selection import mutual_info_classif\\\\\n \\\\n \\\\\n \\\\n impFeatures = []\\\\\n \\\\n if cat_features:\\\\\n \\\\n categoricalData=df[cat_features]\\\\\n \\\\n chiSqCategorical=chi2(categoricalData,df[target_feature])[1]\\\\\n \\\\n corrSeries=pd.Series(chiSqCategorical, index=cat_features)\\\\\n \\\\n impFeatures.append(corrSeries[corrSeriescorrTh].index.tolist())\\\\\n \\\\n pearsonScore=df.corr() \\\\\n \\\\n targetPScore=abs(pearsonScore[target_feature])\\\\\n \\\\n impFeatures.append(targetPScore[targetPScorecorrTh].index.tolist())\\\\\n \\\\n pearsonScore=df.corr()\\\\\n \\\\n targetPScore=abs(pearsonScore[target_feature])\\\\\n \\\\n impFeatures.append(targetPScore[targetPScore 2):\\\\\n \\\\n score_param = make_scorer(roc_auc_score, needs_proba=True,multi_class='ovr',average='weighted')\\\\\n \\\\n else:\\\\\n \\\\n class_type = 'binary_class' if class_count == 2 else 'multi_class'\\\\\n \\\\n if score_param in scorer_mapping.keys():\\\\\n \\\\n score_param = scorer_mapping[score_param][class_type]\\\\\n \\\\n else:\\\\\n \\\\n score_param = 'accuracy'\\\\\n \\\\n return score_param\"},\n 'log_dataframe':{'name':'log_dataframe','code':f\"\\\\n\\\\\n \\\\ndef log_dataframe(df, msg=None):\\\\\n \\\\n import io\\\\\n \\\\n buffer = io.StringIO()\\\\\n \\\\n df.info(buf=buffer)\\\\\n \\\\n if msg:\\\\\n \\\\n log_text = f'Data frame after {{msg}}:'\\\\\n \\\\n else:\\\\\n \\\\n log_text = 'Data frame:'\\\\\n \\\\n log_text += '\\\\\\\\n\\\\\\\\t'+str(df.head(2)).replace('\\\\\\\\n','\\\\\\\\n\\\\\\\\t')\\\\\n \\\\n log_text += ('\\\\\\\\n\\\\\\\\t' + buffer.getvalue().replace('\\\\\\\\n','\\\\\\\\n\\\\\\\\t'))\\\\\n \\\\n get_logger().info(log_text)\"},\n 'BayesSearchCV':{'name':'BayesSearchCV','imports':[{'mod':'cross_val_score','mod_from':'sklearn.model_selection'},{'mod':'fmin','mod_from':'hyperopt'},{'mod':'tpe','mod_from':'hyperopt'},{'mod':'hp','mod_from':'hyperopt'},{'mod':'STATUS_OK','mod_from':'hyperopt'},{'mod':'Trials','mod_from':'hyperopt'},{'mod':'numpy','mod_as':'np'}],'code':\"\\\\n\\\\\n \\\\nclass BayesSearchCV():\\\\\n \\\\n\\\\\n \\\\n def __init__(self, estimator, params, scoring, n_iter, cv):\\\\\n \\\\n self.estimator = estimator\\\\\n \\\\n self.params = params\\\\\n \\\\n self.scoring = scoring\\\\\n \\\\n self.iteration = n_iter\\\\\n \\\\n self.cv = cv\\\\\n \\\\n self.best_estimator_ = None\\\\\n \\\\n self.best_score_ = None\\\\\n \\\\n self.best_params_ = None\\\\\n \\\\n\\\\\n \\\\n def __min_fun(self, params):\\\\\n \\\\n score=cross_val_score(self.estimator, self.X, self.y,scoring=self.scoring,cv=self.cv)\\\\\n \\\\n acc = score.mean()\\\\\n \\\\n return {'loss':-acc,'score': acc, 'status': STATUS_OK,'model' :self.estimator,'params': params}\\\\\n \\\\n\\\\\n \\\\n def fit(self, X, y):\\\\\n \\\\n trials = Trials()\\\\\n \\\\n self.X = X\\\\\n \\\\n self.y = y\\\\\n \\\\n best = fmin(self.__min_fun,self.params,algo=tpe.suggest, max_evals=self.iteration, trials=trials)\\\\\n \\\\n result = sorted(trials.results, key = lambda x: x['loss'])[0]\\\\\n \\\\n self.best_estimator_ = result['model']\\\\\n \\\\n self.best_score_ = result['score']\\\\\n \\\\n self.best_params_ = result['params']\\\\\n \\\\n self.best_estimator_.fit(X, y)\\\\\n \\\\n\\\\\n \\\\n def hyperOptParamConversion( paramSpace):\\\\\n \\\\n paramDict = {}\\\\\n \\\\n for j in list(paramSpace.keys()):\\\\\n \\\\n inp = paramSpace[j]\\\\\n \\\\n isLog = False\\\\\n \\\\n isLin = False\\\\\n \\\\n isRan = False\\\\\n \\\\n isList = False\\\\\n \\\\n isString = False\\\\\n \\\\n try:\\\\\n \\\\n # check if functions are given as input and reassign paramspace\\\\\n \\\\n v = paramSpace[j]\\\\\n \\\\n if 'logspace' in paramSpace[j]:\\\\\n \\\\n paramSpace[j] = v[v.find('(') + 1:v.find(')')].replace(' ', '')\\\\\n \\\\n isLog = True\\\\\n \\\\n elif 'linspace' in paramSpace[j]:\\\\\n \\\\n paramSpace[j] = v[v.find('(') + 1:v.find(')')].replace(' ', '')\\\\\n \\\\n isLin = True\\\\\n \\\\n elif 'range' in paramSpace[j]:\\\\\n \\\\n paramSpace[j] = v[v.find('(') + 1:v.find(')')].replace(' ', '')\\\\\n \\\\n isRan = True\\\\\n \\\\n elif 'list' in paramSpace[j]:\\\\\n \\\\n paramSpace[j] = v[v.find('(') + 1:v.find(')')].replace(' ', '')\\\\\n \\\\n isList = True\\\\\n \\\\n elif '[' and ']' in paramSpace[j]:\\\\\n \\\\n paramSpace[j] = v.split('[')[1].split(']')[0].replace(' ', '')\\\\\n \\\\n isList = True\\\\\n \\\\n x = paramSpace[j].split(',')\\\\\n \\\\n except:\\\\\n \\\\n x = paramSpace[j]\\\\\n \\\\n str_arg = paramSpace[j]\\\\\n \\\\n\\\\\n \\\\n # check if arguments are string\\\\\n \\\\n try:\\\\\n \\\\n test = eval(x[0])\\\\\n \\\\n except:\\\\\n \\\\n isString = True\\\\\n \\\\n\\\\\n \\\\n if isString:\\\\\n \\\\n paramDict.update({j: hp.choice(j, x)})\\\\\n \\\\n else:\\\\\n \\\\n res = eval(str_arg)\\\\\n \\\\n if isLin:\\\\\n \\\\n y = eval('np.linspace' + str(res))\\\\\n \\\\n paramDict.update({j: hp.uniform(j, eval(x[0]), eval(x[1]))})\\\\\n \\\\n elif isLog:\\\\\n \\\\n y = eval('np.logspace' + str(res))\\\\\n \\\\n paramDict.update(\\\\\n \\\\n {j: hp.uniform(j, 10 ** eval(x[0]), 10 ** eval(x[1]))})\\\\\n \\\\n elif isRan:\\\\\n \\\\n y = eval('np.arange' + str(res))\\\\\n \\\\n paramDict.update({j: hp.choice(j, y)})\\\\\n \\\\n # check datatype of argument\\\\\n \\\\n elif isinstance(eval(x[0]), bool):\\\\\n \\\\n y = list(map(lambda i: eval(i), x))\\\\\n \\\\n paramDict.update({j: hp.choice(j, eval(str(y)))})\\\\\n \\\\n elif isinstance(eval(x[0]), float):\\\\\n \\\\n res = eval(str_arg)\\\\\n \\\\n if len(str_arg.split(',')) == 3 and not isList:\\\\\n \\\\n y = eval('np.linspace' + str(res))\\\\\n \\\\n #print(y)\\\\\n \\\\n paramDict.update({j: hp.uniform(j, eval(x[0]), eval(x[1]))})\\\\\n \\\\n else:\\\\\n \\\\n y = list(res) if isinstance(res, tuple) else [res]\\\\\n \\\\n paramDict.update({j: hp.choice(j, y)})\\\\\n \\\\n else:\\\\\n \\\\n res = eval(str_arg)\\\\\n \\\\n if len(str_arg.split(',')) == 3 and not isList:\\\\\n \\\\n y = eval('np.linspace' +str(res)) if eval(x[2]) >= eval(x[1]) else eval('np.arange'+str(res))\\\\\n \\\\n else:\\\\\n \\\\n y = list(res) if isinstance(res, tuple) else [res]\\\\\n \\\\n paramDict.update({j: hp.choice(j, y)})\\\\\n \\\\n return paramDict\"},\n 's2n':{'name':'s2n','imports':[{'mod':'word2number','mod_as':'w2n'},{'mod':'numpy','mod_as':'np'}],'code':\"\\\\n\\\\\n \\\\ndef s2n(value):\\\\\n \\\\n try:\\\\\n \\\\n x=eval(value)\\\\\n \\\\n return x\\\\\n \\\\n except:\\\\\n \\\\n try:\\\\\n \\\\n return w2n.word_to_num(value)\\\\\n \\\\n except:\\\\\n \\\\n return np.nan\"},\n 'readWrite':{'name':'readWrite','imports':[{'mod':'json'},{'mod':'pandas','mod_as':'pd'}],'code':\"\\\\n\\\\\n \\\\ndef read_json(file_path):\\\\\n \\\\n data = None\\\\\n \\\\n with open(file_path,'r') as f:\\\\\n \\\\n data = json.load(f)\\\\\n \\\\n return data\\\\\n \\\\n\\\\\n \\\\ndef write_json(data, file_path):\\\\\n \\\\n with open(file_path,'w') as f:\\\\\n \\\\n json.dump(data, f)\\\\\n \\\\n\\\\\n \\\\ndef read_data(file_path, encoding='utf-8', sep=','):\\\\\n \\\\n return pd.read_csv(file_path, encoding=encoding, sep=sep)\\\\\n \\\\n\\\\\n \\\\ndef write_data(data, file_path, index=False):\\\\\n \\\\n return data.to_csv(file_path, index=index)\\\\\n \\\\n\\\\\n \\\\n#Uncomment and change below code for google storage\\\\\n \\\\n#def write_data(data, file_path, index=False):\\\\\n \\\\n# file_name= file_path.name\\\\\n \\\\n# data.to_csv('output_data.csv')\\\\\n \\\\n# storage_client = storage.Client()\\\\\n \\\\n# bucket = storage_client.bucket('aion_data')\\\\\n \\\\n# bucket.blob('prediction/'+file_name).upload_from_filename('output_data.csv', content_type='text/csv')\\\\\n \\\\n# return data\\\\\n \\\\n\\\\\n \\\\ndef is_file_name_url(file_name):\\\\\n \\\\n supported_urls_starts_with = ('gs://','https://','http://')\\\\", "instruction": "", "output": "" }, { "input": "\n \\\\n return file_name.startswith(supported_urls_starts_with)\\\\\n \\\\n\"},\n 'logger':{'name':'set_logger','imports':[{'mod':'logging'}],'code':f\"\\\\n\\\\\n \\\\nlog = None\\\\\n \\\\ndef set_logger(log_file, mode='a'):\\\\\n \\\\n global log\\\\\n \\\\n logging.basicConfig(filename=log_file, filemode=mode, format='%(asctime)s %(name)s- %(message)s', level=logging.INFO, datefmt='%d-%b-%y %H:%M:%S')\\\\\n \\\\n log = logging.getLogger(Path(__file__).parent.name)\\\\\n \\\\n return log\\\\\n \\\\n\\\\\n \\\\ndef get_logger():\\\\\n \\\\n return log\\\\n\"},\n 'mlflowSetPath':{'name':'mlflowSetPath','code':f\"\\\\n\\\\ndef mlflowSetPath(path, name):\\\\\n \\\\n{self.tab}db_name = str(Path(path)/'mlruns')\\\\\n \\\\n{self.tab}mlflow.set_tracking_uri('file:///' + db_name)\\\\\n \\\\n{self.tab}mlflow.set_experiment(str(Path(path).name))\\\\\n \\\\n\"},\n 'mlflow_create_experiment':{'name':'mlflow_create_experiment','code':f\"\\\\n\\\\ndef mlflow_create_experiment(config, path, name):\\\\\n \\\\n{self.tab}tracking_uri, artifact_uri, registry_uri = get_mlflow_uris(config, path)\\\\\n \\\\n{self.tab}mlflow.tracking.set_tracking_uri(tracking_uri)\\\\\n \\\\n{self.tab}mlflow.tracking.set_registry_uri(registry_uri)\\\\\n \\\\n{self.tab}client = mlflow.tracking.MlflowClient()\\\\\n \\\\n{self.tab}experiment = client.get_experiment_by_name(name)\\\\\n \\\\n{self.tab}if experiment:\\\\\n \\\\n{self.tab}{self.tab}experiment_id = experiment.experiment_id\\\\\n \\\\n{self.tab}else:\\\\\n \\\\n{self.tab}{self.tab}experiment_id = client.create_experiment(name, artifact_uri)\\\\\n \\\\n{self.tab}return client, experiment_id\\\\\n \\\\n\"},\n 'get_mlflow_uris':{'name':'get_mlflow_uris','code':f\"\\\\n\\\\ndef get_mlflow_uris(config, path):\\\\\n \\\\n artifact_uri = None\\\\\n \\\\n tracking_uri_type = config.get('tracking_uri_type',None)\\\\\n \\\\n if tracking_uri_type == 'localDB':\\\\\n \\\\n tracking_uri = 'sqlite:///' + str(path.resolve()/'mlruns.db')\\\\\n \\\\n elif tracking_uri_type == 'server' and config.get('tracking_uri', None):\\\\\n \\\\n tracking_uri = config['tracking_uri']\\\\\n \\\\n if config.get('artifacts_uri', None):\\\\\n \\\\n if Path(config['artifacts_uri']).exists():\\\\\n \\\\n artifact_uri = 'file:' + config['artifacts_uri']\\\\\n \\\\n else:\\\\\n \\\\n artifact_uri = config['artifacts_uri']\\\\\n \\\\n else:\\\\\n \\\\n artifact_uri = 'file:' + str(path.resolve()/'mlruns')\\\\\n \\\\n else:\\\\\n \\\\n tracking_uri = 'file:' + str(path.resolve()/'mlruns')\\\\\n \\\\n artifact_uri = None\\\\\n \\\\n if config.get('registry_uri', None):\\\\\n \\\\n registry_uri = config['registry_uri']\\\\\n \\\\n else:\\\\\n \\\\n registry_uri = 'sqlite:///' + str(path.resolve()/'registry.db')\\\\\n \\\\n return tracking_uri, artifact_uri, registry_uri\\\\\n \\\\n\"},\n 'logMlflow':{'name':'logMlflow','code':f\"\\\\n\\\\ndef logMlflow( params, metrices, estimator,tags={{}}, algoName=None):\\\\\n \\\\n{self.tab}run_id = None\\\\\n \\\\n{self.tab}for k,v in params.items():\\\\\n \\\\n{self.tab}{self.tab}mlflow.log_param(k, v)\\\\\n \\\\n{self.tab}for k,v in metrices.items():\\\\\n \\\\n{self.tab}{self.tab}mlflow.log_metric(k, v)\\\\\n \\\\n{self.tab}if 'CatBoost' in algoName:\\\\\n \\\\n{self.tab}{self.tab}model_info = mlflow.catboost.log_model(estimator, 'model')\\\\\n \\\\n{self.tab}else:\\\\\n \\\\n{self.tab}{self.tab}model_info = mlflow.sklearn.log_model(sk_model=estimator, artifact_path='model')\\\\\n \\\\n{self.tab}tags['processed'] = 'no'\\\\\n \\\\n{self.tab}tags['registered'] = 'no'\\\\\n \\\\n{self.tab}mlflow.set_tags(tags)\\\\\n \\\\n{self.tab}if model_info:\\\\\n \\\\n{self.tab}{self.tab}run_id = model_info.run_id\\\\\n \\\\n{self.tab}return run_id\\\\\n \\\\n\"},\n 'classification_metrices':{'name':'classification_metrices','imports':[{'mod':'sklearn'},{'mod':'math'}],'code':\"\\\\ndef get_classification_metrices( actual_values, predicted_values):\\\\\n \\\\n result = {}\\\\\n \\\\n accuracy_score = sklearn.metrics.accuracy_score(actual_values, predicted_values)\\\\\n \\\\n avg_precision = sklearn.metrics.precision_score(actual_values, predicted_values,\\\\\n \\\\n average='macro')\\\\\n \\\\n avg_recall = sklearn.metrics.recall_score(actual_values, predicted_values,\\\\\n \\\\n average='macro')\\\\\n \\\\n avg_f1 = sklearn.metrics.f1_score(actual_values, predicted_values,\\\\\n \\\\n average='macro')\\\\\n \\\\n\\\\\n \\\\n result['accuracy'] = math.floor(accuracy_score*10000)/100\\\\\n \\\\n result['precision'] = math.floor(avg_precision*10000)/100\\\\\n \\\\n result['recall'] = math.floor(avg_recall*10000)/100\\\\\n \\\\n result['f1'] = math.floor(avg_f1*10000)/100\\\\\n \\\\n return result\\\\\n \\\\n\"},\n 'regression_metrices':{'name':'regression_metrices','imports':[{'mod':'numpy', 'mod_as':'np'}],'code':\"\\\\ndef get_regression_metrices( actual_values, predicted_values):\\\\\n \\\\n result = {}\\\\\n \\\\n\\\\\n \\\\n me = np.mean(predicted_values - actual_values)\\\\\n \\\\n sde = np.std(predicted_values - actual_values, ddof = 1)\\\\\n \\\\n\\\\\n \\\\n abs_err = np.abs(predicted_values - actual_values)\\\\\n \\\\n mae = np.mean(abs_err)\\\\\n \\\\n sdae = np.std(abs_err, ddof = 1)\\\\\n \\\\n\\\\\n \\\\n abs_perc_err = 100.*np.abs(predicted_values - actual_values) / actual_values\\\\\n \\\\n mape = np.mean(abs_perc_err)\\\\\n \\\\n sdape = np.std(abs_perc_err, ddof = 1)\\\\\n \\\\n\\\\\n \\\\n result['mean_error'] = me\\\\\n \\\\n result['mean_abs_error'] = mae\\\\\n \\\\n result['mean_abs_perc_error'] = mape\\\\\n \\\\n result['error_std'] = sde\\\\\n \\\\n result['abs_error_std'] = sdae\\\\\n \\\\n result['abs_perc_error_std'] = sdape\\\\\n \\\\n return result\\\\\n \\\\n\"}\n }\n \n def add_function(self, name, importer=None):\n if name in self.available_functions.keys():\n self.codeText += self.available_functions[name]['code']\n if importer:\n if 'imports' in self.available_functions[name].keys():\n for module in self.available_functions[name]['imports']:\n mod_name = module['mod']\n mod_from = module.get('mod_from', None)\n mod_as = module.get('mod_as', None)\n importer.addModule(mod_name, mod_from=mod_from, mod_as=mod_as)\n \n def get_function_name(self, name):\n if name in self.available_functions.keys():\n return self.available_functions[name]['name']\n return None\n \n def getCode(self):\n return self.codeText\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\nfrom .imports import importModule\n\nutility_functions = {\n'load_data': ['read_json','write_json','read_data','write_data','is_file_name_url','logger_class'],\n'transformer': ['read_json','write_json','read_data','write_data','is_file_name_url','logger_class'],\n'selector': ['read_json','write_json','read_data','write_data','is_file_name_url','logger_class'],\n'train': ['read_json','write_json','read_data','write_data','is_file_name_url','logger_class'],\n'register': ['read_json','write_json','read_data','write_data','is_file_name_url','logger_class'],\n'Prediction': ['read_json','write_json','read_data','write_data','is_file_name_url','logger_class'],\n'drift': ['read_json','write_json','read_data','write_data','is_file_name_url','logger_class'],\n}\n\n#TODO convert read and write functions in to class functions\nfunctions_code = {\n 'read_json':{'imports':[{'mod':'json'}],'code':\"\\\\n\\\\\n \\\\ndef read_json(file_path):\\\\\n \\\\n data = None\\\\\n \\\\n with open(file_path,'r') as f:\\\\\n \\\\n data = json.load(f)\\\\\n \\\\n return data\\\\\n \\\\n\"},\n 'write_json':{'imports':[{'mod':'json'}],'code':\"\\\\n\\\\\n \\\\ndef write_json(data, file_path):\\\\\n \\\\n with open(file_path,'w') as f:\\\\\n \\\\n json.dump(data, f)\\\\\n \\\\n\"},\n 'read_data':{'imports':[{'mod':'pandas','mod_as':'pd'}],'code':\"\\\\n\\\\\n \\\\ndef read_data(file_path, encoding='utf-8', sep=','):\\\\\n \\\\n return pd.read_csv(file_path, encoding=encoding, sep=sep)\\\\\n \\\\n\"},\n 'write_data':{'imports':[{'mod':'pandas','mod_as':'pd'}],'code':\"\\\\n\\\\\n \\\\ndef write_data(data, file_path, index=False):\\\\\n \\\\n return data.to_csv(file_path, index=index)\\\\\n \\\\n\\\\\n \\\\n#Uncomment and change below code for google storage\\\\\n \\\\n#from google.cloud import storage\\\\\n \\\\n#def write_data(data, file_path, index=False):\\\\\n \\\\n# file_name= file_path.name\\\\\n \\\\n# data.to_csv('output_data.csv')\\\\\n \\\\n# storage_client = storage.Client()\\\\\n \\\\n# bucket = storage_client.bucket('aion_data')\\\\\n \\\\n# bucket.blob('prediction/'+file_name).upload_from_filename('output_data.csv', content_type='text/csv')\\\\\n \\\\n# return data\\\\\n \\\\n\"},\n 'is_file_name_url':{'imports':[],'code':\"\\\\n\\\\\n \\\\ndef is_file_name_url(file_name):\\\\\n \\\\n supported_urls_starts_with = ('gs://','https://','http://')\\\\\n \\\\n return file_name.startswith(supported_urls_starts_with)\\\\\n \\\\n\"},\n 'logger_class':{'imports':[{'mod':'logging'}, {'mod':'io'}],'code':\"\\\\n\\\\\n \\\\nclass logger():\\\\\n \\\\n #setup the logger\\\\\n \\\\n def __init__(self, log_file, mode='w', logger_name=None):\\\\\n \\\\n logging.basicConfig(filename=log_file, filemode=mode, format='%(asctime)s %(name)s- %(message)s', level=logging.INFO, datefmt='%d-%b-%y %H:%M:%S')\\\\\n \\\\n self.log = logging.getLogger(logger_name)\\\\\n \\\\n\\\\\n \\\\n #get logger\\\\\n \\\\n def getLogger(self):\\\\\n \\\\n return self.log\\\\\n \\\\n\\\\\n \\\\n def info(self, msg):\\\\\n \\\\n self.log.info(msg)\\\\\n \\\\n\\\\\n \\\\n def error(self, msg, exc_info=False):\\\\\n \\\\n self.log.error(msg,exc_info)\\\\\n \\\\n\\\\\n \\\\n # format and log dataframe\\\\\n \\\\n def log_dataframe(self, df, rows=2, msg=None):\\\\\n \\\\n buffer = io.StringIO()\\\\\n \\\\n df.info(buf=buffer)\\\\\n \\\\n log_text = 'Data frame{}'.format(' after ' + msg + ':' if msg else ':')\\\\\n \\\\n log_text += '\\\\\\\\n\\\\\\\\t'+str(df.head(rows)).replace('\\\\\\\\n','\\\\\\\\n\\\\\\\\t')\\\\\n \\\\n log_text += ('\\\\\\\\n\\\\\\\\t' + buffer.getvalue().replace('\\\\\\\\n','\\\\\\\\n\\\\\\\\t'))\\\\\n \\\\n self.log.info(log_text)\\\\\n \\\\n\"},\n}\n \nclass utility_function():\n\n def __init__(self, module):\n if module in utility_functions.keys():\n self.module_name = module\n else:\n self.module_name = None\n self.importer = importModule()\n self.codeText = \"\"\n \n def get_code(self):\n code = \"\"\n if self.module_name:\n functions = utility_functions[self.module_name]\n for function in functions:\n self.codeText += self.get_function_code(function)\n code = self.importer.getCode()\n code += self.codeText\n return code\n \n def get_function_code(self, name):\n code = \"\"\n if name in functions_code.keys():\n ", "instruction": "", "output": "" }, { "input": "code += functions_code[name]['code']\n if self.importer:\n if 'imports' in functions_code[name].keys():\n for module in functions_code[name]['imports']:\n mod_name = module['mod']\n mod_from = module.get('mod_from', None)\n mod_as = module.get('mod_as', None)\n self.importer.addModule(mod_name, mod_from=mod_from, mod_as=mod_as)\n return code\n\n def get_importer(self):\n return self.importer\n\nif __name__ == '__main__':\n obj = utility_function('load_data')\n p = obj.get_utility_code()\n print(p) \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nclass output_drift():\n\n def __init__(self, missing=False, word2num_features = None, cat_encoder=False, target_encoder=False, normalizer=False, text_profiler=False, feature_reducer=False, score_smaller_is_better=True, problem_type='classification', tab_size=4):\n self.tab = ' ' * tab_size\n self.codeText = ''\n self.missing = missing\n self.word2num_features = word2num_features\n self.cat_encoder = cat_encoder\n self.target_encoder = target_encoder\n self.normalizer = normalizer\n self.text_profiler = text_profiler\n self.feature_reducer = feature_reducer\n self.score_smaller_is_better = score_smaller_is_better\n self.problem_type = problem_type\n \n def addDatabaseClass(self, indent=0):\n text = \"\\\\\n \\\\nclass database():\\\\\n \\\\n def __init__(self, config):\\\\\n \\\\n self.host = config['host']\\\\\n \\\\n self.port = config['port']\\\\\n \\\\n self.user = config['user']\\\\\n \\\\n self.password = config['password']\\\\\n \\\\n self.database = config['database']\\\\\n \\\\n self.measurement = config['measurement']\\\\\n \\\\n self.tags = config['tags']\\\\\n \\\\n self.client = self.get_client()\\\\\n \\\\n\\\\\n \\\\n def read_data(self, query)->pd.DataFrame:\\\\\n \\\\n cursor = self.client.query(query)\\\\\n \\\\n points = cursor.get_points()\\\\\n \\\\n my_list=list(points)\\\\\n \\\\n df=pd.DataFrame(my_list)\\\\\n \\\\n return df\\\\\n \\\\n\\\\\n \\\\n def get_client(self):\\\\\n \\\\n client = InfluxDBClient(self.host,self.port,self.user,self.password)\\\\\n \\\\n databases = client.get_list_database()\\\\\n \\\\n databases = [x['name'] for x in databases]\\\\\n \\\\n if self.database not in databases:\\\\\n \\\\n client.create_database(self.database)\\\\\n \\\\n return InfluxDBClient(self.host,self.port,self.user,self.password, self.database)\\\\\n \\\\n\\\\\n \\\\n def write_data(self,data):\\\\\n \\\\n if isinstance(data, pd.DataFrame):\\\\\n \\\\n sorted_col = data.columns.tolist()\\\\\n \\\\n sorted_col.sort()\\\\\n \\\\n data = data[sorted_col]\\\\\n \\\\n data = data.to_dict(orient='records')\\\\\n \\\\n for row in data:\\\\\n \\\\n if 'time' in row.keys():\\\\\n \\\\n p = '%Y-%m-%dT%H:%M:%S.%fZ'\\\\\n \\\\n time_str = datetime.strptime(row['time'], p)\\\\\n \\\\n del row['time']\\\\\n \\\\n else:\\\\\n \\\\n time_str = None\\\\\n \\\\n if 'model_ver' in row.keys():\\\\\n \\\\n self.tags['model_ver']= row['model_ver']\\\\\n \\\\n del row['model_ver']\\\\\n \\\\n json_body = [{\\\\\n \\\\n 'measurement': self.measurement,\\\\\n \\\\n 'time': time_str,\\\\\n \\\\n 'tags': self.tags,\\\\\n \\\\n 'fields': row\\\\\n \\\\n }]\\\\\n \\\\n self.client.write_points(json_body)\\\\\n \\\\n\\\\\n \\\\n def close(self):\\\\\n \\\\n self.client.close()\\\\\n \\\\n\"\n if indent:\n text = text.replace('\\\\n', (self.tab * indent) + '\\\\n')\n return text\n\n def addPredictClass(self, indent=0):\n text = \"\\\\\n \\\\nclass predict():\\\\\n \\\\n\\\\\n \\\\n def __init__(self, base_config):\\\\\n \\\\n self.usecase = base_config['modelName'] + '_' + base_config['modelVersion']\\\\\n \\\\n self.dataLocation = base_config['dataLocation']\\\\\n \\\\n self.db_enabled = base_config.get('db_enabled', False)\\\\\n \\\\n if self.db_enabled:\\\\\n \\\\n self.db_config = base_config['db_config']\\\\\n \\\\n home = Path.home()\\\\\n \\\\n if platform.system() == 'Windows':\\\\\n \\\\n from pathlib import WindowsPath\\\\\n \\\\n output_data_dir = WindowsPath(home)/'AppData'/'Local'/'HCLT'/'AION'/'Data'\\\\\n \\\\n output_model_dir = WindowsPath(home)/'AppData'/'Local'/'HCLT'/'AION'/'target'/self.usecase\\\\\n \\\\n else:\\\\\n \\\\n from pathlib import PosixPath\\\\\n \\\\n output_data_dir = PosixPath(home)/'HCLT'/'AION'/'Data'\\\\\n \\\\n output_model_dir = PosixPath(home)/'HCLT'/'AION'/'target'/self.usecase\\\\\n \\\\n if not output_model_dir.exists():\\\\\n \\\\n raise ValueError(f'Configuration file not found at {output_model_dir}')\\\\\n \\\\n\\\\\n \\\\n tracking_uri = 'file:///' + str(Path(output_model_dir)/'mlruns')\\\\\n \\\\n registry_uri = 'sqlite:///' + str(Path(output_model_dir)/'mlruns.db')\\\\\n \\\\n mlflow.set_tracking_uri(tracking_uri)\\\\\n \\\\n mlflow.set_registry_uri(registry_uri)\\\\\n \\\\n client = mlflow.tracking.MlflowClient(\\\\\n \\\\n tracking_uri=tracking_uri,\\\\\n \\\\n registry_uri=registry_uri,\\\\\n \\\\n )\\\\\n \\\\n self.model_version = client.get_latest_versions(self.usecase, stages=['production'] )[0].version\\\\\n \\\\n model_version_uri = 'models:/{model_name}/production'.format(model_name=self.usecase)\\\\\n \\\\n self.model = mlflow.pyfunc.load_model(model_version_uri)\\\\\n \\\\n run = client.get_run(self.model.metadata.run_id)\\\\\n \\\\n if run.info.artifact_uri.startswith('file:'): #remove file:///\\\\\n \\\\n self.artifact_path = Path(run.info.artifact_uri[len('file:///') : ])\\\\\n \\\\n else:\\\\\n \\\\n self.artifact_path = Path(run.info.artifact_uri)\\\\\n \\\\n with open(self.artifact_path/'deploy.json', 'r') as f:\\\\\n \\\\n deployment_dict = json.load(f)\\\\\n \\\\n with open(self.artifact_path/'features.txt', 'r') as f:\\\\\n \\\\n self.train_features = f.readline().rstrip().split(',')\\\\\n \\\\n\\\\\n \\\\n self.dataLocation = base_config['dataLocation']\\\\\n \\\\n self.selected_features = deployment_dict['load_data']['selected_features']\\\\\n \\\\n self.target_feature = deployment_dict['load_data']['target_feature']\\\\\n \\\\n self.output_model_dir = output_model_dir\"\n if self.missing:\n text += \"\\\\n self.missing_values = deployment_dict['transformation']['fillna']\"\n if self.word2num_features:\n text += \"\\\\n self.word2num_features = deployment_dict['transformation']['word2num_features']\"\n if self.cat_encoder == 'labelencoding':\n text += \"\\\\n self.cat_encoder = deployment_dict['transformation']['cat_encoder']\"\n elif (self.cat_encoder == 'targetencoding') or (self.cat_encoder == 'onehotencoding'):\n text += \"\\\\n self.cat_encoder = deployment_dict['transformation']['cat_encoder']['file']\"\n text += \"\\\\n self.cat_encoder_cols = deployment_dict['transformation']['cat_encoder']['features']\"\n if self.target_encoder:\n text += \"\\\\n self.target_encoder = joblib.load(self.artifact_path/deployment_dict['transformation']['target_encoder'])\"\n if self.normalizer:\n text += \"\\\\n self.normalizer = joblib.load(self.artifact_path/deployment_dict['transformation']['normalizer']['file'])\\\\\n\\\\n self.normalizer_col = deployment_dict['transformation']['normalizer']['features']\"\n if self.text_profiler:\n text += \"\\\\n self.text_profiler = joblib.load(self.artifact_path/deployment_dict['transformation']['Status']['text_profiler']['file'])\\\\\n\\\\n self.text_profiler_col = deployment_dict['transformation']['Status']['text_profiler']['features']\"\n if self.feature_reducer:\n text += \"\\\\n self.feature_reducer = joblib.load(self.artifact_path/deployment_dict['featureengineering']['feature_reducer']['file'])\\\\\n\\\\n self.feature_reducer_cols = deployment_dict['featureengineering']['feature_reducer']['features']\"\n text += \"\"\"\n \n def read_data_from_db(self):\n if self.db_enabled:\n try:\n db = database(self.db_config)\n query = \"SELECT * FROM {} WHERE model_ver = '{}' AND {} != ''\".format(db.measurement, self.model_version, self.target_feature)\n if 'read_time' in self.db_config.keys() and self.db_config['read_time']:\n query += f\" time > now() - {self.db_config['read_time']}\"\n data = db.read_data(query)\n except:\n raise ValueError('Unable to read from the database')\n finally:\n if db:\n db.close()\n return data\n return None\"\"\"\n text += \"\\\\\n \\\\n def predict(self, data):\\\\\n \\\\n df = pd.DataFrame()\\\\\n \\\\n if Path(data).exists():\\\\\n \\\\n if Path(data).suffix == '.tsv':\\\\\n \\\\n df=read_data(data,encoding='utf-8',sep='\\\\t')\\\\\n \\\\n elif Path(data).suffix == '.csv':\\\\\n \\\\n df=read_data(data,encoding='utf-8')\\\\\n \\\\n else:\\\\\n \\\\n if Path(data).suffix == '.json':\\\\\n \\\\n jsonData = read_json(data)\\\\\n \\\\n df = pd.json_normalize(jsonData)\\\\\n \\\\n elif is_file_name_url(data):\\\\\n \\\\n df = read_data(data,encoding='utf-8')\\\\\n \\\\n else:\\\\\n \\\\n jsonData = json.loads(data)\\\\\n \\\\n df = pd.json_normalize(jsonData)\\\\\n \\\\n if len(df) == 0:\\\\\n \\\\n raise ValueError('No data record found')\\\\\n \\\\n missing_features = [x for x in self.selected_features if x not in df.columns]\\\\\n \\\\n if missing_features:\\\\\n \\\\n raise ValueError(f'some feature/s is/are missing: {missing_features}')\\\\\n \\\\n if self.target_feature not in df.columns:\\\\\n \\\\n raise ValueError(f'Ground truth values/target column({self.target_feature}) not found in current data')\\\\\n \\\\n df_copy = df.copy()\\\\\n \\\\n df = df[self.selected_features]\"\n if self.word2num_features:\n text += \"\\\\n for feat in self.word2num_features:\"\n text += \"\\\\n df[ feat ] = df[feat].apply(lambda x: s2n(x))\"\n if self.missing:\n text += \"\\\\n df.fillna(self.missing_values, inplace=True)\"\n if self.cat_encoder == 'labelencoding':\n text += \"\\\\n df.replace(self.cat_encoder, inplace=True)\"\n elif self.cat_encoder == 'targetencoding':\n text += \"\\\\n cat_enc = joblib.load(self.artifact_path/self.cat_encoder)\"\n text += \"\\\\n df = cat_enc.transform(df)\"\n elif self.cat_encoder == 'onehotencoding':\n text += \"\\\\n cat_enc = joblib.load(self.artifact_path/self.cat_encoder)\"\n text += \"\\\\n transformed_data = cat_enc.transform(df[self.cat_encoder_cols]).toarray()\"\n text += \"\\\\n df[cat_enc.get_feature_names()] = pd.DataFrame(transformed_data, columns=cat_enc.get_feature_names())[cat_enc.get_feature_names()]\"\n if self.normalizer:\n text += \"\\\\n df[self.normalizer_col] = self.normalizer.transform(df[self.normalizer_col])\"\n if self.text_profiler:\n text += \"\\\\n text_corpus = df[self.text_profiler_col].apply(lambda row: ' '.join(row.values.astype(str)), axis=1)\\\\\n\\\\n df_vect=self.text_profiler.transform(text_corpus)\\\\\n\\\\n if isinstance(df_vect, np.ndarray):\\\\\n\\\\n df1 = pd.DataFrame(df_vect)\\\\\n\\\\n else:\\\\\n\\\\n df1 = pd.DataFrame(df_vect.toarray(),columns = self.text_profiler.named_steps['vectorizer'].get_feature_names())\\\\\n\\\\n df1 = df1.add_suffix('_vect')\\\\\n\\\\n df = pd.concat([df, df1],axis=1)\"\n if self.feature_reducer:\n text += \"\\\\n df = self.feature_reducer.transform(df[self.feature_reducer_cols])\"\n else:\n text += \"\\\\n df = df[self.train_features]\"\n if self.target_encoder:\n text += \"\\\\n output = pd.DataFrame(self.model._model_impl.predict_proba(df), columns=self.target_encoder.classes_)\\\\\n \\\\n df_copy['prediction'] = output.idxmax(axis=1)\"\n else:\n text += \"\\\\n output = self.model.predict(df).reshape(1, -1)[0].round(2)\\\\\n \\\\n df_copy['", "instruction": "", "output": "" }, { "input": "prediction'] = output\"\n text += \"\\\\n return df_copy\"\n if indent:\n text = text.replace('\\\\n', (self.tab * indent) + '\\\\n')\n return text\n\n def getClassificationMatrixCode(self, indent=0):\n text = \"\\\\\n \\\\ndef get_classification_metrices(actual_values, predicted_values):\\\\\n \\\\n result = {}\\\\\n \\\\n accuracy_score = sklearn.metrics.accuracy_score(actual_values, predicted_values)\\\\\n \\\\n avg_precision = sklearn.metrics.precision_score(actual_values, predicted_values,\\\\\n \\\\n average='macro')\\\\\n \\\\n avg_recall = sklearn.metrics.recall_score(actual_values, predicted_values,\\\\\n \\\\n average='macro')\\\\\n \\\\n avg_f1 = sklearn.metrics.f1_score(actual_values, predicted_values,\\\\\n \\\\n average='macro')\\\\\n \\\\n\\\\\n \\\\n result['accuracy'] = accuracy_score\\\\\n \\\\n result['precision'] = avg_precision\\\\\n \\\\n result['recall'] = avg_recall\\\\\n \\\\n result['f1'] = avg_f1\\\\\n \\\\n return result\\\\\n \\\\n\\\\\n \"\n if indent:\n text = text.replace('\\\\n', (self.tab * indent) + '\\\\n')\n return text\n\n def getRegrssionMatrixCode(self, indent=0):\n text = \"\\\\\n \\\\ndef get_regression_metrices( actual_values, predicted_values):\\\\\n \\\\n result = {}\\\\\n \\\\n\\\\\n \\\\n me = np.mean(predicted_values - actual_values)\\\\\n \\\\n sde = np.std(predicted_values - actual_values, ddof = 1)\\\\\n \\\\n\\\\\n \\\\n abs_err = np.abs(predicted_values - actual_values)\\\\\n \\\\n mae = np.mean(abs_err)\\\\\n \\\\n sdae = np.std(abs_err, ddof = 1)\\\\\n \\\\n\\\\\n \\\\n abs_perc_err = 100.*np.abs(predicted_values - actual_values) / actual_values\\\\\n \\\\n mape = np.mean(abs_perc_err)\\\\\n \\\\n sdape = np.std(abs_perc_err, ddof = 1)\\\\\n \\\\n\\\\\n \\\\n result['mean_error'] = me\\\\\n \\\\n result['mean_abs_error'] = mae\\\\\n \\\\n result['mean_abs_perc_error'] = mape\\\\\n \\\\n result['error_std'] = sde\\\\\n \\\\n result['abs_error_std'] = sdae\\\\\n \\\\n result['abs_perc_error_std'] = sdape\\\\\n \\\\n return result\\\\\n \\\\n\\\\\n \"\n if indent:\n text = text.replace('\\\\n', (self.tab * indent) + '\\\\n')\n return text\n \n def addSuffixCode(self, indent=1):\n text =\"\\\\n\\\\\n \\\\ndef check_drift( config):\\\\\n \\\\n prediction = predict(config)\\\\\n \\\\n usecase = config['modelName'] + '_' + config['modelVersion']\\\\\n \\\\n train_data_path = prediction.artifact_path/(usecase+'_data.csv')\\\\\n \\\\n if not train_data_path.exists():\\\\\n \\\\n raise ValueError(f'Training data not found at {train_data_path}')\\\\\n \\\\n curr_with_pred = prediction.read_data_from_db()\\\\\n \\\\n if prediction.target_feature not in curr_with_pred.columns:\\\\\n \\\\n raise ValueError('Ground truth not updated for corresponding data in database')\\\\\n \\\\n train_with_pred = prediction.predict(train_data_path)\\\\\n \\\\n performance = {}\"\n if self.problem_type == 'classification':\n text += \"\\\\n\\\\\n \\\\n performance['train'] = get_classification_metrices(train_with_pred[prediction.target_feature], train_with_pred['prediction'])\\\\\n \\\\n performance['current'] = get_classification_metrices(curr_with_pred[prediction.target_feature], curr_with_pred['prediction'])\"\n else:\n text += \"\\\\n\\\\\n \\\\n performance['train'] = get_regression_metrices(train_with_pred[prediction.target_feature], train_with_pred['prediction'])\\\\\n \\\\n performance['current'] = get_regression_metrices(curr_with_pred[prediction.target_feature], curr_with_pred['prediction'])\"\n text += \"\\\\n return performance\"\n text += \"\\\\n\\\\\n \\\\nif __name__ == '__main__':\\\\\n \\\\n try:\\\\\n \\\\n if len(sys.argv) < 2:\\\\\n \\\\n raise ValueError('config file not present')\\\\\n \\\\n config = sys.argv[1]\\\\\n \\\\n if Path(config).is_file() and Path(config).suffix == '.json':\\\\\n \\\\n with open(config, 'r') as f:\\\\\n \\\\n config = json.load(f)\\\\\n \\\\n else:\\\\\n \\\\n config = json.loads(config)\\\\\n \\\\n output = check_drift(config)\\\\\n \\\\n status = {'Status':'Success','Message':json.loads(output)}\\\\\n \\\\n print('output_drift:'+json.dumps(status))\\\\\n \\\\n except Exception as e:\\\\\n \\\\n status = {'Status':'Failure','Message':str(e)}\\\\\n \\\\n print('output_drift:'+json.dumps(status))\"\n if indent:\n text = text.replace('\\\\n', (self.tab * indent) + '\\\\n')\n return text\n \n def addStatement(self, statement, indent=1):\n self.codeText += '\\\\n' + self.tab * indent + statement\n \n def generateCode(self):\n self.codeText += self.addDatabaseClass()\n self.codeText += self.addPredictClass()\n if self.problem_type == 'classification':\n self.codeText += self.getClassificationMatrixCode()\n elif self.problem_type == 'regression':\n self.codeText += self.getRegrssionMatrixCode()\n else:\n raise ValueError(f\"Unsupported problem type: {self.problem_type}\")\n self.codeText += self.addSuffixCode()\n \n def getCode(self):\n return self.codeText\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom .imports import importModule\n\nsupported_reader = ['sqlite', 'influx','s3']\n\n\n\nfunctions_code = {\n 'dataReader':{'imports':[{'mod':'json'},{'mod': 'Path', 'mod_from': 'pathlib', 'mod_as': None},{'mod': 'pandas', 'mod_from': None, 'mod_as': 'pd'}],'code':\"\"\"\n\nclass dataReader():\n \n def get_reader(self, reader_type, target_path=None, config=None):\n if reader_type == 'sqlite':\n return sqlite_writer(target_path=target_path)\n elif reader_type == 'influx':\n return Influx_writer(config=config)\n elif reader_type == 'gcs':\n return gcs(config=config)\n elif reader_type == 'azure':\n return azure(config=config)\n elif reader_type == 's3':\n return s3bucket(config=config)\n else:\n raise ValueError(reader_type)\n\"\"\"\n },\n 'sqlite':{'imports':[{'mod':'sqlite3'},{'mod': 'pandas', 'mod_from': None, 'mod_as': 'pd'},{'mod': 'Path', 'mod_from': 'pathlib', 'mod_as': None}],'code':\"\"\"\\\\n\\\\\nclass sqlite_writer():\n def __init__(self, target_path):\n self.target_path = Path(target_path)\n database_file = self.target_path.stem + '.db'\n self.db = sqlite_db(self.target_path, database_file)\n\n def file_exists(self, file):\n if file:\n return self.db.table_exists(file)\n else:\n return False\n\n def read(self, file):\n return self.db.read(file)\n \n def write(self, data, file):\n self.db.write(data, file)\n\n def close(self):\n self.db.close()\n\nclass sqlite_db():\n\n def __init__(self, location, database_file=None):\n if not isinstance(location, Path):\n location = Path(location)\n if database_file:\n self.database_name = database_file\n else:\n self.database_name = location.stem + '.db'\n db_file = str(location/self.database_name)\n self.conn = sqlite3.connect(db_file)\n self.cursor = self.conn.cursor()\n self.tables = []\n\n def table_exists(self, name):\n if name in self.tables:\n return True\n elif name:\n query = f\"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}';\"\n listOfTables = self.cursor.execute(query).fetchall()\n if len(listOfTables) > 0 :\n self.tables.append(name)\n return True\n return False\n\n def read(self, table_name):\n return pd.read_sql_query(f\"SELECT * FROM {table_name}\", self.conn)\n\n def create_table(self,name, columns, dtypes):\n query = f'CREATE TABLE IF NOT EXISTS {name} ('\n \n for column, data_type in zip(columns, dtypes):\n query += f\"'{column}' TEXT,\"\n query = query[:-1]\n query += ');'\n self.conn.execute(query)\n return True\n \n def write(self,data, table_name):\n if not self.table_exists(table_name):\n self.create_table(table_name, data.columns, data.dtypes)\n tuple_data = list(data.itertuples(index=False, name=None))\n insert_query = f'INSERT INTO {table_name} VALUES('\n for i in range(len(data.columns)):\n insert_query += '?,'\n insert_query = insert_query[:-1] + ')'\n self.cursor.executemany(insert_query, tuple_data)\n self.conn.commit()\n return True\n \n def delete(self, name):\n pass\n \n def close(self):\n self.conn.close()\n\n \"\"\"\n },\n 'influx':{'imports':[{'mod':'InfluxDBClient','mod_from':'influxdb'},{'mod': 'Path', 'mod_from': 'pathlib', 'mod_as': None},{'mod': 'pandas', 'mod_from': None, 'mod_as': 'pd'}],'code':\"\"\"\\\\n\\\\\nclass Influx_writer():\n\n def __init__(self, config):\n self.db = influx_db(config)\n\n def file_exists(self, file):\n if file:\n return self.db.table_exists(file)\n else:\n return False\n\n def read(self, file):\n query = \"SELECT * FROM {}\".format(file)\n if 'read_time' in self.db_config.keys() and self.db_config['read_time']:\n query += f\" time > now() - {self.db_config['read_time']}\"\n return self.db.read(query)\n\n def write(self, data, file):\n self.db.write(data, file)\n\n def close(self):\n pass\n\n\nclass influx_db():\n\n def __init__(self, config):\n self.host = config['host']\n self.port = config['port']\n self.user = config.get('user', None)\n self.password = config.get('password', None)\n self.token = config.get('token', None)\n self.database = config['database']\n self.measurement = config['measurement']\n self.tags = config['tags']\n self.client = self.get_client()\n\n def table_exists(self, name):\n query = f\"SHOW MEASUREMENTS ON {self.database}\"\n result = self.client(query)\n for measurement in result['measurements']:\n if measurement['name'] == name:\n return True\n return False\n \n def read(self, query)->pd.DataFrame:\n cursor = self.client.query(query)\n points = cursor.get_points()\n my_list=list(points)\n df=pd.DataFrame(my_list)\n return df\n\n def get_client(self):\n headers = None\n if self.token:\n headers={\"Authorization\": self.token} \n client = InfluxDBClient(self.host,self.port,self.user, self.password,headers=headers)\n databases = client.get_list_database()\n databases = [x['name'] for x in databases]\n if self.database not in databases:\n client.create_database(self.database)\n return InfluxDBClient(self.host,self.port,self.user,self.password,self.database,headers=headers)\n\n def write(self,data, measurement=None):\n if isinstance(data, pd.DataFrame):\n sorted_col = data.columns.tolist()\n sorted_col.sort()\n data = data[sorted_col]\n data = data.to_dict(orient='records')\n if not measurement:\n measurement = self.measurement\n for row in data:\n if 'time' in row.keys():\n p = '%Y-%m-%dT%H:%M:%S.%fZ'\n time_str = datetime.strptime(row['time'], p)\n del row['time']\n else:\n time_str = None\n if 'model_ver' in row.keys():\n self.tags['model_ver']= row['model_ver']\n del row['model_ver']\n json_body = [{\n 'measurement': measurement,\n 'time': time_str,\n 'tags': self.tags,\n 'fields': row\n }]\n self.client.write_points(json_body)\n\n def delete(self, name):\n pass\n \n def close(self):\n self.client.close()\n\"\"\"\n},\n 's3':{'imports':[{'mod':'boto3'},{'mod': 'ClientError', 'mod_from': 'botocore.exceptions'},{'mod': 'Path', 'mod_from': 'pathlib'},{'mod': 'pandas', 'mod_as': 'pd'}],'code':\"\"\"\\\\n\\\\\nclass s3bucket():\n \n def __init__(self, config={}):\n if 's3' in config.keys():\n config = config['s3']\n aws_access_key_id = config.get('aws_access_key_id','')\n aws_secret_access_key = config.get('aws_secret_access_key','')\n bucket_name = config.get('bucket_name','')\n if not aws_access_key_id:\n raise ValueError('aws_access_key_id can not be empty')\n if not aws_secret_access_key:\n raise ValueError('aws_secret_access_key can not be empty')\n self.client = boto3.client('s3', aws_access_key", "instruction": "", "output": "" }, { "input": "_id=aws_access_key_id, aws_secret_access_key=str(aws_secret_access_key))\n self.bucket_name = bucket_name\n \n def read(self, file_name):\n try:\n response = self.client.get_object(Bucket=self.bucket_name, Key=file_name)\n return pd.read_csv(response['Body'])\n except ClientError as ex:\n if ex.response['Error']['Code'] == 'NoSuchBucket':\n raise ValueError(f\"Bucket '{self.bucket_name}' not found in aws s3 storage\")\n elif ex.response['Error']['Code'] == 'NoSuchKey':\n raise ValueError(f\"File '{file_name}' not found in s3 bucket '{self.bucket_name}'\")\n else:\n raise\n\n \"\"\"\n}, \n 'azure':{'imports':[{'mod':'DataLakeServiceClient', 'mod_from':'azure.storage.filedatalake'},{'mod':'detect', 'mod_from':'detect_delimiter'},{'mod':'pandavro', 'mod_as':'pdx'},{'mod':'io'},{'mod': 'Path', 'mod_from': 'pathlib'},{'mod': 'pandas', 'mod_as': 'pd'}],'code':\"\"\"\\\\n\\\\\ndef azure():\n\n def __init__(self,config={}):\n if 'azure' in config.keys():\n config = config['azure']\n account_name = config.get('account_name','')\n account_key = config.get('account_key','')\n container_name = config.get('container_name','')\n if not account_name:\n raise ValueError('Account name can not be empty')\n if not account_key:\n raise ValueError('Account key can not be empty')\n if not container_name:\n raise ValueError('Container name can not be empty')\n service_client = DataLakeServiceClient(account_url=\"{}://{}.dfs.core.windows.net\".format(\"https\", account_name), credential=account_key)\n self.file_system_client = service_client.get_file_system_client(container_name)\n \n def read(self, directory_name):\n root_dir = str(directory_name)\n file_paths = self.file_system_client.get_paths(path=root_dir)\t\t\t\t\n main_df = pd.DataFrame()\n for path in file_paths:\n if not path.is_directory:\n file_client = file_system_client.get_file_client(path.name)\n file_ext = Path(path.name).suffix\n if file_ext in [\".csv\", \".tsv\"]:\n with open(csv_local, \"wb\") as my_file:\n file_client.download_file().readinto(my_file)\n with open(csv_local, 'r') as file:\n data = file.read()\n row_delimiter = detect(text=data, default=None, whitelist=[',', ';', ':', '|', '\\\\t'])\n processed_df = pd.read_csv(csv_local, sep=row_delimiter)\n elif file_ext == \".parquet\":\n stream = io.BytesIO()\n file_client.download_file().readinto(stream)\n processed_df = pd.read_parquet(stream, engine='pyarrow')\n elif file_ext == \".avro\": \n with open(avro_local, \"wb\") as my_file:\n file_client.download_file().readinto(my_file)\n processed_df = pdx.read_avro(avro_local)\n if main_df.empty:\n main_df = pd.DataFrame(processed_df)\n else:\n main_df = main_df.append(processed_df, ignore_index=True)\n return main_df\n\n \"\"\"\n },\n 'gcs':{'imports':[{'mod':'storage','mod_from':'google.cloud'},{'mod': 'Path', 'mod_from': 'pathlib'},{'mod': 'pandas', 'mod_as': 'pd'}],'code':\"\"\"\\\\n\\\\\nclass gcs():\n \n def __init__(self, config={}):\n if 'gcs' in config.keys():\n config = config['gcs']\n account_key = config.get('account_key','')\n bucket_name = config.get('bucket_name','')\n if not account_key:\n raise ValueError('Account key can not be empty')\n if not bucket_name:\n raise ValueError('bucket name can not be empty')\n storage_client = storage.Client.from_service_account_json(account_key)\n self.bucket = storage_client.get_bucket(bucket_name)\n \n def read(self, bucket_name, file_name):\n data = self.bucket.blob(file_name).download_as_text()\n return pd.read_csv(data, encoding = 'utf-8', sep = ',')\n \"\"\"\n }\n}\n\nclass data_reader():\n\n def __init__(self, reader_type=[]):\n self.supported_readers = supported_reader\n if isinstance(reader_type, str):\n self.readers = [reader_type]\n elif not reader_type:\n self.readers = self.supported_readers\n else:\n self.readers = reader_type\n unsupported_reader = [ x for x in self.readers if x not in self.supported_readers]\n if unsupported_reader:\n raise ValueError(f\"reader type '{unsupported_reader}' is not supported\\\\nSupported readers are {self.supported_readers}\")\n self.codeText = \"\"\n self.importer = importModule()\n \n def get_reader_code(self, readers):\n reader_code = {\n 'sqlite': 'return sqlite_writer(target_path=target_path)',\n 'influx': 'return Influx_writer(config=config)',\n 'gcs': 'return gcs(config=config)',\n 'azure': 'return azure(config=config)',\n 's3': 'return s3bucket(config=config)'\n }\n code = \"\\\\n\\\\ndef dataReader(reader_type, target_path=None, config=None):\\\\n\"\n for i, reader in enumerate(readers):\n if not i:\n code += f\" if reader_type == '{reader}':\\\\n\"\n else:\n code += f\" elif reader_type == '{reader}':\\\\n\"\n code += f\" {reader_code[reader]}\\\\n\"\n if readers:\n code += \" else:\\\\n\"\n code += f\"\"\" raise ValueError(\"'{{reader_type}}' not added during code generation\")\\\\n\"\"\"\n else:\n code += f\"\"\" raise ValueError(\"'{{reader_type}}' not added during code generation\")\\\\n\"\"\"\n return code\n\n def get_code(self):\n code = self.get_reader_code(self.readers)\n functions = []\n for reader in self.readers:\n functions.append(reader)\n for function in functions:\n code += self.get_function_code(function)\n self.codeText += self.importer.getCode()\n self.codeText += code\n return self.codeText\n \n def get_function_code(self, name):\n code = \"\"\n if name in functions_code.keys():\n code += functions_code[name]['code']\n if self.importer:\n if 'imports' in functions_code[name].keys():\n for module in functions_code[name]['imports']:\n mod_name = module['mod']\n mod_from = module.get('mod_from', None)\n mod_as = module.get('mod_as', None)\n self.importer.addModule(mod_name, mod_from=mod_from, mod_as=mod_as)\n return code\n\n def get_importer(self):\n return self.importer\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom importlib.metadata import version\nimport sys\n\n \nclass importModule():\n\n def __init__(self):\n self.importModule = {}\n self.stdlibModule = []\n self.localModule = {}\n \n def addLocalModule(self,module, mod_from=None, mod_as=None):\n if module == '*':\n if module not in self.localModule.keys():\n self.localModule[module]= [mod_from]\n else:\n self.localModule[module].append(mod_from)\n elif module not in self.localModule.keys():\n self.localModule[module] = {'from':mod_from, 'as':mod_as}\n \n def addModule(self, module, mod_from=None, mod_as=None):\n if module not in self.importModule.keys():\n self.importModule[module] = {'from':mod_from, 'as':mod_as}\n if module in sys.stdlib_module_names:\n self.stdlibModule.append(module)\n elif isinstance(self.importModule[module], list):\n if mod_as not in [x['as'] for x in self.importModule[module]]:\n self.importModule[module].append({'from':mod_from, 'as':mod_as})\n elif mod_as not in [x['from'] for x in self.importModule[module]]:\n self.importModule[module].append({'from':mod_from, 'as':mod_as})\n elif mod_as != self.importModule[module]['as']:\n as_list = [self.importModule[module]]\n as_list.append({'from':mod_from, 'as':mod_as})\n self.importModule[module] = as_list\n elif mod_from != self.importModule[module]['from']:\n as_list = [self.importModule[module]]\n as_list.append({'from':mod_from, 'as':mod_as})\n self.importModule[module] = as_list\n\n def getModules(self):\n return (self.importModule, self.stdlibModule)\n \n def getBaseModule(self, extra_importers=[]):\n modules_alias = { 'sklearn':'scikit-learn', \n 'genetic_selection':'sklearn-genetic',\n 'google': 'google-cloud-storage',\n 'azure':'azure-storage-file-datalake'}\n local_modules = {'AIX':'/app/AIX-0.1-py3-none-any.whl'}\n modules = []\n require = \"\"\n if extra_importers:\n extra_importers = [importer.importModule for importer in extra_importers if isinstance(importer, importModule)]\n importers_module = [self.importModule] + extra_importers\n for importer_module in importers_module:\n for k,v in importer_module.items():\n if v['from']:\n mod = v['from'].split('.')[0]\n else:\n mod = k\n if mod in modules_alias.keys():\n mod = modules_alias[mod]\n modules.append(mod)\n modules = list(set(modules))\n for mod in modules:\n try:\n if mod in local_modules.keys():\n require += f\"{local_modules[mod]}\\\\n\"\n else:\n require += f\"{mod}=={version(mod)}\\\\n\"\n except :\n if mod not in sys.stdlib_module_names:\n raise \n return require\n\n def getCode(self):\n def to_string(k, v):\n mod = ''\n if v['from']:\n mod += 'from {} '.format(v['from'])\n mod += 'import {}'.format(k)\n if v['as']:\n mod += ' as {} '.format(v['as'])\n return mod\n \n modules = \"\"\n local_modules = \"\"\n std_lib_modules = \"\"\n third_party_modules = \"\"\n for k,v in self.importModule.items():\n if k in self.stdlibModule:\n std_lib_modules = std_lib_modules + '\\\\n' + to_string(k, v)\n elif isinstance(v, dict):\n third_party_modules = third_party_modules + '\\\\n' + to_string(k, v)\n elif isinstance(v, list):\n for alias in v:\n third_party_modules = third_party_modules + '\\\\n' + to_string(k, alias)\n for k,v in self.localModule.items():\n if k != '*':\n local_modules = local_modules + '\\\\n' + to_string(k, v)\n else:\n for mod_from in v:\n local_modules = local_modules + '\\\\n' + f'from {mod_from} import {k}'\n if std_lib_modules:\n modules = modules + \"\\\\n#Standard Library modules\" + std_lib_modules\n if third_party_modules:\n modules = modules + \"\\\\n\\\\n#Third Party modules\" + third_party_modules\n if local_modules:\n modules = modules + \"\\\\n\\\\n#local modules\" + local_modules + '\\\\n'\n return modules\n\n def copyCode(self, importer):\n self.importModule, self.stdlibModule = importer.getModules()\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom .imports import importModule\nfrom .load_data import tabularDataReader\nfrom .transformer import transformer as profiler\nfrom .transformer import data_profiler\nfrom .selector import selector\nfrom .trainer import learner\nfrom .register import register\nfrom .deploy import deploy\nfrom .drift_analysis import drift\nfrom .functions import global_function\nfrom .data_reader import data_reader\nfrom .utility import utility_function\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nclass input_drift():\n\n def __init__(self, tab_size=4):\n self.tab = ' ' * tab_size\n self.codeText = ''\n \n def addInputDriftClass(self):\n text = \"\\\\\n \\\\nclass inputdrift():\\\\\n \\\\n\\\\\n \\\\n def __init__(self,base_config):\\\\\n \\\\n self.usecase = base_config['modelName'] + '_' + base_config['modelVersion']\\\\\n \\\\n self.currentDataLocation = base_config['currentDataLocation']\\\\\n \\\\n home = Path.home()\\\\\n \\\\n if platform.system() == 'Windows':\\\\\n \\\\n from pathlib import WindowsPath\\\\\n \\\\n output_data_dir = WindowsPath(home)/'AppData'/'Local'/'HCLT'/'AION'/'Data'\\\\\n \\\\n output_model_dir = WindowsPath(home)/'AppData'/'Local'/'HCLT'/'", "instruction": "", "output": "" }, { "input": "AION'/'target'/self.usecase\\\\\n \\\\n else:\\\\\n \\\\n from pathlib import PosixPath\\\\\n \\\\n output_data_dir = PosixPath(home)/'HCLT'/'AION'/'Data'\\\\\n \\\\n output_model_dir = PosixPath(home)/'HCLT'/'AION'/'target'/self.usecase\\\\\n \\\\n if not output_model_dir.exists():\\\\\n \\\\n raise ValueError(f'Configuration file not found at {output_model_dir}')\\\\\n \\\\n\\\\\n \\\\n tracking_uri = 'file:///' + str(Path(output_model_dir)/'mlruns')\\\\\n \\\\n registry_uri = 'sqlite:///' + str(Path(output_model_dir)/'mlruns.db')\\\\\n \\\\n mlflow.set_tracking_uri(tracking_uri)\\\\\n \\\\n mlflow.set_registry_uri(registry_uri)\\\\\n \\\\n client = mlflow.tracking.MlflowClient(\\\\\n \\\\n tracking_uri=tracking_uri,\\\\\n \\\\n registry_uri=registry_uri,\\\\\n \\\\n )\\\\\n \\\\n model_version_uri = 'models:/{model_name}/production'.format(model_name=self.usecase)\\\\\n \\\\n model = mlflow.pyfunc.load_model(model_version_uri)\\\\\n \\\\n run = client.get_run(model.metadata.run_id)\\\\\n \\\\n if run.info.artifact_uri.startswith('file:'):\\\\\n \\\\n artifact_path = Path(run.info.artifact_uri[len('file:///') : ])\\\\\n \\\\n else:\\\\\n \\\\n artifact_path = Path(run.info.artifact_uri)\\\\\n \\\\n self.trainingDataPath = artifact_path/(self.usecase + '_data.csv')\\\\\n \\\\n\\\\\n \\\\n def get_input_drift(self,current_data, historical_data):\\\\\n \\\\n curr_num_feat = current_data.select_dtypes(include='number')\\\\\n \\\\n hist_num_feat = historical_data.select_dtypes(include='number')\\\\\n \\\\n num_features = [feat for feat in historical_data.columns if feat in curr_num_feat]\\\\\n \\\\n alert_count = 0\\\\\n \\\\n data = {\\\\\n \\\\n 'current':{'data':current_data},\\\\\n \\\\n 'hist': {'data': historical_data}\\\\\n \\\\n }\\\\\n \\\\n dist_changed_columns = []\\\\\n \\\\n dist_change_message = []\\\\\n \\\\n for feature in num_features:\\\\\n \\\\n curr_static_value = st.ks_2samp( hist_num_feat[feature], curr_num_feat[feature]).pvalue\\\\\n \\\\n if (curr_static_value < 0.05):\\\\\n \\\\n distribution = {}\\\\\n \\\\n distribution['hist'] = self.DistributionFinder( historical_data[feature])\\\\\n \\\\n distribution['curr'] = self.DistributionFinder( current_data[feature])\\\\\n \\\\n if(distribution['hist']['name'] == distribution['curr']['name']):\\\\\n \\\\n pass\\\\\n \\\\n else:\\\\\n \\\\n alert_count = alert_count + 1\\\\\n \\\\n dist_changed_columns.append(feature)\\\\\n \\\\n changed_column = {}\\\\\n \\\\n changed_column['Feature'] = feature\\\\\n \\\\n changed_column['KS_Training'] = curr_static_value\\\\\n \\\\n changed_column['Training_Distribution'] = distribution['hist']['name']\\\\\n \\\\n changed_column['New_Distribution'] = distribution['curr']['name']\\\\\n \\\\n dist_change_message.append(changed_column)\\\\\n \\\\n if alert_count:\\\\\n \\\\n resultStatus = dist_change_message\\\\\n \\\\n else :\\\\\n \\\\n resultStatus='Model is working as expected'\\\\\n \\\\n return(alert_count, resultStatus)\\\\\n \\\\n\\\\\n \\\\n def DistributionFinder(self,data):\\\\\n \\\\n best_distribution =''\\\\\n \\\\n best_sse =0.0\\\\\n \\\\n if(data.dtype in ['int','int64']):\\\\\n \\\\n distributions= {'bernoulli':{'algo':st.bernoulli},\\\\\n \\\\n 'binom':{'algo':st.binom},\\\\\n \\\\n 'geom':{'algo':st.geom},\\\\\n \\\\n 'nbinom':{'algo':st.nbinom},\\\\\n \\\\n 'poisson':{'algo':st.poisson}\\\\\n \\\\n }\\\\\n \\\\n index, counts = np.unique(data.astype(int),return_counts=True)\\\\\n \\\\n if(len(index)>=2):\\\\\n \\\\n best_sse = np.inf\\\\\n \\\\n y1=[]\\\\\n \\\\n total=sum(counts)\\\\\n \\\\n mean=float(sum(index*counts))/total\\\\\n \\\\n variance=float((sum(index**2*counts) -total*mean**2))/(total-1)\\\\\n \\\\n dispersion=mean/float(variance)\\\\\n \\\\n theta=1/float(dispersion)\\\\\n \\\\n r=mean*(float(theta)/1-theta)\\\\\n \\\\n\\\\\n \\\\n for j in counts:\\\\\n \\\\n y1.append(float(j)/total)\\\\\n \\\\n distributions['bernoulli']['pmf'] = distributions['bernoulli']['algo'].pmf(index,mean)\\\\\n \\\\n distributions['binom']['pmf'] = distributions['binom']['algo'].pmf(index,len(index),p=mean/len(index))\\\\\n \\\\n distributions['geom']['pmf'] = distributions['geom']['algo'].pmf(index,1/float(1+mean))\\\\\n \\\\n distributions['nbinom']['pmf'] = distributions['nbinom']['algo'].pmf(index,mean,r)\\\\\n \\\\n distributions['poisson']['pmf'] = distributions['poisson']['algo'].pmf(index,mean)\\\\\n \\\\n\\\\\n \\\\n sselist = []\\\\\n \\\\n for dist in distributions.keys():\\\\\n \\\\n distributions[dist]['sess'] = np.sum(np.power(y1 - distributions[dist]['pmf'], 2.0))\\\\\n \\\\n if np.isnan(distributions[dist]['sess']):\\\\\n \\\\n distributions[dist]['sess'] = float('inf')\\\\\n \\\\n best_dist = min(distributions, key=lambda v: distributions[v]['sess'])\\\\\n \\\\n best_distribution = best_dist\\\\\n \\\\n best_sse = distributions[best_dist]['sess']\\\\\n \\\\n\\\\\n \\\\n elif (len(index) == 1):\\\\\n \\\\n best_distribution = 'Constant Data-No Distribution'\\\\\n \\\\n best_sse = 0.0\\\\\n \\\\n elif(data.dtype in ['float64','float32']):\\\\\n \\\\n distributions = [st.uniform,st.expon,st.weibull_max,st.weibull_min,st.chi,st.norm,st.lognorm,st.t,st.gamma,st.beta]\\\\\n \\\\n best_distribution = st.norm.name\\\\\n \\\\n best_sse = np.inf\\\\\n \\\\n nrange = data.max() - data.min()\\\\\n \\\\n\\\\\n \\\\n y, x = np.histogram(data.astype(float), bins='auto', density=True)\\\\\n \\\\n x = (x + np.roll(x, -1))[:-1] / 2.0\\\\\n \\\\n\\\\\n \\\\n for distribution in distributions:\\\\\n \\\\n with warnings.catch_warnings():\\\\\n \\\\n warnings.filterwarnings('ignore')\\\\\n \\\\n params = distribution.fit(data.astype(float))\\\\\n \\\\n arg = params[:-2]\\\\\n \\\\n loc = params[-2]\\\\\n \\\\n scale = params[-1]\\\\\n \\\\n pdf = distribution.pdf(x, loc=loc, scale=scale, *arg)\\\\\n \\\\n sse = np.sum(np.power(y - pdf, 2.0))\\\\\n \\\\n if( sse < best_sse):\\\\\n \\\\n best_distribution = distribution.name\\\\\n \\\\n best_sse = sse\\\\\n \\\\n\\\\\n \\\\n return {'name':best_distribution, 'sse': best_sse}\\\\\n \\\\n\\\\\n \"\n return text\n \n def addSuffixCode(self, indent=1):\n text =\"\\\\n\\\\\n \\\\ndef check_drift( config):\\\\\n \\\\n inputdriftObj = inputdrift(config)\\\\\n \\\\n historicaldataFrame=pd.read_csv(inputdriftObj.trainingDataPath)\\\\\n \\\\n currentdataFrame=pd.read_csv(inputdriftObj.currentDataLocation)\\\\\n \\\\n dataalertcount,message = inputdriftObj.get_input_drift(currentdataFrame,historicaldataFrame)\\\\\n \\\\n if message == 'Model is working as expected':\\\\\n \\\\n output_json = {'status':'SUCCESS','data':{'Message':'Model is working as expected'}}\\\\\n \\\\n else:\\\\\n \\\\n output_json = {'status':'SUCCESS','data':{'Affected Columns':message}}\\\\\n \\\\n return(output_json)\\\\\n \\\\n\\\\\n \\\\nif __name__ == '__main__':\\\\\n \\\\n try:\\\\\n \\\\n if len(sys.argv) < 2:\\\\\n \\\\n raise ValueError('config file not present')\\\\\n \\\\n config = sys.argv[1]\\\\\n \\\\n if Path(config).is_file() and Path(config).suffix == '.json':\\\\\n \\\\n with open(config, 'r') as f:\\\\\n \\\\n config = json.load(f)\\\\\n \\\\n else:\\\\\n \\\\n config = json.loads(config)\\\\\n \\\\n output = check_drift(config)\\\\\n \\\\n status = {'Status':'Success','Message':output}\\\\\n \\\\n print('input_drift:'+json.dumps(status))\\\\\n \\\\n except Exception as e:\\\\\n \\\\n status = {'Status':'Failure','Message':str(e)}\\\\\n \\\\n print('input_drift:'+json.dumps(status))\"\n return text\n\n def addStatement(self, statement, indent=1):\n self.codeText += '\\\\n' + self.tab * indent + statement\n \n def generateCode(self):\n self.codeText += self.addInputDriftClass()\n self.codeText += self.addSuffixCode()\n \n def getCode(self):\n return self.codeText\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\nimport json\n\nclass drift():\n\n def __init__(self, tab_size=4):\n self.tab = ' ' * tab_size\n self.codeText = ''\n \n def getInputFiles(self):\n IOFiles = {\n \"log\": \"aion.log\",\n \"trainingData\":\"rawData.dat\",\n \"production\": \"production.json\",\n \"monitoring\":\"monitoring.json\",\n \"prodData\": \"prodData\",\n \"prodDataGT\":\"prodDataGT\"\n\t\t}\n text = 'IOFiles = '\n if not IOFiles:\n text += '{ }'\n else:\n text += json.dumps(IOFiles, indent=4)\n return text\n\n def getInputOutputFiles(self, indent=0):\n text = '\\\\n'\n text += self.getInputFiles()\n if indent:\n text = text.replace('\\\\n', self.tab * indent + '\\\\n')\n return text\n\n def addStatement(self, statement, indent=1):\n self.codeText += '\\\\n' + self.tab * indent + statement\n \n def getCode(self):\n return self.codeText\n\n# temporary code\n\n def get_input_drift_import_modules(self):\n return [\n {'module': 'sys', 'mod_from': None, 'mod_as': None},\n {'module': 'json', 'mod_from': None, 'mod_as': None},\n {'module': 'mlflow', 'mod_from': None, 'mod_as': None},\n {'module': 'stats', 'mod_from': 'scipy', 'mod_as': 'st'},\n {'module': 'numpy', 'mod_from': None, 'mod_as': 'np'},\n {'module': 'Path', 'mod_from': 'pathlib', 'mod_as': None},\n {'module': 'pandas', 'mod_from': None, 'mod_as': 'pd'},\n {'module': 'warnings', 'mod_from': None, 'mod_as': None},\n {'module': 'platform', 'mod_from': None, 'mod_as': None } \n ]\n \n def get_input_drift_code(self):\n return \"\"\"\n \nclass inputdrift(): \n \n def __init__(self,base_config):\n if 'mlflowURL' in base_config:\t\n self.usecase = base_config['modelName'] + '_' + base_config['modelVersion'] \n self.currentDataLocation = base_config['currentDataLocation'] \n home = Path.home() \n if platform.system() == 'Windows': \n from pathlib import WindowsPath \n output_data_dir = WindowsPath(home)/'AppData'/'Local'/'HCLT'/'AION'/'Data' \n output_model_dir = WindowsPath(home)/'AppData'/'Local'/'HCLT'/'AION'/'target'/self.usecase \n else: \n from pathlib import PosixPath \n output_data_dir = PosixPath(home)/'HCLT'/'AION'/'Data' \n output_model_dir = PosixPath(home)/'HCLT'/'AION'/'target'/self.usecase \n if not output_model_dir.exists(): \n raise ValueError(f'Configuration file not found at {output_model_dir}') \n \n tracking_uri = 'file:///' + str(Path(output_model_dir)/'mlruns') \n registry_uri = 'sqlite:///' + str(Path(output_model_dir)/'mlruns.db') \n mlflow.set_tracking_uri(tracking_uri) \n mlflow.set_registry_uri(registry_uri) \n client = mlflow.tracking.MlflowClient( \n tracking_uri=tracking_uri, \n registry_uri=registry_uri, \n ) \n model_version_uri = 'models:/{model_name}/production'.format(model_name=self.usecase) \n model = mlflow.pyfunc.load_model(model_version_uri) \n run = client.get_run(model.metadata.run_id) \n if run.info.artifact_uri.startswith('file:'): \n artifact_path = Path(run.info.artifact_uri[len('file:///') : ]) \n else: \n artifact_path = Path(run.info.artifact_uri) \n self.trainingDataPath = artifact_path/(self.usecase + '_data.csv') \n \n def get_input_drift(self,current_data, historical_data): \n curr_num_feat = current_data.select_dtypes(include='number') ", "instruction": "", "output": "" }, { "input": "\n hist_num_feat = historical_data.select_dtypes(include='number') \n num_features = [feat for feat in historical_data.columns if feat in curr_num_feat] \n alert_count = 0 \n data = { \n 'current':{'data':current_data}, \n 'hist': {'data': historical_data} \n } \n dist_changed_columns = [] \n dist_change_message = [] \n for feature in num_features: \n curr_static_value = round(st.ks_2samp( hist_num_feat[feature], curr_num_feat[feature]).pvalue,3) \n if (curr_static_value < 0.05):\n try: \n distribution = {} \n distribution['hist'] = self.DistributionFinder( historical_data[feature]) \n distribution['curr'] = self.DistributionFinder( current_data[feature]) \n if(distribution['hist']['name'] == distribution['curr']['name']): \n pass \n else: \n alert_count = alert_count + 1 \n dist_changed_columns.append(feature) \n changed_column = {} \n changed_column['Feature'] = feature \n changed_column['KS_Training'] = curr_static_value \n changed_column['Training_Distribution'] = distribution['hist']['name'] \n changed_column['New_Distribution'] = distribution['curr']['name'] \n dist_change_message.append(changed_column) \n except:\n pass \n if alert_count: \n resultStatus = dist_change_message \n else : \n resultStatus='Model is working as expected' \n return(alert_count, resultStatus) \n \n def DistributionFinder(self,data): \n best_distribution ='' \n best_sse =0.0 \n if(data.dtype in ['int','int64']): \n distributions= {'bernoulli':{'algo':st.bernoulli}, \n 'binom':{'algo':st.binom}, \n 'geom':{'algo':st.geom}, \n 'nbinom':{'algo':st.nbinom}, \n 'poisson':{'algo':st.poisson} \n } \n index, counts = np.unique(data.astype(int),return_counts=True) \n if(len(index)>=2): \n best_sse = np.inf \n y1=[] \n total=sum(counts) \n mean=float(sum(index*counts))/total \n variance=float((sum(index**2*counts) -total*mean**2))/(total-1) \n dispersion=mean/float(variance) \n theta=1/float(dispersion) \n r=mean*(float(theta)/1-theta) \n \n for j in counts: \n y1.append(float(j)/total) \n distributions['bernoulli']['pmf'] = distributions['bernoulli']['algo'].pmf(index,mean) \n distributions['binom']['pmf'] = distributions['binom']['algo'].pmf(index,len(index),p=mean/len(index)) \n distributions['geom']['pmf'] = distributions['geom']['algo'].pmf(index,1/float(1+mean)) \n distributions['nbinom']['pmf'] = distributions['nbinom']['algo'].pmf(index,mean,r) \n distributions['poisson']['pmf'] = distributions['poisson']['algo'].pmf(index,mean) \n \n sselist = [] \n for dist in distributions.keys(): \n distributions[dist]['sess'] = np.sum(np.power(y1 - distributions[dist]['pmf'], 2.0)) \n if np.isnan(distributions[dist]['sess']): \n distributions[dist]['sess'] = float('inf') \n best_dist = min(distributions, key=lambda v: distributions[v]['sess']) \n best_distribution = best_dist \n best_sse = distributions[best_dist]['sess'] \n \n elif (len(index) == 1): \n best_distribution = 'Constant Data-No Distribution' \n best_sse = 0.0 \n elif(data.dtype in ['float64','float32']): \n distributions = [st.uniform,st.expon,st.weibull_max,st.weibull_min,st.chi,st.norm,st.lognorm,st.t,st.gamma,st.beta] \n best_distribution = st.norm.name \n best_sse = np.inf \n nrange = data.max() - data.min() \n \n y, x = np.histogram(data.astype(float), bins='auto', density=True) \n x = (x + np.roll(x, -1))[:-1] / 2.0 \n \n for distribution in distributions: \n with warnings.catch_warnings(): \n warnings.filterwarnings('ignore') \n params = distribution.fit(data.astype(float)) \n arg = params[:-2] \n loc = params[-2] \n scale = params[-1] \n pdf = distribution.pdf(x, loc=loc, scale=scale, *arg) \n sse = np.sum(np.power(y - pdf, 2.0)) \n if( sse < best_sse): \n best_distribution = distribution.name \n best_sse = sse \n \n return {'name':best_distribution, 'sse': best_sse} \n \n \ndef check_drift( config): \n inputdriftObj = inputdrift(config) \n historicaldataFrame=pd.read_csv(inputdriftObj.trainingDataPath,skipinitialspace = True,na_values=['-','?']) \n currentdataFrame=pd.read_csv(inputdriftObj.currentDataLocation,skipinitialspace = True,na_values=['-','?'])\n historicaldataFrame.columns = historicaldataFrame.columns.str.strip()\n currentdataFrame.columns = currentdataFrame.columns.str.strip() \n dataalertcount,message = inputdriftObj.get_input_drift(currentdataFrame,historicaldataFrame) \n if message == 'Model is working as expected': \n output_json = {'status':'SUCCESS','data':{'Message':'Model is working as expected'}} \n else: \n output_json = {'status':'SUCCESS','data':{'Affected Columns':message}} \n return(output_json) \n\"\"\"\n\n def get_main_drift_code(self, problem_type, smaller_is_better=True):\n text = ''\n if problem_type == 'classification':\n text += \"\"\"\ndef is_drift_within_limits(production, current_matrices,scoring_criteria,threshold = 5):\n testscore = production['score']\n current_score = current_matrices[scoring_criteria]\n threshold_value = testscore * threshold / 100.0\n if current_score > (testscore - threshold_value) :\n return True\n else:\n return False\n\ndef get_metrices(actual_values, predicted_values): \n from sklearn.metrics import accuracy_score\n from sklearn.metrics import precision_score\n from sklearn.metrics import recall_score\n from sklearn.metrics import f1_score\n result = {} \n accuracy_score = accuracy_score(actual_values, predicted_values) \n avg_precision = precision_score(actual_values, predicted_values, \n average='macro') \n avg_recall = recall_score(actual_values, predicted_values, \n average='macro') \n avg_f1 = f1_score(actual_values, predicted_values, \n average='macro') \n \n result['accuracy'] = round((accuracy_score*100),2) \n result['precision'] = round((avg_precision*100),2) \n result['recall'] = round((avg_recall*100),2) \n result['f1'] = round((avg_f1*100),2) \n return result \n \"\"\"\n else:\n text += \"\"\"\t\ndef is_drift_within_limits(production, current_matrices,scoring_criteria,threshold = 5):\n testscore = production['score']\n current_score = current_matrices[scoring_criteria]\n threshold_value = testscore * threshold / 100.0\n\"\"\"\n if smaller_is_better:\n text += \"\"\"\n if current_score < (testscore + threshold_value) :\"\"\"\n else:\n text += \"\"\"\n if current_score > (testscore - threshold_value) :\"\"\"\n text += \"\"\"\n return True\n else:\n return False\n\ndef get_metrices(actual_values, predicted_values): \n import numpy as np\n result = {}\n me = np.mean(predicted_values - actual_values)\n sde = np.std(predicted_values - actual_values, ddof = 1)\n\n abs_err = np.abs(predicted_values - actual_values)\n mae = np.mean(abs_err)\n sdae = np.std(abs_err, ddof = 1)\n\n abs_perc_err = 100.0 * np.abs(predicted_values - actual_values) / actual_values\n mape = np.mean(abs_perc_err)\n sdape = np.std(abs_perc_err, ddof = 1)\n\n result['mean_error'] = me\n result['mean_abs_error'] = mae\n result['mean_abs_perc_error'] = mape\n result['error_std'] = sde\n result['abs_error_std'] = sdae\n result['abs_perc_error_std'] = sdape\n return result\n \"\"\"\n text += \"\"\"\t \ndef monitoring(config, log=None):\n targetPath = Path('aion')/config['targetPath']\n targetPath.mkdir(parents=True, exist_ok=True)\t \t\n log_file = targetPath/IOFiles['log']\n log = logger(log_file, mode='a', logger_name=Path(__file__).parent.stem)\n output_json = {}\n trainingDataLocation = targetPath/IOFiles['trainingData']\n monitoring = targetPath/IOFiles['monitoring']\t\n log.info(f'Input Location External: {config[\"inputUriExternal\"]}')\n trainingStatus = 'False'\n dataFileLocation = ''\t\n driftStatus = 'No Drift'\n if monitoring.exists(): \t\n monitoring_data = read_json(monitoring)\n if monitoring_data.get('runNo', False):\n reader = dataReader(reader_type=monitoring_data.get('prod_db_type','sqlite'),target_path=targetPath, config=config.get('db_config',None))\n production= targetPath/IOFiles['production']\n proddataDF = pd.DataFrame()\n predicted_data = pd.DataFrame() \t\t\n if production.exists(): \n production = read_json(production) \n if reader.file_exists(IOFiles['prodData']) and reader.file_exists(IOFiles['prodDataGT']):\n predicted_data = reader.read(IOFiles['prodData']) \t\t\n actual_data = reader.read(IOFiles['prodDataGT'])\n common_col = [k for k in predicted_data.columns.tolist() if k in actual_data.columns.tolist()]\t\t\t\t\n proddataDF = pd.merge(actual_data, predicted_data, on =common_col,how = 'inner')\n currentPerformance = {} \t\t\t\n currentPerformance = get_metrices(proddataDF[config['target_feature']], proddataDF['prediction'])\n if is_drift_within_limits(production, currentPerformance,config['scoring_criteria']):\n log.info(f'OutputDrift: No output drift found')\t\t\t\t\n output_json.update({'outputDrift':'Model score is with in limits'}) \t\t\t\t\t\n else:\n log.info(f'OutputDrift: Found Output Drift')\t\t\t\t\n log.info(f'Original Test Score: {production[\"score\"]}')\t\t\t\t\t\n log.info(f'Current Score: {currentPerformance[config[\"scoring_criteria\"]]}')\t\t\t\t\n output_json.update({'outputDrift':{'Meassage': 'Model output is drifted','trainedScore':production[\"score\"], 'currentScore':currentPerformance[config[\"scoring_criteria\"]]}})\n trainingStatus = 'True'\n driftStatus = 'Output Drift'\t\t\t\t\t\n else:\n if reader.file_exists(IOFiles['prodData']):\n predicted_data = reader.read(IOFiles['prodData']) \n log.info(f'OutputDrift: Prod Data not found')\t\t\t\n output_json.update({'outputDrift':'Prod Data not found'}) \n else:\n log.info(f'Last Time pipeline not executed completely')\t\t\n output_json.update({'Msg':'Pipeline is not executed completely'})\n trainingStatus = 'True'\n if config['inputUriExternal']:\t\t\n dataFileLocation = config['inputUriExternal']\n elif 's3' in config.keys():\n dataFileLocation = 'cloud'\n else:\n dataFileLocation = config['inputUri']\t\t\t\n \n \n if trainingStatus == 'False':\t \t\t\t\n historicaldataFrame=pd.read_csv(trainingDataLocation)\n if config['inputUriExternal']:\t\t\t\n currentdataFrame=pd.read_csv(config['inputUriExternal'])\n elif not predicted_data.empty:\n currentdataFrame = predicted_data.copy() \t\t\t\n elif 's3' in config.keys():\n reader = dataReader(reader_type='s3',target_path=config['targetPath'], config=config['s3'])\n currentdataFrame = reader.read(config['s3']['file_name'])\n else:\n currentdataFrame=pd.read_csv(config['inputUri']) \t\t\t\n inputdriftObj = inputdrift(config)\n dataalertcount,inputdrift_message = inputdriftObj.get_input_drift(currentdataFrame,historicaldataFrame)\t\n\n if inputdrift_message == 'Model is working as expected':\n log.info(f'InputDrift: No input drift found')\t\t\t\n output_json.update({'Status':'SUCCESS','inputDrift':'Model is working as expected'}) \n else: \n log.info(f'InputDrift: Input drift found')\t\t\t\n log.info(f'Affected Columns {inputdrift_message}')\t\t\t\n output_json.update({'inputDrift':{'Affected Columns':inputdrift_message}}) \n trainingStatus = 'True'\n driftStatus = 'Input Drift' \n if config['inputUriExternal']:\n dataFileLocation = config['inputUriExternal']\n elif actual_data_path.exists() and predict_data_path.exists():\t\n dataFileLocation = ''\n elif 's3' in config.keys():\n dataFileLocation = 'cloud'\n else:\n dataFileLocation = config['inputUri']\t\t\t\t\t\n else:\n log.info(f'Pipeline Executing first Time')\t\n output_json.update({'Msg':'Pipeline executing first time'}) \t\n trainingStatus = 'True'\n if config['inputUriExternal']:\t\t\n dataFileLocation = config", "instruction": "", "output": "" }, { "input": "['inputUriExternal']\n elif 's3' in config.keys():\n dataFileLocation = 'cloud'\n else:\n dataFileLocation = config['inputUri']\n else:\n log.info(f'Pipeline Executing first Time')\t\n output_json.update({'Msg':'Pipeline executing first time'}) \t\n trainingStatus = 'True'\n if config['inputUriExternal']:\t\t\n dataFileLocation = config['inputUriExternal']\n elif 's3' in config.keys():\n dataFileLocation = 'cloud'\n else:\n dataFileLocation = config['inputUri']\n if monitoring.exists():\n monitoring_data['runNo'] = int(monitoring_data.get('runNo', '0')) + 1\t\t\n else:\n monitoring_data = {}\n monitoring_data['runNo'] = 1\n monitoring_data['prod_db_type'] = config.get('prod_db_type', 'sqlite')\n monitoring_data['db_config'] = config.get('db_config', {})\n monitoring_data['mlflow_config'] = config.get('mlflow_config', None)\n if 's3' in config.keys():\n monitoring_data['s3'] = config['s3']\n monitoring_data['dataLocation'] = dataFileLocation\n monitoring_data['driftStatus'] = driftStatus\n write_json(monitoring_data,targetPath/IOFiles['monitoring'])\n output = {'Status':'SUCCESS'}\n output.update(output_json)\n return(json.dumps(output)) \n \t\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--inputUri', help='Training Data Location')\n\n args = parser.parse_args()\n config_file = Path(__file__).parent/'config.json'\n if not Path(config_file).exists():\n raise ValueError(f'Config file is missing: {config_file}')\n config = read_json(config_file)\n config['inputUriExternal'] = None\n if args.inputUri:\n if \targs.inputUri != '':\n config['inputUriExternal'] = args.inputUri\n log = None\n try:\n print(monitoring(config, log))\n except Exception as e:\n if log:\n log.error(e, exc_info=True)\n status = {'Status':'Failure','Message':str(e)}\n print(json.dumps(status))\n raise Exception(str(e))\n\"\"\"\n return text \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\nimport json\n\nclass deploy():\n\n def __init__(self, target_encoder=False, feature_reducer=False, score_smaller_is_better=True, tab_size=4):\n self.tab = ' ' * tab_size\n self.codeText = \"\\\\n\\\\n\\\\\n\\\\nclass deploy():\\\\\n\\\\n\\\\\n\\\\n def __init__(self, base_config, log=None):\\\\\n \\\\n self.targetPath = (Path('aion')/base_config['targetPath']).resolve()\\\\\n \\\\n if log:\\\\\n \\\\n self.logger = log\\\\\n \\\\n else:\\\\\n \\\\n log_file = self.targetPath/IOFiles['log']\\\\\n \\\\n self.logger = logger(log_file, mode='a', logger_name=Path(__file__).parent.stem)\\\\\n \\\\n try:\\\\\n \\\\n self.initialize(base_config)\\\\\n \\\\n except Exception as e:\\\\\n \\\\n self.logger.error(e, exc_info=True)\\\\\n \\\\n\\\\\n\\\\n def initialize(self, base_config):\\\\\n \\\\n self.usecase = base_config['targetPath']\\\\\n \\\\n monitoring_data = read_json(self.targetPath/IOFiles['monitor'])\\\\\n \\\\n self.prod_db_type = monitoring_data['prod_db_type']\\\\\n \\\\n self.db_config = monitoring_data['db_config']\\\\\n \\\\n mlflow_default_config = {'artifacts_uri':'','tracking_uri_type':'','tracking_uri':'','registry_uri':''}\\\\\n \\\\n tracking_uri, artifact_uri, registry_uri = get_mlflow_uris(monitoring_data.get('mlflow_config',mlflow_default_config), self.targetPath)\\\\\n \\\\n mlflow.tracking.set_tracking_uri(tracking_uri)\\\\\n \\\\n mlflow.tracking.set_registry_uri(registry_uri)\\\\\n \\\\n client = mlflow.tracking.MlflowClient()\\\\\n \\\\n self.model_version = client.get_latest_versions(self.usecase, stages=['production'] )\\\\\n \\\\n model_version_uri = 'models:/{model_name}/production'.format(model_name=self.usecase)\\\\\n \\\\n self.model = mlflow.pyfunc.load_model(model_version_uri)\\\\\n \\\\n run = client.get_run(self.model.metadata.run_id)\\\\\n \\\\n if run.info.artifact_uri.startswith('file:'): #remove file:///\\\\\n \\\\n skip_name = 'file:'\\\\\n \\\\n if run.info.artifact_uri.startswith('file:///'):\\\\\n \\\\n skip_name = 'file:///'\\\\\n \\\\n self.artifact_path = Path(run.info.artifact_uri[len(skip_name) : ])\\\\\n \\\\n self.artifact_path_type = 'file'\\\\\n \\\\n meta_data = read_json(self.artifact_path/IOFiles['metaData'])\\\\\n \\\\n else:\\\\\n \\\\n self.artifact_path = run.info.artifact_uri\\\\\n \\\\n self.artifact_path_type = 'url'\\\\\n \\\\n meta_data_file = mlflow.artifacts.download_artifacts(self.artifact_path+'/'+IOFiles['metaData'])\\\\\n \\\\n meta_data = read_json(meta_data_file)\\\\\n \\\\n self.selected_features = meta_data['load_data']['selected_features']\\\\\n \\\\n self.train_features = meta_data['training']['features']\"\n if target_encoder:\n self.codeText += \"\\\\\n \\\\n if self.artifact_path_type == 'url':\\\\\n \\\\n preprocessor_file = mlflow.artifacts.download_artifacts(self.artifact_path+'/'+meta_data['transformation']['preprocessor'])\\\\\n \\\\n target_encoder_file = mlflow.artifacts.download_artifacts(self.artifact_path+'/'+meta_data['transformation']['target_encoder'])\\\\\n \\\\n else:\\\\\n \\\\n preprocessor_file = self.artifact_path/meta_data['transformation']['preprocessor']\\\\\n \\\\n target_encoder_file = self.artifact_path/meta_data['transformation']['target_encoder']\\\\\n \\\\n self.target_encoder = joblib.load(target_encoder_file)\"\n else:\n self.codeText += \"\\\\\n \\\\n if self.artifact_path_type == 'url':\\\\\n \\\\n preprocessor_file = mlflow.artifacts.download_artifacts(self.artifact_path+'/'+meta_data['transformation']['preprocessor'])\\\\\n \\\\n else:\\\\\n \\\\n preprocessor_file = self.artifact_path/meta_data['transformation']['preprocessor']\"\n self.codeText += \"\\\\\n \\\\n self.preprocessor = joblib.load(preprocessor_file)\\\\\n \\\\n self.preprocess_out_columns = meta_data['transformation']['preprocess_out_columns']\\\\\n \"\n if feature_reducer:\n self.codeText += \"\\\\\n \\\\n if self.artifact_path_type == 'url':\\\\\n \\\\n feature_reducer_file = mlflow.artifacts.download_artifacts(self.artifact_path+'/'+meta_data['featureengineering']['feature_reducer']['file'])\\\\\n \\\\n else:\\\\\n \\\\n feature_reducer_file = self.artifact_path/meta_data['featureengineering']['feature_reducer']['file']\\\\\n \\\\n self.feature_reducer = joblib.load(feature_reducer_file)\\\\\n \\\\n self.feature_reducer_cols = meta_data['featureengineering']['feature_reducer']['features']\"\n self.codeText +=\"\\\\n\\\\\n\\\\n def write_to_db(self, data):\\\\\n\\\\n prod_file = IOFiles['prodData']\\\\\n\\\\n writer = dataReader(reader_type=self.prod_db_type,target_path=self.targetPath, config=self.db_config )\\\\\n\\\\n writer.write(data, prod_file)\\\\\n\\\\n writer.close()\\\\\n\\\\n\\\\\n\\\\n def predict(self, data=None):\\\\\n\\\\n try:\\\\\n\\\\n return self.__predict(data)\\\\\n\\\\n except Exception as e:\\\\\n\\\\n if self.logger:\\\\\n\\\\n self.logger.error(e, exc_info=True)\\\\\n\\\\n raise ValueError(json.dumps({'Status':'Failure', 'Message': str(e)}))\\\\\n\\\\n\\\\\n\\\\n def __predict(self, data=None):\\\\\n\\\\n df = pd.DataFrame()\\\\\n\\\\n jsonData = json.loads(data)\\\\\n\\\\n df = pd.json_normalize(jsonData)\\\\\n\\\\n if len(df) == 0:\\\\\n\\\\n raise ValueError('No data record found')\\\\\n\\\\n missing_features = [x for x in self.selected_features if x not in df.columns]\\\\\n\\\\n if missing_features:\\\\\n\\\\n raise ValueError(f'some feature/s is/are missing: {missing_features}')\\\\\n\\\\n df_copy = df.copy()\\\\\n\\\\n df = df[self.selected_features]\\\\\n\\\\n df = self.preprocessor.transform(df)\\\\\n\\\\n if isinstance(df, scipy.sparse.spmatrix):\\\\\n\\\\n df = df.toarray()\\\\\n\\\\n df = pd.DataFrame(df, columns=self.preprocess_out_columns)\"\n if feature_reducer:\n self.codeText += \"\\\\n df = self.feature_reducer.transform(df[self.feature_reducer_cols])\"\n else:\n self.codeText += \"\\\\n df = df[self.train_features]\"\n if target_encoder:\n self.codeText += \"\\\\n df = df.astype(np.float32)\\\\\n\t\t\\\\n output = pd.DataFrame(self.model._model_impl.predict_proba(df), columns=self.target_encoder.classes_)\\\\\n \\\\n df_copy['prediction'] = output.idxmax(axis=1)\\\\\n \\\\n self.write_to_db(df_copy)\\\\\n \\\\n df_copy['probability'] = output.max(axis=1).round(2)\\\\\n \\\\n df_copy['remarks'] = output.apply(lambda x: x.to_json(), axis=1)\\\\\n \\\\n output = df_copy.to_json(orient='records')\"\n else:\n self.codeText += \"\\\\n output = self.model._model_impl.predict(df).reshape(1, -1)[0].round(2)\\\\\n \\\\n df_copy['prediction'] = output\\\\\n \\\\n self.write_to_db(df_copy)\\\\\n \\\\n output = df_copy.to_json(orient='records')\"\n self.codeText += \"\\\\n return output\"\n self.input_files = {}\n self.output_files = {}\n self.addInputFiles({'inputData' : 'rawData.dat', 'metaData' : 'modelMetaData.json', 'performance' : 'performance.json','monitor':'monitoring.json','log':'predict.log','prodData':'prodData'})\n \n def addInputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def addOutputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def getInputFiles(self): \n text = 'IOFiles = '\n if not self.input_files:\n text += '{ }'\n else:\n text += json.dumps(self.input_files, indent=4)\n return text\n \n def getOutputFiles(self):\n text = 'output_file = '\n if not self.output_files:\n text += '{ }'\n else:\n text += json.dumps(self.output_files, indent=4)\n return text\n \n def getInputOutputFiles(self, indent=0):\n text = '\\\\n'\n text += self.getInputFiles()\n text += '\\\\n'\n text += self.getOutputFiles()\n if indent:\n text = text.replace('\\\\n', self.tab * indent + '\\\\n')\n return text\n\n def addStatement(self, statement, indent=1):\n pass\n \n def getCode(self):\n return self.codeText\n\n def getGroundtruthCode(self):\n return \"\"\"\nimport sys\nimport math\nimport json\nimport sqlite3\nimport pandas as pd\nfrom datetime import datetime\nfrom pathlib import Path\nimport platform\nfrom utility import *\nfrom data_reader import dataReader\n\nIOFiles = {\n \"monitoring\":\"monitoring.json\", \n \"prodDataGT\":\"prodDataGT\"\n }\n\nclass groundtruth():\n \n def __init__(self, base_config): \n self.targetPath = Path('aion')/base_config['targetPath'] \n data = read_json(self.targetPath/IOFiles['monitoring'])\n self.prod_db_type = data['prod_db_type']\n self.db_config = data['db_config']\n\t\n def actual(self, data=None):\n df = pd.DataFrame()\n jsonData = json.loads(data)\n df = pd.json_normalize(jsonData)\n if len(df) == 0:\n raise ValueError('No data record found')\n self.write_to_db(df)\n status = {'Status':'Success','Message':'uploaded'}\n return json.dumps(status)\n\t\t\n def write_to_db(self, data):\n prod_file = IOFiles['prodDataGT']\n writer = dataReader(reader_type=self.prod_db_type, target_path=self.targetPath, config=self.db_config )\n writer.write(data, prod_file)\n writer.close()\n\t\t\t\n\"\"\"\n def getServiceCode(self):\n return \"\"\"\n\nfrom http.server import BaseHTTPRequestHandler,HTTPServer \nfrom socketserver import ThreadingMixIn \nimport os \nfrom os.path import expanduser \nimport platform \nimport threading \nimport subprocess \nimport argparse \nimport re \nimport cgi \nimport json \nimport shutil\nimport logging\nimport sys \nimport time\nimport seaborn as sns\nfrom pathlib import Path \nfrom predict import deploy\nfrom groundtruth import groundtruth \nimport pandas as pd\nimport scipy.stats as st\nimport numpy as np\nimport warnings\nfrom utility import *\nfrom data_reader import dataReader\n\nwarnings.filterwarnings(\"ignore\")\nconfig_input = None \n \nIOFiles = {\n\t\"inputData\": \"rawData.dat\",\n\t\"metaData\": \"modelMetaData.json\",\n\t\"", "instruction": "", "output": "" }, { "input": "production\": \"production.json\", \n\t\"log\": \"aion.log\",\n\t\"monitoring\":\"monitoring.json\",\n\t\"prodData\": \"prodData\",\n\t\"prodDataGT\":\"prodDataGT\"\n}\n\ndef DistributionFinder(data):\n try:\n distributionName = \"\"\n sse = 0.0\n KStestStatic = 0.0\n dataType = \"\"\n if (data.dtype == \"float64\" or data.dtype == \"float32\"):\n dataType = \"Continuous\"\n elif (data.dtype == \"int\"):\n dataType = \"Discrete\"\n elif (data.dtype == \"int64\"):\n dataType = \"Discrete\"\n if (dataType == \"Discrete\"):\n distributions = [st.bernoulli, st.binom, st.geom, st.nbinom, st.poisson]\n index, counts = np.unique(data.astype(int), return_counts=True)\n\n if (len(index) >= 2):\n best_sse = np.inf\n y1 = []\n total = sum(counts)\n mean = float(sum(index * counts)) / total\n variance = float((sum(index ** 2 * counts) - total * mean ** 2)) / (total - 1)\n dispersion = mean / float(variance)\n theta = 1 / float(dispersion)\n r = mean * (float(theta) / 1 - theta)\n\n for j in counts:\n y1.append(float(j) / total)\n\n pmf1 = st.bernoulli.pmf(index, mean)\n pmf2 = st.binom.pmf(index, len(index), p=mean / len(index))\n pmf3 = st.geom.pmf(index, 1 / float(1 + mean))\n pmf4 = st.nbinom.pmf(index, mean, r)\n pmf5 = st.poisson.pmf(index, mean)\n\n sse1 = np.sum(np.power(y1 - pmf1, 2.0))\n sse2 = np.sum(np.power(y1 - pmf2, 2.0))\n sse3 = np.sum(np.power(y1 - pmf3, 2.0))\n sse4 = np.sum(np.power(y1 - pmf4, 2.0))\n sse5 = np.sum(np.power(y1 - pmf5, 2.0))\n\n sselist = [sse1, sse2, sse3, sse4, sse5]\n best_distribution = 'NA'\n for i in range(0, len(sselist)):\n if best_sse > sselist[i] > 0:\n best_distribution = distributions[i].name\n best_sse = sselist[i]\n\n elif (len(index) == 1):\n best_distribution = \"Constant Data-No Distribution\"\n best_sse = 0.0\n\n distributionName = best_distribution\n sse = best_sse\n\n elif (dataType == \"Continuous\"):\n\n distributions = [st.uniform, st.expon, st.weibull_max, st.weibull_min, st.chi, st.norm, st.lognorm, st.t,\n st.gamma, st.beta]\n best_distribution = st.norm.name\n best_sse = np.inf\n datamin = data.min()\n datamax = data.max()\n nrange = datamax - datamin\n\n y, x = np.histogram(data.astype(float), bins='auto', density=True)\n x = (x + np.roll(x, -1))[:-1] / 2.0\n\n for distribution in distributions:\n params = distribution.fit(data.astype(float))\n arg = params[:-2]\n loc = params[-2]\n scale = params[-1]\n pdf = distribution.pdf(x, loc=loc, scale=scale, *arg)\n sse = np.sum(np.power(y - pdf, 2.0))\n if (best_sse > sse > 0):\n best_distribution = distribution.name\n best_sse = sse\n distributionName = best_distribution\n sse = best_sse\n except:\n response = str(sys.exc_info()[0])\n message = 'Job has Failed' + response\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type) + ' ' + str(fname) + ' ' + str(exc_tb.tb_lineno))\n print(message)\n return distributionName, sse\n \ndef getDriftDistribution(feature, dataframe, newdataframe=pd.DataFrame()):\n import matplotlib.pyplot as plt\n import math\n import io, base64, urllib\n np.seterr(divide='ignore', invalid='ignore')\n try:\t\n plt.clf()\n except:\n pass\n plt.rcParams.update({'figure.max_open_warning': 0})\n sns.set(color_codes=True)\n pandasNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n if len(feature) > 4:\n numneroffeatures = len(feature)\n plt.figure(figsize=(10, numneroffeatures*2))\n else:\n plt.figure(figsize=(10,5))\n \n for i in enumerate(feature):\n \n dataType = dataframe[i[1]].dtypes\n if dataType not in pandasNumericDtypes:\n dataframe[i[1]] = pd.Categorical(dataframe[i[1]])\n dataframe[i[1]] = dataframe[i[1]].cat.codes\n dataframe[i[1]] = dataframe[i[1]].astype(int)\n dataframe[i[1]] = dataframe[i[1]].fillna(dataframe[i[1]].mode()[0])\n else:\n dataframe[i[1]] = dataframe[i[1]].fillna(dataframe[i[1]].mean())\n \n plt.subplots_adjust(hspace=0.5, wspace=0.7, top=1)\n plt.subplot(math.ceil((len(feature) / 2)), 2, i[0] + 1)\n distname, sse = DistributionFinder(dataframe[i[1]]) \n print(distname) \n ax = sns.distplot(dataframe[i[1]], label=distname)\n ax.legend(loc='best')\n if newdataframe.empty == False:\n dataType = newdataframe[i[1]].dtypes\n if dataType not in pandasNumericDtypes:\n newdataframe[i[1]] = pd.Categorical(newdataframe[i[1]])\n newdataframe[i[1]] = newdataframe[i[1]].cat.codes\n newdataframe[i[1]] = newdataframe[i[1]].astype(int)\n newdataframe[i[1]] = newdataframe[i[1]].fillna(newdataframe[i[1]].mode()[0])\n else:\n newdataframe[i[1]] = newdataframe[i[1]].fillna(newdataframe[i[1]].mean())\n distname, sse = DistributionFinder(newdataframe[i[1]]) \n print(distname)\n ax = sns.distplot(newdataframe[i[1]],label=distname)\n ax.legend(loc='best')\n buf = io.BytesIO()\n plt.savefig(buf, format='png')\n buf.seek(0)\n string = base64.b64encode(buf.read())\n uri = urllib.parse.quote(string)\n return uri\n\t\ndef read_json(file_path): \n data = None \n with open(file_path,'r') as f: \n data = json.load(f) \n return data \n \nclass HTTPRequestHandler(BaseHTTPRequestHandler): \n \n\tdef do_POST(self): \n\t\tprint('PYTHON ######## REQUEST ####### STARTED') \n\t\tif None != re.search('/AION/', self.path) or None != re.search('/aion/', self.path):\n\t\t\tctype, pdict = cgi.parse_header(self.headers.get('content-type')) \n\t\t\tif ctype == 'application/json': \n\t\t\t\tlength = int(self.headers.get('content-length')) \n\t\t\t\tdata = self.rfile.read(length) \n\t\t\t\tusecase = self.path.split('/')[-2]\n\t\t\t\tif usecase.lower() == config_input['targetPath'].lower():\t\t\t\t\t\n\t\t\t\t\toperation = self.path.split('/')[-1] \n\t\t\t\t\tdata = json.loads(data) \n\t\t\t\t\tdataStr = json.dumps(data) \n\t\t\t\t\tif operation.lower() == 'predict': \n\t\t\t\t\t\toutput=deployobj.predict(dataStr) \n\t\t\t\t\t\tresp = output \n\t\t\t\t\telif operation.lower() == 'groundtruth':\n\t\t\t\t\t\tgtObj = groundtruth(config_input)\t\t\t\t\n\t\t\t\t\t\toutput = gtObj.actual(dataStr)\n\t\t\t\t\t\tresp = output \n\t\t\t\t\telif operation.lower() == 'delete':\n\t\t\t\t\t\ttargetPath = Path('aion')/config_input['targetPath'] \n\t\t\t\t\t\tfor file in data:\n\t\t\t\t\t\t\tx = targetPath/file \n\t\t\t\t\t\t\tif x.exists():\n\t\t\t\t\t\t\t\tos.remove(x) \n\t\t\t\t\t\tresp = json.dumps({'Status':'Success'})\n\t\t\t\t\telse: \n\t\t\t\t\t\toutputStr = json.dumps({'Status':'Error','Msg':'Operation not supported'}) \n\t\t\t\t\t\tresp = outputStr \n\t\t\t\telse:\n\t\t\t\t\toutputStr = json.dumps({'Status':'Error','Msg':'Wrong URL'}) \n\t\t\t\t\tresp = outputStr\n \n\t\t\telse: \n\t\t\t\toutputStr = json.dumps({'Status':'ERROR','Msg':'Content-Type Not Present'}) \n\t\t\t\tresp = outputStr \n\t\t\tresp=resp+'\\\\\\\\n' \n\t\t\tresp=resp.encode() \n\t\t\tself.send_response(200) \n\t\t\tself.send_header('Content-Type', 'application/json') \n\t\t\tself.end_headers() \n\t\t\tself.wfile.write(resp) \n\t\telse: \n\t\t\tprint('python ==> else1') \n\t\t\tself.send_response(403) \n\t\t\tself.send_header('Content-Type', 'application/json') \n\t\t\tself.end_headers() \n\t\t\tprint('PYTHON ######## REQUEST ####### ENDED') \n\t\treturn \n \n\tdef do_GET(self): \n\t\tprint('PYTHON ######## REQUEST ####### STARTED') \n\t\tif None != re.search('/AION/', self.path) or None != re.search('/aion/', self.path): \n\t\t\tusecase = self.path.split('/')[-2] \n\t\t\tself.send_response(200) \n\t\t\tself.targetPath = Path('aion')/config_input['targetPath']\t\t\t\n\t\t\tmeta_data_file = self.targetPath/IOFiles['metaData'] \n\t\t\tif meta_data_file.exists(): \n\t\t\t\tmeta_data = read_json(meta_data_file) \n\t\t\telse: \n\t\t\t\traise ValueError(f'Configuration file not found: {meta_data_file}')\n\t\t\tproduction_file = self.targetPath/IOFiles['production'] \n\t\t\tif production_file.exists(): \n\t\t\t\tproduction_data = read_json(production_file) \n\t\t\telse: \n\t\t\t\traise ValueError(f'Production Details not found: {production_file}') \n\t\t\toperation = self.path.split('/')[-1] \n\t\t\tif (usecase.lower() == config_input['targetPath'].lower()) and (operation.lower() == 'metrices'):\n\t\t\t\tself.send_header('Content-Type', 'text/html') \n\t\t\t\tself.end_headers() \n\t\t\t\tModelString = production_data['Model']\n\t\t\t\tModelPerformance = ModelString+'_performance.json' \n\t\t\t\tperformance_file = self.targetPath/ModelPerformance \n\t\t\t\tif performance_file.exists(): \n\t\t\t\t\tperformance_data = read_json(performance_file) \n\t\t\t\telse: \n\t\t\t\t\traise ValueError(f'Production Details not found: {performance_data}')\n\t\t\t\tScoring_Creteria = performance_data['scoring_criteria'] \n\t\t\t\ttrain_score = round(performance_data['metrices']['train_score'],2) \n\t\t\t\ttest_score = round(performance_data['metrices']['test_score'],2) \n\t\t\t\tcurrent_score = 'NA' \n\t\t\t\tmonitoring = read_json(self.targetPath/IOFiles['monitoring'])\n\t\t\t\treader = dataReader(reader_type=monitoring['prod_db_type'],target_path=self.targetPath, config=monitoring['db_config'])\n\t\t\t\tinputDatafile = self.targetPath/IOFiles['inputData'] \n\t\t\t\tNoOfPrediction = 0\n\t\t\t\tNoOfGroundTruth = 0 \n\t\t\t\tinputdistribution = '' \n\t\t\t\tif reader.file_exists(IOFiles['prodData']): \n\t\t\t\t\tdfPredict = reader.read(IOFiles['prodData'])\n\t\t\t\t\tdfinput = pd.read_csv(inputDatafile)\n\t\t\t\t\tfeatures = meta_data['training']['features']\n\t\t\t\t\tinputdistribution = getDriftDistribution(features,dfinput,dfPredict) \n\t\t\t\t\tNoOfPrediction = len(dfPredict)\t\t\t\t\n\t\t\t\t\tif reader.file_exists(IOFiles['prodDataGT']): \n\t\t\t\t\t\tdfGroundTruth = reader.read(IOFiles['prodDataGT'])\n\t\t\t\t\t\tNoOfGroundTruth = len(dfGroundTruth) \n\t\t\t\t\t\tcommon_col = [k for k in dfPredict.columns.tolist() if k in dfGroundTruth.columns.tolist()]\t\t\t\t\n\t\t\t\t\t\tproddataDF = pd.merge(dfPredict, dfGroundTruth, on =common_col,how = 'inner')\n\t\t\t\t\t\tif Scoring_Creteria.lower() == 'accuracy': \n\t\t\t\t\t\t\tfrom sklearn.metrics import accuracy_score \n\t\t\t\t\t\t\tcurrent_score = accuracy_score(proddataDF[config_input['target_feature']], proddataDF['prediction'])\n\t\t\t\t\t\t\tcurrent_score = round((current_score*100),2) \n\t\t\t\t\t\telif Scoring_Creteria.lower() == 'recall': \n\t\t\t\t\t\t\tfrom sklearn.metrics import accuracy_score \n\t\t\t\t\t\t\tcurrent_score = recall_score(proddataDF[config_input['target_feature']], proddataDF['prediction'],average='macro')\n\t\t\t\t\t\t\tcurrent_score = round((current_score", "instruction": "", "output": "" }, { "input": "*100),2) \n\t\t\t\tmsg = \\\\\"\"\"\n\nPerformance Details\n\n\n\n

Deployed Model:{ModelString}

\n
\n\n\n\n\n\n\n\n\n\n
No of Prediction{NoOfPrediction}
No of GroundTruth{NoOfGroundTruth}
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Score TypeTrain ScoreTest ScoreProduction Score
{Scoring_Creteria}{train_score}{test_score}{current_score}
\n
\n
\n\"\"\n\n\n\\\\\"\"\".format(border='{border: 1px solid black;}',ModelString=ModelString,Scoring_Creteria=Scoring_Creteria,NoOfPrediction=NoOfPrediction,NoOfGroundTruth=NoOfGroundTruth,train_score=train_score,test_score=test_score,current_score=current_score,newDataDrift=inputdistribution)\n\t\t\telif (usecase.lower() == config_input['targetPath'].lower()) and (operation.lower() == 'logs'): \n\t\t\t\tself.send_header('Content-Type', 'text/plain') \n\t\t\t\tself.end_headers() \n\t\t\t\tlog_file = self.targetPath/IOFiles['log'] \n\t\t\t\tif log_file.exists():\n\t\t\t\t\twith open(log_file) as f:\n\t\t\t\t\t\tmsg = f.read() \n\t\t\t\t\tf.close()\n\t\t\t\telse: \n\t\t\t\t\traise ValueError(f'Log Details not found: {log_file}') \n\t\t\telse:\n\t\t\t\tself.send_header('Content-Type', 'application/json') \n\t\t\t\tself.end_headers() \n\t\t\t\tfeatures = meta_data['load_data']['selected_features']\n\t\t\t\tbodydes='['\n\t\t\t\tfor x in features:\n\t\t\t\t\tif bodydes != '[':\n\t\t\t\t\t\tbodydes = bodydes+','\n\t\t\t\t\tbodydes = bodydes+'{\"'+x+'\":\"value\"}'\t\n\t\t\t\tbodydes+=']'\n\t\t\t\turltext = '/AION/'+config_input['targetPath']+'/predict'\n\t\t\t\turltextgth='/AION/'+config_input['targetPath']+'/groundtruth'\n\t\t\t\turltextproduction='/AION/'+config_input['targetPath']+'/metrices'\n\t\t\t\tmsg=\\\\\"\"\"\nVersion:{modelversion}\nRunNo: {runNo}\nURL for Prediction\n==================\nURL:{url}\nRequestType: POST\nContent-Type=application/json\nBody: {displaymsg}\nOutput: prediction,probability(if Applicable),remarks corresponding to each row.\n\nURL for GroundTruth\n===================\nURL:{urltextgth}\nRequestType: POST\nContent-Type=application/json\nNote: Make Sure that one feature (ID) should be unique in both predict and groundtruth. Otherwise outputdrift will not work \n\nURL for Model In Production Analysis\n====================================\nURL:{urltextproduction}\nRequestType: GET\nContent-Type=application/json\n\n\\\\\"\"\".format(modelversion=config_input['modelVersion'],runNo=config_input['deployedRunNo'],url=urltext,urltextgth=urltextgth,urltextproduction=urltextproduction,displaymsg=bodydes) \n\t\t\tself.wfile.write(msg.encode()) \n\t\telse: \n\t\t\tself.send_response(403) \n\t\t\tself.send_header('Content-Type', 'application/json') \n\t\t\tself.end_headers() \n\t\treturn \n \nclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer): \n\tallow_reuse_address = True \n \n\tdef shutdown(self): \n\t\tself.socket.close() \n\t\tHTTPServer.shutdown(self) \n \nclass file_status():\n\t\n\tdef __init__(self, reload_function, params, file, logger):\n\t\tself.files_status = {}\n\t\tself.initializeFileStatus(file)\n\t\tself.reload_function = reload_function\n\t\tself.params = params\n\t\tself.logger = logger\n\t\t\n\tdef initializeFileStatus(self, file):\n\t\tself.files_status = {'path': file, 'time':file.stat().st_mtime}\n\n\tdef is_file_changed(self):\n\t\tif self.files_status['path'].stat().st_mtime > self.files_status['time']:\n\t\t\tself.files_status['time'] = self.files_status['path'].stat().st_mtime\n\t\t\treturn True\n\t\treturn False\n\t\t\n\tdef run(self):\n\t\tglobal config_input \n\t\twhile( True):\n\t\t\ttime.sleep(30)\n\t\t\tif self.is_file_changed():\n\t\t\t\tproduction_details = targetPath/IOFiles['production']\n\t\t\t\tif not production_details.exists(): \n\t\t\t\t\traise ValueError(f'Model in production details does not exist')\n\t\t\t\tproductionmodel = read_json(production_details)\n\t\t\t\tconfig_file = Path(__file__).parent/'config.json' \n\t\t\t\tif not Path(config_file).exists(): \n\t\t\t\t\traise ValueError(f'Config file is missing: {config_file}') \n\t\t\t\tconfig_input = read_json(config_file)\t\t\t\t\n\t\t\t\tconfig_input['deployedModel'] = productionmodel['Model']\n\t\t\t\tconfig_input['deployedRunNo'] = productionmodel['runNo']\n\t\t\t\tself.logger.info('Model changed Reloading.....')\n\t\t\t\tself.logger.info(f'Model: {config_input[\"deployedModel\"]}')\t\t\t\t\n\t\t\t\tself.logger.info(f'Version: {str(config_input[\"modelVersion\"])}')\n\t\t\t\tself.logger.info(f'runNo: {str(config_input[\"deployedRunNo\"])}')\n\t\t\t\tself.reload_function(config_input)\n\t\t\t\nclass SimpleHttpServer(): \n\tdef __init__(self, ip, port, model_file_path,reload_function,params, logger): \n\t\tself.server = ThreadedHTTPServer((ip,port), HTTPRequestHandler) \n\t\tself.status_checker = file_status( reload_function, params, model_file_path, logger)\n\t\t\n\tdef start(self): \n\t\tself.server_thread = threading.Thread(target=self.server.serve_forever) \n\t\tself.server_thread.daemon = True \n\t\tself.server_thread.start() \n\t\tself.status_thread = threading.Thread(target=self.status_checker.run) \n\t\tself.status_thread.start() \n\t\t\n\tdef waitForThread(self): \n\t\tself.server_thread.join() \n\t\tself.status_thread.join() \n\t\t\n\tdef stop(self): \n\t\tself.server.shutdown() \n\t\tself.waitForThread() \n \nif __name__=='__main__': \n\tparser = argparse.ArgumentParser(description='HTTP Server') \n\tparser.add_argument('-ip','--ipAddress', help='HTTP Server IP') \n\tparser.add_argument('-pn','--portNo', type=int, help='Listening port for HTTP Server') \n\targs = parser.parse_args() \n\tconfig_file = Path(__file__).parent/'config.json' \n\tif not Path(config_file).exists(): \n\t\traise ValueError(f'Config file is missing: {config_file}') \n\tconfig = read_json(config_file) \n\tif args.ipAddress: \n\t\tconfig['ipAddress'] = args.ipAddress \n\tif args.portNo: \n\t\tconfig['portNo'] = args.portNo \n\ttargetPath = Path('aion')/config['targetPath'] \n\tif not targetPath.exists(): \n\t\traise ValueError(f'targetPath does not exist')\n\tproduction_details = targetPath/IOFiles['production']\n\tif not production_details.exists(): \n\t\traise ValueError(f'Model in production details does not exist')\n\tproductionmodel = read_json(production_details)\n\tconfig['deployedModel'] = productionmodel['Model']\n\tconfig['deployedRunNo'] = productionmodel['runNo']\t\n\t#server = SimpleHttpServer(config['ipAddress'],int(config['portNo'])) \n\tconfig_input = config \n\tlogging.basicConfig(filename= Path(targetPath)/IOFiles['log'], filemode='a', format='%(asctime)s %(name)s- %(message)s', level=logging.INFO, datefmt='%d-%b-%y %H:%M:%S') \n\tlogger = logging.getLogger(Path(__file__).parent.name) \n\tdeployobj = deploy(config_input, logger)\n\tserver = SimpleHttpServer(config['ipAddress'],int(config['portNo']),targetPath/IOFiles['production'],deployobj.initialize,config_input, logger)\n\tlogger.info('HTTP Server Running...........')\n\tlogger.info(f\"IP Address: {config['ipAddress']}\")\n\tlogger.info(f\"Port No.: {config['portNo']}\")\n\tprint('HTTP Server Running...........') \n\tprint('For Prediction')\n\tprint('================')\n\tprint('Request Type: Post')\n\tprint('Content-Type: application/json')\t\n\tprint('URL: /AION/'+config['targetPath']+'/predict')\t\n\tprint('\\\\\\\\nFor GroundTruth')\n\tprint('================')\n\tprint('Request Type: Post')\n\tprint('Content-Type: application/json')\t\n\tprint('URL: /AION/'+config['targetPath']+'/groundtruth')\t\n\tprint('\\\\\\\\nFor Help')\n\tprint('================')\n\tprint('Request Type: Get')\n\tprint('Content-Type: application/json')\t\n\tprint('URL: /AION/'+config['targetPath']+'/help')\t\n\tprint('\\\\\\\\nFor Model In Production Analysis')\n\tprint('================')\n\tprint('Request Type: Get')\n\tprint('Content-Type: application/json')\t\n\tprint('URL: /AION/'+config['targetPath']+'/metrices') \n\tserver.start() \n\tserver.waitForThread()\n\"\"\" \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nimport shutil\nfrom pathlib import Path\nimport json\nfrom mlac.ml.core import *\nfrom .utility import *\nimport tarfile\n\noutput_file_map = {\n 'text' : {'text' : 'text_profiler.pkl'},\n 'targetEncoder' : {'targetEncoder' : 'targetEncoder.pkl'},\n 'featureEncoder' : {'featureEncoder' : 'inputEncoder.pkl'},\n 'normalizer' : {'normalizer' : 'normalizer.pkl'}\n}\n\ndef add_common_imports(importer):\n common_importes = [\n {'module': 'json', 'mod_from': None, 'mod_as': None},\n {'module': 'Path', 'mod_from': 'pathlib', 'mod_as': None},\n {'module': 'pandas', 'mod_from': None, 'mod_as': 'pd'},\n {'module': 'argparse', 'mod_from': None, 'mod_as': None},\n {'module': 'platform', 'mod_from': None, 'mod_as': None } \n ]\n for mod in common_importes:\n importer.addModule(mod['module'], mod_from=mod['mod_from'], mod_as=mod['mod_as'])\n\ndef add_text_dependency():\n return \"\"\"nltk==3.6.3\ntextblob==0.15.3\nspacy==3.1.3\ndemoji==1.1.0\nbs4==0.0.1\ntext_unidecode==1.3\ncontractions==0.1.73\n\"\"\"\n \ndef get_transformer_params(config):\n param_keys = [\"modelVersion\",\"problem_type\",\"target_feature\",\"train_features\",\"text_features\",\"profiler\",\"test_ratio\"] #Bugid 13217\n data = {key:value for (key,value) in config.items() if key in param_keys}\n data['targetPath'] = config['modelName']\n return data\n \ndef run_transformer(config):\n transformer = profiler()\n importer = importModule()\n function = global_function()\n importModules(importer, transformer.getPrefixModules())\n importer.addModule('warnings') \n transformer.addPrefixCode()\n importer.addModule('train_test_split', mod_from='sklearn.model_selection')\n if config[\"problem_type\"] == 'classification':\n importer.addModule('LabelEncoder', mod_from='sklearn.preprocessing')\n transformer.addInputFiles({'targetEncoder':'targetEncoder.pkl'})\n update_variable('target_encoder', True)\n transformer.addStatement(\"train_data, test_data = train_test_split(df,stratify=df[target_feature],test_size=config['test_ratio'])\",indent=2) #Bugid 13217\n transformer.addStatement(\"profilerObj = profiler(xtrain=train_data, target=target_feature, encode_target=True, config=config['profiler'],log=log)\") #Bugid 13217\n else:\n transformer.addStatement(\"train_data, test_data = train_test_split(df,test_size=config['test_ratio'])\",indent=2)\n transformer.addStatement(\"profilerObj = profiler(xtrain=train_data, target=target_feature, config=config['profiler'],log=log)\")\n \n importModules(importer, transformer.getSuffixModules())\n importModules(importer, transformer.getMainCodeModules())\n transformer.addSuffixCode( config[\"problem_type\"] == 'classification')\n transformer.addMainCode()\n usecase = config['modelName']+'_'+config['modelVersion']\n deploy_path = Path(config[\"deploy_path\"])/'MLaC'/'DataTransformation'\n deploy_path.mkdir(parents=True, exist_ok=True)\n generated_files = []\n \n # create the utility file\n importer.addLocalModule('*', mod_from='utility')\n utility_obj = utility_function('transformer')\n with open(deploy_path/\"utility.py\", 'w') as f:\n f.write(file_header(usecase) + utility_obj.get_code())\n generated_files.append(\"utility.py\") \n\n # create empty init file to make a package \n with open(deploy_path/\"__init__.py\", 'w') as f:\n f.write(file_header(usecase))\n generated_files.append(\"__init__.py\") \n \n #", "instruction": "", "output": "" }, { "input": "create the dataProfiler file\n profiler_importer = importModule()\n importer.addLocalModule('profiler', mod_from='dataProfiler')\n profiler_obj = data_profiler(profiler_importer, True if config[\"text_features\"] else False)\n code_text = profiler_obj.get_code() # import statement will be generated when profiler_obj.get_code is called.\n # need to copy data profiler from AION code as code is splitted and merging code amnnually\n # can add bugs. need a better way to find the imported module\n #aion_transformer = Path(__file__).parent.parent.parent.parent/'transformations'\n aion_utilities = Path(__file__).parent.parent.parent.parent/'utilities' #added for non encryption --Usnish\n (deploy_path/'transformations').mkdir(parents=True, exist_ok=True)\n if not (aion_utilities/'transformations'/'dataProfiler.py').exists():\n raise ValueError('Data profiler file removed from AION')\n shutil.copy(aion_utilities/'transformations'/'dataProfiler.py',deploy_path/\"dataProfiler.py\")\n shutil.copy(aion_utilities/'transformations'/'data_profiler_functions.py',deploy_path/\"transformations\"/\"data_profiler_functions.py\")\n\n \n if (deploy_path/'text').exists():\n shutil.rmtree(deploy_path/'text')\n\n with tarfile.open(aion_utilities/'text.tar') as file:\n file.extractall(deploy_path)\n if (deploy_path/'utils').exists():\n shutil.rmtree(deploy_path/'utils')\n with tarfile.open(aion_utilities / 'utils.tar') as file:\n file.extractall(deploy_path)\n\n generated_files.append(\"dataProfiler.py\")\n generated_files.append(\"transformations\")\n generated_files.append(\"text\")\n generated_files.append(\"utils\")\n\n code = file_header(usecase)\n code += \"\\\\nimport os\\\\nos.path.abspath(os.path.join(__file__, os.pardir))\\\\n\" #chdir to import from current dir\n code += importer.getCode()\n code += '\\\\nwarnings.filterwarnings(\"ignore\")\\\\n'\n code += transformer.getInputOutputFiles()\n code += function.getCode()\n transformer.addLocalFunctionsCode()\n code += transformer.getCode()\n with open(deploy_path/\"aionCode.py\", \"w\") as f:\n f.write(code)\n generated_files.append(\"aionCode.py\") \n\n with open(deploy_path/\"requirements.txt\", \"w\") as f:\n req=importer.getBaseModule(extra_importers=[utility_obj.get_importer(), profiler_importer])\n if config[\"text_features\"]:\n req += add_text_dependency()\n f.write(req)\n generated_files.append(\"requirements.txt\") \n\n config_file = deploy_path/\"config.json\"\n config_data = get_transformer_params(config)\n with open (config_file, \"w\") as f:\n json.dump(config_data, f, indent=4)\n generated_files.append(\"config.json\") \n\n create_docker_file('transformer', deploy_path,config['modelName'], generated_files,True if config[\"text_features\"] else False)\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom pathlib import Path\nimport json\nimport platform\nfrom mlac.ml.core import *\nfrom .utility import *\n\noutput_file_map = {\n 'feature_reducer' : {'feature_reducer' : 'feature_reducer.pkl'}\n}\n\ndef get_selector_params(config):\n param_keys = [\"modelVersion\",\"problem_type\",\"target_feature\",\"train_features\",\"cat_features\",\"n_components\"]\n data = {key:value for (key,value) in config.items() if key in param_keys}\n data['targetPath'] = config['modelName']\n return data\n \ndef run_selector(config): \n select = selector()\n importer = importModule()\n function = global_function()\n importModules(importer,select.getPrefixModules())\n select.addPrefixCode()\n if config[\"target_feature\"] in config[\"train_features\"]:\n config[\"train_features\"].remove(config[\"target_feature\"])\n select.addStatement(\"train_features = df.columns.tolist()\")\n select.addStatement(\"target_feature = config['target_feature']\")\n select.addStatement(\"train_features.remove(target_feature)\")\n select.addStatement(\"cat_features = prev_step_output['cat_features']\")\n select.add_variable('total_features',[])\n select.addStatement(\"log.log_dataframe(df)\")\n methods = config.get(\"feature_selector\", None)\n feature_reducer = config.get(\"feature_reducer\", None)\n select.addStatement(\"selected_features = {}\")\n select.addStatement(\"meta_data['featureengineering']= {}\")\n if feature_reducer:\n update_variable('feature_reducer', True)\n select.addStatement(f\"log.info('Running dimensionality reduction technique( {feature_reducer})')\")\n if feature_reducer == 'pca':\n importer.addModule('PCA', mod_from='sklearn.decomposition')\n if int(config[\"n_components\"]) == 0:\n select.addStatement(\"dimension_reducer = PCA(n_components='mle',svd_solver = 'full')\")\n elif int(config[\"n_components\"]) < 1:\n select.addStatement(\"dimension_reducer = PCA(n_components=config['n_components'],svd_solver = 'full')\")\n else:\n select.addStatement(\"dimension_reducer = PCA(n_components=config['n_components'])\")\n elif feature_reducer == 'svd':\n importer.addModule('TruncatedSVD', mod_from='sklearn.decomposition')\n if config[\"n_components\"] < 2:\n config[\"n_components\"] = 2\n select.addStatement(\"dimension_reducer = TruncatedSVD(n_components=config['n_components'], n_iter=7, random_state=42)\")\n elif feature_reducer == 'factoranalysis':\n importer.addModule('FactorAnalysis', mod_from='sklearn.decomposition')\n if config[\"n_components\"] == 0:\n select.addStatement(\"dimension_reducer = FactorAnalysis()\")\n else:\n select.addStatement(\"dimension_reducer = FactorAnalysis(n_components=config['n_components'])\")\n elif feature_reducer == 'ica':\n importer.addModule('FastICA', mod_from='sklearn.decomposition')\n if config[\"n_components\"] == 0:\n select.addStatement(\"dimension_reducer = FastICA()\")\n else:\n select.addStatement(\"dimension_reducer = FastICA(n_components=config['n_components'])\")\n select.addStatement(\"pca_array = dimension_reducer.fit_transform(df[train_features])\")\n select.addStatement(\"pca_columns = ['pca_'+str(e) for e in list(range(pca_array.shape[1]))]\")\n select.addStatement(\"scaledDF = pd.DataFrame(pca_array, columns=pca_columns)\")\n select.addStatement(\"scaledDF[target_feature] = df[target_feature]\")\n select.addStatement(\"df = scaledDF\")\n select.addStatement(f\"selected_features['{feature_reducer}'] = pca_columns\")\n select.addStatement(\"total_features = df.columns.tolist()\")\n select.addStatement(\"meta_data['featureengineering']['feature_reducer']= {}\")\n select.addStatement(\"reducer_file_name = str(targetPath/IOFiles['feature_reducer'])\")\n importer.addModule('joblib')\n select.addStatement(\"joblib.dump(dimension_reducer, reducer_file_name)\")\n select.addStatement(\"meta_data['featureengineering']['feature_reducer']['file']= IOFiles['feature_reducer']\")\n select.addStatement(\"meta_data['featureengineering']['feature_reducer']['features']= train_features\")\n select.addOutputFiles(output_file_map['feature_reducer'])\n \n elif methods:\n if 'allFeatures' in methods:\n addDropFeature('target_feature', 'train_features', select)\n select.addStatement(\"selected_features['allFeatures'] = train_features\")\n if 'modelBased' in methods:\n select.addStatement(f\"log.info('Model Based Correlation Analysis Start')\")\n select.addStatement(\"model_based_feat = []\")\n importer.addModule('numpy', mod_as='np')\n importer.addModule('RFE', mod_from='sklearn.feature_selection')\n importer.addModule('MinMaxScaler', mod_from='sklearn.preprocessing')\n if config[\"problem_type\"] == 'classification':\n importer.addModule('ExtraTreesClassifier', mod_from='sklearn.ensemble')\n select.addStatement(\"estimator = ExtraTreesClassifier(n_estimators=100)\")\n else:\n importer.addModule('Lasso', mod_from='sklearn.linear_model')\n select.addStatement(\"estimator = Lasso()\")\n select.addStatement(\"estimator.fit(df[train_features],df[target_feature])\")\n select.addStatement(\"rfe = RFE(estimator, n_features_to_select=1, verbose =0 )\")\n select.addStatement(\"rfe.fit(df[train_features],df[target_feature])\")\n select.addStatement(\"ranks = MinMaxScaler().fit_transform(-1*np.array([list(map(float, rfe.ranking_))]).T).T[0]\")\n select.addStatement(\"ranks = list(map(lambda x: round(x,2), ranks))\")\n select.addStatement(\"for item, rank in zip(df.columns,ranks):\")\n select.addStatement(\"if rank > 0.30:\", indent=2)\n select.addStatement(\"model_based_feat.append(item)\", indent=3)\n addDropFeature('target_feature', 'model_based_feat', select)\n select.addStatement(\"selected_features['modelBased'] = model_based_feat\")\n select.addStatement(f\"log.info(f'Highly Correlated Features : {{model_based_feat}}')\")\n if 'statisticalBased' in methods:\n select.addStatement(f\"log.info('Statistical Based Correlation Analysis Start')\")\n function.add_function('start_reducer',importer)\n select.addStatement(f\"features = start_reducer(df, target_feature, {config['corr_threshold']},{config['var_threshold']})\")\n select.addStatement(\"train_features = [x for x in features if x in train_features]\")\n select.addStatement(\"cat_features = [x for x in cat_features if x in features]\")\n select.addStatement(\"numeric_features = df[features].select_dtypes('number').columns.tolist()\")\n if config[\"problem_type\"] == 'classification':\n function.add_function('feature_importance_class')\n select.addStatement(f\"statistics_based_feat = feature_importance_class(df[features], numeric_features, cat_features, target_feature, {config['pValueThreshold']},{config['corr_threshold']})\")\n else:\n function.add_function('feature_importance_reg')\n select.addStatement(f\"statistics_based_feat = feature_importance_reg(df[features], numeric_features, target_feature, {config['pValueThreshold']},{config['corr_threshold']})\")\n addDropFeature('target_feature', 'statistics_based_feat', select)\n select.addStatement(\"selected_features['statisticalBased'] = statistics_based_feat\")\n select.addStatement(f\"log.info('Highly Correlated Features : {{statistics_based_feat}}')\")\n select.addStatement(\"total_features = list(set([x for y in selected_features.values() for x in y] + [target_feature]))\")\n select.addStatement(f\"df = df[total_features]\")\n select.addStatement(\"log.log_dataframe(df)\")\n select.addSuffixCode()\n importModules(importer, select.getSuffixModules())\n importModules(importer, select.getMainCodeModules())\n select.addMainCode()\n \n generated_files = []\n usecase = config['modelName']+'_'+config['modelVersion']\n deploy_path = Path(config[\"deploy_path\"])/'MLaC'/'FeatureEngineering'\n deploy_path.mkdir(parents=True, exist_ok=True)\n \n # create the utility file\n importer.addLocalModule('*', mod_from='utility')\n utility_obj = utility_function('selector')\n with open(deploy_path/\"utility.py\", 'w') as f:\n f.write(file_header(usecase) + utility_obj.get_code())\n generated_files.append(\"utility.py\") \n\n # create empty init file to make a package \n with open(deploy_path/\"__init__.py\", 'w') as f:\n f.write(file_header(usecase))\n generated_files.append(\"__init__.py\") \n \n code = file_header(usecase)\n code += importer.getCode()\n code += select.getInputOutputFiles()\n code += function.getCode()\n select.addLocalFunctionsCode()\n code += select.getCode()\n with open(deploy_path/\"aionCode.py\", \"w\") as f:\n f.write(code)\n generated_files.append(\"aionCode.py\") \n\n with open(deploy_path/\"requirements.txt\", \"w\") as f:\n req=importer.getBaseModule(extra_importers=[utility_obj.get_importer()])\n f.write(req)\n generated_files.append(\"requirements.txt\") \n\n config_file = deploy_path/\"config.json\"\n config_data = get_selector_params(config)\n with open (config_file, \"w\") as f:\n json.dump(config_data, f, indent=4)\n generated_files.append(\"config.json\") \n\n create_docker_file('selector', deploy_path,config['modelName'], generated_files) \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom pathlib import Path\nimport json\nfrom mlac.ml.core import *\nfrom .utility import *\n\ndef get_model_name(algo, method):\n if method == 'modelBased':\n return algo + '_' + 'MLBased'\n if method == 'statisticalBased':\n return algo + '_' + 'StatisticsBased'\n else:\n return algo", "instruction": "", "output": "" }, { "input": "\n\n\ndef get_training_params(config, algo):\n param_keys = [\"modelVersion\",\"problem_type\",\"target_feature\",\"train_features\",\"scoring_criteria\",\"test_ratio\",\"optimization_param\"]\n data = {key:value for (key,value) in config.items() if key in param_keys}\n data['algorithms'] = {algo: config['algorithms'][algo]}\n data['targetPath'] = config['modelName']\n return data\n\ndef addImporterLearner(model, importer):\n module = get_module_mapping(model)\n mod_from = module.get('mod_from',None)\n mod_as = module.get('mod_as',None)\n importer.addModule(module['module'], mod_from=mod_from, mod_as=mod_as)\n if not get_variable('non_sklearn_modules'):\n update_variable('non_sklearn_modules', [])\n if 'sklearn' not in mod_from:\n modules = get_variable('non_sklearn_modules')\n modules.append(model)\n update_variable('non_sklearn_modules', modules)\n\ndef addEvaluator(scorer_type, optimizer,trainer, importer):\n trainer.addStatement(\"if not X_test.empty:\")\n if optimizer == 'genetic':\n trainer.addStatement('features = [x for i,x in enumerate(features) if grid.support_[i]]',indent=2)\n trainer.addStatement('y_pred = estimator.predict(X_test[features])',indent=2)\n if scorer_type == 'accuracy':\n importer.addModule('accuracy_score', mod_from='sklearn.metrics')\n trainer.addStatement(f\"test_score = round(accuracy_score(y_test,y_pred),2) * 100\",indent=2)\n importer.addModule('confusion_matrix', mod_from='sklearn.metrics')\n trainer.addStatement(\"log.info('Confusion Matrix:')\",indent=2)\n trainer.addStatement(\"log.info('\\\\\\\\n' + pd.DataFrame(confusion_matrix(y_test,y_pred)).to_string())\",indent=2)\n elif scorer_type == 'recall':\n importer.addModule('recall_score', mod_from='sklearn.metrics')\n trainer.addStatement(f\"test_score = round(recall_score(y_test,y_pred,average='macro'),2) * 100\",indent=2)\n importer.addModule('confusion_matrix', mod_from='sklearn.metrics')\n trainer.addStatement(f\"log.info('Confusion Matrix:\\\\\\\\n')\",indent=2)\n trainer.addStatement(f'log.info(pd.DataFrame(confusion_matrix(y_test,y_pred)))',indent=2)\n elif scorer_type == 'precision':\n importer.addModule('precision_score', mod_from='sklearn.metrics')\n trainer.addStatement(f\"test_score = round(precision_score(y_test,y_pred,average='macro'),2) * 100\",indent=2)\n importer.addModule('confusion_matrix', mod_from='sklearn.metrics')\n trainer.addStatement(f\"log.info('Confusion Matrix:\\\\\\\\n')\",indent=2)\n trainer.addStatement(f'log.info(pd.DataFrame(confusion_matrix(y_test,y_pred)))',indent=2)\n elif scorer_type == 'f1_score':\n importer.addModule('f1_score', mod_from='sklearn.metrics')\n trainer.addStatement(f\"test_score = round(f1_score(y_test,y_pred,average='macro'),2) * 100\",indent=2)\n importer.addModule('confusion_matrix', mod_from='sklearn.metrics')\n trainer.addStatement(f\"log.info('Confusion Matrix:\\\\\\\\n')\",indent=2)\n trainer.addStatement(f'log.info(pd.DataFrame(confusion_matrix(y_test,y_pred)))',indent=2)\n elif scorer_type == 'roc_auc':\n importer.addModule('roc_auc_score', mod_from='sklearn.metrics')\n trainer.addStatement(\"try:\")\n trainer.addStatement(f\"test_score = round(roc_auc_score(y_test,y_pred),2) * 100\", indent=3)\n importer.addModule('confusion_matrix', mod_from='sklearn.metrics')\n trainer.addStatement(f\"log.info('Confusion Matrix:\\\\\\\\n')\",indent=3)\n trainer.addStatement(f'log.info(pd.DataFrame(confusion_matrix(y_test,y_pred)))',indent=3)\n trainer.addStatement(\"except:\")\n trainer.addStatement(\"try:\",indent=3)\n trainer.addStatement(\"actual = pd.get_dummies(y_test)\",indent=4)\n trainer.addStatement(\"y_pred = pd.get_dummies(y_pred)\",indent=4)\n trainer.addStatement(f\"test_score = round(roc_auc_score(y_test,y_pred,average='weighted', multi_class='ovr'),2) * 100\", indent=3)\n trainer.addStatement(f\"log.info('Confusion Matrix:\\\\\\\\n')\",indent=4)\n trainer.addStatement(f'log.info(pd.DataFrame(confusion_matrix(y_test,y_pred)))',indent=4)\n trainer.addStatement(\"except:\",indent=3)\n trainer.addStatement(f\"test_score = 0.0\", indent=4)\n elif scorer_type == 'neg_mean_squared_error' or scorer_type == 'mse':\n importer.addModule('mean_squared_error', mod_from='sklearn.metrics')\n trainer.addStatement(f'test_score = round(mean_squared_error(y_test,y_pred),2)',indent=2)\n update_variable('smaller_is_better', True)\n elif scorer_type == 'neg_root_mean_squared_error' or scorer_type == 'rmse':\n importer.addModule('mean_squared_error', mod_from='sklearn.metrics')\n trainer.addStatement(f'test_score = round(mean_squared_error(y_test,y_pred,squared=False),2)',indent=2)\n update_variable('smaller_is_better', True)\n elif scorer_type == 'neg_mean_absolute_error' or scorer_type == 'mae':\n importer.addModule('mean_absolute_error', mod_from='sklearn.metrics')\n trainer.addStatement(f'test_score = round(mean_absolute_error(y_test,y_pred),2)',indent=2)\n update_variable('smaller_is_better', True)\n elif scorer_type == 'r2':\n importer.addModule('r2_score', mod_from='sklearn.metrics')\n trainer.addStatement(f'test_score = round(r2_score(y_test,y_pred),2)',indent=2)\ndef update_search_space(algo, config):\n search_space = []\n algoritms = config[\"algorithms\"]\n model = algo\n params = algoritms[model]\n model_dict = {model:get_module_mapping(model)['mod_from']}\n d = {'algo': model_dict}\n d['param'] = params\n search_space.append(d)\n config['search_space'] = search_space\n\ndef get_optimization(optimization, importer, function=None):\n if optimization == 'grid':\n importer.addModule('GridSearchCV', mod_from='sklearn.model_selection')\n optimization = 'GridSearchCV'\n elif optimization == 'random':\n importer.addModule('RandomizedSearchCV', mod_from='sklearn.model_selection')\n optimization = 'RandomizedSearchCV'\n elif optimization == 'genetic':\n importer.addModule('GeneticSelectionCV', mod_from='genetic_selection')\n optimization = 'GeneticSelectionCV'\n elif optimization == 'bayesopt':\n optimization = 'BayesSearchCV'\n function.add_function(optimization,importer)\n return optimization\n \ndef scoring_criteria_reg(score_param):\n scorer_mapping = { \n 'mse':'neg_mean_squared_error', \n 'rmse':'neg_root_mean_squared_error', \n 'mae':'neg_mean_absolute_error', \n 'r2':'r2' \n } \n return scorer_mapping.get(score_param, 'neg_mean_squared_error') \n\ndef addBalancing(balancingMethod, importer, code):\n if balancingMethod == 'oversample':\n importer.addModule('SMOTE', mod_from='imblearn.over_sampling')\n code.addStatement(\"\\\\n # data balancing\")\n code.addStatement(\"X_train, y_train = SMOTE(sampling_strategy='auto', k_neighbors=1, random_state=100).fit_resample(X_train, y_train)\")\n if balancingMethod == 'undersample':\n importer.addModule('TomekLinks', mod_from='imblearn.under_sampling')\n code.addStatement(\"\\\\n # data balancing\")\n code.addStatement(\"X_train, y_train = TomekLinks().fit_resample(X_train, y_train)\")\n\ndef run_trainer(base_config): \n base_trainer = learner()\n base_importer = importModule()\n function = global_function()\n base_importer.addModule('joblib')\n base_importer.addModule('warnings')\n base_importer.addModule('argparse')\n base_importer.addModule('pandas', mod_as='pd')\n base_importer.addModule('Path', mod_from='pathlib')\n function.add_function('get_mlflow_uris')\n function.add_function('mlflow_create_experiment')\n importModules(base_importer,base_trainer.getPrefixModules())\n base_trainer.addPrefixCode()\n if base_config[\"algorithms\"]:\n base_trainer.add_train_test_split('train_features', 'target_feature', \"config['test_ratio']\")\n if base_config[\"problem_type\"] == 'classification':\n if base_config[\"balancingMethod\"]:\n addBalancing(base_config[\"balancingMethod\"],base_importer,base_trainer)\n base_trainer.addStatement(f\"log.info('Data balancing done')\")\n base_trainer.addStatement(\"\\\\n #select scorer\")\n if base_config[\"problem_type\"] == 'classification':\n function.add_function('scoring_criteria', base_importer)\n base_trainer.addStatement(\"scorer = scoring_criteria(config['scoring_criteria'],config['problem_type'], df[target_feature].nunique())\")\n else:\n base_config['scoring_criteria'] = scoring_criteria_reg(base_config['scoring_criteria'])\n base_trainer.addStatement(f\"scorer = config['scoring_criteria']\")\n base_trainer.addStatement(f\"log.info('Scoring criteria: {base_config['scoring_criteria']}')\")\n feature_selector = []\n if base_config['feature_reducer']:\n feature_selector.append(base_config['feature_reducer'])\n elif base_config['feature_selector']:\n feature_selector = base_config['feature_selector']\n for algo in base_config[\"algorithms\"].keys():\n for method in feature_selector:\n trainer = learner()\n importer = importModule()\n trainer.copyCode(base_trainer)\n importer.copyCode(base_importer)\n config = base_config\n usecase = config['modelName']+'_'+config['modelVersion']\t\t\t\t\n addImporterLearner(algo, importer)\n trainer.addStatement(\"\\\\n #Training model\")\n trainer.addStatement(f\"log.info('Training {algo} for {method}')\")\n trainer.add_model_fit(algo, get_optimization(config[\"optimization\"], importer, function), method, importer)\n trainer.addStatement(\"\\\\n #model evaluation\")\n addEvaluator(config['scoring_criteria'],config[\"optimization\"], trainer, importer)\n function.add_function('mlflowSetPath')\n function.add_function('logMlflow')\n importModules(importer, trainer.getSuffixModules())\n importModules(importer, trainer.getMainCodeModules())\n if base_config[\"problem_type\"] == 'classification':\n function.add_function('classification_metrices', importer)\n trainer.addStatement(\"metrices = get_classification_metrices(y_test,y_pred)\",indent=2)\n trainer.add_100_trainsize_code()\n trainer.addStatement(\"metrices.update({'train_score': train_score, 'test_score':test_score})\")\n else:\n function.add_function('regression_metrices', importer)\n trainer.addStatement(\"metrices = get_regression_metrices(y_test,y_pred)\",indent=2)\n trainer.add_100_trainsize_code()\n trainer.addStatement(\"metrices.update({'train_score': train_score, 'test_score':test_score})\")\n trainer.addSuffixCode()\n trainer.addMainCode()\n\n model_name = get_model_name(algo,method)\n deploy_path = Path(config[\"deploy_path\"])/'MLaC'/('ModelTraining'+'_' + model_name)\n deploy_path.mkdir(parents=True, exist_ok=True)\n generated_files = []\n \n # create the utility file\n importer.addLocalModule('*', mod_from='utility')\n utility_obj = utility_function('train')\n with open(deploy_path/\"utility.py\", 'w') as f:\n f.write(file_header(usecase) + utility_obj.get_code())\n generated_files.append(\"utility.py\") \n\n # create empty init file to make a package \n with open(deploy_path/\"__init__.py\", 'w') as f:\n f.write(file_header(usecase))\n generated_files.append(\"__init__.py\") \n \n code = importer.getCode()\n code += 'warnings.filterwarnings(\"ignore\")\\\\n'\n code += f\"\\\\nmodel_name = '{model_name}'\\\\n\"\n append_variable('models_name',model_name)\n out_files = {'log':f'{model_name}_aion.log','model':f'{model_name}_model.pkl','performance':f'{model_name}_performance.json','metaDataOutput':f'{model_name}_modelMetaData.json'}\n trainer.addOutputFiles(out_files)\n code += trainer.getInputOutputFiles()\n code += function.getCode()\n trainer.addLocalFunctionsCode()\n code += trainer.getCode()\n with open(deploy_path/\"aionCode.py\", \"w\") as f:\n f.write(code)\n generated_files.append(\"aionCode.py\") \n\n with open(deploy_path/\"requirements.txt\", \"w\") as f:\n req=importer.getBaseModule(extra_importers=[utility_obj.get_importer()])\n f.write(req)\n generated_files", "instruction": "", "output": "" }, { "input": ".append(\"requirements.txt\") \n\n with open (deploy_path/\"config.json\", \"w\") as f:\n json.dump(get_training_params(config, algo), f, indent=4)\n generated_files.append(\"config.json\") \n\n create_docker_file('train', deploy_path,config['modelName'], generated_files)\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom pathlib import Path\nimport json\nimport platform\nfrom mlac.ml.core import *\nfrom .utility import *\n\nimported_modules = [\n {'module': 'json', 'mod_from': None, 'mod_as': None},\n {'module': 'Path', 'mod_from': 'pathlib', 'mod_as': None},\n {'module': 'pandas', 'mod_from': None, 'mod_as': 'pd'},\n {'module': 'argparse', 'mod_from': None, 'mod_as': None},\n {'module': 'platform', 'mod_from': None, 'mod_as': None } \n ]\n\ndef get_load_data_params(config):\n param_keys = [\"modelVersion\",\"problem_type\",\"target_feature\",\"selected_features\"]\n data = {key:value for (key,value) in config.items() if key in param_keys}\n data['targetPath'] = config['modelName']\n return data\n\ndef run_loader(config):\n generated_files = []\n importer = importModule()\n loader = tabularDataReader()\n importModules(importer, imported_modules)\n usecase = config['modelName']+'_'+config['modelVersion']\n deploy_path = Path(config[\"deploy_path\"])/'MLaC'/'DataIngestion'\n deploy_path.mkdir(parents=True, exist_ok=True)\n \n # create the utility file\n importer.addLocalModule('*', mod_from='utility')\n utility_obj = utility_function('load_data')\n with open(deploy_path/\"utility.py\", 'w') as f:\n f.write(file_header(usecase) + utility_obj.get_code())\n generated_files.append(\"utility.py\") \n # create the production data reader file\n importer.addLocalModule('dataReader', mod_from='data_reader')\n readers = ['sqlite','influx']\n if 's3' in config.keys():\n readers.append('s3')\n reader_obj = data_reader(readers)\n with open(deploy_path/\"data_reader.py\", 'w') as f:\n f.write(file_header(usecase) + reader_obj.get_code())\n generated_files.append(\"data_reader.py\") \n \n # create empty init file to make a package \n with open(deploy_path/\"__init__.py\", 'w') as f:\n f.write(file_header(usecase))\n generated_files.append(\"__init__.py\") \n \n code = file_header(usecase)\n code += importer.getCode()\n code += loader.getInputOutputFiles()\n code += loader.getCode()\n with open(deploy_path/\"aionCode.py\", \"w\") as f:\n f.write(code)\n generated_files.append(\"aionCode.py\") \n\n with open(deploy_path/\"requirements.txt\", \"w\") as f:\n req=importer.getBaseModule(extra_importers=[utility_obj.get_importer(), reader_obj.get_importer()])\n f.write(req)\n generated_files.append(\"requirements.txt\") \n \n config_file = deploy_path/\"config.json\"\n config_data = get_load_data_params(config)\n with open (config_file, \"w\") as f:\n json.dump(config_data, f, indent=4)\n generated_files.append(\"config.json\") \n \n create_docker_file('load_data', deploy_path,config['modelName'],generated_files) \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom pathlib import Path\nimport json\nfrom mlac.ml.core import *\nfrom .utility import *\n\ndef get_register_params(config, models):\n param_keys = [\"modelVersion\",\"problem_type\"]\n data = {key:value for (key,value) in config.items() if key in param_keys}\n data['targetPath'] = config['modelName']\n data['models'] = models\n return data\n\ndef run_register(config):\n importer = importModule()\n function = global_function()\n registration = register(importer)\n function.add_function('get_mlflow_uris')\n models = get_variable('models_name')\n smaller_is_better = get_variable('smaller_is_better', False)\n registration.addClassCode(smaller_is_better)\n registration.addLocalFunctionsCode(models)\n registration.addPrefixCode()\n registration.addMainCode(models)\n importModules(importer, registration.getMainCodeModules())\n importer.addModule('warnings')\n\n generated_files = []\n usecase = config['modelName']+'_'+config['modelVersion']\n deploy_path = Path(config[\"deploy_path\"])/'MLaC'/'ModelRegistry'\n deploy_path.mkdir(parents=True, exist_ok=True)\n\n # create the utility file\n importer.addLocalModule('*', mod_from='utility')\n utility_obj = utility_function('register')\n with open(deploy_path/\"utility.py\", 'w') as f:\n f.write(file_header(usecase) + utility_obj.get_code())\n generated_files.append(\"utility.py\") \n\n # create empty init file required for creating a package \n with open(deploy_path/\"__init__.py\", 'w') as f:\n f.write(file_header(usecase))\n generated_files.append(\"__init__.py\") \n\n code = registration.getImportCode()\n code += '\\\\nwarnings.filterwarnings(\"ignore\")\\\\n'\n code += registration.getInputOutputFiles()\n code += function.getCode()\n code += registration.getCode()\n # create serving file\n with open(deploy_path/\"aionCode.py\", 'w') as f:\n f.write(file_header(usecase) + code)\n generated_files.append(\"aionCode.py\") \n\n # create requirements file\n req_file = deploy_path/\"requirements.txt\"\n with open(req_file, \"w\") as f:\n req=importer.getBaseModule(extra_importers=[utility_obj.get_importer()])\n f.write(req)\n generated_files.append(\"requirements.txt\")\n \n # create config file\n with open (deploy_path/\"config.json\", \"w\") as f:\n json.dump(get_register_params(config, models), f, indent=4)\n generated_files.append(\"config.json\") \n \n # create docker file\n create_docker_file('register', deploy_path,config['modelName'], generated_files) \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nimport datetime\nfrom pathlib import Path\n\nvariables = {}\n\ndef init_variables():\n global variables\n variables = {}\ndef update_variable(name, value):\n variables[name] = value\n \ndef get_variable(name, default=None):\n return variables.get(name, default)\n\ndef append_variable(name, value):\n data = get_variable(name)\n if not data:\n update_variable(name, [value])\n elif not isinstance(data, list):\n update_variable(name, [data, value])\n else:\n data.append(value)\n update_variable(name, data)\n \ndef addDropFeature(feature, features_list, coder, indent=1):\n coder.addStatement(f'if {feature} in {features_list}:', indent=indent)\n coder.addStatement(f'{features_list}.remove({feature})', indent=indent+1)\n \ndef importModules(importer, modules_list):\n for module in modules_list:\n mod_from = module.get('mod_from',None)\n mod_as = module.get('mod_as',None)\n importer.addModule(module['module'], mod_from=mod_from, mod_as=mod_as)\n \ndef file_header(use_case, module_name=None):\n time_str = datetime.datetime.now().isoformat(timespec='seconds', sep=' ')\n text = \"#!/usr/bin/env python\\\\n# -*- coding: utf-8 -*-\\\\n\"\n return text + f\"'''\\\\nThis file is automatically generated by AION for {use_case} usecase.\\\\nFile generation time: {time_str}\\\\n'''\"\n\ndef get_module_mapping(module):\n mapping = {\n \"LogisticRegression\": {'module':'LogisticRegression', 'mod_from':'sklearn.linear_model'}\n ,\"GaussianNB\": {'module':'GaussianNB', 'mod_from':'sklearn.naive_bayes'}\n ,\"DecisionTreeClassifier\": {'module':'DecisionTreeClassifier', 'mod_from':'sklearn.tree'}\n ,\"SVC\": {'module':'SVC', 'mod_from':'sklearn.svm'}\n ,\"KNeighborsClassifier\": {'module':'KNeighborsClassifier', 'mod_from':'sklearn.neighbors'}\n ,\"GradientBoostingClassifier\": {'module':'GradientBoostingClassifier', 'mod_from':'sklearn.ensemble'}\n ,'RandomForestClassifier':{'module':'RandomForestClassifier','mod_from':'sklearn.ensemble'}\n ,'XGBClassifier':{'module':'XGBClassifier','mod_from':'xgboost'}\n ,'LGBMClassifier':{'module':'LGBMClassifier','mod_from':'lightgbm'}\n ,'CatBoostClassifier':{'module':'CatBoostClassifier','mod_from':'catboost'}\n\n ,\"LinearRegression\": {'module':'LinearRegression', 'mod_from':'sklearn.linear_model'}\n ,\"Lasso\": {'module':'Lasso', 'mod_from':'sklearn.linear_model'}\n ,\"Ridge\": {'module':'Ridge', 'mod_from':'sklearn.linear_model'}\n ,\"DecisionTreeRegressor\": {'module':'DecisionTreeRegressor', 'mod_from':'sklearn.tree'}\n ,'RandomForestRegressor':{'module':'RandomForestRegressor','mod_from':'sklearn.ensemble'}\n ,'XGBRegressor':{'module':'XGBRegressor','mod_from':'xgboost'}\n ,'LGBMRegressor':{'module':'LGBMRegressor','mod_from':'lightgbm'}\n ,'CatBoostRegressor':{'module':'CatBoostRegressor','mod_from':'catboost'}\n }\n return mapping.get(module, None)\n\ndef create_docker_file(name, path,usecasename,files=[],text_feature=False):\n text = \"\"\n if name == 'load_data':\n text='FROM python:3.8-slim-buster'\n text+='\\\\n'\n text+='LABEL \"usecase\"=\"'+str(usecasename)+'\"'\n text+='\\\\n'\n text+='LABEL \"usecase_test\"=\"'+str(usecasename)+'_test'+'\"'\n for file in files:\n text+=f'\\\\nCOPY {file} {file}'\n text+='\\\\n'\n text+='RUN pip install --no-cache-dir -r requirements.txt'\n elif name == 'transformer':\n text='FROM python:3.8-slim-buster\\\\n'\n text+='LABEL \"usecase\"=\"'+str(usecasename)+'\"'\n text+='\\\\n'\n text+='LABEL \"usecase_test\"=\"'+str(usecasename)+'_test'+'\"'\n text+='\\\\n'\t\t\n for file in files:\n text+=f'\\\\nCOPY {file} {file}'\n text+='\\\\n'\n text+='''RUN \\\\\n'''\n text+=''' pip install --no-cache-dir -r requirements.txt\\\\\n'''\n if text_feature:\n text += ''' && python -m nltk.downloader stopwords && python -m nltk.downloader punkt && python -m nltk.downloader wordnet && python -m nltk.downloader averaged_perceptron_tagger\\\\\n'''\n text+='\\\\n'\n elif name == 'selector':\n text='FROM python:3.8-slim-buster'\n text+='\\\\n'\n text+='LABEL \"usecase\"=\"'+str(usecasename)+'\"'\n text+='\\\\n'\n text+='LABEL \"usecase_test\"=\"'+str(usecasename)+'_test'+'\"'\n text+='\\\\n'\t\t\t\t\n for file in files:\n text+=f'\\\\nCOPY {file} {file}'\n text+='\\\\n'\n text+='RUN pip install --no-cache-dir -r requirements.txt'\n elif name == 'train':\n text='FROM python:3.8-slim-buster'\n text+='\\\\n'\n text+='LABEL \"usecase\"=\"'+str(usecasename)+'\"'\n text+='\\\\n'\n text+='LABEL \"usecase_test\"=\"'+str(usecasename)+'_test'+'\"'\n text+='\\\\n'\n text+='COPY requirements.txt requirements.txt'\n text+='\\\\n'\n text+='COPY config.json config.json'\n text+='\\\\n'\n text+='COPY aionCode.py aionCode.py'\n text+='\\\\n'\n text+='COPY utility.py utility.py' \n text+='\\\\n'\n text+='RUN pip install --no-cache-dir -r requirements.txt'\n elif name == 'register':\n text='FROM python:3.8-slim-buster'\n text+='\\\\n'\n text+='LABEL \"usecase\"=\"'+str(usecasename)+'\"'\n text+='\\\\n'\n text+='LABEL \"usecase_test\"=\"'+str(usecasename)+'_test'+'\"'\n text+='\\\\n'\n for file in files:\n text+=f'\\\\nCOPY {file} {file}'\n text+='\\\\n'\n text+='RUN pip install --no-cache-dir -r requirements.txt'\n elif name == 'Prediction':\n text='FROM python:3.8-slim-buster'\n text+='\\\\n'\n text+='LABEL \"usecase\"=\"'+str(usecasename)+'\"'\n text+='\\\\n'\n text+='LABEL \"usecase", "instruction": "", "output": "" }, { "input": "_test\"=\"'+str(usecasename)+'_test'+'\"'\n text+='\\\\n'\n for file in files:\n text+=f'\\\\nCOPY {file} {file}'\n text+='\\\\n'\t\t\t\t\n text+='''RUN \\\\\n'''\t\t\n text+='''pip install --no-cache-dir -r requirements.txt\\\\\n'''\n if text_feature:\n text += ''' && python -m nltk.downloader stopwords && python -m nltk.downloader punkt && python -m nltk.downloader wordnet && python -m nltk.downloader averaged_perceptron_tagger\\\\\n'''\n text+='\\\\n'\n text+='ENTRYPOINT [\"python\", \"aionCode.py\",\"-ip\",\"0.0.0.0\",\"-pn\",\"8094\"]\\\\n'\n elif name == 'input_drift':\n text='FROM python:3.8-slim-buster'\n text+='\\\\n'\n text+='LABEL \"usecase\"=\"'+str(usecasename)+'\"'\n text+='\\\\n'\n text+='LABEL \"usecase_test\"=\"'+str(usecasename)+'_test'+'\"'\n text+='\\\\n'\n for file in files:\n text+=f'\\\\nCOPY {file} {file}'\n text+='\\\\n'\n text+='RUN pip install --no-cache-dir -r requirements.txt'\n file_name = Path(path)/'Dockerfile'\n with open(file_name, 'w') as f:\n f.write(text) \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom pathlib import Path\nimport json\nfrom mlac.ml.core import *\nfrom .utility import *\n\ndef run_output_drift(config):\n importer = importModule()\n drifter = output_drift(missing = get_variable('fillna', False), word2num_features= get_variable('word2num_features', False), cat_encoder = get_variable('cat_encoder', False),target_encoder = get_variable('target_encoder', False),normalizer = get_variable('normalizer', False),text_profiler = get_variable('text_features', False),feature_reducer = get_variable('feature_reducer', False),score_smaller_is_better = get_variable('smaller_is_better', False),problem_type=config['problem_type'])\n function = global_function()\n importer.addModule('sys')\n importer.addModule('math')\n importer.addModule('json')\n importer.addModule('platform')\n importer.addModule('joblib')\n importer.addModule('mlflow')\n importer.addModule('sklearn')\n importer.addModule('numpy', mod_as='np')\n importer.addModule('pandas', mod_as='pd')\n importer.addModule('Path', mod_from='pathlib')\n importer.addModule('InfluxDBClient', mod_from='influxdb')\n function.add_function('readWrite')\n code = file_header(config['modelName']+'_'+config['modelVersion'])\n code += importer.getCode()\n code += function.getCode()\n drifter.generateCode()\n code += drifter.getCode()\n deploy_path = Path(config[\"deploy_path\"])/'MLaC'/'OutputDrift'\n deploy_path.mkdir(parents=True, exist_ok=True)\n py_file = deploy_path/\"output_drift.py\"\n with open(py_file, \"w\") as f:\n f.write(code)\n req_file = deploy_path/\"requirements.txt\"\n with open(req_file, \"w\") as f:\n f.write(importer.getBaseModule())\n create_docker_file('output_drift', deploy_path)\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom .load_data import run_loader\nfrom .transformer import run_transformer\nfrom .selector import run_selector\nfrom .trainer import run_trainer\nfrom .register import run_register\nfrom .deploy import run_deploy\nfrom .drift_analysis import run_drift_analysis\n \n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom pathlib import Path\nimport json\nfrom mlac.ml.core import *\nfrom .utility import *\n\n\ndef run_input_drift(config):\n importer = importModule()\n drifter = input_drift()\n importer.addModule('sys')\n importer.addModule('json')\n importer.addModule('mlflow')\n importer.addModule('platform')\n importer.addModule('warnings') \n importer.addModule('numpy', mod_as='np')\n importer.addModule('pandas', mod_as='pd')\n importer.addModule('stats', mod_from='scipy', mod_as='st')\n importer.addModule('Path', mod_from='pathlib')\n code = file_header(config['modelName']+'_'+config['modelVersion'])\n code += importer.getCode()\n drifter.generateCode()\n code += drifter.getCode()\n deploy_path = Path(config[\"deploy_path\"])/'MLaC'/'InputDrift'\n deploy_path.mkdir(parents=True, exist_ok=True)\n py_file = deploy_path/\"input_drift.py\"\n with open(py_file, \"w\") as f:\n f.write(code)\n req_file = deploy_path/\"requirements.txt\"\n with open(req_file, \"w\") as f:\n f.write(importer.getBaseModule())\n create_docker_file('input_drift', deploy_path)\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom pathlib import Path\nimport json\nfrom mlac.ml.core import *\nfrom .utility import *\n\nimported_modules = [\n {'module': 'sys', 'mod_from': None, 'mod_as': None},\n {'module': 'json', 'mod_from': None, 'mod_as': None},\n {'module': 'math', 'mod_from': None, 'mod_as': None},\n {'module': 'joblib', 'mod_from': None, 'mod_as': None},\n {'module': 'mlflow', 'mod_from': None, 'mod_as': None},\n {'module': 'sklearn', 'mod_from': None, 'mod_as': None},\n {'module': 'Path', 'mod_from': 'pathlib', 'mod_as': None},\n {'module': 'numpy', 'mod_from': None, 'mod_as': 'np'},\n {'module': 'pandas', 'mod_from': None, 'mod_as': 'pd'},\n {'module': 'argparse', 'mod_from': None, 'mod_as': None},\n {'module': 'stats', 'mod_from': 'scipy', 'mod_as': 'st'},\n {'module': 'platform', 'mod_from': None, 'mod_as': None } \n ]\n\ndef get_drift_params(config):\n param_keys = [\"modelVersion\",\"problem_type\",\"target_feature\",\"selected_features\",\"scoring_criteria\",\"s3\"]\n data = {key:value for (key,value) in config.items() if key in param_keys}\n usecase = config['modelName']\n data['targetPath'] = usecase\n if config['dataLocation'] != '':\n data['inputUri'] = config['dataLocation']\t\n else:\t\n data['inputUri'] = ''\t\n data['prod_db_type'] = config.get('prod_db_type', 'sqlite')\n data['db_config'] = config.get('db_config', {})\n data['mlflow_config'] = config.get('mlflow_config', {'artifacts_uri':'','tracking_uri_type':'','tracking_uri':'','registry_uri':''})\n return data\n\ndef run_drift_analysis(config):\n init_variables()\n importer = importModule()\n function = global_function()\n drifter = drift()\n importModules(importer, imported_modules)\n usecase = config['modelName']+'_'+config['modelVersion']\n deploy_path = Path(config[\"deploy_path\"])/'MLaC'/'ModelMonitoring'\n deploy_path.mkdir(parents=True, exist_ok=True)\n \n generated_files = []\n # create the utility file\n importer.addLocalModule('*', mod_from='utility')\n utility_obj = utility_function('drift')\n with open(deploy_path/\"utility.py\", 'w') as f:\n f.write(file_header(usecase) + utility_obj.get_code())\n generated_files.append(\"utility.py\") \n # create the production data reader file\n importer.addLocalModule('dataReader', mod_from='data_reader')\n readers = ['sqlite','influx']\n if 's3' in config.keys():\n readers.append('s3')\n reader_obj = data_reader(readers)\n with open(deploy_path/\"data_reader.py\", 'w') as f:\n f.write(file_header(usecase) + reader_obj.get_code())\n generated_files.append(\"data_reader.py\") \n \n # create empty init file to make a package \n with open(deploy_path/\"__init__.py\", 'w') as f:\n f.write(file_header(usecase))\n generated_files.append(\"__init__.py\") \n importer.addLocalModule('inputdrift', mod_from='input_drift')\n \n code = file_header(usecase)\n code += importer.getCode()\n code += drifter.getInputOutputFiles()\n code += function.getCode()\n code += drifter.get_main_drift_code(config['problem_type'], get_variable('smaller_is_better', False))\n with open(deploy_path/\"aionCode.py\", \"w\") as f:\n f.write(code)\n generated_files.append(\"aionCode.py\") \n\n input_drift_importer = importModule()\n importModules(input_drift_importer, drifter.get_input_drift_import_modules())\n code = file_header(usecase)\n code += input_drift_importer.getCode()\n code += drifter.get_input_drift_code()\n with open(deploy_path/\"input_drift.py\", \"w\") as f:\n f.write(code)\n generated_files.append(\"input_drift.py\") \n\n with open (deploy_path/\"config.json\", \"w\") as f:\n json.dump(get_drift_params(config), f, indent=4)\n generated_files.append(\"config.json\") \n\n req_file = deploy_path/\"requirements.txt\"\n with open(req_file, \"w\") as f:\n f.write(importer.getBaseModule(extra_importers=[utility_obj.get_importer(), reader_obj.get_importer(), input_drift_importer]))\n generated_files.append(\"requirements.txt\") \n create_docker_file('input_drift', deploy_path,config['modelName'], generated_files)\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nimport shutil\nfrom pathlib import Path\nimport json\nfrom mlac.ml.core import *\nfrom .utility import *\nimport tarfile\ndef add_text_dependency():\n return \"\"\"nltk==3.6.3\ntextblob==0.15.3\nspacy==3.1.3\ndemoji==1.1.0\nbs4==0.0.1\ntext_unidecode==1.3\ncontractions==0.1.73\n\"\"\"\n \ndef get_deploy_params(config):\n param_keys = [\"modelVersion\",\"problem_type\",\"target_feature\"]\n data = {key:value for (key,value) in config.items() if key in param_keys}\n data['targetPath'] = config['modelName']\n data['ipAddress'] = '127.0.0.1'\n data['portNo'] = '8094'\n return data\n\ndef import_trainer_module(importer):\n non_sklearn_modules = get_variable('non_sklearn_modules')\n if non_sklearn_modules:\n for mod in non_sklearn_modules:\n module = get_module_mapping(mod)\n mod_from = module.get('mod_from',None)\n mod_as = module.get('mod_as',None)\n importer.addModule(module['module'], mod_from=mod_from, mod_as=mod_as)\n\nimported_modules = [\n {'module': 'sys', 'mod_from': None, 'mod_as': None},\n {'module': 'math', 'mod_from': None, 'mod_as': None},\n {'module': 'json', 'mod_from': None, 'mod_as': None},\n {'module': 'scipy', 'mod_from': None, 'mod_as': None},\n {'module': 'joblib', 'mod_from': None, 'mod_as': None},\n {'module': 'shutil', 'mod_from': None, 'mod_as': None},\n {'module': 'mlflow', 'mod_from': None, 'mod_as': None},\n {'module': 'sklearn', 'mod_from': None, 'mod_as': None},\n {'module': 'numpy', 'mod_from': None, 'mod_as': 'np'},\n {'module': 'Path', 'mod_from': 'pathlib', 'mod_as': None},\n {'module': 'pandas', 'mod_from': None, 'mod_as': 'pd'},\n {'module': 'argparse', 'mod_from': None, 'mod_as': None},\n {'module': 'platform', 'mod_from': None, 'mod", "instruction": "", "output": "" }, { "input": "_as': None} \n ]\n\ndef run_deploy(config):\n generated_files = []\n importer = importModule()\n deployer = deploy(target_encoder = get_variable('target_encoder', False),feature_reducer = get_variable('feature_reducer', False),score_smaller_is_better = get_variable('smaller_is_better', False))\n\n function = global_function()\n importModules(importer, imported_modules)\n\n if get_variable('cat_encoder', False):\n importer.addModule('category_encoders')\n import_trainer_module(importer)\n if get_variable('word2num_features'):\n function.add_function('s2n', importer)\n if get_variable('text_features'):\n importer.addLocalModule('textProfiler', mod_from='text.textProfiler')\n\n usecase = config['modelName']+'_'+config['modelVersion']\n deploy_path = Path(config[\"deploy_path\"])/'MLaC'/'ModelServing'\n deploy_path.mkdir(parents=True, exist_ok=True)\n\n # create the utility file\n importer.addLocalModule('*', mod_from='utility')\n utility_obj = utility_function('Prediction')\n with open(deploy_path/\"utility.py\", 'w') as f:\n f.write(file_header(usecase) + utility_obj.get_code())\n generated_files.append(\"utility.py\") \n \n # create the production data reader file\n importer.addLocalModule('*', mod_from='data_reader')\n reader_obj = data_reader(['sqlite','influx'])\n with open(deploy_path/\"data_reader.py\", 'w') as f:\n f.write(file_header(usecase) + reader_obj.get_code())\n generated_files.append(\"data_reader.py\") \n\n # need to copy data profiler from AION code as code is splitted and merging code amnnually\n # can add bugs\n aion_utilities = Path(__file__).parent.parent.parent.parent / 'utilities'\n\n with tarfile.open(aion_utilities / 'text.tar') as file:\n file.extractall(deploy_path)\n if (deploy_path / 'utils').exists():\n shutil.rmtree(deploy_path / 'utils')\n with tarfile.open(aion_utilities / 'utils.tar') as file:\n file.extractall(deploy_path )\n generated_files.append(\"text\") \n generated_files.append(\"utils\") \n \n # create empty init file required for creating a package \n with open(deploy_path/\"__init__.py\", 'w') as f:\n f.write(file_header(usecase))\n generated_files.append(\"__init__.py\") \n\n function.add_function('get_mlflow_uris')\n code = file_header(usecase)\n code += importer.getCode()\n code += deployer.getInputOutputFiles()\n code += function.getCode()\n code += deployer.getCode()\n\n # create prediction file\n with open(deploy_path/\"predict.py\", 'w') as f:\n f.write(code)\n generated_files.append(\"predict.py\") \n \n # create groundtruth file\n with open(deploy_path/\"groundtruth.py\", 'w') as f:\n f.write(file_header(usecase) + deployer.getGroundtruthCode())\n generated_files.append(\"groundtruth.py\") \n\n # create create service file\n with open(deploy_path/\"aionCode.py\", 'w') as f:\n f.write(file_header(usecase) + deployer.getServiceCode())\n generated_files.append(\"aionCode.py\") \n importer.addModule('seaborn')\n # create requirements file\n req_file = deploy_path/\"requirements.txt\"\n with open(req_file, \"w\") as f:\n req=importer.getBaseModule(extra_importers=[utility_obj.get_importer(), reader_obj.get_importer()])\n if config[\"text_features\"]:\n req += add_text_dependency()\n f.write(req)\n generated_files.append(\"requirements.txt\")\n \n # create config file\n config_file = deploy_path/\"config.json\"\n config_data = get_deploy_params(config)\n with open (config_file, \"w\") as f:\n json.dump(config_data, f, indent=4)\n generated_files.append(\"config.json\") \n \n # create docker file\n create_docker_file('Prediction', deploy_path,config['modelName'], generated_files, True if config[\"text_features\"] else False) \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\nimport json\n\nclass transformer():\n \n def __init__(self, indent=0, tab_size=4):\n self.df_name = 'df'\n self.tab = ' ' * tab_size\n self.codeText = \"\"\n self.transformers = []\n self.TxCols = []\n self.imputers = {}\n self.input_files = {}\n self.output_files = {}\n self.function_code = ''\n self.addInputFiles({'inputData' : 'rawData.dat', 'metaData' : 'modelMetaData.json','log' : 'aion.log','transformedData' : 'transformedData.dat','normalization' : 'normalization.pkl'})\n \n def addInputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def addOutputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def getInputFiles(self): \n text = 'IOFiles = '\n if not self.input_files:\n text += '{ }'\n else:\n text += json.dumps(self.input_files, indent=4)\n return text\n \n def getOutputFiles(self):\n text = 'output_file = '\n if not self.output_files:\n text += '{ }'\n else:\n text += json.dumps(self.output_files, indent=4)\n return text\n \n def getInputOutputFiles(self, indent=0):\n text = '\\\\n'\n text += self.getInputFiles()\n if indent:\n text = text.replace('\\\\n', self.tab * indent + '\\\\n')\n return text\n \n def __addValidateConfigCode(self):\n text = \"\\\\n\\\\\n \\\\ndef validateConfig():\\\\\n \\\\n config_file = Path(__file__).parent/'config.json'\\\\\n \\\\n if not Path(config_file).exists():\\\\\n \\\\n raise ValueError(f'Config file is missing: {config_file}')\\\\\n \\\\n config = read_json(config_file)\\\\\n \\\\n return config\"\n return text\n\n def getPrefixModules(self):\n modules = [\n {'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'pandas', 'mod_as':'pd'}\n ,{'module':'warnings'}\n ,{'module':'json'}\n ,{'module':'logging'}\n ,{'module':'joblib'}\n ,{'module':'MinMaxScaler', 'mod_from':'sklearn.preprocessing'}\n ]\n return modules\n \n def addPrefixCode(self, indent=1):\n self.codeText += \"\"\"\ndef transformation(config, targetPath, log):\n dataLoc = targetPath / IOFiles['inputData']\n if not dataLoc.exists():\n return {'Status': 'Failure', 'Message': 'Data location does not exists.'}\n df = read_data(dataLoc)\n log.log_dataframe(df)\n\n target_feature = config['target_feature']\n dateTimeFeature=config['dateTimeFeature']\n df.set_index(dateTimeFeature, inplace=True)\n df = df.dropna()\n df=df.fillna(df.mean())\n if len(target_feature) == 1:\n trainX = df[target_feature].to_numpy().reshape(-1,1)\n else:\n trainX = df[target_feature].to_numpy()\n \n scaler = MinMaxScaler(feature_range=(0, 1))\n trainX = scaler.fit_transform(trainX)\n normalization_file_name = str(targetPath / IOFiles['normalization'])\n joblib.dump(scaler, normalization_file_name)\n \n df[target_feature] = trainX\n log.log_dataframe(df)\n csv_path = str(targetPath / IOFiles['transformedData'])\n write_data(df, csv_path, index=True)\n\n status = {'Status': 'Success', 'DataFilePath': IOFiles['transformedData'],\n 'target_feature': target_feature,'dateTimeFeature':dateTimeFeature,\n \"Normalization_file\":normalization_file_name }\n meta_data['transformation'] = {}\n meta_data['transformation']['Status'] = status\n write_json(meta_data, str(targetPath / IOFiles['metaData']))\n log.info(f'Transformed data saved at {csv_path}')\n log.info(f'output: {status}')\n return json.dumps(status)\n \"\"\"\n def getMainCodeModules(self):\n modules = [{'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'sys'}\n ,{'module':'json'}\n ,{'module':'logging'}\n ,{'module':'argparse'}\n ]\n return modules\n \n def addMainCode(self, indent=1):\n self.codeText += \"\"\"\nif __name__ == '__main__':\n config = validateConfig()\n targetPath = Path('aion') / config['targetPath']\n if not targetPath.exists():\n raise ValueError(f'targetPath does not exist')\n meta_data_file = targetPath / IOFiles['metaData']\n if meta_data_file.exists():\n meta_data = read_json(meta_data_file)\n else:\n raise ValueError(f'Configuration file not found: {meta_data_file}')\n log_file = targetPath / IOFiles['log']\n log = logger(log_file, mode='a', logger_name=Path(__file__).parent.stem)\n try:\n print(transformation(config, targetPath, log))\n except Exception as e:\n \n status = {'Status': 'Failure', 'Message': str(e)}\n print(json.dumps(status))\n \"\"\"\n def addValidateConfigCode(self, indent=1):\n self.function_code += self.__addValidateConfigCode()\n\n def addLocalFunctionsCode(self):\n self.addValidateConfigCode()\n\n def addStatement(self, statement, indent=1):\n self.codeText += '\\\\n' + self.tab * indent + statement\n\n def getCode(self, indent=1):\n return self.function_code + '\\\\n' + self.codeText\n \n def getDFName(self):\n return self.df_name\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\nimport json\n\nclass selector():\n\n def __init__(self, indent=0, tab_size=4):\n self.tab = \" \"*tab_size\n self.codeText = \"\"\n self.pipe = 'pipe'\n self.code_generated = False\n self.input_files = {}\n self.output_files = {}\n self.function_code = ''\n self.addInputFiles({'inputData' : 'transformedData.dat', 'metaData' : 'modelMetaData.json','log' : 'aion.log','outputData' : 'featureEngineeredData.dat'})\n\n def addInputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def addOutputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def getInputFiles(self): \n text = 'IOFiles = '\n if not self.input_files:\n text += '{ }'\n else:\n text += json.dumps(self.input_files, indent=4)\n return text\n \n def getOutputFiles(self):\n text = 'output_file = '\n if not self.output_files:\n text += '{ }'\n else:\n text += json.dumps(self.output_files, indent=4)\n return text\n \n def getInputOutputFiles(self, indent=0):\n text = '\\\\n'\n text += self.getInputFiles()\n if indent:\n text = text.replace('\\\\n', self.tab * indent + '\\\\n')\n return text\n \n def __addValidateConfigCode(self):\n text = \"\\\\n\\\\\n \\\\ndef validateConfig():\\\\\n \\\\n config_file = Path(__file__).parent/'config.json'\\\\\n \\\\n if not Path(config_file).exists():\\\\\n \\\\n raise ValueError(f'Config file is missing: {config_file}')\\\\\n \\\\n config = read_json(config_file)\\\\\n \\\\n return config\"\n return text\n\n def addMainCode(self):\n self.codeText += \"\"\"\nif __name__ == '__main__':\n config = validateConfig()\n targetPath = Path('aion') / config['targetPath']\n if not targetPath.exists():\n raise ValueError(f'targetPath does not exist')\n meta_data_file = targetPath / IOFiles['metaData']\n if meta_data_file.exists():\n meta_data = read_json(meta_data_file)\n else:\n raise ValueError(f'Configuration file not found: {meta_data_file}')\n log_file = targetPath / IOFiles['log']\n log = logger(log_file, mode='a', logger_name=Path(__file__).parent.stem)\n try:\n print(featureSelector(config,targetPath, log))\n except Exception as e:\n \n status = {'Status': 'Failure', 'Message': str(e)}\n print(json.dumps(status))\n \"\"\"\n\n def", "instruction": "", "output": "" }, { "input": "addValidateConfigCode(self, indent=1):\n self.function_code += self.__addValidateConfigCode()\n\n def addStatement(self, statement, indent=1):\n self.codeText += '\\\\n' + self.tab * indent + statement\n \n def getCode(self):\n return self.function_code + '\\\\n' + self.codeText\n\n def addLocalFunctionsCode(self):\n self.addValidateConfigCode()\n \n def getPrefixModules(self):\n modules = [{'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'pandas', 'mod_as':'pd'}\n ]\n return modules\n \n def addPrefixCode(self, indent=1):\n self.codeText += \"\"\"\ndef featureSelector(config, targetPath, log):\n dataLoc = targetPath / IOFiles['inputData']\n if not dataLoc.exists():\n return {'Status': 'Failure', 'Message': 'Data location does not exists.'}\n\n status = dict()\n df = pd.read_csv(dataLoc)\n log.log_dataframe(df)\n\n csv_path = str(targetPath / IOFiles['outputData'])\n write_data(df, csv_path, index=False)\n status = {'Status': 'Success', 'dataFilePath': IOFiles['outputData']}\n log.info(f'Selected data saved at {csv_path}')\n meta_data['featureengineering'] = {}\n meta_data['featureengineering']['Status'] = status\n write_json(meta_data, str(targetPath / IOFiles['metaData']))\n log.info(f'output: {status}')\n return json.dumps(status)\n \"\"\"\n \n def getSuffixModules(self):\n modules = []\n return modules\n \n def addSuffixCode(self, indent=1):\n self.codeText += \"\"\n\n def getMainCodeModules(self):\n modules = [\n {'module':'json'}\n ,{'module':'logging'}\n ]\n return modules\n \n def addStatement(self, statement, indent=1):\n self.codeText += f\"\\\\n{self.tab * indent}{statement}\"\n\n def getPipe(self):\n return self.pipe\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nimport json\n\nclass learner():\n\n def __init__(self, problem_type=\"classification\", target_feature=\"\", sample_method=None,indent=0, tab_size=4):\n self.tab = \" \"*tab_size\n self.df_name = 'df'\n self.problem_type = problem_type\n self.target_feature = target_feature\n self.search_space = []\n self.codeText = f\"\\\\ndef train(log):\"\n self.input_files = {}\n self.output_files = {}\n self.function_code = ''\n self.addInputFiles({'inputData' : 'featureEngineeredData.dat', 'metaData' : 'modelMetaData.json','monitor':'monitoring.json'})\n\n def addInputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def addOutputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def getInputFiles(self): \n text = 'IOFiles = '\n if not self.input_files:\n text += '{ }'\n else:\n text += json.dumps(self.input_files, indent=4)\n return text\n \n def getOutputFiles(self):\n text = 'output_file = '\n if not self.output_files:\n text += '{ }'\n else:\n text += json.dumps(self.output_files, indent=4)\n return text\n \n def getInputOutputFiles(self, indent=0):\n text = '\\\\n'\n text += self.getInputFiles()\n if indent:\n text = text.replace('\\\\n', self.tab * indent + '\\\\n')\n return text\n \n def __addValidateConfigCode(self):\n text = \"\\\\n\\\\\n \\\\ndef validateConfig():\\\\\n \\\\n config_file = Path(__file__).parent/'config.json'\\\\\n \\\\n if not Path(config_file).exists():\\\\\n \\\\n raise ValueError(f'Config file is missing: {config_file}')\\\\\n \\\\n config = utils.read_json(config_file)\\\\\n \\\\n return config\"\n return text\n\n def addStatement(self, statement, indent=1):\n self.codeText += '\\\\n' + self.tab * indent + statement\n \n def getCode(self):\n return self.function_code + '\\\\n' + self.codeText\n\n def addLocalFunctionsCode(self):\n self.function_code += self.__addValidateConfigCode()\n\n def getPrefixModules(self):\n modules = [{'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'pandas', 'mod_as':'pd'}\n ]\n return modules\n \n def addPrefixCode(self, indent=1):\n self.codeText += \"\\\\\n \"\n def getSuffixModules(self):\n modules = []\n return modules\n\n def addSuffixCode(self, indent=1):\n self.codeText += \"\\\\n\\\\\n \"\n def getMainCodeModules(self):\n modules = [{'module':'logging'}\n ]\n return modules\n\n def getMlpCodeModules(self):\n modules = [{'module':'math'}\n ,{'module':'json'}\n ,{'module':'joblib'}\n ,{'module':'keras_tuner'}\n ,{'module':'pandas', 'mod_as':'pd'}\n ,{'module':'numpy', 'mod_as':'np'}\n ,{'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'r2_score', 'mod_from':'sklearn.metrics'}\n ,{'module':'mean_squared_error', 'mod_from':'sklearn.metrics'}\n ,{'module':'mean_absolute_error', 'mod_from':'sklearn.metrics'}\n ,{'module':'Dense', 'mod_from':'tensorflow.keras.layers'}\n ,{'module':'Sequential', 'mod_from':'tensorflow.keras'}\n ,{'module':'Dropout', 'mod_from':'tensorflow.keras.layers'}\n ]\n return modules\n\n def addMlpCode(self):\n self.codeText = \"\"\"\ndef getdlparams(config): \n for k, v in config.items():\n if (k == \"activation\"):\n activation_fn = str(v)\n elif (k == \"optimizer\"):\n optimizer = str(v)\n elif (k == \"loss\"):\n loss_fn = str(v)\n elif (k == \"first_layer\"):\n if not isinstance(k, list):\n first_layer = str(v).split(',')\n else:\n first_layer = k\n elif (k == \"lag_order\"):\n lag_order = int(v)\n elif (k == \"hidden_layers\"):\n hidden_layers = int(v)\n elif (k == \"dropout\"):\n if not isinstance(k, list):\n dropout = str(v).split(',')\n else:\n dropout = k\n elif (k == \"batch_size\"):\n batch_size = int(v)\n elif (k == \"epochs\"):\n epochs = int(v)\n elif (k == \"model_name\"):\n model_name = str(v)\n return activation_fn, optimizer, loss_fn, first_layer, lag_order, hidden_layers, dropout, batch_size, epochs, model_name\ndef numpydf(dataset, look_back):\n dataX, dataY = [], []\n for i in range(len(dataset) - look_back - 1):\n subset = dataset[i:(i + look_back), 0]\n dataX.append(subset)\n dataY.append(dataset[i + look_back, 0])\n return np.array(dataX), np.array(dataY)\n\ndef startTraining(dataset,train_size,mlpConfig,filename_scaler,target_feature,scoreParam,log):\n log.info('Training started')\n activation_fn, optimizer, loss_fn, first_layer, hidden_layers, look_back, dropout, batch_size, epochs, model_name = getdlparams(mlpConfig)\n hp = keras_tuner.HyperParameters() \n first_layer_min = round(int(first_layer[0]))\n first_layer_max = round(int(first_layer[1]))\n dropout_min = float(dropout[0])\n dropout_max = float(dropout[1]) \n dataset = dataset.values\n train, test = dataset[0:train_size, :], dataset[train_size:len(dataset), :]\n trainX, trainY = numpydf(train, look_back)\n testX, testY = numpydf(test, look_back)\n # create and fit Multilayer Perceptron model\n model = Sequential()\n model.add(Dense(units=hp.Int('units',min_value=first_layer_min,max_value=first_layer_max,step=16), input_dim=look_back, activation=activation_fn)) #BUGID 13484\n model.add(Dropout(hp.Float('Dropout_rate',min_value=dropout_min,max_value=dropout_max,step=0.1))) #BUGID 13484\n model.add(Dense(1, activation='sigmoid'))\n model.compile(loss=loss_fn, optimizer=optimizer)\n model_fit = model.fit(trainX, trainY, epochs=epochs, batch_size=batch_size, verbose=2)\n # Estimate model performance\n trainScore = model.evaluate(trainX, trainY, verbose=0)\n testScore = model.evaluate(testX, testY, verbose=0)\n # Scoring values for the model\n mse_eval = testScore\n rmse_eval = math.sqrt(testScore)\n # generate predictions for training\n trainPredict = model.predict(trainX)\n testPredict = model.predict(testX)\n scaler = joblib.load(filename_scaler)\n\n trainY = scaler.inverse_transform([trainY])\n trainPredict = scaler.inverse_transform(trainPredict)\n ## For test data\n testY = scaler.inverse_transform([testY])\n testPredict = scaler.inverse_transform(testPredict)\n mse_mlp = mean_squared_error(testY.T, testPredict)\n scores = {}\n r2 = round(r2_score(testY.T, testPredict), 2)\n scores['R2'] = r2\n \n mae = round(mean_absolute_error(testY.T, testPredict), 2)\n scores['MAE'] = mae\n \n scores['MSE'] = round(mse_mlp, 2)\n \n rmse = round(math.sqrt(mse_mlp), 2)\n scores['RMSE'] = rmse\n \n \n scores[scoreParam] = scores.get(scoreParam.upper(), scores['MSE'])\n log.info(\"mlp rmse: \"+str(rmse))\n log.info(\"mlp mse: \"+str(round(mse_mlp, 2)))\n log.info(\"mlp r2: \"+str(r2))\n log.info(\"mlp mae: \"+str(mae))\n\n return model, look_back, scaler,testScore,trainScore,scores\n\ndef train(config, targetPath, log):\n\n dataLoc = targetPath / IOFiles['inputData']\n if not dataLoc.exists():\n return {'Status': 'Failure', 'Message': 'Data location does not exists.'}\n\n status = dict()\n usecase = config['targetPath']\n df = utils.read_data(dataLoc)\n target_feature = config['target_feature']\n dateTimeFeature= config['dateTimeFeature']\n df.set_index(dateTimeFeature, inplace=True)\n train_size = int(len(df) * (1-config['test_ratio'])) #BugID:13217\n mlpConfig = config['algorithms']['MLP']\n filename = meta_data['transformation']['Status']['Normalization_file']\n scoreParam = config['scoring_criteria']\n log.info('Training MLP for TimeSeries')\n mlp_model, look_back, scaler,testScore,trainScore, error_matrix = startTraining(df,train_size,mlpConfig,filename,target_feature,scoreParam,log)\n score = error_matrix[scoreParam]\n # Training model\n \n\n model_path = targetPath/'runs'/str(meta_data['monitoring']['runId'])/model_name\n model_file_name = str(model_path/'model')\n mlp_model.save(model_file_name)\n meta_data['training'] = {}\n meta_data['training']['model_filename'] = model_file_name\n meta_data['training']['dateTimeFeature'] = dateTimeFeature\n meta_data['training']['target_feature'] = target_feature\n utils.write_json(meta_data, targetPath / IOFiles['metaData'])\n utils.write_json({'scoring_criteria': scoreParam, 'metrices': error_matrix,'score':error_matrix[scoreParam]}, model_path / IOFiles['metrics'])\n # return status\n status = {'Status': 'Success', 'errorMatrix': error_matrix, 'test_score':testScore, 'train_score': trainScore,'score':error_matrix[scoreParam]}\n log.info(f'Test score: {testScore}')\n log.info(f'Train score: {trainScore}')\n log.info(f'output: {status}')\n return json.dumps(status)\n \"\"\"\n\n def getLstmCodeModules(self):\n modules = [{'module':'math'}\n ,{'module':'json'}\n ,{'module':'joblib'}\n ,{'module':'keras_tuner'}\n ,{'module':'pandas', 'mod_as':'pd'}\n ,{'module':'numpy', 'mod_as':'np'}\n ,{'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'r2_score', 'mod_from':'sklearn.metrics'}\n ,{'module':'mean_squared_error', 'mod_from':'sklearn.metrics'}\n ,{'module':'mean_absolute_error', 'mod_from':'sklearn.metrics'}\n ,{'module':'Dense', 'mod_from':'tensorflow.keras.layers'}\n ,{'module':'Sequential', 'mod_from':'tensorflow.keras'}\n ,{'module':'Dropout', 'mod_from':'tensorflow.keras.layers'}\n ,{'module':'LSTM', 'mod_from':'tensorflow.keras.layers'}\n ,{'module':'TimeseriesGenerator', 'mod_from':'tensorflow.keras.preprocessing.sequence'}\n ,{'module':'train_test_split', 'mod_from':'sklearn.model_selection'}\n ]\n return modules\n\n def addLstmCode(self):\n self.codeText = \"\"\"\ndef getdlparams(config):\n for k, v in config.items():\n if (k", "instruction": "", "output": "" }, { "input": "== \"activation\"):\n activation_fn = str(v)\n elif (k == \"optimizer\"):\n optimizer = str(v)\n elif (k == \"loss\"):\n loss_fn = str(v)\n elif (k == \"first_layer\"):\n if not isinstance(k, list):\n ", "instruction": "", "output": "" }, { "input": "\n status = {}\n output_data_path = targetPath / IOFiles['outputData']\n log.log_dataframe(df)\n required_features = list(set(config['selected_features'] + config['dateTimeFeature'] + config['target_feature']))\n log.info('Dataset features required: ' + ','.join(required_features))\n missing_features = [x for x in required_features if x not in df.columns.tolist()]\n if missing_features:\n raise ValueError(f'Some feature/s is/are missing: {missing_features}')\n log.info('Removing unused features: ' + ','.join(list(set(df.columns) - set(required_features))))\n df = df[required_features]\n log.info(f'Required features: {required_features}')\n try:\n log.info(f'Saving Dataset: {str(output_data_path)}')\n write_data(df, output_data_path, index=False)\n status = {'Status': 'Success', 'DataFilePath': IOFiles['outputData'], 'Records': len(df)}\n except:\n raise ValueError('Unable to create data file')\n\n meta_data['load_data'] = {}\n meta_data['load_data']['selected_features'] = [x for x in config['selected_features'] if\n x != config['target_feature']]\n meta_data['load_data']['Status'] = status\n write_json(meta_data, meta_data_file)\n output = json.dumps(status)\n log.info(output)\n return output\n\"\"\"\n def addValidateConfigCode(self, indent=1):\n self.function_code += self.__addValidateConfigCode()\n\n def addLocalFunctionsCode(self):\n self.addValidateConfigCode()\n\n def addStatement(self, statement, indent=1):\n self.codeText += '\\\\n' + self.tab * indent + statement\n \n def getCode(self):\n return self.function_code + '\\\\n' + self.codeText\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\nimport json\n\nclass register():\n\n def __init__(self, importer, indent=0, tab_size=4):\n self.tab = \" \"*tab_size\n self.codeText = \"\"\n self.function_code = \"\"\n self.importer = importer\n self.input_files = {}\n self.output_files = {}\n self.addInputFiles({'log' : 'aion.log', 'metaData' : 'modelMetaData.json','metrics': 'metrics.json','production': 'production.json'})\n \n def addInputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def addOutputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def getInputFiles(self): \n text = 'IOFiles = '\n if not self.input_files:\n text += '{ }'\n else:\n text += json.dumps(self.input_files, indent=4)\n return text\n \n def getOutputFiles(self):\n text = 'output_file = '\n if not self.output_files:\n text += '{ }'\n else:\n text += json.dumps(self.output_files, indent=4)\n return text\n \n def getInputOutputFiles(self, indent=0):\n text = '\\\\n'\n text += self.getInputFiles()\n if indent:\n text = text.replace('\\\\n', self.tab * indent + '\\\\n')\n return text\n\n def __addValidateConfigCode(self, models=None):\n text = \"\\\\n\\\\\n \\\\ndef validateConfig():\\\\\n \\\\n config_file = Path(__file__).parent/'config.json'\\\\\n \\\\n if not Path(config_file).exists():\\\\\n \\\\n raise ValueError(f'Config file is missing: {config_file}')\\\\\n \\\\n config = utils.read_json(config_file)\\\\\n \\\\n return config\\\\\n \"\n return text\n \n def addLocalFunctionsCode(self, models):\n self.function_code += self.__addValidateConfigCode(models)\n \n def addPrefixCode(self, smaller_is_better=False, indent=1):\n compare = 'min' if smaller_is_better else 'max'\n self.codeText += f\"\"\"\ndef get_best_model(run_path):\n models_path = [d for d in run_path.iterdir() if d.is_dir]\n scores = {{}}\n for model in models_path:\n metrics = utils.read_json(model/IOFiles['metrics'])\n if metrics.get('score', None):\n scores[model.stem] = metrics['score']\n best_model = {compare}(scores, key=scores.get) \n return best_model\n\ndef __merge_logs(log_file_sequence,path, files): \n if log_file_sequence['first'] in files: \n with open(path/log_file_sequence['first'], 'r') as f: \n main_log = f.read() \n files.remove(log_file_sequence['first']) \n for file in files: \n with open(path/file, 'r') as f: \n main_log = main_log + f.read() \n (path/file).unlink() \n with open(path/log_file_sequence['merged'], 'w') as f: \n f.write(main_log) \n \ndef merge_log_files(folder, models): \n log_file_sequence = {{ \n 'first': 'aion.log', \n 'merged': 'aion.log' \n }} \n log_file_suffix = '_aion.log' \n log_files = [x+log_file_suffix for x in models if (folder/(x+log_file_suffix)).exists()] \n log_files.append(log_file_sequence['first']) \n __merge_logs(log_file_sequence, folder, log_files) \n\ndef register(config, targetPath, log): \n meta_data_file = targetPath / IOFiles['metaData']\n if meta_data_file.exists():\n meta_data = utils.read_json(meta_data_file)\n else:\n raise ValueError(f'Configuration file not found: {{meta_data_file}}')\n run_id = meta_data['monitoring']['runId']\n usecase = config['targetPath']\n current_run_path = targetPath/'runs'/str(run_id)\n register_model_name = get_best_model(current_run_path)\n models = config['models'] \n merge_log_files(targetPath, models) \n meta_data['register'] = {{'runId':run_id, 'model': register_model_name}}\n utils.write_json(meta_data, targetPath/IOFiles['metaData'])\n utils.write_json({{'Model':register_model_name,'runNo':str(run_id)}}, targetPath/IOFiles['production'])\n status = {{'Status':'Success','Message':f'Model Registered: {{register_model_name}}'}} \n log.info(f'output: {{status}}') \n return json.dumps(status)\n \"\"\"\n def getMainCodeModules(self):\n modules = [{'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'json'}\n ]\n return modules\n \n def addMainCode(self, models, indent=1):\n self.codeText += \"\"\"\nif __name__ == '__main__':\n config = validateConfig()\n targetPath = Path('aion') / config['targetPath']\n if not targetPath.exists():\n raise ValueError(f'targetPath does not exist')\n log_file = targetPath / IOFiles['log']\n log = utils.logger(log_file, mode='a', logger_name=Path(__file__).parent.stem)\n try:\n print(register(config, targetPath, log))\n except Exception as e:\n \n status = {'Status': 'Failure', 'Message': str(e)}\n print(json.dumps(status))\n \"\"\"\n\n def addStatement(self, statement, indent=1):\n self.codeText += f\"\\\\n{self.tab * indent}{statement}\"\n \n def getCode(self, indent=1):\n return self.function_code + '\\\\n' + self.codeText\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nclass global_function():\n\n def __init__(self, tab_size=4):\n self.tab = ' ' * tab_size\n self.codeText = \"\"\n self.available_functions = {\n 'iqr':{'name':'iqrOutlier','code':f\"\\\\n\\\\ndef iqrOutlier(df):\\\\\n \\\\n{self.tab}Q1 = df.quantile(0.25)\\\\\n \\\\n{self.tab}Q3 = df.quantile(0.75)\\\\\n \\\\n{self.tab}IQR = Q3 - Q1\\\\\n \\\\n{self.tab}index = ~((df < (Q1 - 1.5 * IQR)) |(df > (Q3 + 1.5 * IQR))).any(axis=1)\\\\\n \\\\n{self.tab}return index\"},\n 'zscore':{'name':'zscoreOutlier','imports':[{'mod':'stats','mod_from':'scipy'},{'mod':'numpy'}],'code':f\"\\\\n\\\\ndef zscoreOutlier(df):\\\\\n \\\\n{self.tab}z = numpy.abs(stats.zscore(df))\\\\\n \\\\n{self.tab}index = (z < 3).all(axis=1)\\\\\n \\\\n{self.tab}return index\"},\n 'iforest':{'name':'iforestOutlier','imports':[{'mod':'IsolationForest','mod_from':'sklearn.ensemble'}],'code':f\"\\\\n\\\\ndef iforestOutlier(df):\\\\\n \\\\n{self.tab}from sklearn.ensemble import IsolationForest\\\\\n \\\\n{self.tab}isolation_forest = IsolationForest(n_estimators=100)\\\\\n \\\\n{self.tab}isolation_forest.fit(df)\\\\\n \\\\n{self.tab}y_pred_train = isolation_forest.predict(df)\\\\\n \\\\n{self.tab}return y_pred_train == 1\"},\n 'minMaxImputer':{'name':'minMaxImputer','code':f\"\\\\n\\\\nclass minMaxImputer(TransformerMixin):\\\\\n \\\\n{self.tab}def __init__(self, strategy='max'):\\\\\n \\\\n{self.tab}{self.tab}self.strategy = strategy\\\\\n \\\\n{self.tab}def fit(self, X, y=None):\\\\\n \\\\n{self.tab}{self.tab}self.feature_names_in_ = X.columns\\\\\n \\\\n{self.tab}{self.tab}if self.strategy == 'min':\\\\\n \\\\n{self.tab}{self.tab}{self.tab}self.statistics_ = X.min()\\\\\n \\\\n{self.tab}{self.tab}else:\\\\\n \\\\n{self.tab}{self.tab}{self.tab}self.statistics_ = X.max()\\\\\n \\\\n{self.tab}{self.tab}return self\\\\\n \\\\n{self.tab}def transform(self, X):\\\\\n \\\\n{self.tab}{self.tab}import numpy\\\\\n \\\\n{self.tab}{self.tab}return numpy.where(X.isna(), self.statistics_, X)\"},\n 'DummyEstimator':{'name':'DummyEstimator','code':f\"\\\\n\\\\nclass DummyEstimator(BaseEstimator):\\\\\n \\\\n{self.tab}def fit(self): pass\\\\\n \\\\n{self.tab}def score(self): pass\"},\n 'start_reducer':{'name':'start_reducer','code':\"\\\\n\\\\\n \\\\ndef start_reducer(df,target_feature,corr_threshold=0.85,var_threshold=0.05):\\\\\n \\\\n import numpy as np\\\\\n \\\\n import pandas as pd\\\\\n \\\\n import itertools\\\\\n \\\\n from sklearn.feature_selection import VarianceThreshold\\\\\n \\\\n\\\\\n \\\\n train_features = df.columns.tolist()\\\\\n \\\\n train_features.remove(target_feature)\\\\\n \\\\n df = df.loc[:, (df != df.iloc[0]).any()] #remove constant feature\\\\\n \\\\n numeric_features = df.select_dtypes(include='number').columns.tolist()\\\\\n \\\\n non_numeric_features = df.select_dtypes(exclude='number').columns.tolist()\\\\\n \\\\n if numeric_features and var_threshold:\\\\\n \\\\n qconstantFilter = VarianceThreshold(threshold=var_threshold)\\\\\n \\\\n tempDf=df[numeric_features]\\\\\n \\\\n qconstantFilter.fit(tempDf)\\\\\n \\\\n numeric_features = [x for x,y in zip(numeric_features,qconstantFilter.get_support()) if y]\\\\\n \\\\n if numeric_features:\\\\\n \\\\n numColPairs = list(itertools.product(numeric_features, numeric_features))\\\\\n \\\\n for item in numColPairs:\\\\\n \\\\n if(item[0] == item[1]):\\\\\n \\\\n numColPairs.remove(item)\\\\\n \\\\n tempArray = []\\\\\n \\\\n for item in numColPairs:\\\\\n \\\\n tempCorr = np.abs(df[item[0]].corr(df[item[1]]))\\\\\n \\\\n if(tempCorr > corr_threshold):\\\\\n \\\\n tempArray.append(item[0])\\\\\n \\\\n tempArray = np.unique(tempArray).tolist()\\\\\n \\\\n nonsimilarNumericalCols = list(set(numeric_features) - set(tempArray))\\\\\n \\\\n groupedFeatures = []\\\\\n \\\\n if tempArray:\\\\\n \\\\n corrDic = {}\\\\\n \\\\n for feature in tempArray:\\\\\n \\\\n temp = []\\\\\n \\\\n for col in tempArray:\\\\\n \\\\n tempCorr = np.abs(df[feature].corr(df[col]))\\\\\n \\\\n temp.append(tempCorr)\\\\\n \\\\n corrDic[feature] = temp\\\\\n \\\\n #Similar correlation df\\\\\n \\\\n corrDF = pd.DataFrame(corrDic,index = tempArray)\\\\\n \\\\n corrDF.loc[:,:] = ", "instruction": "", "output": "" }, { "input": "np.tril(corrDF, k=-1)\\\\\n \\\\n alreadyIn = set()\\\\\n \\\\n similarFeatures = []\\\\\n \\\\n for col in corrDF:\\\\\n \\\\n perfectCorr = corrDF[col][corrDF[col] > corr_threshold].index.tolist()\\\\\n \\\\n if perfectCorr and col not in alreadyIn:\\\\\n \\\\n alreadyIn.update(set(perfectCorr))\\\\\n \\\\n perfectCorr.append(col)\\\\\n \\\\n similarFeatures.append(perfectCorr)\\\\\n \\\\n updatedSimFeatures = []\\\\\n \\\\n for items in similarFeatures:\\\\\n \\\\n if(target_feature != '' and target_feature in items):\\\\\n \\\\n for p in items:\\\\\n \\\\n updatedSimFeatures.append(p)\\\\\n \\\\n else:\\\\\n \\\\n updatedSimFeatures.append(items[0])\\\\\n \\\\n newTempFeatures = list(set(updatedSimFeatures + nonsimilarNumericalCols))\\\\\n \\\\n updatedFeatures = list(set(newTempFeatures + non_numeric_features))\\\\\n \\\\n else:\\\\\n \\\\n updatedFeatures = list(set(columns) - set(constFeatures)-set(qconstantColumns))\\\\\n \\\\n else:\\\\\n \\\\n updatedFeatures = list(set(columns) - set(constFeatures)-set(qconstantColumns))\\\\\n \\\\n return updatedFeatures\"},\n 'feature_importance_class':{'name':'feature_importance_class','code':\"\\\\n\\\\\n \\\\ndef feature_importance_class(df, numeric_features, cat_features,target_feature,pValTh,corrTh):\\\\\n \\\\n import pandas as pd\\\\\n \\\\n from sklearn.feature_selection import chi2\\\\\n \\\\n from sklearn.feature_selection import f_classif\\\\\n \\\\n from sklearn.feature_selection import mutual_info_classif\\\\\n \\\\n \\\\\n \\\\n impFeatures = []\\\\\n \\\\n if cat_features:\\\\\n \\\\n categoricalData=df[cat_features]\\\\\n \\\\n chiSqCategorical=chi2(categoricalData,df[target_feature])[1]\\\\\n \\\\n corrSeries=pd.Series(chiSqCategorical, index=cat_features)\\\\\n \\\\n impFeatures.append(corrSeries[corrSeriescorrTh].index.tolist())\\\\\n \\\\n pearsonScore=df.corr() \\\\\n \\\\n targetPScore=abs(pearsonScore[target_feature])\\\\\n \\\\n impFeatures.append(targetPScore[targetPScorecorrTh].index.tolist())\\\\\n \\\\n pearsonScore=df.corr()\\\\\n \\\\n targetPScore=abs(pearsonScore[target_feature])\\\\\n \\\\n impFeatures.append(targetPScore[targetPScore 2):\\\\\n \\\\n score_param = make_scorer(roc_auc_score, needs_proba=True,multi_class='ovr',average='weighted')\\\\\n \\\\n else:\\\\\n \\\\n class_type = 'binary_class' if class_count == 2 else 'multi_class'\\\\\n \\\\n if score_param in scorer_mapping.keys():\\\\\n \\\\n score_param = scorer_mapping[score_param][class_type]\\\\\n \\\\n else:\\\\\n \\\\n score_param = 'accuracy'\\\\\n \\\\n return score_param\"},\n 'log_dataframe':{'name':'log_dataframe','code':f\"\\\\n\\\\\n \\\\ndef log_dataframe(df, msg=None):\\\\\n \\\\n import io\\\\\n \\\\n buffer = io.StringIO()\\\\\n \\\\n df.info(buf=buffer)\\\\\n \\\\n if msg:\\\\\n \\\\n log_text = f'Data frame after {{msg}}:'\\\\\n \\\\n else:\\\\\n \\\\n log_text = 'Data frame:'\\\\\n \\\\n log_text += '\\\\\\\\n\\\\\\\\t'+str(df.head(2)).replace('\\\\\\\\n','\\\\\\\\n\\\\\\\\t')\\\\\n \\\\n log_text += ('\\\\\\\\n\\\\\\\\t' + buffer.getvalue().replace('\\\\\\\\n','\\\\\\\\n\\\\\\\\t'))\\\\\n \\\\n get_logger().info(log_text)\"},\n 'BayesSearchCV':{'name':'BayesSearchCV','imports':[{'mod':'cross_val_score','mod_from':'sklearn.model_selection'},{'mod':'fmin','mod_from':'hyperopt'},{'mod':'tpe','mod_from':'hyperopt'},{'mod':'hp','mod_from':'hyperopt'},{'mod':'STATUS_OK','mod_from':'hyperopt'},{'mod':'Trials','mod_from':'hyperopt'},{'mod':'numpy','mod_as':'np'}],'code':\"\\\\n\\\\\n \\\\nclass BayesSearchCV():\\\\\n \\\\n\\\\\n \\\\n def __init__(self, estimator, params, scoring, n_iter, cv):\\\\\n \\\\n self.estimator = estimator\\\\\n \\\\n self.params = params\\\\\n \\\\n self.scoring = scoring\\\\\n \\\\n self.iteration = n_iter\\\\\n \\\\n self.cv = cv\\\\\n \\\\n self.best_estimator_ = None\\\\\n \\\\n self.best_score_ = None\\\\\n \\\\n self.best_params_ = None\\\\\n \\\\n\\\\\n \\\\n def __min_fun(self, params):\\\\\n \\\\n score=cross_val_score(self.estimator, self.X, self.y,scoring=self.scoring,cv=self.cv)\\\\\n \\\\n acc = score.mean()\\\\\n \\\\n return {'loss':-acc,'score': acc, 'status': STATUS_OK,'model' :self.estimator,'params': params}\\\\\n \\\\n\\\\\n \\\\n def fit(self, X, y):\\\\\n \\\\n trials = Trials()\\\\\n \\\\n self.X = X\\\\\n \\\\n self.y = y\\\\\n \\\\n best = fmin(self.__min_fun,self.params,algo=tpe.suggest, max_evals=self.iteration, trials=trials)\\\\\n \\\\n result = sorted(trials.results, key = lambda x: x['loss'])[0]\\\\\n \\\\n self.best_estimator_ = result['model']\\\\\n \\\\n self.best_score_ = result['score']\\\\\n \\\\n self.best_params_ = result['params']\\\\\n \\\\n self.best_estimator_.fit(X, y)\\\\\n \\\\n\\\\\n \\\\n def hyperOptParamConversion( paramSpace):\\\\\n \\\\n paramDict = {}\\\\\n \\\\n for j in list(paramSpace.keys()):\\\\\n \\\\n inp = paramSpace[j]\\\\\n \\\\n isLog = False\\\\\n \\\\n isLin = False\\\\\n \\\\n isRan = False\\\\\n \\\\n isList = False\\\\\n \\\\n isString = False\\\\\n \\\\n try:\\\\\n \\\\n # check if functions are given as input and reassign paramspace\\\\\n \\\\n v = paramSpace[j]\\\\\n \\\\n if 'logspace' in paramSpace[j]:\\\\\n \\\\n paramSpace[j] = v[v.find('(') + 1:v.find(')')].replace(' ', '')\\\\\n \\\\n isLog = True\\\\\n \\\\n elif 'linspace' in paramSpace[j]:\\\\\n \\\\n paramSpace[j] = v[v.find('(') + 1:v.find(')')].replace(' ', '')\\\\\n \\\\n isLin = True\\\\\n \\\\n elif 'range' in paramSpace[j]:\\\\\n \\\\n paramSpace[j] = v[v.find('(') + 1:v.find(')')].replace(' ', '')\\\\\n \\\\n isRan = True\\\\\n \\\\n elif 'list' in paramSpace[j]:\\\\\n \\\\n paramSpace[j] = v[v.find('(') + 1:v.find(')')].replace(' ', '')\\\\\n \\\\n isList = True\\\\\n \\\\n elif '[' and ']' in paramSpace[j]:\\\\\n \\\\n paramSpace[j] = v.split('[')[1].split(']')[0].replace(' ', '')\\\\\n \\\\n isList = True\\\\\n \\\\n x = paramSpace[j].split(',')\\\\\n \\\\n except:\\\\\n \\\\n x = paramSpace[j]\\\\\n \\\\n str_arg = paramSpace[j]\\\\\n \\\\n\\\\\n \\\\n # check if arguments are string\\\\\n \\\\n try:\\\\\n \\\\n test = eval(x[0])\\\\\n \\\\n except:\\\\\n \\\\n isString = True\\\\\n \\\\n\\\\\n \\\\n if isString:\\\\\n \\\\n paramDict.update({j: hp.choice(j, x)})\\\\\n \\\\n else:\\\\\n \\\\n res = eval(str_arg)\\\\\n \\\\n if isLin:\\\\\n \\\\n y = eval('np.linspace' + str(res))\\\\\n \\\\n paramDict.update({j: hp.uniform(j, eval(x[0]), eval(x[1]))})\\\\\n \\\\n elif isLog:\\\\\n \\\\n y = eval('np.logspace' + str(res))\\\\\n \\\\n paramDict.update(\\\\\n \\\\n {j: hp.uniform(j, 10 ** eval(x[0]), 10 ** eval(x[1]))})\\\\\n \\\\n elif isRan:\\\\\n \\\\n y = eval('np.arange' + str(res))\\\\\n \\\\n paramDict.update({j: hp.choice(j, y)})\\\\\n \\\\n # check datatype of argument\\\\\n \\\\n elif isinstance(eval(x[0]), bool):\\\\\n \\\\n y = list(map(lambda i: eval(i), x))\\\\\n \\\\n paramDict.update({j: hp.choice(j, eval(str(y)))})\\\\\n \\\\n elif isinstance(eval(x[0]), float):\\\\\n \\\\n res = eval(str_arg)\\\\\n \\\\n if len(str_arg.split(',')) == 3 and not isList:\\\\\n \\\\n y = eval('np.linspace' + str(res))\\\\\n \\\\n #print(y)\\\\\n \\\\n paramDict.update({j: hp.uniform(j, eval(x[0]), eval(x[1]))})\\\\\n \\\\n else:\\\\\n \\\\n y = list(res) if isinstance(res, tuple) else [res]\\\\\n \\\\n paramDict.update({j: hp.choice(j, y)})\\\\\n \\\\n else:\\\\\n \\\\n res = eval(str_arg)\\\\\n \\\\n if len(str_arg.split(',')) == 3 and not isList:\\\\\n \\\\n y = eval('np.linspace' +str(res)) if eval(x[2]) >= eval(x[1]) else eval('np.arange'+str(res))\\\\\n \\\\n else:\\\\\n \\\\n y = list(res) if isinstance(res, tuple) else [res]\\\\\n \\\\n paramDict.update({j: hp.choice(j, y)})\\\\\n \\\\n return paramDict\"},\n 's2n':{'name':'s2n','imports':[{'mod':'word2number','mod_as':'w2n'},{'mod':'numpy','mod_as':'np'}],'code':\"\\\\n\\\\\n \\\\ndef s2n(value):\\\\\n \\\\n try:\\\\\n \\\\n x=eval(value)\\\\\n \\\\n return x\\\\\n \\\\n except:\\\\\n \\\\n try:\\\\\n \\\\n return w2n.word_to_num(value)\\\\\n \\\\n except:\\\\\n \\\\n return np.nan\"},\n 'readWrite':{'name':'readWrite','imports':[{'mod':'json'},{'mod':'pandas','mod_as':'pd'}],'code':\"\\\\n\\\\", "instruction": "", "output": "" }, { "input": "\n \\\\ndef read_json(file_path):\\\\\n \\\\n data = None\\\\\n \\\\n with open(file_path,'r') as f:\\\\\n \\\\n data = json.load(f)\\\\\n \\\\n return data\\\\\n \\\\n\\\\\n \\\\ndef write_json(data, file_path):\\\\\n \\\\n with open(file_path,'w') as f:\\\\\n \\\\n json.dump(data, f)\\\\\n \\\\n\\\\\n \\\\ndef read_data(file_path, encoding='utf-8', sep=','):\\\\\n \\\\n return pd.read_csv(file_path, encoding=encoding, sep=sep)\\\\\n \\\\n\\\\\n \\\\ndef write_data(data, file_path, index=False):\\\\\n \\\\n return data.to_csv(file_path, index=index)\\\\\n \\\\n\\\\\n \\\\n#Uncomment and change below code for google storage\\\\\n \\\\n#def write_data(data, file_path, index=False):\\\\\n \\\\n# file_name= file_path.name\\\\\n \\\\n# data.to_csv('output_data.csv')\\\\\n \\\\n# storage_client = storage.Client()\\\\\n \\\\n# bucket = storage_client.bucket('aion_data')\\\\\n \\\\n# bucket.blob('prediction/'+file_name).upload_from_filename('output_data.csv', content_type='text/csv')\\\\\n \\\\n# return data\\\\\n \\\\n\\\\\n \\\\ndef is_file_name_url(file_name):\\\\\n \\\\n supported_urls_starts_with = ('gs://','https://','http://')\\\\\n \\\\n return file_name.startswith(supported_urls_starts_with)\\\\\n \\\\n\"},\n 'logger':{'name':'set_logger','imports':[{'mod':'logging'}],'code':f\"\\\\n\\\\\n \\\\nlog = None\\\\\n \\\\ndef set_logger(log_file, mode='a'):\\\\\n \\\\n global log\\\\\n \\\\n logging.basicConfig(filename=log_file, filemode=mode, format='%(asctime)s %(name)s- %(message)s', level=logging.INFO, datefmt='%d-%b-%y %H:%M:%S')\\\\\n \\\\n log = logging.getLogger(Path(__file__).parent.name)\\\\\n \\\\n return log\\\\\n \\\\n\\\\\n \\\\ndef get_logger():\\\\\n \\\\n return log\\\\n\"},\n 'mlflowSetPath':{'name':'mlflowSetPath','code':f\"\\\\n\\\\ndef mlflowSetPath(path, name):\\\\\n \\\\n{self.tab}db_name = str(Path(path)/'mlruns')\\\\\n \\\\n{self.tab}mlflow.set_tracking_uri('file:///' + db_name)\\\\\n \\\\n{self.tab}mlflow.set_experiment(str(Path(path).name))\\\\\n \\\\n\"},\n 'mlflow_create_experiment':{'name':'mlflow_create_experiment','code':f\"\\\\n\\\\ndef mlflow_create_experiment(config, path, name):\\\\\n \\\\n{self.tab}tracking_uri, artifact_uri, registry_uri = get_mlflow_uris(config, path)\\\\\n \\\\n{self.tab}mlflow.tracking.set_tracking_uri(tracking_uri)\\\\\n \\\\n{self.tab}mlflow.tracking.set_registry_uri(registry_uri)\\\\\n \\\\n{self.tab}client = mlflow.tracking.MlflowClient()\\\\\n \\\\n{self.tab}experiment = client.get_experiment_by_name(name)\\\\\n \\\\n{self.tab}if experiment:\\\\\n \\\\n{self.tab}{self.tab}experiment_id = experiment.experiment_id\\\\\n \\\\n{self.tab}else:\\\\\n \\\\n{self.tab}{self.tab}experiment_id = client.create_experiment(name, artifact_uri)\\\\\n \\\\n{self.tab}return client, experiment_id\\\\\n \\\\n\"},\n 'get_mlflow_uris':{'name':'get_mlflow_uris','code':f\"\\\\n\\\\ndef get_mlflow_uris(config, path):\\\\\n \\\\n artifact_uri = None\\\\\n \\\\n tracking_uri_type = config.get('tracking_uri_type',None)\\\\\n \\\\n if tracking_uri_type == 'localDB':\\\\\n \\\\n tracking_uri = 'sqlite:///' + str(path.resolve()/'mlruns.db')\\\\\n \\\\n elif tracking_uri_type == 'server' and config.get('tracking_uri', None):\\\\\n \\\\n tracking_uri = config['tracking_uri']\\\\\n \\\\n if config.get('artifacts_uri', None):\\\\\n \\\\n if Path(config['artifacts_uri']).exists():\\\\\n \\\\n artifact_uri = 'file:' + config['artifacts_uri']\\\\\n \\\\n else:\\\\\n \\\\n artifact_uri = config['artifacts_uri']\\\\\n \\\\n else:\\\\\n \\\\n artifact_uri = 'file:' + str(path.resolve()/'mlruns')\\\\\n \\\\n else:\\\\\n \\\\n tracking_uri = 'file:' + str(path.resolve()/'mlruns')\\\\\n \\\\n artifact_uri = None\\\\\n \\\\n if config.get('registry_uri', None):\\\\\n \\\\n registry_uri = config['registry_uri']\\\\\n \\\\n else:\\\\\n \\\\n registry_uri = 'sqlite:///' + str(path.resolve()/'registry.db')\\\\\n \\\\n return tracking_uri, artifact_uri, registry_uri\\\\\n \\\\n\"},\n 'logMlflow':{'name':'logMlflow','code':f\"\\\\n\\\\ndef logMlflow( params, metrices, estimator,tags={{}}, algoName=None):\\\\\n \\\\n{self.tab}run_id = None\\\\\n \\\\n{self.tab}for k,v in params.items():\\\\\n \\\\n{self.tab}{self.tab}mlflow.log_param(k, v)\\\\\n \\\\n{self.tab}for k,v in metrices.items():\\\\\n \\\\n{self.tab}{self.tab}mlflow.log_metric(k, v)\\\\\n \\\\n{self.tab}if 'CatBoost' in algoName:\\\\\n \\\\n{self.tab}{self.tab}model_info = mlflow.catboost.log_model(estimator, 'model')\\\\\n \\\\n{self.tab}else:\\\\\n \\\\n{self.tab}{self.tab}model_info = mlflow.sklearn.log_model(sk_model=estimator, artifact_path='model')\\\\\n \\\\n{self.tab}tags['processed'] = 'no'\\\\\n \\\\n{self.tab}tags['registered'] = 'no'\\\\\n \\\\n{self.tab}mlflow.set_tags(tags)\\\\\n \\\\n{self.tab}if model_info:\\\\\n \\\\n{self.tab}{self.tab}run_id = model_info.run_id\\\\\n \\\\n{self.tab}return run_id\\\\\n \\\\n\"},\n 'classification_metrices':{'name':'classification_metrices','imports':[{'mod':'sklearn'},{'mod':'math'}],'code':\"\\\\ndef get_classification_metrices( actual_values, predicted_values):\\\\\n \\\\n result = {}\\\\\n \\\\n accuracy_score = sklearn.metrics.accuracy_score(actual_values, predicted_values)\\\\\n \\\\n avg_precision = sklearn.metrics.precision_score(actual_values, predicted_values,\\\\\n \\\\n average='macro')\\\\\n \\\\n avg_recall = sklearn.metrics.recall_score(actual_values, predicted_values,\\\\\n \\\\n average='macro')\\\\\n \\\\n avg_f1 = sklearn.metrics.f1_score(actual_values, predicted_values,\\\\\n \\\\n average='macro')\\\\\n \\\\n\\\\\n \\\\n result['accuracy'] = math.floor(accuracy_score*10000)/100\\\\\n \\\\n result['precision'] = math.floor(avg_precision*10000)/100\\\\\n \\\\n result['recall'] = math.floor(avg_recall*10000)/100\\\\\n \\\\n result['f1'] = math.floor(avg_f1*10000)/100\\\\\n \\\\n return result\\\\\n \\\\n\"},\n 'regression_metrices':{'name':'regression_metrices','imports':[{'mod':'numpy', 'mod_as':'np'}],'code':\"\\\\ndef get_regression_metrices( actual_values, predicted_values):\\\\\n \\\\n result = {}\\\\\n \\\\n\\\\\n \\\\n me = np.mean(predicted_values - actual_values)\\\\\n \\\\n sde = np.std(predicted_values - actual_values, ddof = 1)\\\\\n \\\\n\\\\\n \\\\n abs_err = np.abs(predicted_values - actual_values)\\\\\n \\\\n mae = np.mean(abs_err)\\\\\n \\\\n sdae = np.std(abs_err, ddof = 1)\\\\\n \\\\n\\\\\n \\\\n abs_perc_err = 100.*np.abs(predicted_values - actual_values) / actual_values\\\\\n \\\\n mape = np.mean(abs_perc_err)\\\\\n \\\\n sdape = np.std(abs_perc_err, ddof = 1)\\\\\n \\\\n\\\\\n \\\\n result['mean_error'] = me\\\\\n \\\\n result['mean_abs_error'] = mae\\\\\n \\\\n result['mean_abs_perc_error'] = mape\\\\\n \\\\n result['error_std'] = sde\\\\\n \\\\n result['abs_error_std'] = sdae\\\\\n \\\\n result['abs_perc_error_std'] = sdape\\\\\n \\\\n return result\\\\\n \\\\n\"}\n }\n \n def add_function(self, name, importer=None):\n if name in self.available_functions.keys():\n self.codeText += self.available_functions[name]['code']\n if importer:\n if 'imports' in self.available_functions[name].keys():\n for module in self.available_functions[name]['imports']:\n mod_name = module['mod']\n mod_from = module.get('mod_from', None)\n mod_as = module.get('mod_as', None)\n importer.addModule(mod_name, mod_from=mod_from, mod_as=mod_as)\n \n def get_function_name(self, name):\n if name in self.available_functions.keys():\n return self.available_functions[name]['name']\n return None\n \n def getCode(self):\n return self.codeText\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\nfrom .imports import importModule\n\nutility_functions = {\n'load_data': ['read_json','write_json','read_data','write_data','is_file_name_url','logger_class'],\n'transformer': ['read_json','write_json','read_data','write_data','is_file_name_url','logger_class'],\n'selector': ['read_json','write_json','read_data','write_data','is_file_name_url','logger_class'],\n'train': ['read_json','write_json','read_data','write_data','is_file_name_url','logger_class'],\n'register': ['read_json','write_json','read_data','write_data','is_file_name_url','logger_class'],\n'Prediction': ['read_json','write_json','read_data','write_data','is_file_name_url','logger_class'],\n'drift': ['read_json','write_json','read_data','write_data','is_file_name_url','logger_class'],\n}\n\n#TODO convert read and write functions in to class functions\nfunctions_code = {\n 'read_json':{'imports':[{'mod':'json'}],'code':\"\\\\n\\\\\n \\\\ndef read_json(file_path):\\\\\n \\\\n data = None\\\\\n \\\\n with open(file_path,'r') as f:\\\\\n \\\\n data = json.load(f)\\\\\n \\\\n return data\\\\\n \\\\n\"},\n 'write_json':{'imports':[{'mod':'json'}],'code':\"\\\\n\\\\\n \\\\ndef write_json(data, file_path):\\\\\n \\\\n with open(file_path,'w') as f:\\\\\n \\\\n json.dump(data, f)\\\\\n \\\\n\"},\n 'read_data':{'imports':[{'mod':'pandas','mod_as':'pd'}],'code':\"\\\\n\\\\\n \\\\ndef read_data(file_path, encoding='utf-8', sep=','):\\\\\n \\\\n return pd.read_csv(file_path, encoding=encoding, sep=sep)\\\\\n \\\\n\"},\n 'write_data':{'imports':[{'mod':'pandas','mod_as':'pd'}],'code':\"\\\\n\\\\\n \\\\ndef write_data(data, file_path, index=False):\\\\\n \\\\n return data.to_csv(file_path, index=index)\\\\\n \\\\n\\\\\n \\\\n#Uncomment and change below code for google storage\\\\\n \\\\n#from google.cloud import storage\\\\\n \\\\n#def write_data(data, file_path, index=False):\\\\\n \\\\n# file_name= file_path.name\\\\\n \\\\n# data.to_csv('output_data.csv')\\\\\n \\\\n# storage_client = storage.Client()\\\\\n \\\\n# bucket = storage_client.bucket('aion_data')\\\\\n \\\\n# bucket.blob('prediction/'+file_name).upload_from_filename('output_data.csv', content_type='text/csv')\\\\\n \\\\n# return data\\\\\n \\\\n\"},\n 'is_file_name_url':{'imports':[],'code':\"\\\\n\\\\\n \\\\ndef is_file_name_url(file_name):\\\\\n \\\\n supported_urls_starts_with = ('gs://','https://','http://')\\\\\n \\\\n return file_name.startswith(supported_urls_starts_with)\\\\\n \\\\n\"},\n 'logger_class':{'imports':[{'mod':'logging'}, {'mod':'io'}],'code':\"\\\\n\\\\\n \\\\nclass logger():\\\\\n \\\\n #setup the logger\\\\\n \\\\n def __init__(self, log_file, mode='w', logger_name=None):\\\\\n \\\\n logging.basicConfig(filename=log_file, filemode=mode, format='%(asctime)s %(name)s- %(message)s', level=logging.INFO, datefmt='%d-%b-%y %H:%M:%S')\\\\\n \\\\n self.log = logging.getLogger(logger_name)\\\\\n \\\\n\\\\\n \\\\n #get logger\\\\\n \\\\n def getLogger(self):\\\\\n \\\\n return self.log\\\\\n \\\\n", "instruction": "", "output": "" }, { "input": "\\\\\n \\\\n def info(self, msg):\\\\\n \\\\n self.log.info(msg)\\\\\n \\\\n\\\\\n \\\\n def error(self, msg, exc_info=False):\\\\\n \\\\n self.log.error(msg,exc_info)\\\\\n \\\\n\\\\\n \\\\n # format and log dataframe\\\\\n \\\\n def log_dataframe(self, df, rows=2, msg=None):\\\\\n \\\\n buffer = io.StringIO()\\\\\n \\\\n df.info(buf=buffer)\\\\\n \\\\n log_text = 'Data frame{}'.format(' after ' + msg + ':' if msg else ':')\\\\\n \\\\n log_text += '\\\\\\\\n\\\\\\\\t'+str(df.head(rows)).replace('\\\\\\\\n','\\\\\\\\n\\\\\\\\t')\\\\\n \\\\n log_text += ('\\\\\\\\n\\\\\\\\t' + buffer.getvalue().replace('\\\\\\\\n','\\\\\\\\n\\\\\\\\t'))\\\\\n \\\\n self.log.info(log_text)\\\\\n \\\\n\"},\n}\n \nclass utility_function():\n\n def __init__(self, module):\n if module in utility_functions.keys():\n self.module_name = module\n else:\n self.module_name = None\n self.importer = importModule()\n self.codeText = \"\"\n \n def get_code(self):\n code = \"\"\n if self.module_name:\n functions = utility_functions[self.module_name]\n for function in functions:\n self.codeText += self.get_function_code(function)\n code = self.importer.getCode()\n code += self.codeText\n return code\n \n def get_function_code(self, name):\n code = \"\"\n if name in functions_code.keys():\n code += functions_code[name]['code']\n if self.importer:\n if 'imports' in functions_code[name].keys():\n for module in functions_code[name]['imports']:\n mod_name = module['mod']\n mod_from = module.get('mod_from', None)\n mod_as = module.get('mod_as', None)\n self.importer.addModule(mod_name, mod_from=mod_from, mod_as=mod_as)\n return code\n\n def get_importer(self):\n return self.importer\n\nif __name__ == '__main__':\n obj = utility_function('load_data')\n p = obj.get_utility_code()\n print(p) \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nclass output_drift():\n\n def __init__(self, missing=False, word2num_features = None, cat_encoder=False, target_encoder=False, normalizer=False, text_profiler=False, feature_reducer=False, score_smaller_is_better=True, problem_type='classification', tab_size=4):\n self.tab = ' ' * tab_size\n self.codeText = ''\n self.missing = missing\n self.word2num_features = word2num_features\n self.cat_encoder = cat_encoder\n self.target_encoder = target_encoder\n self.normalizer = normalizer\n self.text_profiler = text_profiler\n self.feature_reducer = feature_reducer\n self.score_smaller_is_better = score_smaller_is_better\n self.problem_type = problem_type\n \n def addDatabaseClass(self, indent=0):\n text = \"\\\\\n \\\\nclass database():\\\\\n \\\\n def __init__(self, config):\\\\\n \\\\n self.host = config['host']\\\\\n \\\\n self.port = config['port']\\\\\n \\\\n self.user = config['user']\\\\\n \\\\n self.password = config['password']\\\\\n \\\\n self.database = config['database']\\\\\n \\\\n self.measurement = config['measurement']\\\\\n \\\\n self.tags = config['tags']\\\\\n \\\\n self.client = self.get_client()\\\\\n \\\\n\\\\\n \\\\n def read_data(self, query)->pd.DataFrame:\\\\\n \\\\n cursor = self.client.query(query)\\\\\n \\\\n points = cursor.get_points()\\\\\n \\\\n my_list=list(points)\\\\\n \\\\n df=pd.DataFrame(my_list)\\\\\n \\\\n return df\\\\\n \\\\n\\\\\n \\\\n def get_client(self):\\\\\n \\\\n client = InfluxDBClient(self.host,self.port,self.user,self.password)\\\\\n \\\\n databases = client.get_list_database()\\\\\n \\\\n databases = [x['name'] for x in databases]\\\\\n \\\\n if self.database not in databases:\\\\\n \\\\n client.create_database(self.database)\\\\\n \\\\n return InfluxDBClient(self.host,self.port,self.user,self.password, self.database)\\\\\n \\\\n\\\\\n \\\\n def write_data(self,data):\\\\\n \\\\n if isinstance(data, pd.DataFrame):\\\\\n \\\\n sorted_col = data.columns.tolist()\\\\\n \\\\n sorted_col.sort()\\\\\n \\\\n data = data[sorted_col]\\\\\n \\\\n data = data.to_dict(orient='records')\\\\\n \\\\n for row in data:\\\\\n \\\\n if 'time' in row.keys():\\\\\n \\\\n p = '%Y-%m-%dT%H:%M:%S.%fZ'\\\\\n \\\\n time_str = datetime.strptime(row['time'], p)\\\\\n \\\\n del row['time']\\\\\n \\\\n else:\\\\\n \\\\n time_str = None\\\\\n \\\\n if 'model_ver' in row.keys():\\\\\n \\\\n self.tags['model_ver']= row['model_ver']\\\\\n \\\\n del row['model_ver']\\\\\n \\\\n json_body = [{\\\\\n \\\\n 'measurement': self.measurement,\\\\\n \\\\n 'time': time_str,\\\\\n \\\\n 'tags': self.tags,\\\\\n \\\\n 'fields': row\\\\\n \\\\n }]\\\\\n \\\\n self.client.write_points(json_body)\\\\\n \\\\n\\\\\n \\\\n def close(self):\\\\\n \\\\n self.client.close()\\\\\n \\\\n\"\n if indent:\n text = text.replace('\\\\n', (self.tab * indent) + '\\\\n')\n return text\n\n def addPredictClass(self, indent=0):\n text = \"\\\\\n \\\\nclass predict():\\\\\n \\\\n\\\\\n \\\\n def __init__(self, base_config):\\\\\n \\\\n self.usecase = base_config['modelName'] + '_' + base_config['modelVersion']\\\\\n \\\\n self.dataLocation = base_config['dataLocation']\\\\\n \\\\n self.db_enabled = base_config.get('db_enabled', False)\\\\\n \\\\n if self.db_enabled:\\\\\n \\\\n self.db_config = base_config['db_config']\\\\\n \\\\n home = Path.home()\\\\\n \\\\n if platform.system() == 'Windows':\\\\\n \\\\n from pathlib import WindowsPath\\\\\n \\\\n output_data_dir = WindowsPath(home)/'AppData'/'Local'/'HCLT'/'AION'/'Data'\\\\\n \\\\n output_model_dir = WindowsPath(home)/'AppData'/'Local'/'HCLT'/'AION'/'target'/self.usecase\\\\\n \\\\n else:\\\\\n \\\\n from pathlib import PosixPath\\\\\n \\\\n output_data_dir = PosixPath(home)/'HCLT'/'AION'/'Data'\\\\\n \\\\n output_model_dir = PosixPath(home)/'HCLT'/'AION'/'target'/self.usecase\\\\\n \\\\n if not output_model_dir.exists():\\\\\n \\\\n raise ValueError(f'Configuration file not found at {output_model_dir}')\\\\\n \\\\n\\\\\n \\\\n tracking_uri = 'file:///' + str(Path(output_model_dir)/'mlruns')\\\\\n \\\\n registry_uri = 'sqlite:///' + str(Path(output_model_dir)/'mlruns.db')\\\\\n \\\\n mlflow.set_tracking_uri(tracking_uri)\\\\\n \\\\n mlflow.set_registry_uri(registry_uri)\\\\\n \\\\n client = mlflow.tracking.MlflowClient(\\\\\n \\\\n tracking_uri=tracking_uri,\\\\\n \\\\n registry_uri=registry_uri,\\\\\n \\\\n )\\\\\n \\\\n self.model_version = client.get_latest_versions(self.usecase, stages=['production'] )[0].version\\\\\n \\\\n model_version_uri = 'models:/{model_name}/production'.format(model_name=self.usecase)\\\\\n \\\\n self.model = mlflow.pyfunc.load_model(model_version_uri)\\\\\n \\\\n run = client.get_run(self.model.metadata.run_id)\\\\\n \\\\n if run.info.artifact_uri.startswith('file:'): #remove file:///\\\\\n \\\\n self.artifact_path = Path(run.info.artifact_uri[len('file:///') : ])\\\\\n \\\\n else:\\\\\n \\\\n self.artifact_path = Path(run.info.artifact_uri)\\\\\n \\\\n with open(self.artifact_path/'deploy.json', 'r') as f:\\\\\n \\\\n deployment_dict = json.load(f)\\\\\n \\\\n with open(self.artifact_path/'features.txt', 'r') as f:\\\\\n \\\\n self.train_features = f.readline().rstrip().split(',')\\\\\n \\\\n\\\\\n \\\\n self.dataLocation = base_config['dataLocation']\\\\\n \\\\n self.selected_features = deployment_dict['load_data']['selected_features']\\\\\n \\\\n self.target_feature = deployment_dict['load_data']['target_feature']\\\\\n \\\\n self.output_model_dir = output_model_dir\"\n if self.missing:\n text += \"\\\\n self.missing_values = deployment_dict['transformation']['fillna']\"\n if self.word2num_features:\n text += \"\\\\n self.word2num_features = deployment_dict['transformation']['word2num_features']\"\n if self.cat_encoder == 'labelencoding':\n text += \"\\\\n self.cat_encoder = deployment_dict['transformation']['cat_encoder']\"\n elif (self.cat_encoder == 'targetencoding') or (self.cat_encoder == 'onehotencoding'):\n text += \"\\\\n self.cat_encoder = deployment_dict['transformation']['cat_encoder']['file']\"\n text += \"\\\\n self.cat_encoder_cols = deployment_dict['transformation']['cat_encoder']['features']\"\n if self.target_encoder:\n text += \"\\\\n self.target_encoder = joblib.load(self.artifact_path/deployment_dict['transformation']['target_encoder'])\"\n if self.normalizer:\n text += \"\\\\n self.normalizer = joblib.load(self.artifact_path/deployment_dict['transformation']['normalizer']['file'])\\\\\n\\\\n self.normalizer_col = deployment_dict['transformation']['normalizer']['features']\"\n if self.text_profiler:\n text += \"\\\\n self.text_profiler = joblib.load(self.artifact_path/deployment_dict['transformation']['Status']['text_profiler']['file'])\\\\\n\\\\n self.text_profiler_col = deployment_dict['transformation']['Status']['text_profiler']['features']\"\n if self.feature_reducer:\n text += \"\\\\n self.feature_reducer = joblib.load(self.artifact_path/deployment_dict['featureengineering']['feature_reducer']['file'])\\\\\n\\\\n self.feature_reducer_cols = deployment_dict['featureengineering']['feature_reducer']['features']\"\n text += \"\"\"\n \n def read_data_from_db(self):\n if self.db_enabled:\n try:\n db = database(self.db_config)\n query = \"SELECT * FROM {} WHERE model_ver = '{}' AND {} != ''\".format(db.measurement, self.model_version, self.target_feature)\n if 'read_time' in self.db_config.keys() and self.db_config['read_time']:\n query += f\" time > now() - {self.db_config['read_time']}\"\n data = db.read_data(query)\n except:\n raise ValueError('Unable to read from the database')\n finally:\n if db:\n db.close()\n return data\n return None\"\"\"\n text += \"\\\\\n \\\\n def predict(self, data):\\\\\n \\\\n df = pd.DataFrame()\\\\\n \\\\n if Path(data).exists():\\\\\n \\\\n if Path(data).suffix == '.tsv':\\\\\n \\\\n df=read_data(data,encoding='utf-8',sep='\\\\t')\\\\\n \\\\n elif Path(data).suffix == '.csv':\\\\\n \\\\n df=read_data(data,encoding='utf-8')\\\\\n \\\\n else:\\\\\n \\\\n if Path(data).suffix == '.json':\\\\\n \\\\n jsonData = read_json(data)\\\\\n \\\\n df = pd.json_normalize(jsonData)\\\\\n \\\\n elif is_file_name_url(data):\\\\\n \\\\n df = read_data(data,encoding='utf-8')\\\\\n \\\\n else:\\\\\n \\\\n jsonData = json.loads(data)\\\\\n \\\\n df = pd.json_normalize(jsonData)\\\\\n \\\\n if len(df) == 0:\\\\\n \\\\n raise ValueError('No data record found')\\\\\n \\\\n missing_features = [x for x in self.selected_features if x not in df.columns]\\\\\n \\\\n if missing_features:\\\\\n \\\\n raise ValueError(f'some feature/s is/are missing: {missing_features}')\\\\\n \\\\n if self.target_feature not in df.columns:\\\\\n \\\\n raise ValueError(f'Ground truth values/target column({self.target_feature}) not found in current data')\\\\\n \\\\n df_copy = df.copy()\\\\\n \\\\n df = df[self.selected_features]\"\n if self.word2num_features:\n text += \"\\\\n for feat in self.word2num_features:\"\n text += \"\\\\n df[ feat ] = df[feat].apply(lambda x: s2n(x))\"\n if self.missing:\n text += \"\\\\n df.fillna(self.missing_values, inplace=True)\"\n if self.cat_encoder == 'labelencoding':\n text += \"\\\\n df.replace(self.cat_encoder, inplace=True)\"\n elif self.cat_encoder == 'targetencoding':\n text += \"\\\\n cat_enc = joblib.load(self.artifact_path/self.cat_encoder)\"\n text += \"\\\\n df = cat_enc.transform(df)\"\n elif self.cat_encoder == 'onehotencoding':\n text += \"\\\\n cat_enc = joblib.load(self.artifact_path/self.cat_encoder)\"\n text += \"\\\\n transformed_data = cat_enc.transform(df[self.cat_encoder_cols]).toarray()\"\n text += \"\\\\n df[cat_enc.get_feature_names()] = pd.DataFrame(transformed_data, columns=cat_enc", "instruction": "", "output": "" }, { "input": ".get_feature_names())[cat_enc.get_feature_names()]\"\n if self.normalizer:\n text += \"\\\\n df[self.normalizer_col] = self.normalizer.transform(df[self.normalizer_col])\"\n if self.text_profiler:\n text += \"\\\\n text_corpus = df[self.text_profiler_col].apply(lambda row: ' '.join(row.values.astype(str)), axis=1)\\\\\n\\\\n df_vect=self.text_profiler.transform(text_corpus)\\\\\n\\\\n if isinstance(df_vect, np.ndarray):\\\\\n\\\\n df1 = pd.DataFrame(df_vect)\\\\\n\\\\n else:\\\\\n\\\\n df1 = pd.DataFrame(df_vect.toarray(),columns = self.text_profiler.named_steps['vectorizer'].get_feature_names())\\\\\n\\\\n df1 = df1.add_suffix('_vect')\\\\\n\\\\n df = pd.concat([df, df1],axis=1)\"\n if self.feature_reducer:\n text += \"\\\\n df = self.feature_reducer.transform(df[self.feature_reducer_cols])\"\n else:\n text += \"\\\\n df = df[self.train_features]\"\n if self.target_encoder:\n text += \"\\\\n output = pd.DataFrame(self.model._model_impl.predict_proba(df), columns=self.target_encoder.classes_)\\\\\n \\\\n df_copy['prediction'] = output.idxmax(axis=1)\"\n else:\n text += \"\\\\n output = self.model.predict(df).reshape(1, -1)[0].round(2)\\\\\n \\\\n df_copy['prediction'] = output\"\n text += \"\\\\n return df_copy\"\n if indent:\n text = text.replace('\\\\n', (self.tab * indent) + '\\\\n')\n return text\n\n def getClassificationMatrixCode(self, indent=0):\n text = \"\\\\\n \\\\ndef get_classification_metrices(actual_values, predicted_values):\\\\\n \\\\n result = {}\\\\\n \\\\n accuracy_score = sklearn.metrics.accuracy_score(actual_values, predicted_values)\\\\\n \\\\n avg_precision = sklearn.metrics.precision_score(actual_values, predicted_values,\\\\\n \\\\n average='macro')\\\\\n \\\\n avg_recall = sklearn.metrics.recall_score(actual_values, predicted_values,\\\\\n \\\\n average='macro')\\\\\n \\\\n avg_f1 = sklearn.metrics.f1_score(actual_values, predicted_values,\\\\\n \\\\n average='macro')\\\\\n \\\\n\\\\\n \\\\n result['accuracy'] = accuracy_score\\\\\n \\\\n result['precision'] = avg_precision\\\\\n \\\\n result['recall'] = avg_recall\\\\\n \\\\n result['f1'] = avg_f1\\\\\n \\\\n return result\\\\\n \\\\n\\\\\n \"\n if indent:\n text = text.replace('\\\\n', (self.tab * indent) + '\\\\n')\n return text\n\n def getRegrssionMatrixCode(self, indent=0):\n text = \"\\\\\n \\\\ndef get_regression_metrices( actual_values, predicted_values):\\\\\n \\\\n result = {}\\\\\n \\\\n\\\\\n \\\\n me = np.mean(predicted_values - actual_values)\\\\\n \\\\n sde = np.std(predicted_values - actual_values, ddof = 1)\\\\\n \\\\n\\\\\n \\\\n abs_err = np.abs(predicted_values - actual_values)\\\\\n \\\\n mae = np.mean(abs_err)\\\\\n \\\\n sdae = np.std(abs_err, ddof = 1)\\\\\n \\\\n\\\\\n \\\\n abs_perc_err = 100.*np.abs(predicted_values - actual_values) / actual_values\\\\\n \\\\n mape = np.mean(abs_perc_err)\\\\\n \\\\n sdape = np.std(abs_perc_err, ddof = 1)\\\\\n \\\\n\\\\\n \\\\n result['mean_error'] = me\\\\\n \\\\n result['mean_abs_error'] = mae\\\\\n \\\\n result['mean_abs_perc_error'] = mape\\\\\n \\\\n result['error_std'] = sde\\\\\n \\\\n result['abs_error_std'] = sdae\\\\\n \\\\n result['abs_perc_error_std'] = sdape\\\\\n \\\\n return result\\\\\n \\\\n\\\\\n \"\n if indent:\n text = text.replace('\\\\n', (self.tab * indent) + '\\\\n')\n return text\n \n def addSuffixCode(self, indent=1):\n text =\"\\\\n\\\\\n \\\\ndef check_drift( config):\\\\\n \\\\n prediction = predict(config)\\\\\n \\\\n usecase = config['modelName'] + '_' + config['modelVersion']\\\\\n \\\\n train_data_path = prediction.artifact_path/(usecase+'_data.csv')\\\\\n \\\\n if not train_data_path.exists():\\\\\n \\\\n raise ValueError(f'Training data not found at {train_data_path}')\\\\\n \\\\n curr_with_pred = prediction.read_data_from_db()\\\\\n \\\\n if prediction.target_feature not in curr_with_pred.columns:\\\\\n \\\\n raise ValueError('Ground truth not updated for corresponding data in database')\\\\\n \\\\n train_with_pred = prediction.predict(train_data_path)\\\\\n \\\\n performance = {}\"\n if self.problem_type == 'classification':\n text += \"\\\\n\\\\\n \\\\n performance['train'] = get_classification_metrices(train_with_pred[prediction.target_feature], train_with_pred['prediction'])\\\\\n \\\\n performance['current'] = get_classification_metrices(curr_with_pred[prediction.target_feature], curr_with_pred['prediction'])\"\n else:\n text += \"\\\\n\\\\\n \\\\n performance['train'] = get_regression_metrices(train_with_pred[prediction.target_feature], train_with_pred['prediction'])\\\\\n \\\\n performance['current'] = get_regression_metrices(curr_with_pred[prediction.target_feature], curr_with_pred['prediction'])\"\n text += \"\\\\n return performance\"\n text += \"\\\\n\\\\\n \\\\nif __name__ == '__main__':\\\\\n \\\\n try:\\\\\n \\\\n if len(sys.argv) < 2:\\\\\n \\\\n raise ValueError('config file not present')\\\\\n \\\\n config = sys.argv[1]\\\\\n \\\\n if Path(config).is_file() and Path(config).suffix == '.json':\\\\\n \\\\n with open(config, 'r') as f:\\\\\n \\\\n config = json.load(f)\\\\\n \\\\n else:\\\\\n \\\\n config = json.loads(config)\\\\\n \\\\n output = check_drift(config)\\\\\n \\\\n status = {'Status':'Success','Message':json.loads(output)}\\\\\n \\\\n print('output_drift:'+json.dumps(status))\\\\\n \\\\n except Exception as e:\\\\\n \\\\n status = {'Status':'Failure','Message':str(e)}\\\\\n \\\\n print('output_drift:'+json.dumps(status))\"\n if indent:\n text = text.replace('\\\\n', (self.tab * indent) + '\\\\n')\n return text\n \n def addStatement(self, statement, indent=1):\n self.codeText += '\\\\n' + self.tab * indent + statement\n \n def generateCode(self):\n self.codeText += self.addDatabaseClass()\n self.codeText += self.addPredictClass()\n if self.problem_type == 'classification':\n self.codeText += self.getClassificationMatrixCode()\n elif self.problem_type == 'regression':\n self.codeText += self.getRegrssionMatrixCode()\n else:\n raise ValueError(f\"Unsupported problem type: {self.problem_type}\")\n self.codeText += self.addSuffixCode()\n \n def getCode(self):\n return self.codeText\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom .imports import importModule\n\nsupported_reader = ['sqlite', 'influx','s3']\n\n\n\nfunctions_code = {\n 'dataReader':{'imports':[{'mod':'json'},{'mod': 'Path', 'mod_from': 'pathlib', 'mod_as': None},{'mod': 'pandas', 'mod_from': None, 'mod_as': 'pd'}],'code':\"\"\"\n\nclass dataReader():\n \n def get_reader(self, reader_type, target_path=None, config=None):\n if reader_type == 'sqlite':\n return sqlite_writer(target_path=target_path)\n elif reader_type == 'influx':\n return Influx_writer(config=config)\n elif reader_type == 'gcs':\n return gcs(config=config)\n elif reader_type == 'azure':\n return azure(config=config)\n elif reader_type == 's3':\n return s3bucket(config=config)\n else:\n raise ValueError(reader_type)\n\"\"\"\n },\n 'sqlite':{'imports':[{'mod':'sqlite3'},{'mod': 'pandas', 'mod_from': None, 'mod_as': 'pd'},{'mod': 'Path', 'mod_from': 'pathlib', 'mod_as': None}],'code':\"\"\"\\\\n\\\\\nclass sqlite_writer():\n def __init__(self, target_path):\n self.target_path = Path(target_path)\n database_file = self.target_path.stem + '.db'\n self.db = sqlite_db(self.target_path, database_file)\n\n def file_exists(self, file):\n if file:\n return self.db.table_exists(file)\n else:\n return False\n\n def read(self, file):\n return self.db.read(file)\n \n def write(self, data, file):\n self.db.write(data, file)\n\n def close(self):\n self.db.close()\n\nclass sqlite_db():\n\n def __init__(self, location, database_file=None):\n if not isinstance(location, Path):\n location = Path(location)\n if database_file:\n self.database_name = database_file\n else:\n self.database_name = location.stem + '.db'\n db_file = str(location/self.database_name)\n self.conn = sqlite3.connect(db_file)\n self.cursor = self.conn.cursor()\n self.tables = []\n\n def table_exists(self, name):\n if name in self.tables:\n return True\n elif name:\n query = f\"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}';\"\n listOfTables = self.cursor.execute(query).fetchall()\n if len(listOfTables) > 0 :\n self.tables.append(name)\n return True\n return False\n\n def read(self, table_name):\n return pd.read_sql_query(f\"SELECT * FROM {table_name}\", self.conn)\n\n def create_table(self,name, columns, dtypes):\n query = f'CREATE TABLE IF NOT EXISTS {name} ('\n \n for column, data_type in zip(columns, dtypes):\n query += f\"'{column}' TEXT,\"\n query = query[:-1]\n query += ');'\n self.conn.execute(query)\n return True\n \n def write(self,data, table_name):\n if not self.table_exists(table_name):\n self.create_table(table_name, data.columns, data.dtypes)\n tuple_data = list(data.itertuples(index=False, name=None))\n insert_query = f'INSERT INTO {table_name} VALUES('\n for i in range(len(data.columns)):\n insert_query += '?,'\n insert_query = insert_query[:-1] + ')'\n self.cursor.executemany(insert_query, tuple_data)\n self.conn.commit()\n return True\n \n def delete(self, name):\n pass\n \n def close(self):\n self.conn.close()\n\n \"\"\"\n },\n 'influx':{'imports':[{'mod':'InfluxDBClient','mod_from':'influxdb'},{'mod': 'Path', 'mod_from': 'pathlib', 'mod_as': None},{'mod': 'pandas', 'mod_from': None, 'mod_as': 'pd'}],'code':\"\"\"\\\\n\\\\\nclass Influx_writer():\n\n def __init__(self, config):\n self.db = influx_db(config)\n\n def file_exists(self, file):\n if file:\n return self.db.table_exists(file)\n else:\n return False\n\n def read(self, file):\n query = \"SELECT * FROM {}\".format(file)\n if 'read_time' in self.db_config.keys() and self.db_config['read_time']:\n query += f\" time > now() - {self.db_config['read_time']}\"\n return self.db.read(query)\n\n def write(self, data, file):\n self.db.write(data, file)\n\n def close(self):\n pass\n\n\nclass influx_db():\n\n def __init__(self, config):\n self.host = config['host']\n self.port = config['port']\n self.user = config.get('user', None)\n self.password = config.get('password', None)\n self.token = config.get('token', None)\n self.database = config['database']\n self.measurement = config['measurement']\n self.tags = config['tags']\n self.client = self.get_client()\n\n def table_exists(self, name):\n query = f\"SHOW MEASUREMENTS ON {self.database}\"\n result = self.client(query)\n for measurement in result['measurements']:\n if measurement['name'] == name:\n return True\n return False\n \n def read(self, query)->pd.DataFrame:\n cursor = self.client.query(query)\n points = cursor.get_points()\n my_list=list(points)\n df=pd.DataFrame(my_list)\n return df\n\n def get_client(self):\n headers = None\n if self.token:\n headers={\"Authorization\": self.token} \n client = InfluxDBClient(self.host,self.port,self.user, self.password,headers=headers)\n databases = client.get_list_database()\n databases = [x['name'] for x in databases]\n if self.database not in databases:\n client.create_database(self.database)\n return InfluxDBClient(self.host,self.port,self.user,self.password,self.database,headers=headers)\n\n def write(self,data, measurement=None):\n if isinstance(data, pd.DataFrame):\n sorted_col = data.columns.tolist()\n sorted_col.sort()\n data = data[sorted_col]\n data = data.to_dict(orient='records')\n if not measurement:\n measurement = self.measurement\n for row in data:\n if 'time' in row.keys():\n p", "instruction": "", "output": "" }, { "input": "= '%Y-%m-%dT%H:%M:%S.%fZ'\n time_str = datetime.strptime(row['time'], p)\n del row['time']\n else:\n time_str = None\n if 'model_ver' in row.keys():\n self.tags['model_ver']= row[", "instruction": "", "output": "" }, { "input": "_data import tabularDataReader\nfrom mlac.timeseries.core.transformer import transformer as profiler\nfrom mlac.timeseries.core.selector import selector\nfrom mlac.timeseries.core.trainer import learner\nfrom mlac.timeseries.core.register import register\nfrom mlac.timeseries.core.deploy import deploy\nfrom mlac.timeseries.core.drift_analysis import drift\nfrom mlac.timeseries.core.functions import global_function\nfrom mlac.timeseries.core.data_reader import data_reader\nfrom mlac.timeseries.core.utility import utility_function\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nclass input_drift():\n\n def __init__(self, tab_size=4):\n self.tab = ' ' * tab_size\n self.codeText = ''\n \n def addInputDriftClass(self):\n text = \"\\\\\n \\\\nclass inputdrift():\\\\\n \\\\n\\\\\n \\\\n def __init__(self,base_config):\\\\\n \\\\n self.usecase = base_config['modelName'] + '_' + base_config['modelVersion']\\\\\n \\\\n self.currentDataLocation = base_config['currentDataLocation']\\\\\n \\\\n home = Path.home()\\\\\n \\\\n if platform.system() == 'Windows':\\\\\n \\\\n from pathlib import WindowsPath\\\\\n \\\\n output_data_dir = WindowsPath(home)/'AppData'/'Local'/'HCLT'/'AION'/'Data'\\\\\n \\\\n output_model_dir = WindowsPath(home)/'AppData'/'Local'/'HCLT'/'AION'/'target'/self.usecase\\\\\n \\\\n else:\\\\\n \\\\n from pathlib import PosixPath\\\\\n \\\\n output_data_dir = PosixPath(home)/'HCLT'/'AION'/'Data'\\\\\n \\\\n output_model_dir = PosixPath(home)/'HCLT'/'AION'/'target'/self.usecase\\\\\n \\\\n if not output_model_dir.exists():\\\\\n \\\\n raise ValueError(f'Configuration file not found at {output_model_dir}')\\\\\n \\\\n\\\\\n \\\\n tracking_uri = 'file:///' + str(Path(output_model_dir)/'mlruns')\\\\\n \\\\n registry_uri = 'sqlite:///' + str(Path(output_model_dir)/'mlruns.db')\\\\\n \\\\n mlflow.set_tracking_uri(tracking_uri)\\\\\n \\\\n mlflow.set_registry_uri(registry_uri)\\\\\n \\\\n client = mlflow.tracking.MlflowClient(\\\\\n \\\\n tracking_uri=tracking_uri,\\\\\n \\\\n registry_uri=registry_uri,\\\\\n \\\\n )\\\\\n \\\\n model_version_uri = 'models:/{model_name}/production'.format(model_name=self.usecase)\\\\\n \\\\n model = mlflow.pyfunc.load_model(model_version_uri)\\\\\n \\\\n run = client.get_run(model.metadata.run_id)\\\\\n \\\\n if run.info.artifact_uri.startswith('file:'):\\\\\n \\\\n artifact_path = Path(run.info.artifact_uri[len('file:///') : ])\\\\\n \\\\n else:\\\\\n \\\\n artifact_path = Path(run.info.artifact_uri)\\\\\n \\\\n self.trainingDataPath = artifact_path/(self.usecase + '_data.csv')\\\\\n \\\\n\\\\\n \\\\n def get_input_drift(self,current_data, historical_data):\\\\\n \\\\n curr_num_feat = current_data.select_dtypes(include='number')\\\\\n \\\\n hist_num_feat = historical_data.select_dtypes(include='number')\\\\\n \\\\n num_features = [feat for feat in historical_data.columns if feat in curr_num_feat]\\\\\n \\\\n alert_count = 0\\\\\n \\\\n data = {\\\\\n \\\\n 'current':{'data':current_data},\\\\\n \\\\n 'hist': {'data': historical_data}\\\\\n \\\\n }\\\\\n \\\\n dist_changed_columns = []\\\\\n \\\\n dist_change_message = []\\\\\n \\\\n for feature in num_features:\\\\\n \\\\n curr_static_value = st.ks_2samp( hist_num_feat[feature], curr_num_feat[feature]).pvalue\\\\\n \\\\n if (curr_static_value < 0.05):\\\\\n \\\\n distribution = {}\\\\\n \\\\n distribution['hist'] = self.DistributionFinder( historical_data[feature])\\\\\n \\\\n distribution['curr'] = self.DistributionFinder( current_data[feature])\\\\\n \\\\n if(distribution['hist']['name'] == distribution['curr']['name']):\\\\\n \\\\n pass\\\\\n \\\\n else:\\\\\n \\\\n alert_count = alert_count + 1\\\\\n \\\\n dist_changed_columns.append(feature)\\\\\n \\\\n changed_column = {}\\\\\n \\\\n changed_column['Feature'] = feature\\\\\n \\\\n changed_column['KS_Training'] = curr_static_value\\\\\n \\\\n changed_column['Training_Distribution'] = distribution['hist']['name']\\\\\n \\\\n changed_column['New_Distribution'] = distribution['curr']['name']\\\\\n \\\\n dist_change_message.append(changed_column)\\\\\n \\\\n if alert_count:\\\\\n \\\\n resultStatus = dist_change_message\\\\\n \\\\n else :\\\\\n \\\\n resultStatus='Model is working as expected'\\\\\n \\\\n return(alert_count, resultStatus)\\\\\n \\\\n\\\\\n \\\\n def DistributionFinder(self,data):\\\\\n \\\\n best_distribution =''\\\\\n \\\\n best_sse =0.0\\\\\n \\\\n if(data.dtype in ['int','int64']):\\\\\n \\\\n distributions= {'bernoulli':{'algo':st.bernoulli},\\\\\n \\\\n 'binom':{'algo':st.binom},\\\\\n \\\\n 'geom':{'algo':st.geom},\\\\\n \\\\n 'nbinom':{'algo':st.nbinom},\\\\\n \\\\n 'poisson':{'algo':st.poisson}\\\\\n \\\\n }\\\\\n \\\\n index, counts = np.unique(data.astype(int),return_counts=True)\\\\\n \\\\n if(len(index)>=2):\\\\\n \\\\n best_sse = np.inf\\\\\n \\\\n y1=[]\\\\\n \\\\n total=sum(counts)\\\\\n \\\\n mean=float(sum(index*counts))/total\\\\\n \\\\n variance=float((sum(index**2*counts) -total*mean**2))/(total-1)\\\\\n \\\\n dispersion=mean/float(variance)\\\\\n \\\\n theta=1/float(dispersion)\\\\\n \\\\n r=mean*(float(theta)/1-theta)\\\\\n \\\\n\\\\\n \\\\n for j in counts:\\\\\n \\\\n y1.append(float(j)/total)\\\\\n \\\\n distributions['bernoulli']['pmf'] = distributions['bernoulli']['algo'].pmf(index,mean)\\\\\n \\\\n distributions['binom']['pmf'] = distributions['binom']['algo'].pmf(index,len(index),p=mean/len(index))\\\\\n \\\\n distributions['geom']['pmf'] = distributions['geom']['algo'].pmf(index,1/float(1+mean))\\\\\n \\\\n distributions['nbinom']['pmf'] = distributions['nbinom']['algo'].pmf(index,mean,r)\\\\\n \\\\n distributions['poisson']['pmf'] = distributions['poisson']['algo'].pmf(index,mean)\\\\\n \\\\n\\\\\n \\\\n sselist = []\\\\\n \\\\n for dist in distributions.keys():\\\\\n \\\\n distributions[dist]['sess'] = np.sum(np.power(y1 - distributions[dist]['pmf'], 2.0))\\\\\n \\\\n if np.isnan(distributions[dist]['sess']):\\\\\n \\\\n distributions[dist]['sess'] = float('inf')\\\\\n \\\\n best_dist = min(distributions, key=lambda v: distributions[v]['sess'])\\\\\n \\\\n best_distribution = best_dist\\\\\n \\\\n best_sse = distributions[best_dist]['sess']\\\\\n \\\\n\\\\\n \\\\n elif (len(index) == 1):\\\\\n \\\\n best_distribution = 'Constant Data-No Distribution'\\\\\n \\\\n best_sse = 0.0\\\\\n \\\\n elif(data.dtype in ['float64','float32']):\\\\\n \\\\n distributions = [st.uniform,st.expon,st.weibull_max,st.weibull_min,st.chi,st.norm,st.lognorm,st.t,st.gamma,st.beta]\\\\\n \\\\n best_distribution = st.norm.name\\\\\n \\\\n best_sse = np.inf\\\\\n \\\\n nrange = data.max() - data.min()\\\\\n \\\\n\\\\\n \\\\n y, x = np.histogram(data.astype(float), bins='auto', density=True)\\\\\n \\\\n x = (x + np.roll(x, -1))[:-1] / 2.0\\\\\n \\\\n\\\\\n \\\\n for distribution in distributions:\\\\\n \\\\n with warnings.catch_warnings():\\\\\n \\\\n warnings.filterwarnings('ignore')\\\\\n \\\\n params = distribution.fit(data.astype(float))\\\\\n \\\\n arg = params[:-2]\\\\\n \\\\n loc = params[-2]\\\\\n \\\\n scale = params[-1]\\\\\n \\\\n pdf = distribution.pdf(x, loc=loc, scale=scale, *arg)\\\\\n \\\\n sse = np.sum(np.power(y - pdf, 2.0))\\\\\n \\\\n if( sse < best_sse):\\\\\n \\\\n best_distribution = distribution.name\\\\\n \\\\n best_sse = sse\\\\\n \\\\n\\\\\n \\\\n return {'name':best_distribution, 'sse': best_sse}\\\\\n \\\\n\\\\\n \"\n return text\n \n def addSuffixCode(self, indent=1):\n text =\"\\\\n\\\\\n \\\\ndef check_drift( config):\\\\\n \\\\n inputdriftObj = inputdrift(config)\\\\\n \\\\n historicaldataFrame=pd.read_csv(inputdriftObj.trainingDataPath)\\\\\n \\\\n currentdataFrame=pd.read_csv(inputdriftObj.currentDataLocation)\\\\\n \\\\n dataalertcount,message = inputdriftObj.get_input_drift(currentdataFrame,historicaldataFrame)\\\\\n \\\\n if message == 'Model is working as expected':\\\\\n \\\\n output_json = {'status':'SUCCESS','data':{'Message':'Model is working as expected'}}\\\\\n \\\\n else:\\\\\n \\\\n output_json = {'status':'SUCCESS','data':{'Affected Columns':message}}\\\\\n \\\\n return(output_json)\\\\\n \\\\n\\\\\n \\\\nif __name__ == '__main__':\\\\\n \\\\n try:\\\\\n \\\\n if len(sys.argv) < 2:\\\\\n \\\\n raise ValueError('config file not present')\\\\\n \\\\n config = sys.argv[1]\\\\\n \\\\n if Path(config).is_file() and Path(config).suffix == '.json':\\\\\n \\\\n with open(config, 'r') as f:\\\\\n \\\\n config = json.load(f)\\\\\n \\\\n else:\\\\\n \\\\n config = json.loads(config)\\\\\n \\\\n output = check_drift(config)\\\\\n \\\\n status = {'Status':'Success','Message':output}\\\\\n \\\\n print('input_drift:'+json.dumps(status))\\\\\n \\\\n except Exception as e:\\\\\n \\\\n status = {'Status':'Failure','Message':str(e)}\\\\\n \\\\n print('input_drift:'+json.dumps(status))\"\n return text\n\n def addStatement(self, statement, indent=1):\n self.codeText += '\\\\n' + self.tab * indent + statement\n \n def generateCode(self):\n self.codeText += self.addInputDriftClass()\n self.codeText += self.addSuffixCode()\n \n def getCode(self):\n return self.codeText\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\nimport json\n\nclass drift():\n\n def __init__(self, indent=0, tab_size=4):\n self.tab = \" \"*tab_size\n self.codeText = \"\"\n self.function_code = \"\"\n self.input_files = {}\n self.output_files = {}\n self.addInputFiles({'log' : 'aion.log', 'metaData' : 'modelMetaData.json'})\n \n def addInputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def addOutputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def getInputFiles(self): \n text = 'IOFiles = '\n if not self.input_files:\n text += '{ }'\n else:\n text += json.dumps(self.input_files, indent=4)\n return text\n \n def getOutputFiles(self):\n text = 'output_file = '\n if not self.output_files:\n text += '{ }'\n else:\n text += json.dumps(self.output_files, indent=4)\n return text\n \n def getInputOutputFiles(self, indent=0):\n text = '\\\\n'\n text += self.getInputFiles()\n if indent:\n text = text.replace('\\\\n', self.tab * indent + '\\\\n')\n return text\n\n def __addValidateConfigCode(self):\n text = \"\\\\n\\\\\n \\\\ndef validateConfig():\\\\\n \\\\n config_file = Path(__file__).parent/'config.json'\\\\\n \\\\n if not Path(config_file).exists():\\\\\n \\\\n raise ValueError(f'Config file is missing: {config_file}')\\\\\n \\\\n config = utils.read_json(config_file)\\\\\n\t\t\\\\n return config\\\\\n\t\t\"\n return text\n \n def addLocalFunctionsCode(self):\n self.function_code += self.__addValidateConfigCode()\n \n def addPrefixCode(self, smaller_is_better=False, indent=1):\n self.codeText += \"\"\"\ndef monitoring(config, targetPath, log):\n retrain = False\n last_run_id = 0\n retrain_threshold = config.get('retrainThreshold', 100)\n meta_data_file =", "instruction": "", "output": "" }, { "input": "targetPath / IOFiles['metaData']\n if meta_data_file.exists():\n meta_data = utils.read_json(meta_data_file)\n if not meta_data.get('register', None):\n log.info('Last time Pipeline not executed properly')\n retrain = True\n else:\n last_run_id = meta_data['register']['runId']\n df = utils.read_data(config['dataLocation'])\n df_len = len(df)\n if not meta_data['monitoring'].get('endIndex', None):\n meta_data['monitoring']['endIndex'] = int(meta_data['load_data']['Status']['Records'])\n meta_data['monitoring']['endIndexTemp'] = meta_data['monitoring']['endIndex']\n if meta_data['register'].get('registered', False):\n meta_data['monitoring']['endIndex'] = meta_data['monitoring']['endIndexTemp']\n meta_data['register']['registered'] = False #ack registery\n if (meta_data['monitoring']['endIndex'] + retrain_threshold) < df_len:\n meta_data['monitoring']['endIndexTemp'] = df_len\n retrain = True\n else:\n log.info('Pipeline running first time')\n meta_data = {}\n meta_data['monitoring'] = {}\n retrain = True\n if retrain:\n meta_data['monitoring']['runId'] = last_run_id + 1\n meta_data['monitoring']['retrain'] = retrain\n utils.write_json(meta_data, targetPath/IOFiles['metaData'])\n status = {'Status':'Success','retrain': retrain, 'runId':meta_data['monitoring']['runId']} \n log.info(f'output: {status}') \n return json.dumps(status)\n \"\"\"\n def getMainCodeModules(self):\n modules = [{'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'pandas','mod_as':'pd'}\n ,{'module':'json'}\n ]\n return modules\n \n def addMainCode(self, indent=1):\n self.codeText += \"\"\"\nif __name__ == '__main__':\n config = validateConfig()\n targetPath = Path('aion') / config['targetPath']\n targetPath.mkdir(parents=True, exist_ok=True)\n log_file = targetPath / IOFiles['log']\n log = utils.logger(log_file, mode='a', logger_name=Path(__file__).parent.stem)\n try:\n print(monitoring(config, targetPath, log))\n except Exception as e:\n status = {'Status': 'Failure', 'Message': str(e)}\n print(json.dumps(status))\n \"\"\"\n\n def addStatement(self, statement, indent=1):\n self.codeText += f\"\\\\n{self.tab * indent}{statement}\"\n \n def getCode(self, indent=1):\n return self.function_code + '\\\\n' + self.codeText\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\nimport json\n\nclass deploy():\n\n def __init__(self, tab_size=4):\n self.tab = ' ' * tab_size\n self.codeText = \"\"\n self.input_files = {}\n self.output_files = {}\n self.addInputFiles({'metaData' : 'modelMetaData.json','log':'predict.log'})\n \n def addInputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def addOutputFiles(self, files):\n if not isinstance(files, dict):\n raise TypeError(f\"Required dict type got {type(files)} type\")\n for k,v in files.items():\n self.input_files[k] = v\n \n def getInputFiles(self): \n text = 'IOFiles = '\n if not self.input_files:\n text += '{ }'\n else:\n text += json.dumps(self.input_files, indent=4)\n return text\n \n def getOutputFiles(self):\n text = 'output_file = '\n if not self.output_files:\n text += '{ }'\n else:\n text += json.dumps(self.output_files, indent=4)\n return text\n \n def getInputOutputFiles(self, indent=0):\n text = '\\\\n'\n text += self.getInputFiles()\n text += '\\\\n'\n text += self.getOutputFiles()\n if indent:\n text = text.replace('\\\\n', self.tab * indent + '\\\\n')\n return text\n\n def addStatement(self, statement, indent=1):\n pass\n\n def getPredictionCodeModules(self):\n modules = [{'module':'json'}\n ,{'module':'joblib'}\n ,{'module':'pandas', 'mod_as':'pd'}\n ,{'module':'numpy', 'mod_as':'np'}\n ,{'module':'Path', 'mod_from':'pathlib'}\n ,{'module':'json_normalize', 'mod_from':'pandas'}\n ,{'module':'load_model', 'mod_from':'tensorflow.keras.models'}\n ]\n return modules\n \n def addPredictionCode(self):\n self.codeText += \"\"\"\nclass deploy():\n\n def __init__(self, base_config, log=None):\n self.targetPath = (Path('aion') / base_config['targetPath']).resolve()\n if log:\n self.logger = log\n else:\n log_file = self.targetPath / IOFiles['log']\n self.logger = logger(log_file, mode='a', logger_name=Path(__file__).parent.stem)\n try:\n self.initialize(base_config)\n except Exception as e:\n self.logger.error(e, exc_info=True)\n\n def initialize(self, base_config):\n targetPath = Path('aion') / base_config['targetPath']\n meta_data_file = targetPath / IOFiles['metaData']\n if meta_data_file.exists():\n meta_data = utils.read_json(meta_data_file)\n self.dateTimeFeature = meta_data['training']['dateTimeFeature']\n self.targetFeature = meta_data['training']['target_feature']\n\n normalization_file = meta_data['transformation']['Status']['Normalization_file']\n self.normalizer = joblib.load(normalization_file)\n self.lag_order = base_config['lag_order']\n self.noofforecasts = base_config['noofforecasts']\n run_id = str(meta_data['register']['runId'])\n model_path = str(targetPath/'runs'/str(meta_data['register']['runId'])/meta_data['register']['model']/'model')\n self.model = load_model(model_path)\n self.model_name = meta_data['register']['model']\n\n def predict(self, data=None):\n try:\n return self.__predict(data)\n except Exception as e:\n if self.logger:\n self.logger.error(e, exc_info=True)\n raise ValueError(json.dumps({'Status': 'Failure', 'Message': str(e)}))\n\n def __predict(self, data=None):\n jsonData = json.loads(data)\n\n dataFrame = json_normalize(jsonData)\n\n xtrain = dataFrame\n if len(dataFrame) == 0:\n raise ValueError('No data record found')\n\n df_l = len(dataFrame)\n pred_threshold = 0.1\n max_pred_by_user = round((df_l) * pred_threshold)\n # prediction for 24 steps or next 24 hours\n if self.noofforecasts == -1:\n self.noofforecasts = max_pred_by_user\n no_of_prediction = self.noofforecasts\n if (str(no_of_prediction) > str(max_pred_by_user)):\n no_of_prediction = max_pred_by_user\n noofforecasts = no_of_prediction\n\n # self.sfeatures.remove(self.datetimeFeature)\n features = self.targetFeature\n if len(features) == 1:\n xt = xtrain[features].values\n else:\n xt = xtrain[features].values\n xt = xt.astype('float32')\n xt = self.normalizer.transform(xt)\n pred_data = xt\n y_future = []\n self.lag_order = int(self.lag_order)\n for i in range(int(no_of_prediction)):\n pdata = pred_data[-self.lag_order:]\n if len(features) == 1:\n pdata = pdata.reshape((1, self.lag_order))\n else:\n pdata = pdata.reshape((1, self.lag_order, len(features)))\n\n if (len(features) > 1):\n pred = self.model.predict(pdata)\n predout = self.normalizer.inverse_transform(pred)\n y_future.append(predout)\n pred_data = np.append(pred_data, pred, axis=0)\n else:\n pred = self.model.predict(pdata)\n predout = self.normalizer.inverse_transform(pred)\n y_future.append(predout.flatten()[-1])\n pred_data = np.append(pred_data, pred)\n pred = pd.DataFrame(index=range(0, len(y_future)), columns=self.targetFeature)\n for i in range(0, len(y_future)):\n pred.iloc[i] = y_future[i]\n predictions = pred\n forecast_output = predictions.to_json(orient='records')\n return forecast_output \n \"\"\"\n \n def getCode(self):\n return self.codeText\n\n def getServiceCode(self):\n return \"\"\"\n\nfrom http.server import BaseHTTPRequestHandler,HTTPServer \nfrom socketserver import ThreadingMixIn \nimport os \nfrom os.path import expanduser \nimport platform \nimport threading \nimport subprocess \nimport argparse \nimport re \nimport cgi \nimport json \nimport shutil\nimport logging\nimport sys \nimport time\nimport seaborn as sns\nfrom pathlib import Path \nfrom predict import deploy\nimport pandas as pd\nimport scipy.stats as st\nimport numpy as np\nimport warnings\nfrom utility import *\n\nwarnings.filterwarnings(\"ignore\")\nconfig_input = None \n \nIOFiles = {\n\t\"inputData\": \"rawData.dat\",\n\t\"metaData\": \"modelMetaData.json\",\n\t\"production\": \"production.json\", \n\t\"log\": \"aion.log\",\n\t\"monitoring\":\"monitoring.json\",\n\t\"prodData\": \"prodData\",\n\t\"prodDataGT\":\"prodDataGT\"\n}\n\ndef DistributionFinder(data):\n try:\n distributionName = \"\"\n sse = 0.0\n KStestStatic = 0.0\n dataType = \"\"\n if (data.dtype == \"float64\" or data.dtype == \"float32\"):\n dataType = \"Continuous\"\n elif (data.dtype == \"int\"):\n dataType = \"Discrete\"\n elif (data.dtype == \"int64\"):\n dataType = \"Discrete\"\n if (dataType == \"Discrete\"):\n distributions = [st.bernoulli, st.binom, st.geom, st.nbinom, st.poisson]\n index, counts = np.unique(data.astype(int), return_counts=True)\n\n if (len(index) >= 2):\n best_sse = np.inf\n y1 = []\n total = sum(counts)\n mean = float(sum(index * counts)) / total\n variance = float((sum(index ** 2 * counts) - total * mean ** 2)) / (total - 1)\n dispersion = mean / float(variance)\n theta = 1 / float(dispersion)\n r = mean * (float(theta) / 1 - theta)\n\n for j in counts:\n y1.append(float(j) / total)\n\n pmf1 = st.bernoulli.pmf(index, mean)\n pmf2 = st.binom.pmf(index, len(index), p=mean / len(index))\n pmf3 = st.geom.pmf(index, 1 / float(1 + mean))\n pmf4 = st.nbinom.pmf(index, mean, r)\n pmf5 = st.poisson.pmf(index, mean)\n\n sse1 = np.sum(np.power(y1 - pmf1, 2.0))\n sse2 = np.sum(np.power(y1 - pmf2, 2.0))\n sse3 = np.sum(np.power(y1 - pmf3, 2.0))\n sse4 = np.sum(np.power(y1 - pmf4, 2.0))\n sse5 = np.sum(np.power(y1 - pmf5, 2.0))\n\n sselist = [sse1, sse2, sse3, sse4, sse5]\n best_distribution = 'NA'\n for i in range(0, len(sselist)):\n if best_sse > sselist[i] > 0:\n best_distribution = distributions[i].name\n best_sse = sselist[i]\n\n elif (len(index) == 1):\n best_distribution = \"Constant Data-No Distribution\"\n best_sse = 0.0\n\n distributionName = best_distribution\n sse = best_sse\n\n elif (dataType == \"Continuous\"):\n\n distributions = [st.uniform, st.expon, st.weibull_max, st.weibull_min, st.chi, st.norm, st.lognorm, st.t,\n st.gamma, st.beta]\n best_distribution = st.norm.name\n best_sse = np.inf\n datamin = data.min()\n datamax = data.max()\n nrange = datamax - datamin\n\n y, x = np.histogram(data.astype(float), bins='auto', density=True)\n x = (x + np.roll(x, -1))[:-1] / 2.0\n\n for distribution in distributions:\n params = distribution.fit(data.astype(float))\n arg = params[:-2]\n loc = params[-2]\n scale = params[-1]\n pdf = distribution.pdf(x, loc=loc, scale=scale, *arg)\n sse = np.sum(np.power(y - pdf, 2.0))\n if (best_sse > sse > 0):\n best_distribution = distribution.name\n best_sse = sse\n distributionName = best_distribution\n sse = best_sse\n except:\n response = str(sys.exc_info()[0])\n message = 'Job has Failed' + response\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n print(str(exc_type) + ' ' + str(fname) + ' ' + str(exc_tb.", "instruction": "", "output": "" }, { "input": "tb_lineno))\n print(message)\n return distributionName, sse\n \ndef getDriftDistribution(feature, dataframe, newdataframe=pd.DataFrame()):\n import matplotlib.pyplot as plt\n import math\n import io, base64, urllib\n np.seterr(divide='ignore', invalid='ignore')\n try:\t\n plt.clf()\n except:\n pass\n plt.rcParams.update({'figure.max_open_warning': 0})\n sns.set(color_codes=True)\n pandasNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n if len(feature) > 4:\n numneroffeatures = len(feature)\n plt.figure(figsize=(10, numneroffeatures*2))\n else:\n plt.figure(figsize=(10,5))\n \n for i in enumerate(feature):\n \n dataType = dataframe[i[1]].dtypes\n if dataType not in pandasNumericDtypes:\n dataframe[i[1]] = pd.Categorical(dataframe[i[1]])\n dataframe[i[1]] = dataframe[i[1]].cat.codes\n dataframe[i[1]] = dataframe[i[1]].astype(int)\n dataframe[i[1]] = dataframe[i[1]].fillna(dataframe[i[1]].mode()[0])\n else:\n dataframe[i[1]] = dataframe[i[1]].fillna(dataframe[i[1]].mean())\n \n plt.subplots_adjust(hspace=0.5, wspace=0.7, top=1)\n plt.subplot(math.ceil((len(feature) / 2)), 2, i[0] + 1)\n distname, sse = DistributionFinder(dataframe[i[1]]) \n print(distname) \n ax = sns.distplot(dataframe[i[1]], label=distname)\n ax.legend(loc='best')\n if newdataframe.empty == False:\n dataType = newdataframe[i[1]].dtypes\n if dataType not in pandasNumericDtypes:\n newdataframe[i[1]] = pd.Categorical(newdataframe[i[1]])\n newdataframe[i[1]] = newdataframe[i[1]].cat.codes\n newdataframe[i[1]] = newdataframe[i[1]].astype(int)\n newdataframe[i[1]] = newdataframe[i[1]].fillna(newdataframe[i[1]].mode()[0])\n else:\n newdataframe[i[1]] = newdataframe[i[1]].fillna(newdataframe[i[1]].mean())\n distname, sse = DistributionFinder(newdataframe[i[1]]) \n print(distname)\n ax = sns.distplot(newdataframe[i[1]],label=distname)\n ax.legend(loc='best')\n buf = io.BytesIO()\n plt.savefig(buf, format='png')\n buf.seek(0)\n string = base64.b64encode(buf.read())\n uri = urllib.parse.quote(string)\n return uri\n\t\ndef read_json(file_path): \n data = None \n with open(file_path,'r') as f: \n data = json.load(f) \n return data \n \nclass HTTPRequestHandler(BaseHTTPRequestHandler): \n \n\tdef do_POST(self): \n\t\tprint('PYTHON ######## REQUEST ####### STARTED') \n\t\tif None != re.search('/AION/', self.path) or None != re.search('/aion/', self.path):\n\t\t\tctype, pdict = cgi.parse_header(self.headers.get('content-type')) \n\t\t\tif ctype == 'application/json': \n\t\t\t\tlength = int(self.headers.get('content-length')) \n\t\t\t\tdata = self.rfile.read(length) \n\t\t\t\tusecase = self.path.split('/')[-2]\n\t\t\t\tif usecase.lower() == config_input['targetPath'].lower():\t\t\t\t\t\n\t\t\t\t\toperation = self.path.split('/')[-1] \n\t\t\t\t\tdata = json.loads(data) \n\t\t\t\t\tdataStr = json.dumps(data) \n\t\t\t\t\tif operation.lower() == 'predict': \n\t\t\t\t\t\toutput=deployobj.predict(dataStr) \n\t\t\t\t\t\tresp = output \n\t\t\t\t\telif operation.lower() == 'groundtruth':\n\t\t\t\t\t\tgtObj = groundtruth(config_input)\t\t\t\t\n\t\t\t\t\t\toutput = gtObj.actual(dataStr)\n\t\t\t\t\t\tresp = output \n\t\t\t\t\telif operation.lower() == 'delete':\n\t\t\t\t\t\ttargetPath = Path('aion')/config_input['targetPath'] \n\t\t\t\t\t\tfor file in data:\n\t\t\t\t\t\t\tx = targetPath/file \n\t\t\t\t\t\t\tif x.exists():\n\t\t\t\t\t\t\t\tos.remove(x) \n\t\t\t\t\t\tresp = json.dumps({'Status':'Success'})\n\t\t\t\t\telse: \n\t\t\t\t\t\toutputStr = json.dumps({'Status':'Error','Msg':'Operation not supported'}) \n\t\t\t\t\t\tresp = outputStr \n\t\t\t\telse:\n\t\t\t\t\toutputStr = json.dumps({'Status':'Error','Msg':'Wrong URL'}) \n\t\t\t\t\tresp = outputStr\n \n\t\t\telse: \n\t\t\t\toutputStr = json.dumps({'Status':'ERROR','Msg':'Content-Type Not Present'}) \n\t\t\t\tresp = outputStr \n\t\t\tresp=resp+'\\\\\\\\n' \n\t\t\tresp=resp.encode() \n\t\t\tself.send_response(200) \n\t\t\tself.send_header('Content-Type', 'application/json') \n\t\t\tself.end_headers() \n\t\t\tself.wfile.write(resp) \n\t\telse: \n\t\t\tprint('python ==> else1') \n\t\t\tself.send_response(403) \n\t\t\tself.send_header('Content-Type', 'application/json') \n\t\t\tself.end_headers() \n\t\t\tprint('PYTHON ######## REQUEST ####### ENDED') \n\t\treturn \n \n\tdef do_GET(self): \n\t\tprint('PYTHON ######## REQUEST ####### STARTED') \n\t\tif None != re.search('/AION/', self.path) or None != re.search('/aion/', self.path): \n\t\t\tusecase = self.path.split('/')[-2] \n\t\t\tself.send_response(200) \n\t\t\tself.targetPath = Path('aion')/config_input['targetPath']\t\t\t\n\t\t\tmeta_data_file = self.targetPath/IOFiles['metaData'] \n\t\t\tif meta_data_file.exists(): \n\t\t\t\tmeta_data = read_json(meta_data_file) \n\t\t\telse: \n\t\t\t\traise ValueError(f'Configuration file not found: {meta_data_file}')\n\t\t\tproduction_file = self.targetPath/IOFiles['production'] \n\t\t\tif production_file.exists(): \n\t\t\t\tproduction_data = read_json(production_file) \n\t\t\telse: \n\t\t\t\traise ValueError(f'Production Details not found: {production_file}') \n\t\t\toperation = self.path.split('/')[-1] \n\t\t\tif (usecase.lower() == config_input['targetPath'].lower()) and (operation.lower() == 'metrices'):\n\t\t\t\tself.send_header('Content-Type', 'text/html') \n\t\t\t\tself.end_headers() \n\t\t\t\tModelString = production_data['Model']\n\t\t\t\tModelPerformance = ModelString+'_performance.json' \n\t\t\t\tperformance_file = self.targetPath/ModelPerformance \n\t\t\t\tif performance_file.exists(): \n\t\t\t\t\tperformance_data = read_json(performance_file) \n\t\t\t\telse: \n\t\t\t\t\traise ValueError(f'Production Details not found: {performance_data}')\n\t\t\t\tScoring_Creteria = performance_data['scoring_criteria'] \n\t\t\t\ttrain_score = round(performance_data['metrices']['train_score'],2) \n\t\t\t\ttest_score = round(performance_data['metrices']['test_score'],2) \n\t\t\t\tcurrent_score = 'NA' \n\t\t\t\tmonitoring = read_json(self.targetPath/IOFiles['monitoring'])\n\t\t\t\treader = dataReader(reader_type=monitoring['prod_db_type'],target_path=self.targetPath, config=monitoring['db_config'])\n\t\t\t\tinputDatafile = self.targetPath/IOFiles['inputData'] \n\t\t\t\tNoOfPrediction = 0\n\t\t\t\tNoOfGroundTruth = 0 \n\t\t\t\tinputdistribution = '' \n\t\t\t\tif reader.file_exists(IOFiles['prodData']): \n\t\t\t\t\tdfPredict = reader.read(IOFiles['prodData'])\n\t\t\t\t\tdfinput = pd.read_csv(inputDatafile)\n\t\t\t\t\tfeatures = meta_data['training']['features']\n\t\t\t\t\tinputdistribution = getDriftDistribution(features,dfinput,dfPredict) \n\t\t\t\t\tNoOfPrediction = len(dfPredict)\t\t\t\t\n\t\t\t\t\tif reader.file_exists(IOFiles['prodDataGT']): \n\t\t\t\t\t\tdfGroundTruth = reader.read(IOFiles['prodDataGT'])\n\t\t\t\t\t\tNoOfGroundTruth = len(dfGroundTruth) \n\t\t\t\t\t\tcommon_col = [k for k in dfPredict.columns.tolist() if k in dfGroundTruth.columns.tolist()]\t\t\t\t\n\t\t\t\t\t\tproddataDF = pd.merge(dfPredict, dfGroundTruth, on =common_col,how = 'inner')\n\t\t\t\t\t\tif Scoring_Creteria.lower() == 'accuracy': \n\t\t\t\t\t\t\tfrom sklearn.metrics import accuracy_score \n\t\t\t\t\t\t\tcurrent_score = accuracy_score(proddataDF[config_input['target_feature']], proddataDF['prediction'])\n\t\t\t\t\t\t\tcurrent_score = round((current_score*100),2) \n\t\t\t\t\t\telif Scoring_Creteria.lower() == 'recall': \n\t\t\t\t\t\t\tfrom sklearn.metrics import accuracy_score \n\t\t\t\t\t\t\tcurrent_score = recall_score(proddataDF[config_input['target_feature']], proddataDF['prediction'],average='macro')\n\t\t\t\t\t\t\tcurrent_score = round((current_score*100),2) \n\t\t\t\tmsg = \\\\\"\"\"\n\nPerformance Details\n\n\n\n

Deployed Model:{ModelString}

\n
\n\n\n\n\n\n\n\n\n\n
No of Prediction{NoOfPrediction}
No of GroundTruth{NoOfGroundTruth}
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Score TypeTrain ScoreTest ScoreProduction Score
{Scoring_Creteria}{train_score}{test_score}{current_score}
\n
\n
\n\"\"\n\n\n\\\\\"\"\".format(border='{border: 1px solid black;}',ModelString=ModelString,Scoring_Creteria=Scoring_Creteria,NoOfPrediction=NoOfPrediction,NoOfGroundTruth=NoOfGroundTruth,train_score=train_score,test_score=test_score,current_score=current_score,newDataDrift=inputdistribution)\n\t\t\telif (usecase.lower() == config_input['targetPath'].lower()) and (operation.lower() == 'logs'): \n\t\t\t\tself.send_header('Content-Type', 'text/plain') \n\t\t\t\tself.end_headers() \n\t\t\t\tlog_file = self.targetPath/IOFiles['log'] \n\t\t\t\tif log_file.exists():\n\t\t\t\t\twith open(log_file) as f:\n\t\t\t\t\t\tmsg = f.read() \n\t\t\t\t\tf.close()\n\t\t\t\telse: \n\t\t\t\t\traise ValueError(f'Log Details not found: {log_file}') \n\t\t\telse:\n\t\t\t\tself.send_header('Content-Type', 'application/json') \n\t\t\t\tself.end_headers() \n\t\t\t\tfeatures = meta_data['load_data']['selected_features']\n\t\t\t\tbodydes='['\n\t\t\t\tfor x in features:\n\t\t\t\t\tif bodydes != '[':\n\t\t\t\t\t\tbodydes = bodydes+','\n\t\t\t\t\tbodydes = bodydes+'{\"'+x+'\":\"value\"}'\t\n\t\t\t\tbodydes+=']'\n\t\t\t\turltext = '/AION/'+config_input['targetPath']+'/predict'\n\t\t\t\turltextgth='/AION/'+config_input['targetPath']+'/groundtruth'\n\t\t\t\turltextproduction='/AION/'+config_input['targetPath']+'/metrices'\n\t\t\t\tmsg=\\\\\"\"\"\nVersion:{modelversion}\nRunNo: {runNo}\nURL for Prediction\n==================\nURL:{url}\nRequestType: POST\nContent-Type=application/json\nBody: {displaymsg}\nOutput: prediction,probability(if Applicable),remarks corresponding to each row.\n\nURL for GroundTruth\n===================\nURL:{urltextgth}\nRequestType: POST\nContent-Type=application/json\nNote: Make Sure that one feature (ID) should be unique in both predict and groundtruth. Otherwise outputdrift will not work \n\nURL for Model In Production Analysis\n====================================\nURL:{urltextproduction}\nRequestType: GET\nContent-Type=application/json\n\n\\\\\"\"\".format(modelversion=config_input['modelVersion'],runNo=config_input['deployedRunNo'],url=urltext,urltextgth=urltextgth,urltextproduction=urltextproduction,displaymsg=bodydes) \n\t\t\tself.wfile.write(msg.encode()) \n\t\telse: \n\t\t\tself.send_response(403) \n\t\t\tself.send_header('Content-Type', 'application/json') \n\t\t\tself.end_headers() \n\t\treturn \n \nclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer): \n\tallow_reuse_address = True \n \n\tdef shutdown(self): \n\t\tself.socket.close() \n\t\tHTTPServer.shutdown(self) \n \nclass file_status():\n\t\n\tdef __init__(self, reload_function, params, file, logger):\n\t\tself.files_status = {}\n\t\tself.initializeFileStatus(file)\n\t\tself.", "instruction": "", "output": "" }, { "input": "reload_function = reload_function\n\t\tself.params = params\n\t\tself.logger = logger\n\t\t\n\tdef initializeFileStatus(self, file):\n\t\tself.files_status = {'path': file, 'time':file.stat().st_mtime}\n\n\tdef is_file_changed(self):\n\t\tif self.files_status['path'].stat().st_mtime > self.files_status['time']:\n\t\t\tself.files_status['time'] = self.files_status['path'].stat().st_mtime\n\t\t\treturn True\n\t\treturn False\n\t\t\n\tdef run(self):\n\t\tglobal config_input \n\t\twhile( True):\n\t\t\ttime.sleep(30)\n\t\t\tif self.is_file_changed():\n\t\t\t\tproduction_details = targetPath/IOFiles['production']\n\t\t\t\tif not production_details.exists(): \n\t\t\t\t\traise ValueError(f'Model in production details does not exist')\n\t\t\t\tproductionmodel = read_json(production_details)\n\t\t\t\tconfig_file = Path(__file__).parent/'config.json' \n\t\t\t\tif not Path(config_file).exists(): \n\t\t\t\t\traise ValueError(f'Config file is missing: {config_file}') \n\t\t\t\tconfig_input = read_json(config_file)\t\t\t\t\n\t\t\t\tconfig_input['deployedModel'] = productionmodel['Model']\n\t\t\t\tconfig_input['deployedRunNo'] = productionmodel['runNo']\n\t\t\t\tself.logger.info('Model changed Reloading.....')\n\t\t\t\tself.logger.info(f'Model: {config_input[\"deployedModel\"]}')\t\t\t\t\n\t\t\t\tself.logger.info(f'Version: {str(config_input[\"modelVersion\"])}')\n\t\t\t\tself.logger.info(f'runNo: {str(config_input[\"deployedRunNo\"])}')\n\t\t\t\tself.reload_function(config_input)\n\t\t\t\nclass SimpleHttpServer(): \n\tdef __init__(self, ip, port, model_file_path,reload_function,params, logger): \n\t\tself.server = ThreadedHTTPServer((ip,port), HTTPRequestHandler) \n\t\tself.status_checker = file_status( reload_function, params, model_file_path, logger)\n\t\t\n\tdef start(self): \n\t\tself.server_thread = threading.Thread(target=self.server.serve_forever) \n\t\tself.server_thread.daemon = True \n\t\tself.server_thread.start() \n\t\tself.status_thread = threading.Thread(target=self.status_checker.run) \n\t\tself.status_thread.start() \n\t\t\n\tdef waitForThread(self): \n\t\tself.server_thread.join() \n\t\tself.status_thread.join() \n\t\t\n\tdef stop(self): \n\t\tself.server.shutdown() \n\t\tself.waitForThread() \n \nif __name__=='__main__': \n\tparser = argparse.ArgumentParser(description='HTTP Server') \n\tparser.add_argument('-ip','--ipAddress', help='HTTP Server IP') \n\tparser.add_argument('-pn','--portNo', type=int, help='Listening port for HTTP Server') \n\targs = parser.parse_args() \n\tconfig_file = Path(__file__).parent/'config.json' \n\tif not Path(config_file).exists(): \n\t\traise ValueError(f'Config file is missing: {config_file}') \n\tconfig = read_json(config_file) \n\tif args.ipAddress: \n\t\tconfig['ipAddress'] = args.ipAddress \n\tif args.portNo: \n\t\tconfig['portNo'] = args.portNo \n\ttargetPath = Path('aion')/config['targetPath'] \n\tif not targetPath.exists(): \n\t\traise ValueError(f'targetPath does not exist')\n\tproduction_details = targetPath/IOFiles['production']\n\tif not production_details.exists(): \n\t\traise ValueError(f'Model in production details does not exist')\n\tproductionmodel = read_json(production_details)\n\tconfig['deployedModel'] = productionmodel['Model']\n\tconfig['deployedRunNo'] = productionmodel['runNo']\t\n\t#server = SimpleHttpServer(config['ipAddress'],int(config['portNo'])) \n\tconfig_input = config \n\tlogging.basicConfig(filename= Path(targetPath)/IOFiles['log'], filemode='a', format='%(asctime)s %(name)s- %(message)s', level=logging.INFO, datefmt='%d-%b-%y %H:%M:%S') \n\tlogger = logging.getLogger(Path(__file__).parent.name) \n\tdeployobj = deploy(config_input, logger)\n\tserver = SimpleHttpServer(config['ipAddress'],int(config['portNo']),targetPath/IOFiles['production'],deployobj.initialize,config_input, logger)\n\tlogger.info('HTTP Server Running...........')\n\tlogger.info(f\"IP Address: {config['ipAddress']}\")\n\tlogger.info(f\"Port No.: {config['portNo']}\")\n\tprint('HTTP Server Running...........') \n\tprint('For Prediction')\n\tprint('================')\n\tprint('Request Type: Post')\n\tprint('Content-Type: application/json')\t\n\tprint('URL: /AION/'+config['targetPath']+'/predict')\t\n\tprint('\\\\\\\\nFor GroundTruth')\n\tprint('================')\n\tprint('Request Type: Post')\n\tprint('Content-Type: application/json')\t\n\tprint('URL: /AION/'+config['targetPath']+'/groundtruth')\t\n\tprint('\\\\\\\\nFor Help')\n\tprint('================')\n\tprint('Request Type: Get')\n\tprint('Content-Type: application/json')\t\n\tprint('URL: /AION/'+config['targetPath']+'/help')\t\n\tprint('\\\\\\\\nFor Model In Production Analysis')\n\tprint('================')\n\tprint('Request Type: Get')\n\tprint('Content-Type: application/json')\t\n\tprint('URL: /AION/'+config['targetPath']+'/metrices') \n\tserver.start() \n\tserver.waitForThread()\n\"\"\" \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom pathlib import Path\nimport json\nimport platform\nfrom mlac.timeseries.core import *\nfrom .utility import *\n\noutput_file_map = {\n 'text' : {'text' : 'text_profiler.pkl'},\n 'targetEncoder' : {'targetEncoder' : 'targetEncoder.pkl'},\n 'featureEncoder' : {'featureEncoder' : 'inputEncoder.pkl'},\n 'normalizer' : {'normalizer' : 'normalizer.pkl'}\n}\n\ndef add_common_imports(importer):\n common_importes = [\n {'module': 'json', 'mod_from': None, 'mod_as': None},\n {'module': 'Path', 'mod_from': 'pathlib', 'mod_as': None},\n {'module': 'pandas', 'mod_from': None, 'mod_as': 'pd'},\n {'module': 'argparse', 'mod_from': None, 'mod_as': None},\n {'module': 'platform', 'mod_from': None, 'mod_as': None } \n ]\n for mod in common_importes:\n importer.addModule(mod['module'], mod_from=mod['mod_from'], mod_as=mod['mod_as'])\n\ndef get_transformer_params(config):\n param_keys = [\"modelVersion\",\"problem_type\",\"target_feature\",\"train_features\",\"text_features\",\"profiler\",\"test_ratio\",\"dateTimeFeature\"] #BugID:13217\n data = {key:value for (key,value) in config.items() if key in param_keys}\n data['targetPath'] = config['modelName']\n return data\n \ndef run_transformer(config):\n transformer = profiler()\n importer = importModule()\n function = global_function()\n importModules(importer, transformer.getPrefixModules())\n importer.addModule('warnings') \n transformer.addPrefixCode()\n importModules(importer, transformer.getMainCodeModules())\n transformer.addMainCode()\n usecase = config['modelName']+'_'+config['modelVersion']\n deploy_path = Path(config[\"deploy_path\"])/'MLaC'/'DataTransformation'\n deploy_path.mkdir(parents=True, exist_ok=True)\n generated_files = []\n \n # create the utility file\n importer.addLocalModule('*', mod_from='utility')\n utility_obj = utility_function('transformer')\n with open(deploy_path/\"utility.py\", 'w') as f:\n f.write(file_header(usecase) + utility_obj.get_code())\n generated_files.append(\"utility.py\") \n\n # create empty init file to make a package \n with open(deploy_path/\"__init__.py\", 'w') as f:\n f.write(file_header(usecase))\n generated_files.append(\"__init__.py\") \n \n code = file_header(usecase)\n code += \"\\\\nimport os\\\\nos.path.abspath(os.path.join(__file__, os.pardir))\\\\n\" #chdir to import from current dir\n code += importer.getCode()\n code += '\\\\nwarnings.filterwarnings(\"ignore\")\\\\n'\n code += transformer.getInputOutputFiles()\n code += function.getCode()\n transformer.addLocalFunctionsCode()\n code += transformer.getCode()\n with open(deploy_path/\"aionCode.py\", \"w\") as f:\n f.write(code)\n generated_files.append(\"aionCode.py\") \n\n with open(deploy_path/\"requirements.txt\", \"w\") as f:\n req=importer.getBaseModule(extra_importers=[utility_obj.get_importer()])\n f.write(req)\n generated_files.append(\"requirements.txt\") \n\n config_file = deploy_path/\"config.json\"\n config_data = get_transformer_params(config)\n with open (config_file, \"w\") as f:\n json.dump(config_data, f, indent=4)\n generated_files.append(\"config.json\") \n\n create_docker_file('transformer', deploy_path,config['modelName'], generated_files)\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom pathlib import Path\nimport json\nimport platform\nfrom mlac.timeseries.core import *\nfrom .utility import *\n\noutput_file_map = {\n 'feature_reducer' : {'feature_reducer' : 'feature_reducer.pkl'}\n}\n\ndef get_selector_params(config):\n param_keys = [\"modelVersion\",\"problem_type\",\"target_feature\",\"train_features\",\"cat_features\",\"n_components\"]\n data = {key:value for (key,value) in config.items() if key in param_keys}\n data['targetPath'] = config['modelName']\n return data\n \ndef run_selector(config): \n select = selector()\n importer = importModule()\n function = global_function()\n importModules(importer,select.getPrefixModules())\n importModules(importer, select.getSuffixModules())\n importModules(importer, select.getMainCodeModules())\n select.addPrefixCode()\n select.addSuffixCode()\n select.addMainCode()\n \n generated_files = []\n usecase = config['modelName']+'_'+config['modelVersion']\n deploy_path = Path(config[\"deploy_path\"])/'MLaC'/'FeatureEngineering'\n deploy_path.mkdir(parents=True, exist_ok=True)\n \n # create the utility file\n importer.addLocalModule('*', mod_from='utility')\n utility_obj = utility_function('selector')\n with open(deploy_path/\"utility.py\", 'w') as f:\n f.write(file_header(usecase) + utility_obj.get_code())\n generated_files.append(\"utility.py\") \n\n # create empty init file to make a package \n with open(deploy_path/\"__init__.py\", 'w') as f:\n f.write(file_header(usecase))\n generated_files.append(\"__init__.py\") \n \n code = file_header(usecase)\n code += importer.getCode()\n code += select.getInputOutputFiles()\n code += function.getCode()\n select.addLocalFunctionsCode()\n code += select.getCode()\n with open(deploy_path/\"aionCode.py\", \"w\") as f:\n f.write(code)\n generated_files.append(\"aionCode.py\") \n\n with open(deploy_path/\"requirements.txt\", \"w\") as f:\n req=importer.getBaseModule(extra_importers=[utility_obj.get_importer()])\n f.write(req)\n generated_files.append(\"requirements.txt\") \n\n config_file = deploy_path/\"config.json\"\n config_data = get_selector_params(config)\n with open (config_file, \"w\") as f:\n json.dump(config_data, f, indent=4)\n generated_files.append(\"config.json\") \n\n create_docker_file('selector', deploy_path,config['modelName'], generated_files) \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom pathlib import Path\nimport json\nfrom mlac.timeseries.core import *\nfrom mlac.timeseries.app import utility as utils\n\ndef get_model_name(algo, method):\n if method == 'modelBased':\n return algo + '_' + 'MLBased'\n if method == 'statisticalBased':\n return algo + '_' + 'StatisticsBased'\n else:\n return algo\n\n\ndef get_training_params(config, algo):\n param_keys = [\"modelVersion\",\"problem_type\",\"target_feature\",\"train_features\",\"scoring_criteria\",\"test_ratio\",\"optimization_param\",\"dateTimeFeature\"]#BugID:13217\n data = {key:value for (key,value) in config.items() if key in param_keys}\n data['algorithms'] = {algo: config['algorithms'][algo]}\n data['targetPath'] = config['modelName']\n return data\n\ndef update_score_comparer(scorer):\n smaller_is_better_scorer = ['neg_mean_squared_error','mse','neg_root_mean_squared_error','rmse','neg_mean_absolute_error','mae']\n if scorer", "instruction": "", "output": "" }, { "input": ".lower() in smaller_is_better_scorer:\n utils.update_variable('smaller_is_better', True)\n else:\n utils.update_variable('smaller_is_better', False)\n\ndef run_trainer(config): \n trainer = learner()\n importer = importModule()\n function = global_function()\n utils.importModules(importer,trainer.getPrefixModules())\n update_score_comparer(config['scoring_criteria'])\n model_name = list(config['algorithms'].keys())[0]\n if model_name == 'MLP':\n utils.importModules(importer,trainer.getMlpCodeModules())\n trainer.addMlpCode()\n elif model_name == 'LSTM':\n utils.importModules(importer,trainer.getLstmCodeModules())\n trainer.addLstmCode()\n trainer.addMainCode()\n\n usecase = config['modelName']+'_'+config['modelVersion']\n deploy_path = Path(config[\"deploy_path\"])/'MLaC'/('ModelTraining'+'_' + model_name)\n deploy_path.mkdir(parents=True, exist_ok=True)\n generated_files = []\n \n # create the utility file\n importer.addLocalModule('utility', mod_as='utils')\n utility_obj = utility_function('train')\n with open(deploy_path/\"utility.py\", 'w') as f:\n f.write(utils.file_header(usecase) + utility_obj.get_code())\n generated_files.append(\"utility.py\") \n\n # create empty init file to make a package \n with open(deploy_path/\"__init__.py\", 'w') as f:\n f.write(utils.file_header(usecase))\n generated_files.append(\"__init__.py\") \n importer.addModule(\"warnings\")\n code = importer.getCode()\n code += 'warnings.filterwarnings(\"ignore\")\\\\n'\n code += f\"\\\\nmodel_name = '{model_name}'\\\\n\"\n utils.append_variable('models_name',model_name)\n out_files = {'log':f'{model_name}_aion.log','model':f'{model_name}_model.pkl','metrics':'metrics.json','metaDataOutput':f'{model_name}_modelMetaData.json','production':'production.json'}\n trainer.addOutputFiles(out_files)\n code += trainer.getInputOutputFiles()\n code += function.getCode()\n trainer.addLocalFunctionsCode()\n code += trainer.getCode()\n with open(deploy_path/\"aionCode.py\", \"w\") as f:\n f.write(code)\n generated_files.append(\"aionCode.py\") \n\n with open(deploy_path/\"requirements.txt\", \"w\") as f:\n req=importer.getBaseModule(extra_importers=[utility_obj.get_importer()])\n f.write(req)\n generated_files.append(\"requirements.txt\") \n\n with open (deploy_path/\"config.json\", \"w\") as f:\n json.dump(get_training_params(config, model_name), f, indent=4)\n generated_files.append(\"config.json\") \n\n utils.create_docker_file('train', deploy_path,config['modelName'], generated_files)\n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom pathlib import Path\nimport json\nimport platform\nfrom mlac.timeseries.core import *\nfrom .utility import *\n\nimported_modules = [\n {'module': 'json', 'mod_from': None, 'mod_as': None},\n {'module': 'Path', 'mod_from': 'pathlib', 'mod_as': None},\n {'module': 'pandas', 'mod_from': None, 'mod_as': 'pd'},\n {'module': 'argparse', 'mod_from': None, 'mod_as': None},\n {'module': 'platform', 'mod_from': None, 'mod_as': None } \n ]\n\ndef get_load_data_params(config):\n param_keys = [\"modelVersion\",\"problem_type\",\"target_feature\",\"selected_features\",\"dateTimeFeature\",\"dataLocation\"]\n data = {key:value for (key,value) in config.items() if key in param_keys}\n data['targetPath'] = config['modelName']\n return data\n\ndef run_loader(config):\n generated_files = []\n importer = importModule()\n loader = tabularDataReader()\n importModules(importer, imported_modules)\n usecase = config['modelName']+'_'+config['modelVersion']\n deploy_path = Path(config[\"deploy_path\"])/'MLaC'/'DataIngestion'\n deploy_path.mkdir(parents=True, exist_ok=True)\n \n # create the utility file\n importer.addLocalModule('*', mod_from='utility')\n utility_obj = utility_function('load_data')\n with open(deploy_path/\"utility.py\", 'w') as f:\n f.write(file_header(usecase) + utility_obj.get_code())\n generated_files.append(\"utility.py\") \n # create the production data reader file\n importer.addLocalModule('dataReader', mod_from='data_reader')\n readers = ['sqlite','influx']\n if 's3' in config.keys():\n readers.append('s3')\n reader_obj = data_reader(readers)\n with open(deploy_path/\"data_reader.py\", 'w') as f:\n f.write(file_header(usecase) + reader_obj.get_code())\n generated_files.append(\"data_reader.py\") \n \n # create empty init file to make a package \n with open(deploy_path/\"__init__.py\", 'w') as f:\n f.write(file_header(usecase))\n generated_files.append(\"__init__.py\") \n \n code = file_header(usecase)\n code += importer.getCode()\n code += loader.getInputOutputFiles()\n loader.addLocalFunctionsCode()\n loader.addLoadDataCode()\n loader.addMainCode()\n code += loader.getCode()\n with open(deploy_path/\"aionCode.py\", \"w\") as f:\n f.write(code)\n generated_files.append(\"aionCode.py\") \n\n with open(deploy_path/\"requirements.txt\", \"w\") as f:\n req=importer.getBaseModule(extra_importers=[utility_obj.get_importer(), reader_obj.get_importer()])\n f.write(req)\n generated_files.append(\"requirements.txt\") \n \n config_file = deploy_path/\"config.json\"\n config_data = get_load_data_params(config)\n with open (config_file, \"w\") as f:\n json.dump(config_data, f, indent=4)\n generated_files.append(\"config.json\") \n \n create_docker_file('load_data', deploy_path,config['modelName'],generated_files) \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nfrom pathlib import Path\nimport json\nfrom mlac.timeseries.core import *\nfrom .utility import *\n\ndef get_register_params(config, models):\n param_keys = [\"modelVersion\",\"problem_type\"]\n data = {key:value for (key,value) in config.items() if key in param_keys}\n data['targetPath'] = config['modelName']\n data['models'] = models\n return data\n\ndef run_register(config):\n importer = importModule()\n\n registration = register(importer)\n models = get_variable('models_name')\n smaller_is_better = get_variable('smaller_is_better', False)\n registration.addLocalFunctionsCode(models)\n registration.addPrefixCode(smaller_is_better)\n registration.addMainCode(models)\n importModules(importer, registration.getMainCodeModules())\n importer.addModule('warnings')\n\n generated_files = []\n usecase = config['modelName']+'_'+config['modelVersion']\n deploy_path = Path(config[\"deploy_path\"])/'MLaC'/'ModelRegistry'\n deploy_path.mkdir(parents=True, exist_ok=True)\n\n # create the utility file\n importer.addLocalModule('utility', mod_as='utils')\n utility_obj = utility_function('register')\n with open(deploy_path/\"utility.py\", 'w') as f:\n f.write(file_header(usecase) + utility_obj.get_code())\n generated_files.append(\"utility.py\") \n\n # create empty init file required for creating a package \n with open(deploy_path/\"__init__.py\", 'w') as f:\n f.write(file_header(usecase))\n generated_files.append(\"__init__.py\") \n\n code = importer.getCode()\n code += '\\\\nwarnings.filterwarnings(\"ignore\")\\\\n'\n code += registration.getInputOutputFiles()\n code += registration.getCode()\n # create serving file\n with open(deploy_path/\"aionCode.py\", 'w') as f:\n f.write(file_header(usecase) + code)\n generated_files.append(\"aionCode.py\") \n\n # create requirements file\n req_file = deploy_path/\"requirements.txt\"\n with open(req_file, \"w\") as f:\n req=importer.getBaseModule(extra_importers=[utility_obj.get_importer()])\n f.write(req)\n generated_files.append(\"requirements.txt\")\n \n # create config file\n with open (deploy_path/\"config.json\", \"w\") as f:\n json.dump(get_register_params(config, models), f, indent=4)\n generated_files.append(\"config.json\") \n \n # create docker file\n create_docker_file('register', deploy_path,config['modelName'], generated_files) \n \"\"\"\n/**\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* \u00a9 Copyright HCL Technologies Ltd. 2021, 2022\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*/\n\"\"\"\n\nimport datetime\nfrom pathlib import Path\n\nvariables = {}\n\ndef update_variable(name, value):\n variables[name] = value\n \ndef get_variable(name, default=None):\n return variables.get(name, default)\n\ndef append_variable(name, value):\n data = get_variable(name)\n if not data:\n update_variable(name, [value])\n elif not isinstance(data, list):\n update_variable(name, [data, value])\n else:\n data.append(value)\n update_variable(name, data)\n \ndef addDropFeature(feature, features_list, coder, indent=1):\n coder.addStatement(f'if {feature} in {features_list}:', indent=indent)\n coder.addStatement(f'{features_list}.remove({feature})', indent=indent+1)\n \ndef importModules(importer, modules_list):\n for module in modules_list:\n mod_from = module.get('mod_from',None)\n mod_as = module.get('mod_as',None)\n importer.addModule(module['module'], mod_from=mod_from, mod_as=mod_as)\n \ndef file_header(use_case, module_name=None):\n time_str = datetime.datetime.now().isoformat(timespec='seconds', sep=' ')\n text = \"#!/usr/bin/env python\\\\n# -*- coding: utf-8 -*-\\\\n\"\n return text + f\"'''\\\\nThis file is automatically generated by AION for {use_case} usecase.\\\\nFile generation time: {time_str}\\\\n'''\"\n\ndef get_module_mapping(module):\n mapping = {\n \"LogisticRegression\": {'module':'LogisticRegression', 'mod_from':'sklearn.linear_model'}\n ,\"GaussianNB\": {'module':'GaussianNB', 'mod_from':'sklearn.naive_bayes'}\n ,\"DecisionTreeClassifier\": {'module':'DecisionTreeClassifier', 'mod_from':'sklearn.tree'}\n ,\"SVC\": {'module':'SVC', 'mod_from':'sklearn.svm'}\n ,\"KNeighborsClassifier\": {'module':'KNeighborsClassifier', 'mod_from':'sklearn.neighbors'}\n ,\"GradientBoostingClassifier\": {'module':'GradientBoostingClassifier', 'mod_from':'sklearn.ensemble'}\n ,'RandomForestClassifier':{'module':'RandomForestClassifier','mod_from':'sklearn.ensemble'}\n ,'XGBClassifier':{'module':'XGBClassifier','mod_from':'xgboost'}\n ,'LGBMClassifier':{'module':'LGBMClassifier','mod_from':'lightgbm'}\n ,'CatBoostClassifier':{'module':'CatBoostClassifier','mod_from':'catboost'}\n\n ,\"LinearRegression\": {'module':'LinearRegression', 'mod_from':'sklearn.linear_model'}\n ,\"Lasso\": {'module':'Lasso', 'mod_from':'sklearn.linear_model'}\n ,\"Ridge\": {'module':'Ridge', 'mod_from':'sklearn.linear_model'}\n ,\"DecisionTreeRegressor\": {'module':'DecisionTreeRegressor', 'mod_from':'sklearn.tree'}\n ,'RandomForestRegressor':{'module':'RandomForestRegressor','mod_from':'sklearn.ensemble'}\n ,'XGBRegressor':{'module':'XGBRegressor','mod_from':'xgboost'}\n ,'LGBMRegressor':{'module':'LGBMRegressor','mod_from':'lightgbm'}\n ,'CatBoostRegressor':{'module':'CatBoostRegressor','mod_from':'catboost'}\n }\n return mapping.get(module, None)\n\ndef create_docker_file(name, path,usecasename,files=[],text_feature=False):\n text = \"\"\n if name == 'load_data':\n text='FROM python:3.8-slim-buster'\n text+='\\\\n'\n text+='LABEL \"usecase\"=\"'+str(usecasename)+'\"'\n text+='\\\\n'\n text+='LABEL \"usecase_test\"=\"'+str(usecasename)+'_test'+'\"'\n for file in files:\n text+=f'\\\\nCOPY {file} {file}'\n text+='\\\\n'\n text+='RUN pip install --no-cache-dir -r requirements.txt'\n elif name == 'transformer':\n text='FROM python:3.8-slim-buster\\\\n'\n text+='LABEL \"usecase\"=\"'+str(usecasename)+'\"'\n text", "instruction": "", "output": "" }, { "input": "+='\\\\n'\n text+='LABEL \"usecase_test\"=\"'+str(usecasename)+'_test'+'\"'\n text+='\\\\n'\t\t\n for file in files:\n text+=f'\\\\nCOPY {file} {file}'\n if text_feature:\n text+='COPY AIX-0.1-py3-none-any.whl AIX-0.1-py3", "instruction": "", "output": "" }, { "input": "_names = {}\n encoders = {}\n \n dataFrame = dataFrame.replace('Unknown', 'NA')\n dataFrame = dataFrame.replace(np.nan, 'NA')\n try:\n # Label-Encoding\n for feature in dataFrame.columns:\n le = LabelEncoder()\n le.fit(data_encoded[feature])\n data_encoded[feature] = le.transform(data_encoded[feature])\n categorical_names[feature] = le.classes_\n encoders[feature] = le\n \n privileged_class = np.where(categorical_names[protected_feature] == privileged_className)[0]\n target_feature_count = len(data_encoded[target_feature].value_counts()) \n # Check if it's BinaryLabel\n if target_feature_count == 2:\n binaryLabelDataset = aif360.datasets.BinaryLabelDataset(\n favorable_label='1',\n unfavorable_label='0',\n df=data_encoded,\n label_names=[target_feature],\n protected_attribute_names=[protected_feature])\n data_orig = binaryLabelDataset\n \n # Check if it's Non-BinaryLabel\n if target_feature_count > 2:\n data_orig = StandardDataset(data_encoded, \n label_name=target_feature, \n favorable_classes=[1], \n protected_attribute_names=[protected_feature], \n privileged_classes=[privileged_class])\n \n if algorithm == 'DIR':\n DIR = DisparateImpactRemover(repair_level=0.9)\n data_transf_train = DIR.fit_transform(data_orig)\n # log.info('Status:-|... DIR applied on input dataset')\n else:\n privileged_groups, unprivileged_groups = self.get_attributes(data_orig, selected_attr=[protected_feature])\n RW = Reweighing(unprivileged_groups=unprivileged_groups, privileged_groups=privileged_groups)\n data_transf_train = RW.fit_transform(data_orig)\n # log.info('Status:-|... Reweighing applied on input dataset')\n \n transf_dataFrame = data_transf_train.convert_to_dataframe()[0]\n \n data_decoded = transf_dataFrame.copy().astype('int')\n for column in data_decoded.columns:\n data_decoded[column] = encoders[column].inverse_transform(data_decoded[column])\n \n debiased_dataFrame = data_decoded\n \n except Exception as e:\n print(e)\n debiased_dataFrame = dataFrame\n \n return debiased_dataFrame\n import warnings\nimport sys\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nimport xgboost as xgb\nimport dask.array as da\nimport shutil\nimport dask.distributed\nimport dask.dataframe as dd\nimport dask_ml\nimport logging\nfrom sklearn.metrics import accuracy_score, recall_score, \\\\\n roc_auc_score, precision_score, f1_score, \\\\\n mean_squared_error, mean_absolute_error, \\\\\n r2_score, classification_report, confusion_matrix, \\\\\n mean_absolute_percentage_error\n\nimport lightgbm as lgb\nimport re\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom dask_ml.impute import SimpleImputer\nfrom dask_ml.compose import ColumnTransformer\nfrom dask_ml.decomposition import TruncatedSVD, PCA\nfrom dask_ml.preprocessing import StandardScaler, \\\\\n MinMaxScaler, \\\\\n OneHotEncoder, LabelEncoder\nfrom dask_ml.wrappers import ParallelPostFit\nimport numpy as np\nimport json\nimport time\nfrom sklearn.ensemble import IsolationForest\nimport joblib\nimport pickle as pkl\nimport os\npredict_config={}\n\ndask.config.set({\"distributed.workers.memory.terminate\": 0.99})\ndask.config.set({\"array.chunk-size\": \"128 MiB\"})\ndask.config.set({\"distributed.admin.tick.limit\": \"3h\"})\n\n# dask.config.set({\"distributed.workers.memory.pause\": 0.9})\n\nclass MinImputer(BaseEstimator, TransformerMixin):\n def fit(self, X, y=None):\n return self\n def transform(self, X, y=None):\n # to_fillna = ['public_meeting', 'scheme_management', 'permit']\n # X[to_fillna] = X[to_fillna].fillna(value='NaN')\n # X[to_fillna] = X[to_fillna].astype(str) \n X = X.fillna(value=X.min())\n # X = X.astype(str) \n return X\n\nclass MaxImputer(BaseEstimator, TransformerMixin):\n def fit(self, X, y=None):\n return self\n def transform(self, X, y=None):\n X = X.fillna(value=X.max())\n return X\n\nclass DropImputer(BaseEstimator, TransformerMixin): \n def fit(self, X, y=None):\n return self\n def transform(self, X, y=None):\n X = X.dropna()\n return X\n\nclass ModeCategoricalImputer(BaseEstimator, TransformerMixin): \n def fit(self, X, y=None):\n return self\n def transform(self, X, y=None):\n X = X.fillna(value=X.mode())\n return X\n\nclass IsoForestOutlierExtractor(TransformerMixin):\n def fit(self, X, y=None):\n return self\n def transform(self, X, y):\n lcf = IsolationForest()\n with joblib.parallel_backend('dask'):\n lcf.fit(X)\n y_pred_train = lcf.predict(X)\n y_pred_train = y_pred_train == 1\n return X\n\ndef load_config_json(json_file):\n with open(json_file, 'r') as j:\n contents = json.loads(j.read())\n return contents\n\ndef load_data_dask(data_file, npartitions=500):\n big_df = dd.read_csv(data_file, # sep=r'\\\\s*,\\\\s*',\n assume_missing=True,\n parse_dates=True, infer_datetime_format=True,\n sample=1000000,\n # dtype={'caliper': 'object',\n # 'timestamp': 'object'},\n # dtype='object',\n na_values=['-','?']\n )\n big_df = big_df.repartition(npartitions) \n return big_df\n\ndef get_dask_eda(df_dask):\n descr = df_dask.describe().compute()\n corr = df_dask.corr().compute()\n return descr, corr\n\ndef normalization(config):\n scaler = config[\"advance\"] \\\\\n [\"profiler\"][\"normalization\"]\n scaler_method = None\n if scaler[\"minMax\"] == \"True\":\n scaler_method = MinMaxScaler()\n if scaler[\"standardScaler\"] == \"True\":\n scaler_method = StandardScaler()\n return scaler_method\n\ndef categorical_encoding(config):\n encoder = config[\"advance\"][\"profiler\"] \\\\\n [\"categoryEncoding\"]\n encoder_method = None\n if encoder[\"OneHotEncoding\"] == \"True\":\n encoder_method = OneHotEncoder()\n # OneHotEncoder(handle_unknown='ignore', sparse=False)\n if encoder[\"LabelEncoding\"] == \"True\": \n encoder_method = LabelEncoder()\n return encoder_method\n\ndef numeric_feature_imputing(config):\n imputer_numeric_method = None\n imputer_numeric = config[\"advance\"] \\\\\n [\"profiler\"][\"numericalFillMethod\"]\n if imputer_numeric[\"Median\"] == \"True\":\n print(\"Median Simple Imputer\")\n imputer_numeric_method = SimpleImputer(strategy='median')\n if imputer_numeric[\"Mean\"] == \"True\":\n print(\"Mean Simple Imputer\")\n imputer_numeric_method = SimpleImputer(strategy='mean')\n if imputer_numeric[\"Min\"] == \"True\":\n print(\"Min Simple Imputer\")\n imputer_numeric_method = MinImputer()\n if imputer_numeric[\"Max\"] == \"True\":\n print(\"Max Simple Imputer\")\n imputer_numeric_method = MaxImputer()\n if imputer_numeric[\"Zero\"] == \"True\":\n print(\"Zero Simple Imputer\")\n imputer_numeric_method = SimpleImputer(strategy='constant', \n fill_value=0)\n # if imputer_numeric[\"Drop\"] == \"True\":\n # print(\"Median Simple Imputer\")\n # imputer_numeric_method = DropImputer()\n return imputer_numeric_method\n\ndef categorical_feature_imputing(config):\n imputer_categorical_method = None\n imputer_categorical = config[\"advance\"] \\\\\n [\"profiler\"][\"categoricalFillMethod\"]\n if imputer_categorical[\"MostFrequent\"] == \"True\":\n imputer_categorical_method = SimpleImputer(strategy='most_frequent')\n if imputer_categorical[\"Mode\"] == \"True\":\n imputer_categorical_method = ModeCategoricalImputer()\n if imputer_categorical[\"Zero\"] == \"True\":\n imputer_categorical_method = SimpleImputer(strategy='constant', \n fill_value=0)\n return imputer_categorical_method\n\ndef preprocessing_pipeline(config, X_train):\n print(\"Start preprocessing\")\n scaler_method = normalization(config)\n encoding_method = categorical_encoding(config)\n imputer_numeric_method = numeric_feature_imputing(config)\n imputer_categorical_method = categorical_feature_imputing(config)\n \n numeric_pipeline = Pipeline(steps=[\n ('impute', imputer_numeric_method),\n ('scale', scaler_method)\n ])\n\n categorical_pipeline = Pipeline(steps=[\n ('impute', imputer_categorical_method),\n ('encoding', encoding_method)\n ])\n\n numerical_features = X_train._get_numeric_data().columns.values.tolist()\n categorical_features = list(set(X_train.columns) - set(X_train._get_numeric_data().columns))\n print(\"numerical_features: \", numerical_features)\n print(\"categorical_features: \", categorical_features)\n full_processor = ColumnTransformer(transformers=[\n ('number', numeric_pipeline, numerical_features),\n # ('category', categorical_pipeline, categorical_features)\n ])\n return full_processor \n\ndef full_pipeline(X_train, X_test, config):\n full_processor = preprocessing_pipeline(config, X_train)\n reduce_dim = config[\"advance\"] \\\\\n [\"selector\"][\"featureEngineering\"]\n feature_reduce = None\n if reduce_dim[\"SVD\"] == \"True\":\n feature_reduce = TruncatedSVD(n_components=3)\n if reduce_dim[\"PCA\"] == \"True\":\n feature_reduce = PCA(n_components=3)\n X_train = full_processor.fit_transform(X_train)\n # joblib.dump(full_processor, 'full_processor_pipeline.pkl')\n deploy_location = config[\"basic\"][\"modelLocation\"]\n profiler_file = os.path.join(deploy_location,'model','profiler.pkl')\n selector_file = os.path.join(deploy_location,'model','selector.pkl')\n save_pkl(full_processor, profiler_file)\n X_test = full_processor.transform(X_test)\n predict_config['profilerLocation'] = 'profiler.pkl' \n if feature_reduce != None:\n X_train = feature_reduce.fit_transform(X_train.to_dask_array(lengths=True))\n save_pkl(feature_reduce, selector_file)\n predict_config['selectorLocation'] = 'selector.pkl'\n # joblib.dump(feature_reduce, 'feature_reduce_pipeline.pkl')\n X_test = feature_reduce.transform(X_test.to_dask_array(lengths=True))\n X_train = dd.from_dask_array(X_train)\n X_test = dd.from_dask_array(X_test)\n else:\n predict_config['selectorLocation'] = ''\n return X_train, X_test\n\ndef train_xgb_classification(client, X_train, y_train, X_test, config):\n print(\"Training XGBoost classification\")\n model_hyperparams = config[\"advance\"] \\\\\n [\"distributedlearner_config\"] \\\\\n [\"modelParams\"] \\\\\n [\"classifierModelParams\"] \\\\\n [\"Distributed Extreme Gradient Boosting (XGBoost)\"]\n dask_model = xgb.dask.DaskXGBClassifier(\n tree_method=model_hyperparams[\"tree_method\"],\n n_estimators=int(model_hyperparams[\"n_estimators\"]),\n max_depth=int(model_hyperparams[\"max_depth\"]),\n gamma=float(model_hyperparams[\"gamma\"]),\n min_child_weight=float(model_hyperparams[\"min_child_weight\"]),\n subsample=float(model_hyperparams[\"subsample\"]),\n colsample_bytree=float(model_hyperparams[\"colsample_bytree\"]),\n learning_rate=float(model_hyperparams[\"learning_rate\"]),\n reg_alpha=float(model_hyperparams[\"reg_alpha\"]),\n reg_lambda=float(model_hyperparams[\"reg_lambda\"]),\n random_state=int(model_hyperparams[\"random_state\"]),\n verbosity=3) \n dask_model.client = client \n X_train, X_test = full_pipeline(X_train, X_test, config)\n dask_model.fit(X_train, y_train)\n save_model(config, dask_model)\n save_config(config)\n return dask_model, X_train, X_test\n \ndef train_xgb_regression(client, X_train, y_train, X_test, config):\n model_hyperparams = config[\"advance\"] \\\\\n [\"distributedlearner_config\"] \\\\\n [\"modelParams\"] \\\\\n [\"regressorModelParams\"] \\\\\n [\"Distributed Extreme Gradient Boosting (XGBoost)\"]\n print(\"Training XGBoost regression\")\n dask_model = xgb.dask.DaskXGBRegressor(\n tree_method=model_hyperparams[\"tree_method\"],\n n_estimators=int(model_hyperparams[\"n_estimators\"]),\n max_depth=int(model_hyperparams[\"max_depth\"]),\n gamma=float(model_hyperparams[\"gamma\"]),\n min_child_weight=float(model_hyperparams[\"min_child_weight\"]),\n subsample=float(model_hyperparams[\"subsample\"]),\n colsample_bytree=float(model_hyperparams[\"colsample_bytree\"]),\n learning_rate=float(model_hyperparams[\"learning_rate\"]),\n reg_alpha=float(model_hyperparams[\"reg_", "instruction": "", "output": "" }, { "input": "alpha\"]),\n reg_lambda=float(model_hyperparams[\"reg_lambda\"]),\n random_state=int(model_hyperparams[\"random_state\"]),\n verbosity=3)\n dask_model.client = client\n X_train, X_test = full_pipeline(X_train, X_test, config)\n dask_model.fit(X_train, y_train)\n # dask_model.fit(X_train, y_train, eval_set=[(X_test, y_test)])\n save_model(config, dask_model)\n save_config(config) \n return dask_model, X_train, X_test \n\ndef train_lgbm_regression(client, X_train, y_train, X_test, config):\n print(\"Training lightGBM regression\")\n model_hyperparams = config[\"advance\"] \\\\\n [\"distributedlearner_config\"] \\\\\n [\"modelParams\"] \\\\\n [\"regressorModelParams\"] \\\\\n [\"Distributed Light Gradient Boosting (LightGBM)\"]\n \n dask_model = lgb.DaskLGBMRegressor(\n client=client,\n n_estimators=int(model_hyperparams[\"n_estimators\"]),\n num_leaves=int(model_hyperparams[\"num_leaves\"]),\n max_depth =int(model_hyperparams[\"max_depth\"]),\n learning_rate=float(model_hyperparams[\"learning_rate\"]),\n min_child_samples=int(model_hyperparams[\"min_child_samples\"]),\n reg_alpha=int(model_hyperparams[\"reg_alpha\"]),\n subsample=float(model_hyperparams[\"subsample\"]),\n reg_lambda=int(model_hyperparams[\"reg_lambda\"]),\n colsample_bytree=float(model_hyperparams[\"colsample_bytree\"]),\n n_jobs=4,\n verbosity=3)\n\n X_train, X_test = full_pipeline(X_train, X_test, config)\n\n # print(\"before X_train.shape, y_train.shape\", \n # X_train.shape, \n # y_train.shape)\n # indices = dask_findiforestOutlier(X_train)\n # print(\"X_train type: \", type(X_train))\n # print(\"y_train type: \", type(y_train))\n # X_train, y_train = X_train.iloc[indices, :], \\\\\n # y_train.iloc[indices]\n # print(\"after X_train.shape, y_train.shape\", \n # X_train.shape, \n # y_train.shape)\n \n dask_model.fit(X_train, y_train)\n # dask_model.fit(X_train, y_train, \n # # eval_set=[(X_test,y_test),\n # # (X_train,y_train)],\n # verbose=20,eval_metric='l2')\n save_model(config, dask_model)\n save_config(config)\n return dask_model, X_train, X_test\n\ndef train_lgbm_classification(client, X_train, y_train, X_test, config):\n print(\"Training lightGBM classification\") \n model_hyperparams = config[\"advance\"] \\\\\n [\"distributedlearner_config\"] \\\\\n [\"modelParams\"] \\\\\n [\"classifierModelParams\"] \\\\\n [\"Distributed Light Gradient Boosting (LightGBM)\"]\n dask_model = lgb.DaskLGBMClassifier(\n client=client,\n num_leaves=int(model_hyperparams[\"num_leaves\"]),\n learning_rate=float(model_hyperparams[\"learning_rate\"]),\n feature_fraction=float(model_hyperparams[\"feature_fraction\"]),\n bagging_fraction=float(model_hyperparams[\"bagging_fraction\"]),\n bagging_freq=int(model_hyperparams[\"bagging_freq\"]),\n max_depth=int(model_hyperparams[\"max_depth\"]),\n min_data_in_leaf=int(model_hyperparams[\"min_data_in_leaf\"]),\n n_estimators=int(model_hyperparams[\"n_estimators\"]),\n verbosity=3)\n X_train, X_test = full_pipeline(X_train, X_test, config)\n dask_model.fit(X_train, y_train)\n # dask_model.fit(X_train, y_train, \n # eval_set=[(X_test,y_test),\n # (X_train,y_train)],\n # verbose=20,eval_metric='logloss')\n save_model(config, dask_model)\n save_config(config)\n return dask_model, X_train, X_test \n\ndef evaluate_model_classification(model, config, X_test, y_test, class_names):\n metrics = config[\"basic\"][\"scoringCriteria\"][\"classification\"]\n y_test = y_test.to_dask_array().compute()\n log = logging.getLogger('eion')\n X_test = X_test.to_dask_array(lengths=True)\n y_pred = model.predict(X_test)\n if metrics[\"Accuracy\"] == \"True\":\n # ParallelPostFit(estimator=model, scoring='accuracy')\n # score = model.score(X_test, y_test) * 100.0\n score = accuracy_score(y_test, y_pred) * 100.0\n type = 'Accuracy'\n log.info('Status:-|... Accuracy Score '+str(score))\n \n if metrics[\"Recall\"] == \"True\":\n score = recall_score(y_test, y_pred)\n type = 'Recall' \n log.info('Status:-|... Recall Score '+str(score))\n\n if metrics[\"Precision\"] == \"True\":\n score = precision_score(y_test, y_pred)\n type = 'Precision' \n log.info('Status:-|... Precision Score '+str(score))\n\n if metrics[\"F1_Score\"] == \"True\":\n score = f1_score(y_test, y_pred)\n type = 'F1' \n log.info('Status:-|... F1 Score '+str(score)) \n\n y_pred_prob = model.predict_proba(X_test)\n if len(class_names) == 2:\n roc_auc = roc_auc_score(y_test, y_pred)\n else:\n roc_auc = roc_auc_score(y_test, y_pred_prob, multi_class='ovr')\n if metrics[\"ROC_AUC\"] == \"True\":\n score = roc_auc\n type = 'ROC_AUC' \n log.info('Status:-|... ROC AUC Score '+str(score)) \n\n class_report = classification_report(y_test, y_pred, output_dict=True, target_names=class_names)\n conf_matrix = confusion_matrix(y_test, y_pred)\n return type, score, class_report, conf_matrix, roc_auc\n \ndef evaluate_model_regression(model, config, X_test, y_test):\n metrics = config[\"basic\"][\"scoringCriteria\"][\"regression\"]\n y_pred = model.predict(X_test).compute()\n y_test = y_test.to_dask_array().compute()\n X_test = X_test.to_dask_array(lengths=True)\n log = logging.getLogger('eion')\n \n mse = mean_squared_error(y_test, y_pred)\n rmse = mean_squared_error(y_test, y_pred, squared=False)\n norm_rmse = rmse * 100 / (y_test.max() - y_test.min())\n mape = mean_absolute_percentage_error(y_test, y_pred)\n r2 = r2_score(y_test, y_pred)\n mae = mean_absolute_error(y_test, y_pred)\n\n if metrics[\"Mean Squared Error\"] == \"True\": \n type = 'Mean Squared Error' \n score = mse\n log.info('Status:-|... Mean Squared Error '+str(score))\n \n if metrics[\"Root Mean Squared Error\"] == \"True\":\n type = 'Root Mean Squared Error'\n score = rmse\n log.info('Status:-|... Root Mean Square Error '+str(score))\n \n if metrics[\"R-Squared\"] == \"True\":\n type = 'R-Squared'\n score = r2 \n log.info('Status:-|... R Squared Error '+str(score))\n\n if metrics[\"Mean Absolute Error\"] == \"True\":\n type = 'Mean Absolute Error' \n score = mae \n log.info('Status:-|... Mean Absolute Error '+str(score))\n\n return type, score, mse, rmse, norm_rmse, r2, mae, mape\n\ndef save_config(config):\n deploy_location = config[\"basic\"][\"modelLocation\"]\n saved_model_file = os.path.join(deploy_location,'etc','config.json') \n print(predict_config)\n with open (saved_model_file,'w') as f:\n json.dump(predict_config, f) \n f.close() \ndef save_model(config, model):\n model_name = config[\"basic\"][\"modelName\"]\n model_version = config[\"basic\"][\"modelVersion\"]\n analysis_type = config[\"basic\"][\"analysisType\"]\n deploy_location = config[\"basic\"][\"modelLocation\"]\n if analysis_type[\"classification\"] == \"True\":\n problem_type = \"classification\"\n if analysis_type[\"regression\"] == \"True\":\n problem_type = \"regression\"\n print(\"model_name\", model_name)\n print(\"model_version\", model_version)\n print(\"problem_type\", problem_type)\n print(\"deploy_location\", deploy_location)\n file_name = problem_type + '_' + model_version + \".sav\"\n saved_model = os.path.join(deploy_location,'model',file_name)\n print(\"Save trained model to directory: \", save_model)\n with open (saved_model,'wb') as f:\n pkl.dump(model,f) \n f.close()\n predict_config['modelLocation'] = file_name\ndef save_pkl(model, filename):\n with open(filename, 'wb') as f:\n pkl.dump(model, f, \n protocol=pkl.HIGHEST_PROTOCOL)\n\n\ndef dask_findiforestOutlier(X):\n print(\"Outlier removal with Isolation Forest...\")\n isolation_forest = IsolationForest(n_estimators=100)\n with joblib.parallel_backend('dask'):\n isolation_forest.fit(X)\n y_pred_train = isolation_forest.fit_predict(X)\n mask_isoForest = y_pred_train != -1\n return mask_isoForest\n\ndef training(configFile):\n start_time = time.time()\n config = load_config_json(configFile)\n\n data_dir = config[\"basic\"][\"dataLocation\"]\n\n n_workers = int(config[\"advance\"]\n [\"distributedlearner_config\"]\n [\"n_workers\"])\n npartitions = int(config[\"advance\"]\n [\"distributedlearner_config\"]\n [\"npartitions\"])\n\n threads_per_worker = int(config[\"advance\"]\n [\"distributedlearner_config\"]\n [\"threads_per_worker\"])\n predict_config['modelName'] = config[\"basic\"][\"modelName\"]\n predict_config['modelVersion'] = config[\"basic\"][\"modelVersion\"] \n predict_config['targetFeature'] = config[\"basic\"][\"targetFeature\"]\n predict_config['trainingFeatures'] = config[\"basic\"][\"trainingFeatures\"] \n predict_config['dataLocation'] = config[\"basic\"][\"dataLocation\"] \n predict_config['n_workers'] = n_workers\n predict_config['npartitions'] = npartitions\n predict_config['threads_per_worker'] = threads_per_worker \n if config['basic']['analysisType'][\"classification\"] == \"True\":\n problemType = \"classification\"\n oProblemType = \"Distributed Classification\"\n if config['basic']['analysisType'][\"regression\"] == \"True\": \n problemType = \"regression\"\n oProblemType = \"Distributed Regression\" \n predict_config['analysisType'] = problemType\n predict_config['scoringCriteria'] = '' \n target_feature = config[\"basic\"][\"targetFeature\"]\n training_features = config[\"basic\"][\"trainingFeatures\"]\n deploy_location = config[\"basic\"][\"deployLocation\"]\n \n is_xgb_class = config[\"basic\"] \\\\\n [\"algorithms\"][\"classification\"] \\\\\n [\"Distributed Extreme Gradient Boosting (XGBoost)\"]\n\n is_lgbm_class = config[\"basic\"] \\\\\n [\"algorithms\"][\"classification\"] \\\\\n [\"Distributed Light Gradient Boosting (LightGBM)\"]\n \n is_xgb_regress = config[\"basic\"] \\\\\n [\"algorithms\"][\"regression\"] \\\\\n [\"Distributed Extreme Gradient Boosting (XGBoost)\"]\n\n is_lgbm_regress = config[\"basic\"] \\\\\n [\"algorithms\"][\"regression\"] \\\\\n [\"Distributed Light Gradient Boosting (LightGBM)\"]\n \n if is_xgb_class==\"True\" or is_xgb_regress==\"True\":\n algorithm = \"Distributed Extreme Gradient Boosting (XGBoost)\"\n predict_config['algorithm'] = algorithm\n if is_lgbm_class==\"True\" or is_lgbm_regress==\"True\":\n algorithm = \"Distributed Light Gradient Boosting (LightGBM)\"\n predict_config['algorithm'] = algorithm\n \n cluster = dask.distributed.LocalCluster(n_workers=n_workers,\n threads_per_worker=threads_per_worker,\n # dashboard_address=\"127.0.0.1:8787\"\n )\n client = dask.distributed.Client(cluster)\n df_dask = load_data_dask(data_dir, npartitions=npartitions)\n deployFolder = config[\"basic\"][\"deployLocation\"]\n modelName = config[\"basic\"][\"modelName\"]\n modelName = modelName.replace(\" \", \"_\")\n modelVersion = config[\"basic\"][\"modelVersion\"]\n modelLocation = os.path.join(deployFolder,modelName)\n os.makedirs(modelLocation,exist_ok = True)\n deployLocation = os.path.join(modelLocation,modelVersion)\n predict_config['deployLocation'] = deployLocation\n try:\n os.makedirs(deployLocation)\n except OSError as e:\n shutil.rmtree(deployLocation)\n time.sleep(2)\n os.makedirs(deployLocation)\n modelFolderLocation = os.path.join(deployLocation,'model')\n try:\n os.makedirs(modelFolderLocation)\n except OSError as e: \n print(\"\\\\nModel Folder Already Exists\")\n etcFolderLocation = os.path.join(deployLocation,'etc')\n try:\n os.makedirs(etcFolderLocation)\n except OSError as e: \n print(\"\\\\ETC Folder Already Exists\") \n logFolderLocation = os.path.join(deployLocation,'log')\n try:\n os.makedirs(logFolderLocation)\n except OSError as e:\n print(\"\\\\nLog Folder Already Exists\")\n logFileName=os.path.join(logFolderLocation,'model_training_", "instruction": "", "output": "" }, { "input": "logs.log') \n outputjsonFile=os.path.join(deployLocation,'etc','output.json') \n filehandler = logging.FileHandler(logFileName, 'w','utf-8')\n formatter = logging.Formatter('%(message)s')\n filehandler.setFormatter(formatter)\n log = logging.getLogger('eion')\n log.propagate = False\n for hdlr in log.handlers[:]: # remove the existing file handlers\n if isinstance(hdlr,logging.FileHandler):\n log.removeHandler(hdlr)\n log.addHandler(filehandler)\n log.setLevel(logging.INFO)\n log.info('Status:-|... Distributed Learning Started') \n config['basic']['modelLocation'] = deployLocation\n # Get input for EDA\n # descr, corr = get_dask_eda(df_dask=df_dask)\n #print(descr)\n # print(corr)\n #print(df_dask.columns)\n #print(\"target feature\", target_feature)\n df_dask = df_dask.dropna(subset=[target_feature])\n if is_xgb_class == \"True\" or is_lgbm_class == \"True\":\n df_dask = df_dask.categorize(columns=[target_feature])\n df_dask[target_feature] = df_dask[target_feature].astype('category')\n df_dask[target_feature] = df_dask[target_feature].cat.as_known()\n label_mapping = dict(enumerate(df_dask[target_feature].cat.categories))\n df_dask[target_feature] = df_dask[target_feature].cat.codes\n label_mapping_file =os.path.join(deployLocation,'etc','label_mapping.json') \n with open(label_mapping_file, 'w') as f:\n json.dump(label_mapping, f)\n \n if config[\"advance\"][\"profiler\"][\"removeDuplicate\"] == \"True\":\n df_dask = df_dask.drop_duplicates()\n \n # Need to dropna for case of categoricalFillMethod\n # if config[\"advance\"][\"profiler\"][\"numericalFillMethod\"][\"Drop\"] == \"True\":\n # df_dask = df_dask.dropna()\n trainingFeatures = config[\"basic\"][\"trainingFeatures\"].split(',')\n if target_feature not in trainingFeatures:\n trainingFeatures.append(target_feature)\n df_dask = df_dask[trainingFeatures]\n y = df_dask[target_feature]\n X = df_dask.drop(target_feature, axis=1)\n \n print(\"after X.shape, y.shape\", X.shape, y.shape)\n\n X_train, X_test, y_train, y_test = dask_ml.model_selection.train_test_split(X, y,\n test_size=0.2, random_state=0)\n trainingFeatures = config[\"basic\"][\"trainingFeatures\"].split(',') \n \n outputJson = None\n conf_matrix_dict = {}\n train_conf_matrix_dict = {} \n try: \n if is_xgb_class == \"True\":\n modelName = 'Distributed Extreme Gradient Boosting (XGBoost)'\n dask_model, X_train, X_test = train_xgb_classification(client, X_train, y_train, X_test, config)\n class_names = list(label_mapping.values())\n _, _, train_class_report, train_conf_matrix, train_roc_auc = evaluate_model_classification(dask_model, config,\n X_train, y_train, class_names) \n scoringCreteria,score, class_report, conf_matrix, roc_auc = evaluate_model_classification(dask_model, config,\n X_test, y_test, class_names)\n for i in range(len(conf_matrix)):\n conf_matrix_dict_1 = {} \n for j in range(len(conf_matrix[i])):\n conf_matrix_dict_1['pre:' + str(class_names[j])] = int(conf_matrix[i][j])\n conf_matrix_dict['act:'+ str(class_names[i])] = conf_matrix_dict_1\n\n for i in range(len(train_conf_matrix)):\n train_conf_matrix_dict_1 = {} \n for j in range(len(train_conf_matrix[i])):\n train_conf_matrix_dict_1['pre:' + str(class_names[j])] = int(train_conf_matrix[i][j])\n train_conf_matrix_dict['act:'+ str(class_names[i])] = train_conf_matrix_dict_1\n # print(roc_auc)\n outputJson = {'status':'SUCCESS','data':{'ModelType':oProblemType,\\\\\n 'deployLocation':deployLocation,'BestModel':modelName,'BestScore':score,'ScoreType':scoringCreteria,\\\\\n 'matrix':{'ConfusionMatrix':conf_matrix_dict,'ClassificationReport':class_report,'ROC_AUC_SCORE':roc_auc},\\\\\n 'trainmatrix':{'ConfusionMatrix':train_conf_matrix_dict,'ClassificationReport':train_class_report,'ROC_AUC_SCORE':train_roc_auc},\\\\\n 'featuresused':trainingFeatures,'targetFeature':target_feature,'EvaluatedModels':[{'Model':modelName,'Score':score}],\n 'LogFile':logFileName}} \n if is_lgbm_class == \"True\":\n modelName = 'Distributed Light Gradient Boosting (LightGBM)' \n dask_model, X_train, X_test = train_lgbm_classification(client, X_train, y_train, X_test, config)\n class_names = list(label_mapping.values())\n _, _, train_class_report, train_conf_matrix, train_roc_auc = evaluate_model_classification(dask_model, config,\n X_train, y_train, class_names)\n scoringCreteria,score, class_report, conf_matrix, roc_auc = evaluate_model_classification(dask_model, config,\n X_test, y_test, class_names)\n for i in range(len(conf_matrix)):\n conf_matrix_dict_1 = {} \n for j in range(len(conf_matrix[i])):\n conf_matrix_dict_1['pre:' + str(class_names[j])] = int(conf_matrix[i][j])\n conf_matrix_dict['act:'+ str(class_names[i])] = conf_matrix_dict_1\n\n for i in range(len(train_conf_matrix)):\n train_conf_matrix_dict_1 = {} \n for j in range(len(train_conf_matrix[i])):\n train_conf_matrix_dict_1['pre:' + str(class_names[j])] = int(train_conf_matrix[i][j])\n train_conf_matrix_dict['act:'+ str(class_names[i])] = train_conf_matrix_dict_1\n\n outputJson = {'status':'SUCCESS','data':{'ModelType':oProblemType,\\\\\n 'deployLocation':deployLocation,'BestModel':modelName,'BestScore':score,'ScoreType':scoringCreteria,\\\\\n 'matrix':{'ConfusionMatrix':conf_matrix_dict,'ClassificationReport':class_report,'ROC_AUC_SCORE':roc_auc},\\\\\n 'trainmatrix':{'ConfusionMatrix':train_conf_matrix_dict,'ClassificationReport':train_class_report,'ROC_AUC_SCORE':train_roc_auc},\\\\\n 'featuresused':trainingFeatures,'targetFeature':target_feature,'EvaluatedModels':[{'Model':modelName,'Score':score}],\n 'LogFile':logFileName}} \n if is_xgb_regress == \"True\":\n modelName = 'Distributed Extreme Gradient Boosting (XGBoost)' \n dask_model, X_train, X_test = train_xgb_regression(client, X_train, y_train, X_test, config)\n _, _, train_mse, train_rmse, train_norm_rmse, train_r2, train_mae, train_mape = evaluate_model_regression(dask_model, config, \n X_train, y_train)\n scoringCreteria, score, mse, rmse, norm_rmse, r2, mae, mape = evaluate_model_regression(dask_model, config, \n X_test, y_test)\n outputJson = {'status':'SUCCESS','data':{'ModelType':oProblemType,\\\\\n 'deployLocation':deployLocation,'BestModel':modelName,'BestScore':score,'ScoreType':scoringCreteria,\\\\\n 'matrix':{'MAE':mae,'R2Score':r2,'MSE':mse,'MAPE':mape,'RMSE':rmse,'Normalised RMSE(%)':norm_rmse}, \\\\\n 'trainmatrix':{'MAE':train_mae,'R2Score':train_r2,'MSE':train_mse,'MAPE':train_mape,'RMSE':train_rmse,'Normalised RMSE(%)':train_norm_rmse}, \\\\\n 'featuresused':trainingFeatures,'targetFeature':target_feature,'EvaluatedModels':[{'Model':modelName,'Score':score}],\n 'LogFile':logFileName}} \n if is_lgbm_regress == \"True\":\n modelName = 'Distributed Light Gradient Boosting (LightGBM)' \n dask_model, X_train, X_test = train_lgbm_regression(client, X_train, y_train, X_test, config) \n _, _, train_mse, train_rmse, train_norm_rmse, train_r2, train_mae, train_mape = evaluate_model_regression(dask_model, config, \n X_train, y_train)\n scoringCreteria, score, mse, rmse, norm_rmse, r2, mae, mape = evaluate_model_regression(dask_model, config, \n X_test, y_test)\n outputJson = {'status':'SUCCESS','data':{'ModelType':oProblemType,\\\\\n 'deployLocation':deployLocation,'BestModel':modelName,'BestScore':score,'ScoreType':scoringCreteria,\\\\\n 'matrix':{'MAE':mae,'R2Score':r2,'MSE':mse,'MAPE':mape,'RMSE':rmse,'Normalised RMSE(%)':norm_rmse}, \\\\\n 'trainmatrix':{'MAE':train_mae,'R2Score':train_r2,'MSE':train_mse,'MAPE':train_mape,'RMSE':train_rmse,'Normalised RMSE(%)':train_norm_rmse}, \\\\\n 'featuresused':trainingFeatures,'targetFeature':target_feature,'EvaluatedModels':[{'Model':modelName,'Score':score}],\n 'LogFile':logFileName}} \n src = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','utilities','dl_aion_predict.py')\n shutil.copy2(src,deployLocation)\n os.rename(os.path.join(deployLocation,'dl_aion_predict.py'),os.path.join(deployLocation,'aion_predict.py')) \n \n except Exception as e:\n outputJson = {\"status\":\"FAIL\",\"message\":str(e)}\n print(e)\n client.close()\n cluster.close()\n log.info('Status:-|... Distributed Learning Completed') \n with open(outputjsonFile, 'w') as f:\n json.dump(outputJson, f)\n f.close()\n output_json = json.dumps(outputJson) \n log.info('aion_learner_status:'+str(output_json)) \n for hdlr in log.handlers[:]: # remove the existing file handlers\n if isinstance(hdlr,logging.FileHandler):\n hdlr.close()\n log.removeHandler(hdlr)\n print(\"\\\\n\")\n print(\"aion_learner_status:\",output_json)\n print(\"\\\\n\")\n end_time = time.time() \n print(\"--- %s processing time (sec) ---\" % (end_time - start_time)) '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n''' '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom lifelines import KaplanMeierFitter, CoxPHFitter\nfrom lifelines.utils import datetimes_to_durations\nimport logging\nimport numpy as np\nimport re\nimport sys\nimport os\n\n\nclass SurvivalAnalysis(object):\n\n def __init__(self, df, pipe, method, event_column, duration_column, filterExpression, train_features_type,start=None, end=None):\n pd.options.display.width = 30\n self.df = df\n self.pipe = pipe\n self.train_features_type = train_features_type\n self.filterExpression = filterExpression\n self.covariateExpression = filterExpression\n self.method = method\n self.event_column = event_column\n if start is not None and end is not None:\n self.df['duration'], _ = datetimes_to_durations(start, end)\n self.duration_column = 'duration'\n else:\n self.duration_column = duration_column\n self.models = []\n self.score = 0\n self.log = logging.getLogger('eion')\n self.plots = []\n\n def transform_filter_expression(self, covariate, covariate_input):\n '''\n Filter expression given by user will be encoded if it is categorical and if it is a numerical feature that\n is normalised in data profiler, in filter expression feature also it will be converted to normalised value\n '''\n cols = list(self.df.columns)\n if self.duration_column in cols:\n cols.remove(self.duration_column)\n if self.event_column in cols:\n cols.remove(self.event_column)\n df_filter = pd.DataFrame([{covariate:covariate_input}], columns=cols)\n df_filter[covariate] = df_filter[covariate].astype(self.train_features_type[covariate])\n df_transform_array = self.pipe.transform(df_filter)\n df_transform = pd.DataFrame(df_transform_array, columns=cols)\n return df_transform[covariate].iloc[0]\n\n def learn(self):\n self.log.info('\\\\n---------- SurvivalAnalysis learner has started ----------')\n self.log.info('\\\\n---------- SurvivalAnalysis learner method is \"%s\" ----------' % self.method)\n\n if self.method.lower() in ['kaplanmeierfitter', 'kaplanmeier', 'kaplan-meier', 'kaplan meier', 'kaplan', 'km',\n 'kmf']:\n self.log.info('\\\\n---------- SurvivalAnalysis learner method \"%s\"", "instruction": "", "output": "" }, { "input": "has started ----------' % self.method)\n kmf = KaplanMeierFitter()\n T = self.df[self.duration_column]\n E = self.df[self.event_column]\n self.log.info('\\\\n T : \\\\n%s' % str(T))\n self.log.info('\\\\n E : \\\\n%s' % str(E))\n K = kmf.fit(T, E)\n kmf_sf = K.survival_function_\n kmf_sf_json = self.survival_probability_to_json(kmf_sf)\n self.models.append(K)\n if isinstance(self.filterExpression, str):\n df_f, df_n, refined_filter_expression = self.parse_filterExpression()\n kmf1 = KaplanMeierFitter()\n kmf2 = KaplanMeierFitter()\n self.log.info(\n '\\\\n---------- SurvivalAnalysis learner \"%s\" fitting for filter expression has started----------' % self.method)\n T1 = df_f[self.duration_column]\n E1 = df_f[self.event_column]\n T2 = df_n[self.duration_column]\n E2 = df_n[self.event_column]\n kmf1.fit(T1, E1)\n fig, ax = plt.subplots(1, 1)\n ax = kmf1.plot_survival_function(ax=ax, label='%s' % refined_filter_expression)\n self.log.info(\n '\\\\n---------- SurvivalAnalysis learner \"%s\" fitting for filter expression has ended----------' % self.method)\n plt.title(\"KM Survival Functions - Filter vs Negation\")\n self.log.info(\n '\\\\n---------- SurvivalAnalysis learner \"%s\" fitting for negation has started----------' % self.method)\n kmf2.fit(T2, E2)\n ax = kmf2.plot_survival_function(ax=ax, label='~%s' % refined_filter_expression)\n self.log.info(\n '\\\\n---------- SurvivalAnalysis learner \"%s\" fitting for negation has ended----------' % self.method)\n self.models.extend([kmf1, kmf2])\n\n kmf1_sf = kmf1.survival_function_\n kmf2_sf = kmf2.survival_function_\n kmf1_sf_json = self.survival_probability_to_json(kmf1_sf)\n self.plots.append(fig)\n self.log.info('\\\\n---------- SurvivalAnalysis learner method \"%s\" has ended ----------' % self.method)\n self.log.info('\\\\n---------- SurvivalAnalysis learner has ended ----------')\n self.log.info('Status:- |... Algorithm applied: KaplanMeierFitter')\n return kmf1_sf_json\n else:\n fig, ax = plt.subplots(1, 1)\n ax = kmf_sf.plot(ax=ax)\n plt.title(\"KM Survival Functions\")\n self.plots.append(fig)\n self.log.info('\\\\n---------- SurvivalAnalysis learner method \"%s\" has ended ----------' % self.method)\n self.log.info('\\\\n---------- SurvivalAnalysis learner has ended ----------')\n self.log.info('Status:- |... Algorithm applied: KaplanMeierFitter')\n return kmf_sf_json\n\n\n elif self.method.lower() in ['coxphfitter', 'coxregression', 'cox-regression', 'cox regression',\n 'coxproportionalhazard', 'coxph', 'cox', 'cph']:\n self.log.info('\\\\n---------- SurvivalAnalysis learner method \"%s\" has started ----------' % self.method)\n\n cph = CoxPHFitter(penalizer=0.1)\n self.df = self.drop_constant_features(self.df)\n C = cph.fit(self.df, self.duration_column, self.event_column)\n self.models.append(C)\n cph_sf = C.baseline_survival_\n self.score = C.score(self.df, scoring_method=\"concordance_index\")\n self.log.info(\n '\\\\n---------- SurvivalAnalysis learner \"%s\" score is \"%s\"----------' % (self.method, str(self.score)))\n cph_sf_json = self.survival_probability_to_json(cph_sf)\n if isinstance(self.covariateExpression, str):\n covariate, covariate_inputs, covariate_values = self.parse_covariateExpression()\n fig, (ax1, ax2) = plt.subplots(1, 2)\n fig.tight_layout()\n ax1 = C.plot(ax=ax1, hazard_ratios=True)\n self.log.info('\\\\n Summary : \\\\n%s' % str(C.summary))\n ax1.set_title(\"COX hazard ratio\")\n ax2 = C.plot_partial_effects_on_outcome(covariate, covariate_values, ax=ax2)\n mylabels = [covariate + '=' + str(x) for x in covariate_inputs]\n mylabels.append('baseline')\n ax2.legend(labels=mylabels)\n ax2.set_title(\"Covariate Plot\")\n self.plots.append(fig)\n else:\n fig = plt.figure()\n ax1 = C.plot(hazard_ratios=True)\n self.log.info('\\\\n Summary : \\\\n%s' % str(C.summary))\n plt.title(\"COX hazard ratio\")\n self.plots.append(fig)\n self.log.info('\\\\n---------- SurvivalAnalysis learner method \"%s\" has ended ----------' % self.method)\n self.log.info('\\\\n---------- SurvivalAnalysis learner has ended ----------')\n self.log.info('Status:- |... Algorithm applied: CoxPHFitter')\n return cph_sf_json\n\n def parse_filterExpression(self):\n import operator\n self.log.info('\\\\n---------- Filter Expression parsing has started ----------')\n self.log.info('Filter Expression provided : %s' % self.filterExpression)\n self.log.info('Shape before filter : %s' % str(self.df.shape))\n f = self.filterExpression.split('&')\n f = list(filter(None, f))\n if len(f) == 1:\n p = '[<>=!]=?'\n op = re.findall(p, self.filterExpression)[0]\n covariate, covariate_input = [x.strip().strip('\\\\'').strip('\\\\\"') for x in self.filterExpression.split(op)]\n refined_filter_expression = covariate + op + covariate_input\n self.log.info('Final refined filter : %s' % refined_filter_expression)\n ops = {\"==\": operator.eq, \">\": operator.gt, \"<\": operator.lt, \">=\": operator.ge, \"<=\": operator.le,\n \"!=\": operator.ne}\n try:\n fv = self.transform_filter_expression(covariate, covariate_input)\n df_f = self.df[ops[op](self.df[covariate], fv)]\n self.log.info('Shape after filter : %s' % str(df_f.shape))\n df_n = self.df[~self.df[covariate].isin(df_f[covariate])]\n self.log.info('Shape of negation : %s' % str(df_n.shape))\n self.log.info('---------- Filter Expression has ended ----------')\n return df_f, df_n, refined_filter_expression\n except Exception:\n self.log.info('\\\\n-----> Filter Expression parsing encountered error!!!')\n exc_type, exc_obj, exc_tb = sys.exc_info()\n if exc_type == IndexError or ValueError or KeyError:\n self.log.info('----->Given filter expression '+ self.filterExpression +' is invalid')\n self.log.info('Valid examples are \"A>100\", \"B==category1\", \"C>=10 && C<=20\" etc..')\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n self.log.info(str(exc_type)+' '+str(fname) + ' ' + str(exc_tb.tb_lineno))\n raise Exception(str(exc_type)+str(exc_obj))\n else:\n full_f = []\n try:\n for filterExpression in f:\n p = '[<>=!]=?'\n op = re.findall(p, filterExpression)[0]\n covariate, covariate_input = [x.strip().strip('\\\\'').strip('\\\\\"') for x in filterExpression.split(op)]\n full_f.append(covariate + op + covariate_input)\n ops = {\"==\": operator.eq, \">\": operator.gt, \"<\": operator.lt, \">=\": operator.ge, \"<=\": operator.le,\n \"!=\": operator.ne}\n\n fv = self.transform_filter_expression(covariate, covariate_input)\n df_f = self.df[ops[op](self.df[covariate], fv)]\n df_n = self.df[~self.df[covariate].isin(df_f[covariate])]\n \n refined_filter_expression = \" & \".join(full_f)\n self.log.info('Final refined filter : %s' % refined_filter_expression)\n self.log.info('Shape after filter : %s' % str(df_f.shape))\n self.log.info('Shape of negation : %s' % str(df_n.shape))\n self.log.info('---------- Filter Expression has ended ----------')\n return df_f, df_n, refined_filter_expression\n # except (IndexError, ValueError, KeyError):\n except Exception:\n self.log.info('\\\\n-----> Filter Expression parsing encountered error!!!')\n exc_type, exc_obj, exc_tb = sys.exc_info()\n if exc_type == IndexError or ValueError or KeyError:\n self.log.info('----->Given filter expression '+ self.filterExpression +' is invalid')\n self.log.info('Valid examples are \"A>100\", \"B==category1\", \"C>=10 && C<=20\" etc..')\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n self.log.info(str(exc_type)+' '+str(fname) + ' ' + str(exc_tb.tb_lineno))\n raise Exception(str(exc_type)+str(exc_obj))\n\n def parse_covariateExpression(self):\n self.log.info('\\\\n---------- Covariate Expression parsing has started ----------')\n self.log.info('\\\\n Covariate Expression provided : %s' % self.covariateExpression)\n import ast\n p = '[=:]'\n try:\n op = re.findall(p, self.covariateExpression)[0]\n covariate, covariate_inputs = [x.strip().strip('\\\\'').strip('\\\\\"') for x in\n self.covariateExpression.split(op)]\n covariate_inputs = ast.literal_eval(covariate_inputs)\n covariate_values = [self.transform_filter_expression(covariate, x) for x in covariate_inputs]\n self.log.info('\\\\n---------- Covariate Expression parsing has ended ----------')\n return covariate, covariate_inputs, covariate_values\n except Exception:\n self.log.info('\\\\n-----> Covariate Expression parsing encountered error!!!')\n exc_type, exc_obj, exc_tb = sys.exc_info()\n if exc_type == IndexError or ValueError or KeyError:\n self.log.info('----->Given covariate expression '+ self.filterExpression +' is invalid')\n self.log.info(\"\\\\n Valid examples are A=['Yes','No'] or B=[100,500,1000]\")\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n self.log.info(str(exc_type)+' '+str(fname) + ' ' + str(exc_tb.tb_lineno))\n raise Exception(str(exc_type)+str(exc_obj))\n\n def survival_probability_to_json(self, sf):\n '''\n sf = Survival function i.e. KaplanMeierFitter.survival_function_ or CoxPHFitter.baseline_survival_\n returns json of survival probabilities\n '''\n sf = sf[sf.columns[0]].apply(lambda x: \"%4.2f\" % (x * 100))\n self.log.info('\\\\n Survival probabilities : \\\\n%s' % str(sf))\n sf = sf.reset_index()\n sf = sf.sort_values(sf.columns[0])\n sf_json = sf.to_json(orient='records')\n self.log.info('\\\\n Survival probability json : \\\\n%s' % str(sf_json))\n\n return sf_json\n\n def drop_constant_features(self, df):\n dropped = []\n for col in df.columns:\n if (len(df[col].unique()) == 1) and (col not in [self.duration_column, self.event_column]):\n df.drop(col, inplace=True, axis=1)\n dropped.append(col)\n if len(dropped) != 0:\n self.log.info('\\\\n Dropping constant features %s' % str(col))\n self.log.info('\\\\n After dropping constant features : \\\\n%s' % str(df))\n return df\n\n def predict(self):\n if self.method == 'KaplanMeierFitter':\n return self.model.predict(self.test[self.duration_column])\n\n\n elif self.method == 'CoxPHFitter':\n res = []\n for idx, row in self.test.iterrows():\n res.append(\n self.model.predict_survival_function(self.test, times=row[self.model.duration_col])[idx].values[0])\n return pd.DataFrame(res)\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n''' import os\nfrom typing import List\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n\ndef split_csv(fp: str = \"./data/creditcard.csv\", fp_dest: str = \"./data\",\n name: str = \"credit\", test_size: int = 0.5, strat_col: str = \"Class\") -> None:\n \"\"\"Splits a csv file in two, in a stratified fashion.\n Format for filenames will be `{name}0.csv and `{name}1.csv`.\n\n :param fp: The path at which the csv file is located.\n :type fp: str\n :param fp_dest: The path to save the train and test files.\n :type fp_dest: str\n :param name: The prefix for the files.\n ", "instruction": "", "output": "" }, { "input": ":type name: str\n :param test_size: The fraction of total size for the test file.\n :type test_size: float\n :param strat_col: The column in the original csv file to stratify.\n\n :return: None, two files located at `fp_dest`.\n :rtype: NoneType\n \"\"\"\n if not os.path.isfile(fp):\n raise FileNotFoundError(f\"File at {fp} does not exist.\")\n if not os.path.isdir(fp_dest):\n raise ValueError(f\"Directory at {fp_dest} does not exist.\")\n if not 0 < test_size < 1:\n raise ValueError(f\"{test_size} is not in interval 0 < x < 1.\")\n\n df = pd.read_csv(fp)\n\n if not (strat_col in df.columns):\n raise ValueError(f\"Stratify column {strat_col} not found in DataFrame.\")\n\n train, test = train_test_split(df, test_size=test_size, stratify=df[strat_col])\n\n train.to_csv(f\"{fp_dest}/{name}0.csv\", index=False)\n test.to_csv(f\"{fp_dest}/{name}1.csv\", index=False)\n\n\ndef rounded_dict(d: dict, precision: int = 6) -> dict:\n \"\"\"Rounds all values in a dictionairy to `precision` digits after the decimal point.\n\n :param d: Dictionairy containing only floats or ints as values\n :type d: dict\n\n :return: Rounded dictionairy\n :rtype: dict\n \"\"\"\n return {k: round(v, precision) for k, v in d.items()}\n\n\ndef imbalance_ratio(y: np.ndarray, min_classes: List[int] = [1], maj_classes: List[int] = [0]) -> float:\n \"\"\"Calculates imbalance ratio of minority class(es) and majority class(es).\n\n :param y: y-vector with labels.\n :type y: np.ndarray\n :param min_classes: The labels of the minority classes\n :type min_classes: list\n :param maj_classes: The labels of the minority classes\n :type maj_classes: list\n\n :return: The imbalance ratio\n :rtype: float\n \"\"\"\n return np.isin(y, min_classes).sum() / np.isin(y, maj_classes).sum()\n \nimport os\nimport numpy as np\nimport pandas as pd\nimport time\n\nfrom DeepRL.agents.ddqn import TrainDDQN\nfrom DeepRL.agents.dqn import TrainDQN\nfrom DeepRL.dataprocess import get_train_test_val\nfrom DeepRL.utils import rounded_dict\nfrom tensorflow.keras.layers import Dense, Dropout\n\nfrom sklearn.model_selection import train_test_split\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\" # CPU is faster than GPU on structured data\n\ndef PredictRL(input_csv_file, model_load_path, RL_hparams_config_file, RL_Algo_Name):\n\n if not (os.path.exists(model_load_path)):\n os.makedirs(model_load_path)\n\n episodes = RL_hparams_config_file['DeepRL']['episodes'] # Total number of episodes\n warmup_steps = RL_hparams_config_file['DeepRL']['warmup_steps'] # Amount of warmup steps to collect data with random policy\n memory_length = warmup_steps # Max length of the Replay Memory\n batch_size = RL_hparams_config_file['DeepRL']['batch_size']\n collect_steps_per_episode = RL_hparams_config_file['DeepRL']['collect_steps_per_episode']\n collect_every = RL_hparams_config_file['DeepRL']['collect_every']\n\n target_update_period = RL_hparams_config_file['DeepRL']['target_update_period'] # Period to overwrite the target Q-network with the default Q-network\n target_update_tau = RL_hparams_config_file['DeepRL']['target_update_tau'] # Soften the target model update\n n_step_update = RL_hparams_config_file['DeepRL']['n_step_update']\n\n learning_rate = RL_hparams_config_file['DeepRL']['learning_rate'] # Learning rate\n gamma = RL_hparams_config_file['DeepRL']['gamma'] # Discount factor\n min_epsilon = RL_hparams_config_file['DeepRL']['min_epsilon'] # Minimal and final chance of choosing random action\n decay_episodes = episodes // 10 # Number of episodes to decay from 1.0 to `min_epsilon``\n\n #path = '/home/renith/Renith/Project/AION/Reinforcement/RL_Classification/Code/rl_text_classification/telemetry_data.csv'\n\n data = pd.read_csv(input_csv_file)\n\n device5 = data[data['device_id'] == \"Device_1\"]\n device5 = device5.drop(['device_id'], axis = 1)\n device5.reset_index(drop=True, inplace=True)\n\n target_value = []\n for i in range(device5['device_status'].shape[0]):\n if(device5['device_status'][i] == \"NORMAL\"):\n target_value.append(0.0)\n else:\n target_value.append(1.0)\n\n device5['target'] = target_value\n device5 = device5.drop(['device_status'], axis = 1)\n\n X_test = device5.iloc[:,1:-1]\n y_test = device5.iloc[:,-1]\n\n X_test = X_test.astype(np.float32)\n y_test = y_test.astype(np.int32)\n\n #Normalization\n mini, maxi = X_test.min(axis=0), X_test.max(axis=0)\n X_test -= mini\n X_test /= maxi - mini\n\n min_class = [1] #Minority class\n maj_class = [0] #Majority class\n\n #X_train, X_test, y_train, y_test = train_test_split(X_train, y_train, test_size=0.8, stratify=y_train)\n\n #X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, stratify=y_train)\n\n #X_train = np.array(X_train)\n #y_train = np.array(y_train)\n #X_val = np.array(X_val)\n #y_val = np.array(y_val)\n X_test = np.array(X_test)\n y_test = np.array(y_test)\n\n #X_train, y_train, X_test, y_test, X_val, y_val = get_train_test_val(X_train.values, y_train.values, X_test.values, y_test.values,\n # min_class, maj_class, val_frac=0.2)\n\n layers = [Dense(128, activation=\"relu\"),\n Dense(64, activation=\"relu\"),\n Dense(32, activation=\"relu\"),\n Dense(2, activation=None)]\n\n if(RL_Algo_Name == \"DDQN\"):\n model = TrainDDQN(episodes, warmup_steps, learning_rate, gamma, min_epsilon, decay_episodes, target_update_period=target_update_period,\n target_update_tau=target_update_tau, batch_size=batch_size, collect_steps_per_episode=collect_steps_per_episode,\n memory_length=memory_length, collect_every=collect_every, n_step_update=n_step_update, model_path=model_load_path)\n elif(RL_Algo_Name == \"DQN\"):\n model = TrainDQN(episodes, warmup_steps, learning_rate, gamma, min_epsilon, decay_episodes, target_update_period=target_update_period,\n target_update_tau=target_update_tau, batch_size=batch_size, collect_steps_per_episode=collect_steps_per_episode,\n memory_length=memory_length, collect_every=collect_every, n_step_update=n_step_update, model_path=model_load_path)\n\n model.compile_model(X_test, y_test, layers)\n model.q_net.summary()\n\n #model.train(X_val, y_val, \"F1\")\n\n #print(\"Training Ended !!!!\")\n\n stats = model.evaluate(X_test, y_test)\n print(rounded_dict(stats))\n #stats = model.evaluate(X_train, y_train)\n #print(rounded_dict(stats))\n import os\nfrom typing import List, Tuple\n\nimport numpy as np\nfrom pandas import read_csv\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nfrom tensorflow.keras.datasets import cifar10, fashion_mnist, imdb, mnist\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\n\nTrainTestData = Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]\nTrainTestValData = Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]\n\n\ndef load_image(data_source: str) -> TrainTestData:\n \"\"\"\n Loads one of the following image datasets: {mnist, famnist, cifar10}.\n Normalizes the data. Returns X and y for both train and test datasets.\n Dtypes of X's and y's will be `float32` and `int32` to be compatible with `tf_agents`.\n\n :param data_source: Either mnist, famnist or cifar10\n :type data_source: str\n\n :return: Tuple of (X_train, y_train, X_test, y_test) containing original split of train/test\n :rtype: tuple\n \"\"\"\n reshape_shape = -1, 28, 28, 1\n\n if data_source == \"mnist\":\n (X_train, y_train), (X_test, y_test) = mnist.load_data()\n\n elif data_source == \"famnist\":\n (X_train, y_train), (X_test, y_test) = fashion_mnist.load_data()\n\n elif data_source == \"cifar10\":\n (X_train, y_train), (X_test, y_test) = cifar10.load_data()\n reshape_shape = -1, 32, 32, 3\n\n else:\n raise ValueError(\"No valid `data_source`.\")\n\n X_train = X_train.reshape(reshape_shape).astype(np.float32) # Float32 is the expected dtype for the observation spec in the env\n X_test = X_test.reshape(reshape_shape).astype(np.float32)\n\n X_train /= 255 # /= is not available when casting int to float: https://stackoverflow.com/a/48948461/10603874\n X_test /= 255\n\n y_train = y_train.reshape(y_train.shape[0], ).astype(np.int32)\n y_test = y_test.reshape(y_test.shape[0], ).astype(np.int32)\n\n return X_train, y_train, X_test, y_test\n\n\ndef load_csv(fp_train: str, fp_test: str, label_col: str, drop_cols: List[str], normalization: bool = False) -> TrainTestData:\n \"\"\"\n Loads any csv-file from local filepaths. Returns X and y for both train and test datasets.\n Option to normalize the data with min-max normalization.\n Only csv-files with float32 values for the features and int32 values for the labels supported.\n Source for dataset: https://mimic-iv.mit.edu/\n\n :param fp_train: Location of the train csv-file\n :type fp_train: str\n :param fp_test: Location of the test csv-file\n :type fp_test: str\n :param label_col: The name of the column containing the labels of the data\n :rtype label_col: str\n :param drop_cols: List of the names of the columns to be dropped. `label_col` gets dropped automatically\n :rtype drop_cols: List of strings\n :param normalization: Normalize the data with min-max normalization?\n :type normalization: bool\n\n :return: Tuple of (X_train, y_train, X_test, y_test) containing original split of train/test\n :rtype: Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]\n \"\"\"\n if not os.path.isfile(fp_train):\n raise FileNotFoundError(f\"`fp_train` {fp_train} does not exist.\")\n if not os.path.isfile(fp_test):\n raise FileNotFoundError(f\"`fp_test` {fp_test} does not exist.\")\n if not isinstance(normalization, bool):\n raise TypeError(f\"`normalization` must be of type `bool`, not {type(normalization)}\")\n\n X_train = read_csv(fp_train).astype(np.float32) # DataFrames directly converted to float32\n X_test = read_csv(fp_test).astype(np.float32)\n\n y_train = X_train[label_col].astype(np.int32)\n y_test = X_test[label_col].astype(np.int32)\n X_train.drop(columns=drop_cols + [label_col], inplace=True) # Dropping cols and label column\n X_test.drop(columns=drop_cols + [label_col], inplace=True)\n\n # Other data sources are already normalized. RGB values are always in range 0 to 255.\n if normalization:\n mini, maxi = X_train.min(axis=0), X_train.max(axis=0)\n X_train -= mini\n X_train /= maxi - mini\n X_test -= mini\n X_test /= maxi - mini\n\n return X_train.values, y_train.values, X_test.values, y_test.values # Numpy arrays\n\n\ndef load_imdb(config: Tuple[int, int] = (5_000, 500)) -> TrainTestData:\n \"\"\"Loads the IMDB dataset. Returns X and y for both train and test datasets.\n\n :param config: Tuple of number of most frequent words and max length of each sequence.\n :type config: str\n\n :return: Tuple of (X_train, y_train, X_test, y_test) containing original split of train/test\n :rtype: tuple\n \"\"\"\n if not isinstance(config, (tuple, list)):\n raise TypeError(f\"{type(config)} is no valid datatype for `config`.\")\n if len(config) != 2:\n raise ValueError(\"Tuple length of `config` must be 2.\")\n if not all(i > 0 for i in config):\n raise ValueError(\"All integers of `config` must be > 0.\")\n\n (X_train,", "instruction": "", "output": "" }, { "input": "y_train), (X_test, y_test) = imdb.load_data(num_words=config[0])\n\n X_train = pad_sequences(X_train, maxlen=config[1])\n X_test = pad_sequences(X_test, maxlen=config[1])\n\n y_train = y_train.astype(np.int32)\n y_test = y_test.astype(np.int32)\n\n return X_train, y_train, X_test, y_test\n\n\ndef get_train_test_val(X_train: np.ndarray, y_train: np.ndarray, X_test: np.ndarray, y_test: np.ndarray, min_classes: List[int],\n maj_classes: List[int], imb_ratio: float = None, imb_test: bool = True, val_frac: float = 0.25,\n print_stats: bool = True) -> TrainTestValData:\n \"\"\"\n Imbalances data and divides the data into train, test and validation sets.\n The imbalance rate of each individual dataset is approx. the same as the given `imb_ratio`.\n\n :param X_train: The X_train data\n :type X_train: np.ndarray\n :param y_train: The y_train data\n :type y_train: np.ndarray\n :param X_test: The X_test data\n :type X_test: np.ndarray\n :param y_test: The y_test data\n :type y_test: np.ndarray\n :param min_classes: List of labels of all minority classes\n :type min_classes: list\n :param maj_classes: List of labels of all majority classes.\n :type maj_classes: list\n :param imb_ratio: Imbalance ratio for minority to majority class: len(minority datapoints) / len(majority datapoints)\n If the `imb_ratio` is None, data will not be imbalanced and will only be relabeled to 1's and 0's.\n :type imb_ratio: float\n :param imb_test: Imbalance the test dataset?\n :type imb_test: bool\n :param val_frac: Fraction to take from X_train and y_train for X_val and y_val\n :type val_frac: float\n :param print_stats: Print the imbalance ratio of the imbalanced data?\n :type print_stats: bool\n\n :return: Tuple of (X_train, y_train, X_test, y_test, X_val, y_val)\n :rtype: Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]\n \"\"\"\n if not 0 < val_frac < 1:\n raise ValueError(f\"{val_frac} is not in interval 0 < x < 1.\")\n if not isinstance(print_stats, bool):\n raise TypeError(f\"`print_stats` must be of type `bool`, not {type(print_stats)}.\")\n\n X_train, y_train = imbalance_data(X_train, y_train, min_classes, maj_classes, imb_ratio=imb_ratio)\n # Only imbalance test-data if imb_test is True\n X_test, y_test = imbalance_data(X_test, y_test, min_classes, maj_classes, imb_ratio=imb_ratio if imb_test else None)\n\n # stratify=y_train to ensure class balance is kept between train and validation datasets\n X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=val_frac, stratify=y_train)\n\n if print_stats:\n p_train, p_test, p_val = [((y == 1).sum(), imbalance_ratio(y)) for y in (y_train, y_test, y_val)]\n print(f\"Imbalance ratio `p`:\\\\n\"\n f\"\\\\ttrain: n={p_train[0]}, p={p_train[1]:.6f}\\\\n\"\n f\"\\\\ttest: n={p_test[0]}, p={p_test[1]:.6f}\\\\n\"\n f\"\\\\tvalidation: n={p_val[0]}, p={p_val[1]:.6f}\")\n\n return X_train, y_train, X_test, y_test, X_val, y_val\n\n\ndef imbalance_data(X: np.ndarray, y: np.ndarray, min_class: List[int], maj_class: List[int],\n imb_ratio: float = None) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Split data in minority and majority, only values in {min_class, maj_class} will be kept.\n (Possibly) decrease minority rows to match the imbalance rate.\n If initial imb_ratio of dataset is lower than given `imb_ratio`, the imb_ratio of the returned data will not be changed.\n If the `imb_ratio` is None, data will not be imbalanced and will only be relabeled to 1's and 0's.\n \"\"\"\n if not isinstance(X, np.ndarray):\n raise TypeError(f\"`X` must be of type `np.ndarray` not {type(X)}\")\n if not isinstance(y, np.ndarray):\n raise TypeError(f\"`y` must be of type `np.ndarray` not {type(y)}\")\n if X.shape[0] != y.shape[0]:\n raise ValueError(\"`X` and `y` must contain the same amount of rows.\")\n if not isinstance(min_class, (list, tuple)):\n raise TypeError(\"`min_class` must be of type list or tuple.\")\n if not isinstance(maj_class, (list, tuple)):\n raise TypeError(\"`maj_class` must be of type list or tuple.\")\n\n if (imb_ratio is not None) and not (0 < imb_ratio < 1):\n raise ValueError(f\"{imb_ratio} is not in interval 0 < imb_ratio < 1.\")\n\n if imb_ratio is None: # Do not imbalance data if no `imb_ratio` is given\n imb_ratio = 1\n\n X_min = X[np.isin(y, min_class)] # Mask the correct indexes\n X_maj = X[np.isin(y, maj_class)] # Only keep data/labels for x in {min_class, maj_class} and forget all other\n\n min_len = int(X_maj.shape[0] * imb_ratio) # Amount of rows to select from minority classes to get to correct imbalance ratio\n # Keep all majority rows, decrease minority rows to match `imb_ratio`\n X_min = X_min[np.random.choice(X_min.shape[0], min(min_len, X_min.shape[0]), replace=False), :]\n\n X_imb = np.concatenate([X_maj, X_min]).astype(np.float32)\n y_imb = np.concatenate((np.zeros(X_maj.shape[0]), np.ones(X_min.shape[0]))).astype(np.int32)\n X_imb, y_imb = shuffle(X_imb, y_imb)\n\n return X_imb, y_imb\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport os\nimport numpy as np\nimport pandas as pd\nimport time\nimport sys\nimport logging\nfrom reinforcement.agents.ddqn import TrainDDQN\nfrom reinforcement.agents.dqn import TrainDQN\nfrom reinforcement.utils import rounded_dict\nfrom tensorflow.keras.layers import Dense, Dropout\n\nfrom sklearn.model_selection import train_test_split\nfrom learner.machinelearning import machinelearning\nfrom learner.aion_matrix import aion_matrix\n\nfrom reinforcement.metrics import network_predictions\nfrom learner.machinelearning import machinelearning\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\" # CPU is faster than GPU on structured data\n\n#def TrainRL(input_csv_file, model_save_path, rl_config, RL_Algo_Name):\nclass ReinformentLearning():\n\tdef __init__(self,rlConfig,scoreParam,modelType):\n\t\t\n\t\tself.rl_config= rlConfig\n\t\tself.scoreParam = scoreParam\n\t\tself.log = logging.getLogger('eion')\n\t\tself.modelType = modelType\n\t\t\n\tdef TrainRL(self,xtrain,ytrain,xtest,ytest,algorithm,deployLocation): \n\t\ttry:\n\t\t\tscoredetails = ''\n\t\t\tX_train, xval, y_train, yval = train_test_split(xtrain, ytrain, test_size=0.2, stratify=ytrain)\n\t\t\tX_train = np.array(X_train)\n\t\t\ty_train = np.array(y_train)\n\t\t\txval = np.array(xval)\n\t\t\tyval = np.array(yval)\n\t\t\tvalueCount=ytrain.value_counts()\n\t\t\tcategoryCountList=valueCount.tolist()\n\t\t\txtest = np.array(xtest)\n\t\t\tytest = np.array(ytest)\n\t\t\tobjClf = aion_matrix()\n\t\t\tepisodes = self.rl_config['episodes'] # Total number of episodes\n\t\t\twarmup_steps = self.rl_config['warmup_steps'] # Amount of warmup steps to collect data with random policy\n\t\t\tmemory_length = warmup_steps # Max length of the Replay Memory\n\t\t\tbatch_size = self.rl_config['batch_size']\n\t\t\tcollect_steps_per_episode = self.rl_config['collect_steps_per_episode']\n\t\t\tcollect_every = self.rl_config['collect_every']\n\n\t\t\ttarget_update_period = self.rl_config['target_update_period'] # Period to overwrite the target Q-network with the default Q-network\n\t\t\ttarget_update_tau = self.rl_config['target_update_tau'] # Soften the target model update\n\t\t\tn_step_update = self.rl_config['n_step_update']\n\n\t\t\tlearning_rate = self.rl_config['learning_rate'] # Learning rate\n\t\t\tgamma = self.rl_config['gamma'] # Discount factor\n\t\t\tmin_epsilon = self.rl_config['min_epsilon'] # Minimal and final chance of choosing random action\n\t\t\tdecay_episodes = episodes // 10 # Number of episodes to decay from 1.0 to `min_epsilon``\n\n\t\t\tlayers = [Dense(128, activation=\"relu\"), #need modification\n\t\t\t\t\t Dense(64, activation=\"relu\"),\n\t\t\t\t\t Dense(32, activation=\"relu\"),\n\t\t\t\t\t Dense(len(np.unique(y_train)), activation=None)]\n\t\t\tlogFilePath=os.path.join(deployLocation,'log')\t\t\t\t\t \n\t\t\tif algorithm == \"DQN\":\n\t\t\t\tstart = time.time()\n\t\t\t\tmodelName = \"DQN\"\n\t\t\t\tmodel_save_path = os.path.dirname(__file__)\n\t\t\t\tmodel = TrainDQN(episodes, warmup_steps, learning_rate, gamma, min_epsilon, decay_episodes, target_update_period=target_update_period,target_update_tau=target_update_tau, batch_size=batch_size, collect_steps_per_episode=collect_steps_per_episode,memory_length=memory_length, collect_every=collect_every, n_step_update=n_step_update, model_path=model_save_path,log_dir=logFilePath)\n\t\t\t\tmodel.compile_model(X_train,y_train,layers)\n\t\t\t\tmodel.q_net.summary()\n\t\t\t\tmodel.train(xval,yval)\n\t\t\t\tnetwork = model.get_network()\n\t\t\t\tpredictedytrain=network_predictions(network,np.array(xtrain))\n\t\t\t\t\t\t\n\t\t\t\tpredictedytest = network_predictions(network,np.array(xtest))\n\t\t\t\t\n\t\t\tif \"DDQN\" == algorithm:\n\t\t\t\tstart = time.time()\n\t\t\t\tmodelName = \"DDQN\"\n\t\t\t\tmodel = TrainDDQN(episodes, warmup_steps, learning_rate, gamma, min_epsilon, decay_episodes, target_update_period=target_update_period,target_update_tau=target_update_tau, batch_size=batch_size, collect_steps_per_episode=collect_steps_per_episode,memory_length=memory_length, collect_every=collect_every, n_step_update=n_step_update,log_dir=logFilePath)\n\t\t\t\t\n\t\t\t\tmodel.compile_model(X_train,y_train,layers)\n\t\t\t\tmodel.q_net.summary()\n\t\t\t\tmodel.train(xval,yval)\n\t\t\t\tnetwork = model.get_network()\n\t\t\t\tpredictedytrain=network_predictions(network,np.array(xtrain))\n\t\t\t\t\n\t\t\t\tpredictedytest = network_predictions(network,np.array(xtest))\n\t\t\tscore = objClf.get_score(self.scoreParam,ytest,predictedytest)\t\n\t\t\tscore = round(score,2)\n\t\t\t\n\t\t\treturn (network,self.rl_config,score,algorithm,-1,-1,-1)\n\t\texcept Exception as inst:\n\t\t\tself.log.info( '\\\\n-----> RL Failed!!!.'+str(inst))\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\n\t\t\n\t\t\n import matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nfrom sklearn.metrics import (auc, average_precision_score, confusion_matrix,\n f1_score, precision_recall_curve, roc_curve,precision_score,recall_score)\nfrom tensorflow import constant\nfrom tf_agents.trajectories import time_step\n\n\ndef network_predictions(network, X: np.ndarray) -> dict:\n \"\"\"Computes y_pred using a given network.\n Input is array of data entries.\n\n :param network: The network to use to calculate metrics\n :type network: (Q)Network\n :param X: X data, input to network\n :type X: np.ndarray\n\n :return: Numpy array of predicted targets for given X\n :rtype: np.ndarray\n \"\"\"\n if not isinstance(X, np.ndarray):\n raise ValueError(f\"`X` must be of type `np.ndarray` not {type(X)}\")\n\n q, _ = network(X, step_type=constant([time_step.StepType.FIR", "instruction": "", "output": "" }, { "input": "ST] * X.shape[0]), training=False)\n return np.argmax(q.numpy(), axis=1) # Max action for each x in X\n\n\ndef decision_function(network, X: np.ndarray) -> dict:\n \"\"\"Computes the score for the predicted class of each x in X using a given network.\n Input is array of data entries.\n\n :param network: The network to use to calculate the score per x in X\n :type network: (Q)Network\n :param X: X data, input to network\n :type X: np.ndarray\n\n :return: Numpy array of scores for given X\n :rtype: np.ndarray\n \"\"\"\n if not isinstance(X, np.ndarray):\n raise ValueError(f\"`X` must be of type `np.ndarray` not {type(X)}\")\n\n q, _ = network(X, step_type=constant([time_step.StepType.FIRST] * X.shape[0]), training=False)\n return np.max(q.numpy(), axis=1) # Value of max action for each x in X\n\n\ndef classification_metrics(y_true: list, y_pred: list) -> dict:\n \"\"\"Computes metrics using y_true and y_pred.\n\n :param y_true: True labels\n :type y_true: np.ndarray\n :param y_pred: Predicted labels, corresponding to y_true\n :type y_pred: np.ndarray\n\n :return: Dictionairy containing Geometric Mean, F1, Precision, Recall, TP, TN, FP, FN\n :rtype: dict\n \"\"\"\n if not isinstance(y_true, (list, tuple, np.ndarray)):\n raise ValueError(f\"`y_true` must be of type `list` not {type(y_true)}\")\n if not isinstance(y_pred, (list, tuple, np.ndarray)):\n raise ValueError(f\"`y_pred` must be of type `list` not {type(y_pred)}\")\n if len(y_true) != len(y_pred):\n raise ValueError(\"`X` and `y` must be of same length.\")\n \n\n #G_mean = np.sqrt(recall * specificity) # Geometric mean of recall and specificity\n F1 = f1_score(y_true, y_pred, average='macro') # Default F-measure\n recall = recall_score(y_true,y_pred,average='macro')\n precision = precision_score(y_true,y_pred,average='macro')\n return {\"F1\": F1, \"Precision\": precision, \"Recall\": recall}\n\n\ndef plot_pr_curve(network, X_test: np.ndarray, y_test: np.ndarray,\n X_train: np.ndarray = None, y_train: np.ndarray = None) -> None: # pragma: no cover\n \"\"\"Plots PR curve of X_test and y_test of given network.\n Optionally plots PR curve of X_train and y_train.\n Average precision is shown in the legend.\n\n :param network: The network to use to calculate the PR curve\n :type network: (Q)Network\n :param X_test: X data, input to network\n :type X_test: np.ndarray\n :param y_test: True labels for `X_test`\n :type y_test: np.ndarray\n :param X_train: Optional X data to plot validation PR curve\n :type X_train: np.ndarray\n :param y_train: True labels for `X_val`\n :type y_train: np.ndarray\n\n :return: None\n :rtype: NoneType\n \"\"\"\n plt.plot((0, 1), (1, 0), color=\"black\", linestyle=\"--\", label=\"Baseline\")\n # TODO: Consider changing baseline\n\n if X_train is not None and y_train is not None:\n y_val_score = decision_function(network, X_train)\n val_precision, val_recall, _ = precision_recall_curve(y_train, y_val_score)\n val_AP = average_precision_score(y_train, y_val_score)\n plt.plot(val_recall, val_precision, label=f\"Train AP: {val_AP:.3f}\")\n\n y_test_score = decision_function(network, X_test)\n test_precision, test_recall, _ = precision_recall_curve(y_test, y_test_score)\n test_AP = average_precision_score(y_test, y_test_score)\n\n plt.plot(test_recall, test_precision, label=f\"Test AP: {test_AP:.3f}\")\n plt.xlim((-0.05, 1.05))\n plt.ylim((-0.05, 1.05))\n plt.xlabel(\"Recall\")\n plt.ylabel(\"Precision\")\n plt.title(\"PR Curve\")\n plt.gca().set_aspect(\"equal\", adjustable=\"box\")\n plt.legend(loc=\"lower left\")\n plt.grid(True)\n plt.show()\n\n\ndef plot_roc_curve(network, X_test: np.ndarray, y_test: np.ndarray,\n X_train: np.ndarray = None, y_train: np.ndarray = None) -> None: # pragma: no cover\n \"\"\"Plots ROC curve of X_test and y_test of given network.\n Optionally plots ROC curve of X_train and y_train.\n Average precision is shown in the legend.\n\n :param network: The network to use to calculate the PR curve\n :type network: (Q)Network\n :param X_test: X data, input to network\n :type X_test: np.ndarray\n :param y_test: True labels for `X_test`\n :type y_test: np.ndarray\n :param X_train: Optional X data to plot validation PR curve\n :type X_train: np.ndarray\n :param y_train: True labels for `X_val`\n :type y_train: np.ndarray\n\n :return: None\n :rtype: NoneType\n \"\"\"\n plt.plot((0, 1), (0, 1), color=\"black\", linestyle=\"--\", label=\"Baseline\")\n # TODO: Consider changing baseline\n\n if X_train is not None and y_train is not None:\n y_train_score = decision_function(network, X_train)\n fpr_train, tpr_train, _ = roc_curve(y_train, y_train_score)\n plt.plot(fpr_train, tpr_train, label=f\"Train AUROC: {auc(fpr_train, tpr_train):.2f}\")\n\n y_test_score = decision_function(network, X_test)\n fpr_test, tpr_test, _ = roc_curve(y_test, y_test_score)\n\n plt.plot(fpr_test, tpr_test, label=f\"Test AUROC: {auc(fpr_test, tpr_test):.2f}\")\n plt.xlim((-0.05, 1.05))\n plt.ylim((-0.05, 1.05))\n plt.xlabel(\"False Positive Rate\")\n plt.ylabel(\"True Positive Rate\")\n plt.title(\"ROC Curve\")\n plt.gca().set_aspect(\"equal\", adjustable=\"box\")\n plt.legend(loc=\"lower right\")\n plt.grid(True)\n plt.show()\n\n\ndef plot_confusion_matrix(TP: int, FN: int, FP: int, TN: int) -> None: # pragma: no cover\n \"\"\"Plots confusion matric of given TP, FN, FP, TN.\n\n :param TP: True Positive\n :type TP: int\n :param FN: False Negative\n :type FN: int\n :param FP: False Positive\n :type FP: int\n :param TN: True Negative\n :type TN: int\n\n :return: None\n :rtype: NoneType\n \"\"\"\n if not all(isinstance(i, (int, np.integer)) for i in (TP, FN, FP, TN)):\n raise ValueError(\"Not all arguments are integers.\")\n\n ticklabels = (\"Minority\", \"Majority\")\n sns.heatmap(((TP, FN), (FP, TN)), annot=True, fmt=\"_d\", cmap=\"viridis\", xticklabels=ticklabels, yticklabels=ticklabels)\n\n plt.title(\"Confusion matrix\")\n plt.xlabel(\"Predicted labels\")\n plt.ylabel(\"True labels\")\n plt.show()\n import os\nimport pickle\nfrom datetime import datetime\n\nimport numpy as np\nimport tensorflow as tf\nfrom reinforcement.environments.classifierenv import ClassifierEnv\nfrom reinforcement.metrics import (classification_metrics, decision_function,\n network_predictions, plot_pr_curve, plot_roc_curve)\nfrom reinforcement.utils import imbalance_ratio\nfrom tensorflow import data\nfrom tensorflow.keras.optimizers import Adam\nfrom tf_agents.agents.dqn.dqn_agent import DdqnAgent\nfrom tf_agents.drivers.dynamic_step_driver import DynamicStepDriver\nfrom tf_agents.environments.tf_py_environment import TFPyEnvironment\nfrom tf_agents.networks.sequential import Sequential\nfrom tf_agents.policies.random_tf_policy import RandomTFPolicy\nfrom tf_agents.replay_buffers.tf_uniform_replay_buffer import \\\\\n TFUniformReplayBuffer\nfrom tf_agents.utils import common\n\n\n\nclass TrainDDQN():\n \"\"\"Wrapper for DDQN training, validation, saving etc.\"\"\"\n\n def __init__(self, episodes: int, warmup_steps: int, learning_rate: float, gamma: float, min_epsilon: float, decay_episodes: int,\n model_path: str = None, log_dir: str = None, batch_size: int = 64, memory_length: int = None,\n collect_steps_per_episode: int = 1, val_every: int = None, target_update_period: int = 1, target_update_tau: float = 1.0,\n progressbar: bool = True, n_step_update: int = 1, gradient_clipping: float = 1.0, collect_every: int = 1) -> None:\n \"\"\"\n Wrapper to make training easier.\n Code is partly based of https://www.tensorflow.org/agents/tutorials/1_dqn_tutorial\n\n :param episodes: Number of training episodes\n :type episodes: int\n :param warmup_steps: Number of episodes to fill Replay Buffer with random state-action pairs before training starts\n :type warmup_steps: int\n :param learning_rate: Learning Rate for the Adam Optimizer\n :type learning_rate: float\n :param gamma: Discount factor for the Q-values\n :type gamma: float\n :param min_epsilon: Lowest and final value for epsilon\n :type min_epsilon: float\n :param decay_episodes: Amount of episodes to decay from 1 to `min_epsilon`\n :type decay_episodes: int\n :param model_path: Location to save the trained model\n :type model_path: str\n :param log_dir: Location to save the logs, usefull for TensorBoard\n :type log_dir: str\n :param batch_size: Number of samples in minibatch to train on each step\n :type batch_size: int\n :param memory_length: Maximum size of the Replay Buffer\n :type memory_length: int\n :param collect_steps_per_episode: Amount of data to collect for Replay Buffer each episiode\n :type collect_steps_per_episode: int\n :param collect_every: Step interval to collect data during training\n :type collect_every: int\n :param val_every: Validate the model every X episodes using the `collect_metrics()` function\n :type val_every: int\n :param target_update_period: Update the target Q-network every X episodes\n :type target_update_period: int\n :param target_update_tau: Parameter for softening the `target_update_period`\n :type target_update_tau: float\n :param progressbar: Enable or disable the progressbar for collecting data and training\n :type progressbar: bool\n\n :return: None\n :rtype: NoneType\n \"\"\"\n self.episodes = episodes # Total episodes\n self.warmup_steps = warmup_steps # Amount of warmup steps before training\n self.batch_size = batch_size # Batch size of Replay Memory\n self.collect_steps_per_episode = collect_steps_per_episode # Amount of steps to collect data each episode\n self.collect_every = collect_every # Step interval to collect data during training\n self.learning_rate = learning_rate # Learning Rate\n self.gamma = gamma # Discount factor\n self.min_epsilon = min_epsilon # Minimal chance of choosing random action\n self.decay_episodes = decay_episodes # Number of episodes to decay from 1.0 to `EPSILON`\n self.target_update_period = target_update_period # Period for soft updates\n self.target_update_tau = target_update_tau\n self.progressbar = progressbar # Enable or disable the progressbar for collecting data and training\n self.n_step_update = n_step_update\n self.gradient_clipping = gradient_clipping # Clip the loss\n self.compiled = False\n NOW = \"DDQN\" #datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n\n if memory_length is not None:\n self.memory_length = memory_length # Max Replay Memory length\n else:\n self.memory_length = warmup_steps\n\n if val_every is not None:\n self.val_every = val_every # Validate the policy every `val_every` episodes\n else:\n self.val_every = self.episodes // min(50, self.episodes) # Can't validate the model 50 times if self.episodes < 50\n\n if model_path is not None:\n #if os.path.exists(model_path + \"/\" + NOW + \".pkl\"):\n # os.remove(model_path + \"/\" + NOW + \".pkl\")\n self.model_path = model_path + \"/\" + NOW + \".pkl\"\n else:\n self.model_path = \"./models/\" + NOW + \".pkl\"\n\n if log_dir is None:\n log_dir = \"./logs/\" + NOW\n self.writer = tf.summary.create_file_writer(log_dir)\n\n def compile_model(self, X_train, y_train, layers: list = [], imb_ratio: float = None, loss_fn=common.element_wise_squared_loss) -> None:\n \"\"\"Initializes the neural networks, DDQN-agent, collect policies and replay buffer.\n\n :param X_train: Training data for the model.\n :type X_train: np.ndarray\n :param y_train: Labels corresponding to `X_train`. 1 for the positive class, 0 for the negative class.\n :param y_train: np.ndarray\n :param layers: List of layers to feed into the TF-agents custom Sequential(!) layer.\n :type layers: list\n :param imb_ratio: The imbalance ratio of the data.\n :type imb_ratio: float\n :param loss_fn: Callable loss function\n :type loss_", "instruction": "", "output": "" }, { "input": "fn: tf.compat.v1.losses\n\n :return: None\n :rtype: NoneType\n \"\"\"\n if imb_ratio is None:\n imb_ratio = imbalance_ratio(y_train)\n\n self.train_env = TFPyEnvironment(ClassifierEnv(X_train, y_train, imb_ratio))\n self.global_episode = tf.Variable(0, name=\"global_episode\", dtype=np.int64, trainable=False) # Global train episode counter\n\n # Custom epsilon decay: https://github.com/tensorflow/agents/issues/339\n epsilon_decay = tf.compat.v1.train.polynomial_decay(\n 1.0, self.global_episode, self.decay_episodes, end_learning_rate=self.min_epsilon)\n\n self.q_net = Sequential(layers, self.train_env.observation_spec())\n\n self.agent = DdqnAgent(self.train_env.time_step_spec(),\n self.train_env.action_spec(),\n q_network=self.q_net,\n optimizer=Adam(learning_rate=self.learning_rate),\n td_errors_loss_fn=loss_fn,\n train_step_counter=self.global_episode,\n target_update_period=self.target_update_period,\n target_update_tau=self.target_update_tau,\n gamma=self.gamma,\n epsilon_greedy=epsilon_decay,\n n_step_update=self.n_step_update,\n gradient_clipping=self.gradient_clipping)\n self.agent.initialize()\n\n self.random_policy = RandomTFPolicy(self.train_env.time_step_spec(), self.train_env.action_spec())\n self.replay_buffer = TFUniformReplayBuffer(data_spec=self.agent.collect_data_spec,\n batch_size=self.train_env.batch_size,\n max_length=self.memory_length)\n\n self.warmup_driver = DynamicStepDriver(self.train_env,\n self.random_policy,\n observers=[self.replay_buffer.add_batch],\n num_steps=self.warmup_steps) # Uses a random policy\n\n self.collect_driver = DynamicStepDriver(self.train_env,\n self.agent.collect_policy,\n observers=[self.replay_buffer.add_batch],\n num_steps=self.collect_steps_per_episode) # Uses the epsilon-greedy policy of the agent\n\n self.agent.train = common.function(self.agent.train) # Optimalization\n self.warmup_driver.run = common.function(self.warmup_driver.run)\n self.collect_driver.run = common.function(self.collect_driver.run)\n\n self.compiled = True\n\n def train(self, *args) -> None:\n \"\"\"Starts the training of the model. Includes warmup period, metrics collection and model saving.\n\n :param *args: All arguments will be passed to `collect_metrics()`.\n This can be usefull to pass callables, testing environments or validation data.\n Overwrite the TrainDDQN.collect_metrics() function to use your own *args.\n :type *args: Any\n\n :return: None\n :rtype: NoneType, last step is saving the model as a side-effect\n \"\"\"\n assert self.compiled, \"Model must be compiled with model.compile_model(X_train, y_train, layers) before training.\"\n\n # Warmup period, fill memory with random actions\n if self.progressbar:\n print(f\"\\\\033[92mCollecting data for {self.warmup_steps:_} steps... This might take a few minutes...\\\\033[0m\")\n\n self.warmup_driver.run(time_step=None, policy_state=self.random_policy.get_initial_state(self.train_env.batch_size))\n\n if self.progressbar:\n print(f\"\\\\033[92m{self.replay_buffer.num_frames():_} frames collected!\\\\033[0m\")\n\n dataset = self.replay_buffer.as_dataset(sample_batch_size=self.batch_size, num_steps=self.n_step_update + 1,\n num_parallel_calls=data.experimental.AUTOTUNE).prefetch(data.experimental.AUTOTUNE)\n iterator = iter(dataset)\n\n def _train():\n experiences, _ = next(iterator)\n return self.agent.train(experiences).loss\n _train = common.function(_train) # Optimalization\n\n ts = None\n policy_state = self.agent.collect_policy.get_initial_state(self.train_env.batch_size)\n self.collect_metrics(*args) # Initial collection for step 0\n \n for _ in range(self.episodes):\n if not self.global_episode % self.collect_every:\n # Collect a few steps using collect_policy and save to `replay_buffer`\n if self.collect_steps_per_episode != 0:\n ts, policy_state = self.collect_driver.run(time_step=ts, policy_state=policy_state)\n \n\n # Sample a batch of data from `replay_buffer` and update the agent's network\n train_loss = _train()\n\n if not self.global_episode % self.val_every:\n with self.writer.as_default():\n tf.summary.scalar(\"train_loss\", train_loss, step=self.global_episode)\n\n self.collect_metrics(*args)\n \n\n def collect_metrics(self, X_val: np.ndarray, y_val: np.ndarray, save_best: str = None):\n \"\"\"Collects metrics using the trained Q-network.\n\n :param X_val: Features of validation data, same shape as X_train\n :type X_val: np.ndarray\n :param y_val: Labels of validation data, same shape as y_train\n :type y_val: np.ndarray\n :param save_best: Saving the best model of all validation runs based on given metric:\n Choose one of: {Gmean, F1, Precision, Recall, TP, TN, FP, FN}\n This improves stability since the model at the last episode is not guaranteed to be the best model.\n :type save_best: str\n \"\"\"\n y_pred = network_predictions(self.agent._target_q_network, X_val)\n stats = classification_metrics(y_val, y_pred)\n avgQ = np.mean(decision_function(self.agent._target_q_network, X_val)) # Max action for each x in X\n\n if save_best is not None:\n if not hasattr(self, \"best_score\"): # If no best model yet\n self.best_score = 0.0\n\n if stats.get(save_best) >= self.best_score: # Overwrite best model\n self.save_network() # Saving directly to avoid shallow copy without trained weights\n self.best_score = stats.get(save_best)\n\n with self.writer.as_default():\n tf.summary.scalar(\"AverageQ\", avgQ, step=self.global_episode) # Average Q-value for this epoch\n for k, v in stats.items():\n tf.summary.scalar(k, v, step=self.global_episode)\n\n def evaluate(self,X_train,y_train, X_test, y_test):\n \"\"\"\n Final evaluation of trained Q-network with X_test and y_test.\n Optional PR and ROC curve comparison to X_train, y_train to ensure no overfitting is taking place.\n\n :param X_test: Features of test data, same shape as X_train\n :type X_test: np.ndarray\n :param y_test: Labels of test data, same shape as y_train\n :type y_test: np.ndarray\n :param X_train: Features of train data\n :type X_train: np.ndarray\n :param y_train: Labels of train data\n :type y_train: np.ndarray\n \"\"\"\n #if hasattr(self, \"best_score\"):\n # print(f\"\\\\033[92mBest score: {self.best_score:6f}!\\\\033[0m\")\n # network = self.load_network(self.model_path) # Load best saved model\n #else:\n # network = self.agent._target_q_network # Load latest target model\n\n #network = self.load_network(self.model_path)\n #if (X_train is not None) and (y_train is not None):\n # plot_pr_curve(network, X_test, y_test, X_train, y_train)\n # plot_roc_curve(network, X_test, y_test, X_train, y_train)\n\n y_pred = network_predictions(self.agent._target_q_network, X_test)\n return classification_metrics(y_test, y_pred)\n \n def get_network(self):\n #network = self.load_network(self.model_path)\n return self.agent._target_q_network\n \n def save_network(self, filename_rl): #usnish\n \"\"\"Saves Q-network as pickle to `model_path`.\"\"\"\n with open(self.filename_rl, \"wb\") as f: # Save Q-network as pickle\n pickle.dump(self.agent._target_q_network, f)\n\n @staticmethod\n def load_network(fp: str):\n \"\"\"Static method to load Q-network pickle from given filepath.\n\n :param fp: Filepath to the saved pickle of the network\n :type fp: str\n\n :returns: The network-object loaded from a pickle file.\n :rtype: tensorflow.keras.models.Model\n \"\"\"\n with open(fp, \"rb\") as f: # Load the Q-network\n network = pickle.load(f)\n return network\n import os\nimport pickle\nfrom datetime import datetime\n\nimport numpy as np\nimport tensorflow as tf\nfrom reinforcement.environments.classifierenv import ClassifierEnv\nfrom reinforcement.metrics import (classification_metrics, decision_function,\n network_predictions, plot_pr_curve, plot_roc_curve)\nfrom reinforcement.utils import imbalance_ratio\nfrom tensorflow import data\nfrom tensorflow.keras.optimizers import Adam\n#from tf_agents.agents.dqn.dqn_agent import DdqnAgent\nfrom tf_agents.agents import DqnAgent\nfrom tf_agents.drivers.dynamic_step_driver import DynamicStepDriver\nfrom tf_agents.environments.tf_py_environment import TFPyEnvironment\nfrom tf_agents.networks.sequential import Sequential\nfrom tf_agents.policies.random_tf_policy import RandomTFPolicy\nfrom tf_agents.replay_buffers.tf_uniform_replay_buffer import \\\\\n TFUniformReplayBuffer\nfrom tf_agents.utils import common\n\n\nclass TrainDQN():\n \"\"\"Wrapper for DDQN training, validation, saving etc.\"\"\"\n\n def __init__(self, episodes: int, warmup_steps: int, learning_rate: float, gamma: float, min_epsilon: float, decay_episodes: int,\n model_path: str = None, log_dir: str = None, batch_size: int = 64, memory_length: int = None,\n collect_steps_per_episode: int = 1, val_every: int = None, target_update_period: int = 1, target_update_tau: float = 1.0,\n progressbar: bool = True, n_step_update: int = 1, gradient_clipping: float = 1.0, collect_every: int = 1) -> None:\n \"\"\"\n Wrapper to make training easier.\n Code is partly based of https://www.tensorflow.org/agents/tutorials/1_dqn_tutorial\n\n :param episodes: Number of training episodes\n :type episodes: int\n :param warmup_steps: Number of episodes to fill Replay Buffer with random state-action pairs before training starts\n :type warmup_steps: int\n :param learning_rate: Learning Rate for the Adam Optimizer\n :type learning_rate: float\n :param gamma: Discount factor for the Q-values\n :type gamma: float\n :param min_epsilon: Lowest and final value for epsilon\n :type min_epsilon: float\n :param decay_episodes: Amount of episodes to decay from 1 to `min_epsilon`\n :type decay_episodes: int\n :param model_path: Location to save the trained model\n :type model_path: str\n :param log_dir: Location to save the logs, usefull for TensorBoard\n :type log_dir: str\n :param batch_size: Number of samples in minibatch to train on each step\n :type batch_size: int\n :param memory_length: Maximum size of the Replay Buffer\n :type memory_length: int\n :param collect_steps_per_episode: Amount of data to collect for Replay Buffer each episiode\n :type collect_steps_per_episode: int\n :param collect_every: Step interval to collect data during training\n :type collect_every: int\n :param val_every: Validate the model every X episodes using the `collect_metrics()` function\n :type val_every: int\n :param target_update_period: Update the target Q-network every X episodes\n :type target_update_period: int\n :param target_update_tau: Parameter for softening the `target_update_period`\n :type target_update_tau: float\n :param progressbar: Enable or disable the progressbar for collecting data and training\n :type progressbar: bool\n\n :return: None\n :rtype: NoneType\n \"\"\"\n self.episodes = episodes # Total episodes\n self.warmup_steps = warmup_steps # Amount of warmup steps before training\n self.batch_size = batch_size # Batch size of Replay Memory\n self.collect_steps_per_episode = collect_steps_per_episode # Amount of steps to collect data each episode\n self.collect_every = collect_every # Step interval to collect data during training\n self.learning_rate = learning_rate # Learning Rate\n self.gamma = gamma # Discount factor\n self.min_epsilon = min_epsilon # Minimal chance of choosing random action\n self.decay_episodes = decay_episodes # Number of episodes to decay from 1.0 to `EPSILON`\n self.target_update_period = target_update_period # Period for soft updates\n self.target_update_tau = target_update_tau\n self.progressbar = progressbar # Enable or disable the progressbar for collecting data and training\n self.n_step_update = n_step_update\n self.gradient_clipping = gradient_clipping # Clip the loss\n self.compiled = False\n NOW = \"DQN\" #datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n\n if memory_length is not None:\n self.memory_length = memory_length # Max Replay Memory length\n else:\n self.memory_length = warmup_steps\n\n if val_every is not None:\n self.val_every = val_every # Validate the policy every `val_every` episodes\n else:\n self.val_every", "instruction": "", "output": "" }, { "input": "= self.episodes // min(50, self.episodes) # Can't validate the model 50 times if self.episodes < 50\n\n if model_path is not None:\n #if os.path.exists(model_path + \"/\" + NOW + \".pkl\"):\n # os.remove(model_path + \"/\" + NOW + \"", "instruction": "", "output": "" }, { "input": "when minority class is misclassified\n else: # Majority\n reward = -self.imb_ratio # False Positive\n\n if self.episode_step == self.X_train.shape[0] - 1: # If last step in data\n self._episode_ended = True\n\n self._state = self.X_train[self.id[self.episode_step]] # Update state with new datapoint\n\n if self._episode_ended:\n return ts.termination(self._state, reward)\n else:\n return ts.transition(self._state, reward)\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\n# For timeseries pyramid pdaarima module\nfrom pmdarima.arima import auto_arima\nimport pmdarima as pm\nimport json\n\n#Python sklearn & std libraries\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_selection import VarianceThreshold\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.metrics import mean_squared_error\n#from sklearn.metrics import mean_absolute_percentage_error\nfrom sklearn.linear_model import LinearRegression\nfrom math import sqrt\nimport warnings\n# For serialization.\n#from sklearn.externals import joblib\nimport pickle \nimport os,sys\n# For ploting (mathlab)\nimport matplotlib.pyplot as plt\n#Import eion config manager module\nimport logging\nfrom sklearn import metrics\nfrom sklearn.metrics import accuracy_score\nimport time\nimport os\nimport sys\n\n# Eion arima module\nclass eion_arima ():\n\n #Constructor\n\tdef __init__(self,configfile,testpercentage,sesonalityChecks,stationaryChecks): # eaobj - eion arima class object\n\t\ttry:\n\t\t\ttsarima_params = configfile\n\t\t\tself.testpercentage = testpercentage\n\t\t\tself.start_p= int(tsarima_params['start_p'])\n\t\t\tself.start_q= int(tsarima_params['start_q'])\n\t\t\tself.max_p= int(tsarima_params['max_p'])\n\t\t\tself.max_q= int(tsarima_params['max_q'])\n\t\t\t\n\t\t\tself.max_d= int(tsarima_params['max_d'])\n\t\t\tself.max_order= int(tsarima_params['max_order'])\n\t\t\tself.start_Q= int(tsarima_params['start_Q'])\n\t\t\tself.max_P= int(tsarima_params['max_P'])\n\t\t\tself.max_D= int(tsarima_params['max_D'])\n\t\t\tself.max_Q= int(tsarima_params['max_Q'])\n\t\t\t\n\t\t\tself.m= int(tsarima_params['m'])\n\t\t\tself.start_P= int(tsarima_params['start_P'])\n\t\t\tself.seasonal= tsarima_params['seasonal']\n\t\t\t#self.seasonal= sesonalityChecks\n\t\t\tself.stationary=stationaryChecks\n\t\t\t#print(\"self.seasonal: \\\\n\",self.seasonal)\n\t\t\t#print(\"self.stationary: \\\\n\",self.stationary)\t\t\t\n\t\t\t\t\n\t\t\tif self.seasonal and not self.seasonal.isspace():\n\t\t\t\tif (self.seasonal.lower() == 'true'):\n\t\t\t\t\tself.seasonal=True\n\t\t\t\telif (self.seasonal.lower() == 'false'):\n\t\t\t\t\tself.seasonal=False\n\t\t\t\telse:\n\t\t\t\t\tself.seasonal=True\n\t\t\telse:\n\t\t\t\tself.seasonal=True\n\t\t\t\n\t\t\t\n\t\t\tself.d= int(tsarima_params['d'])\n\t\t\tself.D= int(tsarima_params['D'])\n\t\t\t#self.trace= tsarima_params['trace']\n\t\t\tself.error_action= tsarima_params['error_action']\n\t\t\tself.suppress_warnings= tsarima_params['suppress_warnings']\n\t\t\tself.stepwise= tsarima_params['stepwise']\n\t\t\t#self.random= tsarima_params['random']\n\t\t\tself.log = logging.getLogger('eion')\n\t\texcept Exception as inst:\n\t\t\tself.log.info(' ')\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\tdef mean_absolute_percentage_error(self,y_true, y_pred): \n\t\ttry:\n\t\t\ty_true, y_pred=np.array(y_true), np.array(y_pred)\n\t\t\treturn np.mean(np.abs((y_true - y_pred) / y_true+sys.float_info.epsilon)) * 100\n\t\t\t\n\t\texcept Exception as inst:\n\t\t\tself.log.info('<------------- mean_absolute_percentage_error ---------------> ')\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\n\tdef eion_arima(self,train_data):\n\t\ttry:\n\t\t\tstart = time.time()\n\t\t\tauto_arima_stepwise_fit = pm.auto_arima(train_data, start_p=self.start_p, start_q=self.start_q,max_p=self.max_p, max_q=self.max_q,max_d=self.max_d,max_P=self.max_P,max_D=self.max_D,max_Q=self.max_Q,max_order=self.max_order, m=self.m,start_P=self.start_P,start_Q=self.start_Q, seasonal=self.seasonal,stationary=self.stationary,d=self.d, D=self.D,error_action=self.error_action,suppress_warnings=self.suppress_warnings,stepwise=self.stepwise)\n\t\t\t#auto_arima_stepwise_fit = pm.auto_arima(train_data, start_p=self.start_p, start_q=self.start_q,max_p=self.max_p, max_q=self.max_q,max_d=self.max_d,max_P=self.max_P,max_D=self.max_D,max_Q=self.max_Q,max_order=self.max_order, m=self.m,start_P=self.start_P,start_Q=self.start_Q, seasonal=True,stationary=True,d=self.d, D=self.D,error_action=self.error_action,suppress_warnings=self.suppress_warnings,random_state=20,stepwise=True)\n\t\t\taic_score = auto_arima_stepwise_fit.aic()\n\t\t\tself.log.info('------->AIC Score: '+str(aic_score))\n\t\t\tself.log.info('\\\\n--------- Fit Summary --------------')\n\t\t\tself.log.info (auto_arima_stepwise_fit.summary()) \n\t\t\tself.log.info('--------- Fit Summary End--------------\\\\n')\n\t\t\tself.log.info(\"\\\\n--------------- Modal Validation Start ---------------\")\n\t\t\tsize = int(len(train_data) * (100 - self.testpercentage)/100)\n\t\t\t\n\t\t\ttrain = train_data.loc[0:size]\n\t\t\t\n\t\t\tvalid = train_data.loc[size:len(train_data)]\n\t\t\t# valid_perc=((100-self.testpercentage)/100)\n\t\t\t# valid_perc=round(valid_perc, 1)\n\t\t\t# print(\"valid_perc: \\\\n\", valid_perc)\n\t\t\t\n\t\t\tself.log.info(\"------->Train Data Shape: \"+str(train.shape))\n\t\t\tself.log.info(\"------->Valid Data Shape\"+str(valid.shape))\n\t\t\tstart1=len(train)\n\t\t\tend1=len(train_data)\t\t\t\n\t\t\tmodelfit = auto_arima_stepwise_fit.fit(train)\n\t\t\ta_prediction = auto_arima_stepwise_fit.predict(valid.shape[0])\n\t\t\t#a_prediction = auto_arima_stepwise_fit.predict(n_periods=len(valid))\n\t\t\t#a_prediction = auto_arima_stepwise_fit.predict(start=start1,end=end1)\n\t\t\t#print(\"a_prediction: \\\\n\",a_prediction)\n\t\t\t#self.log.info(a_prediction)\n\t\t\tmae = metrics.mean_absolute_error(valid, a_prediction)\n\t\t\tself.log.info (\"------->MAE: \"+str(mae))\n\t\t\tmape = self.mean_absolute_percentage_error(valid, a_prediction)\n\t\t\t\n\t\t\t#mape=np.mean(np.abs((valid - a_prediction) / valid)) * 100\n\t\t\t\n\t\t\tself.log.info (\"------->MAPE :\"+str(mape))\n\t\t\t#RMSE\n\t\t\trmse = sqrt(mean_squared_error(valid,a_prediction))\n\t\t\tmse = mean_squared_error(valid,a_prediction)\n\t\t\tself.log.info (\"------->RMSE :\"+str(rmse))\n\t\t\tself.log.info (\"------->MSE :\"+str(mse))\n\t\t\tfrom sklearn.metrics import r2_score\n\t\t\tr2 = r2_score(valid,a_prediction)\n\t\t\t########### End ####################\n\t\t\n\t\t\t# now we have the model\n\t\t\tauto_arima_stepwise_fit.fit(train_data)\n\t\t\tself.log.info(\"------------- Validate Model End----------------\\\\n\")\n\t\t\texecutionTime=time.time() - start\n\t\t\tself.log.info('-------> Time: '+str(executionTime)+'\\\\n')\n\t\t\treturn auto_arima_stepwise_fit,mae,rmse,mse,r2,aic_score,mape,valid,a_prediction\n\t\texcept Exception as inst:\n\t\t\tself.log.info(' '+str(inst))\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\n\n\t '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport json\n\n#Python sklearn & std libraries\nimport numpy as np\nimport pandas as pd\nfrom time_series.ts_arima_eion import eion_arima\nfrom statsmodels.tsa.vector_ar.vecm import coint_johansen\nfrom statsmodels.tsa.vector_ar.var_model import VAR\nfrom math import *\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nfrom math import sqrt\nimport logging\nimport os\nimport sys\nimport time\nfrom statsmodels.tsa.arima_model import ARIMA\nfrom sklearn.metrics import mean_squared_error\nfrom pandas import read_csv\nfrom statsmodels.tsa.stattools import adfuller\nimport pmdarima as pm\nfrom statsmodels.tsa.stattools import grangercausalitytests\nfrom statsmodels.stats.stattools import durbin_watson\nfrom sklearn.utils import check_array\n\n\nclass timeseriesModelTests():\n\tdef __init__(self,data,targetFeature,datetimeFeature,count):\n\t\t#self.tsConfig = tsConfig\n\t\t#self.modelconfig = modelconfig\n\t\t#self.modelList = modelList\n\t\tself.data = data\n\t\tself.targetFeature = targetFeature\n\t\tself.dateTimeFeature = datetimeFeature\n\t\tself.count=count\n\t\tself.log = logging.getLogger('eion')\n\tdef StatinaryChecks(self,dictDiffCount):\n\t\tself.log.info(\"\\\\n---------------Start Stationary Checks-----------\")\n\t\ttFeature = self.targetFeature.split(',')\n\t\ttFeature.append(self.dateTimeFeature)\n\t\tself.data=self.data[tFeature]\n\t\ttFeature.remove(self.dateTimeFeature)\n\t\tlengthtFeature=len(tFeature)\n\t\tdiffCount=0\n\t\ttry :\n\t\t\tfor features in (tFeature):\n\t\t\t\tXSt = self.data[features]\n\t\t\t\tXSt=XSt.values\n\t\t\t\tresultSt = adfuller(XSt,autolag='AIC')\n\t\t\t\tstationaryFlag = False\n\t\t\t\t#print(resultSt)\n\t\t\t\tself.log.info('-------> Features: '+str(features))\n\t\t\t\tself.log.info('----------> ADF Statistic: '+str(resultSt[0]))\n\t\t\t\tself.log.info('----------> p-value: %f' % resultSt[1])\n\t\t\t\tif resultSt[1]<= 0.05:\n\t\t\t\t\tself.log.info(\"-------------> Converted As Stationary Data\")\n\t\t\t\t\tstationaryFlag = True\n\t\t\t\telse:\n\t\t\t\t\tself.log.info(\"-------------> Stationary Conversion Required\")\n\t\t\t\t\tstationaryFlag = False\n\t\t\t\t\t\n\t\t\t\tself.log.info('----------> Critical Values')\n\t\t\t\tfor key, value in resultSt[4].items():\n\t\t\t\t\tself.log.info('----------> '+str(key)+': '+str(value))\n\t\t\t\t\n\t\t\t\tif stationaryFlag == False:\n\t\t\t\t\tself.data[features]=self.data[features].diff()\n\t\t\t\t\tself.data=self.data.dropna()\n\t\t\t\t\tdictDiffCount[features]=1\n\t\t\t\t\tXStt = self.data[features]\n\t\t\t\t\tXStt=XStt.values\t\n\t\t\t\t\tresultStt = adfuller(XStt)\n\t\t\t\t\tif resultStt[1] > 0.05", "instruction": "", "output": "" }, { "input": ":\n\t\t\t\t\t\tself.data[features]=self.data[features].diff()\n\t\t\t\t\t\tself.data=self.data.dropna()\n\t\t\t\t\t\tdictDiffCount[features]=2\n\t\t\t\t\t\tXSttt = self.data[features]\n\t\t\t\t\t\tXSttt=XSttt.values\t\n\t\t\t\t\t\tresultSttt = adfuller(XSttt)\n\t\t\t\t\t\tif resultSttt[1]<= 0.05:\n\t\t\t\t\t\t\tstationaryFlag = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tstationaryFlag = True\t\t\t\t\n\t\t\t\tself.log.info(\"------------->\"+str(dictDiffCount))\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif stationaryFlag == True:\n\t\t\t\t\tself.log.info(\"----------> Equals to Stationary Data\")\n\t\t\t\telse:\n\t\t\t\t\tself.log.info(\"----------> Not Equal To Stationary Data\")\n\t\t\t\t\t\n\t\t\tself.log.info(\"-------> Stationary data diff()\")\n\t\t\tself.log.info(dictDiffCount)\n\t\t\tself.log.info(\"---------------Start Stationary Checks Ends-----------\\\\n\")\n\t\t\treturn self.data,dictDiffCount\n\t\t\t\t\t\t\n\t\t\n\t\texcept Exception as inst:\n\t\t\t\tself.log.info(' ')\n\t\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\n\tdef varTimeseriesModelTests(self,data):\n\t\ttry :\n\t\t\ttFeature = self.targetFeature.split(',')\n\t\t\tself.log.info(\"\\\\n--------- Start Granger Causality Test Results ------------\")\n\t\t\tgtest=grangercausalitytests(data[tFeature], maxlag=15, addconst=True, verbose=True)\t\n\t\t\tself.log.info(\"-------> GrangerCausalitytest Results \"+str(gtest.values()))\n\t\t\tself.log.info(\"--------- End Granger Causality Test Results ------------\\\\n\")\n\t\t\treturn gtest\n\t\texcept Exception as inst:\n\t\t\t\tself.log.info(' ')\n\t\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\n\tdef grangersCausationMatrix(self,data, variables, test='ssr_chi2test', verbose=False): \n\t\n\t\ttry :\n\t\t\tcountVariables=0\n\t\t\tself.log.info(len(variables))\n\t\t\tself.log.info(\"\\\\n--------------Start GrangersCausationMatrix---------------\")\n\t\t\tdf = pd.DataFrame(np.zeros((len(variables), len(variables))), columns=variables, index=variables)\n\t\t\tfor c in df.columns:\n\t\t\t\tfor r in df.index:\n\t\t\t\t\ttest_result = grangercausalitytests(data[[r, c]], maxlag=12, verbose=False)\n\t\t\t\t\tp_values = [round(test_result[i+1][0][test][1],4) for i in range(12)]\n\t\t\t\t\tif verbose: print(f'Y = {r}, X = {c}, P Values = {p_values}')\n\t\t\t\t\tmin_p_value = np.min(p_values)\n\t\t\t\t\tdf.loc[r, c] = min_p_value\n\t\t\tdf.columns = [var + '_x' for var in variables]\n\t\t\tdf.index = [var + '_y' for var in variables]\n\t\t\tself.log.info(df)\n\t\t\tfor i in range(len(variables)):\n\t\t\t\tfor j in range(len(variables)):\n\t\t\t\t\tif i!=j and df.iloc[i][j]<0.05 and df.iloc[i][j]<0.05:\n\t\t\t\t\t\tcountVariables=countVariables+1\n\t\t\tself.log.info(\"--------------End GrangersCausationMatrix---------------\\\\n\")\n\t\t\treturn df,countVariables\n\t\texcept Exception as inst:\n\t\t\tself.log.info(' ')\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\treturn df,countVariables\n\t\t\n\tdef coIntegrationTest(self,data):\n\t\ttry :\n\t\t\ttdata = data.drop([self.dateTimeFeature], axis=1)\n\t\t\ttdata.index = data[self.dateTimeFeature]\n\t\t\tcols = tdata.columns\n\t\t\tself.log.info(\"\\\\n-------------- Start of the Co Integration test ---------------\")\n\t\t\tlenTargetFeature=len(self.targetFeature)\n\t\t\tcountIntegrationFeature=0\n\n\t\t\tN, l = tdata.shape\n\t\t\tjres = coint_johansen(tdata, 0, 1)\n\t\t\ttrstat = jres.lr1 \n\t\t\ttsignf = jres.cvt \n\t\t\t\n\t\t\tfor i in range(l):\n\t\t\t\tif trstat[i] > tsignf[i, 1]: \n\t\t\t\t\tr = i + 1\n\t\t\tjres.r = r\n\t\t\tjres.evecr = jres.evec[:, :r]\n\t\t\t\t\t\n\t\t\tjres.r = r\n\t\t\tcountIntegrationFeature=jres.r\n\t\t\tjres.evecr = jres.evec[:, :r]\n\t\t\t\n\t\t\tself.log.info('------->coint_johansen trace statistics: '+str(trstat))\n\t\t\tself.log.info('------->coint_johansen critical values:')\n\t\t\tself.log.info(tsignf)\n\t\t\tself.log.info(\"------->There are \"+str(countIntegrationFeature)+\" Co-Integration vectors\")\n\t\t\tself.log.info(\"-------------- End of the Co Integration test ---------------\\\\n\")\n\t\t\t\t\n\t\t\treturn countIntegrationFeature\n\t\texcept Exception as inst:\n\t\t\tself.log.info(' ')\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tfname = os.path.split(exc_tb.tb_frame.f_code.co_filename)\n\t\t\tself.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))\n\t\t\n\t\t\n\n\t\n\t\t\n\t\t\n\t\n\t\t\n\t\t\t\n\t\t\t '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport pandas as pd\n# import os\nimport tensorflow as tf\nimport numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nimport math\nfrom sklearn.metrics import mean_squared_error\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import LSTM\nimport logging\n# import kerastuner\nimport keras_tuner\n#from keras_tuner.engine.hyperparameters import HyperParameters\nfrom keras_tuner.tuners import RandomSearch,BayesianOptimization ,Hyperband\n\nimport warnings\nwarnings.simplefilter(\"ignore\", UserWarning)\n\n# from keras.models import load_model\n\n# from tensorflow.keras.optimizers import SGD\n# from tensorflow.keras.utils import load_model\nfrom tensorflow.keras.models import load_model\n\n\nclass timeseriesDLUnivariate:\n def __init__(self,configfile,testpercentage,targetFeature,dateTimeFeature,modelName):\n self.look_back=None\n #Preprocessed dataframe\n # self.df=df\n self.savedmodelname=None\n self.deploy_location=None\n self.epochs=None\n self.batch_size=None\n self.hidden_layers=None\n self.optimizer=None\n self.activation_fn=None\n self.loss_fn=None\n self.first_layer=None\n self.dropout=None\n self.model_name=None\n self.hpt_train=None\n ##Below is model type (MLP or lstm)\n self.model_type=modelName\n #self.dataFolderLocation=str(dataFolderLocation)\n ##Added for ts hpt\n self.tuner_algorithm=\"\"\n \n self.dl_params = configfile\n # self.data=data\n self.targetFeature=targetFeature\n self.dateTimeFeature=dateTimeFeature\n self.testpercentage = testpercentage \n self.log = logging.getLogger('eion')\n \n #To extract dict key,values\n def extract_params(self,dict):\n self.dict=dict\n for k,v in self.dict.items():\n return k,v\n \n ##Get deep learning model hyperparameter from advanced config\n def getdlparams(self):\n val=self.dl_params\n self.log.info('-------> The given mlp/lstm timeseries algorithm parameters:>>') \n self.log.info(\" \"+str(val))\n for k,v in val.items():\n try:\n if (k == \"tuner_algorithm\"):\n self.tuner_algorithm=str(v)\n elif (k == \"activation\"):\n self.activation_fn=str(v)\n elif (k == \"optimizer\"):\n self.optimizer=str(v)\n elif (k == \"loss\"):\n self.loss_fn=str(v)\n elif (k == \"first_layer\"):\n if not isinstance(k,list):\n self.first_layer=str(v).split(',')\n else:\n self.first_layer=k\n elif (k == \"lag_order\"):\n if isinstance(k,list):\n k = ''.join(v)\n k=int(float(str(v)))\n else: \n self.look_back=int(float(str(v)))\n elif (k == \"hidden_layers\"):\n self.hidden_layers=int(v)\n elif (k == \"dropout\"): \n if not isinstance(k,list):\n self.dropout=str(v).split(',')\n else:\n self.dropout=k\n elif (k == \"batch_size\"):\n self.batch_size=int(v)\n elif (k == \"epochs\"):\n self.epochs=int(v)\n elif (k == \"model_name\"):\n self.model_name=str(v)\n \n except Exception as e: \n self.log.info('Exception occured in deeep learn param reading, setting up default params.')\n self.activation_fn=\"relu\"\n self.optimizer=\"adam\"\n self.loss_fn=\"mean_squared_error\"\n self.first_layer=[8,512]\n self.hidden_layers=1\n self.look_back=int(2)\n self.dropout=[0.1,0.5]\n self.batch_size=2\n self.epochs=50\n self.model_name=\"lstmmodel.h5\"\n continue\n \n ## Just use this if user need to create dataframe from input data.\n def createdf(self,df):\n target=\"\"\n # splitting reframed to X and Y considering the first column to be out target featureX=reframed.drop(['var1(t)'],axis=1)\n X=df.drop([target],axis=1)\n Y=df[target]\n X_values=X.values\n Y_values=Y.values\n n_predict=len(Y_values)\n train_X,train_Y = X_values[:(X_values.shape[0]-n_predict),:],Y_values[:(X_values.shape[0]-n_predict)]\n test_X,test_Y = X_values[(X_values.shape[0]-n_predict):,:],Y_values[(X_values.shape[0]-n_predict):]\n \n #reshaping train and test to feed to LSTM\n train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))\n test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))\n \n return train_X,train_Y,test_X,test_Y\n \n # convert an array of values into a dataset matrix\n def numpydf(self,dataset, look_back):\n dataX, dataY = [], []\n for i in range(len(dataset)-look_back-1):\n a = dataset[i:(i+look_back), 0]\n dataX.append(a)\n dataY.append(dataset[i + look_back, 0])\n\n # x,y=numpy.array(dataX), numpy.array(dataY)\n return np.array(dataX), np.array(dataY)\n \n def model_save(self,model):\n import os.path\n savedmodelname=self.model_name\n path = os.path.join(self.deploy_location,savedmodelname) \n model.save(path)\n return (savedmodelname)\n \n ## MLP model buid\n def mlpDL(self,df):\n self.log.info(\"MLP timeseries learning starts.....\") \n try:\n self.getdlparams()\n # look_back = self.look_back\n dataset = df.values\n dataset = dataset.astype('float32')\n ##The below Kwiatkowski-Phillips-Schmidt-Shin (kpss) statsmodel lib used for stationary check as well getting number of lags. \n ##number of lag calculated just for reference ,not used now.\n #Dont delete this, just use in future.\n from statsmodels.tsa.stattools import kpss\n statistic, p_value, n_lags, critical_values = kpss(df[self.targetFeature])\n self.log.info(\"Based on kpss statsmodel, lag order (time steps to calculate next prediction) is: \\\\t\"+str(n_lags))\n scaler = MinMaxScaler(feature_range=(0, 1))\n dataset = scaler.fit_transform(dataset)\n # split into train and test sets\n train_size = int(len(", "instruction": "", "output": "" }, { "input": "dataset) * 0.80)\n test_size = len(dataset) - train_size\n train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]\n self.hpt_train=train\n tuner_alg=self.tuner_algorithm\n try:\n ## Remove untitled_project dir in AION root folder created by previous tuner search run\n import shutil\n shutil.rmtree(r\".\\\\untitled_project\")\n except:\n pass\n if (tuner_alg.lower()==\"randomsearch\"):\n tuner=RandomSearch(self.build_model,keras_tuner.Objective(\"val_loss\", direction=\"min\"),max_trials=5,executions_per_trial=3)\n elif (tuner_alg.lower()==\"bayesianoptimization\"):\n tuner=BayesianOptimization(self.build_model,keras_tuner.Objective(\"val_loss\", direction=\"min\"),max_trials=5,executions_per_trial=3)\n elif (tuner_alg.lower()==\"hyperband\"):\n tuner=Hyperband(self.build_model,keras_tuner.Objective(\"val_loss\", direction=\"min\"),max_epochs=50,factor=3)\n # tuner.search(X[...,np.new_axis],y,epochs=2,validation_data=(y[...,np.newaxis]))\n stop_early = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)\n try:\n tuner.search(x=train,y=train,validation_data=(test,test),callbacks=[stop_early])\n except:\n tuner.search(x=train,y=train,validation_split=0.2,callbacks=[stop_early])\n # best_model=tuner.get_best_models(num_models=1)[0]\n best_hps=tuner.get_best_hyperparameters(num_trials=1)[0]\n best_first_layer=best_hps.get('units')\n best_dropout=best_hps.get('Dropout_rate')\n best_learning_rate=float(best_hps.get('learning_rate'))\n self.log.info(\"best hyperparameter values for mlp: \\\\n\"+str(best_hps.values))\n look_back = 1 ## Because univariate problemtype\n trainX, trainY = self.numpydf(train, look_back)\n testX, testY = self.numpydf(test, look_back)\n best_hmodel=tuner.hypermodel.build(best_hps)\n ##Added for mlp issue,because tuner build also need to compile.\n try:\n best_hmodel.compile(loss=self.loss_fn, optimizer=self.optimizer)\n except:\n pass \n model_fit = best_hmodel.fit(trainX, trainY, epochs=self.epochs, batch_size=self.batch_size, verbose=2)\n val_acc_per_epoch = model_fit.history['loss']\n best_epoch = val_acc_per_epoch.index(min(val_acc_per_epoch)) + 1\n self.log.info(\"MLP best epochs value:\\\\n\"+str(best_epoch)) \n trainScore = best_hmodel.evaluate(trainX, trainY, verbose=0)\n testScore = best_hmodel.evaluate(testX, testY, verbose=0)\n #Scoring values for the model\n mse_eval=testScore\n try:\n #If mse_eval is list of values\n min_v=min(mse_eval)\n except:\n #If mse_eval is single value\n min_v=mse_eval \n rmse_eval = math.sqrt(min_v)\n # generate predictions for training\n trainPredict = best_hmodel.predict(trainX)\n #print(testX) \n testPredict = best_hmodel.predict(testX)\n #print(testPredict)\n # invert predictions, because we used mimanmax scaler\n trainY = scaler.inverse_transform([trainY]) \n trainPredict = scaler.inverse_transform(trainPredict)\n ## For test data\n testY = scaler.inverse_transform([testY])\n testPredict = scaler.inverse_transform(testPredict)\n ## Creating dataframe for actual,predictions\n predictions = pd.DataFrame(testPredict, columns=[self.targetFeature+'_pred'])\n actual = pd.DataFrame(testY.T, columns=[self.targetFeature+'_actual'])\n df_predicted=pd.concat([actual,predictions],axis=1)\n #print(df_predicted)\n from math import sqrt\n from sklearn.metrics import mean_squared_error\n try:\n mse_mlp = mean_squared_error(testY.T,testPredict)\n rmse_mlp=sqrt(mse_mlp)\n self.log.info('mse_mlp: '+str(mse_mlp))\n self.log.info('rmse_mlp: '+str(rmse_mlp))\n from sklearn.metrics import r2_score\n from sklearn.metrics import mean_absolute_error\n r2 = r2_score(testY.T,testPredict)\n mae = mean_absolute_error(testY.T,testPredict)\n self.log.info('r2_mlp: '+str(r2))\n self.log.info('mae_mlp: '+str(mae))\n except Exception as e:\n import traceback\n self.log.info(\"MLP dataframe creation error traceback: \\\\n\"+str(traceback.print_exc()))\n self.log.info(e)\n # df_predicted.to_csv('mlp_prediction.csv')\n\n except Exception as e: \n self.log.info(\"MLP timeseries model traceback error msg e: \"+str(e))\n self.log.info(\"MLP training successfully completed.\\\\n\")\n return mse_mlp,rmse_mlp,r2,mae,best_hmodel,df_predicted,look_back,scaler\n \n ## Added function for hyperparam tuning (TFSTask:7033)\n def build_model(self,hp):\n try:\n loss=self.loss_fn\n optimizer=self.optimizer\n try:\n if optimizer.lower() == \"adam\":\n optimizer=tf.keras.optimizers.Adam\n elif(optimizer.lower() == \"adadelta\"):\n optimizer=tf.keras.optimizers.experimental.Adadelta\n elif(optimizer.lower() == \"nadam\"):\n optimizer=tf.keras.optimizers.experimental.Nadam\n elif(optimizer.lower() == \"adagrad\"):\n optimizer=tf.keras.optimizers.experimental.Adagrad\n elif(optimizer.lower() == \"adamax\"):\n optimizer=tf.keras.optimizers.experimental.Adamax\n elif(optimizer.lower() == \"rmsprop\"):\n optimizer=tf.keras.optimizers.experimental.RMSprop\n elif(optimizer.lower() == \"sgd\"):\n optimizer=tf.keras.optimizers.experimental.SGD\n else:\n optimizer=tf.keras.optimizers.Adam \n except:\n optimizer=tf.keras.optimizers.Adam\n pass\n first_layer_min=round(int(self.first_layer[0]))\n first_layer_max=round(int(self.first_layer[1]))\n dropout_min=float(self.dropout[0])\n dropout_max=float(self.dropout[1])\n model=tf.keras.Sequential()\n if (self.model_type.lower() == 'lstm'):\n model.add(LSTM(units=hp.Int('units',min_value=first_layer_min,max_value=first_layer_max,step=16),input_shape=(self.look_back,self.hpt_train.shape[1]),\n activation=hp.Choice('dense_activation',values=['relu'])))\n elif (self.model_type.lower() == 'mlp'):\n # model.add(Dense(units=hp.Int('units',min_value=first_layer_min,max_value=first_layer_max,step=16),input_dim=(hp.Int('time_steps',min_value=look_back_min,max_value=look_back_max,step=1)),\n # activation='relu'))\n ##input_dim is 1 because mlp is for univariate.\n model.add(Dense(units=hp.Int('units',min_value=first_layer_min,max_value=first_layer_max,step=16),input_dim=(1),activation='relu'))\n model.add(Dropout(hp.Float('Dropout_rate',min_value=dropout_min,max_value=dropout_max,step=0.1)))\n model.add(Dense(units=1))\n model.compile(optimizer=optimizer(hp.Choice('learning_rate',values=[1e-1,1e-2,1e-3,1e-4])),loss=loss,metrics=[loss])\n except Exception as e:\n import traceback\n self.log.info(\"lstm errorbuild_model traceback: \\\\n\"+str(traceback.print_exc()))\n return model\n \n ##LSTM timeseries function call\n def ts_lstm(self,df):\n self.log.info(\"lstm network model learning starts.....\\\\n\")\n try:\n self.getdlparams()\n dataset = df.values\n dataset = dataset.astype('float32')\n ##The below Kwiatkowski-Phillips-Schmidt-Shin (kpss) statsmodel lib used for stationary check as well getting number of lags. \n ##number of lag calculated just for reference ,not used now.\n #Dont delete this, just use in future.\n from statsmodels.tsa.stattools import kpss\n statistic, p_value, n_lags, critical_values = kpss(df[self.targetFeature])\n self.log.info(\"Based on kpss statsmodel, lag order (time steps to calculate next prediction) is: \\\\t\"+str(n_lags))\n # normalize the dataset\n scaler = MinMaxScaler(feature_range=(0, 1))\n dataset = scaler.fit_transform(dataset)\n # split into train and test sets\n train_size = int(len(dataset) * 0.80)\n test_size = len(dataset) - train_size\n train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]\n self.hpt_train=train\n tuner_alg=self.tuner_algorithm\n try:\n ## Remove untitled_project dir in AION root folder created by previous tuner search run\n import shutil\n shutil.rmtree(r\".\\\\untitled_project\")\n except:\n pass\n if (tuner_alg.lower()==\"randomsearch\"):\n tuner=RandomSearch(self.build_model,keras_tuner.Objective(\"val_loss\", direction=\"min\"),max_trials=5,executions_per_trial=3)\n elif (tuner_alg.lower()==\"bayesianoptimization\"):\n tuner=BayesianOptimization(self.build_model,keras_tuner.Objective(\"val_loss\", direction=\"min\"),max_trials=5,executions_per_trial=3)\n elif (tuner_alg.lower()==\"hyperband\"):\n tuner=Hyperband(self.build_model,keras_tuner.Objective(\"val_loss\", direction=\"min\"),max_epochs=50,factor=3)\n # tuner.search(X[...,np.new_axis],y,epochs=2,validation_data=(y[...,np.newaxis]))\n from keras.callbacks import EarlyStopping\n stop_early = EarlyStopping(monitor='val_loss', patience=5)\n ##Need both x and y with same dimention.\n tuner.search(x=train,y=train,validation_split=0.2,callbacks=[stop_early])\n # tuner.search(x=train,y=test,validation_data=(test,test),callbacks=[stop_early])\n best_hps=tuner.get_best_hyperparameters(num_trials=1)[0]\n best_time_steps=self.look_back\n self.log.info(\"best lag order or lookback (time_steps) for LSTM: \\\\n\"+str(best_time_steps))\n self.log.info(\"best hyperparameter values for LSTM: \\\\n\"+str(best_hps.values))\n look_back = best_time_steps\n trainX, trainY = self.numpydf(train, look_back)\n testX, testY = self.numpydf(test, look_back)\n # reshape input to be [samples, time steps, features]\n trainX = np.reshape(trainX, (trainX.shape[0], trainX.shape[1], 1))\n testX = np.reshape(testX, (testX.shape[0], testX.shape[1], 1))\n #create and fit the LSTM network \n best_hmodel=tuner.hypermodel.build(best_hps) \n try:\n best_hmodel.compile(loss=self.loss_fn, optimizer=self.optimizer)\n except:\n pass\n model_fit = best_hmodel.fit(trainX, trainY, validation_split=0.2, epochs=self.epochs, batch_size=self.batch_size, verbose=2)\n val_acc_per_epoch = model_fit.history['loss']\n best_epoch = val_acc_per_epoch.index(min(val_acc_per_epoch)) + 1\n self.log.info(\"best epochs value:\\\\n\"+str(best_epoch))\n # best_hmodel=tuner.hypermodel.build(best_hps)\n # best_hmodel.fit(x=trainX,y=trainY,validation_split=0.2,epochs=best_epoch)\n ##Using model_evaluate,calculate mse\n # mse_eval = model.evaluate(testX, testY, verbose=0)\n mse_eval = best_hmodel.evaluate(testX, testY, verbose=0)\n try:\n #If mse_eval is list of values\n min_v=min(mse_eval)\n except:\n #If mse_eval is single value\n min_v=mse_eval\n rmse_eval=math.sqrt(min_v) \n # self.log.info('LSTM mse:'+str(mse_eval))\n # self.log.info('LSTM rmse:'+str(rmse_eval))\n # lstm time series predictions\n trainPredict = best_hmodel.predict(trainX)\n testPredict = best_hmodel.predict(testX)\n # invert predictions, because we used mim=nmax scaler\n trainY = scaler.inverse_transform([trainY]) \n trainPredict = scaler.inverse_transform(trainPredict)\n testY = scaler.inverse_transform([testY])\n testPredict = scaler.inverse_transform(testPredict)\n ## Creating dataframe for actual,predictions\n predictions = pd.DataFrame(testPredict, columns=[self.targetFeature+'_pred'])\n actual = pd.DataFrame(testY.T, columns=[self.targetFeature+'_actual'])\n df_predicted=pd.concat([actual,", "instruction": "", "output": "" }, { "input": "predictions],axis=1)\n from math import sqrt\n from sklearn.metrics import mean_squared_error\n try:\n mse_lstm=None\n mse_lstm = mean_squared_error(testY.T,testPredict)\n rmse_lstm=sqrt(mse_lstm) \n self.log.info(\"mse_lstm: \"+str(mse_lstm))\n self.log.info(\"rmse_lstm: \"+str(rmse_lstm))\n from sklearn.metrics import r2_score\n from sklearn.metrics import mean_absolute_error\n r2 = r2_score(testY.T,testPredict)\n mae = mean_absolute_error(testY.T,testPredict)\n self.log.info('r2_lstm: '+str(r2))\n self.log.info('mae_lstm: '+str(mae))\n except Exception as e: \n self.log.info(\"lstm error loss fns\"+str(e))\n return 'Error',0,0,0,0,None,pd.DataFrame(),0,None\n except Exception as e:\n import traceback\n self.log.info(\"lstm training error traceback: \\\\n\"+str(traceback.print_exc()))\n return 'Error',0,0,0,0,None,pd.DataFrame(),0,None\n return 'Success',mse_lstm,rmse_lstm,r2,mae,best_hmodel,df_predicted,look_back,scaler\n \n \n\nif __name__ == '__main__':\n print('Inside timeseriesDLUnivariate main....\\\\n')\n# tsdl_obj = timeseriesDLUnivariate()\n \n ## for testing purpose\n '''\n df1= pd.read_csv(r\"C:\\\\aiontest\\\\testPrograms\\\\Data\\\\energydemand.csv\",encoding='utf-8', engine='python')\n dateTimeFeature = \"utcTimeStamp\"\n targetFeature=\"temperature\" \n try:\n df1[dateTimeFeature] = pd.to_datetime(df1[dateTimeFeature]) #, format = '%d/%m/%Y %H.%M')\n except:\n pass\n tdata = df1.drop([dateTimeFeature], axis=1)\n tdata.index = df1[dateTimeFeature]\n tdata = pd.DataFrame(tdata[targetFeature])\n cols = tdata.columns \n mse,rmse,model = tsdl_obj.mlpDL(tdata)\n lmse,lrmse,lstmmodel = tsdl_obj.ts_lstm(tdata)\n print(\"mlp mse: \\\\n\",mse)\n print(\"mlp rmse: \\\\n\",rmse)\n print(\"lstm mse: \\\\n\",lmse)\n print(\"lstm rmse: \\\\n\",lrmse)\n savedmodelname=tsdl_obj.model_save(lstmmodel)\n '''\n\n '''\n*\n* =============================================================================\n* COPYRIGHT NOTICE\n* =============================================================================\n* @ Copyright HCL Technologies Ltd. 2021, 2022,2023\n* Proprietary and confidential. All information contained herein is, and\n* remains the property of HCL Technologies Limited. Copying or reproducing the\n* contents of this file, via any medium is strictly prohibited unless prior\n* written permission is obtained from HCL Technologies Limited.\n*\n'''\nimport pandas as pd\nimport os\nimport numpy as np\nimport numpy\nimport pandas\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import LSTM\nfrom sklearn.preprocessing import MinMaxScaler\nimport logging\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Dropout\nimport math\nimport tensorflow as tf\nimport keras_tuner\n#from keras_tuner.engine.hyperparameters import HyperParameters\nfrom keras_tuner.tuners import RandomSearch,BayesianOptimization ,Hyperband\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.preprocessing.sequence import TimeseriesGenerator\nimport warnings\nwarnings.simplefilter(\"ignore\", UserWarning)\n\n\nclass timeseriesDLMultivariate:\n def __init__(self,configfile,testpercentage,targetFeature,dateTimeFeature):\n self.look_back=None\n \n # self.df=df\n \n self.epochs=None\n self.batch_size=None\n self.hidden_layers=None\n self.optimizer=None\n self.activation_fn=\"relu\"\n self.loss_fn=None\n self.first_layer=None\n self.dropout=None\n self.model_name=None\n self.dl_params = configfile\n # self.data=data\n self.targetFeature=targetFeature\n self.dateTimeFeature=dateTimeFeature\n self.testpercentage = float(testpercentage) \n self.log = logging.getLogger('eion')\n ##Added for ts hpt (TFSTask:7033)\n self.tuner_algorithm=\"\" \n self.num_features=0\n \n ##Get deep learning model hyperparameter from advanced config\n def getdlparams(self):\n val=self.dl_params\n self.log.info('-------> The given mlp/lstm timeseries algorithm parameters:>>') \n self.log.info(\" \"+str(val))\n for k,v in val.items():\n try:\n if (k == \"tuner_algorithm\"):\n self.tuner_algorithm=str(v)\n elif (k == \"activation\"):\n self.activation_fn=str(v)\n elif (k == \"optimizer\"):\n self.optimizer=str(v)\n elif (k == \"loss\"):\n self.loss_fn=str(v)\n elif (k == \"first_layer\"):\n if not isinstance(k,list):\n self.first_layer=str(v).split(',')\n else:\n self.first_layer=k\n elif (k == \"lag_order\"):\n if isinstance(k,list):\n k = ''.join(v)\n k=int(float(str(v)))\n else: \n self.look_back=int(float(str(v)))\n elif (k == \"hidden_layers\"):\n self.hidden_layers=int(v)\n elif (k == \"dropout\"): \n if not isinstance(k,list):\n self.dropout=str(v).split(',')\n else:\n self.dropout=k\n elif (k == \"batch_size\"):\n self.batch_size=int(v)\n elif (k == \"epochs\"):\n self.epochs=int(v)\n elif (k == \"model_name\"):\n self.model_name=str(v)\n \n except Exception as e: \n self.log.info('Exception occured in deeep learn param reading, setting up default params.')\n self.activation_fn=\"relu\"\n self.optimizer=\"adam\"\n self.loss_fn=\"mean_squared_error\"\n self.first_layer=[8,512]\n self.hidden_layers=1\n self.look_back=int(2)\n self.dropout=[0.1,0.5]\n self.batch_size=2\n self.epochs=50\n self.model_name=\"lstmmodel.h5\"\n continue\n \n # Reshape the data to the required input shape of the LSTM model\n def create_dataset(self,X, y, n_steps):\n Xs, ys = [], []\n for i in range(len(X) - n_steps):\n v = X.iloc[i:(i + n_steps)].values\n Xs.append(v)\n ys.append(y.iloc[i + n_steps])\n return np.array(Xs), np.array(ys) \n\n \n ## Added function for hyperparam tuning (TFSTask:7033)\n def build_model(self,hp):\n n_features = len(self.targetFeature)\n try:\n loss=self.loss_fn\n optimizer=self.optimizer\n # self.getdlparams()\n try:\n if optimizer.lower() == \"adam\":\n optimizer=tensorflow.keras.optimizers.Adam\n elif(optimizer.lower() == \"adadelta\"):\n optimizer=tensorflow.keras.optimizers.experimental.Adadelta\n elif(optimizer.lower() == \"nadam\"):\n optimizer=tensorflow.keras.optimizers.experimental.Nadam\n elif(optimizer.lower() == \"adagrad\"):\n optimizer=tensorflow.keras.optimizers.experimental.Adagrad\n elif(optimizer.lower() == \"adamax\"):\n optimizer=tensorflow.keras.optimizers.experimental.Adamax\n elif(optimizer.lower() == \"rmsprop\"):\n optimizer=tensorflow.keras.optimizers.experimental.RMSprop\n elif(optimizer.lower() == \"sgd\"):\n optimizer=tensorflow.keras.optimizers.experimental.SGD\n else:\n optimizer=tensorflow.keras.optimizers.Adam \n except:\n optimizer=tf.keras.optimizers.Adam\n pass \n # look_back_min=int(self.look_back[0])\n # look_back_max=int(self.look_back[1])\n first_layer_min=round(int(self.first_layer[0]))\n first_layer_max=round(int(self.first_layer[1]))\n dropout_min=float(self.dropout[0])\n dropout_max=float(self.dropout[1]) \n model=tf.keras.Sequential() \n try:\n model.add(LSTM(units=hp.Int('units',min_value=first_layer_min,max_value=first_layer_max,step=16),input_shape=(self.look_back,self.num_features)))\n except Exception as e:\n import traceback\n self.log.info(\"lstm build traceback: \\\\n\"+str(traceback.print_exc()))\n return model\n model.add(Dropout(hp.Float('Dropout_rate',min_value=dropout_min,max_value=dropout_max,step=0.1)))\n model.add(Dense(units=n_features))\n model.compile(optimizer=optimizer(hp.Choice('learning_rate',values=[1e-1,1e-2,1e-3,1e-4])),loss=loss,metrics=[self.loss_fn])\n except Exception as e: \n self.log.info(\",Hyperparam tuning build_model err msg: \\\\n\"+ str(e))\n return model\n ##Multivariate lstm prediction function (lstm model, train, prediction, metrics)\n def lstm_multivariate(self,df): \n try: \n self.getdlparams()\n n_features = len(self.targetFeature)\n self.num_", "instruction": "", "output": "" } ]