【机器学习】LR(线性回归)—— python3 实现方案

import numpy as np
import pandas as pd
from sklearn import preprocessing as pp


class LinearRegression():
    def calCost(self, X, y, theta, lamb=0):
        '''
        最小均方算法(LMS algorithm),使用L2正则化,数据集均为np.array格式
        :param X: 特征集m*n, m=样本数, n=特征数
        :param y: 目标集m*1
        :param theta: 参数集1*(n+1)
        :param lamb: 正则化参数,默认值为1
        :return: 最小均方误差
        '''
        X, y = map(np.array, (X, y))
        m = X.shape[0]
        X = np.insert(X, 0, 1, axis=1)  # 特征集增加一列x0,且令x0=1,以便于矩阵运算
        inner = np.power(X.dot(theta.T) - y, 2)  # 核心方程式
        reg = lamb / (2 * m) * np.sum(np.power(theta[:, 1:], 2))  # 正则项
        return np.sum(inner) / (2 * m) + reg

    def training(self, X, y, learning_rate=0.01, lamb=0, steps=1000):
        '''
        使用批量梯度下降算法
        :param X: 特征集m*n, m=样本数, n=特征数
        :param y: 目标集m*1
        :param learning_rate: 学习速率,默认值为1
        :param lamb: 正则化参数,默认值为1
        :param steps: 训练次数(梯度下降次数)
        :return: 训练好的参数theta
        '''
        m, n = X.shape
        X = np.insert(X, 0, 1, axis=1)  # 特征集增加一列x0,且令x0=1,以便于矩阵运算
        theta = np.zeros((1, n + 1))  # 初始化参数theta

        for _ in range(steps):  # 利用矩阵运算,一次性计算梯度
            error = X.dot(theta.T) - y  # 误差
            grad = (error.T).dot(X) / m + lamb / m * theta  # 计算梯度
            grad[0, 0] = np.sum(error) / m  # 上一步对所有theta都进行了正则化,这一步重新计算theta0的梯度,以取消正则化
            theta = theta - learning_rate * grad  # 更新theta
        return theta

    def predict(self, x, theta):
        '''
        输入单个样本和参数,输出预测结果
        :param x: 单个样本1*n
        :param theta: 参数集1*(n+1)
        :return: 预测值
        '''
        x = np.array(x)
        return theta[0, 0] + x.dot(theta[0, 1:].T)


def test():  # 测试
    data = pd.read_csv('data/ex1data2.txt')
    data = pp.scale(np.array(data))  # 归一化
    X = data[:, : -1]
    y = data[:, -1:]

    lr = LinearRegression()
    theta = lr.training(X, y)
    print(lr.calCost([[0.5, 0.6]], [[1]], theta))
    print(lr.predict([0.5, 0.6], theta))

猜你喜欢

转载自blog.csdn.net/zhenghaitian/article/details/83618748