python机器学习——线性回归

1.根据线性回归公式实现
在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt

#创建数据集
def create_data():
        w=0.9
        b=15
        x=np.random.uniform(0.0, 80.0, (200, 1)) #200行1列的0-80的浮点数
        y=w*x+b

        # 对数据进行标准正态分布处理
        #normal(loc=0.0, scale=1.0, size=None) loc表示正太分布的中心, scale表示正太分布的标准差
        x = np.random.normal(x, 2)
        y = np.random.normal(y, 2)
        return x, y


#创建模型
def build_model():
    model=np.array([0,0],dtype=float)
    return model

#定义训练函数
def train_math(model,xtr,ytr):
    print('train.....')
    x_mean=np.mean(xtr)
    y_mean=np.mean(ytr)

    num1=0.0 #分子
    num2=0.0 #分母

    for x_i,y_i in zip(xtr,ytr):
        num1+=(x_i-x_mean)*(y_i-y_mean)
        num2+=(x_i-x_mean)**2
    w = num1/num2
    b = y_mean - w*x_mean

    model[0]=w
    model[1]=b

    print("斜率:{},截距:{}".format(model[0],model[1]))

    pass

#定义测试函数
def test_math(model,xte,yte):
    err=0.0
    for x_i, y_i in zip(xte, yte):
        y_i1 = model[0]*x_i+model[1]
        err += (y_i-y_i1)**2
    res=np.sqrt(err/len(yte))
    print("模型的残差标准差为:{}".format(res))
    pass


#预测
def predict_math(model,xkno):
    ypre=[]
    for x in xkno:
        ypre.append(round(x*model[0]+model[1],2))
    return ypre

    pass


if __name__ == '__main__':
    #创建数据集
    x_data,y_data=create_data()
    plt.xlim(0,85)
    plt.ylim(10,90)
    plt.scatter(x_data,y_data)

    #分割数据集 :得到训练数据集和测试数据集
    x_train = x_data[:160]
    y_train = y_data[:160]

    x_test = x_data[160:]
    y_test = y_data[160:]

    #创建模型
    model=build_model()
    #训练数据
    train_math(model,x_train,y_train)

    plt.plot([0,85],[0*model[0]+model[1], 85*model[0]+model[1]])

    #调用测试函数
    test_math(model, x_test, y_test)

    #预测
    xkno = [1,2,3,4,5,6]
    yresult = predict_math(model,xkno)
    print("预测结果为:{}".format(yresult))

    plt.show()


运行结果:
在这里插入图片描述

在这里插入图片描述
2.使用keras实现

import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from keras import optimizers

#定义创建数据集的函数
def create_data():
        w=0.9
        b=15
        x=np.random.uniform(0.0, 80.0, (200, 1)) #200行1列的0-80的浮点数
        y=w*x+b

        # 对数据进行标准正态分布处理
        #normal(loc=0.0, scale=1.0, size=None) loc表示正太分布的中心, scale表示正太分布的标准差
        x = np.random.normal(x, 2)
        y = np.random.normal(y, 2)
        return x, y

#定义创建模型的函数
def build_model():
    model=Sequential() #创建模型
    model.add(Dense(input_dim=1, units=1)) #添加神经网络,input_dim:神经网络输入通道数, units:神经网络输出通道数
    # model.compile(loss='mse', optimizer='adam')
    adam = optimizers.Adam(lr=0.01) #设置优化器,将学习率设置为0.01,在机器学习的时候会根据学习率设置梯度
    model.compile(loss='mse', optimizer='adam')

    return model

#定义训练/学习函数
def train_math(model,x_train,y_train):
    print('Training......')
    for step in range(25000):
        const=model.train_on_batch(x_train,y_train)
        if step%100==0:
            # print(const)
            plt.cla()
            plt.xlim(0,80)
            plt.ylim(0,100)
            plt.plot(x_train,y_train,'co',label='train_data')
            w, b = model.layers[-1].get_weights()
            plt.plot(x_train,w*x_train+b,'y',label='train_result')
            plt.pause(0.0001)
    w,b=model.layers[-1].get_weights()
    print('Weigth= ',w,'biases= ',b)

#定义测试函数
def test_math(model,x_test,y_test):
    print('Testing......')
    const = model.evaluate(x_test,y_test,batch_size=40)
    print('test_const: ',const)

#定义预测函数
def predict_math(model,user_x):
    w, b = model.layers[-1].get_weights()
    return w * user_x + b
    pass

if __name__ == '__main__':
    #1.创建数据集
    x_data, y_data = create_data()
    plt.xlim(0, 85)
    plt.ylim(10, 90)
    plt.scatter(x_data, y_data)

    #2.分割数据集
    x_train = x_data[:160]
    y_train = y_data[:160]

    x_test = x_data[160:]
    y_test = y_data[160:]

    #3.创建模型
    model = build_model()

    #4.机器学习,得到模型
    train_math(model,x_train,y_train)

    #5.测试,评估模型好坏
    test_math(model,x_test,y_test)

    #6.预测
    user_x = 3.5
    predict_y=predict_math(model,user_x)
    print('predict_y:',predict_y)

    plt.show()
    pass

运行结果:
在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值