基于机器学习线性回归模型案例(包含一元线性回归,多元线性回归和pca降维)的python代码
时间: 2023-06-22 19:44:39 浏览: 229
好的,下面是一个基于机器学习线性回归模型案例(包含一元线性回归,多元线性回归和pca降维)的Python代码:
一元线性回归:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义训练数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([3, 5, 7, 9, 11])
# 计算均值
x_mean = np.mean(x)
y_mean = np.mean(y)
# 计算斜率和截距
numerator = 0 # 分子
denominator = 0 # 分母
for i in range(len(x)):
numerator += (x[i] - x_mean) * (y[i] - y_mean)
denominator += (x[i] - x_mean) ** 2
k = numerator / denominator
b = y_mean - k * x_mean
# 计算预测值
y_pred = k * x + b
# 绘图
plt.scatter(x, y)
plt.plot(x, y_pred)
plt.show()
```
多元线性回归:
```python
import numpy as np
from sklearn.linear_model import LinearRegression
# 定义训练数据
X = np.array([[1, 2], [2, 4], [3, 6], [4, 8], [5, 10]])
y = np.array([3, 5, 7, 9, 11])
# 训练模型
model = LinearRegression()
model.fit(X, y)
# 预测
X_pred = np.array([[6, 12]])
y_pred = model.predict(X_pred)
print('预测值:', y_pred)
```
PCA降维:
```python
import numpy as np
from sklearn.decomposition import PCA
# 定义训练数据
X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
# PCA降维
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X)
print('降维后的数据:', X_reduced)
```
阅读全文