walliuswilliam / machine-learning

0 stars 0 forks source link

Optional simplifications in Linear Regressor #11

Closed snowthesprite closed 3 years ago

snowthesprite commented 3 years ago

So this is a weird thing that quite literally every one in the class has had. Every single person has this and its always the exact same code. Anyway, you have this thing right?

for coefficient_index in range(len(y_mat.elements)):
      if coefficient_index == 0:
        key = 'constant'
      else:
        key = self.independent_variables[coefficient_index-1] #constant takes up first spot, everything shifts over one index
      final_dict[key] = [coefficient[0] for coefficient in y_mat.elements][coefficient_index]

Well you can completely get rid of that if else statement if you move your final_dict down to the just above that for loop and then just.... initialize it with the constant already there. You could even get rid of the list comprehension if you just change a few things. Like take that coefficient and just make it an actual variable. I'm very tired right now, so this probably makes no sense, but what I'm thinking of is this :

    y_mat = mat_pseudoinv @ Matrix(y) #coefficients
    coefficients = y_mat.transpose().elements[0]
    final_dict = {'constant' :  coefficients[0]}

    for coefficient_index in range(len(self.independent_variables)):
      key = self.independent_variables[coefficient_index]
      final_dict[key] = coefficients[coefficient_index + 1]

That should work better. If ya want, you could even get rid of y_mat. We never use it, just replace add on whats there for coefficients and BOOM, should work.

walliuswilliam commented 3 years ago

thanks, it looks a lot cleaner now