How to use calc_label method in hypothesis

Best Python code snippet using hypothesis

script.py

Source:script.py Github

copy

Full Screen

1'''2University at Buffalo - Spring 20153CSE 574 - Introduction to Machine Learning4Programming Assignment 25Authors: Dheeraj Balakavi, Pravin Umamaheswaran, Mithun Nagesh6It's not who you are, it's what you do that defines you - Batman / Bruce Wayne7'''8from __future__ import division9import numpy as np10from scipy.optimize import minimize11from scipy.io import loadmat12from math import sqrt13import scipy.io14import matplotlib.pyplot as plt15import pickle16def ldaLearn(X,y):17 # Inputs18 # X - a N x d matrix with each row corresponding to a training example19 # y - a N x 1 column vector indicating the labels for each training example20 #21 # Outputs22 # means - A d x k matrix containing learnt means for each of the k classes23 # covmat - A single d x d learnt covariance matrix 24 25 # IMPLEMENT THIS METHOD26 27 28 means = np.array([])29 unique_y = np.unique(y)30 31 i = 0;32 # processing each unique values in batches33 for index_val in unique_y:34 35 mapp_matrix = (y == index_val)36 mapp_matrix.shape = ((1,X.shape[0])) 37 #extended matrix38 ex_mapp_matrix = np.tile(mapp_matrix,X.shape[1])39 ex_mapp_matrix = np.reshape(ex_mapp_matrix,(X.shape[1],X.shape[0]))40 ex_mapp_matrix = ex_mapp_matrix.T41 42 MeanMat = np.asarray(X[ex_mapp_matrix])43 new_row = MeanMat.shape[0]/X.shape[1]44 45 KIK = np.reshape(MeanMat,(new_row,X.shape[1]))46 #taking the maen values of i/p per input data variable(x^i) per class47 Mean_Val = KIK.mean(0)48 49 if i == 0:50 means = np.hstack(Mean_Val)51 else :52 means = np.vstack((means,Mean_Val)) 53 i+=1 54 55 means = means . T56 covmat = np.cov(X.T) # i am not sure about the covarience57 58 return means,covmat59def qdaLearn(X,y):60 # Inputs61 # X - a N x d matrix with each row corresponding to a training example62 # y - a N x 1 column vector indicating the labels for each training example63 #64 # Outputs65 # means - A d x k matrix containing learnt means for each of the k classes66 # covmats - A list of k d x d learnt covariance matrices for each of the k classes67 68 # IMPLEMENT THIS METHOD69 covmats = list()70 unique_classes = np.unique(y)71 mean_vectors = []72 for cl in range(1,5):73 mean_vectors.append(np.mean(X[y==cl], axis=0))74 75 i =0 76 for class_val in unique_classes:77 mapping_matrix = (y==class_val)78 mapping_matrix.shape = ((1,X.shape[0]))79 80 # creating an extended matrix by using tile function81 # to match the dimensions and separate by class82 83 ext_map_matrix = np.tile(mapping_matrix,X.shape[1])84 ext_map_matrix = np.reshape(ext_map_matrix,(X.shape[1],X.shape[0]))85 ext_map_matrix = ext_map_matrix.T86 87 class_ip = np.asarray(X[ext_map_matrix])88 row_size = class_ip.shape[0]/X.shape[1]89 90 class_ip = np.reshape(class_ip,(row_size,X.shape[1]))91 covmat = np.cov(class_ip.T)92 covmats.append(covmat)93 94 #take mean values of i/p per input data variable per class95 mean_value = class_ip.mean(0)96 if i == 0:97 means = np.hstack(mean_value)98 else :99 means = np.vstack((means,mean_value)) 100 i+=1 101 102 means = means . T103 104 return means,covmats105def ldaTest(means,covmat,Xtest,ytest):106 # Inputs107 # means, covmat - parameters of the LDA model108 # Xtest - a N x d matrix with each row corresponding to a test example109 # ytest - a N x 1 column vector indicating the labels for each test example110 # Outputs111 # acc - A scalar accuracy value112 113 # IMPLEMENT THIS METHOD114 no_of_classes = 5115 inv_covariance = np.linalg.inv(covmat) 116 N = Xtest.shape[0]117 118 calc_label = np.array([])119 #calc_label = np.reshape(calc_label,(100,1))120 new_mean = means.T121 i = 0122 for each_row in range(N): # for each row data calculate the probability or the classes123 row_data = Xtest[each_row,:]124 pdf_vector = np.array([])125 for each_class in range(no_of_classes):126 X_MU = row_data - new_mean[each_class]127 intmdt = np.dot(X_MU.T,inv_covariance)128 temp = np.dot(intmdt,X_MU)129 d = 1130 pdf = np.exp(-1/2*temp)131 pdf_vector = np.append(pdf_vector,pdf)132 #pdf_vector[each_class] = pdf133 calc_label = np.append(calc_label,[np.argmax(pdf_vector)+1]) 134 calc_label = np.matrix(calc_label).T 135 136 acc = 100 * np.mean((calc_label == ytest).astype(float)) 137 #plotGraph(Xtest,ytest,calc_label)138 return acc139def qdaTest(means,covmats,Xtest,ytest):140 # Inputs141 # means, covmats - parameters of the QDA model142 # Xtest - a N x d matrix with each row corresponding to a test example143 # ytest - a N x 1 column vector indicating the labels for each test example144 # Outputs145 # acc - A scalar accuracy value146 147 # IMPLEMENT THIS METHOD148 #no_of_classes = 5149 k = 5150 N = Xtest.shape[0]151 i= 0152 new_mean = means.T153 calc_label = np.array([])154 for each_row in range(N): # for each row of the data calculate the probability 155 x_i = Xtest[each_row,:]156 pdf_vector = np.array([])157 for cl,cov_mat in zip(range(1,6),covmats):158 inv_covmat = np.linalg.inv(cov_mat) # inverse covariance matrix159 normlz_factor = 1/np.sqrt((2*np.pi)**k * np.linalg.det(cov_mat))160 161 X_MU = x_i - new_mean[cl-1]162 intmdt = np.dot(X_MU.T,inv_covmat)163 temp = np.dot(intmdt,X_MU)164 pdf = np.exp(-1/2*temp)*normlz_factor165 pdf_vector = np.append(pdf_vector,pdf)166 calc_label = np.append(calc_label,[np.argmax(pdf_vector)+1])167 168 calc_label = np.matrix(calc_label).T 169 170 acc = 100 * np.mean((calc_label == ytest).astype(float)) 171 172 return acc173# Author: Dheeraj Balakavi174 # Inputs: 175 # X = N x d 176 # y = N x 1 177 # Output: 178 # w = d x 1179def learnOLERegression(X,y):180 # Step-1: Compute the Pseudo-Inverse of X --> PI(X)181 XT = X.transpose()182 XT_into_X = np.dot (XT, X)183 XT_into_X_inv = np.linalg.inv(XT_into_X)184 185 X_pi = np.dot (XT_into_X_inv, XT)186 187 # Test to see if I got it right.. if we do (X-pi * x) we must get an identity matrix 188 # as it is pseudo inverse we are doing189 X_ident = np.dot (X_pi, X)190 191 # Step-2: Compute w192 w = np.dot (X_pi, y) 193 return w194# Author: Dheeraj Balakavi195 # Inputs:196 # X = N x d 197 # y = N x 1 198 # lambd = ridge parameter (scalar)199 # Output: 200 # w = d x 1 201def learnRidgeRegression(X,y,lambd):202 X_rows, X_columns = X.shape203 N = X_rows204 M = X_columns205 # Step-1: Compute the Pseudo-Inverse of X with regularization co-eff206 XT = X.transpose()207 XT_into_X = np.dot (XT, X)208 identity = np.identity (M)209 lambd_into_NI = (lambd * N )* identity210 211 sum_lambNI_XTX = lambd_into_NI + XT_into_X212 sum_lambNI_XTX_inv = np.linalg.inv(sum_lambNI_XTX)213 214 # Step-2: Compute w215 product_one = np.dot (sum_lambNI_XTX_inv, XT)216 w = np.dot (product_one, y)217 218 return w219# Author: Dheeraj Balakavi220 # Inputs:221 # w = d x 1222 # Xtest = N x d223 # ytest = X x 1224 # Output:225 # rmse226def testOLERegression(w,Xtest,ytest):227 # Step-1: Compute the root mean square error (rmse)228 X_rows, X_columns = Xtest.shape229 N = X_rows230 231 wT = w.transpose()232 wT_into_Xtest = np.dot (Xtest, wT.transpose())233 234 subVal = np.subtract (ytest, wT_into_Xtest)235 subVal_sqr = subVal * subVal236 237 sumVal = np.sum (subVal_sqr)238 239 sumVal_sqrt = np.sqrt(sumVal)240 rmse = sumVal_sqrt / N241 return rmse242# Author: Dheeraj Balakavi243 # compute squared error (scalar) and gradient of squared error with respect244 # to w (vector) for the given data X and y and the regularization parameter245 # lambda 246def regressionObjVal(w, X, y, lambd):247 # Step-1: Error computation --> scalar248 X_rows, X_columns = X.shape249 N = X_rows250 w = np.vstack (w)251 #w = np.reshape(w, (w.shape[0], 1)) 252 Xw = np.dot (X, w)253 y_minus_Xw = y - Xw254 y_minus_Xw_transpose = y_minus_Xw.transpose()255 256 prod1 = (np.dot (y_minus_Xw_transpose, y_minus_Xw)) / (2 * N) 257 prod2 = (1/2) * lambd * np.dot (w.transpose(), w) 258 error = (prod1 + prod2).item(0)259 #print error260 # Step-2: Error grad computation --> vector261 XT_X = np.dot (X.transpose(), X)262 wT_XT_X = np.dot (w.transpose(), XT_X) 263 yT_X = np.dot (y.transpose(), X)264 yT_X = -1 * yT_X265 266 sum1 = (yT_X + wT_XT_X) / N267 sum2 = lambd * w.transpose()268 error_grad = sum1 + sum2269 error_grad = np.squeeze(np.asarray(error_grad))270 #print error_grad 271 272 return error, error_grad273def mapNonLinear(x,p):274 # Inputs: 275 # x - a single column vector (N x 1) 276 # p - integer (>= 0) 277 # Outputs: 278 # Xd - (N x (d+1)) 279 # IMPLEMENT THIS METHOD280 output = []281 for val in np.nditer(x):282 283 #if p == 0:284 # Xd = np.ones((x.shape[0],1))285 # break286 287 for power in range(0,p+1):288 #print 'awesome' 289 output.append(pow(val,power))290 #print 'x:' + str(x.shape[0])291 #print 'p:' + str(p)292 #print 'Size is:' + str(len(output))293 Xd = np.asarray(output)294 Xd = np.reshape(Xd,(x.shape[0],p+1))295 return Xd296# Main script297# Problem 1298# load the sample data 299 300X,y,Xtest,ytest = pickle.load(open('sample.pickle','rb')) 301# LDA302means,covmat = ldaLearn(X,y)303ldaacc = ldaTest(means,covmat,Xtest,ytest)304print('LDA Accuracy = '+str(ldaacc))305# QDA306means,covmats = qdaLearn(X,y)307qdaacc = qdaTest(means,covmats,Xtest,ytest)308print('QDA Accuracy = '+str(qdaacc))309# Problem 2310X,y,Xtest,ytest = pickle.load(open('diabetes.pickle','rb')) 311# add intercept312X_i = np.concatenate((np.ones((X.shape[0],1)), X), axis=1)313Xtest_i = np.concatenate((np.ones((Xtest.shape[0],1)), Xtest), axis=1)314w = learnOLERegression(X,y)315mle = testOLERegression(w,Xtest,ytest)316w_i = learnOLERegression(X_i,y)317mle_i = testOLERegression(w_i,Xtest_i,ytest)318print('RMSE without intercept '+str(mle))319print('RMSE with intercept '+str(mle_i))320# Problem 3321k = 101322lambdas = np.linspace(0, 0.004, num=k)323i = 0324rmses3 = np.zeros((k,1))325for lambd in lambdas:326 w_l = learnRidgeRegression(X_i,y,lambd)327 rmses3[i] = testOLERegression(w_l,Xtest_i,ytest)328 i = i + 1329#plt.plot(lambdas,rmses3)330# Problem 4331k = 101332lambdas = np.linspace(0, 0.004, num=k)333i = 0334rmses4 = np.zeros((k,1))335opts = {'maxiter' : 100} # Preferred value. 336w_init = np.zeros((X_i.shape[1],1))337for lambd in lambdas:338 args = (X_i, y, lambd)339 w_l = minimize(regressionObjVal, w_init, jac=True, args=args,method='CG', options=opts)340 w_l_1 = np.zeros((X_i.shape[1],1))341 for j in range(len(w_l.x)):342 w_l_1[j] = w_l.x[j]343 rmses4[i] = testOLERegression(w_l_1,Xtest_i,ytest)344 i = i + 1345#plt.plot(lambdas,rmses4)346fig, ax = plt.subplots()347fig.suptitle('Using Gradient Descent for Ridge Regression Learning', fontsize=14, fontweight='bold')348ax.set_title('Lambda vs RMSE4 for Training data')349ax.plot(lambdas,rmses4)350ax.set_xlabel('Lambda')351ax.set_ylabel('RMSE4')352ax.legend(loc='upper right')353# Problem 5354pmax = 7355lambda_opt = lambdas[np.argmin(rmses4)]356rmses5 = np.zeros((pmax,2))357for p in range(pmax):358 Xd = mapNonLinear(X[:,2],p)359 Xdtest = mapNonLinear(Xtest[:,2],p)360 w_d1 = learnRidgeRegression(Xd,y,0)361 rmses5[p,0] = testOLERegression(w_d1,Xdtest,ytest)362 w_d2 = learnRidgeRegression(Xd,y,lambda_opt)363 rmses5[p,1] = testOLERegression(w_d2,Xdtest,ytest)364plt.plot(range(pmax),rmses5)...

Full Screen

Full Screen

main.py

Source:main.py Github

copy

Full Screen

1# Temperature converter2from tkinter import *3from tkinter import messagebox4root = Tk()5root.geometry('800x600')6root.config(bg='#00A676')7# Frames for celsius to fahrenheit and vice versa8c_f_frame = Frame(root, width=300, height=200, bg='#333')9c_f_frame.place(x=80, y=50)10f_c_frame = Frame(root, width=300, height=200, bg='#333')11f_c_frame.place(x=420, y=50)12# Headings for celsius to fahrenheit and vice versa13c_f_label = Label(c_f_frame, text='Celsius to Fahrenheit', bg='#333', fg='white')14c_f_label.place(x=10, y=10)15f_c_label = Label(f_c_frame, text='Fahrenheit to Celsius', bg='#333', fg='white')16f_c_label.place(x=10,y=10)17# Entry fields for celsius to fahrenheit and vice versa18c_f_entry = Entry(c_f_frame, state='readonly')19c_f_entry.place(x=70, y=100)20f_c_entry = Entry(f_c_frame, state='readonly')21f_c_entry.place(x=70, y=100)22# Functionality for activating entry fields23def c_f_activation():24 c_f_entry.config(state='normal')25 c_f_entry.focus()26 f_c_entry.config(state='normal')27 f_c_entry.delete(0, END)28 f_c_entry.config(state='readonly')29def f_c_activation():30 f_c_entry.config(state='normal')31 f_c_entry.focus()32 c_f_entry.config(state='normal')33 c_f_entry.delete(0, END)34 c_f_entry.config(state='readonly')35# Entry activation buttons36c_f_activate = Button(root, text='Activate - Celsius to fahrenheit', command=c_f_activation)37c_f_activate.place(x=115, y=270)38f_c_activate = Button(root, text='Activate - Fahrenheit to Celsius', command=f_c_activation)39f_c_activate.place(x=455, y=270)40# Temperature conversion function41def conversion():42 try:43 # Clears result label44 calc_label.config(text='')45 # Celsius to Fahrenheit46 if c_f_entry['state'] == 'normal':47 c_temp = float(c_f_entry.get())48 f_result = round((c_temp * (9/5)) + 32, 1)49 calc_label.config(text=f_result)50 # Fahrenheit to Celsius51 elif f_c_entry['state'] == 'normal':52 f_temp = float(f_c_entry.get())53 c_result = round((f_temp-32)*(5/9), 1)54 calc_label.config(text=c_result)55 # raise value error if invalid entry given56 except ValueError:57 messagebox.showerror(message='Invalid entry')58# Convert button and label for result59calc = Button(root, text='Calculate Conversion', command=conversion)60calc.place(x=200, y=350)61calc_label = Label(root, width=20, height=2, bg='#333', fg='white')62calc_label.place(x=420, y=350)63# functionality for clear button to clear fields64def delete():65 c_f_entry.config(state='normal')66 f_c_entry.config(state='normal')67 calc_label.config(text='')68 c_f_entry.delete(0, END)69 f_c_entry.delete(0, END)70 f_c_entry.config(state='readonly')71 c_f_entry.config(state='readonly')72# clear button73clear = Button(root, text='Clear', command=delete)74clear.place(x=550, y=500)75# Exit button with inbuilt function76escape = Button(root, text='Exit', command='exit')77escape.place(x=650, y=500)...

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