python简单线性回归定义函数的方法
时间: 2023-11-04 09:00:36 浏览: 46
在Python中定义一个简单线性回归函数可以使用以下步骤:
1. 导入所需的库,如numpy和matplotlib。
2. 定义一个函数,命名为“simple_linear_regression”,该函数接受两个参数,即x和y。
3. 在函数中计算x和y的均值,以及x和y的差异和乘积的均值。
4. 计算斜率和截距,使用公式y = mx + b,其中m是斜率,b是截距。
5. 使用matplotlib库绘制输入数据和回归线。
下面是一个简单线性回归函数的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
def simple_linear_regression(x, y):
x_mean = np.mean(x)
y_mean = np.mean(y)
xy_mean = np.mean(x * y)
x_sq_mean = np.mean(x ** 2)
m = (xy_mean - x_mean * y_mean) / (x_sq_mean - x_mean ** 2)
b = y_mean - m * x_mean
plt.scatter(x, y)
plt.plot(x, m * x + b, color='red')
plt.show()
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 5, 4, 5])
simple_linear_regression(x, y)
```
在上面的代码中,我们导入了numpy和matplotlib库,并定义了一个名为“simple_linear_regression”的函数,该函数接受两个参数x和y。在函数内部,我们计算了x和y的均值、x和y的差异和乘积的均值、斜率和截距,并使用matplotlib库绘制了输入数据和回归线。最后,我们使用numpy库中的array函数来创建x和y的NumPy数组,并调用simple_linear_regression函数来绘制回归线。