IBM Watson视觉识别API:如何用变量动态指定分类器参数名?
create_classifier Absolutely, this is totally doable in Python! The key here is leveraging Python's ability to handle dynamic keyword arguments using dictionary unpacking—perfect for your use case where you want to generate parameter names from variables.
Why Your Initial Idea Won't Work Directly
If you try to write something like var1_positive_examples=beagle directly, Python will treat var1_positive_examples as a literal parameter name, not the value stored in var1. So we need a way to dynamically build that parameter name.
Step-by-Step Solution
Define your variable with the base name you want to use:
var1 = "beagle" # Assume `beagle` is already defined as your positive examples file/bytesCreate a dictionary where the key is the dynamically generated parameter name (combining your variable with
_positive_examples), and the value is your example data:classifier_params = { f"{var1}_positive_examples": beagle }Note: We use an f-string here to easily concatenate the variable value with the suffix—Python 3.6+ supports this. For older versions, you can use
var1 + "_positive_examples"instead.Pass the dictionary to
create_classifierusing**unpacking:
The**operator tells Python to unpack the dictionary's key-value pairs into keyword arguments, just like if you had written them explicitly:model = visual_recognition.create_classifier('dogs', **classifier_params)
Bonus: Handling Multiple Dynamic Parameters
If you need to add more classes dynamically, you can just extend the dictionary:
var2 = "golden_retriever" classifier_params[f"{var2}_positive_examples"] = golden_retriever # Now call with both parameters model = visual_recognition.create_classifier('dog_breeds', **classifier_params)
This approach works exactly the same as writing out each parameter explicitly—IBM's SDK will receive the correct parameter names and values just like the example in the docs.
内容的提问来源于stack exchange,提问作者Gianmarco Carrieri

