Machine_learning(持续补充......)

1.线性回归

涉及到了批量梯度下降算法和正规方程求解

#-*- coding:utf-8 -*-
import numpy as np
import time 



#装饰器用来计算运行时间
def compute_for_time(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        call_back = func(*args, **kwargs)
        end_time = time.time()
        runntime = end_time - start_time
        return call_back, runntime
    return wrapper

#代价函数
def cost_function(theta, X, y):
    '''
    '''
    m = len(X)#
    return (X.dot(theta) - y).T.dot(X.dot(theta) - y) / (2 * m)
    

#正规方程
@compute_for_time
def regular_equation(X, y):
    '''
        X:特征矩阵
        y:标签向量
    返回:
        theta:相关系数向量
    '''
    theta = np.linalg.pinv(X.T.dot(X)).dot(X.T).dot(y)
    error = cost_function(theta, X, y)
    print('最终的代价值为:{}'.format(error))
    return theta
    
#梯度下降法
@compute_for_time
def compute_for_theta(alpha, maxloops, X, y):
    '''
       alpha:学习率
       maxloops:最大迭代次数
    '''
    m, n = X.shape
    
    #初始化theta
    theta = np.random.randn(n)
    #theta = np.zeros(n)
    
    minerror = 1e-3 #当梯度下降不明显时,即收敛阈值
    
    is_coveraged = False
    count = 0
    
    while not is_coveraged:
        
        sum_tmp = X.dot(theta) - y
        
        temp_theta = theta - alpha * (sum_tmp.dot(X)) / m#批量更新,也可以采用for循环逐个去更新theta
        
        if np.sum(abs(temp_theta - theta)) < minerror:
            is_coveraged = True
            print('参数已经收敛')
            
        count += 1
        theta = temp_theta
        error = cost_function(theta, X, y)
        
        if count % 10 == 0:
           print('第{}次迭代,当前损失值为:{}'.format(count, error))
        
        if count > maxloops:
           is_reveraged = True
           print('已达到最大迭代次数{}'.format(maxloops))
           
    return theta
    
    #注对于读取到的特征数据,一般还是需要做前期处理
    X = data_load[:, 0].reshape(-1, 1)#将列向量转换为行向量,如 [1, 2, 3, 4] ---> [[1], [2], [3], [4]]
    X = np.hstack((np.ones_like(X), X))#水平叠加
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • AI人工智能时代,机器学习,深度学习作为其核心,本文主要介绍机器学习的基础算法,以详细线介绍 线性回归算法 及其 ...
    erixhao阅读 13,957评论 0 36
  • 机器学习是做NLP和计算机视觉这类应用算法的基础,虽然现在深度学习模型大行其道,但是懂一些传统算法的原理和它们之间...
    在河之简阅读 20,557评论 4 65
  • “因为我好挂住你咯。” 我认识了一个女孩,她聪明,特别,笑起来又很好看。 可她有抑郁症,曾经吃过安眠药,我认识她时...
    是萱阅读 662评论 0 1
  • 楼下轰鸣声响起, 我从睡梦中苏醒, 匆匆忙洗漱。 透过窗户,放眼望去, 红衣女郎也已开工。 如今,阳光被雾霾笼罩,...
    叔丙仄阅读 185评论 0 4
  • 2017年5月3日,上午,10:50。我坐在书桌前,继续给你写信。 昨天的信我写得断断续续,并且写得非常辛苦。我知...
    Haijia_Seasee阅读 416评论 2 4