Created
March 2, 2012 03:15
-
-
Save cbilson/1955295 to your computer and use it in GitHub Desktop.
My lame roughly macro for clojure.test. Sucks? Rocks?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns model-trainer.test.helpers | |
(:use [model-trainer.math :only [msum mabs msubtract rvec matrix]] | |
[clojure.test]) | |
(:import [cern.colt.matrix DoubleMatrix2D DoubleMatrix1D])) | |
;; usage | |
#_(deftest computing-activations | |
;; this tests computing activation for a layer in a multi-layer perceptron, | |
;; basically: multiply rvec by matrix and apply the sigmoid activation function to | |
;; constrain the values to the 0 to 1 range. The result should be the first vector. | |
(with-tolerance 1e-6 | |
(is (roughly (rvec [0.0 0.5 1.0]) | |
(compute-activation sigmoid | |
(rvec 1e6 1e6) | |
(matrix [-1 0] | |
[ 0 0] | |
[ 0 1])))))) | |
;; actual code: | |
(def ^:dynamic *tolerance* 1e-6) | |
(defmacro with-tolerance [n & body] | |
`(binding [*tolerance* ~n] | |
~@body)) | |
(defmulti abs-difference (fn [x _] (class x))) | |
(defmethod abs-difference java.lang.Double [x y] | |
(Math/abs (- x y))) | |
(defmethod abs-difference cern.colt.matrix.DoubleMatrix2D [x y] | |
(-> (msubtract x y) | |
mabs | |
msum)) | |
(defmethod abs-difference cern.colt.matrix.DoubleMatrix1D [x y] | |
(-> (msubtract x y) | |
mabs | |
msum)) | |
;; this was the hard part | |
;; * I wanted it to work with scalars, vectors, and matrices | |
;; * Figuring out that what I needed was an "assert-expr" was the hardest part | |
(defmethod assert-expr 'roughly [msg form] | |
`(let [d# (abs-difference ~(nth form 1) ~(nth form 2)) | |
result# (> *tolerance* d#)] | |
(if result# | |
(do-report {:type :pass :message ~msg | |
:expected '(:difference-within ~*tolerance*) :actual d#}) | |
(do-report {:type :fail :message ~msg | |
:expected '(:difference-within ~*tolerance*) :actual d# })) | |
result#)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment