基于机器学习线性回归模型案例(包含一元线性回归,多元线性回归和pca降维)的python代码需要有图
时间: 2023-09-16 11:12:51 浏览: 100
好的,以下是一个基于机器学习线性回归模型案例(包含一元线性回归,多元线性回归和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.xlabel('x')
plt.ylabel('y')
plt.title('Linear Regression')
plt.show()
```
多元线性回归:
```python
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
# 定义训练数据
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)
# 绘图
x1 = X[:, 0]
x2 = X[:, 1]
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x1, x2, y)
xx1, xx2 = np.meshgrid(x1, x2)
yy = model.intercept_ + model.coef_[0] * xx1 + model.coef_[1] * xx2
ax.plot_surface(xx1, xx2, yy, alpha=0.5)
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_zlabel('y')
plt.show()
```
PCA降维:
```python
import numpy as np
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
# 定义训练数据
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)
# 绘图
plt.scatter(X_reduced[:, 0], X_reduced[:, 1])
plt.xlabel('PC 1')
plt.ylabel('PC 2')
plt.title('PCA')
plt.show()
```
希望这些代码帮到了您!
阅读全文