import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.pylab as mpl
from mpl_toolkits.mplot3d import Axes3D
# 设置可以显示中文符的画图
mpl.rcParams['font.sans-serif'] = [u'simHei']
mpl.rcParams['axes.unicode_minus'] = False
flag = True
# 数据准备,准备X,Y
X1 = np.array([ [10, 1], [15, 1], [20, 1], [30, 1], [50, 2], [60, 1], [60, 2], [70, 2]]).reshape((-1, 2))
Y = np.array([0.8, 1.0, 1.8, 2.0, 3.2, 3.0, 3.1, 3.5]).reshape((-1, 1))
if flag:
# 添加一列截距项
X = np.column_stack(X1, np.ones(shape=(X1.shape[0], 1)))
else:
X = X1
# 将X, Y的 np.array 形式转换成矩阵形式
X = np.mat(X)
Y = np.mat(Y)
# 训练模型
theta = (X.T * X).I * X.T * Y
# 预测模型
y_pre = X * theta
# 基于训练好的模型对一个未知样本做预测
if flag:
x = np.mat(np.array([[55.0, 2.0, 1.0]]))
else:
x = np.mat(np.array([[55.0, 2.0]]))
predict_y = x * theta
print("当房屋面积为55平方并且房间数为2时,预测价格为:{}".format(predict_y))
# 评估模型 #############
# 画图
x1 = X[:, 0] # N行
x2 = X[:, 1] # N行1列
# 准备3D画布
fig = plt.figure(facecolor='w')
ax = Axes3D(fig)
# 画点图
ax.scatter(x1, x2, Y, s=40, c='r', dspthshade=False)
x1 = np.arange(0, 100)
x2 = np.arange(0, 4)
x1, x2 = np.meshgrid(x1, x2) # 将x1,x2坐标轴混在一个空间平面上
def predict(x1, x2, theta, bas=False):
if base:
y_ = x1 * theta[0] + x2 * theta[1] + theta[2]
else:
y_ = x1 * theta[0] + x2 * theta[1]
return y_
z = np.array(list(map(lambda t: predict(t[0], t[1], theta, base=flag), zip(x1.flatten(), x2.flatten()))))
z.shape = x1.shape
ax.plot_surface(x1, x2, z, rstride=1, cstride=1, cmap=plt.cm.jet) # cmap=plt.cm.jet 画超平面
ax.set_title(u'房屋租赁价格预测')
plt.show()