logistic回归的多分类任务实现------鸢尾花数据(DATA MINING HOMEWORK)

鸢尾花问题:

http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data

对于以上给出的数据集,用模型进行训练,得到良好的分类器,分类模型。(要求用线性回归模型)

初看数据可以知道大概这么几个信息:首先数据是四维的,类别是三类,是一个多分类问题。因为题目要求用线性模型做,能想到的分类方式大概就是最朴素的线性回归分类,多项式回归分类,然后就是logistics多分类的处理,和softmax分类器。

  • 线性回归或者多项式回归的分类

因为此堂课老师的的要求是linear regression to train,而且上课也提到了在分类的时候,如何去对这三个类的标签进行一个赋值试探。所以怀疑初衷可能是用朴素的线性回归去做,但是另一方面,logistic分类和softmax其本质也是线性回归,只是嵌套了sigmoid函数和概率方法,因此应该也没有什么问题。但是还是先用线性回归去进行了一些实验。代码如下:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

def liner_Regression(data_x,data_y,learningRate,Loopnum):

    Weight=np.ones(shape=(1,data_x.shape[1]))  #The shape size of weight just follows the shape of data_x
    baise=np.array([[1]])

    for num in range(Loopnum):
        WXPlusB = np.dot(data_x, Weight.T) + baise

        loss=np.dot((data_y-WXPlusB).T,data_y-WXPlusB)/data_y.shape[0]
        w_gradient = -(2/data_x.shape[0])*np.dot((data_y-WXPlusB).T,data_x)
        baise_gradient = -2*np.dot((data_y-WXPlusB).T,np.ones(shape=[data_x.shape[0],1]))/data_x.shape[0]

        Weight=Weight-learningRate*w_gradient
        baise=baise-learningRate*baise_gradient
        if num%50==0:
            print('The loss is:',loss[0,0])
    return (Weight,baise)


def test_square_error_computing(test_x,test_y,Weight,baise):
    test_xMat = np.mat(test_x)  # 创建xMat矩阵
    test_yMat = np.mat(test_y).T  # 创建yMat矩阵(行向量)

    y_predict = np.dot(test_xMat,Weight.T)+baise
    square_error = np.dot((test_yMat-y_predict).T,test_yMat-y_predict)/test_yMat.shape[0]

    return square_error

def loadDataSet(fileName):
    xArr = [];
    yArr = []
    for line in open(fileName).readlines():
        curLine = line.strip().split()
        # curLine = line.strip().split('\t')  #中间有很多个空格、缩进或者tab,split的参数直接不用写就行
        xonerow = []  # 添加1.0作为第一个系数,则第一个系数的权重用来代表y=wx+b中的b变量
        for i in range(len(curLine) - 1):

            xonerow.append(float(curLine[i]))  # 最后一列为输出结果值y,前面的值为输入x值
        xArr.append(xonerow)
        yArr.append(float(curLine[-1]))  # 添加最后一列为结果值

    return xArr, yArr
if __name__== "__main__":
    # np.seterr(divide='ignore', invalid='ignore')
    # We type a order for input to choose which dataset we want to load.
    print("Type the order you want")
    order=input()
    if order == '1':
        data_x,data_y=loadDataSet('C:/Users/Carzolar/Desktop/DM_regression2.txt')
        xMat = np.mat(data_x)  # 创建xMat矩阵
        yMat = np
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值