Best Python code snippet using Airtest
Evaluation.py
Source:Evaluation.py
...9 df = pd.DataFrame()10 df['y_xgb_test'] = y_test11 df['y_xgb_pred'] = y_pred12 kstable = ks(df, 'y_xgb_test', 'y_xgb_pred')13 get_pos_neg_cnt(y_test, y_pred, get_predict_point(kstable))14def ks(data=None, target=None, prob=None):15 data['target0'] = 1 - data[target]16 data['bucket'] = pd.qcut(data[prob], 10)17 grouped = data.groupby('bucket', as_index=False)18 kstable = pd.DataFrame()19 kstable['min_prob'] = grouped.min()[prob]20 kstable['max_prob'] = grouped.max()[prob]21 kstable['events'] = grouped.sum()[target]22 kstable['nonevents'] = grouped.sum()['target0']23 kstable = kstable.sort_values(by="min_prob", ascending=False).reset_index(drop=True)24 kstable['event_rate'] = (kstable.events / data[target].sum()).apply('{0:.2%}'.format)25 kstable['nonevent_rate'] = (kstable.nonevents / data['target0'].sum()).apply('{0:.2%}'.format)26 kstable['cum_eventrate'] = (kstable.events / data[target].sum()).cumsum()27 kstable['cum_noneventrate'] = (kstable.nonevents / data['target0'].sum()).cumsum()28 kstable['KS'] = np.round(kstable['cum_eventrate'] - kstable['cum_noneventrate'], 3) * 10029 # Formating30 kstable['cum_eventrate'] = kstable['cum_eventrate'].apply('{0:.2%}'.format)31 kstable['cum_noneventrate'] = kstable['cum_noneventrate'].apply('{0:.2%}'.format)32 kstable.index = range(1, 11)33 kstable.index.rename('Decile', inplace=True)34 pd.set_option('display.max_columns', 9)35 print(kstable)36 # Display KS37 from colorama import Fore38 print(Fore.RED + "KS is " + str(max(kstable['KS'])) + "%" + " at decile " + str(39 (kstable.index[kstable['KS'] == max(kstable['KS'])][0])))40 return kstable41# è¿åæ£è´é¢æµ array42def get_pos_neg_predict(y_test, y_pred):43 print('in %s' % sys._getframe().f_code.co_name)44 y = pd.DataFrame(np.array([list(y_test), list(y_pred)]).T, columns=['true', 'pred'])45 pos_pred = y[y['true'] == 1]['pred']46 neg_pred = y[y['true'] == 0]['pred']47 print(pos_pred.shape)48 print(neg_pred.shape)49 return pos_pred, neg_pred50def draw_pos_neg_picture(pos_pred, neg_pred):51 print('in %s' % sys._getframe().f_code.co_name)52 # 使æ£è´æ ·æ¬éä¸è´ ç¨nanå¡«å
53 pos_cnt = pos_pred.shape[0]54 neg_cnt = neg_pred.shape[0]55 if neg_cnt > pos_cnt:56 pos_pred_fill = np.array([np.nan] * (neg_cnt - pos_cnt))57 pos_pred_fill = np.hstack((pos_pred, pos_pred_fill))58 neg_pred_fill = neg_pred59 else:60 neg_pred_fill = np.array([np.nan] * (pos_cnt - neg_cnt))61 neg_pred_fill = np.hstack((neg_pred, neg_pred_fill))62 pos_pred_fill = pos_pred63 dist = pd.DataFrame(np.array([pos_pred_fill, neg_pred_fill]).T, columns=['good', 'bad'])64 # dist= pd.DataFrame(np.array([[0.1,0.2,0.2,np.nan],[0.7,0.8,0.8,0.9]]).T,columns=['a','b'])65 fig, ax = plt.subplots(figsize=(15, 6))66 dist.plot.kde(ax=ax, legend=False, title='Histogram: good vs. bad')67 dist.plot.hist(density=False, ax=ax, color=['red', 'blue'], histtype='barstacked') # density=Frueç¨äºå è½®å»68 ax.set_ylabel('Frequency')69 ax.grid(axis='sample')70 ax.set_facecolor('#d8dcd6')71 plt.xlim(0, 1)72 plt.show()73# ä½ç»æåå¸å¾ è°ç¨save_test_resultãget_test_resultãget_pos_neg_predictãdraw_pos_neg_pictureçå½æ°74def get_pos_neg_picture(y_test, y_pred):75 import ParseData76 print('in %s' % sys._getframe().f_code.co_name)77 ParseData.save_test_result(y_test, y_pred)78 y_test, y_pred = ParseData.read_test_result()79 pos_pred, neg_pred = get_pos_neg_predict(y_pred, y_test)80 draw_pos_neg_picture(pos_pred, neg_pred)81# è·å¾é¢æµååç¹ï¼ksæ大çç¹çæ¦çå¼ï¼82def get_predict_point(kstable):83 max_decile = kstable.index[kstable['KS'] == max(kstable['KS'])][0]84 predict_point = kstable['min_prob'][max_decile]85 return predict_point86# è·å¾æ£è´æ ·æ¬çå®ãé¢æµä¸ªæ° ä¼ å
¥ä¸ºarrayæSeries87def get_pos_neg_cnt(y_true, y_pred, predict_point):88 df = pd.DataFrame()89 df['true'] = y_true90 df['pred'] = y_pred91 true_pos = df[df['true'] == 1].shape[0]92 true_neg = df[df['true'] == 0].shape[0]93 pred_pos = df[df['pred'] > predict_point].shape[0] # ksæ¯å·¦å¼å³éåºé´94 pred_neg = df[df['pred'] <= predict_point].shape[0]95 assert true_pos + true_neg == pred_pos + pred_neg, 'çå¼åé¢æµå¼çæ°éä¸ä¸è´ï¼'96 print('å¨å®é
çæ ·æ¬ä¸ï¼%d为æ£æ ·æ¬ï¼%d为è´æ ·æ¬ï¼æ£è´æ¯ä¾ä¸º%f' % (true_pos, true_neg, (true_pos / true_neg)))...
callbacks.py
Source:callbacks.py
...22 self.row=row23 self.count = count24 self.point = point25 26 def get_predict_point(self, transform_mat):27 """28 transform_mat: (batch, 6)29 """30 if self.point == 4:31 zeros=tf.zeros_like(transform_mat)[:,:1]32 # affine_transforms=(batch, 6)33 transform_mat = tf.concat([transform_mat[:,0:1], zeros, transform_mat[:,1:2], zeros, transform_mat[:,2:4]],1)34 35 #print("get_predict_point : transform_mat ",end = "")36 #print(type(transform_mat[1]), transform_mat.shape,transform_mat) 37 #tf.print(tf.shape(transform_mat))38 transform_mat = np.array(transform_mat)39 #print("\n\nafter\n\n")40 #print(type(transform_mat[1]), transform_mat.shape,transform_mat)41 transform_mat = transform_mat.reshape((-1, 2, 3))42 my_coord = np.array([[43 [-1,-1,1],44 [ 1, 1,1],45 [ 1,-1,1],46 [-1, 1,1]47 ]])48 my_coord = my_coord.transpose((0,2,1))49 new_coord = np.matmul(transform_mat, my_coord)50 new_coord = new_coord.transpose((0,2,1))51 return new_coord52 def coord_to_int(self, coords, imgshape):53 b, ih, iw = imgshape[:3]54 n_points=coords.shape[-1] // 255 ncoords = (coords + 1.0) / 2.0 * np.array([[iw, ih]*n_points])56 ncoords = ncoords.astype(np.int32).reshape((b, -1))57 return ncoords58 def on_epoch_end(self, epoch, logs={}):59 for i, (images,labels) in enumerate(self.dataset, 1):60 if self.require_coords:61 label, coords=labels62 stn_result, transform_mat = self.stn_model(images, training=False)63 # process origin image64 images = images.numpy()[:self.row]65 images = (images*255.).astype(np.uint8)66 transform_mat = transform_mat.numpy()[:self.row]67 #print("on_epoch_end : transform_mat ",end = "")68 #print(type(transform_mat[1]), transform_mat.shape,transform_mat) 69 #tf.print(tf.shape(transform_mat))70 pcoords = self.coord_to_int(self.get_predict_point(transform_mat), images.shape)71 if self.require_coords: 72 gcoords = self.coord_to_int(coords.numpy()[:self.row], images.shape)73 n_points = pcoords.shape[-1] // 274 for ii in range(len(images)):75 img = images[ii].copy()76 for iii in range(n_points):77 if self.require_coords: 78 images[ii] = cv2.circle(img, tuple(gcoords[ii,2*iii:2*(iii+1)]), 3, (int(127+128/4*iii), 0, 0), -1)79 images[ii] = cv2.circle(img, tuple(pcoords[ii,2*iii:2*(iii+1)]), 3, (0, 0, int(127+128/4*iii)), -1)80 81 images = np.vstack(images)82 # process stn_result83 stn_result = stn_result.numpy()[:self.row]84 stn_result = (stn_result*255.).astype(np.uint8)...
server.py
Source:server.py
...24@app.route("/predict", methods=["GET","POST"])25def predict():26 if not request.json or not 'data' in request.json:27 abort(400)28 result = get_predict_point(embeddings,29 request.json['p0x'], 30 request.json['p0y'],31 request.json['p0r'],32 request.json['p1x'],33 request.json['p1y'],34 request.json['p1r'])35 return result, 20036def get_predict_point(embeddings, p0x, p0y, p0r, p1x, p1y, p1r):37 #max_p0x, max_p0y, max_p1x, max_p1y = get_corners(p0x, p0y, p0r, p1x, p1y, p1r)38 39 #area_embeddings = get_embaddings_of_tiles_in_area(max_p0x, max_p0y, max_p1x, max_p1y)40 41 id0 = get_tile_id_by_geolocation(p0x, p0y)42 id1 = get_tile_id_by_geolocation(p1x, p1y)43 grapf = build_grapf(area_embeddings)44 predict_point = predict_on_tree(id0, id1, grapf)45def predict_on_tree(id0, id1, grapf):46 interpolation_size = 547 # interpolate from 185175 to 75168848 # These numbers are cherry picked. Once we train for longer, we can remove it49 begin_index = id0 #8421250 end_index = id1...
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!!