2015-04-20 21 views
1

我使用defprotocol來實現多態性。我有一個簡單的邏輯門。 forwardbackward是要由每個門執行的兩個功能。IllegalArgumentException:在defprotocol中沒有單一方法

代碼:

;; a single unit has forward value and backward gradient. 
(defrecord Unit 
    [value gradient]) 

(defrecord Gate 
    [^:Unit input-a ^:Unit input-b]) 

(defprotocol GateOps 
    (forward [this]) 
    (backward [this back-grad])) 

(extend-protocol GateOps 
    Unit 
    (forward [this] 
    (-> this :value)) 
    (backward [this back-grad] 
    ({this back-grad}))) 

(defrecord MultiplyGate [input-a input-b] 
    GateOps 
    (forward [this] 
    (* (forward (-> this :input-a)) (forward (:input-b this)))) 

    (backward [this back-grad] 
    (let [val-a (forward (-> this :input-a)) 
      val-b (forward (-> this :input-b)) 
      input-a (:input-a this) 
      input-b (:input-b this)] 
     (merge-with + (backward input-a (* val-b back-grad)) 
        (backward input-b (* val-a back-grad)))))) 

(defrecord AddGate [input-a input-b] 
    GateOps 
    (forward [this] 
    (+ (forward (:input-a this)) (forward (:input-b this)))) 

    (backward [this back-grad] 
    (let [val-a (forward (-> this :input-a)) 
      val-b (forward (-> this :input-b)) 
      input-a (:input-a this) 
      input-b (:input-b this)] 
     (merge-with + (backward input-a (* 1.0 back-grad)) 
        (backward input-b (* 1.0 back-grad)))))) 


(defn sig [x] 
    (/ 1 (+ 1 (Math/pow Math/E (- x))))) 

(defrecord SigmoidGate [gate] 
    GateOps 
    (forward [this] 
    (sig (forward (:gate this)))) 

    (backward [this back-grad] 
    (let [s (forward this) 
      ds (* s (- 1 s))] 
     (backward (:gate this) ds)))) 

forward工作正常,在backward我得到異常:

user> (neurals.core/forward neurals.core/sigaxcby) 
0.8807970779778823 

user> (neurals.core/backward neurals.core/sigaxcby) 
CompilerException java.lang.IllegalArgumentException: 
No single method: backward of interface: neurals.core.GateOps 
found for function: backward of protocol: GateOps, 
compiling:(C:\xxyyzz\AppData\Local\Temp\form-init8132866244624247216.clj:1:1) 

user> 

版本信息:Clojure的1.6.0

我到底做錯了什麼?

+1

了吧..應該已經落後也給初始值。少一個論點。 –

回答

0

這很奇怪,因爲error-output與實際錯誤沒有任何關聯:Arity error

我應該給初始back-grad值的backward功能:

(neurals.core/backward neurals.core/sigaxcby 1.0) 
+0

是啊,這很奇怪,但「沒有單一的方法」通常意味着一個方法 – noisesmith

+0

好的.. ..謝謝。會將這個錯誤添加到我的錯誤命名空間中。 :) –

相關問題