Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Statistics for Machine Learning

You're reading from  Statistics for Machine Learning

Product type Book
Published in Jul 2017
Publisher Packt
ISBN-13 9781788295758
Pages 442 pages
Edition 1st Edition
Languages
Concepts
Author (1):
Pratap Dangeti Pratap Dangeti
Profile icon Pratap Dangeti

Table of Contents (16) Chapters

Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
Journey from Statistics to Machine Learning Parallelism of Statistics and Machine Learning Logistic Regression Versus Random Forest Tree-Based Machine Learning Models K-Nearest Neighbors and Naive Bayes Support Vector Machines and Neural Networks Recommendation Engines Unsupervised Learning Reinforcement Learning

Tuning of k-value in KNN classifier


In the previous section, we just checked with only the k-value of three. Actually, in any machine learning algorithm, we need to tune the knobs to check where the better performance can be obtained. In the case of KNN, the only tuning parameter is k-value. Hence, in the following code, we are determining the best k-value with grid search:

# Tuning of K- value for Train & Test data 
>>> dummyarray = np.empty((5,3)) 
>>> k_valchart = pd.DataFrame(dummyarray) 
>>> k_valchart.columns = ["K_value","Train_acc","Test_acc"] 
 
>>> k_vals = [1,2,3,4,5] 
 
>>> for i in range(len(k_vals)): 
...     knn_fit = KNeighborsClassifier(n_neighbors=k_vals[i],p=2,metric='minkowski') 
...     knn_fit.fit(x_train,y_train) 
 
...     print ("\nK-value",k_vals[i]) 
     
...     tr_accscore = round(accuracy_score(y_train,knn_fit.predict(x_train)),3) 
...     print ("\nK-Nearest Neighbors - Train ConfusionMatrix\n\n",pd.crosstab...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}