回归分析--线性回归和逻辑(斯特)回归

一、线性回归

*一般用于连续值变量的预测-->机器学习里的有监督学习

gif.latex?f%5Cleft%20%28%20x%20%5Cright%20%29%3D%5CTheta%20%5E%7B%5CGamma%20%7Dx(其中x0为1,设置截距)

1.损失函数(衡量好不好)

gif.latex?J%5Cleft%20%28%20%5CTheta%20_%7B_0%7D%2C%5CTheta%20_%7B1%7D%2C%5CTheta_%7B2%7D%20%2C......%5CTheta_%7Bn%7D%5Cright%20%29%3D%5Cfrac%7B1%7D%7B2m%7D%5Csum%20%28h_%7B0%7D%28x%5E%7B%28i%29%7D%29-y%5E%7B%28i%29%7D%29%5E%7B2%7D

2.找最小化损失函数:

  • 梯度下降

假如现在有n个特征/变量gif.latex?x_%7Bj%7D%28j%3D1...n%29

repeat until convergence{
    gif.latex?%5CTheta%3A%3D%5CTheta_%7Bj%7D-%5Calpha%5Cfrac%7B%5Cdelta%7D%7B%5Cdelta%5CTheta_%7Bj%7D%7D%20J%28%5CTheta_%7B0%7D%2C%5CTheta_%7B1%7D%29
}

其中,学习率\alpha的确定:太小会收敛慢,太大会振荡,可能找不到最合适的学习率

  •   回归与欠/过拟合

(1)过拟合:拟合得过好导致失去了一般性,穿过了每一个点但预测效果差

(2)欠拟合:差距太大

(3)正则化(限制波动太大,解决过拟合问题):

增加惩罚因子gif.latex?%5Clambda( 惩罚因子的取值自己取,取多少,哪些特征要惩罚就靠后面的评价指标去判断,到接受范围内就行)

gif.latex?J%28%5CTheta%29%3D%5Cfrac%7B1%7D%7B2m%7D%5B%5Csum%20_%7Bi%3D1%7D%5E%7Bm%7D%28h_%7B%5CTheta%7D%28x%5E%7B%28i%29%7D%29-y%5E%7B%28i%29%7D%29%5E%7B2%7D+%5Clambda%20%5Csum_%7Bj%3D1%7D%5E%7Bn%7D%5CTheta_%7Bj%7D%5E%7B2%7D%5D

则修改梯度下降过程:

Repeat until convergence{

gif.latex?%5CTheta%20_%7B0%7D%3A%3D%5CTheta_%7B0%7D-a%5Cfrac%7B1%7D%7Bm%7D%5Csum_%7Bi%3D1%7D%5E%7Bm%7D%28h_%7B%5CTheta%7D%28x%5E%7B%28i%29%7D%29-y%5E%7B%28i%29%7D%29x_%7B0%7D%5E%7B%28i%29%7D

gif.latex?%5CTheta%20_%7Bj%7D%3A%3D%5CTheta_%7Bj%7D-a%5B%5Cfrac%7B1%7D%7Bm%7D%5Csum_%7Bi%3D1%7D%5E%7Bm%7D%28h_%7B%5CTheta%7D%28x%5E%7B%28i%29%7D%29-y%5E%7B%28i%29%7D%29x_%7B0%7D%5E%7B%28i%29%7D+%5Cfrac%7B%5Clambda%20%7D%7Bm%7D%5CTheta_%7Bj%7D%5D

}

import numpy
#梯度下降求解损失函数最小值
def gradientDesc(x,y,theta=np.zeros((2,1)),alpha=0.01,iterations=
1500):
    m=y.aize
    J=[]
    for n in range(iterations):
        a=theta[0][0]-alpha*(1/m)*sum((x.dot(theta).flatten()-y)*x[:,0])
        #dot表示矩阵乘法,flatten降维
        b=theta[1][0]-alpha*(1/m)*sum((x.dot(theta).flatten()-y)*x[:,1])
        theta[0][0],theta[1][0]=a,b
        print(theta[0][0])
        print(theta[1][0])
        J.append(cost(x,y,theta))
        print('Cost:'+str(J[-1]))
    return theta

#计算损失函数值并返回
def cost(x,y,theta=np.zeros((2,1))):
    m=len(x)
    J=1/(2*m)*sum((x.dot(theta).flatten()-y)**2)
    return J

或者直接利用python已有的库求线性回归模型

import numpy as np
X=data.iloc[:,0].to_numpy().reshape(-1,1)
Y=data.iloc[:,1].to_numpy().reshape(-1,1)

from sklearn.linear_model import LinearRegression
linear_regressor=LinearRegression()
linear_regressor=fit(X,Y)
Y_pred=linear_regressor.predit(X)

import matplotlib.pyplot as plt
plt.scatter(X,Y)
plt.plot(X,Y_pred,color='red')
plt.show()

预测:

linear_regressor.predict(np.array([[40]]))

二、逻辑回归

1.损失函数

J\left ( \Theta \right )=\left [ -\frac{1}{m}\sum _{i=1}^{m} y^{(i)}log(h_\theta(x^{(i)})+(1-y^{(i)})log1-h_\theta(x^{(i)}))\right ]+\frac{\lambda}{m}\sum_{i=1}^n\theta_j^{2}

2.梯度函数求最小值

\theta_j:=\theta_j-\alpha\frac{\partial }{\partial \theta_j}J(\theta)

3.二分类与多分类

 4.关于样本处理

 5.关于特征化处理

 

 

 逻辑回归python代码(文件路径用的相对路径,在c/用户/Emilia里)

%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import csv
import numpy as np
import math

def loadDataset():
    data=[]
    labels=[]
    with open('logic.txt','r') as f:
        reader = csv.reader(f,delimiter='\t')#csv文件,以逗号为分隔值,reader是一行一行的
        for row in reader:
            data.append([1.0, float(row[0]), float(row[1])])
            labels.append(int(row[2]))
            #print(data)
    return data,labels

def plotBestFit(W):
    # 把训练集数据用坐标的形式画出来
    dataMat,labelMat=loadDataset()
    dataArr = np.array(dataMat)
    n = np.shape(dataArr)[0] 
    xcord1 = []
    ycord1 = []
    xcord2 = []
    ycord2 = []
    for i in range(n):
        if int(labelMat[i])== 1:
            xcord1.append(dataArr[i,1]); ycord1.append(dataArr[i,2])
        else:
            xcord2.append(dataArr[i,1]); ycord2.append(dataArr[i,2])
    fig = plt.figure()
    ax = fig.add_subplot(111)#把画布分成1x1的格子,占第1个格子
    ax.scatter(xcord1, ycord1, s=30, c='red', marker='s')
    ax.scatter(xcord2, ycord2, s=30, c='green')

    # 把分类边界画出来
    x = np.arange(-3.0,3.0,0.1)
    y = (-W[0]-W[1]*x)/W[2]
    ax.plot(x,y)
    plt.show()

def plotloss(loss_list):
    x = np.arange(0,30,0.01)
    plt.plot(x,np.array(loss_list),label = 'linear')

    plt.xlabel('time')       # 梯度下降的次数
    plt.ylabel('loss')       # 损失值
    plt.title('loss trend')         # 损失值随着W不断更新,不断变化的趋势
    plt.legend()               # 图形图例
    plt.show()



def main():
    # 读取训练集(txt文件)中的数据,
    data, labels = loadDataset()
    # 将数据转换成矩阵的形式,便于后面进行计算
    # 构建特征矩阵X
    X = np.array(data)
    # 构建标签矩阵y
    y = np.array(labels).reshape(-1,1)
    # 随机生成一个w参数(权重)矩阵    .reshape((-1,1))的作用是,不知道有多少行,只想变成一列
    W = 0.001*np.random.randn(3,1).reshape((-1,1))   
    # m表示一共有多少组训练数据
    m = len(X)
    # 定义梯度下降的学习率 0.03
    learn_rate = 0.03

    loss_list = []
    # 实现梯度下降算法,不断更新W,获得最优解,使损失函数的损失值最小
    for i in range(3000):
        # 最重要的就是这里用numpy 矩阵计算,完成假设函数计算,损失函数计算,梯度下降计算
        # 计算假设函数 h(w)x
        g_x = np.dot(X,W)
        h_x = 1/(1+np.exp(-g_x))

        # 计算损失函数 Cost Function 的损失值loss
        loss = np.log(h_x)*y+(1-y)*np.log(1-h_x)
        loss = -np.sum(loss)/m
        loss_list.append(loss)

        # 梯度下降函数更新W权重
        dW = X.T.dot(h_x-y)/m
        W += -learn_rate*dW

    # 得到更新后的W,可视化
    print('W最优解:')
    print(W)
    print('最终得到的分类边界:')
    plotBestFit(W)
    print('损失值随着W不断更新,不断变化的趋势:')
    plotloss(loss_list)



    # 定义一个测试数据,计算他属于那一类别
    test_x = np.array([1,-1.395634,4.662541])
    test_y = 1/(1+np.exp(-np.dot(test_x,W)))
    print(test_y)

#     print(data_arr)
if __name__=='__main__':
    main()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值