Skip to content

Instantly share code, notes, and snippets.

@ghostandthemachine
Created November 9, 2013 02:55
Show Gist options
  • Save ghostandthemachine/7380969 to your computer and use it in GitHub Desktop.
Save ghostandthemachine/7380969 to your computer and use it in GitHub Desktop.
(ns ai.core
(:require [clojure.core.async :as async :refer [<! >! <!! timeout chan alt! go]]))
;; Helper functions
(defn log
"Log function. Takes base and a value."
[b v]
(/ (Math/log v)
(Math/log b)))
(defn mult-vecs
"Multiplies two vectors together into one. Assumes they are of the same length."
[v1 v2]
(into []
(map #(apply * %) (partition 2 (interleave v1 v2)))))
;; Problems
(defn problem-one [xs ys]
"Solves HW problem 1."
(let [x-sum (apply + xs)
y-sum (apply + ys)
xx (apply + (map #(* % %) xs))
xy (apply + (mult-vecs xs ys))
w1 (/
(- (* (count xs) xy) (* x-sum y-sum))
(- (* (count xs) xx) (* x-sum x-sum)))
w0 (/
(- y-sum (* w1 x-sum))
(count xs))]
{:x-sum x-sum
:y-sum y-sum
:xx xx
:xy xy
:w0 w0
:w1 w1
:h (str "h = " w1 "x + " w0)}))
(def xs-notes [2 6 4 8])
(def ys-notes [1 3 0 2])
; (problem-one xs-notes ys-notes)
;; results
; {:x-sum 20,
; :y-sum 6,
; :xx 120,
; :xy 36,
; :w0 0N,
; :w1 3/10,
; :h "h = 3/10x + 0"}
;; Answer
;; h = 3/10x + 0
(def xs-hw [2 1 -1 3 1.5 2.5 0.5])
(def ys-hw [3 2 -4 5 2 6 -0.5])
; (mult-vecs xs-notes ys-notes)
; (problem-one xs-hw ys-hw)
;; results
; {:x-sum 9.5,
; :y-sum 13.5,
; :xx 23.75,
; :xy 44.75,
; :w0 -1.375,
; :w1 2.4342105263157894,
; :h "h = 2.4342105263157894x + -1.375"}
;; Answer
;; h = 2.4342105263157894x + -1.375
(defn problem-two
[data iterations]
(let [alpha 0.01
;; add 1 to the front of each vector
data (map
(fn [[w in out]]
[w (into [1] in) out])
data)
;; create w's based on count of first vector in x's (size of Xj)
w0 (map (fn [_] 0) (range (count (first (:x data)))))
;; h function
hfn (fn [xj w]
(apply + (mult-vecs xj w)))
wfn (fn [w x y]
(+ w
(* theta
())))
]
(loop [d data i iterations]
(if (== i 0)
d
(let [hs (mult-vecs (:ws d) (:xs d))
ws (map
(fn [w]
(+ w (* alpha))))]
(recur d (dec i)))))))
(def data-notes
{:x [[1 3]
[2 -1]
[3 3]]
:y [4 6 2]})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment