I wrote a code for linear regression using linregress from scipy.stats and I wanted to compare it with another code using LinearRegression from sklearn.linear_model which I found on the internet.
With scipy the true and predicted values seem to be easy to extract (if I did it correctly), but in the sklearn code I received an error when I tried to calculate the MSE and RMSE.
What should I choose as predicted and true value to calculate MSE and RMSE for linear regression with sklearn?
scipy code:
from scipy.stats import linregress
import math
from sklearn.metrics import mean_squared_error
import pandas as pd
import statistics
import numpy as np
data_y = [76.6,118.6,200.8,362.3,648.9]
data_x = [10,20,40,80,160]
s_data_y = pd.Series(data_y)
s_data_x = pd.Series(data_x)
slope, intercept, r_value, p_value, std_err = linregress(s_data_x,s_data_y)
linregress(s_data_x,s_data_y)
true_val = s_data_y
predicted_val = intercept + slope * s_data_x
mse = mean_squared_error(true_val, predicted_val)
rmse = math.sqrt(mse)
plt.scatter(s_data_x,s_data_y)
plt.plot(s_data_x, predicted_val, 'r', label='fitted line')
plt.xlabel("X",fontweight='bold')
plt.ylabel("Y",fontweight='bold')
plt.grid(True)
plt.show()
print(dev_contact_resistance_params_all)
print(f'{slope=}\n{intercept=}\n{r_value=}\n{p_value=}\n{std_err=}\n')
print('Mean square error:',mse)
print('Root mean square error:',rmse)
sklearn code (from the internet):
from sklearn import linear_model
import matplotlib.pyplot as plt
import numpy as np
import random
#----------------------------------------------------------------------------------------#
# Step 1: training data
Y = [76.6,118.6,200.8,362.3,648.9]
X = [10,20,40,80,160]
X = np.asarray(X)
Y = np.asarray(Y)
X = X[:,np.newaxis]
Y = Y[:,np.newaxis]
plt.scatter(X,Y)
#----------------------------------------------------------------------------------------#
# Step 2: define and train a model
model = linear_model.LinearRegression()
model.fit(X, Y)
print(model.coef_, model.intercept_)
#----------------------------------------------------------------------------------------#
# Step 3: prediction
x_new_min = 0.0
x_new_max = 200.0
X_NEW = np.linspace(x_new_min, x_new_max, 100)
X_NEW = X_NEW[:,np.newaxis]
Y_NEW = model.predict(X_NEW)
plt.plot(X_NEW, Y_NEW, color='coral', linewidth=3)
plt.grid()
plt.xlim(x_new_min,x_new_max)
plt.ylim(0,1000)
plt.title("Simple Linear Regression using scikit-learn and python 3",fontsize=10)
plt.xlabel('x')
plt.ylabel('y')
plt.savefig("simple_linear_regression.png", bbox_inches='tight')
plt.show()
true_val = Y
predicted_val = Y_NEW
mse = mean_squared_error(true_val, predicted_val)
rmse = math.sqrt(mse)
print('Mean square error:',mse)
print('Root mean square error:',rmse)
Error from sklearn code:
Traceback (most recent call last):
File "C:\Users\test.py", line 21, in <module>
mse = mean_squared_error(r_value, p_value)
File "C:\lib\site-packages\sklearn\metrics\_regression.py", line 423, in mean_squared_error
y_type, y_true, y_pred, multioutput = _check_reg_targets(
File "C:\Users\lib\site-packages\sklearn\metrics\_regression.py", line 89, in _check_reg_targets
check_consistent_length(y_true, y_pred)
File "C:\Users\lib\site-packages\sklearn\utils\validation.py", line 328, in check_consistent_length
lengths = [_num_samples(X) for X in arrays if X is not None]
File "C:\Users\lib\site-packages\sklearn\utils\validation.py", line 328, in <listcomp>
lengths = [_num_samples(X) for X in arrays if X is not None]
File "C:\Users\lib\site-packages\sklearn\utils\validation.py", line 268, in _num_samples
raise TypeError(
ValueError: Found input variables with inconsistent numbers of samples: [5, 100]