[英]How to take the item from string and use it as a value
I have a string and I need to use this string to fit a model.我有一个字符串,我需要使用这个字符串来适应 model。 However when I try try to do this, of course it raises an error which can be seen below.
但是,当我尝试这样做时,当然会引发一个错误,如下所示。 How can I use this string to fit the model?
我怎样才能使用这个字符串来适应 model?
import re
best_model_final = 'LinearRegression(fit_intercept=True,normalize=True)'
best_model_name = re.sub("[\(\[].*?[\)\]]", "", best_model_final )
best_model_name.fit(X.iloc[:-1], y.iloc[:-1])
AttributeError: 'str' object has no attribute 'fit'
You need to evaluate the string into a Python object, ie do您需要将字符串评估为 Python object,即执行
best_model_final = 'LinearRegression(fit_intercept=True,normalize=True)'
best_model_name = re.sub("[\(\[].*?[\)\]]", "", best_model_final )
best_model = eval(best_model_name)
best_model.fit(X.iloc[:-1], y.iloc[:-1]
See documentation of eval()
https://docs.python.org/3/library/functions.html#eval请参阅
eval()
https://docs.python.org/3/library/functions.html#eval的文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.