input stringlengths 6 17.2k | output stringclasses 1
value | instruction stringclasses 1
value |
|---|---|---|
].astype(str).str.split().str.len()) > 10) and targetFeature != item[0]:
self.textFtrs.append(item[0])
else:
self.allCatCols.append(item[0])
else:
self.allCatCols.append(item[0])
misval_ratio = float(conf_json['misValueRatio'])
self.configDict['misval_ratio'] = misval_ratio
missing... | ||
try:
self.log.info('\\n---------- Creating Incremental profiler models ----------')
self.createIncProfiler(df, conf_json, allNumCols, numFtrs, allCatCols, textFtrs, missingValFtrs)
self.log.info('\\n--------- Incremental profiler models have been created ---------')
except Exception as inst:
se... | ||
-------> Remove Duplicate Rows')
dataframe = dataframe.dropna(axis=0,how='all',subset=dataColumns)
noofdplicaterows = dataframe.duplicated(keep='first').sum()
dataframe = dataframe.drop_duplicates(keep="first")
dataframe = dataframe.reset_index(dr | ||
cmd):
try:
subprocess.check_output(cmd, stderr=subprocess.PIPE)
except subprocess.CalledProcessError as e:
if e.stderr:
if isinstance(e.stderr, bytes):
err_msg = e.stderr.decode(sys.getfilesystemencoding())
else:
err_msg = e.stderr
... | ||
response = requests.post(ser_url, data=inputFieldsJson,headers={"Content-Type":"application/json",})
outputStr=response.content
outputStr = outputStr.decode('utf-8')
outputStr = outputStr.strip()
decoded_data = json.loads(outputStr)
print(decoded_data)
... | ||
ined_model_path():
try:
from appbe.dataPath import DATA_DIR
modelsPath = Path(DATA_DIR)/'PreTrainedModels'/'TextProcessing'
except:
modelsPath = Path('aion')/'PreTrainedModels'/'TextProcessing'
if not modelsPath.exists():
modelsPath.mkdir(parents=True, exist_ok=True)
retu... | ||
chunk_embeddings.append( get_embedding(chunk, engine=self.embedding_engine))
chunk_lens.append(len(chunk))
chunk_embeddings = np.average(chunk_embeddings, axis=0, weights=None)
chunk_embeddings = chunk_embeddings / np.linalg.norm(chunk_embeddings) # normalizes length to 1
chunk_emb... | ||
ags,
removeNoise_RemoveOrReplaceEmoji,
removeNoise_fUnicodeToAscii,
removeNoise_fRemoveNonAscii)
if function == 'ExpandContractions':
if (fExp... | ||
counter = Counter(tags)
x, y = list(map(list, zip(*counter.most_common(7))))
return pd.DataFrame([x, y],index=['postag', 'freq']).T
except:
self.__Log("exception", sys.exc_info())
raise
def MostCommonWordsInPOSTag(self, inputCorpus, ... | ||
ngram_min = 1
ngram_max = 1
invalidNgramWarning = 'WARNING : invalid ngram config.\\nUsing the default values min_n={}, max_n={}'.format(ngram_min, ngram_max)
self.log.info(invalidNgramWarning)
ngram_range_tuple = (ngram_min, ngram_max)
textConversionMethod = conf_json.get('textConversionMethod')
c... | ||
None
params=None
threshold = -1
precisionscore =-1
recallscore = -1
objClf = aion_matrix()
try:
lr = LogisticRegression(solver='lbfgs',random_state=1,max_iter=200)
rf = RandomForestClassifier(random_state=1)
gnb = GaussianNB()
svc = SVC(probability=True) #Need to keep probability=True... | ||
#NAME? | ||
MakeFP0 = True
self.log.info('-------- Calculate Threshold for FP End-------')
if self.MakeFN0:
self.log.info('-------- Ensemble: Calculate Threshold for FN Start-------')
startRange = 1.0
endRange = 0.0
... | ||
)
self.log.info('\\n--------- Performance Matrix with Train Data ---------')
trainingperformancematrix = mlobj.get_regression_matrix(ytrain, predictedData)
self.log.info('--------- Performance Matrix with Train Data End---------\\n')
predictedData = self.getDLPredictionData(model_dl,hist_reloaded,xtest)
... | ||
self.testX = testX
self.testY = testY
self.method =method
#self.logFile = logFile
self.randomMethod=randomMethod
self.roundLimit=roundLimit
self.log = logging.getLogger('eion')
self.best_feature_model = best_feature_model
def RNNRegression(self,x_train,y_train,x_val,y_val,params):
tf.keras.ba... | ||
": [float(n) for n in data["dropout"].split(",")],
"lr": [float(n) for n in data["learning_rate"].split(",")],
"batch_size": [int(n) for n in data["batch_size"].split(",")],
"epochs": [int(n) for n in data["epochs"].split(",")]}
scan_object = talos.Scan(x=X_train,y=y_train,x_val = X_test... | ||
_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)
matrix_type = 'val_loss'
if self.scoreParam.lower() == 'rmse':
matrix_type = 'val_rmse_m'
elif(self.... | ||
best_model = best_modelRNNGRU
best_params = best_paramsRNNGRU
elif len(scoreRNNLSTM) != 0 and max(modelScore) == scoreRNNLSTM[1]:
selectedModel = "Recurrent Neural Network (LSTM)"
best_model = best_modelRNNLSTM
best_params = best_paramsRNNLSTM
elif len(scoreCNN) !... | ||
activation":data["last_activation"].split(","),
"optimizer":data["optimizer"].split(","),
"losses":data["losses"].split(","),
"first_neuron":[int(n) for n in data["first_layer"].split(",")],
"shapes": data["shapes"].split(","),
"hidden_layers":[int(n) for n in data["hidden_layers"].split("... | ||
optimizer = 'Nadam'
batchsize = 32
if self.scoreParam == 'accuracy':
best_modelRNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=['accuracy'])
elif self.scoreParam == 'recall':
best_modelRNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[recall_m])
elif self.scorePara... | ||
ochs"].split(",")]}
param_combinations = int(np.prod([len(x.split(',')) for x in p]))
round_limit = self.roundLimit if not self.roundLimit else min(self.roundLimit, param_combinations)
scan_object = talos.Scan(x=X_train,
y=y_train,
x_val = X_test,
y_val = y_test,
model = modelOb... | ||
elif self.scoreParam == 'recall':
best_modelCNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[recall_m])
elif self.scoreParam == 'precision':
best_modelCNN.compile(loss=loss_matrix,optimizer=optimizer, metrics=[precision_m])
elif self.scoreParam == 'roc_auc':
best_modelCNN.compile(los... | ||
columns)
else:
df = pd.DataFrame(df, columns=columns)
return df
"""
return code.replace('\\n', '\\n'+(indent * TAB_CHAR))
def feature_selector_code( params, indent=0):
modules = [
{'module': 'pandas', 'mod_from': None, 'mod_as': 'pd'}
]
code = """
class selector():
# this class ... | ||
File += '\\n'
#self.predictionFile += ' jsonData = json.loads(json_data)'
self.predictionFile += ' jsonData=json_data'
self.predictionFile += '\\n'
self.predictionFile += ' model_obj = importlib.util.spec_from_file_location("module.name", os.path.dirname(o... | ||
+= ' output = json.dumps(output)'
self.predictionFile += '\\n'
self.predictionFile += ' print("drift:",output)'
self.predictionFile += '\\n'
self.predictionFile += ' return(output)'
self | ||
as e:
print(e)
output = {"status":"FAIL","message":str(e).strip('"')}
print("drift:",json.dumps(output))
return (json.dumps(output))
except Exception as e:
print(e)
output = {"status":"FAIL","message":str(e).strip('"')}
print("drift:",json.dumps(output))
... | ||
performance_dashboard.as_dict()
output = {"status":"SUCCESS","htmlPath":report, 'drift_details':metrics_output['metrics']}
print("drift:",json.dumps(output))
return (json.dumps(output))
else:
output = {"status":"SUCCESS","htmlPath":'NA'}
... | ||
prodData'):
return jsonify({'status':'Error','msg':'Prod data not available'})
data = sqlite_dbObj.read('prodData')
filetimestamp = str(int(time.time()))
dataFile = dataPath/('AION_' + filetimestamp+'.csv')
data.to_csv(dataFile, index=False)
data =... | ||
rietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''
import subprocess
import os... | ||
l \\
&& python -m pip install --no-cache-dir scikit-learn==0.24.2 \\
&& python -m pip install --no-cache-dir -r requirements.txt \\
&& chmod +x start_modelservice.sh
ENTRYPOINT ["./start_modelservice.sh"]
'''
f = open(dockerfile, "w")
f.write(str(dockerdata))
f.close()
requirementdata=''
requir... | ||
.to_json(orient='records',double_precision=5)
outputjson = {"status":"SUCCESS","data":json.loads(outputjson)}
return(json.dumps(outputjson))
"""
class regression( deployer):
def __init__(self, params={}):
super().__init__( params)
self.feature_reducer = False
... | ||
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... | ||
'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', 'expens... | ||
'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_vec... | ||
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', 'r... | ||
_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_ve... | ||
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', '... | ||
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', 'eff... | ||
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', 'lang... | ||
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',... | ||
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',... | ||
path.join(project_path, subdir))
encrypt(alldirs)
print("*"*50)
replace_by_compressed(alldirs)
# python eion_compress.py "C:\\Users\\ashwani.s\\Desktop\\22April\\22April\\Mohita" "C:\\Users\\ashwani.s\\Desktop\\eion\\eion" > logfile.log
<s> '''
*
* ==================================================================... | ||
readme+= '========== How to call the model =========='
self.readme+='\\n'
self.readme+= '============== From Windows Terminal =========='
self.readme+='\\n'
if method == 'optimus_package':
self.readme += 'python aion_prediction.py filename.json'
self.readme +='\\n... | ||
# continue
operation = action['Action']
if(operation == 'Drop'):
self.profilerfile += " if '"+feature+"' in df.columns:"
self.profilerfile += '\\n'
self.profilerfile += " ... | ||
def print_files(self):
self.log.info(self.modelfile)
def create_util_folder(self, deploy_path,learner_type):
import tarfile
ext_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..','utilities'))
for x in os.listdir(ext_path):
if x.endswith('.tar'):
... | ||
["input_ids"], max_length=512, min_length=140, length_penalty=2.0, num_beams=4, early_stopping=True)
summarizedOutputOfSection= tokenizer.decode(outputs[0])
summarizedOutputOfSection=summarizedOutputOfSection.replace("</s>","")
summarizedOutputOfSection=summarizedOutputOfSection.replace("<s>",""... | ||
compile=False)"
self.modelfile += '\\n'
self.modelfile += ' self.model.compile(loss=\\''+loss_matrix+'\\',optimizer=\\''+optimizer+'\\', metrics=[f1_m])'
self.modelfile += '\\n'
elif scoreParam == 'r2':
self.modelfile += " self.mode... | ||
self.modelfile += '\\n'
self.modelfile += ' test_sentence2 = self.preprocessing.texts_to_sequences(X["'+secondDocFeature+'"].values)'
self.modelfile += '\\n'
self.modelfile += ' test_sentence1 = pad_sequences(test_sentence1, maxlen='+str(padding_length)+', padding=\\'post... | ||
self.modelfile += ' for i in range(0, len(y_future)):'
self.modelfile += '\\n'
self.modelfile += ' pred.iloc[i] = y_future[i]'
self.modelfile += '\\n'
... | ||
+= ' outputjson = {"status":"SUCCESS","data":json.loads(outputjson)}'
self.output_formatfile += '\\n'
elif(learner_type == 'TS'):
if(model == 'VAR'):
self.output_formatfile += ' modeloutput = | ||
YRIGHT NOTICE
* =============================================================================
* @ Copyright HCL Technologies Ltd. 2021, 2022,2023
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this fi... | ||
= {"status":"SUCCESS","data":json.loads(df)}
return(json.dumps(outputjson))
"""
class mlp( lstm):
def __init__(self, params={}):
super().__init__( params)
self.name = 'timeseriesforecasting'
def training_code( self): | ||
modelname']= str(modelname)
self.displayjson['preprocessedData'] = str(original_data_file)
self.displayjson['nrows'] = str(nrows)
self.displayjson['ncols'] = str(ncols)
self.displayjson['saved_model'] = str(saved_model)
self.displayjson['scoreParam'] = str(scoreParam)
self.displayjson['labelMaps'] = eval(st... | ||
{\\\\"field\\\\":\\\\"'+ycolumn+'\\\\",\\\\"size\\\\":100,\\\\"order\\\\":\\\\"asc\\\\",\\\\"orderBy\\\\":\\\\"1\\\\",\\\\"otherBucket\\\\":false,\\\\"otherBucketLabel\\\\":\\\\"Other\\\\",\\\\"missingBucket\\\\":false,\\\\"missingBucketLabel\\\\":\\\\"Missing\\\\"}}]}","uiStateJSON":"{}","description": "","version": 1... | ||
ialize a list of prediction and/or
an algorithm that were dumped on drive using :func:`dump()
<surprise.dump.dump>`.
Args:
file_name(str): The path of the file from which the algorithm is
to be loaded
Returns:
A tuple ``(predictions, algo)`` where ``predictions`` is a list ... | ||
dict(list)
# user raw id, item raw id, translated rating, time stamp
for urid, irid, r, timestamp in raw_trainset:
try:
uid = raw2inner_id_users[urid]
except KeyError:
uid = current_u_index
raw2inner_id_users[urid] = current_u_inde... | ||
always space-separated (use the ``sep`` parameter). Default is
``'user item rating'``.
sep(char): the separator between fields. Example : ``';'``.
rating_scale(:obj:`tuple`, optional): The rating scale used for every
rating. Default is ``(1, 5)``.
skip_lines(:... | ||
ices)) + 1
) # sklearn starts at 1 as well
best_index[m] = mean_test_measures.argmin()
elif m in ("fcp",):
cv_results[f"rank_test_{m}"][indices] = np.arange(len(indices), 0, -1)
best_index[m] = mean_test_measures.argmax()
best_para... | ||
distribution, sampling with replacement is used.
It is highly recommended to use continuous distributions for continuous
parameters.
Note that before SciPy 0.16, the ``scipy.stats.distributions`` do not
accept a custom RNG instance and always use the singleton RNG from
``numpy.r... | ||
"""
if self.n_splits > len(data.raw_ratings) or self.n_splits < 2:
raise ValueError(
"Incorrect value for n_splits={}. "
"Must be >=2 and less than the number "
"of ratings".format(len(data.raw_ratings))
)
# We use indice... | ||
set, testset
def get_n_folds(self):
return self.n_splits
<s> """
the :mod:`knns` module includes some k-NN inspired algorithms.
"""
import heapq
import numpy as np
from .algo_base import AlgoBase
from .predictions import PredictionImpossible
# Important note: as soon as an algorithm uses a similarit... | ||
mas = np.zeros(self.n_x)
# when certain sigma is 0, use overall sigma
self.overall_sigma = np.std([r for (_, _, r) in self.trainset.all_ratings()])
for x, ratings in self.xr.items():
self.means[x] = np.mean([r for (_, r) in ratings])
sigma = np.std([r for (_, r) in ratin... | ||
note<raw_inner_note>`.
iid: The (raw) item id. See :ref:`this note<raw_inner_note>`.
r_ui(float): The true rating :math:`r_{ui}`.
est(float): The estimated rating :math:`\\\\hat{r}_{ui}`.
details (dict): Stores additional details about the prediction that
might be useful for ... | ||
self.mlflowtosagemakerDeploy=mlflowtosagemakerDeploy
self.mlflowtosagemakerPushOnly=str(mlflowtosagemakerPushOnly)
self.mlflowtosagemakerPushImageName=str(mlflowtosagemakerPushImageName)
self.mlflowtosagemakerdeployModeluri=str(mlflowtosagemakerdeployModeluri)
... | ||
lops_trackuri=mlops_trackuri.replace('file:','')
mlops_trackuri=str(mlops_trackuri)
# mlflow_root_dir = os.getcwd()
mlflow_root_dir = None
try:
os.chdir(str(self.sagemakerLogLocation))
mlflow_root_dir = os.getcwd()
self.log.... | ||
any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*
'''<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* @ Copyright ... | ||
o4U3gbzWgwiYohLrhrwJ5ANun/7IB2lIykvk7B3g1nZzRYDIk
EFpuI3ppWA8NwOUUoj/zksycQ9tx5Pn0JCMKKgYXsS322ozc3B6o3AoSC5GpzDH4
UnAOwavvC0ZZNeoEX6ok8TP7EL3EOYW8s4zIa0KFgPac0Q0+T4tFhMG9qW+PWwhy
Oxeo3wKBiCQ8LEgmHnXZv3UZvwcikj6oCrPy8fnhp5RZl2DPPlaqf3vokE6W5oEo
LIKcWKvth3EU7HRKwYgaznj/Mw55aETx31R0FiXMG266B4V7QWPF/KuaR0GBsYfu
+edGXQCnLg... | ||
import VarianceThreshold
import logging
class featureReducer():
def __init__(self):
self.pandasNumericDtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
self.log = logging.getLogger('eion')
def startReducer(self,df,data_columns,target,var_threshold):
self.log.info('\\n---------- Feature Redu... | ||
numFeatureXYcat.append(col) #numeric feature xy when target is cat
featureDict[col] = AnovaResults[1]
#input vs input
# preason/spearman/ols # numeric feature xx when target is cat
if len(numFeatureXYcat) != 0:
df_xx = dataframe[numFeatureXYcat]
rows, c... | ||
miClassSeries=pd.Series(miClassScore,index=quantFeatures)
impFeatures.append(fClassSeries[fClassSeries<pValTh].index.tolist())
impFeatures.append(miClassSeries[miClassSeries>corrTh].index.tolist())
featureImpDict['anovaPValue']=fClassSeries.to_dict()
featureImpDict['MIScore']=miClassSe... | ||
'true') and featureEngineeringSelector.lower() == 'true':
# check is PCA or SVD is true
pcaColumns=[]
#print(svdReducerStatus.lower())
if target != "":
dataColumns.remove(target)
targetArray=df[target].values
targetArray.shape = (len(targetArray), 1)
if pcaReducerStatus.lower() == "tr... | ||
of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*/
"""<s> """
/**
* =============================================================================
* COPYRIGHT NOTICE
* =====... | ||
ffix}supported data type is pandas.DataFrame but provide data is of {type(xtrain)} type')
if xtrain.empty:
raise ValueError(f'{log_suffix}Data frame is empty')
if target and target in xtrain.columns:
self.target = xtrain[target]
xtrain.drop(target, axis=1, inplace=Tru... | ||
.num_fill_method_dict[f][en]
if not self.num_fill_method_dict[f]:
del self.num_fill_method_dict[f]
def update_cat_fill_dict(self):
self.cat_fill_method_dict = {}
if 'catFill' in self.process_method.keys():
for f in supported_method['fillNa']['categori... | ||
[k] == 'nochange' and v != 'disable':
self.log.info(f'-------> Total outliers in "{k}": {(~index).sum()}')
if self.config.get('outlierDetection',None):
if self.config['outlierDetection'].get('IsolationForest','False') == 'True':
index = findiforestOutl... | ||
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 return config"
return text
def __addSaveModelCode(self):
text = "\\n\\
\\ndef save_mode... | ||
targetPath = Path('aion')/config['targetPath']
targetPath.mkdir(parents=True, exist_ok=True)
log_file = targetPath/IOFiles['log']
log = logger(log_file, mode='a', logger_name=Path(__file__).parent.stem)
monitoring = targetPath/IOFiles['monitoring']
if monitoring.exists(): ... | ||
istry_uri,\\
\\n )\\
\\n self.experiment_id = self.client.get_experiment_by_name(self.model_name).experiment_id\\
\\n"
self.codeText += self.query_with_quetes_code(smaller_is_better == False)
self.codeText += "\\
\\n def __log_unprocessed_runs(self, r... | ||
pValTh,corrTh):\\
\\n import pandas as pd\\
\\n from sklearn.feature_selection import chi2\\
\\n from sklearn.feature_selection import f_classif\\
\\n from sklearn.feature_selection import mutual_info_classif\\
... | ||
\\n return file_name.startswith(supported_urls_starts_with)\\
\\n"},
'logger':{'name':'set_logger','imports':[{'mod':'logging'}],'code':f"\\n\\
\\nlog = None\\
\\ndef set_logger(log_file, mode='a'):\\
\\n... | ||
code += functions_code[name]['code']
if self.importer:
if 'imports' in functions_code[name].keys():
for module in functions_code[name]['imports']:
mod_name = module['mod']
mod_from = module.get('mod_from', None)
mod_as = mod... | ||
prediction'] = output"
text += "\\n return df_copy"
if indent:
text = text.replace('\\n', (self.tab * indent) + '\\n')
return text
def getClassificationMatrixCode(self, indent=0):
text = "\\
\\ndef get_classification_metrices(actual_values, predicted_value... | ||
_id=aws_access_key_id, aws_secret_access_key=str(aws_secret_access_key))
self.bucket_name = bucket_name
def read(self, file_name):
try:
response = self.client.get_object(Bucket=self.bucket_name, Key=file_name)
return pd.read_csv(response['Body'])
except Clie... | ||
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... | ||
hist_num_feat = historical_data.select_dtypes(include='number')
num_features = [feat for feat in historical_data.columns if feat in curr_num_feat]
alert_count = 0
data = {
'current':{'data':current_data},
'hist': {'data': h... | ||
['inputUriExternal']
elif 's3' in config.keys():
dataFileLocation = 'cloud'
else:
dataFileLocation = config['inputUri']
else:
log.info(f'Pipeline Executing first Time')
output_json.update({'Msg':'Pipeline executing first time'})
trai... | ||
production": "production.json",
"log": "aion.log",
"monitoring":"monitoring.json",
"prodData": "prodData",
"prodDataGT":"prodDataGT"
}
def DistributionFinder(data):
try:
distributionName = ""
sse = 0.0
KStestStatic = 0.0
dataType = ""
if (data.dtype == "float64" or dat... | ||
*100),2)
msg = \\"""<html>
<head>
<title>Performance Details</title>
</head>
<style>
table, th, td {border}
</style>
<body>
<h2><b>Deployed Model:</b>{ModelString}</h2>
<br/>
<table style="width:50%">
<tr>
<td>No of Prediction</td>
<td>{NoOfPrediction}</td>
</tr>
<tr>
<td>No of GroundTrut... | ||
create the dataProfiler file
profiler_importer = importModule()
importer.addLocalModule('profiler', mod_from='dataProfiler')
profiler_obj = data_profiler(profiler_importer, True if config["text_features"] else False)
code_text = profiler_obj.get_code() # import statement will be generated when profiler_... | ||
def get_training_params(config, algo):
param_keys = ["modelVersion","problem_type","target_feature","train_features","scoring_criteria","test_ratio","optimization_param"]
data = {key:value for (key,value) in config.items() if key in param_keys}
data['algorithms'] = {algo: config['algorithms'][algo]}
... | ||
.append("requirements.txt")
with open (deploy_path/"config.json", "w") as f:
json.dump(get_training_params(config, algo), f, indent=4)
generated_files.append("config.json")
create_docker_file('train', deploy_path,config['modelName'], generated_... | ||
_test"="'+str(usecasename)+'_test'+'"'
text+='\\n'
for file in files:
text+=f'\\nCOPY {file} {file}'
text+='\\n'
text+='''RUN \\
'''
text+='''pip install --no-cache-dir -r requirements.txt\\
'''
if text_feature:
text += ''' && python -m nlt... | ||
_as': None}
]
def run_deploy(config):
generated_files = []
importer = importModule()
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))
functio... | ||
addValidateConfigCode(self, indent=1):
self.function_code += self.__addValidateConfigCode()
def addStatement(self, statement, indent=1):
self.codeText += '\\n' + self.tab * indent + statement
def getCode(self):
return self.function_code + '\\n' + self.codeText
def ... | ||
== "activation"):
activation_fn = str(v)
elif (k == "optimizer"):
optimizer = str(v)
elif (k == "loss"):
loss_fn = str(v)
elif (k == "first_layer"):
if not isinstance(k, list):
| ||
status = {}
output_data_path = targetPath / IOFiles['outputData']
log.log_dataframe(df)
required_features = list(set(config['selected_features'] + config['dateTimeFeature'] + config['target_feature']))
log.info('Dataset features required: ' + ','.join(required_features))
missing_features = [x f... | ||
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()\\
... | ||
\\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\\
\\ndef write_json(data, fil... | ||
\\
\\n def info(self, msg):\\
\\n self.log.info(msg)\\
\\n\\
\\n def error(self, msg, exc_info=False):\\
\\n self.log.error(msg,exc_info)\\
\\n\\
\\n # format and log dataframe\\
\\n def log_dataframe(self, df, rows=2, msg=None):\... | ||
.get_feature_names())[cat_enc.get_feature_names()]"
if self.normalizer:
text += "\\n df[self.normalizer_col] = self.normalizer.transform(df[self.normalizer_col])"
if self.text_profiler:
text += "\\n text_corpus = df[self.text_profiler_col].apply(lambda row: ' '.join... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.