Book Image

Clojure for Data Science

By : Henry Garner
Book Image

Clojure for Data Science

By: Henry Garner

Overview of this book

Table of Contents (18 chapters)
Clojure for Data Science
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
Preface
Index

Fitting curves with a linear model


First, let's remind ourselves how we would fit a straight line using Incanter's linear-model function. We want to extract the x5 and x6 columns from the dataset and apply them (in that order: x6, the year, is our predictor variable) to the incanter.stats/linear-model function.

(defn ex-9-3 []
  (let [data  (d/get-dataset :longley)
        model (s/linear-model (i/$ :x5 data)
                              (i/$ :x6 data))]
    (println "R-square" (:r-square model))
    (-> (c/scatter-plot (i/$ :x6 data)
                        (i/$ :x5 data)
                        :x-label "Year"
                        :y-label "Population")
        (c/add-lines (i/$ :x6 data)
                     (:fitted model))
        (i/view))))

;; R-square 0.9879

The preceding code generates the following chart:

While the straight line is a close fit to the data—generating an R2 of over 0.98—it doesn't capture the curve of the line. In particular, we can see that points diverge from...