How to use pre method in avocado

Best Python code snippet using avocado_python

tbPreCard_TabStripMenus_Operations.js

Source:tbPreCard_TabStripMenus_Operations.js Github

copy

Full Screen

12var CurrentPageState_PreCard = 'View';3var ConfirmState_PreCard = null;4var ObjPreCard_PreCard = null;5var SelectedPreCardType_PreCard = null;6var CurrentPageCombosCallBcakStateObj = new Object();7function GetBoxesHeaders_PreCard() {8 document.getElementById('header_PreCards_PreCard').innerHTML = document.getElementById('hfheader_PreCards_PreCard').value;9 document.getElementById('header_tblPreCards_PreCard').innerHTML = document.getElementById('hfheader_tblPreCards_PreCard').value;10}11function tlbItemNew_TlbPreCard_onClick() {12 ClearList_PreCard();13 ChangePageState_PreCard('Add'); 14 FocusOnFirstElement_PreCard();15}16function FocusOnFirstElement_PreCard() {17 document.getElementById('chbActivePreCard_PreCard').focus();18}19function SetActionMode_PreCard(state) {20 document.getElementById('ActionMode_PreCard').innerHTML = document.getElementById("hf" + state + "_PreCard").value;21}22function ChangePageState_PreCard(state) {23 CurrentPageState_PreCard = state;24 SetActionMode_PreCard(state);25 if (state == 'Add' || state == 'Edit' || state == 'Delete') {26 if (TlbPreCard.get_items().getItemById('tlbItemNew_TlbPreCard') != null) {27 TlbPreCard.get_items().getItemById('tlbItemNew_TlbPreCard').set_enabled(false);28 TlbPreCard.get_items().getItemById('tlbItemNew_TlbPreCard').set_imageUrl('add_silver.png');29 }30 if (TlbPreCard.get_items().getItemById('tlbItemEdit_TlbPreCard') != null) {31 TlbPreCard.get_items().getItemById('tlbItemEdit_TlbPreCard').set_enabled(false);32 TlbPreCard.get_items().getItemById('tlbItemEdit_TlbPreCard').set_imageUrl('edit_silver.png');33 }34 if (TlbPreCard.get_items().getItemById('tlbItemDelete_TlbPreCard') != null) {35 TlbPreCard.get_items().getItemById('tlbItemDelete_TlbPreCard').set_enabled(false);36 TlbPreCard.get_items().getItemById('tlbItemDelete_TlbPreCard').set_imageUrl('remove_silver.png');37 }38 TlbPreCard.get_items().getItemById('tlbItemSave_TlbPreCard').set_enabled(true);39 TlbPreCard.get_items().getItemById('tlbItemSave_TlbPreCard').set_imageUrl('save.png');40 TlbPreCard.get_items().getItemById('tlbItemCancel_TlbPreCard').set_enabled(true);41 TlbPreCard.get_items().getItemById('tlbItemCancel_TlbPreCard').set_imageUrl('cancel.png');42 document.getElementById('chbActivePreCard_PreCard').disabled = '';43 if (state == 'Add')44 document.getElementById('chbActivePreCard_PreCard').checked = true;45 document.getElementById('txtPreCardCode_PreCard').disabled = '';46 document.getElementById('txtPreCardName_PreCard').disabled = '';47 document.getElementById('rdbDaily_PreCard').disabled = '';48 document.getElementById('rdbHourly_PreCard').disabled = '';49 document.getElementById('chbJustification_PreCard').disabled = '';50 cmbPreCardType_PreCard.enable();51 if (state == 'Edit')52 NavigatePreCard_PreCard(GridPreCards_PreCard.getSelectedItems()[0]);53 if (state == 'Delete')54 PreCard_onSave();55 }56 if (state == 'View') {57 if (TlbPreCard.get_items().getItemById('tlbItemNew_TlbPreCard') != null) {58 TlbPreCard.get_items().getItemById('tlbItemNew_TlbPreCard').set_enabled(true);59 TlbPreCard.get_items().getItemById('tlbItemNew_TlbPreCard').set_imageUrl('add.png');60 }61 if (TlbPreCard.get_items().getItemById('tlbItemEdit_TlbPreCard')) {62 TlbPreCard.get_items().getItemById('tlbItemEdit_TlbPreCard').set_enabled(true);63 TlbPreCard.get_items().getItemById('tlbItemEdit_TlbPreCard').set_imageUrl('edit.png');64 }65 if (TlbPreCard.get_items().getItemById('tlbItemDelete_TlbPreCard') != null) {66 TlbPreCard.get_items().getItemById('tlbItemDelete_TlbPreCard').set_enabled(true);67 TlbPreCard.get_items().getItemById('tlbItemDelete_TlbPreCard').set_imageUrl('remove.png');68 }69 TlbPreCard.get_items().getItemById('tlbItemSave_TlbPreCard').set_enabled(false);70 TlbPreCard.get_items().getItemById('tlbItemSave_TlbPreCard').set_imageUrl('save_silver.png');71 TlbPreCard.get_items().getItemById('tlbItemCancel_TlbPreCard').set_enabled(false);72 TlbPreCard.get_items().getItemById('tlbItemCancel_TlbPreCard').set_imageUrl('cancel_silver.png');73 document.getElementById('chbActivePreCard_PreCard').disabled = 'disabled';74 document.getElementById('txtPreCardCode_PreCard').disabled = 'disabled';75 document.getElementById('txtPreCardName_PreCard').disabled = 'disabled';76 document.getElementById('rdbDaily_PreCard').disabled = 'disabled';77 document.getElementById('rdbHourly_PreCard').disabled = 'disabled';78 document.getElementById('chbJustification_PreCard').disabled = 'disabled';79 cmbPreCardType_PreCard.disable();80 }81}82function PreCard_onSave() {83 if (CurrentPageState_PreCard != 'Delete')84 UpdatePreCard_PreCard();85 else86 ShowDialogConfirm('Delete');87}88function UpdatePreCard_PreCard() {89 ObjPreCard_PreCard = new Object();90 ObjPreCard_PreCard.ID = '0';91 ObjPreCard_PreCard.IsActive = false;92 ObjPreCard_PreCard.Code = null;93 ObjPreCard_PreCard.Name = null;94 ObjPreCard_PreCard.PreCardTypeID = '0';95 ObjPreCard_PreCard.PreCardTypeTitle = null;96 ObjPreCard_PreCard.IsDaily = false;97 ObjPreCard_PreCard.IsHourly = false;98 ObjPreCard_PreCard.IsJustification = false;99 var SelectedItems_GridPreCards_PreCard = GridPreCards_PreCard.getSelectedItems();100 if (SelectedItems_GridPreCards_PreCard.length > 0)101 ObjPreCard_PreCard.ID = SelectedItems_GridPreCards_PreCard[0].getMember("ID").get_text();102 if (CurrentPageState_PreCard != 'Delete') {103 ObjPreCard_PreCard.IsActive = document.getElementById('chbActivePreCard_PreCard').checked;104 ObjPreCard_PreCard.Code = document.getElementById('txtPreCardCode_PreCard').value;105 ObjPreCard_PreCard.Name = document.getElementById('txtPreCardName_PreCard').value;106 ObjPreCard_PreCard.IsDaily = document.getElementById('rdbDaily_PreCard').checked;107 ObjPreCard_PreCard.IsHourly = document.getElementById('rdbHourly_PreCard').checked;108 ObjPreCard_PreCard.IsJustification = document.getElementById('chbJustification_PreCard').checked;109 if (cmbPreCardType_PreCard.getSelectedItem() != undefined) {110 ObjPreCard_PreCard.PreCardTypeID = cmbPreCardType_PreCard.getSelectedItem().get_value();111 ObjPreCard_PreCard.PreCardTypeTitle = cmbPreCardType_PreCard.getSelectedItem().get_text();112 }113 else {114 if (SelectedPreCardType_PreCard != null) {115 ObjPreCard_PreCard.PreCardTypeID = SelectedPreCardType_PreCard.ID;116 ObjPreCard_PreCard.PreCardTypeTitle = SelectedPreCardType_PreCard.Name;117 }118 }119 }120 UpdatePreCard_PreCardPage(CharToKeyCode_PreCard(CurrentPageState_PreCard), CharToKeyCode_PreCard(ObjPreCard_PreCard.ID), CharToKeyCode_PreCard(ObjPreCard_PreCard.IsActive.toString()), CharToKeyCode_PreCard(ObjPreCard_PreCard.Code), CharToKeyCode_PreCard(ObjPreCard_PreCard.Name), CharToKeyCode_PreCard(ObjPreCard_PreCard.PreCardTypeID), CharToKeyCode_PreCard(ObjPreCard_PreCard.IsDaily.toString()), CharToKeyCode_PreCard(ObjPreCard_PreCard.IsHourly.toString()), CharToKeyCode_PreCard(ObjPreCard_PreCard.IsJustification.toString()));121}122function UpdatePreCard_PreCardPage_onCallBack(Response) {123 var RetMessage = Response;124 if (RetMessage != null && RetMessage.length > 0) {125 if (Response[1] == "ConnectionError") {126 Response[0] = document.getElementById('hfErrorType_PreCard').value;127 Response[1] = document.getElementById('hfConnectionError_PreCard').value;128 }129 showDialog(RetMessage[0], Response[1], RetMessage[2]);130 if (RetMessage[2] == 'success') {131 ClearList_PreCard();132 PreCard_OnAfterUpdate(Response);133 ChangePageState_PreCard('View');134 }135 else {136 if (CurrentPageState_PreCard == 'Delete')137 ChangePageState_PreCard('View');138 }139 }140}141function PreCard_OnAfterUpdate(Response) {142 if (ObjPreCard_PreCard != null) {143 var IsActive = ObjPreCard_PreCard.IsActive;144 var PreCardCode = ObjPreCard_PreCard.Code;145 var PreCardName = ObjPreCard_PreCard.Name;146 var PreCardTypeID = ObjPreCard_PreCard.PreCardTypeID;147 var PreCardTypeTitle = ObjPreCard_PreCard.PreCardTypeTitle;148 var IsDaily = ObjPreCard_PreCard.IsDaily;149 var IsHourly = ObjPreCard_PreCard.IsHourly;150 var IsJustification = ObjPreCard_PreCard.IsJustification;151 var PreCardItem = null;152 GridPreCards_PreCard.beginUpdate();153 switch (CurrentPageState_PreCard) {154 case 'Add':155 PreCardItem = GridPreCards_PreCard.get_table().addEmptyRow(GridPreCards_PreCard.get_recordCount());156 PreCardItem.setValue(0, Response[3], false);157 GridPreCards_PreCard.selectByKey(Response[3], 0, false);158 break;159 case 'Edit':160 GridPreCards_PreCard.selectByKey(Response[3], 0, false);161 PreCardItem = GridPreCards_PreCard.getItemFromKey(0, Response[3]);162 break;163 case 'Delete':164 GridPreCards_PreCard.selectByKey(ObjPreCard_PreCard.ID, 0, false);165 GridPreCards_PreCard.deleteSelected();166 break;167 }168 if (CurrentPageState_PreCard != 'Delete') {169 PreCardItem.setValue(1, IsActive, false);170 PreCardItem.setValue(2, PreCardCode, false);171 PreCardItem.setValue(3, PreCardName, false);172 PreCardItem.setValue(4, PreCardTypeID, false);173 PreCardItem.setValue(5, PreCardTypeTitle, false);174 PreCardItem.setValue(6, IsDaily, false);175 PreCardItem.setValue(7, IsHourly, false);176 PreCardItem.setValue(8, IsJustification, false);177 }178 GridPreCards_PreCard.endUpdate();179 }180}181function ClearList_PreCard() {182 document.getElementById('chbActivePreCard_PreCard').checked = false;183 document.getElementById('txtPreCardCode_PreCard').value = '';184 document.getElementById('txtPreCardName_PreCard').value = '';185 document.getElementById('cmbPreCardType_PreCard_Input').value = document.getElementById('hfcmbAlarm_PreCard').value;186 cmbPreCardType_PreCard.unSelect();187 document.getElementById('rdbDaily_PreCard').checked = false;188 document.getElementById('rdbHourly_PreCard').checked = false;189 document.getElementById('chbJustification_PreCard').checked = false;190}191function CharToKeyCode_PreCard(str) {192 var OutStr = '';193 if (str != null && str != undefined) {194 for (var i = 0; i < str.length; i++) {195 var KeyCode = str.charCodeAt(i);196 var CharKeyCode = '//' + KeyCode;197 OutStr += CharKeyCode;198 }199 }200 return OutStr;201}202function tlbItemEdit_TlbPreCard_onClick() {203 ChangePageState_PreCard('Edit');204 FocusOnFirstElement_PreCard();205}206function tlbItemDelete_TlbPreCard_onClick() {207 ChangePageState_PreCard('Delete'); 208}209function tlbItemSave_TlbPreCard_onClick() {210 CollapseControls_PreCard();211 PreCard_onSave();212}213function tlbItemCancel_TlbPreCard_onClick() {214 ChangePageState_PreCard('View');215 ClearList_PreCard();216}217function tlbItemExit_TlbPreCard_onClick() {218 ShowDialogConfirm('Exit');219}220function ShowDialogConfirm(confirmState) {221 ConfirmState_PreCard = confirmState;222 if (CurrentPageState_PreCard == 'Delete')223 document.getElementById('lblConfirm').innerHTML = document.getElementById('hfDeleteMessage_PreCard').value;224 else225 document.getElementById('lblConfirm').innerHTML = document.getElementById('hfCloseMessage_PreCard').value;226 DialogConfirm.Show();227 CollapseControls_PreCard();228}229function Refresh_GridPreCards_PreCard() {230 Fill_GridPreCards_PreCard();231}232function Fill_GridPreCards_PreCard() {233 document.getElementById('loadingPanel_GridPreCards_PreCard').innerHTML = document.getElementById('hfloadingPanel_GridPreCards_PreCard').value;234 CallBack_GridPreCards_PreCard.callback();235}236function GridPreCards_PreCard_onLoad(sender, e) {237 document.getElementById('loadingPanel_GridPreCards_PreCard').innerHTML = '';238}239function GridPreCards_PreCard_onItemSelect(sender, e) {240 if (CurrentPageState_PreCard != 'Add')241 NavigatePreCard_PreCard(e.get_item());242}243function NavigatePreCard_PreCard(selectedPreCardItem) {244 if (selectedPreCardItem != undefined) {245 document.getElementById('chbActivePreCard_PreCard').checked = selectedPreCardItem.getMember('Active').get_value();246 document.getElementById('txtPreCardCode_PreCard').value = selectedPreCardItem.getMember('Code').get_value();247 document.getElementById('txtPreCardName_PreCard').value = selectedPreCardItem.getMember('Name').get_value();248 SelectedPreCardType_PreCard = new Object();249 SelectedPreCardType_PreCard.ID = selectedPreCardItem.getMember('PrecardGroup.ID').get_text();250 document.getElementById('cmbPreCardType_PreCard_Input').value = SelectedPreCardType_PreCard.Name = selectedPreCardItem.getMember('PrecardGroup.Name').get_text();251 document.getElementById('rdbDaily_PreCard').checked = selectedPreCardItem.getMember('IsDaily').get_value();252 document.getElementById('rdbHourly_PreCard').checked = selectedPreCardItem.getMember('IsHourly').get_value();253 document.getElementById('chbJustification_PreCard').checked = selectedPreCardItem.getMember('IsPermit').get_value();254 } 255}256function CallBack_GridPreCards_PreCard_onCallbackComplete(sender, e) {257 var error = document.getElementById('ErrorHiddenField_PreCards').value;258 if (error != "") {259 var errorParts = eval('(' + error + ')');260 showDialog(errorParts[0], errorParts[1], errorParts[2]);261 if (errorParts[3] == 'Reload')262 Fill_GridPreCards_PreCard();263 }264}265function cmbPreCardType_PreCard_onExpand(sender, e) {266 if (cmbPreCardType_PreCard.get_itemCount() == 0 && CurrentPageCombosCallBcakStateObj.IsExpandOccured_cmbPreCardType_PreCard == undefined) {267 CurrentPageCombosCallBcakStateObj.IsExpandOccured_cmbPreCardType_PreCard = true;268 CallBack_cmbPreCardType_PreCard.callback();269 }270}271function cmbPreCardType_PreCard_onCollapse(sender, e) {272 if (CurrentPageCombosCallBcakStateObj.cmbPreCardType_PreCard) {273 CurrentPageCombosCallBcakStateObj.cmbPreCardType_PreCard = false;274 cmbPreCardType_PreCard.expand();275 }276 if (cmbPreCardType_PreCard.getSelectedItem() == undefined && SelectedPreCardType_PreCard == null)277 document.getElementById('cmbPreCardType_PreCard_Input').value = document.getElementById('hfcmbAlarm_PreCard').value;278 else {279 if (SelectedPreCardType_PreCard != null)280 document.getElementById('cmbPreCardType_PreCard_Input').value = SelectedPreCardType_PreCard.Name;281 }282}283function CallBack_cmbPreCardType_PreCard_onBeforeCallback(sender, e) {284 cmbPreCardType_PreCard.dispose();285}286function CallBack_cmbPreCardType_PreCard_onCallbackComplete(sender, e) {287 var error = document.getElementById('ErrorHiddenField_PreCardType').value;288 if (error == "") {289 if (CheckNavigator_onCmbCallBackCompleted())290 CurrentPageCombosCallBcakStateObj.cmbPreCardType_PreCard = true;291 else292 CurrentPageCombosCallBcakStateObj.cmbPreCardType_PreCard = false;293 document.getElementById('cmbPreCardType_PreCard_DropDown').style.display = 'none';294 cmbPreCardType_PreCard.expand();295 }296 else {297 var errorParts = eval('(' + error + ')');298 showDialog(errorParts[0], errorParts[1], errorParts[2]);299 document.getElementById('cmbPreCardType_PreCard_DropDown').style.display = 'none';300 }301}302function tlbItemOk_TlbOkConfirm_onClick() {303 switch (ConfirmState_PreCard) {304 case 'Delete':305 DialogConfirm.Close();306 UpdatePreCard_PreCard();307 break;308 case 'Exit':309 ClearList_PreCard();310 parent.CloseCurrentTabOnTabStripMenus();311 break;312 default:313 }314}315function CheckNavigator_onCmbCallBackCompleted() {316 if (navigator.userAgent.indexOf('Safari') != -1 || navigator.userAgent.indexOf('Chrome') != -1)317 return true;318 return false;319}320function tlbItemCancel_TlbCancelConfirm_onClick() {321 DialogConfirm.Close();322 ChangePageState_PreCard('View');323}324function CallBack_GridPreCards_PreCard_onCallbackError(sender, e) {325 document.getElementById('loadingPanel_GridPreCards_PreCard').innerHTML = '';326 ShowConnectionError_PreCard();327}328function ShowConnectionError_PreCard() {329 var error = document.getElementById('hfErrorType_PreCard').value;330 var errorBody = document.getElementById('hfConnectionError_PreCard').value;331 showDialog(error, errorBody, 'error');332}333function CollapseControls_PreCard() {334 cmbPreCardType_PreCard.collapse();335}336function tlbItemFormReconstruction_TlbPreCard_onClick() {337 parent.DialogLoading.Show();338 parent.document.getElementById('pgvPreCardIntroduction_iFrame').src = 'PreCard.aspx';339}340function tlbItemHelp_TlbPreCard_onClick() {341 LoadHelpPage('tlbItemHelp_TlbPreCard'); ...

Full Screen

Full Screen

train_rf.py

Source:train_rf.py Github

copy

Full Screen

1print('begin')2import numpy as np3import matplotlib.pyplot as plt 4from sklearn import linear_model5from sklearn.pipeline import Pipeline6from sklearn.ensemble import ExtraTreesRegressor7from sklearn.ensemble import AdaBoostRegressor8from sklearn.feature_selection import RFECV9from sklearn.ensemble.forest import RandomForestRegressor10from sklearn.ensemble import GradientBoostingRegressor11from sklearn.linear_model import LassoLarsCV12from sklearn.linear_model import ElasticNet13from sklearn.metrics import mean_squared_error14from sklearn.linear_model import BayesianRidge15from sklearn.linear_model import SGDRegressor16from sklearn.neighbors import KNeighborsRegressor17road1 = "E:/tianchi_koubei/mid_dataset/weather_pm_feature.txt"18road2 = "E:/tianchi_koubei/mid_dataset/count_shop_pay_correct.txt"19way1 = 'r'20road3 = "E:/tianchi_koubei/result/err_shop_loss_rf_last14_0.9.txt"21#road4 ="E:/tianchi_koubei/result/err_shop_loss_gbrt.txt"22way2 = 'w'23def create_xday(xday):24 for i in range(1,504):25 xday.append(i)26 return xday27xday_list = []28xday = create_xday(xday_list)29def create_weekend(xweekend):30 j = 331 qweekend = [68, 102, 190, 190, 229, 348, 446, 467]32 for i in range(1,504): 33 if j == 6 or j ==7:34 if i not in qweekend:35 xweekend.append(1)36 if j == 7:37 j = 138 else:39 j += 140 else:41 if j == 7:42 j = 143 else:44 j += 145 xweekend.append(0)46 else:47 xweekend.append(0)48 j += 149 return xweekend50def create_weekday():51 j = 352 weekday = []53 for i in range(1,504):54 weekday.append(j)55 j += 156 if j == 8:57 j = 158 return weekday59def create_holiday(xday):60 ho_f = []61 holiday = [51,65,66,67,88,89,93,94,95,96,97,98,99,134,177,178,185,186,187,222,223,224,225,226,227,228,229,237,277,278,279,306,307,308,345,346,347,406,443,444,445,459,460,461,462,463,464,465]62 for d in xday:63 if d not in holiday:64 ho_f.append(0)65 else:66 ho_f.append(1)67 return ho_f68xholiday = create_holiday(xday)69xweekday = create_weekday()70xweekend_list = []71xweekend = create_weekend(xweekend_list)72fr1 = open(road1,way1)73fr2 = open(road2,way1)74fw_rf = open(road3,way2)75#fw_gbrt = open(road4,way2)76i = 077#读取特征78def readfile_oneshop_X(fr,xday,xweekend,xweekday,xholiday):79 X = []80 X.append(xday)81 X.append(xweekend)82 X.append(xweekday)83 X.append(xholiday)84 '''85 for r in range(0,5):86 line = fr.readline()87 if 2<r < 4:88 re = line.strip('\n').split(',')89 data_str = map(float,re[1:])90 data_float = []91 for s in data_str:92 data_float.append(s)93 X.append((data_float))94 '''95 return np.array(X).T96#读取目标值97def readfile_oneshop_Y(fr):98 line = fr.readline()99 re = line.strip('\n').split(',')100 data_str = map(float,re[1:])101 data_float = []102 for s in data_str:103 data_float.append(s)104 for i in range(1,490):105 if data_float[i] != 0.0:106 start = i107 break108 return data_float[start-1:]109def Evaluation(pred,test):110 shop_err = 0111 for i in range(0,len(pred)):112 for p,t in zip(pred[i],test[i]):113 if (p+t) == 0.0:114 shop_err += 0.0115 else:116 shop_err += abs((p-t)/(p+t))117 total_err = shop_err/(len(pred)*len(pred[0]))118 return total_err119#shuchu120def output(fw,shopid,y_pre):121 y_pre_str = []122 y_pre_int = map(int,y_pre)123 y_pre_tostr = map(str,y_pre_int)124 for i in y_pre_tostr:125 y_pre_str.append(i)126 fw.write(str(shopid)+','+','.join(y_pre_str)+'\n')127################## 128def Evaluation(pred,test):129 shop_err = 0130 for i in range(0,len(pred)):131 for p,t in zip(pred[i],test[i]):132 if (p+t) == 0.0:133 shop_err += 0.0134 else:135 shop_err += abs((p-t)/(p+t))136 total_err = shop_err/(len(pred)*len(pred[0]))137 return total_err138def create_sampleweight(l):139 sample_weight = []140 for i in range(0,l):141 if i > l-15:142 sample_weight.append(i*0.015)143 else:144 sample_weight.append(i*0.01)145 return np.array(sample_weight)146#print(sample_weight)147adb_pre = []148knn_pre = []149sgd_pre = []150br_pre = []151lacv_pre = []152rf_pre = []153rcv_pre = []154gbrt_pre = []155ext_pre = []156Y_test = []157#ext_pre7d = []158shop = []159err_shop_rf = []160err_shop_gbrt = []161while i<10:162 # readfile163 X = []164 Y = readfile_oneshop_Y(fr2)165 start = len(Y)166 #print(start)167 X = readfile_oneshop_X(fr1,xday,xweekend,xweekday,xholiday)[-(start+14):-14]168 169 x_train = X[:-7]170 y_train = Y[:-7]171 x_test = X[-7:]172 y_test = Y[-7:]173 #sample_weight = create_sampleweight(len(y_train))174 ###175 '''176 ###177 lacv = LassoLarsCV(normalize=True,cv=8)178 lacv.fit(x_train,y_train)179 y_pre_lacv = lacv.predict(x_test)180 lacv_pre.append(y_pre_lacv)181 params_ExtraTrees = {'max_features':'log2','n_estimators': 600,'max_depth':10,'oob_score': True, 'n_jobs':4,'bootstrap':True}182 ext = ExtraTreesRegressor(**params_ExtraTrees)183 ext.fit(x_train,y_train)184 y_pre_ext = ext.predict(x_test)185 ext_pre.append(y_pre_ext)186 ###187 '''188 params_adb = {'n_estimators': 800, 'loss': 'square', 'learning_rate': 0.01, 'random_state': 3}189 adb = AdaBoostRegressor(**params_adb)190 adb.fit(x_train,y_train)191 y_pre_adb = adb.predict(x_test)192 adb_pre.append(y_pre_adb)193 params_rf = {'n_estimators':500,'max_depth':10,'min_samples_split':2,'warm_start':True,'n_jobs':4,'oob_score':True,'max_features':'log2'}194 rf = RandomForestRegressor(**params_rf)195 rf.fit(x_train,y_train)196 y_pre_rf = rf.predict(x_test)197 rf_pre.append(y_pre_rf)198 199 ###200 201 RigeLinearCV = linear_model.RidgeCV(cv=8,normalize=True,gcv_mode='auto',scoring='neg_mean_absolute_error')202 rcv = RigeLinearCV.fit(x_train,y_train)203 y_pre_rcv = rcv.predict(x_test)204 rcv_pre.append(y_pre_rcv)205 br = BayesianRidge(n_iter=300)206 br.fit(x_train,y_train)207 y_pre_br = br.predict(x_test)208 br_pre.append( y_pre_br)209 knn = KNeighborsRegressor(n_neighbors=14,algorithm='brute')210 knn.fit(x_train,y_train)211 y_pre_knn = knn.predict(x_test)212 knn_pre.append(y_pre_knn)213 #print(y_pre_knn)214 #print(y_pre_rcv)215 #y_pre_ext1 = ext.predict(x_test[:-7])216 #y_pre_ext7d = np.append(y_pre_ext1,y_pre_ext1)217 #ext_pre7d.append(y_pre_ext7d)218 #print(y_pre_ext)219 #print(y_pre_ext1)220 ###221 '''222 params_gbrt = {'loss':'huber','n_estimators': 500,'max_depth':12,'learning_rate': 0.01, 'random_state': 3}223 gbrt = GradientBoostingRegressor(**params_gbrt)224 gbrt.fit(x_train,y_train)225 y_pre_gbrt = gbrt.predict(x_test)226 gbrt_pre.append(y_pre_gbrt)227 '''228 ###229 230 Y_test.append(y_test)231 ###232 '''233 loss_rf = Evaluation([y_pre_ext],[y_test])234 #loss_gbrt = Evaluation([y_pre_gbrt],[y_test])235 if loss_rf>0.05:236 output(fw_rf,i+1,y_pre_ext)237 shop.append(i+1)238 fw_rf.write(str(i+1)+',rf,'+str(loss_rf)+'\n')239 plt.scatter(xday[-(start+14):-21],y_train)240 plt.scatter(xday[-21:-14],y_test,color = 'green')241 plt.plot(xday[-21:-14],y_pre_ext,color = 'red')242 path = "e://tianchi_koubei/fig/rf_train_7d_0.9_2.0/"+str(i+1)+'.png'243 plt.savefig(path+".png")244 plt.clf()#清除图像,所有的都画到一起了245 '''246 '''247 if loss_gbrt>0.015:248 output(fw_gbrt,i+1,y_pre_rf)249 fw_gbrt.write(str(i+1)+',gbrt,'+str(loss_gbrt)+'\n')250 '''251 252 253 254 255 print(i)256 i += 1257output(fw_rf,9999,shop)258fr1.close()259fr2.close()260fw_rf.close()261#fw_gbrt.close()262print((Evaluation(rf_pre,Y_test)))263#print(Evaluation(gbrt_pre,Y_test))264print(Evaluation(adb_pre,Y_test))265print(Evaluation(rcv_pre,Y_test))266#print(Evaluation(br_pre,Y_test))267print(Evaluation(knn_pre,Y_test))268#print(Evaluation(ext_pre,Y_test))269#print(Evaluation(lacv_pre,Y_test))...

Full Screen

Full Screen

train_rf_change.py

Source:train_rf_change.py Github

copy

Full Screen

1print('begin')2import numpy as np3import matplotlib.pyplot as plt 4from sklearn import linear_model5from sklearn.pipeline import Pipeline6from sklearn.ensemble import ExtraTreesRegressor7from sklearn.ensemble import AdaBoostRegressor8from sklearn.feature_selection import RFECV9from sklearn.ensemble.forest import RandomForestRegressor10from sklearn.ensemble import GradientBoostingRegressor11from sklearn.linear_model import LassoLarsCV12from sklearn.linear_model import ElasticNet13from sklearn.metrics import mean_squared_error14road1 = "E:/tianchi_koubei/mid_dataset/weather_pm_feature.txt"15road2 = "E:/tianchi_koubei/mid_dataset/count_shop_pay_correct.txt"16way1 = 'r'17road3 = "E:/tianchi_koubei/result/err_shop_loss_rf_last14_0.9_val.txt"18#road4 ="E:/tianchi_koubei/result/err_shop_loss_gbrt.txt"19way2 = 'w'20def create_xday(xday):21 for i in range(1,504):22 xday.append(i)23 return xday24xday_list = []25xday = create_xday(xday_list)26def create_weekend(xweekend):27 j = 328 qweekend = [68, 102, 190, 190, 229, 348, 446, 467]29 for i in range(1,504): 30 if j == 6 or j ==7:31 if i not in qweekend:32 xweekend.append(1)33 if j == 7:34 j = 135 else:36 j += 137 else:38 if j == 7:39 j = 140 else:41 j += 142 xweekend.append(0)43 else:44 xweekend.append(0)45 j += 146 return xweekend47def create_weekday():48 j = 349 weekday = []50 for i in range(1,504):51 weekday.append(j)52 j += 153 if j == 8:54 j = 155 return weekday56def create_holiday(xday):57 ho_f = []58 holiday = [51,65,66,67,88,89,93,94,95,96,97,98,99,134,177,178,185,186,187,222,223,224,225,226,227,228,229,237,277,278,279,306,307,308,345,346,347,406,443,444,445,459,460,461,462,463,464,465]59 for d in xday:60 if d not in holiday:61 ho_f.append(0)62 else:63 ho_f.append(1)64 return ho_f65xholiday = create_holiday(xday)66xweekday = create_weekday()67xweekend_list = []68xweekend = create_weekend(xweekend_list)69fr1 = open(road1,way1)70fr2 = open(road2,way1)71fw_rf = open(road3,way2)72#fw_gbrt = open(road4,way2)73i = 074#读取特征75def readfile_oneshop_X(fr,xday,xweekend,xweekday,xholiday):76 X = []77 X.append(xday)78 X.append(xweekend)79 X.append(xweekday)80 X.append(xholiday)81 '''82 for r in range(0,5):83 line = fr.readline()84 if 2<r < 4:85 re = line.strip('\n').split(',')86 data_str = map(float,re[1:])87 data_float = []88 for s in data_str:89 data_float.append(s)90 X.append((data_float))91 '''92 return np.array(X).T93#读取目标值94def readfile_oneshop_Y(fr):95 line = fr.readline()96 re = line.strip('\n').split(',')97 data_str = map(float,re[1:])98 data_float = []99 for s in data_str:100 data_float.append(s)101 for i in range(1,490):102 if data_float[i] != 0.0:103 start = i104 break105 return data_float[start-1:]106def Evaluation(pred,test):107 shop_err = 0108 for i in range(0,len(pred)):109 for p,t in zip(pred[i],test[i]):110 if (p+t) == 0.0:111 shop_err += 0.0112 else:113 shop_err += abs((p-t)/(p+t))114 total_err = shop_err/(len(pred)*len(pred[0]))115 return total_err116#shuchu117def output(fw,shopid,y_pre):118 y_pre_str = []119 y_pre_int = map(int,y_pre)120 y_pre_tostr = map(str,y_pre_int)121 for i in y_pre_tostr:122 y_pre_str.append(i)123 fw.write(str(shopid)+','+','.join(y_pre_str)+'\n')124################## 125def Evaluation(pred,test):126 shop_err = 0127 for i in range(0,len(pred)):128 for p,t in zip(pred[i],test[i]):129 if (p+t) == 0.0:130 shop_err += 0.0131 else:132 shop_err += abs((p-t)/(p+t))133 total_err = shop_err/(len(pred)*len(pred[0]))134 return total_err135lacv_pre = []136rf_pre = []137rcv_pre = []138gbrt_pre = []139ext_pre = []140Y_test = []141ori_pre = []142#ext_pre7d = []143shop = []144err_shop_rf = []145err_shop_gbrt = []146while i<2000:147 # readfile148 X = []149 Y = readfile_oneshop_Y(fr2)150 start = len(Y)151 #print(start)152 X = readfile_oneshop_X(fr1,xday,xweekend,xweekday,xholiday)[-(start+14):-14]153 154 x_train = X[:-14]155 y_train = Y[:-14]156 x_test = X[-14:-7]157 y_test = Y[-14:-7]158 x_val = X[-7:]159 y_val = Y[-7:]160 ###161 '''162 ###163 lacv = LassoLarsCV(normalize=True,cv=8)164 lacv.fit(x_train,y_train)165 y_pre_lacv = lacv.predict(x_test)166 lacv_pre.append(y_pre_lacv)167 ###168 RigeLinearCV = linear_model.RidgeCV(cv=8,normalize=True,gcv_mode='auto',scoring='neg_mean_absolute_error')169 rcv = RigeLinearCV.fit(x_train,y_train)170 y_pre_rcv = rcv.predict(x_test)171 rcv_pre.append(y_pre_rcv)172 params_rf = {'n_estimators':500,'max_depth':10,'min_samples_split':2,'warm_start':True,'n_jobs':4,'oob_score':True,'max_features':'log2'}173 rf = RandomForestRegressor(**params_rf)174 rf.fit(x_train,y_train)175 y_pre_rf = rf.predict(x_test)176 rf_pre.append(y_pre_rf)177 '''178 ###179 params_ExtraTrees = {'max_features':'log2','n_estimators': 600,'max_depth':10,'oob_score': True, 'n_jobs':4,'bootstrap':True}180 ext = ExtraTreesRegressor(**params_ExtraTrees)181 ext.fit(x_train,y_train)182 y_pre_ext = ext.predict(x_test)183 #ext_pre.append(y_pre_ext)184 #y_pre_ext1 = ext.predict(x_test[:-7])185 #y_pre_ext7d = np.append(y_pre_ext1,y_pre_ext1)186 #ext_pre7d.append(y_pre_ext7d)187 #print(y_pre_ext)188 #print(y_pre_ext1)189 ###190 '''191 params_gbrt = {'loss':'huber','n_estimators': 500,'max_depth':12,'learning_rate': 0.01, 'random_state': 3}192 gbrt = GradientBoostingRegressor(**params_gbrt)193 gbrt.fit(x_train,y_train)194 y_pre_gbrt = gbrt.predict(x_test)195 gbrt_pre.append(y_pre_gbrt)196 '''197 ###198 199 200 ###201 per = 1202 loss_rf = Evaluation([y_pre_ext],[y_test])203 #loss_gbrt = Evaluation([y_pre_gbrt],[y_test])204 if loss_rf>0.09:205 output(fw_rf,i+1,y_pre_ext)206 shop.append(i+1)207 #fw_rf.write(str(i+1)+',rf,'+str(loss_rf)+'\n')208 per = np.mean(y_test)/np.mean(y_pre_ext)209 ext.fit(np.concatenate((x_train,x_test),axis=0),np.append(y_train,y_test))210 pre_ori = ext.predict(x_val)211 if per <1:212 y_last_pre = pre_ori*per*1.05213 elif per >1:214 y_last_pre = pre_ori*per*0.95215 else:216 y_last_pre = pre_ori217 218 ori_pre.append(pre_ori)219 ext_pre.append(y_last_pre)220 Y_test.append(y_val)221 loss = Evaluation([y_last_pre],[y_test])222 if loss > 0.09:223 fw_rf.write(str(i+1)+',rf,'+str(loss)+'\n')224 plt.scatter(xday[-(start+14):-28],y_train)225 plt.scatter(xday[-28:-21],y_test,color = 'green')226 plt.plot(xday[-28:-21],y_pre_ext,color = 'red')227 plt.plot(xday[-21:-14],y_last_pre,color = 'yellow')228 plt.plot(xday[-21:-14],pre_ori,color = 'black')229 plt.scatter(xday[-21:-14],y_val,color = 'blue')230 path = "e://tianchi_koubei/fig/rf_train_7d_0.9_val/"+str(i+1)+'.png'231 plt.savefig(path+".png")232 plt.clf()#清除图像,所有的都画到一起了233 234 '''235 if loss_gbrt>0.015:236 output(fw_gbrt,i+1,y_pre_rf)237 fw_gbrt.write(str(i+1)+',gbrt,'+str(loss_gbrt)+'\n')238 '''239 240 241 242 243 print(i)244 i += 1245output(fw_rf,9999,shop)246fr1.close()247fr2.close()248fw_rf.close()249#fw_gbrt.close()250#print((Evaluation(rf_pre,Y_test)))251#print(Evaluation(gbrt_pre,Y_test))252#print(Evaluation(rcv_pre,Y_test))253print(Evaluation(ext_pre,Y_test))254print(Evaluation(ori_pre,Y_test))255#print(Evaluation(ext_pre7d,Y_test))256#print(Evaluation(lacv_pre,Y_test))...

Full Screen

Full Screen

train_rf_mean.py

Source:train_rf_mean.py Github

copy

Full Screen

1print('begin')2import numpy as np3import matplotlib.pyplot as plt 4from sklearn.ensemble.forest import RandomForestRegressor5from sklearn.ensemble import GradientBoostingRegressor6road1 = "E:/tianchi_koubei/mid_dataset/create_feature_withpre.txt"7road2 = "E:/tianchi_koubei/mid_dataset/count_shop_pay.txt"8way1 = 'r'9#road3 = "d:/tianchi_koubei/result/union_rf_mean_median_result.csv"10#way2 = 'w'11def create_xday(xday):12 for i in range(1,504):13 xday.append(i)14 return xday15xday_list = []16xday = create_xday(xday_list)17def create_weekend(xweekend):18 j = 319 for i in range(1,504):20 if j == 6 or j ==7:21 xweekend.append(1)22 if j == 7:23 j = 124 else:25 j += 126 else:27 xweekend.append(0)28 j += 129 return xweekend30xweekend_list = []31xweekend = create_weekend(xweekend_list)32fr1 = open(road1,way1)33fr2 = open(road2,way1)34#fw = open(road3,way2)35i = 036#读取特征37def readfile_oneshop_X(fr,xday,xweekend):38 X = []39 X.append(xday)40 X.append(xweekend)41 for r in range(0,13):42 line = fr.readline()43 re = line.strip('\n').split(',')44 data_str = map(float,re[1:])45 data_float = []46 for s in data_str:47 data_float.append(s)48 X.append((data_float))49 return np.array(X).T50#读取目标值51def readfile_oneshop_Y(fr):52 line = fr.readline()53 re = line.strip('\n').split(',')54 data_str = map(float,re[1:])55 data_float = []56 for s in data_str:57 data_float.append(s)58 return data_float59def Evaluation(pred,test):60 shop_err = 061 for i in range(0,len(pred)):62 for p,t in zip(pred[i],test[i]):63 if (p+t) == 0.0:64 shop_err += 0.065 else:66 shop_err += abs((p-t)/(p+t))67 total_err = shop_err/(len(pred)*len(pred[0]))68 return total_err69#shuchu70def output(fw,shopid,y_pre):71 y_pre_str = []72 y_pre_int = map(int,y_pre)73 y_pre_tostr = map(str,y_pre_int)74 for i in y_pre_tostr:75 y_pre_str.append(i)76 fw.write(str(shopid)+','+','.join(y_pre_str)+'\n')77################## 78def mean_cp_predict(x_test,mean,cp,n):79 y_pre_cp = []80 for i in range(0,len(x_test)):81 ypre = mean+n*cp82 mean = ypre83 y_pre_cp.append(ypre)84 return y_pre_cp85def mean_predict(x_test,mean,n):86 y_pre_m = []87 for i in range(0,len(x_test)):88 y_pre_m.append(n*mean)89 return y_pre_m90err_shop = []91Y_test = []92rf_pre = []93m2_pre = []94me2_pre = []95union_pre = []96while i<50:97 # readfile98 X = []99 X = readfile_oneshop_X(fr1,xday,xweekend)[-350:]100 Y = readfile_oneshop_Y(fr2)[-350:]101 x_train = X[:-14]102 y_train = Y[:-14]103 x_test = X[-14:]104 y_test = Y[-14:]105 ###106 params_rf = {'n_estimators':800, 'min_samples_split': 2,'warm_start':True,'n_jobs':4}107 rf = RandomForestRegressor(**params_rf)108 rf.fit(x_train,y_train)109 y_pre_rf = rf.predict(x_test)110 ###111 mean1 = np.mean(Y[-7:])112 mean2 = np.mean(Y[-14:])113 mean3 = np.mean(Y[-21:])114 mean4 = np.mean(Y[-28:])115 median1 = np.median(Y[-7:])116 median2 = np.median(Y[-14:])117 median3 = np.median(Y[-21:])118 median4 = np.median(Y[-28:])119 y_pre_m1 = mean_predict(x_test,mean1,1)120 y_pre_m2 = mean_predict(x_test,mean2,1)121 y_pre_m3 = mean_predict(x_test,mean3,1)122 y_pre_m4 = mean_predict(x_test,mean4,1)123 y_pre_me1 = mean_predict(x_test,median1,1)124 y_pre_me2 = mean_predict(x_test,median2,1)125 y_pre_me3 = mean_predict(x_test,median3,1)126 y_pre_me4 = mean_predict(x_test,median4,1)127 ###128 union = 0.6*np.array(y_pre_rf)+0.08*np.array(y_pre_m2)+0.04*np.array(y_pre_m1)+0.04*np.array(y_pre_m3)+0.04*np.array(y_pre_m4)+0.08*np.array(y_pre_me2)+0.04*np.array(y_pre_me1)+0.04*np.array(y_pre_me3)+0.04*np.array(y_pre_me4)129 Y_test.append(y_test)130 rf_pre.append(y_pre_rf)131 m2_pre.append(y_pre_m2)132 me2_pre.append(y_pre_me2)133 union_pre.append(union)134 #output(fw,i+1,union)135 print(i)136 i += 1137fr1.close()138fr2.close()139#fw.close()140print(Evaluation(rf_pre,Y_test))141print(Evaluation(m2_pre,Y_test))142print(Evaluation(me2_pre,Y_test))...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run avocado automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful