机器学习(新手入门)-线性回归 #房价预测

题目:给定数据集dataSet,每一行代表一组数据记录,每组数据记录中,第一个值为房屋面积(单位:平方英尺),第二个值为房屋中的房间数,第三个值为房价(单位:千美元),试用梯度下降法,构造损失函数,在函数gradientDescent中实现房价price关于房屋面积area和房间数rooms的线性回归,返回值为线性方程𝑝𝑟𝑖𝑐𝑒=𝜃0+𝜃1∗𝑎𝑟𝑒𝑎+𝜃2∗𝑟𝑜𝑜𝑚𝑠中系数𝜃𝑖(𝑖=0,1,2)的列表。

python 复制代码
%matplotlib inline

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from numpy import genfromtxt
dataPath = r"./Input/data1.csv"
dataSet = pd.read_csv(dataPath,header=None)
print(dataSet)
price = []
rooms = []
area = []
for data in range(0,len(dataSet)):
    area.append(dataSet[0][data])
    rooms.append(dataSet[1][data])
    price.append(dataSet[2][data])
print(area)

执行结果:

python 复制代码
def gradientDescent(rooms, price, area):
    epochs = 500
    alpha = 0.00000001
    theta_gradient = [0,0,0]
    const = [1,1,1,1,1]
    theta = [1,2,1]
    loss = []
    
    for i in range(epochs):
        
        theta0 = np.dot(theta[0],const)
        theta1 = np.dot(theta[1],area)
        theat2 = np.dot(theta[2],rooms) 
        predict_tmp = np.add(theta0,theta1)
        predict = np.add(predict_tmp,theat2) 
        loss_ = predict - price
        theta_gradient[0] = (theta_gradient[0] + np.dot(const,loss_.transpose()))/5
        theta_gradient[1] = (theta_gradient[1] + np.dot(area,loss_.transpose()))/5
        theta_gradient[2] = (theta_gradient[2] + np.dot(rooms,loss_.transpose()))/5
        loss_t = np.sum(np.divide(np.square(loss_),2))/5
        if i%50==0:
            print("loss_t:",loss_t)
        loss.append(loss_t)
        theta[0] = theta[0] - alpha * theta_gradient[0]
        theta[1] = theta[1] - alpha * theta_gradient[1]
        theta[2] = theta[2] - alpha * theta_gradient[2]
    plt.plot(loss,c='b')
    plt.show()
    return theta
python 复制代码
def demo_GD():
    
    theta_list = gradientDescent(rooms, price, area)
demo_GD()

j结果展示:

相关推荐
Henry-SAP5 小时前
SAP引领ERP智能化转型
人工智能·云原生·sap·erp
峥嵘life5 小时前
Android16 311Y3 EAP-TLS 网络连接失败分析与修复总结
android·开发语言·人工智能·php
特立独行的猫a6 小时前
一切皆插件:DeepSeek Harness 的架构哲学,以及与主流 Agent 的对比
人工智能·架构·agent·deepseek·harness
电商API_180079052476 小时前
京东商品详情API技术文章
大数据·运维·人工智能·网络爬虫
fīɡЙtīиɡ ℡6 小时前
AI Agent 记忆系统
人工智能
企鹅的企7 小时前
2027北京AI数字健康与智慧医疗展官方:超两成展品亚洲首秀
人工智能·科技·机器人
lvts_cs7 小时前
淄博高新区绿天使数智创新港:高标准产研厂房全维度详解
大数据·人工智能
百胜软件@百胜软件7 小时前
从“人找货”到“货找人”:「胜券商品」如何用AI重构配补调
人工智能·重构
风流 少年7 小时前
Spring AI 2.0:Advisor
android·人工智能·spring