import math
import numpy as np
from numpy import genfromtxt
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 导入数据
data = genfromtxt("Delivery.csv", delimiter=",")
x_data = data[1:, :2] # 选择前两列作为特征
y_data = data[1:, 2] # 选择第三列作为目标变量
# 检查特征数量
num_features = x_data.shape[1]
# 初始化参数
weights = np.zeros(num_features + 1) # +1 for w0
alpha = 0.005
epsilon = 1e-4
error = float('inf') # 初始化为无穷大
m = len(x_data)
while error > epsilon:
prediction = np.dot(x_data, weights[1:]) + weights[0] # 计算预测
error_i = prediction - y_data
grad_w = np.dot(x_data.T, error_i) / m # 计算梯度
weights[1:] -= alpha * grad_w
weights[0] -= alpha * np.mean(error_i) # 更新 w0
# 计算误差
error = np.linalg.norm(grad_w) # 计算误差
print(weights, error)
# 绘制三维图
ax = plt.figure().add_subplot(111, projection='3d')
ax.scatter(x_data[:, 0], x_data[:, 1], y_data, c='r', marker='o', s=100)
x0 = np.unique(x_data[:, 0])
x1 = np.unique(x_data[:, 1])
X0, X1 = np.meshgrid(x0, x1) # 使用唯一值生成网格
Z = weights[0] + weights[1] * X0 + weights[2] * X1
ax.plot_surface(X0, X1, Z, alpha=0.5)
ax.set_xlabel('Miles') # 根据需要修改标签
ax.set_ylabel('Number of Deliveries') # 根据需要修改标签
ax.set_zlabel('Time') # 根据需要修改标签
plt.show()
标签:import,weights,error,np,ax,路演,data
From: https://www.cnblogs.com/positive-boy/p/18492988