问题
Assume you have some function function
in Python that works by looping: for example it could be a function that evaluates a certain mathematical expression, e.g. x**2
, for all elements from an array, e.g. ([1, 2, ..., 100])
(obviously this is a toy example). Would it be possible to write a code such that, each time function
goes through a loop and obtains a result, some code is executed, e.g. print("Loop %s has been executed" % i)
? So, in our example, when x**1
has been computed, the program prints Loop 1 has been executed
, then when x**2
has been computed, it prints Loop 2 has been executed
, and so on.
Note that the difficulty comes from the fact that I do not program the function, it is a preexisting function from some package (more specifically, the function I am interested in would be GridSearchCV
from package scikit learn
).
回答1:
The easiest way to do this would be to just copy the function's code into your own function, tweak it, and then use it. In your case, you would have to subclass GridSearchCV
and override the _fit
method. The problem with this approach is that it may not survive a package upgrade.
In your case, that's not necessary. You can just specify a verbosity level when creating the object:
GridSearchCV(verbose=100)
I'm not entirely sure what the verbosity number itself means. Here's the documentation from the package used internally that does the printing:
The verbosity level: if non zero, progress messages are printed. Above 50, the output is sent to stdout. The frequency of the messages increases with the verbosity level. If it more than 10, all iterations are reported.
You can look at the source code if you really want to know what the verbosity
number does. I can't tell.
回答2:
You could potentially use monkey-patching ("monkey" because it's hacky)
Assuming the library function is
def function(f):
for i in range(100):
i**2
and you want to enter a print statement, you would need to copy the entire function into your own file, and make your tiny edit:
def my_function(f):
for i in range(100):
i**2
print ("Loop %s" % i)
Now you overwrite the library function:
from library import module
module.existing_function = my_function
Obviously this is not an easily maintainable solution (if your target library is upgraded, you might have to go through this process again), so make sure you use it only for temporary debugging purposes.
来源:https://stackoverflow.com/questions/34697048/gridsearchcv-print-some-expression-each-time-a-function-completes-a-loop