I have a string and I need to use this string to fit a 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?
JavaScript
x
7
1
import re
2
best_model_final = 'LinearRegression(fit_intercept=True,normalize=True)'
3
best_model_name = re.sub("[([].*?[)]]", "", best_model_final )
4
best_model_name.fit(X.iloc[:-1], y.iloc[:-1])
5
6
AttributeError: 'str' object has no attribute 'fit'
7
Advertisement
Answer
You need to evaluate the string into a Python object, ie do
JavaScript
1
5
1
best_model_final = 'LinearRegression(fit_intercept=True,normalize=True)'
2
best_model_name = re.sub("[([].*?[)]]", "", best_model_final )
3
best_model = eval(best_model_name)
4
best_model.fit(X.iloc[:-1], y.iloc[:-1]
5
See documentation of eval()
https://docs.python.org/3/library/functions.html#eval