【发布时间】:2021-12-19 00:29:00
【问题描述】:
我使用scipy.stats 中的linregress 编写了一个线性回归代码,我想将它与我在互联网上找到的使用sklearn.linear_model 中的LinearRegression 的另一个代码进行比较。
使用scipy,真实值和预测值似乎很容易提取(如果我做得正确的话),但在sklearn 代码中,当我尝试计算 MSE 和 RMSE 时收到错误。
在使用sklearn 计算线性回归的 MSE 和 RMSE 时,我应该选择什么作为预测值和真实值?
scipy代码:
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代码(来自互联网):
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)
来自sklearn 代码的错误:
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]
【问题讨论】:
-
欢迎来到Stack Overflow.!要求有关问题方法的一般指导的问题通常过于宽泛,不适合本网站。人们有自己解决问题的方法,因此不可能有正确的答案。仔细阅读 Where to Start 和 Minimal Reproducible Example,然后编辑您的帖子。
标签: python scikit-learn scipy linear-regression