top of page

Using %timeit To Calculate the Run Time of the KNeighborsClassifier Cross-Validation for the Digits

Requirements

In the k-nearest neighbors algorithm, the computation time for classifying samples increases with the value of k. Use %timeit to calculate the run time of the KNeighborsClassifier cross-validation for the Digits dataset. Use values of 1, 10 and 20 for k. Compare the results.


Import Libraries

from sklearn import (datasets, metrics,
                     model_selection as skms,
                     naive_bayes, neighbors)

Load Dataset

%timeit -r1 datasets.load_iris()

Output:

The slowest run took 8.04 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 1: 1.07 ms per loop


iris = datasets.load_iris()

Split Dataset

from sklearn.model_selection import train_test_split
(iris_train_ftrs, iris_test_ftrs,iris_train_tgt,iris_test_tgt) = train_test_split(iris.data,iris.target,test_size=.25)

Fit Into Model

%%timeit -r1
knn = neighbors.KNeighborsClassifier(n_neighbors=3)
fit = knn.fit(iris_train_ftrs, iris_train_tgt)
preds = fit.predict(iris_test_ftrs)
metrics.accuracy_score(iris_test_tgt, preds)

Output:

The slowest run took 6.08 times longer than the fastest. This could mean that an intermediate result is being cached. 100 loops, best of 1: 2.95 ms per loop


knn = neighbors.KNeighborsClassifier(n_neighbors=3)
%timeit -r1 fit = knn.fit(iris_train_ftrs, iris_train_tgt)

Output:

The slowest run took 15.41 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 1: 336 µs per loop



If you have any query, feel free to ask in below comment section or if you need any other help related to Python, Machine Learning & Data Science then send your requirement details at:


realcode4you@gmail.com

Commentaires


REALCODE4YOU

Realcode4you is the one of the best website where you can get all computer science and mathematics related help, we are offering python project help, java project help, Machine learning project help, and other programming language help i.e., C, C++, Data Structure, PHP, ReactJs, NodeJs, React Native and also providing all databases related help.

Hire Us to get Instant help from realcode4you expert with an affordable price.

USEFUL LINKS

Discount

ADDRESS

Noida, Sector 63, India 201301

Follows Us!

  • Facebook
  • Twitter
  • Instagram
  • LinkedIn

OUR CLIENTS BELONGS TO

  • india
  • australia
  • canada
  • hong-kong
  • ireland
  • jordan
  • malaysia
  • new-zealand
  • oman
  • qatar
  • saudi-arabia
  • singapore
  • south-africa
  • uae
  • uk
  • usa

© 2023 IT Services provided by Realcode4you.com

bottom of page