|
| 1 | +# |
| 2 | +# Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | +# contributor license agreements. See the NOTICE file distributed with |
| 4 | +# this work for additional information regarding copyright ownership. |
| 5 | +# The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | +# (the "License"); you may not use this file except in compliance with |
| 7 | +# the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +# |
| 17 | + |
| 18 | +""" |
| 19 | +Correlations using MLlib. |
| 20 | +""" |
| 21 | + |
| 22 | +import sys |
| 23 | + |
| 24 | +from pyspark import SparkContext |
| 25 | +from pyspark.mllib.regression import LabeledPoint |
| 26 | +from pyspark.mllib.stat import Statistics |
| 27 | +from pyspark.mllib.util import MLUtils |
| 28 | + |
| 29 | + |
| 30 | +if __name__ == "__main__": |
| 31 | + if len(sys.argv) not in [1,2]: |
| 32 | + print >> sys.stderr, "Usage: correlations (<file>)" |
| 33 | + exit(-1) |
| 34 | + sc = SparkContext(appName="PythonCorrelations") |
| 35 | + if len(sys.argv) == 2: |
| 36 | + filepath = sys.argv[1] |
| 37 | + else: |
| 38 | + filepath = 'data/mllib/sample_linear_regression_data.txt' |
| 39 | + corrType = 'pearson' |
| 40 | + |
| 41 | + points = MLUtils.loadLibSVMFile(sc, filepath)\ |
| 42 | + .map(lambda lp: LabeledPoint(lp.label, lp.features.toArray())) |
| 43 | + |
| 44 | + print |
| 45 | + print 'Summary of data file: ' + filepath |
| 46 | + print '%d data points' % points.count() |
| 47 | + |
| 48 | + # Statistics (correlations) |
| 49 | + print |
| 50 | + print 'Correlation (%s) between label and each feature' % corrType |
| 51 | + print 'Feature\tCorrelation' |
| 52 | + numFeatures = points.take(1)[0].features.size |
| 53 | + labelRDD = points.map(lambda lp: lp.label) |
| 54 | + for i in range(numFeatures): |
| 55 | + featureRDD = points.map(lambda lp: lp.features[i]) |
| 56 | + corr = Statistics.corr(labelRDD, featureRDD, corrType) |
| 57 | + print '%d\t%g' % (i, corr) |
| 58 | + print |
| 59 | + |
| 60 | + sc.stop() |
0 commit comments