Henri
Henri

Reputation: 1235

Store result inside a Python class?

If you run the fit attribute on an instance of a sklearn estimator, for example LinearRegression(), is the result stored somewhere inside the instance of the class? I don't create a new object but I fit the model and can do new things like predict etc.

lr = LinearRegression()
lr.fit(X_train, y_train)

Could I achieve something similar with a class of my own. How could I store the result from run_model() inside the instance of the class?

data = pd.DataFrame({'n':[1,1,4,1],
                    'target':[36,8,0,41],
                    'string':['z', 's', 'd', 'h']})

class test:
    
    def __init__(self,
                 dataframe,
                 target,
                 features):
        
        self.dataframe=dataframe
        self.target = target
        self.features = features
    
    def x_y(self):
        X=self.dataframe[self.features]
        y=self.dataframe[[self.target]]
        
        return X, y 
    
    def run_model(self):
        X, y = self.x_y()
        list_result = X.n*4
        return list_result
        

a = test(dataframe=data, target='target', features=['n','string'])     
a.run_model()

Output:
0     4
1     4
2    16
3     4
Name: n, dtype: int64

Upvotes: 1

Views: 108

Answers (1)

Lucas M. Uriarte
Lucas M. Uriarte

Reputation: 3101

here is a basic example


class test:
    
    def __init__(self,
                 dataframe,
                 target,
                 features):
        
        self.dataframe=dataframe
        self.target = target
        self.features = features
        self.run_model_results = None # is not obligatory but I advice to declare your attribute in the constructor 
    
    def x_y(self):
        X=self.dataframe[self.features]
        y=self.dataframe[[self.target]]
        
        return X, y 
    
    def run_model(self):
        X, y = self.x_y()
        list_result = X.n*4
        self.run_model_results = list_result  # store values in your attribute
        return list_result

    def square_model_result(self):
        
        if self.run_model_results is not None: # this if only if you declare your attribute in the init
            return  self.run_model_results**2  # reuse your results here or anywere
        else:
            print("run model first")

a = test(dataframe=data, target='target', features=['n','string'])     
a.run_model()  
a.square_model_result()

The last method have use the values you have store to produce its result

0     16
1     16
2    256
3     16

Upvotes: 2

Related Questions