Best Python code snippet using pytest-django_python
Libertas.py
Source:Libertas.py  
1import pandas as pd2import numpy as np 3from sklearn import preprocessing4from sklearn.feature_extraction import DictVectorizer5from sklearn.preprocessing import LabelEncoder6from sklearn.ensemble import RandomForestRegressor7from sklearn.ensemble import BaggingRegressor8import xgboost as xgb9	10def xgboost_pred(train,labels,test):11	params = {}12	params["objective"] = "count:poisson"13	params["eta"] = 0.00514	params["min_child_weight"] = 615	params["subsample"] = 0.716	params["colsample_bytree"] = 0.717	params["scale_pos_weight"] = 118	params["silent"] = 119	params["max_depth"] = 920    21    22	plst = list(params.items())23	#Using 4000 rows for early stopping. 24	offset = 400025	num_rounds = 1000026	xgtest = xgb.DMatrix(test)27	#create a train and validation dmatrices 28	xgtrain = xgb.DMatrix(train[offset:,:], label=labels[offset:])29	xgval = xgb.DMatrix(train[:offset,:], label=labels[:offset])30	#train using early stopping and predict31	watchlist = [(xgtrain, 'train'),(xgval, 'val')]32	model = xgb.train(plst, xgtrain, num_rounds, watchlist, early_stopping_rounds=120)33	preds1 = model.predict(xgtest,ntree_limit=model.best_iteration)34	#reverse train and labels and use different 4k for early stopping. 35	train = train[::-1,:]36	labels = np.log(labels[::-1])37	xgtrain = xgb.DMatrix(train[offset:,:], label=labels[offset:])38	xgval = xgb.DMatrix(train[:offset,:], label=labels[:offset])39	watchlist = [(xgtrain, 'train'),(xgval, 'val')]40	model = xgb.train(plst, xgtrain, num_rounds, watchlist, early_stopping_rounds=120)41	preds2 = model.predict(xgtest,ntree_limit=model.best_iteration)42	#combine predictions43	#since the metric only cares about relative rank we don't need to average44	print "preds1 -> ", preds1 * 0.545	print "preds2 -> ", np.exp(preds2)*0.5, "\n"46	preds = (preds1)*0.5 + np.exp(preds2)*0.547	return preds48def xgboost_Label(train,test,labels):49	print("Train & Test xgboost_Label")50	train.drop('T2_V10', axis=1, inplace=True)51	train.drop('T2_V7', axis=1, inplace=True)52	train.drop('T1_V13', axis=1, inplace=True)53	train.drop('T1_V10', axis=1, inplace=True)54	test.drop('T2_V10', axis=1, inplace=True)55	test.drop('T2_V7', axis=1, inplace=True)56	test.drop('T1_V13', axis=1, inplace=True)57	test.drop('T1_V10', axis=1, inplace=True)58	train = np.array(train)59	test = np.array(test)60	for i in range(train.shape[1]):61	    lbl = preprocessing.LabelEncoder()62	    lbl.fit(list(train[:,i]) + list(test[:,i]))63	    train[:,i] = lbl.transform(train[:,i])64	    test[:,i] = lbl.transform(test[:,i])65	train = train.astype(float)66	test = test.astype(float)67	preds = xgboost_pred(train,labels,test)68	return preds69def xgboost_Vect(train,test,labels):70	print("Train & Test xgboost_Vect")71	test = test.T.to_dict().values()72	train = train.T.to_dict().values()73	vec = DictVectorizer()74	train = vec.fit_transform(train)75	test = vec.transform(test)76	preds = xgboost_pred(train,labels,test)77	return preds78def xgboost_Dummies(train,test,labels):79	print("Train & Test xgboost_Dummies")80	train = pd.get_dummies(train)81	test = pd.get_dummies(test)82	preds = xgboost_pred(train.values,labels,test.values)83	return preds84if __name__ == '__main__':85	#load train and test 86	print("Chargement des donnees")87	train  = pd.read_csv('train.csv', index_col=0)88	test  = pd.read_csv('test.csv', index_col=0)89	labels = train.Hazard90	train.drop('Hazard', axis=1, inplace=True)91	############ RF LABEL #################92	train_rf = train.copy()93	test_rf = test.copy()94	train_rf.drop('T2_V10', axis=1, inplace=True)95	train_rf.drop('T2_V7', axis=1, inplace=True)96	train_rf.drop('T1_V13', axis=1, inplace=True)97	train_rf.drop('T1_V10', axis=1, inplace=True)98	test_rf.drop('T2_V10', axis=1, inplace=True)99	test_rf.drop('T2_V7', axis=1, inplace=True)100	test_rf.drop('T1_V13', axis=1, inplace=True)101	test_rf.drop('T1_V10', axis=1, inplace=True)102	train_rf = np.array(train_rf)103	test_rf = np.array(test_rf)104	for i in range(train_rf.shape[1]):105	    lbl = LabelEncoder()106	    lbl.fit(list(train_rf[:,i]))107	    train_rf[:,i] = lbl.transform(train_rf[:,i])108	for i in range(test_rf.shape[1]):109	    lbl = LabelEncoder()110	    lbl.fit(list(test_rf[:,i]))111	    test_rf[:,i] = lbl.transform(test_rf[:,i])112	train_rf = train_rf.astype(float)113	test_rf = test_rf.astype(float)114	############# RF DUMMIES ##############115	train_du = train.copy()116	test_du = test.copy()117	train_du.drop('T2_V10', axis=1, inplace=True)118	train_du.drop('T2_V7', axis=1, inplace=True)119	train_du.drop('T1_V13', axis=1, inplace=True)120	train_du.drop('T1_V10', axis=1, inplace=True)121	test_du.drop('T2_V10', axis=1, inplace=True)122	test_du.drop('T2_V7', axis=1, inplace=True)123	test_du.drop('T1_V13', axis=1, inplace=True)124	test_du.drop('T1_V10', axis=1, inplace=True)125	train_du = pd.get_dummies(train_du)126	test_du = pd.get_dummies(test_du)127	algorithms = [128		[RandomForestRegressor(n_estimators=2048, max_depth=18, min_samples_split=4, min_samples_leaf=20), "labels"],129		[RandomForestRegressor(n_estimators=2048, max_depth=22, min_samples_split=4, min_samples_leaf=20), "dummies"],130		["xgboost_Dummies", ""],131		["xgboost_Label", ""],132		["xgboost_Vect", ""]133	]134	full_predictions = []135	for alg, predictors in algorithms:136		if(alg == "xgboost_Label"):137			full_predictions.append(xgboost_Label(train, test, labels))138		elif(alg == "xgboost_Vect"):139			full_predictions.append(xgboost_Vect(train, test, labels))140		elif(alg == "xgboost_Dummies"):141			full_predictions.append(xgboost_Dummies(train, test, labels))142		else :143			if(predictors == "dummies"):144				print("Train ", alg.__class__.__name__ , " dummies Model ")145				alg=BaggingRegressor(alg)146				alg.fit(train_du, labels)147				print 'Prediction :' , alg.__class__.__name__ , ' dummies Model '148				prediction = alg.predict(test_du)149				full_predictions.append(prediction)150			else :151				print("Train ", alg.__class__.__name__ , " Label Model ")152				alg=BaggingRegressor(alg)153				alg.fit(train_rf, labels)154				print 'Prediction :' , alg.__class__.__name__ , ' Label Model '155				prediction = alg.predict(test_rf)156				full_predictions.append(prediction)157	# Ensemble models158	RF_label_pred = full_predictions[0]159	RF_dummies_pred = full_predictions[1]160	pred_xgb_dummies = full_predictions[2]161	pred_xgb_Label = full_predictions[3]162	pred_xgb_Vect = full_predictions[4]163	pred_RF = RF_dummies_pred * 0.50 + RF_label_pred * 0.50 164	pred_xgb = pred_xgb_dummies * 0.45 + pred_xgb_Label * 0.28 + pred_xgb_Vect * 0.27 165	preds = pred_RF * 0.15 + pred_xgb * 0.85 166	#generate solution167	print("Construction csv")168	preds = pd.DataFrame({"Id": test.index, "Hazard": preds})169	preds = preds.set_index('Id')...rf_moving_pre_arrive_test.py
Source:rf_moving_pre_arrive_test.py  
1#!/usr/bin/env python32import test_rf3import time4import argparse5import socket6def main():7    parser = argparse.ArgumentParser(description="rf arguments")8    parser.add_argument("gateway_ip", help="ip address of gateway", type=str)9    parser.add_argument("gateway_port", help="port of gateway", type=int)10    parser.add_argument("rf_address", help="rf address", type=str)11    parser.add_argument("test_times", help="how many times to test", type=int)12    parser.add_argument("target_pos", help="absolute target in counts in hex", type=str)13    parser.add_argument("velocity", help="velocity in counts/s", type=int)14    parser.add_argument("is_destination", help="0 - not | 1 - is dest", type=int)15    parser.add_argument("is_vertical", help="0 - horizontal | 1 - vertical", type=int)16    parser.add_argument("pre_arrive_count", help="pre arrive distance in counts", type=int)17    parser.add_argument("is_sensor_triggered", help="0 - no sensor | 1 - has sensor", type=int)18    gateway = parser.parse_args().gateway_ip19    port = parser.parse_args().gateway_port20    rf_addr = parser.parse_args().rf_address21    test = parser.parse_args().test_times22    pos = parser.parse_args().target_pos23    vel = parser.parse_args().velocity24    is_dest = parser.parse_args().is_destination25    is_vert = parser.parse_args().is_vertical26    pre_arrive = parser.parse_args().pre_arrive_count27    is_sensor = parser.parse_args().is_sensor_triggered28    recv_count = 029    timeout_count = 030    error_count = 031    test_rf.serverAddressPort = (gateway, port)32    test_rf.rf = rf_addr33    test_rf.moving_pre_arrive_count = pre_arrive34    for x in range(test):35        test_rf.error_count = 036        res = test_rf.moving(pos, vel, is_dest, is_vert, is_sensor)37        if res[0] == "received":38            recv_count += 139        if res[0] == "timeout":40            timeout_count += 141        error_count += res[1]42    print("{} {} {}".format(recv_count, timeout_count, error_count), end="")43if __name__ == "__main__":...rf_ping.py
Source:rf_ping.py  
1#!/usr/bin/env python32import test_rf3import time4import argparse5import socket6def main():7    parser = argparse.ArgumentParser(description="rf arguments")8    parser.add_argument("gateway_ip", help="ip address of gateway", type=str)9    parser.add_argument("gateway_port", help="port of gateway", type=str)10    parser.add_argument("rf_address", help="rf address", type=str)11    parser.add_argument("test_times", help="how many times to test", type=str)12    parser.add_argument("ping_operation", help="0 - read | 1 - online", type=str)13    gateway = parser.parse_args().gateway_ip14    port = int(parser.parse_args().gateway_port)15    rf_addr = parser.parse_args().rf_address16    sub = int(parser.parse_args().ping_operation)17    test = int(parser.parse_args().test_times)18    recv_count = 019    timeout_count = 020    error_count = 021    test_rf.serverAddressPort = (gateway, port)22    test_rf.rf = rf_addr23    for x in range(test):24        test_rf.error_count = 025        res = test_rf.ping(sub)26        if res[0] == "received":27            recv_count += 128        if res[0] == "timeout":29            timeout_count += 130        error_count += res[1]31    print("{} {} {}".format(recv_count, timeout_count, error_count), end="")32if __name__ == "__main__":...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
