content stringlengths 255 17.2k |
|---|
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
import pickle
import logging
class recommendersystem():
def __init__(self,features,svd_params):
self.features = features
self.svd_input = svd_params
self.log = logging.getLogger('eion')
print ("recommendersystem st... |
prediction)
acc_sco = accuracy_score(y_test, prediction)
predict_df = pd.DataFrame()
predict_df['actual'] = y_test
predict_df['predict'] = prediction
predict_df.to_csv(predicted_data_file)
self.log.info('-------> Model Score Matrix: Accuracy')
... |
os.path.split(exc_tb.tb_frame.f_code.co_filename)
self.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
<s> '''
*
* =============================================================================
* COPYRIGHT NOTICE
* ===========================================================... |
prior_scale}
grid = ParameterGrid(params_grid)
p_cnt = 0
for p in grid:
p_cnt = p_cnt+1
self.log.info("--------------- Total Possible prophet iterations: --------------- \\n")
self.log.info(p_cnt)
self.log.info("\\n--------------- M... |
col+'_actual'
predictfeature = target_col+'_pred'
prophet_df_new=prophet_df_new.rename(columns={'ds': 'datetime', 'y': actualfeature,'yhat': predictfeature})
#prophet_df_new.to_csv(predicted_data_file)
#cv_results = cross_validation( model = best_prophet_mode... |
Config,modelconfig,modelList,data,targetFeature,dateTimeFeature,modelName,trainPercentage,usecasename,version,deployLocation,scoreParam):
self.tsConfig = tsConfig
self.modelconfig = modelconfig
self.modelList = modelList
self.data = data
self.data1=data
self.pred_freq = '... |
self.scoreParam.lower(),'NA',None,selectedColumns,'','{}',pd.DataFrame(),lag_order,None
except Exception as e:
self.log.info("getEncDecLSTMMultVrtInUniVrtOut method error. Error msg: "+str(e))
return 'Error',modelName.upper(),self.scoreParam.lower(),'NA',None,selectedColumns,'','{}'... |
=rmse_arima
self.log.info("ARIMA Univariant User selected scoring parameter is RMSE. RMSE value: "+str(rmse_arima))
elif (self.scoreParam.lower() == "mse"):
scoringparam_v=mse
sel |
.append(rmse_mlp)
modelScore.append(rmse_var)
if (min(modelScore) == rmse_arima and rmse_arima != 0xFFFF):
best_model='arima'
self.log.info('Status:- |... TimeSeries Best Algorithm: ARIMA')
return best_model
elif (min(modelSc... |
Process(self.modelName,lentFeature,trained_data_file,tFeature,predicted_data_file,dataFolderLocation)
return best_model,modelName,score_type,score,model_fit,selectedColumns,error_matrix,scoredetails,dictDiffCount,pred_freq,additional_regressors,filename,saved_model,lag_order,scaler_transformation
... |
log.info('-------> The given mlp/lstm timeseries algorithm parameters:>>')
self.log.info(" "+str(val))
for k,v in val.items():
try:
if (k == "tuner_algorithm"):
self.tuner_algorithm=str(v)
elif (k == "activation"):
s... |
n_lags))
# normalize the dataset
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
# split into train and test sets
train_size = int(len(dataset) * 0.80)
test_size = len(dataset) - train_size
train, tes... |
round(int(self.first_layer[1]))
dropout_min=float(self.dropout[0])
dropout_max=float(self.dropout[1])
dropout_step=float(self.dropout[2])
#import pdb; pdb.set_trace()
n_past= self.look_back
n_future = self.look_back
enco... |
_dropout[lindx] = best_hps.get('enc_lstm_dropout_'+str(lindx))
encoder_inputs = Input(shape=(n_past, n_features))
if(self.hidden_layers > 0):
encoder_l[0] = LSTM(enc_input_unit, activation = enc_input_activation, return_sequences = True, return_state=True... |
"dropout"):
if not isinstance(k,list):
self.dropout=str(v).split(',')
else:
self.dropout=k
elif (k == "batch_size"):
self.batch_size=int(v)
elif (k == "epochs")... |
mae_dict[name]=mae
## For VAR comparison, send last target mse and rmse from above dict
lstm_var = lstm_var/len(target)
select_msekey=list(mse_dict.keys())[-1]
l_mse=list(mse_dict.values())[-1]
select_rmsekey=list(rm... |
ality_combined_res))
self.log.info("Time series Seasonality test completed.\\n")
return df,decompose_result_mult,seasonality_result,seasonality_combined_res
#Main fn for standalone test purpose
if __name__=='__main__':
... |
init__(self, config={}):
if 'gcs' in config.keys():
config = config['gcs']
account_key = config.get('account_key','')
bucket_name = config.get('bucket_name','')
if not account_key:
raise ValueError('Account key can not be empty')
if not bucket_name:
... |
not found in current data')\\
\\n df_copy = df.copy()\\
\\n df = df[self.selected_features]"
if self.word2num_features:
text += "\\n for feat in self.word2num_features:"
text += "\\n df[ feat ] = df[feat].apply(lambda x: s2n(x))"
if... |
log.log_dataframe(train_data)
status = {'Status':'Success','trainData':IOFiles['trainData'],'testData':IOFiles['testData']}
meta_data['transformation'] = {}
meta_data['transformation']['cat_features'] = train_data.select_dtypes('category').columns.tolist()
meta_data['tran... |
column):
return column == self.target_name
def fill_default_steps(self):
num_fill_method = get_one_true_option(self.config.get('numericalFillMethod',None))
normalization_method = get_one_true_option(self.config.get('normalization',None))
for colm in self.numeric_feature... |
self.data.drop(feat_to_remove, axis=1, inplace=True)
for feat in feat_to_remove:
self.dropped_features[feat] = reason
self.log_drop_feature(feat_to_remove, reason)
self.__update_type()
def drop_duplicate(self):
index = self.data.dup... |
,{'module':'time'}
,{'module':'platform'}
,{'module':'tempfile'}
,{'module':'sqlite3'}
,{'module':'mlflow'}
,{'module':'Path', 'mod_from':'pathlib'}
,{'module':'ViewType', 'mod_from':'mlflow.entities'}
,{'module':'MlflowClient', 'mod_fr... |
better=True, indent=1):
if smaller_is_better:
min_max = 'min'
else:
min_max = 'max'
self.codeText += "\\ndef validate_config(deploy_dict):\\
\\n try:\\
\\n load_data_loc = deploy_dict['load_data']['Status']['DataFilePath']\\
\\n except... |
\\n raise ValueError(json.dumps({'Status':'Failure', 'Message': str(e)}))\\
\\n\\
\\n def __predict(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... |
.lower() == 'groundtruth':
gtObj = groundtruth(config_input)
output = gtObj.actual(dataStr)
resp = output
elif operation.lower() == 'delete':
targetPath = Path('aion')/config_input['targetPath']
for file in data:
x = targetPath/file ... |
logger = logging.getLogger(Path(__file__).parent.name)
deployobj = deploy(config_input, logger)
server = SimpleHttpServer(config['ipAddress'],int(config['portNo']),targetPath/IOFiles['production'],deployobj.initialize,config_input, logger)
logger.info('HTTP Server Running...........')
logge... |
, scoring, n_iter, cv):\\
\\n self.estimator = estimator\\
\\n self.params = params\\
\\n self.scoring = scoring\\
\\n self.iteration = n_iter\\
\\n self.cv = cv\\
\... |
)/100\\
\\n result['precision'] = math.floor(avg_precision*10000)/100\\
\\n result['recall'] = math.floor(avg_recall*10000)/100\\
\\n result['f1'] = math.floor(avg_f1*10000)/100\\
\\n return result\\
\\n"},
... |
_score':metrices['train_score']}\\
\\n log.info(f'Test score: {test_score}')\\
\\n log.info(f'Train score: {train_score}')\\
\\n log.info(f'MLflow run id: {run_id}')\\
\\n log.info(f'output: {status}')\\
\\n return json.dumps(status)"
def getMainCodeModules(se... |
ess']):\\
\\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']\... |
Path(home)/'HCLT'/'AION'/'target'/self.usecase
if not output_model_dir.exists():
raise ValueError(f'Configuration file not found at {output_model_dir}')
tracking_uri = 'file:///' + str(Path(output_model_dir)/'mlruns')
registry_... |
:
currentdataFrame=pd.read_csv(config['inputUri'])
inputdriftObj = inputdrift(config)
dataalertcount,inputdrift_message = inputdriftObj.get_input_drift(currentdataFrame,historicaldataFrame)
if inputdrift_message == 'Model is working as expected':... |
.core import *
from .utility import *
import tarfile
output_file_map = {
'text' : {'text' : 'text_profiler.pkl'},
'targetEncoder' : {'targetEncoder' : 'targetEncoder.pkl'},
'featureEncoder' : {'featureEncoder' : 'inputEncoder.pkl'},
'normalizer' : {'normalizer' : 'normalizer.pkl'}
}
def add_common_imp... |
usecase"="'+str(usecasename)+'"'
text+='\\n'
text+='LABEL "usecase_test"="'+str(usecasename)+'_test'+'"'
for file in files:
text+=f'\\nCOPY {file} {file}'
text+='\\n'
text+='RUN pip install --no-cache-dir -r requirements.txt'
elif name == 'transformer':
t... |
i]]',indent=2)
trainer.addStatement('y_pred = estimator.predict(X_test[features])',indent=2)
if scorer_type == 'accuracy':
importer.addModule('accuracy_score', mod_from='sklearn.metrics')
trainer.addStatement(f"test_score = round(accuracy_score(y_test,y_pred),2) * 100",indent=2)
importer... |
importer.addModule('stats', mod_from='scipy', mod_as='st')
importer.addModule('Path', mod_from='pathlib')
code = file_header(config['modelName']+'_'+config['modelVersion'])
code += importer.getCode()
drifter.generateCode()
code += drifter.getCode()
deploy_path = Path(config["deploy_path"])/'MLaC... |
_file_name)")
select.addStatement("meta_data['featureengineering']['feature_reducer']['file']= IOFiles['feature_reducer']")
select.addStatement("meta_data['featureengineering']['feature_reducer']['features']= train_features")
select.addOutputFiles(output_file_map['feature_reducer'])
... |
aws_secret_access_key = config.get('aws_secret_access_key','')
bucket_name = config.get('bucket_name','')
if not aws_access_key_id:
raise ValueError('aws_access_key_id can not be empty')
if not aws_secret_access_key:
raise ValueError('aws_secret_access_key can not ... |
rstrip().split(',')\\
\\n\\
\\n self.dataLocation = base_config['dataLocation']\\
\\n self.selected_features = deployment_dict['load_data']['selected_features']\\
\\n self.target_feature = deployment_dict['load_data']['target_feature']\\
\\n self.outpu... |
input_files:
text += '{ }'
else:
text += json.dumps(self.input_files, indent=4)
return text
def getOutputFiles(self):
text = 'output_file = '
if not self.output_files:
text += '{ }'
else:
text += json.dumps(self.output_... |
_url(file_name):\\
\\n supported_urls_starts_with = ('gs://','https://','http://')\\
\\n return file_name.startswith(supported_urls_starts_with)\\
\\n"},
'logger_class':{'imports':[{'mod':'logging'}, {'mod':'io'}],'code':"\\n\\
\\nclass logger():\\
\\n #setup the log... |
uniform, st.expon, st.weibull_max, st.weibull_min, st.chi, st.norm, st.lognorm, st.t,
st.gamma, st.beta]
best_distribution = st.norm.name
best_sse = np.inf
datamin = data.min()
datamax = data.max()
nrange = datamax - datamin
... |
Version:{modelversion}
RunNo: {runNo}
URL for Prediction
==================
URL:{url}
RequestType: POST
Content-Type=application/json
Body: {displaymsg}
Output: prediction,probability(if Applicable),remarks corresponding to each row.
URL for GroundTruth
===================
URL:{urltextgth}
RequestType: POST
Content-Ty... |
\\n updatedFeatures = list(set(columns) - set(constFeatures)-set(qconstantColumns))\\
\\n return updatedFeatures"},
'feature_importance_class':{'name':'feature_importance_class','code':"\\n\\
\\ndef feature_importance_class(df, numeric_features, cat_featu... |
('prediction/'+file_name).upload_from_filename('output_data.csv', content_type='text/csv')\\
\\n# return data\\
\\n\\
\\ndef is_file_name_url(file_name):\\
\\n supported_urls_starts_with = ('gs://','https://','http://')\\
... |
22
* Proprietary and confidential. All information contained herein is, and
* remains the property of HCL Technologies Limited. Copying or reproducing the
* contents of this file, via any medium is strictly prohibited unless prior
* written permission is obtained from HCL Technologies Limited.
*/
"""
import json
clas... |
in = TimeseriesGenerator(train, train, length=n_input, batch_size=8)
generatorTest = TimeseriesGenerator(test, test, length=n_input, batch_size=8)
batch_0 = generatorTrain[0]
x, y = batch_0
epochs = int(epochs)
##Multivariate LSTM model
model = Sequential()
model.add(LSTM(units=hp.Int('units... |
\\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 cou... |
registered'] = False #ack registery
if (meta_data['monitoring']['endIndex'] + retrain_threshold) < df_len:
meta_data['monitoring']['endIndexTemp'] = df_len
retrain = True
else:
log.info('Pipeline running first time')
meta_data = {}
meta_data['monit... |
deploy_path,config['modelName'], generated_files)
<s> """
/**
* =============================================================================
* COPYRIGHT NOTICE
* =============================================================================
* © Copyright HCL Technologies Ltd. 2021, 2022
* Proprietary and confident... |
else:
return algo
def get_training_params(config, algo):
param_keys = ["modelVersion","problem_type","target_feature","train_features","scoring_criteria","test_ratio","optimization_param","dateTimeFeature"]#BugID:13217
data = {key:value for (key,value) in config.items() if key in param_keys}
data[... |
3
import subprocess
import os
import sys
import re
import json
import pandas as pd
from appbe.eda import ux_eda
from aif360.datasets import StandardDataset
from aif360.metrics import ClassificationMetric
from aif360.datasets import BinaryLabelDataset
def get_metrics(request):
dataFile = os.path.join(request.sessi... |
self.featureName = featureName
self.paramvales = []
self.X = []
self.Y = []
self.problem = {}
def preprocess(self):
self.X = self.data[self.featureName].values
self.Y = self.data[self.target].values
bounds = [[np.min(self.X[:, i]), np.max(self.X[:, i])] fo... |
log.info('\\n================== Data Profiling Details==================')
datacolumns=list(self.dataframe.columns)
self.log.info('================== Data Profiling Details End ==================\\n')
self.log.info('================== Features Correlation Details ==================\\n')
self.log.info('\\n==... |
gs\\\\":[{\\\\"id\\\\":\\\\"1\\\\",\\\\"enabled\\\\":true,\\\\"type\\\\":\\\\"count\\\\",\\\\"schema\\\\":\\\\"metric\\\\",\\\\"params\\\\":{}},{\\\\"id\\\\":\\\\"2\\\\",\\\\"enabled\\\\":true,\\\\"type\\\\":\\\\"terms\\\\",\\\\"schema\\\\":\\\\"segment\\\\",\\\\"params\\\\":{\\\\"field\\\\":\\\\"'+xcolumn+'\\\\",\\\\"... |
backward trellis
self.clear_trellis()
param_dict = self.unpack_params(params)
# populate forward and backward trellis
lpx = self.weighted_alpha_recursion(self.X[0], param_dict['pi0'],
param_dict['phi'],
... |
), D)
w = npr.randn(D, 1)
y = sigmoid((x @ w)).ravel()
y = npr.binomial(n=1, p=y) # corrupt labels
y_test = sigmoid(x_test @ w).ravel()
# y_test = np.round(y_test)
y_test = npr.binomial(n=1, p=y_test)
return x, np.atleast_2d(y), x_test, np.atleast_2d(y_test)
<s> i... |
""" Method to obtain the predicitve uncertainty, this can return the total, epistemic and/or aleatoric
uncertainty in the predictions.
"""
raise NotImplementedError
def set_params(self, **parameters):
for parameter, value in parameters.items():
setattr(self, para... |
main_model.parameters(), lr=self.config["lr"])
optimizer_aux_model = torch.optim.Adam(self.aux_model.parameters(), lr=self.config["lr"])
for it in range(self.config["num_outer_iters"]):
# Train the main model
for epoch in range(self.config["num_main_iters"]):
av... |
X: array-like of shape (n_samples, n_features).
Features vectors of the test points.
mc_samples: Number of Monte-Carlo samples.
return_dists: If True, the predictive distribution for each instance using scipy distributions is returned.
return_epistemic: if ... |
self.meta_model = self._get_model_instance(meta_model if meta_model is not None else self.meta_model_default,
self.meta_config)
def get_params(self, deep=True):
return {"base_model": self.base_model, "meta_model": self.meta_model, "base_config": self.base_... |
stack([X, y_hat_prime])
z_hat = self.meta_model.predict(X_meta_in)
Result = namedtuple('res', ['y_mean', 'y_lower', 'y_upper'])
res = Result(y_hat, y_hat - z_hat, y_hat + z_hat)
return res
<s> from .quantile_regression import QuantileRegression
<s> from collections import namedtuple
f... |
shape (n_samples, [n_output_dims])
Mean of predictive distribution of the test points.
y_lower: ndarray of shape (n_samples, [n_output_dims])
Lower quantile of predictive distribution of the test points.
y_upper: ndarray of shape (n_samples, [n_output_dims])
... |
x_) - radius, max(x) + radius])
ax2.set_ylim([0, max_y + radius])
ax2.set_aspect(1)
if title is not None:
ax.set_title(title)
if xlabel is not None:
ax.set_xlabel(xlabel)
if ylabel is not None:
ax.set_ylabel(ylabel)
return ax
def plot_picp_by_feature(x_tes... |
bin = len(y_true) // num_bins
selection_threshold = selection_scores[order[samples_in_bin * (bin_id+1)-1]]
selection_thresholds.append(selection_threshold)
ids = selection_scores >= selection_threshold
if sum(ids) > 0:
if attributes is None:
if isinstance(y_tr... |
)
plt.title("Risk vs Selection Threshold Plot")
plt.grid()
plt.show()
return aurrrc_list, rejection_rate_list, selection_thresholds_list, risk_list
<s> from .classification_metrics import expected_calibration_error, area_under_risk_rejection_rate_curve, \\
compute_classification_metrics, entropy_b... |
idx] / ynorm})
if len(recipe) < 2:
return recipe[0]
else:
return recipe
def _find_min_cost_in_component(self, plotdata, idx1, idx2, cost1, cost2):
"""
Find s minimum cost function value and corresp. position index in plotdata
:param plotdata: liste ... |
= [i[self.x_axis_idx] / xnorm for i in plotdata]
axisY_data = [i[self.y_axis_idx] / ynorm for i in plotdata]
marker = None
if markers is not None: marker = markers[s]
p = plt.plot(axisX_data, axisY_data, lab |
- 0.5
return kld_weights.sum() + kld_bias.sum()
class HorseshoeLayer(BayesianLinearLayer):
"""
Uses non-centered parametrization. w_k = v*tau_k*beta_k where k indexes an output unit and w_k and beta_k
are vectors of all weights incident into the unit
"""
def __init__(self... |
NN(nn.Module, ABC):
"""
Bayesian neural network with Horseshoe layers.
"""
def __init__(self, ip_dim=1, op_dim=1, num_nodes=50, activation_type='relu', num_layers=1,
hshoe_scale=1e-1, use_reg_hshoe=False):
if use_reg_hshoe:
layer = RegularizedHorseshoeLayer
... |
str) and v.lower() == 'true') or (isinstance(v, bool) and v == True):
return k
return default_value
def get_boolean(value):
if (isinstance(value, str) and value.lower() == 'true') or (isinstance(value, bool) and value == True):
return True
else:
return False
def get_source_delta( ... |
or feature == dateTime or feature == 'index':
continue
if dataframe[feature].empty == True:
continue
if dataframe[feature].isnull().all() == True:
continue
if featureType in ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']:
temp = {'size','sum','max','min','mean'}
aggjson[featur... |
{}
self.train_features_type={}
self.__update_type()
self.config = config
self.featureDict = config.get('featureDict', [])
self.output_columns = []
self.feature_expender = []
self.text_to_num = {}
self.force_numeric_conv = []
if log:
sel... |
k1}'] = Pipeline([
('selector', ColumnTransformer([
("selector", "passthrough", v1)
], remainder="drop")),
(k, self.get_cat_imputer(k)),
(k1, self.get_cat_encoder(k1))
]) ... |
):
index_feature = []
for feat in self.numeric_feature:
if self.data[feat].nunique() == len(self.data):
#if (self.data[feat].sum()- sum(self.data.index) == (self.data.iloc[0][feat]-self.data.index[0])*len(self.data)):
# index feature can be time based ... |
augConf[key].get('noOfImages',1))
else:
limit = 0.2
numberofImages = 1
df = self.__objAug(imageLoc, df, classes_names, category_id_to_name,category_name_to_id,limit,numberofImages,op=key)
return df
... |
(df > (Q3 + 1.5 * IQR)))
return index
def findzscoreOutlier(df):
z = np.abs(scipy.stats.zscore(df))
index = (z < 3)
return index
def findiforestOutlier(df):
from sklearn.ensemble import IsolationForest
isolation_forest = IsolationForest(n_estimators=100)
isolation_forest.fit(df)
... |
_tb.tb_lineno)
return {}
def textLemmitizer(self,text):
try:
tag_map = defaultdict(lambda : wn.NOUN)
tag_map['J'] = wn.ADJ
tag_map['V'] = wn.VERB
tag_map['R'] = wn.ADV
Final_words = []
word_Lemmatized = WordNetLemmatizer()
for word, tag in pos_tag(text):
if word not in stopwords.words(... |
split(X, y, test_size=0.3, random_state=0)
uqObj=aionUQ(df,X,y,ProblemName,Params,model,modelfeatures,tar)
#accuracy,uq_ece,output_jsonobject,model_confidence_per,model_uncertaitny_per=uqObj.uqMain_BBMClassification(X_train, X_test, y_train, y_test,"uqtest")
accuracy,uq_ece,output_jsonobject,model_confidence_per,... |
plt.close()
pltreg=plot_picp_by_feature(X_test, y_test,
y_lower, y_upper,
xlabel=x_feature)
#pltreg.savefig('x.png')
pltr=pltreg.figure
if os.path.exists(str(self.uqgraphlocation)+'/picp_per_feature.png'):
os.remove(str(self.uqgraphlocation)+'/picp_per_feature.png')
pltr.savefig(str(sel... |
ensembling to reduce ECE (ECE~0).'
else:
# self.log.info('Model has good ECE score and accuracy, ready to deploy.\\n.')
if (uq_ece <= 0.1 and model_confidence >= 0.9):
# Green Text
recommendation = 'Model has best calibration score (near to 0) and good confidence score , ready to deploy. '
els... |
served_alphas_picp
output['MeanPredictionIntervalWidth']=round(observed_widths_mpiw)
output['DesirableMPIWRange: ']=(str(round(mpiw_lower_range))+str(' - ')+str(round(mpiw_upper_range)))
output['Recommendation']=str(recommendation)
output['Metric']=uq_scoring_param
output['Score']=metric_used
output['... |
y'], 'o', label='Observed')
plt.plot(pred_df_sorted[x_feature1[0]], pred_df_sorted['y_mean'], '-', lw=2, label='Predicted')
plt.plot(pred_df_sorted[x_feature1[0]], pred_df_sorted['y_upper'], 'r--', lw=2, label='Upper Bound')
plt.plot(pred_df_sorted[x_feature1[0]], pred_df_sorted['y_lower'], 'r--', lw=2, label=... |
=round((model_uncertainty*100),2)
# model_confidence_per=round((model_confidence*100),2)
model_confidence_per=round((ece_confidence_score*100),2)
acc_score_per = round((acc_score*100),2)
uq_ece_per=round((uq_ece*100),2)
output={}
recommendati |
()
for x in y_hat_lb:
y_hat_ub.append(x)
total_pi=y_hat_ub
medium_UQ_range = y_hat_ub
best_UQ_range= y_hat.tolist()
ymean_upper=[]
ymean_lower=[]
y_hat_m=y_hat.tolist()
for i in y_hat_m:
y_hat_m_range= (i*20/100)
x=i+y_hat_m_range
y=i-y_hat_m_range
ymean_upper.append... |
_code.co_filename)
self.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))
return df, missingValFtrs, emptyCols, dataCols, self.allNumCols, self.allCatCols, self.textFtrs
def createIncProfiler(self, df, conf_json, allNumCols, numFtrs, allCatCols, textFtrs, missingValFtrs):
self.incLabelMappi... |
self.configDict['cat_fill'] = {col:self.incFill['cat_fill'].stats[col].get() for col in allCatCols}
self.log.info('\\nStatus:- |... Missing value treatment done')
except Exception as inst:
self.log.info("Error in Missing value treatment "+str(inst))
exc_type, exc_obj, exc_tb = sys.exc_info()
fna... |
checkNumeric(tempDataFrame,feature)
tempDf = testDf[feature]
tempDf = tempDf.dropna()
numberOfNonNullVals = tempDf.count()
if(numberOfNonNullVals > int(numOfRows * numericRatio)):
tempDataFrame=df.copy(deep=True)
testDf = self.convertWordToNumeric(tempDataFrame,feature)
tempDf = testDf[fe... |
bestModel =model
bestParams=modelParams
bestEstimator=estimator
self.bestTrainPredictedData = trainPredictedData
self.bestPredictedData = predictedData
else:
if abs(score) < bestScore or bestScore == -sys.float_info.max:
bestScore =abs(score)
bestModel =model
bestParam... |
KNNClassifier,'Online Linear Regression':LinearRegression, 'Online Decision Tree Regressor':HoeffdingAdaptiveTreeRegressor, 'Online KNN Regressor':KNNRegressor}
self.optDict={'sgd': SGD, 'adam':Adam, 'adadelta':AdaDelta, 'nesterovmomentum':NesterovMomentum, 'rmsprop':RMSProp}
self.log = logging.getLogger('eion')
... |
= self.algorithms
if len(algos) <= self.numInstances:
self.numInstances = len(algos)
algosPerInstances = (len(algos)+(self.numInstances - 1))//self.numInstances
remainingAlgos = len(algos)
for i in range(self.nu |
ances = Path().glob("*.ec2instance")
for file in openInstances:
with open(file, 'r') as f:
data = json.load(f)
prevConfig = list(data.values())[0]
key = Path(file).stem
if prevConfig['AMAZON_EC2']['amiId']:
prevConfig['AMAZO... |
if c.recv_ready():
stdout_chunks.append(stdout.channel.recv(len(c.in_buffer)))
got_chunk = True
if c.recv_stderr_ready():
# make sure to read stderr to prevent stall
stderr.channel.recv_stderr(len(c.in... |
= {}
modelsTrainOutput = {}
self.baseFolder = self.folders[0].parent/"_".join(self.folders[0].name.split('_')[:-1])
if len(self.folders) == 1:
if self.baseFolder.exists():
shutil.rmtree(self.baseFolder)
|
predictions (:obj:`list` of :obj:`Prediction\\
<surprise.prediction_algorithms.predictions.Prediction>`):
A list of predictions, as returned by the :meth:`test()
<surprise.prediction_algorithms.algo_base.AlgoBase.test>` method.
verbose: If True, will print computed v... |
Prediction",
"Dataset",
"Reader",
"Trainset",
"dump",
"KNNWithZScore",
"get_dataset_dir",
"model_selection",
]
__version__ = get_distribution("scikit-surprise").version
<s> """This module contains the Reader class."""
from .builtin_datasets import BUILTIN_DATASETS
class Reader:
"""T... |
See :ref:`this note<raw_inner_note>`.
Args:
ruid(str): The user raw id.
Returns:
int: The user inner id.
Raises:
ValueError: When user is not part of the trainset.
"""
try:
return self._raw2inner_id_users[ruid]
except Ke... |
eline* rating.
The prediction :math:`\\\\hat{r}_{ui}` is set as:
.. math::
\\\\hat{r}_{ui} = b_{ui} + \\\\frac{ \\\\sum\\\\limits_{v \\\\in N^k_i(u)}
\\\\text{sim}(u, v) \\\\cdot (r_{vi} - b_{vi})} {\\\\sum\\\\limits_{v \\\\in
N^k_i(u)} \\\\text{sim}(u, v)}
or
.. math::
... |
of the user. See :ref:`this note<raw_inner_note>`.
iid: (Raw) id of the item. See :ref:`this note<raw_inner_note>`.
r_ui(float): The true rating :math:`r_{ui}`. Optional, default is
``None``.
clip(bool): Whether to clip the estimation into the rating scale.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.