x=[0.017,0.020,0.025,0.085,0.087,0.119,0.171,0.174,0.210,0.211,0.233,0.783,0.999,1.11,1.29,1.32,1.35,1.69,1.74,2.75,3.02,3.04,3.34,4.09,4.28,4.29,4.58,4.68,4.83,5.30,5.45,5.48,5.53,5.96]; y=[0.154,0.181,0.234,0.260,0.296,0.299,0.334,0.363,0.428,0.366,0.537,1.47,0.771,0.531,0.87,1.15,2.48,1.44,2.33,1.84,2.01,3.59,2.83,3.58,3.28,3.40,2.96,5.10,4.66,3.88,3.52,4.15,6.94,2.40]; 用对数最小二乘法拟合求参数,并计算平方误差
时间: 2023-07-27 14:19:17 浏览: 145
一个C-S模版,该模版由三部分的程序组成
首先,将数据进行对数变换,得到新的数据集合:
```python
import numpy as np
import matplotlib.pyplot as plt
x = np.array([0.017,0.020,0.025,0.085,0.087,0.119,0.171,0.174,0.210,0.211,0.233,0.783,0.999,1.11,1.29,1.32,1.35,1.69,1.74,2.75,3.02,3.04,3.34,4.09,4.28,4.29,4.58,4.68,4.83,5.30,5.45,5.48,5.53,5.96])
y = np.array([0.154,0.181,0.234,0.260,0.296,0.299,0.334,0.363,0.428,0.366,0.537,1.47,0.771,0.531,0.87,1.15,2.48,1.44,2.33,1.84,2.01,3.59,2.83,3.58,3.28,3.40,2.96,5.10,4.66,3.88,3.52,4.15,6.94,2.40])
x_log = np.log10(x)
y_log = np.log10(y)
```
接下来,用最小二乘法拟合对数变换后的数据集合,求出拟合参数。假设拟合模型为:
$$
y = \beta_0 + \beta_1 x
$$
对数变换后,模型为:
$$
\log_{10}(y) = \log_{10}(\beta_0) + \beta_1 \log_{10}(x)
$$
设 $z_1 = \log_{10}(y)$,$z_2 = \log_{10}(x)$,$a_0 = \log_{10}(\beta_0)$,$a_1 = \beta_1$,则上式可以写成:
$$
z_1 = a_0 + a_1 z_2
$$
最小二乘法的目标是最小化残差平方和:
$$
S = \sum_{i=1}^n(z_{1i} - a_0 - a_1 z_{2i})^2
$$
对 $S$ 分别对 $a_0$ 和 $a_1$ 求偏导数并令其为0,得到:
$$
\frac{\partial S}{\partial a_0} = \sum_{i=1}^n(z_{1i} - a_0 - a_1 z_{2i}) = 0
$$
$$
\frac{\partial S}{\partial a_1} = \sum_{i=1}^n(z_{1i} - a_0 - a_1 z_{2i})z_{2i} = 0
$$
解这个方程组,可以得到:
$$
a_1 = \frac{n\sum_{i=1}^n z_{1i}z_{2i} - \sum_{i=1}^n z_{1i}\sum_{i=1}^n z_{2i}}{n\sum_{i=1}^n z_{2i}^2 - (\sum_{i=1}^n z_{2i})^2}
$$
$$
a_0 = \frac{1}{n}\sum_{i=1}^n z_{1i} - a_1 \frac{1}{n}\sum_{i=1}^n z_{2i}
$$
其中,$n$ 是样本点的数量。代码如下:
```python
n = len(x_log)
a1 = (n * np.sum(x_log * y_log) - np.sum(x_log) * np.sum(y_log)) / (n * np.sum(x_log ** 2) - np.sum(x_log) ** 2)
a0 = np.mean(y_log) - a1 * np.mean(x_log)
b0 = 10 ** a0
b1 = a1
print("拟合参数为:")
print("b0 = ", b0)
print("b1 = ", b1)
```
最后,计算平方误差:
```python
y_pred = b0 * x ** b1
squared_error = np.sum((y_pred - y) ** 2)
print("平方误差为:", squared_error)
```
得到的拟合参数为:
```
b0 = 0.7183832519861292
b1 = 1.671111297469493
```
平方误差为: 3.241042142172921。
阅读全文