首先是较为简单的梯度上升算法的回归函数

具体原理啥的不介绍了

直接看代码:

刚开始是导入数据集的操作

总的来说很简单

机器学习实战-逻辑回归

输出的结果为:

机器学习实战-逻辑回归

下一个函数是sigmoid函数,这个函数很好写

机器学习实战-逻辑回归

最后一个函数就是gradAscent函数

这个函数我错了很多次

首先看几个函数

首先是mat函数,功能大概就是将一个输入转换成矩阵类型

只有转换成矩阵类型后,才可以使用相应的函数

python文档为:

>>> help(numpy.mat)
Help on function asmatrix in module numpy.matrixlib.defmatrix:

asmatrix(data, dtype=None)
    Interpret the input as a matrix.

    Unlike `matrix`, `asmatrix` does not make a copy if the input is already
    a matrix or an ndarray.  Equivalent to ``matrix(data, copy=False)``.

    Parameters
    ----------
    data : array_like
        Input data.
    dtype : data-type
       Data-type of the output matrix.

    Returns
    -------
    mat : matrix
        `data` interpreted as a matrix.

    Examples
    --------
    >>> x = np.array([[1, 2], [3, 4]])

    >>> m = np.asmatrix(x)

    >>> x[0,0] = 5

    >>> m
    matrix([[5, 2],
            [3, 4]])

再添加个示例

机器学习实战-逻辑回归

还有就是transpose函数:功能应该是将某个函数进行转置

python文档为:

>>> help(numpy.transpose)
Help on function transpose in module numpy.core.fromnumeric:

transpose(a, axes=None)
    Permute the dimensions of an array.

    Parameters
    ----------
    a : array_like
        Input array.
    axes : list of ints, optional
        By default, reverse the dimensions, otherwise permute the axes
        according to the values given.

    Returns
    -------
    p : ndarray
        `a` with its axes permuted.  A view is returned whenever
        possible.

    See Also
    --------
    moveaxis
    argsort

    Notes
    -----
    Use `transpose(a, argsort(axes))` to invert the transposition of tensors
    when using the `axes` keyword argument.

    Transposing a 1-D array returns an unchanged view of the original array.

    Examples
    --------
    >>> x = np.arange(4).reshape((2,2))
    >>> x
    array([[0, 1],
           [2, 3]])

    >>> np.transpose(x)
    array([[0, 2],
           [1, 3]])

    >>> x = np.ones((1, 2, 3))
    >>> np.transpose(x, (1, 0, 2)).shape
    (2, 1, 3)

再写个例子

机器学习实战-逻辑回归

非mat类型是不能调用transpose函数的

另外矩阵相乘的时候一定要注意到各个矩阵的形状是什么样子的

下面使用一下shape函数对各个形状的矩阵进行示例

机器学习实战-逻辑回归

总之,在走了一些弯路后,终于把结果给写出来了

贴一下代码

机器学习实战-逻辑回归

 

 

相关文章:

  • 2021-07-04
  • 2022-03-06
  • 2021-09-09
猜你喜欢
  • 2022-12-23
  • 2021-12-05
  • 2021-10-15
  • 2021-09-15
  • 2021-10-30
  • 2021-12-31
  • 2021-05-24
相关资源
相似解决方案