机器学习实验------线性回归方法

第1关:数据载入与分析

任务描述

本关任务:编写一个能够载入线性回归相关数据的小程序。

编程要求

该实战内容中数据为一元数据,利用 pandas 读入数据文件,并为相应的数据附上名字标签,分别为Population 和 Profit。

python 复制代码
#encoding=utf8
import os
import pandas as pd

if __name__ == "__main__":
    path = os.getcwd() + '/ex1data1.txt'
    #利用pandas读入数据data,并将数据属性分别命名为'Population'和'Profit'
    #********* begin *********#
    data = pd.read_csv(path, header=None ,names=['Population','Profit'])
    #********* end *********#
    print(data.shape)

第2关:计算损失函数

编程要求

根据以上公式,编写计算损失函数computeCost(X, y, theta),最后返回cost。

  • X:一元数据矩阵,即Population数据;
  • y:目标数据,即Profit数据;
  • theta:模型参数;
  • cost:损失函数值。
python 复制代码
#encoding=utf8
import numpy as np

def computeCost(X, y, theta):
    #根据公式编写损失函数计算函数
    #********* begin *********#
    inner=np.power(((X*theta.T)-y),2)
    cost=np.sum(inner)/(2*len(X))
    cost=round(cost,10)
    #********* end *********#
    return cost

第3关:进行梯度下降得到线性模型

编程要求

根据以上公式,编写计算损失函数gradientDescent(X, y, theta, alpha, iters),最后返回theta, cost。

  • x:一元数据矩阵,即Population数据;
  • y:目标数据,即Profit数据;
  • theta:模型参数;
  • m:数据规模;
  • α: 学习率。
python 复制代码
#encoding=utf8
import numpy as np

def computeCost(X, y, theta):
    inner = np.power(((X * theta.T) - y), 2)
    return np.sum(inner) / (2 * len(X))

def gradientDescent(X, y, theta, alpha, iters):
    temp = np.matrix(np.zeros(theta.shape))
    parameters = int(theta.ravel().shape[1])
    cost = np.zeros(iters)
    
    for i in range(iters):
        error = (X * theta.T) - y
        
        for j in range(parameters):
            #********* begin *********#
            term=np.multiply(error,X[:,j])
            temp[0,j]=theta[0,j]-((alpha/len(X))*np.sum(term))
            #********* end *********#
        theta = temp
        cost[i] = computeCost(X, y, theta)
        
    return theta, cost

第4关:建立完整线性回归模型

编程要求

在前三个关卡的基础上,从宏观的视角构建一个完整的线性回归模型。主要编写数据载入,损失函数,梯度下降函数三部分。

python 复制代码
#encoding=utf8

import os
import numpy as np
import pandas as pd

#载入数据并进行数据处理
path = os.getcwd() + '/ex1data1.txt'
#********* begin *********#
data=pd.read_csv(path,header=None,names=['Population','Profit'])


#********* end *********#
data.insert(0, 'Ones', 1)
cols = data.shape[1]
X = data.iloc[:,0:cols-1]
y = data.iloc[:,cols-1:cols]

#初始化相关参数
X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0]))
alpha = 0.01
iters = 1000

#定义损失函数
def computeCost(X, y, theta):
    #********* begin *********#
    inner=np.power(((X*theta.T)-y),2)
    cost=np.sum(inner)/(2*len(X))
    cost=round(cost,10)

    #********* end *********#
    return cost

#定义梯度下降函数
def gradientDescent(X, y, theta, alpha, iters):
    temp = np.matrix(np.zeros(theta.shape))
    parameters = int(theta.ravel().shape[1])
    cost = np.zeros(iters)
    
    for i in range(iters):
        error = (X * theta.T) - y
        
        for j in range(parameters):
            #********* begin *********#
            term=np.multiply(error,X[:,j])
            temp[0,j]=theta[0,j]-((alpha/len(X))*np.sum(term))

            #********* end *********#            
        theta = temp
        cost[i] = computeCost(X, y, theta)        
    return theta, cost

#根据梯度下架算法得到最终线性模型参数
g, cost = gradientDescent(X, y, theta, alpha, iters)

print("模型参数为:", g)
相关推荐
AI大模型知识分享3 分钟前
Prompt最佳实践|指定输出的长度
人工智能·gpt·机器学习·语言模型·chatgpt·prompt·gpt-3
十有久诚15 分钟前
TaskRes: Task Residual for Tuning Vision-Language Models
人工智能·深度学习·提示学习·视觉语言模型
全云在线allcloudonline29 分钟前
微软 Azure AI 服务免费试用及申请:语音识别、文本转语音、基于视觉、语言处理、文档分析等10大场景
人工智能·microsoft·azure
Filotimo_29 分钟前
【自然语言处理】实验三:新冠病毒的FAQ问答系统
人工智能·经验分享·笔记·python·学习·自然语言处理·pycharm
标贝科技30 分钟前
ChatGPT对话训练数据采集渠道有哪些
数据库·人工智能·机器学习·chatgpt
zhangfeng113331 分钟前
rnn input_size hidden_size 分别是什么意思 ,人工智能 Python
人工智能·rnn·自然语言处理
PD我是你的真爱粉31 分钟前
GPTo1论文详解
人工智能·深度学习
说私域36 分钟前
构建有温度的用户关系:开源 AI 智能名片、链动 2+1 模式与 S2B2C 商城小程序的作用
人工智能·小程序
newxtc1 小时前
【天怡AI-注册安全分析报告-无验证方式导致安全隐患】
人工智能·安全
WF199807191 小时前
秋招自我介绍
人工智能