【问题标题】:TypeError: loop of ufunc does not support argument 0 of type ArrayBox which has no callable log methodTypeError: ufunc 的循环不支持 ArrayBox 类型的参数 0,它没有可调用的日志方法
【发布时间】:2021-04-21 12:11:42
【问题描述】:

我正在使用python的auto grad库来计算逻辑回归成本函数的梯度。

这是LR的fit方法的代码:

import numpy as np
import pandas as pd

class LogisticRegression:
    def __init__(self) -> None:
        self.num_of_iterations = None
        self.thetas = None
        self.tolerance = None

        self.thetas_history = []
        self.cost_func_history = []

   
    def fit_autograd(self, X, y, tol, n_iter=100, lr=0.01, fit_intercept=True):

        from autograd import grad
        from autograd import elementwise_grad as egrad
        import autograd.numpy as npa
        from math import e

        def training_loss(weights):
            # Training loss is the negative log-likelihood of the training labels.
            
            preds = (1/(1 + e**( np.dot(X_il, weights) )) - 0.00001)
            label_probabilities = preds * y_il + (1 - preds) * (1 - y_il)
            return -np.sum(np.log(label_probabilities))

        
        
        # handling fit intercept param
        if (fit_intercept == True):
            self.num_of_thetas = len(list(X.columns))+1
            thetas = pd.Series(np.random.randn(self.num_of_thetas))
            bias = pd.DataFrame(pd.Series([1.0 for i in range(len(X))]))
            X = pd.concat([bias,X],axis=1)
        else:
            self.num_of_thetas = len(list(X.columns))
            self.thetas = pd.Series(np.random.randn(self.num_of_thetas))
        
        self.num_of_samples = len(X)
        self.num_of_iterations = n_iter
        self.learning_rate = lr
        self.tolerance = tol
        self.fit_intercept = fit_intercept

        mygrad = grad(training_loss)

        X_il,y_il = X.to_numpy(),y.to_numpy()
        theta_il = thetas.to_numpy()

        for it in range(self.num_of_iterations):

            temp_grad = mygrad(theta_il)
            print(temp_grad)
            print("thetas:",thetas)
            thetas -= (lr/self.num_of_samples) * temp_grad
            self.thetas_history.append(thetas)
            self.cost_func_history.append(temp_grad)

        return thetas

它正在引发以下错误。

TypeError: loop of ufunc does not support argument 0 of type ArrayBox which has no callable log method

我已经检查了github 上的以下问题,使用它我能够为 np.exp() 解决。我不确定如何为 np.log() 执行此操作。

谢谢

【问题讨论】:

    标签: python gradient logistic-regression autograd


    【解决方案1】:

    我认为您需要使用import autograd.numpy as np 而不是import numpy as np。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-14
      • 2021-09-29
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      相关资源
      最近更新 更多