【问题标题】:My code giving differnt result where as the same code in my Machine learning assignment expects a different result?当我的机器学习作业中的相同代码期望不同的结果时,我的代码给出不同的结果?
【发布时间】:2021-09-01 16:50:00
【问题描述】:

我的代码

def lrCostFunction(theta, X, y, lambda_):
    m = y.size

    if y.dtype == bool:
        y = y.astype(int)

    tempt = theta
    tempt[0] = 0

    J = 0
    grad = np.zeros(theta.shape)
    hx = X.dot(theta.T)
    h = sigmoid(hx)

    J = (1/m) * np.sum(-y.dot(np.log(h)) - (1-y).dot(np.log(1-h)))
    J = J + (lambda_/(2*m)) * np.sum(np.square(tempt))

    grad = ((1/m) * (h - y) .dot(X)) + (lambda_/m) * tempt

    return J, grad

# rand_indices = np.random.choice(m, 100, replace=False)
# sel = X[rand_indices, :]\


theta_t = np.array([-2, -1, 1, 2], dtype=float)
X_t = np.concatenate([np.ones((5, 1)), np.arange(1, 16).reshape(5, 3, order='F')/10.0], axis=1)
y_t = np.array([1, 0, 1, 0, 1])
lambda_t = 3

cost, gradient = lrCostFunction(theta_t, X_t, y_t, lambda_t)
print("J= ", cost, "\nGrad= ", gradient)

输出:

J=  3.0857279966152817 
Grad=  [ 0.35537648 -0.49170896  0.88597928  1.66366752]

作业要求来自相同输入的这些结果:

print('Cost         : {:.6f}'.format(J))
print('Expected cost: 2.534819')
print('-----------------------')
print('Gradients:')
print(' [{:.6f}, {:.6f}, {:.6f}, {:.6f}]'.format(*grad))
print('Expected gradients:')
print(' [0.146561, -0.548558, 0.724722, 1.398003]');

我什至在互联网上搜索了每个人的代码都和我一样的答案,他们说他们的结果与预测的一样。我在我的 pycharm IDE 上复制了他们的代码,但我再次得到了相同的答案。 如果您想阅读“向量化正则化逻辑回归”的问题,输入也是相同的

链接:PYTHON ASSIGNMENT OF ANDREW NG ML COURSE

链接到具有相同代码和正确答案的解决方案之一:

链接:ONE OF THE GUYS CLAIMING TO HAVE THE EXPECTED RESULT FROM SAME CODE AS MINE

这也发生在我上次作业的一部分中,真的很令人沮丧,所以我正在寻求帮助。

【问题讨论】:

    标签: python numpy machine-learning pycharm logistic-regression


    【解决方案1】:

    您的代码是正确的。问题是,当您更改值tempt[0] 时,您也在更改theta[0]。复制theta 可确保初始向量不会更改。

    def lrCostFunction(theta, X, y, lambda_):
        m = y.size
    
        if y.dtype == bool:
            y = y.astype(float)
        
        J = 0
        grad = np.zeros(theta.shape)
        hx = X.dot(theta.T)
        h = sigmoid(hx)
    
        tempt = np.copy(theta)    # Copy of theta
        tempt[0] = 0
        
        J = (1/m) * np.sum(-y.dot(np.log(h)) - (1-y).dot(np.log(1-h)))
        J = J + (lambda_/(2*m)) * np.sum(np.square(tempt))
        
        grad = ((1/m) * (h - y) .dot(X)) + (lambda_/m) * tempt
        
        print(theta, tempt)
        return J, grad
    
    cost, gradient = lrCostFunction(theta_t, X_t, y_t, lambda_t)
    print("J= ", cost, "\nGrad= ", gradient)
    
    # Output:
    # [-2. -1.  1.  2.] [ 0. -1.  1.  2.]
    # J=  2.534819396109744 
    # Grad=  [ 0.14656137 -0.54855841  0.72472227  1.39800296]
    

    【讨论】:

    • 如果我的回答对你有帮助,请考虑接受它是正确的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    相关资源
    最近更新 更多