**使用Python实现逻辑回归的算法**-------文章中有源码

实验目的
使用Python实现逻辑回归的算法
实验原理
(1)收集数据:采用任意方法收集数据。
(2)准备数据:由于需要进行距离计算,因此要求数据类型为数值型。另外,结构化数据格式则最佳。
(3)分析数据:采用任意方法对数据进行分析。
(4)训练算法:大部分时间将用于训练,训练的目的是为了找到最佳的分类回归系数。
(5)测试算法:一旦训练步骤完成,分类将会很快。
(6)使用算法:首先,我们需要输入一些数据,并将其转换成对应的结构化数值;接着,基于训练好的回归系数就可以对这些数值进行简单的回归计算,判定它们属于哪个类别;在这之后,我们就可以在输出的类别上做一些其他分析工作。

实验内容(表格区域可拉长)
(1)有如下数据集(2个特征,10个样本):logisticData.txt,试采用逻辑回归,计算各特征的权重和偏移。
(2)手写数字识别
压缩包中包含2个文件夹,分别名为trainingDigits(训练数据)和testDigits(测试数据),文件夹中存放如果txt文件,

代码:

import numpy as np
import os


def getData(path):
    data_x = []
    data_y = []
    for file in os.listdir(path): #遍历返回指定文件夹包含的文件或者文件夹名字列表
        #注意
        test = np.zeros(10, int)
        test[int(file[0])] = 1
        data_y.append(test)

        # temp=[1]
        # data_y.append(int(file[0]))
        with open(path + "/" + file) as lines:   #  读取所有文件
            temp = []
            for line in lines:  #  遍历
                x = line.strip()   #清洗数据
                for i in x:
                    temp.append(int(i))
            data_x.append(temp)

    return np.array(data_x), np.array(data_y)

def soft(z):
    h = []
    for i in z:
        i = i - np.max(i)
        one = []
        for j in i:
            one.append(np.exp(j) / np.sum(np.exp(i)))
        h.append(one)
    return np.array(h)


def logistic(x, y, a=0.0005, times=1000):
    m, n = x.shape   #  m=946  n=1024
    k,l=y.shape      #  l=10
    w = np.array(np.random.rand(n, l))
    #print(w)
    for i in range(times):
        z = np.dot(x, w)
        H = soft(z)
        gradient = np.dot(x.T, (H - y))
        w = w - a * gradient
    return w


def test_w(x, y, w):
    h = soft(np.dot(x, w))
    j=len(h)
    Q=len(y)
    sum = 0
    for i in range(j):
        index= np.argmax(h[i])   #返回最大元素索引
        h[i] = np.zeros(len(h[i]))  #自己创建指定大小的数组
        h[i][index] = 1
        if (h[i] == y[i]).all(): #判断参数是否都为true
            sum += 1
    return sum / Q


if __name__ == "__main__":
    x, y = getData("testDigits")
    print(y)
    x1, y1 = getData("trainingDigits")
    w = logistic(x, y)
    # print(w)
    print(test_w(x1, y1, w))

截图:

在这里插入图片描述

import numpy as np
def getData(path):
    data=[]
    with open(path) as lines: #读取所有文件
        for line in lines:   #遍历
            x=line.strip().split(" ")#清洗数据
            #列表,第一个元素为1
            temp=[1]
            for i in x:
                temp.append(int(i))
            data.append(temp)
    return data


def sigmoid(z):
    return 1/(1+np.exp(-z))

def logistic(x,y,a=0.01,times=20000):
    m,n=x.shape  #x.shape==shape[0]
    # print(m)  10
    # print(n)  3
    w=np.array(np.random.rand(n,1))
    for i in range(times):
        z=np.dot(x,w)
        H=sigmoid(z)
        gradient= np.dot(x.T,(H-y))
        w=w-a*gradient
    return w


if __name__=="__main__":
    data=getData("logisticData.txt")
    x=[]
    y=[]
    for i in data:
        x.append(i[:-1])
        y.append(i[-1])
    x=np.array(x)
    m=np.array(y).shape[0]  #读取一维的长度(shape(x,y),x行数,y列数)
    #print(m)
    y=np.array(y).reshape(m,1)  #转换成m行一列
    w=logistic(x,y)
    print(sigmoid(np.dot(x,w)))

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不良使

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值