用Python写一个 线性拟合算法
时间: 2023-11-27 16:51:55 浏览: 27
下面是使用Python实现线性拟合算法的示例代码:
```python
import numpy as np
def linear_regression(X, y):
"""
线性拟合算法
:param X: 自变量数据,形状为 (m, n),其中 m 为样本数,n 为特征数
:param y: 因变量数据,形状为 (m, 1)
:return: 模型参数 b,形状为 (n+1, 1)
"""
# 增加一列全为 1 的常数列,用于计算截距
X = np.concatenate([np.ones((X.shape[0], 1)), X], axis=1)
# 计算模型参数
b = np.linalg.inv(X.T @ X) @ X.T @ y
return b
```
该函数接受两个参数 `X` 和 `y`,其中 `X` 是自变量数据,形状为 (m, n),其中 m 为样本数,n 为特征数;`y` 是因变量数据,形状为 (m, 1)。函数返回模型参数 b,形状为 (n+1, 1),其中第一个元素为截距。
在函数中,我们首先增加了一列全为 1 的常数列,用于计算截距。然后使用最小二乘法求解模型参数,公式为:$b = (X^TX)^{-1}X^Ty$,其中 $X^T$ 表示 $X$ 的转置,$^{-1}$ 表示矩阵的逆,$@$ 表示矩阵乘法。
示例使用了 numpy 库中的函数,因此需要先安装 numpy 库。
相关问题
python写一个拟合算法
这里提供一个用最小二乘法进行线性拟合的Python代码:
```python
import numpy as np
def linear_fit(x, y):
"""
线性拟合函数,返回拟合系数a, b和拟合误差err
"""
n = len(x) # 样本数量
x_mean = np.mean(x) # x的均值
y_mean = np.mean(y) # y的均值
# 计算拟合系数a, b
numerator = np.sum((x - x_mean) * (y - y_mean)) # 分子
denominator = np.sum((x - x_mean) ** 2) # 分母
a = numerator / denominator
b = y_mean - a * x_mean
# 计算拟合误差err
y_pred = a * x + b
err = np.sqrt(np.sum((y - y_pred) ** 2) / (n - 2))
return a, b, err
```
使用示例:
```python
import matplotlib.pyplot as plt
# 构造样本数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([2.2, 4.1, 6.0, 7.9, 9.8])
# 进行线性拟合
a, b, err = linear_fit(x, y)
# 绘制散点图和拟合直线
plt.scatter(x, y)
plt.plot(x, a * x + b, color='red')
# 显示拟合系数和拟合误差
print("拟合系数 a: ", a)
print("拟合系数 b: ", b)
print("拟合误差 err: ", err)
plt.show()
```
输出结果:
```
拟合系数 a: 1.96
拟合系数 b: 0.2
拟合误差 err: 0.295075899713466
```
绘制的图像如下:
![linear_fit.png](https://i.loli.net/2021/09/22/hGdRnw9zQcjkJbI.png)
用python写一个线性回归的预测算法
好的,以下是用Python实现一个简单的线性回归预测算法的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成随机数据
np.random.seed(0)
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)
# 绘制数据
plt.scatter(X, y)
plt.xlabel('X')
plt.ylabel('y')
plt.show()
# 使用梯度下降算法训练线性回归模型
lr = 0.1
n_iterations = 1000
theta = np.random.randn(2, 1)
for iteration in range(n_iterations):
gradients = 2 / len(X) * X.T.dot(X.dot(theta) - y)
theta = theta - lr * gradients
# 打印训练得到的参数
print('theta:', theta)
# 绘制拟合直线
X_new = np.array([[0], [2]])
X_new_b = np.c_[np.ones((2, 1)), X_new]
y_predict = X_new_b.dot(theta)
plt.plot(X_new, y_predict, 'r-', linewidth=2, label='Predictions')
plt.scatter(X, y)
plt.xlabel('X')
plt.ylabel('y')
plt.legend()
plt.show()
```
这段代码生成了一些随机的数据,并使用梯度下降算法训练了一个线性回归模型。最后绘制了原始数据和拟合直线的图形。你可以根据自己的需求修改代码,例如使用其他的数据集、调整训练参数等。