Home > Software design >  How to take the item from string and use it as a value
How to take the item from string and use it as a value

Time:08-04

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?

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'

CodePudding user response:

You need to evaluate the string into a Python object, ie do

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

  • Related