Python: I want to measure the processing time of a function neatly

Introduction

I think that there are times when you want to measure the execution time of a function, not just scikit-learn, but after the measurement, the calculation gets messed up.

code

If you want to measure the processing time of a function, I personally think it's better to use a decorator, which is one of the interesting features of Python. Let the decorator do the dirty math.

import time
def clock(func):
	def clocked(*args):
		t0 = time.perf_counter()
		result = func(*args)
		elapsed = time.perf_counter() - t0
		arg_str = ", ".join(repr(arg) for arg in args)
		print("[%0.8fs %s(%s) -> %r" % (elapsed,func.__name__,arg_str,result))
		return result
	return clocked

demo

Let's easily measure the learning time of scikit-learn. The above code is saved in clockdeco.py.

from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from clockdeco import clock

# load iris datasets
iris = datasets.load_iris()
X = iris.data[:,[2,3]]
y = iris.target
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=0)

# preprocessing
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
sc.fit(X_train)
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)


def modelDemo(model,x_train,y_train,test):
	model.fit(x_train,y_train)
	y_pred = model.predict(test)
	return round(accuracy_score(y_test,y_pred),2)


# Perceptron
from sklearn.linear_model import Perceptron
@clock
def PerceptronDemo():
	ppn = Perceptron(max_iter=40,eta0=0.1,random_state=0,shuffle=True)
	result = modelDemo(model=ppn,x_train=X_train_std,y_train=y_train,test=X_test_std)
	return result

# LogisticRegression
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import SGDClassifier
@clock
def LogisticRegressionDemo():
	#lr = LogisticRegression(C=1000.0,random_state=0)
	lr = SGDClassifier(loss="log")
	result = modelDemo(model=lr,x_train=X_train_std,y_train=y_train,test=X_test_std)
	return result

# SuportVectorMachine
from sklearn.svm import SVC
@clock
def SVMDemo():
	svm = SVC(kernel="linear", C=1.0, random_state=0)
	result = modelDemo(model=svm,x_train=X_train_std,y_train=y_train,test=X_test_std)
	return result


# DecisionTree
from sklearn.tree import DecisionTreeClassifier
@clock
def DecisionTreeDemo():
	tree = DecisionTreeClassifier(criterion="entropy",max_depth=3,random_state=0)
	result = modelDemo(model=tree,x_train=X_train,y_train=y_train,test=X_test)
	return result

# RandomForest
from sklearn.ensemble import RandomForestClassifier
@clock
def RandomForestDemo():
	forest = RandomForestClassifier(criterion="entropy",n_estimators=10,random_state=1,n_jobs=2)
	result = modelDemo(model=forest,x_train=X_train,y_train=y_train,test=X_test)
	return result

# KNN
from sklearn.neighbors import KNeighborsClassifier
@clock
def KNNDemo():
	knn = KNeighborsClassifier(n_neighbors=5,p=2,metric="minkowski")
	result = modelDemo(model=knn,x_train=X_train,y_train=y_train,test=X_test)
	return result

# wbdc dataset
# pipeline test
from skutils import load_wdbc_dataset
df = load_wdbc_dataset()
X = df.loc[:,2:].values
y = df.loc[:,1].values

#Class 0,Set to 1
from skutils import label_encode
le,y = label_encode(y)
X_train_w,X_test_w,y_train_w,y_test_w = train_test_split(X,y,test_size=0.20,random_state=1)

from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
@clock
def wdbc_piplineDemo():
	procs = [("scl",StandardScaler()),
			("pca",PCA(n_components=2)),("clf",LogisticRegression(random_state=1,solver='lbfgs'))]
	pipe_lr = Pipeline(procs)
	pipe_lr.fit(X_train_w,y_train_w)
	return round(pipe_lr.score(X_test_w,y_test_w),2)



demos = [globals()[name] for name in globals()
			if name.endswith("Demo")
			and name != "modelDemo"]


if __name__ == "__main__":
	for demo in demos :
		demo()

I think the decorator has made it possible to write fairly neatly. By the way, the execution result is as follows.

スクリーンショット 2020-07-29 22.35.19.png

Recommended Posts

Python: I want to measure the processing time of a function neatly
[Python3] Define a decorator to measure the execution time of a function
A function that measures the processing time of a method in python
I made a function to see the movement of a two-dimensional array (Python)
I want to start a lot of processes from python
I made a function to check the model of DCGAN
I want to know the features of Python and pip
I want to create a Dockerfile for the time being.
I want to build a Python environment
The story of blackjack A processing (python)
I want to get the name of the function / method being executed
I want to record the execution time and keep a log.
I want to output the beginning of the next month with Python
[Python] A simple function to find the center coordinates of a circle
[Python] I want to make a 3D scatter plot of the epicenter with Cartopy + Matplotlib!
I made a function to crop the image of python openCV, so please use it.
I want to separate the processing between test time and production environment
Get the caller of a function in Python
I want to create a window in Python
I want to make a game with Python
(Python Selenium) I want to check the settings of the download destination of WebDriver
A clever way to time processing in Python
I want to batch convert the result of "string" .split () in Python
I want to explain the abstract class (ABCmeta) of Python in detail.
I want to sort a list in the order of other lists
I want to color a part of an Excel string in Python
I want to customize the appearance of zabbix
I want to clear up the question of the "__init__" method and the "self" argument of a Python class.
I want to use the activation function Mish
I want to display the progress in Python!
I made a tool to estimate the execution time of cron (+ PyPI debut)
[Python] I want to know the variables in the function when an error occurs!
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
I want to use Python in the environment of pyenv + pipenv on Windows 10
I want to make a music player and file music at the same time
I want to set a life cycle in the task definition of ECS
I want to add silence to the beginning of a wav file for 1 second
I want to see a list of WebDAV files in the Requests module
I want to crop the image along the contour instead of the rectangle [python OpenCV]
I want to store the result of% time, %% time, etc. in an object (variable)
[Python] I tried to get the type name as a string from the type function
I want to get the file name, line number, and function name in Python 3.4
I made a script to record the active window using win32gui of Python
I want to embed a variable in a Python string
I want to easily implement a timeout in python
I want to iterate a Python generator many times
100 image processing knocks !! (021-030) I want to take a break ...
I want to generate a UUID quickly (memorandum) ~ Python ~
I want to grep the execution result of strace
I want to write in Python! (2) Let's write a test
I want to randomly sample a file in Python
I want to inherit to the back with python dataclass
I want to fully understand the basics of Bokeh
I want to work with a robot in python.
I want to install a package of Php Redis
[Python] I want to make a nested list a tuple
I want to write in Python! (3) Utilize the mock
I want to use the R dataset in python
I want to run a quantum computer with Python
Python Note: The mystery of assigning a variable to a variable
I want to increase the security of ssh connections