栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

单变量线性回归

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

单变量线性回归

# 训练集(train_data.txt文件)和测试集test_data.txt文件)
# 请通过Python实现一元线性回归模型,并用此模型预测y,具体要求如下:
import numpy as np,matplotlib.pyplot as plt
#显示中文和负号
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
# 1.完成数据集的读取
def data_process():
    train_data=np.loadtxt(r'./train_data.txt',delimiter=' ')
    test_data=np.loadtxt(r'./test_data.txt')
    #切分特征值和标签
    train_x=train_data[:,:-1]
    train_y=train_data[:,-1:]
    test_x=test_data[:,:-1]
    test_y = test_data[:, -1:]
    #拼接截距项
    train_x=np.c_[np.ones((len(train_x),1)),train_x]
    train_y = np.c_[train_y]
    test_x = np.c_[np.ones((len(test_x), 1)),test_x]
    test_y = np.c_[test_y]
    return train_x,train_y,test_x,test_y
# 2.实现线性回归的代价函数
def lh(x,theta):
    h=x.dot(theta)
    return h
def loss_func(h,y):
    m=len(h)
    e=h-y
    J=1/(2*m)*np.sum(e**2)
    return J
# 3.实现梯度下降函数
def grad_decent(x,h,y):
    m=len(h)
    e=h-y
    dt=1/m*x.T.dot(e)
    return dt
# 5.通过梯度下降训练模型,
def train_model(x,y,alpha=0.005,iters=100):
    m,n=x.shape
    theta=np.zeros((n,1))
    loss_list=[]
    for i in range(iters):
        h=lh(x,theta)
        loss=loss_func(h,y)
        loss_list.append(loss)
        dt=grad_decent(x,h,y)
        theta=theta-alpha*dt
    return loss_list,theta
# 4.要求输出迭代过程中的代价函数值
train_x,train_y,test_x,test_y=data_process()
loss_list,theta=train_model(train_x,train_y)
print('迭代过程中的函数值',loss_list)
plt.plot(loss_list,c='m')
plt.show()
#用所得模型对测试集的数据进行预测
test_h=lh(test_x,theta)
# 6.画出散点图进行对比,横轴 test_x,纵轴:h/y
#画出真实的样本散点图
plt.scatter(test_x[:,1],test_y,c='g',marker='o')
#画出预测的样本散点图
plt.scatter(test_x[:,1],test_h,c='m',marker='*')
plt.xlabel('test_x')
plt.xlabel('test_y/test_h')
plt.show()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/929504.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号