LR判断垃圾邮件spark代码

Spark-MLlib实例——逻辑回归,应用于二元分类的情况,这里以垃圾邮件分类为例,即是否为垃圾邮件两种情况。


1、垃圾邮件分类,使用Spark-MLlib中的两个函数: 

1)HashingTF: 从文本数据构建词频(term frequency)特征向量

2)LogisticRegressionWithSGD: 使用随机梯度下降法(Stochastic Gradient Descent),实现逻辑回归。


2、训练原数据集

垃圾邮件例子 spam.txt

[plain]  view plain  copy
  1. Dear sir, I am a Prince in a far kingdom you have not heard of.  I want to send you money via wire transfer so please ...  
  2. Get Viagra real cheap!  Send money right away to ...  
  3. Oh my gosh you can be really strong too with these drugs found in the rainforest. Get them cheap right now ...  
  4. YOUR COMPUTER HAS BEEN INFECTED!  YOU MUST RESET YOUR PASSWORD.  Reply to this email with your password and SSN ...  
  5. THIS IS NOT A SCAM!  Send money and get access to awesome stuff really cheap and never have to ...  

非垃圾邮件例子 normal.txt

[plain]  view plain  copy
  1. Dear Spark Learner, Thanks so much for attending the Spark Summit 2014!  Check out videos of talks from the summit at ...  
  2. Hi Mom, Apologies for being late about emailing and forgetting to send you the package.  I hope you and bro have been ...  
  3. Wow, hey Fred, just heard about the Spark petabyte sort.  I think we need to take time to try it out immediately ...  
  4. Hi Spark user list, This is my first question to this list, so thanks in advance for your help!  I tried running ...  
  5. Thanks Tom for your email.  I need to refer you to Alice for this one.  I haven't yet figured out that part either ...  
  6. Good job yesterday!  I was attending your talk, and really enjoyed it.  I want to try out GraphX ...  
  7. Summit demo got whoops from audience!  Had to let you know. --Joe  


然后,根据词频把每个文件中的文本转换为特征向量,然后训练出一个可以把两类消息分开的逻辑回归模型。


3、垃圾邮件分类器

[java]  view plain  copy
  1. import org.apache.spark.{ SparkConf, SparkContext }  
  2. import org.apache.spark.mllib.classification.LogisticRegressionWithSGD  
  3. import org.apache.spark.mllib.feature.HashingTF  
  4. import org.apache.spark.mllib.regression.LabeledPoint  
  5. import org.apache.log4j.Level  
  6. import org.apache.log4j.Logger  
  7.   
  8. object MLlib {  
  9.   
  10.   def main(args: Array[String]) {  
  11.     Logger.getLogger("org.apache.spark").setLevel(Level.ERROR);  
  12.     Logger.getLogger("org.eclipse.jetty.server").setLevel(Level.ERROR);  
  13.   
  14.     val conf = new SparkConf().setAppName("MLlib")  
  15.   
  16.     val sc = new SparkContext(conf)  
  17.   
  18.     val spam = sc.textFile("spam.txt")  
  19.     val ham = sc.textFile("Dham.txt")  
  20.   
  21.     //创建一个HashingTF实例来把邮件文本映射为包含25000特征的向量  
  22.     val tf = new HashingTF(numFeatures = 25000)  
  23.      
  24.     //各邮件都被切分为单词,每个单词被映射为一个特征  
  25.     val spamFeatures = spam.map(email => tf.transform(email.split(" ")))  
  26.     val hamFeatures = ham.map(email => tf.transform(email.split(" ")))  
  27.   
  28.     //创建LabeledPoint数据集分别存放垃圾邮件(spam)和正常邮件(ham)的例子  
  29.     spamFeatures.collect().foreach { x => print(x + " ,") }  
  30.     hamFeatures.collect().foreach { x => print(x + " ,") }  
  31.   
  32.     // Create LabeledPoint datasets for positive (spam) and negative (ham) examples.  
  33.     val positiveExamples = spamFeatures.map(features => LabeledPoint(1, features))  
  34.     val negativeExamples = hamFeatures.map(features => LabeledPoint(0, features))  
  35.     val trainingData = positiveExamples.union(negativeExamples)  
  36.     trainingData.cache() // 逻辑回归是迭代算法,所以缓存训练数据的RDD  
  37.   
  38.       
  39.     //使用SGD算法运行逻辑回归  
  40.     val lrLearner = new LogisticRegressionWithSGD()  
  41.     val model = lrLearner.run(trainingData)  
  42.   
  43.     //以垃圾邮件和正常邮件的例子分别进行测试。  
  44.     val posTestExample = tf.transform("O M G GET cheap stuff by sending money to ...".split(" "))  
  45.     val negTestExample = tf.transform("Hi Dad, I started studying Spark the other ...".split(" "))  
  46.   
  47.     val posTest1Example = tf.transform("I really wish well to all my friends.".split(" "))  
  48.     val posTest2Example = tf.transform("He stretched into his pocket for some money.".split(" "))  
  49.     val posTest3Example = tf.transform("He entrusted his money to me.".split(" "))  
  50.     val posTest4Example = tf.transform("Where do you keep your money?".split(" "))  
  51.     val posTest5Example = tf.transform("She borrowed some money of me.".split(" "))  
  52.   
  53.     //首先使用,一样的HashingTF特征来得到特征向量,然后对该向量应用得到的模型  
  54.     println(s"Prediction for positive test example: ${model.predict(posTestExample)}")  
  55.     println(s"Prediction for negative test example: ${model.predict(negTestExample)}")  
  56.   
  57.     println(s"posTest1Example for negative test example: ${model.predict(posTest1Example)}")  
  58.     println(s"posTest2Example for negative test example: ${model.predict(posTest2Example)}")  
  59.     println(s"posTest3Example for negative test example: ${model.predict(posTest3Example)}")  
  60.     println(s"posTest4Example for negative test example: ${model.predict(posTest4Example)}")  
  61.     println(s"posTest5Example for negative test example: ${model.predict(posTest5Example)}")  
  62.   
  63.     sc.stop()  
  64.   }  
  65. }  


分析结果:

[plain]  view plain  copy
  1. Prediction for positive test example: 1.0  
  2. Prediction for negative test example: 0.0  
  3. posTest1Example for negative test example: 0.0  
  4. posTest2Example for negative test example: 0.0  
  5. posTest3Example for negative test example: 1.0  
  6. posTest4Example for negative test example: 0.0  
  7. posTest5Example for negative test example: 1.0  

1 即为 垃圾邮件, 0 为正常邮件。
基于贝叶斯、支持向量机(SVM)和逻辑回归(LR)的垃圾邮件分类可以分为以下几个步骤: 首先,我们需要收集训练数据集,该数据集包括一些已标记为垃圾邮件和非垃圾邮件的样本。对于贝叶斯方法,我们需要统计每个单词在垃圾邮件和非垃圾邮件中出现的频率,并计算出每个单词在垃圾和非垃圾邮件中的条件概率。对于SVM和LR方法,我们需要将邮件的特征提取为数值向量,如词频、字符数、链接数量等。 在训练阶段,对于贝叶斯方法,我们根据训练集中垃圾邮件和非垃圾邮件的词频统计数据,计算出每个单词出现的概率。对于SVM和LR方法,我们使用训练集的特征向量和相应的标签进行模型训练。 在测试阶段,对于贝叶斯方法,我们根据训练阶段计算得到的单词概率,结合测试邮件的单词频率来计算垃圾和非垃圾邮件的条件概率,并根据概率进行分类。对于SVM和LR方法,我们使用训练阶段得到的模型对测试集进行预测,并根据预测结果判断邮件是否为垃圾邮件。 贝叶斯方法基于贝叶斯定理,通过计算单词在垃圾和非垃圾邮件中的概率来进行分类。SVM方法通过在高维空间中找到一个最优的超平面,实现垃圾邮件和非垃圾邮件的分割。LR方法利用对数几率函数来建立一个线性模型,用于将邮件分类为垃圾或非垃圾。 在实际应用中,这些方法在垃圾邮件分类中表现良好,但也存在一些限制。贝叶斯方法对于单词顺序不敏感,如果测试邮件中存在新的单词,将无法给出准确的分类。SVM和LR方法对于特征选择较为敏感,需要在特征提取阶段精心选择合适的特征。此外,模型的性能还受到数据集的大小和质量等因素的影响。综上所述,选择适合的方法和优化相参数是确保垃圾邮件分类准确性的键。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值