Back to home page

OSCL-LXR

 
 

    


0001 #
0002 # Licensed to the Apache Software Foundation (ASF) under one or more
0003 # contributor license agreements.  See the NOTICE file distributed with
0004 # this work for additional information regarding copyright ownership.
0005 # The ASF licenses this file to You under the Apache License, Version 2.0
0006 # (the "License"); you may not use this file except in compliance with
0007 # the License.  You may obtain a copy of the License at
0008 #
0009 #    http://www.apache.org/licenses/LICENSE-2.0
0010 #
0011 # Unless required by applicable law or agreed to in writing, software
0012 # distributed under the License is distributed on an "AS IS" BASIS,
0013 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014 # See the License for the specific language governing permissions and
0015 # limitations under the License.
0016 #
0017 
0018 """
0019 Isotonic Regression Example.
0020 """
0021 from __future__ import print_function
0022 
0023 from pyspark import SparkContext
0024 # $example on$
0025 import math
0026 from pyspark.mllib.regression import IsotonicRegression, IsotonicRegressionModel
0027 from pyspark.mllib.util import MLUtils
0028 # $example off$
0029 
0030 if __name__ == "__main__":
0031 
0032     sc = SparkContext(appName="PythonIsotonicRegressionExample")
0033 
0034     # $example on$
0035     # Load and parse the data
0036     def parsePoint(labeledData):
0037         return (labeledData.label, labeledData.features[0], 1.0)
0038 
0039     data = MLUtils.loadLibSVMFile(sc, "data/mllib/sample_isotonic_regression_libsvm_data.txt")
0040 
0041     # Create label, feature, weight tuples from input data with weight set to default value 1.0.
0042     parsedData = data.map(parsePoint)
0043 
0044     # Split data into training (60%) and test (40%) sets.
0045     training, test = parsedData.randomSplit([0.6, 0.4], 11)
0046 
0047     # Create isotonic regression model from training data.
0048     # Isotonic parameter defaults to true so it is only shown for demonstration
0049     model = IsotonicRegression.train(training)
0050 
0051     # Create tuples of predicted and real labels.
0052     predictionAndLabel = test.map(lambda p: (model.predict(p[1]), p[0]))
0053 
0054     # Calculate mean squared error between predicted and real labels.
0055     meanSquaredError = predictionAndLabel.map(lambda pl: math.pow((pl[0] - pl[1]), 2)).mean()
0056     print("Mean Squared Error = " + str(meanSquaredError))
0057 
0058     # Save and load model
0059     model.save(sc, "target/tmp/myIsotonicRegressionModel")
0060     sameModel = IsotonicRegressionModel.load(sc, "target/tmp/myIsotonicRegressionModel")
0061     # $example off$