master 92ada1dbfdc2 cached
17 files
28.1 KB
7.0k tokens
14 symbols
1 requests
Download .txt
Repository: freeman-lab/spark-ml-streaming
Branch: master
Commit: 92ada1dbfdc2
Files: 17
Total size: 28.1 KB

Directory structure:
gitextract_2wsty9xh/

├── .gitignore
├── LICENSE
├── README.md
├── python/
│   ├── MANIFEST.in
│   ├── bin/
│   │   └── streaming-kmeans
│   ├── mlstreaming/
│   │   ├── __init__.py
│   │   ├── base.py
│   │   ├── kmeans.py
│   │   ├── lib/
│   │   │   ├── __init__.py
│   │   │   └── spark-ml-streaming_2.10-0.1.0.jar
│   │   └── util.py
│   ├── requirements.txt
│   └── setup.py
└── scala/
    ├── build.sbt
    ├── project/
    │   └── build.properties
    └── src/
        └── main/
            └── scala/
                └── spark/
                    └── mlstreaming/
                        ├── KMeans.scala
                        └── Utils.scala

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
scala/target
scala/project/target
scala/project/project
scala/.idea
*.pyc
.idea
dist
spark_ml_streaming.egg-info

================================================
FILE: LICENSE
================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "{}"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2015 Jeremy Freeman

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

================================================
FILE: README.md
================================================
[![Join the chat at https://gitter.im/freeman-lab/spark-ml-streaming](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/freeman-lab/spark-ml-streaming?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

## Visualize streaming machine learning in Spark

![two-dimensional-demo](https://github.com/freeman-lab/spark-streaming-demos/blob/master/animations/databricks-blog-post/4-five-clusters.gif)
![one-dimensional-demo](https://github.com/freeman-lab/spark-streaming-demos/blob/master/animations/databricks-blog-post/6-half-life-5p0.gif)

### About
This Python app generates data, analyzes it in Spark Streaming, and visualizes the results with Lightning. The analyses use streaming machine learning algorithms included with Spark as of version 1.2. The demos are designed for local use, but the same algorithms can run at scale on a cluster with millions of records.

### How to use
To run these demos, you need:

* A working installation of [Spark](http://spark.apache.org/downloads.html)
* A running [Lightning](http://lightning-viz.org) server
* An installation of Python with standard scientific computing libraries (NumPy, SciPy, ScikitLearn)

With those three things in place, install using:

	pip install spark-ml-streaming

Then set `SPARK_HOME` to your Spark installation, and start an executable:

	streaming-kmeans -l <lighting_host>

Where `lightning_host` is the address of your Lightning server. After it starts, your browser will open, and you should see data appear shortly. 

Try running with different settings, for example, to run a 1-d version with 4 clusters and a half-life of 10 points:

	streaming-kmeans -p <temporary_path> -l <lighting_host> -nc 4 -nd 1 -hl 10 -tu points

Where `temporary_path` is where data will be written / read, if not specified the current tmp directory will be used (See Python [tempfile.gettempdir()](https://docs.python.org/2/library/tempfile.html))

2D data will make a scatter plot and 1D data will make a line plot. You can set this with -nd.

To see all options type:

	streaming-kmeans -h

### Build
The demo relies on a Scala package included pre-built inside `python/mlstreaming/lib`. To rebuild it, use sbt:

	cd scala
	sbt package


================================================
FILE: python/MANIFEST.in
================================================
include *.txt
include mlstreaming/lib/*.jar

================================================
FILE: python/bin/streaming-kmeans
================================================
#!/usr/bin/env python

import time
import subprocess
import argparse
import os
import tempfile

from lightning import Lightning

from mlstreaming import StreamingDemo
from mlstreaming.util import findspark, findjar, baseargs

def main():

    # parse arguments
    parser = argparse.ArgumentParser(description='Streaming KMeans demo.')
    parser = baseargs(parser)
    parser.add_argument('-nc', '--ncenters', type=int, default=3, required=False, 
        help='Number of cluster centers')
    parser.add_argument('-nd', '--ndims', type=int, default=2, required=False, 
        help='Number of dimensions')
    parser.add_argument('-rs', '--randomseed', type=int, default=None, required=False,
        help='Random seed')
    parser.add_argument('-sd', '--std', type=float, default=0.3, required=False,
        help='Standard deviation of points')
    parser.add_argument('-up', '--update', type=str, choices=('jump', 'drift', 'none'), default='drift', required=False,
        help='Update behavior')
    parser.add_argument('-a', '--autoopen', type=bool, choices=(True, False), default=True, required=False,
        help='Whether to automatically open Lightning session on a browser')
    args = parser.parse_args()

    # basic setup
    sparkhome = findspark()
    jar = findjar()
    
    # set up lightning
    if args.lightning:
        lgn = Lightning(args.lightning)
        lgn.create_session('streaming-kmeans')
        if (args.autoopen):
            lgn.session.open()
    else:
        lgn = None

    # set temp path
    path = args.path
    if not path or path == '':
        path = tempfile.gettempdir()
    tmpdir = os.path.join(path, 'streamkmeans')

    # setup the demo
    s = StreamingDemo.make('kmeans', npoints=args.npoints, nbatches=args.nbatches)
    s.setup(tmpdir, overwrite=args.overwrite)
    s.params(ncenters=args.ncenters, ndims=args.ndims, std=args.std, seed=args.randomseed, update=args.update)

    # setup the spark job
    sparkSubmit = sparkhome + "/bin/spark-submit"
    sparkArgs = ["--class", "spark.mlstreaming.KMeans", jar]
    demoArgs = [s.datain, s.dataout, str(args.batchtime), str(args.ncenters), str(args.ndims), str(args.halflife), str(args.timeunit)]
    cmd = [sparkSubmit] + sparkArgs + demoArgs

    try:
        # start the spark job    
        p = subprocess.Popen(cmd)
        # wait for spark streaming to start up
        time.sleep(4)
        # start the demo
        s.run(lgn)

    finally:

       p.kill()

if __name__ == "__main__":
    main()



================================================
FILE: python/mlstreaming/__init__.py
================================================
from mlstreaming.base import StreamingDemo

__version__ = '0.1.0'

================================================
FILE: python/mlstreaming/base.py
================================================
import os
import shutil


class StreamingDemo(object):

    def __init__(self, npoints=50, nbatches=5):
        self.npoints = npoints
        self.nbatches = nbatches

    def params(*args, **kwargs):
        """ Get analysis-specific parameters """
        raise NotImplementedError

    def run(*args, **kwargs):
        """ Run the streaming demo """
        raise NotImplementedError

    @staticmethod
    def make(demoname, *args, **kwargs):
        """ Create a streaming demo """

        from mlstreaming.kmeans import StreamingKMeans

        DEMOS = {
            'kmeans': StreamingKMeans
        }
        return DEMOS[demoname](*args, **kwargs)

    def setup(self, path, overwrite=False):
        """ Setup paths for a streaming demo where temporary data will be read / written"""

        if os.path.isdir(path):
            if overwrite:
                shutil.rmtree(path)
                os.mkdir(path)
            else:
                raise Exception('Base directory %s already exists and overwrite is set to False' % path)
        else:
            os.mkdir(path)

        datain = os.path.join(path, 'input')
        dataout = os.path.join(path, 'output')
        if os.path.isdir(datain):
            shutil.rmtree(datain)
        if os.path.isdir(dataout):
            shutil.rmtree(dataout)
        os.mkdir(datain)
        os.mkdir(dataout)
        self.datain = datain
        self.dataout = dataout
        return self

    def writepoints(self, pts, i):
        """ Write data points in a form that can be read by MLlib's vector parser  """

        f = file(os.path.join(self.datain, 'batch%g.txt' % i), 'w')
        s = map(lambda p: ",".join(str(p).split()).replace('[,', '[').replace(',]', ']'), pts)
        tmp = "\n".join(s)
        f.write(tmp)
        f.close()



================================================
FILE: python/mlstreaming/kmeans.py
================================================
import time

from numpy import asarray, array, vstack, hstack, size, random, argsort, ones, argmin, sin, cos, pi
from scipy.spatial.distance import cdist
from sklearn.datasets import make_blobs

from mlstreaming.base import StreamingDemo
from mlstreaming.util import loadrecent


class StreamingKMeans(StreamingDemo):

    def params(self, ncenters=3, ndims=2, std=0.2, seed=None, update='drift', interval=15, transition=None):
        """
        Set up parameters for a streaming kmeans algorithm demo.

        Parameters
        ----------
        ncenters : int, or array-like (ncenters, ndims)
          Number of clusters as an integer, or an array of starting cluster centers.
          If given as an integer, cluster centers will be determined randomly.

        ndims : int
          Number of dimensions

        std : scalar
          Cluster standard deviation

        """

        random.seed(seed)
        if size(ncenters) == 1:
            centers = random.randn(ncenters, ndims) * 2
        else:
            centers = asarray(ncenters)
            ncenters = centers.shape[0]
        self.centers = centers
        self.ncenters = ncenters
        self.ndims = ndims
        self.std = std
        self.update = update
        self.interval = interval
        self.transition = transition

        return self

    def run(self, lgn=None):

        viz = None

        closestpoint = lambda centers, p: argmin(cdist(centers, array([p])))

        centers = self.centers
        modeltime = 0
        model = []

        # loop over batches
        for i in range(1, self.nbatches):

            print('generating batch %g' % i)

            # drift means the points will slowly drift by adding noise to the position
            if self.update == 'drift':
                centers += random.randn(centers.shape[0], centers.shape[1]) * 0.15

            # jump means every 15 batches the points will shift
            if self.update == 'jump':
                if i % self.interval == 0:
                    if self.transition:
                        centers = asarray(self.transition)
                    else:
                        base = random.rand(self.ncenters * self.ndims) * 1 + 2
                        delta = asarray([-d if random.rand() > 0.5 else d for d in base])\
                            .reshape(self.ncenters, self.ndims)
                        centers = centers + delta

            # generate the points by sampling from the clusters and write to disk
            npoints = self.npoints
            pts, labels = make_blobs(npoints, self.ndims, centers, cluster_std=self.std)
            self.writepoints(pts, i)
            time.sleep(1)

            # get the latest model (after waiting)
            model, modeltime = loadrecent(self.dataout + '/*-model.txt', modeltime, model)

            # plot an update (if we got a valid model)
            if len(model) == self.ncenters:

                clrs = labels
                order = argsort(labels)
                clrs = clrs[order]
                pts = pts[order]
                s = ones(self.npoints) * 10

                if self.ndims == 1:
                    pts = vstack((pts, model[:,None]))
                else:
                    pts = vstack((pts, model))
                clrs = hstack((clrs, ones(self.ncenters) * 5))
                s = hstack((s, ones(self.ncenters) * 10))

                # wait a few iterations before plotting
                if (lgn is not None) & (i > 5):

                    # scatter plot for two dimensions
                    if self.ndims == 2:
                        if viz is None:
                            viz = lgn.scatterstreaming(pts[:, 0], pts[:, 1], label=clrs, size=s)
                        else:
                            viz.append(pts[:, 0], pts[:, 1], label=clrs, size=s)

                    # line plot for one dimension
                    elif self.ndims == 1:
                        if viz is None:
                            viz = lgn.linestreaming(pts, label=clrs, size=s/2)
                        else:
                            viz.append(pts, label=clrs, size=s/2)

                    else:
                        raise Exception('Plotting only supported with 1 or 2 dimensions')


================================================
FILE: python/mlstreaming/lib/__init__.py
================================================


================================================
FILE: python/mlstreaming/util.py
================================================
import os
import glob

from numpy import loadtxt


def findspark():
  
    sparkhome = os.getenv("SPARK_HOME")
    if sparkhome is None:
        raise Exception("The environment variable SPARK_HOME must be set to the Spark installation directory")
    else:
        return sparkhome


def findjar():
  
    calldir = os.path.dirname(os.path.realpath(__file__))
    jardir = os.path.join(calldir, 'lib', '*.jar')
    jar = glob.glob(jardir)
    if len(jar) == 0 or not os.path.exists(jar[0]):
        raise Exception("Cannot find jar, looking at %s" % jar)
    else:
        return jar[0]


def loadrecent(filename, oldtime, oldoutput):

    try:
        fname = max(glob.iglob(filename), key=os.path.getctime)
    except:
        print('No file found')
        return [], oldtime

    newtime = os.path.getctime(fname)
    if not (newtime > oldtime):
        print('File is not new')
        return oldoutput, oldtime

    try:
        f = open(fname)
        if os.fstat(f.fileno()).st_size == 0:
            print('File is empty')
            return [], oldtime
    except:
        print('Cannot load file')
        return [], oldtime

    prediction = loadtxt(fname, delimiter=',')
    return prediction, newtime


def baseargs(parser):

    parser.add_argument('-p', '--path', type=str, default=None, required=False,
                        help='Temporary location to store outputs')
    parser.add_argument('-o', '--overwrite', type=bool, choices=(True, False), default=True, required=False,
                        help='Whether to overwrite the temporary location if it already exists')
    parser.add_argument('-lgn', '--lightning', type=str, default=None, required=False,
                        help='Lightning server for visualization')
    parser.add_argument('-bt', '--batchtime', type=int, default=1, required=False,
                        help='Frequency of updates')
    parser.add_argument('-np', '--npoints', type=int, default=50, required=False,
                        help='Number of data points per batch')
    parser.add_argument('-nb', '--nbatches', type=int, default=40, required=False,
                        help='Number of batches')
    parser.add_argument('-hl', '--halflife', type=float, default=1, required=False,
                        help='Half life for streaming updates')
    parser.add_argument('-tu', '--timeunit', type=str, default='batches', choices=('batches', 'points'), required=False,
                        help='Time unit for streaming updates')
    return parser



================================================
FILE: python/requirements.txt
================================================
argparse
numpy
scipy
scikit-learn
lightning-python

================================================
FILE: python/setup.py
================================================
#!/usr/bin/env python

from setuptools import setup
import mlstreaming

setup(
    name='spark-ml-streaming',
    version=str(mlstreaming.__version__),
    description='A Python library for visualizing streaming machine learning in Spark',
    author='Jeremy Freeman',
    author_email='the.freeman.lab@gmail.com',
    url='https://github.com/freeman-lab/spark-ml-streaming',
    packages=['mlstreaming',
              'mlstreaming.lib'
              ],
    scripts = ['bin/streaming-kmeans'],
    package_data = {'mlstreaming.lib': ['spark-ml-streaming_2.10-' + str(mlstreaming.__version__) + '.jar']},
    install_requires=open('requirements.txt').read().split()
)

================================================
FILE: scala/build.sbt
================================================
name := "spark-ml-streaming"

version := "0.1.0"

scalaVersion := "2.10.3"

ivyXML := <dependency org="org.eclipse.jetty.orbit" name="javax.servlet" rev="3.0.0.v201112011016">
<artifact name="javax.servlet" type="orbit" ext="jar"/>
</dependency>

libraryDependencies += "org.apache.hadoop" % "hadoop-client" % "1.0.4"

libraryDependencies += "org.apache.spark" %% "spark-core" % "1.2.0" 

libraryDependencies += "org.apache.spark" %% "spark-streaming" % "1.2.0" 

libraryDependencies += "org.apache.spark" % "spark-mllib_2.10" % "1.2.0"

libraryDependencies += "org.scalatest" % "scalatest_2.10" % "2.0" % "test"

libraryDependencies += "io.spray" %% "spray-json" % "1.2.5"

libraryDependencies += "org.jblas" % "jblas" % "1.2.3"

resolvers += "spray" at "http://repo.spray.io/"

resolvers ++= Seq(
  "Akka Repository" at "http://repo.akka.io/releases/",
  "Spray Repository" at "http://repo.spray.cc/")


================================================
FILE: scala/project/build.properties
================================================
sbt.version=0.12.4


================================================
FILE: scala/src/main/scala/spark/mlstreaming/KMeans.scala
================================================
package spark.mlstreaming

import java.util.Calendar

import org.apache.spark.SparkConf
import org.apache.spark.mllib.clustering.StreamingKMeans
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.streaming.{Seconds, StreamingContext}


/**
 * Demo of streaming k-means with Spark Streaming.
 * Reads data from one directory, and prints models and predictions to another.
 *
 * Run via Python executable in the top-level project directory
 *
 */

object KMeans {

  def main(args: Array[String]) {
    if (args.length != 7) {
      System.err.println(
        "Usage: KMeans " +
          "<inputDir> <outputDir> <batchDuration> <numClusters> <numDimensions> <halfLife> <batchUnit>")
      System.exit(1)
    }

    val (inputDir, outputDir, batchDuration, numClusters, numDimensions, halfLife, timeUnit) =
      (args(0), args(1), args(2).toLong, args(3).toInt, args(4).toInt, args(5).toFloat, args(6))

    val conf = new SparkConf().setMaster("local").setAppName("KMeansDemo")
    val ssc = new StreamingContext(conf, Seconds(batchDuration))

    val trainingData = ssc.textFileStream(inputDir).map(Vectors.parse)

    val model = new StreamingKMeans()
      .setK(numClusters)
      .setHalfLife(halfLife, timeUnit)
      .setRandomCenters(numDimensions, 0.0)

    model.trainOn(trainingData)

    val predictions = model.predictOn(trainingData)

    predictions.foreachRDD { rdd =>
      val modelString = model.latestModel().clusterCenters
        .map(c => c.toString.slice(1, c.toString.length-1)).mkString("\n")
      val predictString = rdd.map(p => p.toString).collect().mkString("\n")
      val dateString = Calendar.getInstance().getTime.toString.replace(" ", "-").replace(":", "-")
      Utils.printToFile(outputDir, dateString + "-model", modelString)
      Utils.printToFile(outputDir, dateString + "-predictions", predictString)
    }

    ssc.start()
    ssc.awaitTermination()
  }
}


================================================
FILE: scala/src/main/scala/spark/mlstreaming/Utils.scala
================================================
package spark.mlstreaming

import java.io.{FileWriter, BufferedWriter, File}

/**
 * Utilities for streaming demos
 */

object Utils {

  def printToFile(pathName: String, fileName: String, contents: String) = {
    val file = new File(pathName + "/" + fileName + ".txt")
    val bw = new BufferedWriter(new FileWriter(file))
    bw.write(contents)
    bw.close()
  }


}
Download .txt
gitextract_2wsty9xh/

├── .gitignore
├── LICENSE
├── README.md
├── python/
│   ├── MANIFEST.in
│   ├── bin/
│   │   └── streaming-kmeans
│   ├── mlstreaming/
│   │   ├── __init__.py
│   │   ├── base.py
│   │   ├── kmeans.py
│   │   ├── lib/
│   │   │   ├── __init__.py
│   │   │   └── spark-ml-streaming_2.10-0.1.0.jar
│   │   └── util.py
│   ├── requirements.txt
│   └── setup.py
└── scala/
    ├── build.sbt
    ├── project/
    │   └── build.properties
    └── src/
        └── main/
            └── scala/
                └── spark/
                    └── mlstreaming/
                        ├── KMeans.scala
                        └── Utils.scala
Download .txt
SYMBOL INDEX (14 symbols across 3 files)

FILE: python/mlstreaming/base.py
  class StreamingDemo (line 5) | class StreamingDemo(object):
    method __init__ (line 7) | def __init__(self, npoints=50, nbatches=5):
    method params (line 11) | def params(*args, **kwargs):
    method run (line 15) | def run(*args, **kwargs):
    method make (line 20) | def make(demoname, *args, **kwargs):
    method setup (line 30) | def setup(self, path, overwrite=False):
    method writepoints (line 54) | def writepoints(self, pts, i):

FILE: python/mlstreaming/kmeans.py
  class StreamingKMeans (line 11) | class StreamingKMeans(StreamingDemo):
    method params (line 13) | def params(self, ncenters=3, ndims=2, std=0.2, seed=None, update='drif...
    method run (line 47) | def run(self, lgn=None):

FILE: python/mlstreaming/util.py
  function findspark (line 7) | def findspark():
  function findjar (line 16) | def findjar():
  function loadrecent (line 27) | def loadrecent(filename, oldtime, oldoutput):
  function baseargs (line 53) | def baseargs(parser):
Condensed preview — 17 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (31K chars).
[
  {
    "path": ".gitignore",
    "chars": 112,
    "preview": "scala/target\nscala/project/target\nscala/project/project\nscala/.idea\n*.pyc\n.idea\ndist\nspark_ml_streaming.egg-info"
  },
  {
    "path": "LICENSE",
    "chars": 11343,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README.md",
    "chars": 2227,
    "preview": "[![Join the chat at https://gitter.im/freeman-lab/spark-ml-streaming](https://badges.gitter.im/Join%20Chat.svg)](https:/"
  },
  {
    "path": "python/MANIFEST.in",
    "chars": 43,
    "preview": "include *.txt\ninclude mlstreaming/lib/*.jar"
  },
  {
    "path": "python/bin/streaming-kmeans",
    "chars": 2513,
    "preview": "#!/usr/bin/env python\n\nimport time\nimport subprocess\nimport argparse\nimport os\nimport tempfile\n\nfrom lightning import Li"
  },
  {
    "path": "python/mlstreaming/__init__.py",
    "chars": 65,
    "preview": "from mlstreaming.base import StreamingDemo\n\n__version__ = '0.1.0'"
  },
  {
    "path": "python/mlstreaming/base.py",
    "chars": 1803,
    "preview": "import os\nimport shutil\n\n\nclass StreamingDemo(object):\n\n    def __init__(self, npoints=50, nbatches=5):\n        self.npo"
  },
  {
    "path": "python/mlstreaming/kmeans.py",
    "chars": 4265,
    "preview": "import time\n\nfrom numpy import asarray, array, vstack, hstack, size, random, argsort, ones, argmin, sin, cos, pi\nfrom sc"
  },
  {
    "path": "python/mlstreaming/lib/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "python/mlstreaming/util.py",
    "chars": 2516,
    "preview": "import os\nimport glob\n\nfrom numpy import loadtxt\n\n\ndef findspark():\n  \n    sparkhome = os.getenv(\"SPARK_HOME\")\n    if sp"
  },
  {
    "path": "python/requirements.txt",
    "chars": 50,
    "preview": "argparse\nnumpy\nscipy\nscikit-learn\nlightning-python"
  },
  {
    "path": "python/setup.py",
    "chars": 666,
    "preview": "#!/usr/bin/env python\n\nfrom setuptools import setup\nimport mlstreaming\n\nsetup(\n    name='spark-ml-streaming',\n    versio"
  },
  {
    "path": "scala/build.sbt",
    "chars": 904,
    "preview": "name := \"spark-ml-streaming\"\n\nversion := \"0.1.0\"\n\nscalaVersion := \"2.10.3\"\n\nivyXML := <dependency org=\"org.eclipse.jetty"
  },
  {
    "path": "scala/project/build.properties",
    "chars": 19,
    "preview": "sbt.version=0.12.4\n"
  },
  {
    "path": "scala/src/main/scala/spark/mlstreaming/KMeans.scala",
    "chars": 1919,
    "preview": "package spark.mlstreaming\n\nimport java.util.Calendar\n\nimport org.apache.spark.SparkConf\nimport org.apache.spark.mllib.cl"
  },
  {
    "path": "scala/src/main/scala/spark/mlstreaming/Utils.scala",
    "chars": 372,
    "preview": "package spark.mlstreaming\n\nimport java.io.{FileWriter, BufferedWriter, File}\n\n/**\n * Utilities for streaming demos\n */\n\n"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the freeman-lab/spark-ml-streaming GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 17 files (28.1 KB), approximately 7.0k tokens, and a symbol index with 14 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!