线性回归算法代码实现
时间: 2024-03-31 09:28:26 浏览: 26
以下是使用Python实现线性回归算法的示例代码:
```python
import numpy as np
from sklearn.linear_model import LinearRegression
# 创建一个简单的数据集
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([2, 4, 5, 4, 5])
# 创建一个线性回归模型并拟合数据
model = LinearRegression().fit(X, y)
# 输出模型的截距和系数
print("Intercept:", model.intercept_)
print("Coefficient:", model.coef_)
# 使用模型进行预测
X_test = np.array([[6], [7], [8]])
y_pred = model.predict(X_test)
print("Predictions:", y_pred)
```
该代码使用NumPy库创建了一个简单的数据集,然后使用scikit-learn库中的LinearRegression类创建了一个线性回归模型,并使用fit()方法拟合数据。然后,使用模型的intercept_和coef_属性输出截距和系数。最后,使用predict()方法对新数据进行预测,并输出预测结果。
相关问题
python线性回归算法代码
以下是Python实现一元线性回归的代码,包括假设函数、损失函数和梯度下降法:
```python
import numpy as np
# 定义假设函数
def hypothesis(theta, X):
return np.dot(X, theta)
# 定义损失函数
def cost_function(theta, X, y):
m = len(y)
J = np.sum((hypothesis(theta, X) - y) ** 2) / (2 * m)
return J
# 定义梯度下降函数
def gradient_descent(theta, X, y, alpha, num_iters):
m = len(y)
J_history = np.zeros(num_iters)
for i in range(num_iters):
theta = theta - alpha / m * np.dot(X.T, (hypothesis(theta, X) - y))
J_history[i] = cost_function(theta, X, y)
return theta, J_history
```
其中,假设函数hypothesis(theta, X)用于计算预测值,损失函数cost_function(theta, X, y)用于计算预测值与真实值之间的误差,梯度下降函数gradient_descent(theta, X, y, alpha, num_iters)用于更新参数theta,使得损失函数最小化。
下面是一个使用上述代码进行一元线性回归的例子:
```python
import matplotlib.pyplot as plt
# 构造数据
X = np.array([1, 2, 3, 4, 5])
y = np.array([3, 5, 7, 9, 11])
# 在X前面添加一列1,用于计算截距
X = np.vstack([np.ones(len(X)), X]).T
# 初始化参数
theta = np.zeros(2)
# 设置学习率和迭代次数
alpha = 0.01
num_iters = 1000
# 进行梯度下降
theta, J_history = gradient_descent(theta, X, y, alpha, num_iters)
# 输出最终的参数和损失函数值
print('theta:', theta)
print('cost:', cost_function(theta, X, y))
# 绘制数据和拟合直线
plt.scatter(X[:, 1], y)
plt.plot(X[:, 1], hypothesis(theta, X))
plt.show()
```
python多项式线性回归算法代码
以下是Python中实现多项式回归的代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成数据
x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
y = np.array([0.1, 0.9, 2.2,2.8, 3.6, 5.0])
# 多项式回归
z = np.polyfit(x, y, 3) # 3表示多项式的次数
p = np.poly1d(z)
# 绘制图像
xp = np.linspace(-1, 6, 100)
plt.plot(x, y, '.', xp, p(xp), '-')
plt.show()
```
这段代码首先生成了一些数据,然后使用`np.polyfit()`函数进行多项式回归,其中第一个参数是自变量,第二个参数是因变量,第三个参数是多项式的次数。然后使用`np.poly1d()`函数将回归结果转换为一个多项式对象,最后使用`plt.plot()`函数绘制图像。