min_square

最小二乘法

测量一个棍子,10次数据如下:

12.3 , 11.8,11.2,11.6,12.5,12.1.11.6.12.0,12.4,11.2

怎样获取最后结果????

这样做有道理吗?用调和平均数行不行?用中位数行不行?用几何平均数行不行?

从概论的角度考虑,每次测量结果的概率值为 Pi, 那么,产生以上结果的概率为: P1*P2....P10;如果方差为高斯分布,要使以上结果概论最大(最大似然),通过推导,可知满足最小二乘法即可。这也是线性回归的本质。

最小二乘可以通过求导解决。不过不能直接求导,可以通过梯度下降法求解。

python3

# Split the data into training/testing sets
diabetes_X_train = diabetes_X[:-20]
diabetes_X_test = diabetes_X[-20:]

# Split the targets into training/testing sets
diabetes_y_train = diabetes_y[:-20]
diabetes_y_test = diabetes_y[-20:]

# Create linear regression object
regr = linear_model.LinearRegression()

# Train the model using the training sets
regr.fit(diabetes_X_train, diabetes_y_train)

# Make predictions using the testing set
diabetes_y_pred = regr.predict(diabetes_X_test)

# The coefficients
print('Coefficients: 
', regr.coef_)
# The mean squared error
print('Mean squared error: %.2f'
      % mean_squared_error(diabetes_y_test, diabetes_y_pred))
# The coefficient of determination: 1 is perfect prediction
print('Coefficient of determination: %.2f'
      % r2_score(diabetes_y_test, diabetes_y_pred))

# Plot outputs
plt.scatter(diabetes_X_test, diabetes_y_test,  color='black')
plt.plot(diabetes_X_test, diabetes_y_pred, color='blue', linewidth=3)

plt.xticks(())
plt.yticks(())

plt.show()

原文地址:https://www.cnblogs.com/heimazaifei/p/12945769.html