码迷,mamicode.com
首页 > 其他好文 > 详细

《机器学习》第三章——对率回归

时间:2017-06-23 22:08:44      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:机器   readline   rom   lis   import   readlines   数据   lin   lines   


import numpy as np
from numpy import random
def dataload(filename,l,r):#导入数据,感觉导入的有点困难
    f=open(filename)
    ar=f.readlines()
    num=len(ar)
    mat=np.zeros((r-l+1,num))
    ind=0
    for line in ar:
        line.split(‘\n‘)
        linelist=line.split(‘ ‘)
        mat[0:r-l,ind]=linelist[l:r]
        mat[r-l:r-l+1,ind]=1.0
        ind=ind+1
    return mat
x=dataload("1.txt",0,2)
y=dataload("1.txt",2,3)
beta=random.random(size=(3,1))#随机生成初始的beta矩阵
def p1(mat,p):
    ha=np.dot(mat.T,x[:,p])
    return np.exp(ha)/(1+np.exp(ha))
def one(mat):#求关于beta函数的一阶导
    tep=np.zeros((3,1))
    for i in range(17):
        temp=np.zeros((3,1))
        for j in range(3):
            temp[j,0]=x[j,i]
        tep=tep+temp*(y[0,i]-p1(mat,i))
    return -1.0*tep
def two(mat):#二阶导
    tep=np.zeros((3,3))
    for i in range(17):
        temp=np.zeros((3,1))
        for j in range(3):
            temp[j,0]=x[j,i]
        tep=tep+np.dot(temp,temp.T)*p1(mat,i)*(1-p1(mat,i))
    return tep
cnt=10000
for i in range(cnt):#使用牛顿法迭代cnt次得到beta矩阵
    tep=two(beta)
    if(np.linalg.det(tep)==0):
        break
    else :
        tep=np.linalg.inv(tep)
        beta=beta-np.dot(tep,one(beta))
ans=np.dot(beta.T,x)
def sigmoid(p):#sigmoid 函数
    return 1.0/(1+np.exp(-p))
for i in range(17):
    print(sigmoid(ans[0,i]))
这是用对率回归得到的数据集3.0的结果,第一次写python的代码,好多东西不会,希望有大神能指点指点我,感觉没人交流我都不知到我自学的对不对,毕竟学习能力不行

《机器学习》第三章——对率回归

标签:机器   readline   rom   lis   import   readlines   数据   lin   lines   

原文地址:http://www.cnblogs.com/zhangchengc919/p/7071540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!