from random import random import math import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn.linear_model import LinearRegression X_size = [2104, 1600, 2400, 1416, 3000] X_room = [3, 3, 3, 2, 4] X_train = np.array(X_size+X_room).reshape((len(X_size), 2)) print(X_train) noise = np.random.randn(5, 1) noise = noise - np.mean(noise) Y_price = np.array([400, 330, 369, 232, 540]) Y_train = np.array(Y_price).reshape((len(Y_price), 1)) Y_train = Y_train+noise lr = LinearRegression() lr.fit(X_train, Y_train) Y_predict = lr.predict(X_train) a_arr = lr.coef_[0] b = lr.intercept_[0] f = "" for i in range(0, len(a_arr)): ai = a_arr[i] if ai >= 0: ai = "+%.4f" % ai else: ai = "%.4f" % ai f = f+"%s*x%s" % (ai, str(i+1)) f = "y=%s+%.4f" % (f[1:], b) print("拟合方程", f) def f(x1,x2): θ = random.randint(-1000,1000) θ1 = random.randint(-1000,1000) θ2 = random.randint(-1000,1000) return θ + θ1 * x1 + θ2 * x2 figure = plt.figure() ax = Axes3D(figure) # 设置图像为三维格式 X = X_size Y = X_room X, Y = np.meshgrid(X, Y) # 绘制网格 Z = 0.05 * X + 100 * Y - 70 Q = X_size W = X_room E = Y_price ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow') # 绘制3D图,后面的参数为调节图像的格式 plt.show()