使用python处理逻辑回归遇到的问题

问题描述 投票:0回答:1

大家。 现在我正在尝试解决 Andrew Ng 的 ML 课程中的任务。 我正在使用 python 进行逻辑回归,但结果对我来说相当混乱。而且使用 scipy.opt 函数时出现问题

我被要求使用逻辑回归进行分类。计算成本和梯度的函数是:

因此,我不想使用 scipy 中提供的 opt 函数,而是坚持使用梯度下降来更新参数,如上一篇教程中所教。

但是当我使用不同的学习率(alpha)时,成本会发生不同的变化。

这是当 alpha=0.0001,iteration=400000 时的结果

cost result

并且...这是当 alpha=0.01,iteration=200000 时的结果

cost result

虽然最终的结果是可以接受的,但似乎这种混乱的结果对我来说很难解释。 对于这种情况有什么解释吗?

使用 scipy.opt 时出现问题 看起来这种混乱的结果对我来说很难解释,尽管最终的结果是可以接受的。 对于这种情况有什么解释吗?

使用 scipy.opt 函数时出现问题

m,n=data.shape 
X=data[:,0:n-1]
y=data[:,-1:]
theta=np.array([[0] for i in range(n)],dtype=np.float64)
print(X.shape,y.shape,theta.shape)

# OUT:(100, 2) (100, 1) (3, 1)

X=np.concatenate((np.array([[1] for i in range(m)]),X),axis=1)

def sigmoid(z):
    return 1/(1+np.exp(-z))
def h(X,theta):
    return sigmoid(X@theta)
def calculate_cost(X,y,theta):
    first=-y.T @ np.log(h(X,theta)+1e-5)  
    second=(1-y)[email protected](1-h(X,theta)+1e-5)   
    return 1/m*(first-second)[0][0]
def gradient(X,y,theta):
    return  1/m*(X.T@(h(X,theta)-y)).T

result = opt.fmin_tnc(func=calculate_cost, x0=theta, fprime=gradient, args=(X, y))

整个过程中出现 ValueError:

Cell In[5], line 4, in h(X, theta)
      3 def h(X,theta):
----> 4     return sigmoid(X@theta)

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 100 is different from 3)

如果这个问题能够得到解决,我会很高兴。 谢谢!

python machine-learning logistic-regression
1个回答
0
投票

似乎

fmin_tnc
x0
参数作为它尝试优化的函数的第一个参数。要解决此问题,只需使用
theta
作为
calculate_cost
gradient
的第一个参数即可。
我还修复了一些导致代码崩溃的错误匹配(
return 1/m*(first-second)[0][0]
->
return 1/m*(first-second)[0]
1/m*(X.T@(h(X,theta)-y)).T, axis=0
->
np.mean(1/m*(X.T@(h(X,theta)-y)).T, axis=0)
),但是你必须看看它是否有用,例如取梯度的平均值。

import numpy as np
from scipy import optimize as opt

data = np.random.rand(100, 3)

m,n=data.shape
X=data[:,0:n-1]
y=data[:,-1:]
theta=np.array([[0] for i in range(n)],dtype=np.float64)
print(X.shape,y.shape,theta.shape)

# OUT:(100, 2) (100, 1) (3, 1)

X=np.concatenate((np.array([[1] for i in range(m)]),X),axis=1)

def sigmoid(z):
    return 1/(1+np.exp(-z))
def h(X,theta):
    return sigmoid(X@theta)
def calculate_cost(theta, X,y):
    first=-y.T @ np.log(h(X,theta)+1e-5)  
    second=(1-y)[email protected](1-h(X,theta)+1e-5)   
    return 1/m*(first-second)[0]
def gradient(theta, X,y):
    return np.mean(1/m*(X.T@(h(X,theta)-y)).T, axis=0)

result = opt.fmin_tnc(func=calculate_cost, x0=theta, fprime=gradient, args=(X, y))
© www.soinside.com 2019 - 2024. All rights reserved.