线性回归python实现
时间: 2023-09-02 14:05:50 浏览: 83
线性回归是一种常见的机器学习算法,用于预测一个数值型变量的值。下面是用Python实现线性回归的基本步骤:
1. 导入必要的库
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
```
2. 读取数据
```python
data = pd.read_csv("data.csv")
X = data.iloc[:, 0]
Y = data.iloc[:, 1]
```
3. 绘制散点图
```python
plt.scatter(X, Y)
plt.show()
```
4. 初始化参数
```python
m = 0
c = 0
L = 0.0001
epochs = 1000
```
5. 定义损失函数
```python
def compute_cost(m, c, X, Y):
n = len(X)
total_cost = sum([val ** 2 for val in (Y - (m * X + c))])
return total_cost / n
```
6. 定义梯度下降函数
```python
def gradient_descent(X, Y, m, c, L, epochs):
n = len(X)
for i in range(epochs):
Y_pred = m * X + c
D_m = (-2 / n) * sum(X * (Y - Y_pred))
D_c = (-2 / n) * sum(Y - Y_pred)
m = m - L * D_m
c = c - L * D_c
return m, c
```
7. 调用梯度下降函数并输出结果
```python
m, c = gradient_descent(X, Y, m, c, L, epochs)
print("Slope = ", m, "Intercept = ", c)
print("Cost = ", compute_cost(m, c, X, Y))
```
以上就是用Python实现线性回归的基本步骤。
阅读全文