How compute cost function for regression in scikit-learn

824 views Asked by At

I'm trying to do a linear regression but don't know compute cost function:

This my code :

lr = LinearRegression()

lr.fit(X_train,y_train)  #X_train les caractéristiques et Y_train les données cibles 


#coef a1 et intercept a0

print(lr.coef_)
print(lr.intercept_)


###cost function 

def cout_fonction(X_train,y_train):
    
    m=len(y_train)
    return 1/(2*m)*np.sum((lr.fit(X_train,y_train)-y_train)**2)


print(cout_fonction(X_train,y_train))

####

error:

  File "C:\Users\selai\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py", line 450, in masked_arith_op
    assert is_scalar(y), type(y)

AssertionError: <class 'sklearn.linear_model.base.LinearRegression'>
1

There are 1 answers

0
sentence On

IIUC, you would like to get the mean_squared_error. Just import it and compute it:

from sklearn.metrics import mean_squared_error
print("MSE on train {:.3f}".format(mean_squared_error(y_train, lr.predict(X_train))))