【Spark機器學習速成寶典】模型篇04朴素貝葉斯【Naive Bayes】(Python版)


目錄

  朴素貝葉斯原理

  朴素貝葉斯代碼(Spark Python)


 

朴素貝葉斯原理

   詳見博文:http://www.cnblogs.com/itmorn/p/7905975.html

 返回目錄

 

朴素貝葉斯代碼(Spark Python) 

  

  代碼里數據:https://pan.baidu.com/s/1jHWKG4I 密碼:acq1

 

# -*-coding=utf-8 -*-  
from pyspark import SparkConf, SparkContext
sc = SparkContext('local')

from pyspark.mllib.classification import NaiveBayes, NaiveBayesModel
from pyspark.mllib.util import MLUtils

# Load and parse the data file.
data = MLUtils.loadLibSVMFile(sc, "data/mllib/sample_libsvm_data.txt")
'''
每一行使用以下格式表示一個標記的稀疏特征向量
label index1:value1 index2:value2 ...

tempFile.write(b"+1 1:1.0 3:2.0 5:3.0\\n-1\\n-1 2:4.0 4:5.0 6:6.0")
>>> tempFile.flush()
>>> examples = MLUtils.loadLibSVMFile(sc, tempFile.name).collect()
>>> tempFile.close()
>>> examples[0]
LabeledPoint(1.0, (6,[0,2,4],[1.0,2.0,3.0]))
>>> examples[1]
LabeledPoint(-1.0, (6,[],[]))
>>> examples[2]
LabeledPoint(-1.0, (6,[1,3,5],[4.0,5.0,6.0]))
'''
# Split data approximately into training (60%) and test (40%) 將數據集按照6:4的比例分成訓練集和測試集
training, test = data.randomSplit([0.6, 0.4])

# Train a naive Bayes model. 訓練朴素貝葉斯模型
model = NaiveBayes.train(training, 1.0)

# Make prediction and test accuracy. 預測和測試准確率
predictionAndLabel = test.map(lambda p: (model.predict(p.features), p.label))
accuracy = 1.0 * predictionAndLabel.filter(lambda pl: pl[0] == pl[1]).count() / test.count()
print('model accuracy {}'.format(accuracy)) #1

# Save and load model 保存和加載模型
output_dir = 'myNaiveBayesModel'
model.save(sc, output_dir)
sameModel = NaiveBayesModel.load(sc, output_dir)
predictionAndLabel = test.map(lambda p: (sameModel.predict(p.features), p.label))
accuracy = 1.0 * predictionAndLabel.filter(lambda pl: pl[0] == pl[1]).count() / test.count()
print('sameModel accuracy {}'.format(accuracy)) #1

 

 返回目錄

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM