1. 程式人生 > >Spark機器學習之分類與迴歸

Spark機器學習之分類與迴歸

本頁面介紹了分類和迴歸的演算法。 它還包括討論特定類別的演算法的部分,如線性方法,樹和集合體。

目錄

分類 Classification
-----------邏輯迴歸 Logistic regression
-------------------二項式邏輯迴歸 Binomial logistic regression
-------------------多項Logistic迴歸 Multinomial logistic regression
-----------決策樹分類器 Decision tree classifier
-----------隨機森林分類器 Random forest classifier
-----------梯度增強樹分類器 Gradient-boosted tree classifier
-----------多層感知器分類器 Multilayer perceptron classifier
---------一對一休息分類器(a.k.a.一對全)One-vs-Rest classifier (a.k.a. One-vs-All)
-----------樸素貝葉斯 Naive Bayes
迴歸 Regression
-----------線性迴歸 Linear regression
----------廣義線性迴歸 Generalized linear regression
-----------------可用的家庭 Available families
-----------決策樹迴歸 Decision tree regression
------------隨機森林迴歸 Random forest regression
-----------梯度增強樹迴歸 Gradient-boosted tree regression
-----------生存迴歸 Survival regression
-----------等滲迴歸 Isotonic regression
----------------例子 Examples
線性方法 Linear methods
決策樹 Decision trees
------------輸入和輸出 Inputs and Outputs
------------輸入列 Input Columns
------------輸出列 Output Columns
樹套 Tree Ensembles
隨機森林 Random Forests
-------------輸入和輸出 Inputs and Outputs
-------------輸入列 Input Columns
-------------輸出列(預測)Output Columns (Predictions)
梯度增強樹(GBT)Gradient-Boosted Trees (GBTs)
--------------輸入和輸出 Inputs and Outputs
-------------輸入列 Input Columns
-------------輸出列(預測)Output Columns (Predictions)

1、Classification 

1.1 Logistic regression

邏輯迴歸是預測分類的流行方法。 廣義線性模型的一個特例是預測結果的可能性。 在spark.ml邏輯迴歸中可以使用二項式邏輯迴歸來預測二進位制結果,也可以通過使用多項Logistic迴歸來預測多類結果。 使用系列引數在這兩種演算法之間進行選擇,或者將其設定為未設定,Spark將推斷出正確的變體。

通過將family引數設定為“多項式”,可以將多項Logistic迴歸用於二進位制分類。 它將產生兩組係數和兩個截距。

      當在具有常量非零列的資料集上對LogisticRegressionModel進行擬合時,Spark MLlib為常數非零列輸出零係數。 此行為與R glmnet相同,但與LIBSVM不同。

1.1.1 Binomial logistic regression

有關二項式邏輯迴歸實現的更多背景和更多細節,請參閱spark.mllib中邏輯迴歸的文件。


以下示例顯示瞭如何用彈性網路正則化來訓練二項分類的二項式和多項Logistic迴歸模型。 elasticNetParam對應於α,regParam對應於λ。

from pyspark.ml.classification import LogisticRegression

# Load training data
training = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt"
) lr = LogisticRegression(maxIter=10, regParam=0.3, elasticNetParam=0.8) # Fit the model lrModel = lr.fit(training) # Print the coefficients and intercept for logistic regression print("Coefficients: " + str(lrModel.coefficients)) print("Intercept: " + str(lrModel.intercept)) # We can also use the multinomial family for binary classification mlr = LogisticRegression(maxIter=10, regParam=0.3, elasticNetParam=0.8, family="multinomial") # Fit the model mlrModel = mlr.fit(training) # Print the coefficients and intercepts for logistic regression with multinomial family print("Multinomial coefficients: " + str(mlrModel.coefficientMatrix)) print("Multinomial intercepts: " + str(mlrModel.interceptVector))
查詢Spark repo中的“examples / src / main / python / ml / logistic_regression_with_elastic_net.py”的完整示例程式碼。
邏輯迴歸的spark.ml實現也支援在訓練集中提取模型的摘要。 請注意,在BinaryLogisticRegressionSummary中儲存為DataFrame的預測和度量標註為@transient,因此僅在驅動程式上可用。

LogisticRegressionTrainingSummary為LogisticRegressionModel提供了一個摘要。 目前,只支援二進位制分類。 將來會增加對多類別模型摘要的支援。
繼續前面的例子:

from pyspark.ml.classification import LogisticRegression

# Extract the summary from the returned LogisticRegressionModel instance trained
# in the earlier example
trainingSummary = lrModel.summary

# Obtain the objective per iteration
objectiveHistory = trainingSummary.objectiveHistory
print("objectiveHistory:")
for objective in objectiveHistory:
    print(objective)

# Obtain the receiver-operating characteristic as a dataframe and areaUnderROC.
trainingSummary.roc.show()
print("areaUnderROC: " + str(trainingSummary.areaUnderROC))

# Set the model threshold to maximize F-Measure
fMeasure = trainingSummary.fMeasureByThreshold
maxFMeasure = fMeasure.groupBy().max('F-Measure').select('max(F-Measure)').head()
bestThreshold = fMeasure.where(fMeasure['F-Measure'] == maxFMeasure['max(F-Measure)']) \
    .select('threshold').head()['threshold']
lr.setThreshold(bestThreshold)
1.1.2 Multinomial logistic regression

通過多項Logistic(softmax)迴歸支援多類分類。 在多項Logistic迴歸中,該演算法產生K係數集,或K×J矩陣,其中KK是結果類的數量,J是特徵數。 如果演算法與截距項擬合,則截距的長度K向量是可用的。

多項式係數可用作係數矩陣,截距可作為interceptVector使用

不支援用多項式族訓練的邏輯迴歸模型的係數和截距方法。 改用係數矩陣和interceptVector。

使用softmax函式建模結果類k∈1,2,...,K的條件概率。

P(Y=k|X,βk,β0k)=eβkX+β0kK1k=0eβkX+β0k

我們使用多項式響應模型將加權負對數似然值最小化,並用彈性網路懲罰來控制過擬合。

                  minβ,β0[i=1LwilogP(Y=yi|xi)]+λ[12(1α)||β||22+α||β||1]


以下示例展示瞭如何使用彈性網路正則化來訓練多元邏輯迴歸模型。

from pyspark.ml.classification import LogisticRegression

# Load training data
training = spark \
    .read \
    .format("libsvm") \
    .load("data/mllib/sample_multiclass_classification_data.txt")

lr = LogisticRegression(maxIter=10, regParam=0.3, elasticNetParam=0.8)

# Fit the model
lrModel = lr.fit(training)

# Print the coefficients and intercept for multinomial logistic regression
print("Coefficients: \n" + str(lrModel.coefficientMatrix))
print("Intercept: " + str(lrModel.interceptVector))

1.2 Decision tree classifier

決策樹是一種流行的分類和迴歸方法。 有關spark.ml實現的更多資訊,請參見決策樹部分。


以下示例以LibSVM格式載入資料集,將其拆分為訓練和測試集,在第一個資料集上訓練,然後對所保留的測試集進行評估。 我們使用兩個特徵轉換來準備資料; 這些幫助索引類別的標籤和分類功能,新增元資料到決策樹演算法可以識別的DataFrame。

from pyspark.ml import Pipeline
from pyspark.ml.classification import DecisionTreeClassifier
from pyspark.ml.feature import StringIndexer, VectorIndexer
from pyspark.ml.evaluation import MulticlassClassificationEvaluator

# Load the data stored in LIBSVM format as a DataFrame.
data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")

# Index labels, adding metadata to the label column.
# Fit on whole dataset to include all labels in index.
labelIndexer = StringIndexer(inputCol="label", outputCol="indexedLabel").fit(data)
# Automatically identify categorical features, and index them.
# We specify maxCategories so features with > 4 distinct values are treated as continuous.
featureIndexer =\
    VectorIndexer(inputCol="features", outputCol="indexedFeatures", maxCategories=4).fit(data)

# Split the data into training and test sets (30% held out for testing)
(trainingData, testData) = data.randomSplit([0.7, 0.3])


            
           

相關推薦

Spark機器學習分類迴歸

本頁面介紹了分類和迴歸的演算法。 它還包括討論特定類別的演算法的部分,如線性方法,樹和集合體。 目錄 分類 Classification -----------邏輯迴歸 Logistic regression -------------------二項式邏輯迴

機器學習分類迴歸區別闡述

很多人分不清楚分類和迴歸,我來講一下,我們經常會碰到這樣的問題: 1、如何將信用卡申請人分為低、中、高風險群? 2、如何預測哪些顧客在未來半年內會取消該公司服務,哪些電話使用者會申請增值服務? 3、如何預測具有某些特徵的顧客是否會購買一臺新的計算機? 4、如何預測病人應當接受三種

機器學習分類迴歸的解決區別

機器學習可以解決很多問題,其中最為重要的兩個是 迴歸與分類。 這兩個問題怎麼解決, 它們之間又有什麼區別呢? 以下舉幾個簡單的例子,以給大家一個概念 1. 線性迴歸 迴歸分析常用於分析兩個變數X和Y 之間的關係。 比如 X=房子大小 和 Y=房價 之間的關係, X=(公園人流量,公園門票票價

機器學習分類迴歸問題的區別聯絡

分類和迴歸問題之間存在重要差異。 從根本上說,分類是關於預測標籤,而回歸是關於預測數量。 我經常看到諸如以下問題: 如何計算迴歸問題的準確性? 像這樣的問題是沒有真正理解分類和迴歸之間的差異以及試圖衡量的準確度的症狀。 在本教程中,您將發現分類和迴歸之間的差異。

機器學習分類迴歸樹CART

CART:Classification and regression tree,分類與迴歸樹。(是二叉樹) CART是決策樹的一種,主要由特徵選擇,樹的生成和剪枝三部分組成。它主要用來處理分類和迴歸問題,下面對分別對其進行介紹。 1、迴歸樹:使用平方誤差最小準則

Spark機器學習--邏輯迴歸

Spark 利用邏輯迴歸做申請評分卡,上乾貨 val spark=SparkSession.builder().appName("LRTest").master("local[*]").getOrCreate() val sc=spark.sparkContex

機器學習SVM邏輯迴歸的聯絡和區別

  通常說的SVM與邏輯迴歸的聯絡一般指的是軟間隔的SVM與邏輯迴歸之間的關係,硬間隔的SVM應該是與感知機模型的區別和聯絡。而且工程中也不能要求所有的點都正確分類,訓練資料中噪聲的存在使得完全正確分類很可能造成過擬合。   軟間隔SVM與邏輯迴歸的聯絡   要說軟間隔SVM與聯絡就要看軟間隔SVM的緣由。

機器學習分類問題實戰(基於UCI Bank Marketing Dataset)

表示 般的 機構 文件 cnblogs opened csv文件 mas htm 導讀: 分類問題是機器學習應用中的常見問題,而二分類問題是其中的典型,例如垃圾郵件的識別。本文基於UCI機器學習數據庫中的銀行營銷數據集,從對數據集進行探索,數據預處理和特征工程,到學習

機器學習微積分概率論入門1

公式 連續 === 等於 產品 c2c ges cto mar 這兩門學科作為機器學習的必備科目! 一、微積分1夾逼定理通俗的講:A≤B≤C當求極限時,存在A=C,則說明B也等於A和C案例1: 案例2: 2 兩個重要極限 3 導數通俗的講就是曲線的斜率二階導數是斜率變化快慢

機器學習分類主要演算法對比

重要引用:Andrew Ng Courera Machine Learning;從機器學習談起;關於機器學習的討論;機器學習常見演算法分類彙總;LeNet Homepage;pluskid svm   首先讓我們瞻仰一下當今機器學習領域的執牛耳者:   這幅圖上的三人是當今機器學習界的

機器學習一元線性迴歸

概述 線性迴歸是利用數理統計中迴歸分析,來確定兩種或兩種以上變數間相互依賴的定量關係的一種統計分析方法,運用十分廣泛。其表達形式為y = w'x+e,e為誤差服從均值為0的正態分佈。 迴歸分析中,只包括一個自變數和一個因變數,且二者的關係可用一條直線近似表示,這種迴歸分析稱為一元線性迴歸分析。 如果迴歸分析

機器學習LogisticRegression邏輯迴歸

機器學習之LogisticRegression邏輯迴歸 # -*- coding: utf-8 -*- """ Created on Wed Nov 21 20:31:59 2018 @author: muli """ import matplotlib.pyplo

機器學習分類決策樹DecisionTreeClassifier

機器學習之分類決策樹DecisionTreeClassifier # -*- coding: utf-8 -*- """ Created on Fri Nov 23 21:06:54 2018 @author: muli """ import numpy as np

機器學習_邏輯迴歸

邏輯迴歸又稱logistic迴歸,邏輯斯諦迴歸,是一種廣義的線性迴歸分析模型。 1. Sigmod函式  Sigmoid函式也是神經網路中常用的函式,用於把x從負無窮到正無窮壓縮到y從0到1之間。畫出來就是一條S型曲線,如下圖中的藍色曲線:  它以0點為中心對稱,公

機器學習分類問題的效能度量

機器學習之分類問題的效能度量 # -*- coding: utf-8 -*- """ Created on Mon Dec 10 10:54:09 2018 @author: muli """ from sklearn.metrics import accuracy

基於Python的機器學習分類學習

所有的資料集都可以從sklearn.datasets中獲得 在評估時,一般使用F1指標,即使用了調和平均數,除了具備平均功能,還會對那些召回率和精血率更加接近的模型給予更高的分數。 分類學習 線性分類器(Linear Classifiers) 線性分類器通過累加計算每

機器學習分類

運動狀態的程式編寫 # -*- coding: utf-8 -*- """ Created on Sun Apr 15 14:20:53 2018 @author: Administrator """ import pandas as pd import numpy as np # 從sklea

機器學習分類器的進階

專案中我用到的分類器是隨機森林。  理解隨機森林,我先po一篇論文。George Vosselman教授的  http://www.sciencedirect.com/science/article/pii/S0924271616306207  這裡面用到的分類器是CRF以

機器學習Bagging 隨機森林演算法

在整合學習裡面,有兩種流派,一個是 boosting 流派,它的特點是對於各個學習器之間有著相互依賴的關係 (比如說在某一次演算法結束後,分類錯誤的樣本會增大比例,以引起下一次的訓練時候的關注度),另一種是bagging 流派,它的特點是各個學習器之間沒有任何的

【十】機器學習路——logistic迴歸python實現

  前面一個部落格機器學習之路——logistic迴歸講了logistic迴歸的理論知識,現在咱們來看一下logistic迴歸如何用python來實現,程式碼、資料參考《機器學習實戰》。   首先看下我們要處理的資料, 我們要做的就是通過logistic