How to use get_predict_point method in Airtest

Best Python code snippet using Airtest

Evaluation.py

Source: Evaluation.py Github

copy

Full Screen

...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)))...

Full Screen

Full Screen

callbacks.py

Source: callbacks.py Github

copy

Full Screen

...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)...

Full Screen

Full Screen

server.py

Source: server.py Github

copy

Full Screen

...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...

Full Screen

Full Screen

Blogs

Check out the latest blogs from LambdaTest on this topic:

QA&#8217;s and Unit Testing &#8211; Can QA Create Effective Unit Tests

Unit testing is typically software testing within the developer domain. As the QA role expands in DevOps, QAOps, DesignOps, or within an Agile team, QA testers often find themselves creating unit tests. QA testers may create unit tests within the code using a specified unit testing tool, or independently using a variety of methods.

LIVE With Automation Testing For OTT Streaming Devices ????

People love to watch, read and interact with quality content — especially video content. Whether it is sports, news, TV shows, or videos captured on smartphones, people crave digital content. The emergence of OTT platforms has already shaped the way people consume content. Viewers can now enjoy their favorite shows whenever they want rather than at pre-set times. Thus, the OTT platform’s concept of viewing anything, anytime, anywhere has hit the right chord.

Why Agile Is Great for Your Business

Agile project management is a great alternative to traditional methods, to address the customer’s needs and the delivery of business value from the beginning of the project. This blog describes the main benefits of Agile for both the customer and the business.

Options for Manual Test Case Development &#038; Management

The purpose of developing test cases is to ensure the application functions as expected for the customer. Test cases provide basic application documentation for every function, feature, and integrated connection. Test case development often detects defects in the design or missing requirements early in the development process. Additionally, well-written test cases provide internal documentation for all application processing. Test case development is an important part of determining software quality and keeping defects away from customers.

Test strategy and how to communicate it

I routinely come across test strategy documents when working with customers. They are lengthy—100 pages or more—and packed with monotonous text that is routinely reused from one project to another. Yawn once more— the test halt and resume circumstances, the defect management procedure, entrance and exit criteria, unnecessary generic risks, and in fact, one often-used model replicates the requirements of textbook testing, from stress to systems integration.

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 Airtest 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