邏輯歸回

邏輯回歸函數(shù)定義

邏輯回歸

** g(z)就是傳說中的sigmoid函數(shù) **
sigmoid求導(dǎo)

** 因為是二分類問題,所以我們假設(shè): **
假設(shè)

** 這里我們可以將其寫成如下公式 **
公示整合

** 似然函數(shù)(這里表示為θ的似然): **
似然函數(shù)

** 對數(shù)似然 **
對數(shù)似然

求導(dǎo)

** 神奇的事情出現(xiàn)了,這里的公式和梯度下降的公式何其相似啊。我們稱之為梯度上升
批梯度上升和隨機梯度上升與我的上篇文章http://m.itdecent.cn/p/52f5ea825f7f提到的批梯度下降和隨機梯度下降是一樣的邏輯。不過你需要仔細(xì)想想這兩個公式有什么不同 **

梯度上升
%matplotlib inline
from numpy import *
#導(dǎo)入數(shù)據(jù)并整理
def loadDataSet(fileName):
    dataMat = []
    labelMat = []
    fr = open(fileName)
    for line in fr.readlines():
        lineArr = line.strip().split()
        dataMat.append([1.0,float(lineArr[0]),float(lineArr[1])])
        labelMat.append(float(lineArr[2]))
    return dataMat,labelMat

#sigmoid函數(shù)
def sigmoid(inX):
    return 1.0/(1+exp(-inX))

#畫圖
def plotBestFit(weights):
    import matplotlib.pyplot as plt
    dataMat,labelMat=loadDataSet('testSet.txt')
    dataArr = array(dataMat)
    n = shape(dataArr)[0] 
    xcord1 = []; ycord1 = []
    xcord2 = []; ycord2 = []
    for i in range(n):
        if int(labelMat[i])== 1:
            xcord1.append(dataArr[i,1]); ycord1.append(dataArr[i,2])
        else:
            xcord2.append(dataArr[i,1]); ycord2.append(dataArr[i,2])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(xcord1, ycord1, s=30, c='red', marker='s')
    ax.scatter(xcord2, ycord2, s=30, c='green')
    x = arange(-3.0, 3.0, 0.1)
    y = (-weights[0]-weights[1]*x)/weights[2]
    ax.plot(x, y)
    plt.xlabel('X1'); plt.ylabel('X2');
    plt.show()

#批梯度上升
def gradAscent(dataMatIn,classLabels,alpha = 0.001,maxCycles = 500):
    dataMatrix = mat(dataMatIn)
    labelMat = mat(classLabels).transpose()
    m,n = shape(dataMatrix)
    weights = ones((n,1))
    for k in range(maxCycles):
        h = sigmoid(dataMatrix * weights)
        error = labelMat - h
        weights = weights + alpha * dataMatrix.transpose()*error
    return weights

#測試
dataArr,labelArr = loadDataSet('testSet.txt')
weights = gradAscent(dataArr,labelArr,0.001,500)
plotBestFit(weights.getA())
批梯度上升
#隨機梯度上升
def stocGradAscent(dataMatrix, classLabels, numIter=150):
    m,n=shape(dataMatrix)
    weights=ones(n)
    for j in range(numIter):
        dataIndex=range(m)
        for i in range(m):
            alpha=4/(1.0+j+i)+0.01
            randIndex=int(random.uniform(0,len(dataIndex)))
            h=sigmoid(sum(dataMatrix[randIndex]*weights))
            error=classLabels[randIndex]-h
            weights=weights+alpha*error*dataMatrix[randIndex]
            del[dataIndex[randIndex]]
    return weights

dataArr,labelMat = loadDataSet('testSet.txt')
weights = stocGradAscent(array(dataArr),labelMat,500)
plotBestFit(weights)
隨機梯度上升

spark代碼示例

public class LogisticWithElasticNet {
    /**
     * 日志控制
     */
    static{
        LogSetting.setWarningLogLevel("org");
        LogSetting.setWarningLogLevel("akka");
        LogSetting.setWarningLogLevel("io");
        LogSetting.setWarningLogLevel("httpclient.wire");
    }

    public static void main(String[] args) {
        String resources = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        SparkConf conf = new SparkConf().setAppName("Logistic Regression with Elastic Net Example").setMaster("local[2]");
        SparkContext sc = new SparkContext(conf);
        SQLContext sqlContext = new SQLContext(sc);

        String path  = resources + "libsvm_data.txt";
        DataFrame training = sqlContext.read().format("libsvm").load(path);

        LogisticRegression lr = new LogisticRegression()
                .setMaxIter(10)
                .setRegParam(0.3)
                .setElasticNetParam(0.8);

        // Fit the model
        LogisticRegressionModel lrModel = lr.fit(training);

        System.out.println("Coefficients: "
                + lrModel.coefficients() + " Intercept: " + lrModel.intercept());

        // Extract the summary from the returned LogisticRegressionModel instance trained in the earlier example
        LogisticRegressionTrainingSummary trainingSummary = lrModel.summary();

        // Obtain the loss per iteration.
        double[] objectiveHistory = trainingSummary.objectiveHistory();
        for (double lossPerIteration : objectiveHistory) {
            System.out.println(lossPerIteration);
        }

        // Obtain the metrics useful to judge performance on test data.
        // We cast the summary to a BinaryLogisticRegressionSummary since the problem is a binary classification problem.
        BinaryLogisticRegressionSummary binarySummary =
                (BinaryLogisticRegressionSummary) trainingSummary;

        // Obtain the receiver-operating characteristic as a dataframe and areaUnderROC.
        DataFrame roc = binarySummary.roc();
        roc.show();
        roc.select("FPR").show();
        System.out.println(binarySummary.areaUnderROC());

        // Get the threshold corresponding to the maximum F-Measure and rerun LogisticRegression with this selected threshold.
        DataFrame fMeasure = binarySummary.fMeasureByThreshold();
        double maxFMeasure = fMeasure.select(functions.max("F-Measure")).head().getDouble(0);
        double bestThreshold = fMeasure.where(fMeasure.col("F-Measure").equalTo(maxFMeasure))
                .select("threshold").head().getDouble(0);
        lrModel.setThreshold(bestThreshold);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容