亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python 實現(xiàn)邏輯回歸

 更新時間:2020年12月30日 10:04:16   作者:呱唧_T_呱唧  
這篇文章主要介紹了python 實現(xiàn)邏輯回歸的方法,幫助大家更好的理解和使用python,感興趣的朋友可以了解下

邏輯回歸

適用類型:解決二分類問題

邏輯回歸的出現(xiàn):線性回歸可以預測連續(xù)值,但是不能解決分類問題,我們需要根據(jù)預測的結(jié)果判定其屬于正類還是負類。所以邏輯回歸就是將線性回歸的結(jié)果,通過Sigmoid函數(shù)映射到(0,1)之間

線性回歸的決策函數(shù):數(shù)據(jù)與θ的乘法,數(shù)據(jù)的矩陣格式(樣本數(shù)×列數(shù)),θ的矩陣格式(列數(shù)×1)

將其通過Sigmoid函數(shù),獲得邏輯回歸的決策函數(shù)

使用Sigmoid函數(shù)的原因:

可以對(-∞, +∞)的結(jié)果,映射到(0, 1)之間作為概率

可以將1/2作為決策邊界

數(shù)學特性好,求導容易

邏輯回歸的損失函數(shù)

線性回歸的損失函數(shù)維平方損失函數(shù),如果將其用于邏輯回歸的損失函數(shù),則其數(shù)學特性不好,有很多局部極小值,難以用梯度下降法求解最優(yōu)

這里使用對數(shù)損失函數(shù)

解釋:如果一個樣本為正樣本,那么我們希望將其預測為正樣本的概率p越大越好,也就是決策函數(shù)的值越大越好,則logp越大越好,邏輯回歸的決策函數(shù)值就是樣本為正的概率;如果一個樣本為負樣本,那么我們希望將其預測為負樣本的概率越大越好,也就是(1-p)越大越好,即log(1-p)越大越好

為什么使用對數(shù)函數(shù):樣本集中有很多樣本,要求其概率連乘,概率為0-1之間的數(shù),連乘越來越小,利用log變換將其變?yōu)檫B加,不會溢出,不會超出計算精度

損失函數(shù):: y(1->m)表示Sigmoid值(樣本數(shù)×1),hθx(1->m)表示決策函數(shù)值(樣本數(shù)×1),所以中括號的值(1×1)

二分類邏輯回歸直線編碼實現(xiàn)

import numpy as np
from matplotlib import pyplot as plt
​
from scipy.optimize import minimize
from sklearn.preprocessing import PolynomialFeatures
​
​
class MyLogisticRegression:
  def __init__(self):
    plt.rcParams["font.sans-serif"] = ["SimHei"]
    # 包含數(shù)據(jù)和標簽的數(shù)據(jù)集
    self.data = np.loadtxt("./data2.txt", delimiter=",")
    self.data_mat = self.data[:, 0:2]
    self.label_mat = self.data[:, 2]
    self.thetas = np.zeros((self.data_mat.shape[1]))
​
    # 生成多項式特征,最高6次項
    self.poly = PolynomialFeatures(6)
    self.p_data_mat = self.poly.fit_transform(self.data_mat)
​
  def cost_func_reg(self, theta, reg):
    """
    損失函數(shù)具體實現(xiàn)
    :param theta: 邏輯回歸系數(shù)
    :param data_mat: 帶有截距項的數(shù)據(jù)集
    :param label_mat: 標簽數(shù)據(jù)集
    :param reg:
    :return:
    """
    m = self.label_mat.size
    label_mat = self.label_mat.reshape(-1, 1)
    h = self.sigmoid(self.p_data_mat.dot(theta))
​
    J = -1 * (1/m)*(np.log(h).T.dot(label_mat) + np.log(1-h).T.dot(1-label_mat))\
      + (reg / (2*m)) * np.sum(np.square(theta[1:]))
    if np.isnan(J[0]):
      return np.inf
    return J[0]
​
  def gradient_reg(self, theta, reg):
    m = self.label_mat.size
    h = self.sigmoid(self.p_data_mat.dot(theta.reshape(-1, 1)))
    label_mat = self.label_mat.reshape(-1, 1)
​
    grad = (1 / m)*self.p_data_mat.T.dot(h-label_mat) + (reg/m)*np.r_[[[0]], theta[1:].reshape(-1, 1)]
    return grad
​
  def gradient_descent_reg(self, alpha=0.01, reg=0, iterations=200):
    """
    邏輯回歸梯度下降收斂函數(shù)
    :param alpha: 學習率
    :param reg:
    :param iterations: 最大迭代次數(shù)
    :return: 邏輯回歸系數(shù)組
    """
    m, n = self.p_data_mat.shape
    theta = np.zeros((n, 1))
    theta_set = []
​
    for i in range(iterations):
      grad = self.gradient_reg(theta, reg)
      theta = theta - alpha*grad.reshape(-1, 1)
      theta_set.append(theta)
    return theta, theta_set
​
  def plot_data_reg(self, x_label=None, y_label=None, neg_text="negative", pos_text="positive", thetas=None):
    neg = self.label_mat == 0
    pos = self.label_mat == 1
    fig1 = plt.figure(figsize=(12, 8))
    ax1 = fig1.add_subplot(111)
    ax1.scatter(self.p_data_mat[neg][:, 1], self.p_data_mat[neg][:, 2], marker="o", s=100, label=neg_text)
    ax1.scatter(self.p_data_mat[pos][:, 1], self.p_data_mat[pos][:, 2], marker="+", s=100, label=pos_text)
    ax1.set_xlabel(x_label, fontsize=14)
​
    # 描繪邏輯回歸直線(曲線)
    if isinstance(thetas, type(np.array([]))):
      x1_min, x1_max = self.p_data_mat[:, 1].min(), self.p_data_mat[:, 1].max()
      x2_min, x2_max = self.p_data_mat[:, 2].min(), self.p_data_mat[:, 2].max()
      xx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max))
      h = self.sigmoid(self.poly.fit_transform(np.c_[xx1.ravel(), xx2.ravel()]).dot(thetas))
      h = h.reshape(xx1.shape)
      ax1.contour(xx1, xx2, h, [0.5], linewidths=3)
    ax1.legend(fontsize=14)
    plt.show()
​
  @staticmethod
  def sigmoid(z):
    return 1.0 / (1 + np.exp(-z))
​
​
if __name__ == '__main__':
  my_logistic_regression = MyLogisticRegression()
  # my_logistic_regression.plot_data(x_label="線性不可分數(shù)據(jù)集")
​
  thetas, theta_set = my_logistic_regression.gradient_descent_reg(alpha=0.5, reg=0, iterations=500)
  my_logistic_regression.plot_data_reg(thetas=thetas, x_label="$\\lambda$ = {}".format(0))
​
  thetas = np.zeros((my_logistic_regression.p_data_mat.shape[1], 1))
  # 未知錯誤,有大佬解決可留言
  result = minimize(my_logistic_regression.cost_func_reg, thetas,
           args=(0, ),
           method=None,
           jac=my_logistic_regression.gradient_reg)
  my_logistic_regression.plot_data_reg(thetas=result.x, x_label="$\\lambda$ = {}".format(0))

二分類問題邏輯回歸曲線編碼實現(xiàn)

import numpy as np
from matplotlib import pyplot as plt
​
from scipy.optimize import minimize
from sklearn.preprocessing import PolynomialFeatures
​
​
class MyLogisticRegression:
  def __init__(self):
    plt.rcParams["font.sans-serif"] = ["SimHei"]
    # 包含數(shù)據(jù)和標簽的數(shù)據(jù)集
    self.data = np.loadtxt("./data2.txt", delimiter=",")
    self.data_mat = self.data[:, 0:2]
    self.label_mat = self.data[:, 2]
    self.thetas = np.zeros((self.data_mat.shape[1]))
​
    # 生成多項式特征,最高6次項
    self.poly = PolynomialFeatures(6)
    self.p_data_mat = self.poly.fit_transform(self.data_mat)
​
  def cost_func_reg(self, theta, reg):
    """
    損失函數(shù)具體實現(xiàn)
    :param theta: 邏輯回歸系數(shù)
    :param data_mat: 帶有截距項的數(shù)據(jù)集
    :param label_mat: 標簽數(shù)據(jù)集
    :param reg:
    :return:
    """
    m = self.label_mat.size
    label_mat = self.label_mat.reshape(-1, 1)
    h = self.sigmoid(self.p_data_mat.dot(theta))
​
    J = -1 * (1/m)*(np.log(h).T.dot(label_mat) + np.log(1-h).T.dot(1-label_mat))\
      + (reg / (2*m)) * np.sum(np.square(theta[1:]))
    if np.isnan(J[0]):
      return np.inf
    return J[0]
​
  def gradient_reg(self, theta, reg):
    m = self.label_mat.size
    h = self.sigmoid(self.p_data_mat.dot(theta.reshape(-1, 1)))
    label_mat = self.label_mat.reshape(-1, 1)
​
    grad = (1 / m)*self.p_data_mat.T.dot(h-label_mat) + (reg/m)*np.r_[[[0]], theta[1:].reshape(-1, 1)]
    return grad
​
  def gradient_descent_reg(self, alpha=0.01, reg=0, iterations=200):
    """
    邏輯回歸梯度下降收斂函數(shù)
    :param alpha: 學習率
    :param reg:
    :param iterations: 最大迭代次數(shù)
    :return: 邏輯回歸系數(shù)組
    """
    m, n = self.p_data_mat.shape
    theta = np.zeros((n, 1))
    theta_set = []
​
    for i in range(iterations):
      grad = self.gradient_reg(theta, reg)
      theta = theta - alpha*grad.reshape(-1, 1)
      theta_set.append(theta)
    return theta, theta_set
​
  def plot_data_reg(self, x_label=None, y_label=None, neg_text="negative", pos_text="positive", thetas=None):
    neg = self.label_mat == 0
    pos = self.label_mat == 1
    fig1 = plt.figure(figsize=(12, 8))
    ax1 = fig1.add_subplot(111)
    ax1.scatter(self.p_data_mat[neg][:, 1], self.p_data_mat[neg][:, 2], marker="o", s=100, label=neg_text)
    ax1.scatter(self.p_data_mat[pos][:, 1], self.p_data_mat[pos][:, 2], marker="+", s=100, label=pos_text)
    ax1.set_xlabel(x_label, fontsize=14)
​
    # 描繪邏輯回歸直線(曲線)
    if isinstance(thetas, type(np.array([]))):
      x1_min, x1_max = self.p_data_mat[:, 1].min(), self.p_data_mat[:, 1].max()
      x2_min, x2_max = self.p_data_mat[:, 2].min(), self.p_data_mat[:, 2].max()
      xx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max))
      h = self.sigmoid(self.poly.fit_transform(np.c_[xx1.ravel(), xx2.ravel()]).dot(thetas))
      h = h.reshape(xx1.shape)
      ax1.contour(xx1, xx2, h, [0.5], linewidths=3)
    ax1.legend(fontsize=14)
    plt.show()
​
  @staticmethod
  def sigmoid(z):
    return 1.0 / (1 + np.exp(-z))
​
​
if __name__ == '__main__':
  my_logistic_regression = MyLogisticRegression()
  # my_logistic_regression.plot_data(x_label="線性不可分數(shù)據(jù)集")
​
  thetas, theta_set = my_logistic_regression.gradient_descent_reg(alpha=0.5, reg=0, iterations=500)
  my_logistic_regression.plot_data_reg(thetas=thetas, x_label="$\\lambda$ = {}".format(0))
​
  thetas = np.zeros((my_logistic_regression.p_data_mat.shape[1], 1))
  # 未知錯誤,有大佬解決可留言
  result = minimize(my_logistic_regression.cost_func_reg, thetas,
           args=(0, ),
           method=None,
           jac=my_logistic_regression.gradient_reg)
  my_logistic_regression.plot_data_reg(thetas=result.x, x_label="$\\lambda$ = {}".format(0))

以上就是python 實現(xiàn)邏輯回歸的詳細內(nèi)容,更多關(guān)于python 實現(xiàn)邏輯回歸的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 分享Python中四個不常見的小技巧

    分享Python中四個不常見的小技巧

    這篇文章主要介紹了分享Python中四個不常見的小技巧,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-08-08
  • 詳解Python 關(guān)聯(lián)規(guī)則分析

    詳解Python 關(guān)聯(lián)規(guī)則分析

    這篇文章主要介紹了Python 關(guān)聯(lián)規(guī)則分析的相關(guān)資料,幫助大家更好的理解和學習使用python,感興趣的朋友可以了解下
    2021-03-03
  • node命令行服務器(http-server)和跨域的實現(xiàn)

    node命令行服務器(http-server)和跨域的實現(xiàn)

    本文主要介紹了node命令行服務器(http-server)和跨域的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-02-02
  • 解析Python中的eval()、exec()及其相關(guān)函數(shù)

    解析Python中的eval()、exec()及其相關(guān)函數(shù)

    本篇文章主要介紹了解析Python中的eval()、exec()及其相關(guān)函數(shù),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-12-12
  • python執(zhí)行系統(tǒng)命令4種方法與比較

    python執(zhí)行系統(tǒng)命令4種方法與比較

    這篇文章主要介紹了python執(zhí)行系統(tǒng)命令4種方法與比較,需要的朋友可以參考下
    2021-04-04
  • Python將Office文檔(Word、Excel、PDF、PPT)轉(zhuǎn)為OFD格式的實現(xiàn)方法

    Python將Office文檔(Word、Excel、PDF、PPT)轉(zhuǎn)為OFD格式的實現(xiàn)方法

    OFD(Open Fixed-layout Document )是我國自主制定的一種開放版式文件格式標準,如果想要通過Python將Office文檔(如Word、Excel或PowerPoint)及PDF文檔轉(zhuǎn)換為OFD格式,可以參考本文中提供的實現(xiàn)方法,需要的朋友可以參考下
    2024-06-06
  • 排序算法之希爾排序法解析

    排序算法之希爾排序法解析

    這篇文章主要介紹了排序算法之希爾排序法解析,希爾排序法(Shell Sort),也稱為縮小增量排序,是一種改進的插入排序算法,它通過將待排序的元素按照一定的間隔分組,對每個分組進行插入排序,逐漸減小間隔直至為1,最后對整個序列進行一次插入排序
    2023-07-07
  • PyCharm搭建一勞永逸的開發(fā)環(huán)境

    PyCharm搭建一勞永逸的開發(fā)環(huán)境

    這篇文章主要介紹了PyCharm搭建一勞永逸的開發(fā)環(huán)境,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-04-04
  • python中安裝django模塊的方法

    python中安裝django模塊的方法

    這篇文章主要介紹了python中安裝django模塊的方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-03-03
  • python多繼承(鉆石繼承)問題和解決方法簡單示例

    python多繼承(鉆石繼承)問題和解決方法簡單示例

    這篇文章主要介紹了python多繼承(鉆石繼承)問題和解決方法,結(jié)合實例形式分析了Python多繼承調(diào)用父類初始化方法相關(guān)操作技巧,需要的朋友可以參考下
    2019-10-10

最新評論