无法将类型“ ndarray”转换为分子/分母

时间:2019-11-04 13:31:43

标签: python machine-learning linear-regression

这是我为实现linear_regression而制作的类

from statistics import mean

import numpy as np 

xs = np.array([1,2,3],dtype = float)

ys = np.array([2,5,6],dtype = float)

class Linear_Regression():        # Our own linear regression Model

  def __init__(self):
     print("The model is ready for use")


  def best_fit_slope_intercept(self,xs,ys):                    # for finding best fit slope(m) and intercept(c)
     self.m = ( ( mean(xs) * mean(ys) -mean(xs*ys)  ) / ( pow(mean(xs),2) - mean(pow(xs,2)) ) )   # For slope (m)
     self.c = mean(ys) - self.m * mean(xs)                                                             # For y-intercept(c)                        

  def fit(self,xs,ys):

     self.best_fit_slope_intercept(xs,ys) 
     self.regression_line = [((self.m)*x)+ (self.c) for x in xs]
     print("Model fitting completed")
     return self.regression_line                             # Returns the fitted values (ys_line) for each input (xs) 

  def squared_error(self,ys_orig, ys_line):                   # Calculates the mean squared error between y_orig and y_line
     return sum((ys_line-ys_orig)**2)                        # N.B.  ys_orig = ys , ys_line = self.regression_line


  def score(self,ys_orig,ys_line):
     y_mean_line = [mean(ys_orig) for y in ys_orig]
     sqr_err_reg = self.squared_error(ys_orig, ys_line)
     sqr_err_y_mean = self.squared_error(ys_orig, y_mean_line)
     return 1- (sqr_err_reg / sqr_err_y_mean )

  def predict(self,x_testing):
     s = self.m *(x_testing) + self.c
     return s 

regr = Linear_Regression()

regr.best_fit_slope_intercept(xs,ys)

执行此代码后,出现此错误:

TypeError: can't convert type 'ndarray' to numerator/denominator

尽管如果我在类之外进行这些功能,则代码运行良好。我真的无法解决问题!

2 个答案:

答案 0 :(得分:0)

我在您的代码上发现了一些错误,正确的类型是float:

xs = np.array([1,2,3],dtype = float)    

ys = np.array([2,5,6],dtype = float)     

您忘记将自己放在这里:

self.c = mean(ys) - self.m * mean(xs)       

答案 1 :(得分:0)

@deepraj1729,请在使用 statistics.mean() 之前展平您的数据。

例如:

变化:

self.c = mean(ys) - self.m * mean(xs)

到:

self.c = mean(ys.flatten()) - self.m * mean(xs.flatten())

希望这会有所帮助。