亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

python 實現邏輯回歸

瀏覽:3日期:2022-06-30 18:15:37
邏輯回歸

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

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

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

python 實現邏輯回歸

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

python 實現邏輯回歸

使用Sigmoid函數的原因:

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

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

python 實現邏輯回歸

數學特性好,求導容易

python 實現邏輯回歸

邏輯回歸的損失函數

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

這里使用對數損失函數

python 實現邏輯回歸

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

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

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

python 實現邏輯回歸

二分類邏輯回歸直線編碼實現

import numpy as npfrom matplotlib import pyplot as plt​from scipy.optimize import minimizefrom sklearn.preprocessing import PolynomialFeatures​​class MyLogisticRegression: def __init__(self): plt.rcParams['font.sans-serif'] = ['SimHei'] # 包含數據和標簽的數據集 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): ''' 損失函數具體實現 :param theta: 邏輯回歸系數 :param data_mat: 帶有截距項的數據集 :param label_mat: 標簽數據集 :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): ''' 邏輯回歸梯度下降收斂函數 :param alpha: 學習率 :param reg: :param iterations: 最大迭代次數 :return: 邏輯回歸系數組 ''' 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='線性不可分數據集')​ 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))二分類問題邏輯回歸曲線編碼實現

import numpy as npfrom matplotlib import pyplot as plt​from scipy.optimize import minimizefrom sklearn.preprocessing import PolynomialFeatures​​class MyLogisticRegression: def __init__(self): plt.rcParams['font.sans-serif'] = ['SimHei'] # 包含數據和標簽的數據集 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): ''' 損失函數具體實現 :param theta: 邏輯回歸系數 :param data_mat: 帶有截距項的數據集 :param label_mat: 標簽數據集 :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): ''' 邏輯回歸梯度下降收斂函數 :param alpha: 學習率 :param reg: :param iterations: 最大迭代次數 :return: 邏輯回歸系數組 ''' 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='線性不可分數據集')​ 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 實現邏輯回歸的詳細內容,更多關于python 實現邏輯回歸的資料請關注好吧啦網其它相關文章!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 国产原创麻豆 | 国产97色在线中文 | 成人免费播放视频777777 | 精品一区二区视频 | 久久国产精品国产自线拍免费 | 国产精品久久久久久久久久日本 | 亚洲黄色美女视频 | 亚洲 午夜在线一区 | 亚洲国产二区 | 日本护士一级毛片在线播放 | 黄色一级视频网站 | 日韩欧美国产偷亚洲清高 | 国产精品成人观看视频免费 | 亚州综合激情另类久久久 | 久久久综合九色合综国产 | 香蕉啪 | 色视频国产 | 日韩欧美特一级大黄作a毛片免费 | 青草视频免费观看在线观看 | 国产日产亚洲系列首页 | 在线免费观看a级片 | 色免费在线观看 | 91大神大战丝袜美女在线观看 | 亚洲在线一区二区 | 免费久久精品视频 | 国产精品区一区二区免费 | 欧美日韩一区二区三区色综合 | 国产人成免费视频 | 91精品国产高清久久久久久 | 国产成人免费高清激情视频 | 日日a.v拍夜夜添久久免费 | 国产一区二区三区四区在线观看 | 在线观看网站黄 | 999久久久精品视频在线观看 | 免费观看性欧美特黄 | 久久草在线视频 | 三级黄色免费网站 | 久热精品视频 | 国产综合第一页在线视频 | 一级做a爰片久久毛片 | 国产高清好大好夹受不了了 |