2多变量线性回归

2多变量线性回归

题目:假设你现在打算卖房子,想知道房子可以卖多少钱,我们拥有房子面积和卧室数量以及房子对应的 价格
数据集:ex1data2.txt

  1. 读取文件
data = pd.read_csv("ex1data2.txt", sep=",", names=["area", "num", "price"])
print(data.head())

在这里插入图片描述

  1. 特征归一化在这里插入图片描述在这里插入图片描述
    本文采用第一种方法
# 特征归一化
def normalize_feature(data):
    return (data - data.mean()) / data.std()


data = normalize_feature(data)
print(data.head())

在这里插入图片描述

  1. 数据格式化处理(同单变量线性回归)
# 在area前插入一列
data.insert(0, "ones", 1)
# 对数据切片,提取前俩列特征值,所有行,可以打印查看格式
X = data.iloc[:, 1:-1]
y = data.iloc[:, -1]
# 目前结构为dataframe结构,不是数组结构,将其转换为数组形
X = X.values
print(X.shape) # 维度为(47,3)
y = y.values
print(y.shape) # 维度为(47,)
y = y.reshape(47, 1)
  1. 损失函数,梯度下降如单变量线性回归,以及不同学习率下损失函数
def cost_function(X, y, theta):
    inner = np.power(X @ theta - y, 2)
    return np.sum(inner) / (2 * len(X))


theta = np.zeros((3, 1))
cost_init = cost_function(X, y, theta)
print(cost_init)    # 初始代价为0.489


def gradient_descent(X, y, theta, alpha, iters, isprint=False):
    costs = []
    for i in range(iters):
        theta = theta - (X.T @ (X @ theta - y)) * alpha / len(X)
        cost = cost_function(X, y, theta)
        costs.append(cost)
        # 抽取几个cost查看,避免太多
        if i % 100 == 0:
            if isprint:
                print(costs)
    return theta, costs


# 不同alpha下的效果
alpha = [0.0003, 0.003, 0.03, 0.0001, 0.001, 0.01]
iters = 2000
fig, ax = plt.subplots()
for i in alpha:
    _, costs = gradient_descent(X, y, theta, i, iters)
    ax.plot(np.arange(iters), costs, label= i)
    ax.legend()
ax.set(xlabel= "iters", ylabel = "costs", title = "cost vs iters")
plt.show()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/jiatongzhui3931/article/details/107833145
今日推荐