6

我正在尝试使用Incanter 数据分析库在 Clojure 中实现一个简单的逻辑回归示例。我已经成功编写了 Sigmoid 和 Cost 函数,但是 Incanter 的 BFGS 最小化函数似乎给我带来了一些麻烦。

(ns ml-clj.logistic
  (:require [incanter.core :refer :all]
            [incanter.optimize :refer :all]))


(defn sigmoid
  "compute the inverse logit function, large positive numbers should be
close to 1, large negative numbers near 0,
z can be a scalar, vector or matrix.
sanity check: (sigmoid 0) should always evaluate to 0.5"
  [z]
  (div 1 (plus 1 (exp (minus z)))))

(defn cost-func
  "computes the cost function (J) that will be minimized
   inputs:params theta X matrix and Y vector"
  [X y]
  (let
      [m (nrow X)
       init-vals (matrix (take (ncol X) (repeat 0)))
       z (mmult X init-vals)
       h (sigmoid z)
       f-half (mult (matrix (map - y)) (log (sigmoid (mmult X init-vals))))
       s-half (mult (minus 1 y) (log (minus 1 (sigmoid (mmult X init-vals)))))
       sub-tmp (minus f-half s-half)
       J (mmult (/ 1 m) (reduce + sub-tmp))]
    J))

当我尝试(minimize (cost-func X y) (matrix [0 0]))给出minimize一个函数并启动参数时,REPL 会抛出一个错误。

ArityException Wrong number of args (2) passed to: optimize$minimize  clojure.lang.AFn.throwArity (AFn.java:437)

我对最小化函数的期望是什么感到非常困惑。

作为参考,我用 python 重写了它,所有代码都按预期运行,使用相同的最小化算法。

import numpy as np
import scipy as sp
data = np.loadtxt('testSet.txt', delimiter='\t')

X = data[:,0:2]
y = data[:, 2]


def sigmoid(X):
    return 1.0 / (1.0 + np.e**(-1.0 * X))

def compute_cost(theta, X, y):
    m = y.shape[0]
    h = sigmoid(X.dot(theta.T))
    J = y.T.dot(np.log(h)) + (1.0 - y.T).dot(np.log(1.0 - h))
    cost = (-1.0 / m) * J.sum() 
    return cost

def fit_logistic(X,y):
    initial_thetas = np.zeros((len(X[0]), 1))
    myargs = (X, y)
    theta = sp.optimize.fmin_bfgs(compute_cost, x0=initial_thetas,
                                     args=myargs)
    return theta

输出

Current function value: 0.594902
         Iterations: 6
         Function evaluations: 36
         Gradient evaluations: 9
array([ 0.08108673, -0.12334958])

我不明白为什么 Python 代码可以成功运行,但我的 Clojure 实现却失败了。有什么建议么?

更新

重新阅读文档字符串,因为minimize我一直在尝试计算其导数cost-func会引发新错误。

(def grad (gradient cost-func (matrix [0 0])))
(minimize cost-func (matrix [0 0]) (grad (matrix [0 0]) X))
ExceptionInfo throw+: {:exception "Matrices of different sizes cannot be differenced.", :asize [2 1], :bsize [1 2]}  clatrix.core/- (core.clj:950)

使用trans将 1xn col 矩阵转换为 nx1 行矩阵只会产生相同的错误和相反的错误。

:asize [1 2], :bsize [2 1]}

我很迷失在这里。

4

2 回答 2

3

我不能说你的实现,但是incanter.optimize/minimize期望(至少)三个参数,你只给它两个:

Arguments:
  f -- Objective function. Takes a collection of values and returns a scalar
       of the value of the function.
  start -- Collection of initial guesses for the minimum
  f-prime -- partial derivative of the objective function. Takes
             a collection of values and returns a collection of partial
             derivatives with respect to each variable. If this is not
             provided it will be estimated using gradient-fn.

不幸的是,我不能直接告诉你f-prime在这里提供什么(为了?),但也许其他人是。顺便说一句,我认为ArityException Wrong number of args (2) passed to [...]这里实际上很有帮助。

编辑:实际上,我认为上面的文档字符串不正确,因为源代码不gradient-fn用于估计f-prime. 也许,你可以用它incanter.optimize/gradient来生成你自己的?

于 2013-11-10T11:29:33.297 回答
1

首先,您的成本函数应该像您的 python 实现一样具有 theta 参数,但是您的实现已固定为初始值。

其次,如果您的成本函数是正确的,那么您可以像这样调用优化

(optimize (fn [theta] (cost-func theta X y)) [0 0 0])

希望这可以帮到你。

于 2016-03-29T07:02:25.460 回答