/
kmeans.hs
310 lines (267 loc) · 9.85 KB
/
kmeans.hs
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
{-# LANGUAGE ScopedTypeVariables, BangPatterns #-}
-- K-Means sample from "Parallel and Concurrent Programming in Haskell"
--
-- With three versions:
-- [ kmeans_seq ] a sequential version
-- [ kmeans_strat ] a parallel version using Control.Parallel.Strategies
-- [ kmeans_par ] a parallel version using Control.Monad.Par
--
-- Usage (sequential):
-- $ ./kmeans-par seq
--
-- Usage (Strategies):
-- $ ./kmeans-par strat 600 +RTS -N4
--
-- Usage (Par monad):
-- $ ./kmeans-par par 600 +RTS -N4
--
-- Usage (divide-and-conquer / Par monad):
-- $ ./kmeans-par divpar 7 +RTS -N4
--
-- Usage (divide-and-conquer / Eval monad):
-- $ ./kmeans-par diveval 7 +RTS -N4
import System.IO
import KMeansCore
import Data.Array
import Data.Array.Unsafe as Unsafe
import Text.Printf
import Data.List
import Data.Function
import Data.Binary (decodeFile)
import Debug.Trace
import Control.Parallel.Strategies as Strategies
import Control.Monad.Par as Par
import Control.DeepSeq
import System.Environment
import Data.Time.Clock
import Control.Exception
import Control.Concurrent
import Control.Monad.ST
import Data.Array.ST
import System.Mem
import Data.Maybe
import qualified Data.Vector as Vector
import Data.Vector (Vector)
import qualified Data.Vector.Mutable as MVector
-- -----------------------------------------------------------------------------
-- main: read input files, time calculation
main = runInUnboundThread $ do
points <- decodeFile "points.bin"
clusters <- read `fmap` readFile "clusters"
let nclusters = length clusters
args <- getArgs
npoints <- evaluate (length points)
performGC
t0 <- getCurrentTime
final_clusters <- case args of
["seq" ] -> kmeans_seq nclusters points clusters
["strat", n] -> kmeans_strat (read n) nclusters points clusters
["par", n] -> kmeans_par (read n) nclusters points clusters
["divpar", n] -> kmeans_div_par (read n) nclusters points clusters npoints
["diveval", n] -> kmeans_div_eval (read n) nclusters points clusters npoints
_other -> error "args"
t1 <- getCurrentTime
print final_clusters
printf "Total time: %.2f\n" (realToFrac (diffUTCTime t1 t0) :: Double)
-- -----------------------------------------------------------------------------
-- K-Means: repeatedly step until convergence (sequential)
-- <<kmeans_seq
kmeans_seq :: Int -> [Point] -> [Cluster] -> IO [Cluster]
kmeans_seq nclusters points clusters =
let
loop :: Int -> [Cluster] -> IO [Cluster]
loop n clusters | n > tooMany = do -- <1>
putStrLn "giving up."
return clusters
loop n clusters = do
printf "iteration %d\n" n
putStr (unlines (map show clusters))
let clusters' = step nclusters clusters points -- <2>
if clusters' == clusters -- <3>
then return clusters
else loop (n+1) clusters'
in
loop 0 clusters
tooMany = 80
-- >>
-- -----------------------------------------------------------------------------
-- K-Means: repeatedly step until convergence (Strategies)
-- <<kmeans_strat
kmeans_strat :: Int -> Int -> [Point] -> [Cluster] -> IO [Cluster]
kmeans_strat numChunks nclusters points clusters =
let
chunks = split numChunks points -- <1>
loop :: Int -> [Cluster] -> IO [Cluster]
loop n clusters | n > tooMany = do
printf "giving up."
return clusters
loop n clusters = do
printf "iteration %d\n" n
putStr (unlines (map show clusters))
let clusters' = parSteps_strat nclusters clusters chunks -- <2>
if clusters' == clusters
then return clusters
else loop (n+1) clusters'
in
loop 0 clusters
-- >>
-- <<split
split :: Int -> [a] -> [[a]]
split numChunks xs = chunk (length xs `quot` numChunks) xs
chunk :: Int -> [a] -> [[a]]
chunk n [] = []
chunk n xs = as : chunk n bs
where (as,bs) = splitAt n xs
-- >>
-- -----------------------------------------------------------------------------
-- K-Means: repeatedly step until convergence (Par monad)
kmeans_par :: Int -> Int -> [Point] -> [Cluster] -> IO [Cluster]
kmeans_par mappers nclusters points clusters =
let
chunks = split mappers points
loop :: Int -> [Cluster] -> IO [Cluster]
loop n clusters | n > tooMany = do printf "giving up."; return clusters
loop n clusters = do
printf "iteration %d\n" n
putStr (unlines (map show clusters))
let
clusters' = steps_par nclusters clusters chunks
if clusters' == clusters
then return clusters
else loop (n+1) clusters'
in
loop 0 clusters
-- -----------------------------------------------------------------------------
-- kmeans_div_par: Use divide-and-conquer, and the Par monad for parallellism.
kmeans_div_par :: Int -> Int -> [Point] -> [Cluster] -> Int -> IO [Cluster]
kmeans_div_par threshold nclusters points clusters npoints =
let
tree = mkPointTree threshold points npoints
loop :: Int -> [Cluster] -> IO [Cluster]
loop n clusters | n > tooMany = do printf "giving up."; return clusters
loop n clusters = do
hPrintf stderr "iteration %d\n" n
hPutStr stderr (unlines (map show clusters))
let
divconq :: Tree [Point] -> Par (Vector PointSum)
divconq (Leaf points) = return $ assign nclusters clusters points
divconq (Node left right) = do
i1 <- spawn $ divconq left
i2 <- spawn $ divconq right
c1 <- get i1
c2 <- get i2
return $! combine c1 c2
clusters' = makeNewClusters $ runPar $ divconq tree
if clusters' == clusters
then return clusters
else loop (n+1) clusters'
in
loop 0 clusters
data Tree a = Leaf a
| Node (Tree a) (Tree a)
mkPointTree :: Int -> [Point] -> Int -> Tree [Point]
mkPointTree threshold points npoints = go 0 points npoints
where
go depth points npoints
| depth >= threshold = Leaf points
| otherwise = Node (go (depth+1) xs half)
(go (depth+1) ys half)
where
half = npoints `quot` 2
(xs,ys) = splitAt half points
-- -----------------------------------------------------------------------------
-- kmeans_div_eval: Use divide-and-conquer, and the Eval monad for parallellism.
kmeans_div_eval :: Int -> Int -> [Point] -> [Cluster] -> Int -> IO [Cluster]
kmeans_div_eval threshold nclusters points clusters npoints =
let
tree = mkPointTree threshold points npoints
loop :: Int -> [Cluster] -> IO [Cluster]
loop n clusters | n > tooMany = do printf "giving up."; return clusters
loop n clusters = do
hPrintf stderr "iteration %d\n" n
hPutStr stderr (unlines (map show clusters))
let
divconq :: Tree [Point] -> Vector PointSum
divconq (Leaf points) = assign nclusters clusters points
divconq (Node left right) = runEval $ do
c1 <- rpar $ divconq left
c2 <- rpar $ divconq right
rdeepseq c1
rdeepseq c2
return $! combine c1 c2
clusters' = makeNewClusters $ divconq tree
if clusters' == clusters
then return clusters
else loop (n+1) clusters'
in
loop 0 clusters
-- -----------------------------------------------------------------------------
-- Perform one step of the K-Means algorithm
-- <<step
step :: Int -> [Cluster] -> [Point] -> [Cluster]
step nclusters clusters points
= makeNewClusters (assign nclusters clusters points)
-- >>
-- <<assign
assign :: Int -> [Cluster] -> [Point] -> Vector PointSum
assign nclusters clusters points = Vector.create $ do
vec <- MVector.replicate nclusters (PointSum 0 zeroPoint)
let
addpoint p = do
let c = nearest p; cid = clId c
ps <- MVector.read vec cid
MVector.write vec cid $! addToPointSum ps p
mapM_ addpoint points
return vec
where
nearest p = fst $ minimumBy (compare `on` snd)
[ (c, sqDistance (clCent c) p) | c <- clusters ]
-- >>
data PointSum = PointSum {-# UNPACK #-} !Int {-# UNPACK #-} !Point
instance NFData PointSum
-- <<addToPointSum
addToPointSum :: PointSum -> Point -> PointSum
addToPointSum (PointSum count ptsum) p
= PointSum (count+1) (ptsum `addPoint` p)
-- >>
-- <<pointSumToCluster
pointSumToCluster :: Int -> PointSum -> Cluster
pointSumToCluster i (PointSum count ptsum@(Point x y)) =
Cluster { clId = i
, clCent = Point (x / fromIntegral count) (y / fromIntegral count)
}
-- >>
-- <<addPointSums
addPointSums :: PointSum -> PointSum -> PointSum
addPointSums (PointSum c1 p1) (PointSum c2 p2)
= PointSum (c1+c2) (p1 `addPoint` p2)
-- >>
-- <<combine
combine :: Vector PointSum -> Vector PointSum -> Vector PointSum
combine = Vector.zipWith addPointSums
-- >>
-- <<parSteps_strat
parSteps_strat :: Int -> [Cluster] -> [[Point]] -> [Cluster]
parSteps_strat nclusters clusters pointss
= makeNewClusters $
foldr1 combine $
(map (assign nclusters clusters) pointss
`using` parList rseq)
-- >>
steps_par :: Int -> [Cluster] -> [[Point]] -> [Cluster]
steps_par nclusters clusters pointss
= makeNewClusters $
foldl1' combine $
(runPar $ Par.parMap (assign nclusters clusters) pointss)
-- <<makeNewClusters
makeNewClusters :: Vector PointSum -> [Cluster]
makeNewClusters vec =
[ pointSumToCluster i ps
| (i,ps@(PointSum count _)) <- zip [0..] (Vector.toList vec)
, count > 0
]
-- >>
-- v. important: filter out any clusters that have
-- no points. This can happen when a cluster is not
-- close to any points. If we leave these in, then
-- the NaNs mess up all the future calculations.