/
ames_test.clj
388 lines (348 loc) · 15.9 KB
/
ames_test.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
(ns tech.ml.dataset.ames-test
(:require [tech.ml.dataset.pipeline
:refer [m= col int-map]
:as dsp]
[tech.ml.dataset.pipeline.pipeline-operators
:refer [pipeline-train-context
pipeline-inference-context]]
[tech.ml.dataset.pipeline.base
:refer [with-ds]]
[tech.ml.dataset.pipeline :as ds-pipe]
[tech.ml.dataset :as ds]
[tech.ml.dataset.column :as ds-col]
[tech.ml.dataset.pipeline.column-filters
:as cf]
[tech.ml.dataset-test
:refer [mapseq-fruit-dataset]
:as ds-test]
[tech.v2.datatype :as dtype]
[tech.v2.datatype.functional :as dfn]
[clojure.set :as c-set]
[tech.libs.tablesaw :as tablesaw]
[clojure.test :refer :all]))
(deftest tablesaw-col-subset-test
(let [test-col (dtype/make-container :tablesaw-column :int32
(range 10))
select-vec [3 5 7 3 2 1]
new-col (ds-col/select test-col select-vec)]
(is (= select-vec
(dtype/->vector new-col)))))
(def src-ds (ds/->dataset "data/ames-house-prices/train.csv"))
(defn missing-pipeline
[dataset]
(-> (ds/->dataset dataset)
(ds/remove-column "Id")
(dsp/replace-missing cf/string? "NA")
(dsp/replace cf/string? {"" "NA"})
(dsp/replace-missing cf/numeric? 0)
(dsp/replace-missing cf/boolean? false)
(dsp/->datatype #(cf/or cf/numeric?
cf/boolean?))))
(deftest basic-pipeline-test
(let [dataset (missing-pipeline src-ds)]
(is (= 19 (count (ds/columns-with-missing-seq src-ds))))
(is (= 0 (count (ds/columns-with-missing-seq dataset))))
(is (= 42 (count (cf/categorical? dataset))))
(is (= #{:string :float64}
(->> (ds/columns dataset)
(map dtype/get-datatype)
set)))))
(deftest log1p-fails-on-wrong-datatype
;;This causes actual data corruption--if the column datatype gets clipped
;;back to an integer type you get values like 12 instead of 12.5. For this
;;dataset that destroys the accuracy.
(is (thrown? Throwable
(dsp/m= src-ds "SalePrice" #(dfn/log1p (col))))))
(defn skew-column-filter
[dataset]
(with-ds dataset
(cf/and cf/numeric?
#(cf/not "SalePrice")
(fn [] (cf/> #(dfn/abs (dfn/skewness (col)))
0.5)))))
;;This test fails if col-filters/and (intersection) isn't
;;implemented correctly
(deftest and-is-lazy
(is (= 29 (count (skew-column-filter src-ds)))))
(defn string-and-math
[dataset]
(-> dataset
(dsp/string->number "Utilities" [["NA" -1] "ELO" "NoSeWa" "NoSewr" "AllPub"])
(dsp/string->number "LandSlope" ["Gtl" "Mod" "Sev" "NA"])
(dsp/string->number ["ExterQual"
"ExterCond"
"BsmtQual"
"BsmtCond"
"HeatingQC"
"KitchenQual"
"FireplaceQu"
"GarageQual"
"GarageCond"
"PoolQC"] ["Ex" "Gd" "TA" "Fa" "Po" "NA"])
(dsp/assoc-metadata ["MSSubClass" "OverallQual" "OverallCond"]
:categorical? true)
(dsp/string->number "MasVnrType" {"BrkCmn" 1
"BrkFace" 1
"CBlock" 1
"Stone" 1
"None" 0
"NA" -1})
(dsp/string->number "SaleCondition" {"Abnorml" 0
"Alloca" 0
"AdjLand" 0
"Family" 0
"Normal" 0
"Partial" 1
"NA" -1})
;; ;;Auto convert the rest that are still string columns
(dsp/string->number)
(dsp/new-column "SalePriceDup" #(ds/column % "SalePrice"))
(dsp/update-column "SalePrice" dfn/log1p)
(ds/set-inference-target "SalePrice")))
(deftest base-etl-test
(let [src-dataset src-ds
;;For inference, we won't have the target but we will have everything else.
inference-columns (c-set/difference
(set (map ds-col/column-name
(ds/columns src-dataset)))
#{"SalePrice"})
inference-dataset (-> (ds/select src-dataset
inference-columns
(range 10))
(ds/->flyweight :error-on-missing-values? false))
dataset (-> src-ds
missing-pipeline
string-and-math)
post-pipeline-columns (c-set/difference inference-columns #{"Id"})
sane-dataset-for-flyweight (ds/select dataset post-pipeline-columns
(range 10))
final-flyweight (-> sane-dataset-for-flyweight
(ds/->flyweight))]
(is (= [81 1460] (dtype/shape src-dataset)))
(is (= [81 1460] (dtype/shape dataset)))
(is (= 45 (count (cf/categorical? dataset))))
(is (= #{"MSSubClass" "OverallQual" "OverallCond"}
(c-set/intersection #{"MSSubClass" "OverallQual" "OverallCond"}
(set (cf/categorical? dataset)))))
(is (= []
(vec (cf/string? dataset))))
(is (= ["SalePrice"]
(vec (cf/target? dataset))))
(is (= []
(vec (cf/not cf/numeric? dataset))))
(let [sale-price (ds/column dataset "SalePriceDup")
sale-price-l1p (ds/column dataset "SalePrice")
sp-stats (ds-col/stats sale-price [:mean :min :max])
sp1p-stats (ds-col/stats sale-price-l1p [:mean :min :max])]
(is (dfn/equals (mapv sp-stats [:mean :min :max])
[180921.195890 34900 755000]
0.01))
(is (dfn/equals (mapv sp1p-stats [:mean :min :max])
[12.024 10.460 13.534]
0.01)))
(is (= 10 (count inference-dataset)))
(is (= 10 (count final-flyweight)))
(let [pre-pipeline (map ds-col/metadata (ds/columns src-ds))
exact-columns (tablesaw/map-seq->tablesaw-dataset
inference-dataset
{:column-definitions pre-pipeline})
;;Just checking that this works at all..
autoscan-columns (tablesaw/map-seq->tablesaw-dataset inference-dataset {})]
;;And the definition of exact is...
(is (= (mapv :datatype (->> pre-pipeline
(sort-by :name)))
(->> (ds/columns exact-columns)
(map ds-col/metadata)
(sort-by :name)
(mapv :datatype))))
(let [inference-ds (-> exact-columns
missing-pipeline
string-and-math)]
;;spot check a few of the items
(is (dfn/equals (dtype/->vector (ds/column sane-dataset-for-flyweight
"MSSubClass"))
(dtype/->vector (ds/column inference-ds "MSSubClass"))))
;;did categorical values get encoded identically?
(is (dfn/equals (dtype/->vector (ds/column sane-dataset-for-flyweight
"OverallQual"))
(dtype/->vector (ds/column inference-ds "OverallQual"))))))))
(defn full-ames-pt-1
[dataset]
(-> (missing-pipeline dataset)
(dsp/string->number "Utilities" [["NA" -1] "ELO" "NoSeWa" "NoSewr" "AllPub"])
(dsp/string->number "LandSlope" ["Gtl" "Mod" "Sev" "NA"])
(dsp/string->number ["ExterQual"
"ExterCond"
"BsmtQual"
"BsmtCond"
"HeatingQC"
"KitchenQual"
"FireplaceQu"
"GarageQual"
"GarageCond"
"PoolQC"] ["Ex" "Gd" "TA" "Fa" "Po" "NA"])
(dsp/assoc-metadata ["MSSubClass" "OverallQual" "OverallCond"]
:categorical? true)
(dsp/string->number "MasVnrType" {"BrkCmn" 1
"BrkFace" 1
"CBlock" 1
"Stone" 1
"None" 0
"NA" -1})
(dsp/string->number "SaleCondition" {"Abnorml" 0
"Alloca" 0
"AdjLand" 0
"Family" 0
"Normal" 0
"Partial" 1
"NA" -1})
;; ;;Auto convert the rest that are still string columns
(dsp/string->number)
(dsp/update-column "SalePrice" dfn/log1p)
(ds/set-inference-target "SalePrice")
(m= "OverallGrade" #(dfn/* (col "OverallQual") (col "OverallCond")))
;; Overall quality of the garage
(m= "GarageGrade" #(dfn/* (col "GarageQual") (col "GarageCond")))
;; Overall quality of the exterior
(m= "ExterGrade" #(dfn/* (col "ExterQual") (col "ExterCond")))
;; Overall kitchen score
(m= "KitchenScore" #(dfn/* (col "KitchenAbvGr") (col "KitchenQual")))
;; Overall fireplace score
(m= "FireplaceScore" #(dfn/* (col "Fireplaces") (col "FireplaceQu")))
;; Overall garage score
(m= "GarageScore" #(dfn/* (col "GarageArea") (col "GarageQual")))
;; Overall pool score
(m= "PoolScore" #(dfn/* (col "PoolArea") (col "PoolQC")))
;; Simplified overall quality of the house
(m= "SimplOverallGrade" #(dfn/* (col "OverallQual") (col "OverallCond")))
;; Simplified overall quality of the exterior
(m= "SimplExterGrade" #(dfn/* (col "ExterQual") (col "ExterCond")))
;; Simplified overall pool score
(m= "SimplPoolScore" #(dfn/* (col "PoolArea") (col "PoolQC")))
;; Simplified overall garage score
(m= "SimplGarageScore" #(dfn/* (col "GarageArea") (col "GarageQual")))
;; Simplified overall fireplace score
(m= "SimplFireplaceScore" #(dfn/* (col "Fireplaces") (col "FireplaceQu")))
;; Simplified overall kitchen score
(m= "SimplKitchenScore" #(dfn/* (col "KitchenAbvGr") (col "KitchenQual")))
;; Total number of bathrooms
(m= "TotalBath" #(dfn/+ (col "BsmtFullBath")
(dfn/* 0.5 (col "BsmtHalfBath"))
(col "FullBath")
(dfn/* 0.5 (col "HalfBath"))))
;; Total SF for house (incl. basement)
(m= "AllSF" #(dfn/+ (col "GrLivArea") (col "TotalBsmtSF")))
;; Total SF for 1st + 2nd floors
(m= "AllFlrsSF" #(dfn/+ (col "1stFlrSF") (col "2ndFlrSF")))
;; Total SF for porch
(m= "AllPorchSF" #(dfn/+ (col "OpenPorchSF") (col "EnclosedPorch")
(col "3SsnPorch") (col "ScreenPorch")))))
(def ames-top-columns
["SalePrice"
"OverallQual"
"AllSF"
"AllFlrsSF"
"GrLivArea"
"GarageCars"
"ExterQual"
"TotalBath"
"KitchenQual"
"GarageArea"
"ExterGrade"])
(defn full-ames-pt-2
[dataset]
;;Drop SalePrice column of course.
(->> (rest ames-top-columns)
(reduce (fn [dataset colname]
(-> dataset
(m= (str colname "-s2") #(dfn/pow (col colname) 2))
(m= (str colname "-s3") #(dfn/pow (col colname) 3))
(m= (str colname "-sqrt") #(dfn/sqrt (col colname)))))
dataset)))
(defn full-ames-pt-3
[dataset]
(-> dataset
(m= (skew-column-filter dataset)
#(dfn/log1p (col)))
(dsp/std-scale)))
(deftest full-ames-pipeline-test
(let [src-dataset src-ds]
(testing "Pathway through ames pt one is sane. Checking skew."
(let [dataset (full-ames-pt-1 src-dataset)]
(is (= ames-top-columns
(->> (get (ds/correlation-table dataset) "SalePrice")
(take 11)
(mapv first))))
(let [[n-cols n-rows] (dtype/shape src-dataset)
[n-new-cols n-new-rows] (-> (dsp/filter src-dataset
"GrLivArea"
#(dfn/< (col) 4000))
dtype/shape)
num-over-the-line (->> (ds/column src-dataset "GrLivArea")
(ds-col/column-values)
(filter #(>= (int %) 4000))
count)]
;;Ensure our test isn't pointless.
(is (not= 0 num-over-the-line))
(is (= n-new-rows
(- n-rows num-over-the-line))))
(let [new-ds (m= src-dataset "SimplOverallQual"
#(int-map {1 1 2 1 3 1
4 2 5 2 6 2
7 3 8 3 9 3 10 3}
(col "OverallQual")))]
(is (= #{1 2 3}
(->> (ds/column new-ds "SimplOverallQual")
(ds-col/unique)
(map int)
set))))))
(testing "Pathway through ames pt 2 is sane. Checking skew."
(let [dataset (-> src-ds
full-ames-pt-1
full-ames-pt-2)
skewed-set (set (skew-column-filter dataset))]
;;This count seems rather high...a diff against the python stuff would be wise.
(is (= 98 (count skewed-set)))
;;Sale price cannot be in the set as it was explicitly removed.
(is (not (contains? skewed-set "SalePrice")))))
(testing "Full ames pathway is sane"
(let [dataset (-> src-ds
full-ames-pt-1
full-ames-pt-2
full-ames-pt-3)
std-set (set (cf/numeric-and-non-categorical-and-not-target dataset))
mean-var-seq (->> std-set
(map (comp #(ds-col/stats % [:mean :variance])
(partial ds/column dataset))))]
;;Are means 0?
(is (dfn/equals (mapv :mean mean-var-seq)
(vec (repeat (count mean-var-seq) 0))
0.001))
(let [pca-ds (dsp/pca dataset)]
(is (= 127 (count (ds/columns dataset))))
(is (= 11 (count (cf/categorical? pca-ds))))
(is (= 63 (count (ds/columns pca-ds))))
(is (= 1 (count (cf/target? pca-ds)))))
(let [pca-ds (dsp/pca dataset
cf/numeric-and-non-categorical-and-not-target
:n-components 10)]
(is (= 11 (count (cf/categorical? dataset))))
(is (= 11 (count (cf/categorical? pca-ds))))
(is (= 127 (count (ds/columns dataset))))
(is (= 22 (count (ds/columns pca-ds))))
(is (= 1 (count (cf/target? pca-ds)))))))))
(deftest tostring-regression
(testing "tostring has to work with missing values"
(is (string?
(.toString ^Object src-ds)))))
(deftest desc-stats-and-correlation
[]
(let [stats-data (ds/descriptive-stats src-ds)
corr-data (ds-pipe/correlation-table src-ds :colname-seq ["SalePrice"])]
(is (= [10 81]
(dtype/shape stats-data)))
(is (= 81
(->> corr-data
first
second
count)))))