# -*- coding: utf-8 -*-
"""@author: 蔚藍的天空tom
"""import numpy as np
import os
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
#global variable
path = r'd:\tom\data'
train_set = 'train_lr.txt'
test_set = 'test_lr.txt'
#load data set from txt file
def load_data_set(path, file_name):
data_list =
label_list =
f = open(os.path.join(path, file_name))
for line in f.readlines():
#feature1 feature2 label
text = line.strip().split()
#data_m追加[feature0=1, feature1, feature2]
#樣本的實際特徵值有2個,附加乙個恆值為1的特徵值feature0,以便運算
#記作features_cnt = 1 + n_features
#label_m追加label value
return data_list, label_list
#sigmoid function
def sigmoid(z):
return 1/(1+np.exp(-1*z))
def sigmoid_for_m(z):
fin = 1
fout = 1
sigmoid_func = np.frompyfunc(sigmoid, fin, fout)
return sigmoid_func(z)
def trainlogisticregression(data_list, label_list):
#samples feature matrix, samples_cnt * features_cnt
#其中samples_cnt = n_samples
#其中features_cnt = 1 + n_features
data_m = np.mat(data_list).astype(np.float64)
#samples label matrix, samples_cnt * 1
#其中samples_cnt = n_samples
label_m = np.mat(label_list).t.astype(np.float64)
#get samples features shape
#其中m = samples_cnt = n_samples
#其中n = features_cnt = 1 + n_samples
m,n = np.shape(data_m)
#初始化權重係數w,features_cnt * 1
#其中features_cnt = 1 + n_features
w = np.ones((n,1))
#初始化學習效率learning rate, alpha
alpha = 0.001
#設定迴圈迭代計算的執行最大次數,loop_limit
loop_limit = 1000
#誤差初始化
error = 10000
#開始迭代計算
for i in range(loop_limit):
predict = sigmoid_for_m(data_m * w)
error = predict - label_m
w = w - alpha * data_m.t * error
return w
#train the test set
def train_test_set(weights, data):
w = weights
return w[0]/w[2] - w[1]/w[2]*data
#顯示擬合圖形
def plot_fit_line(weights, data, label):
if type(weights).__name__ == 'ndarray':
w = weights
else:
w = weights.geta()
#test set
test_data_list,test_label_list = make_blobs(n_samples=200, n_features=2, centers=2)
#plt.figure(1)
test_data_set = np.arange(-3, 3, 0.1)
lr_test_label = -1 * w[0]/w[2] - w[1]/w[2]*test_data_set
#lr_test_label = train_test_set(w, test_data_set)
plt.plot(test_data_set, lr_test_label)
negative = #否定的
positive = #肯定的
scikit-learn文件:
python編寫logistic邏輯回歸:
python實現邏輯回歸的方法示例:
(end)
python 邏輯回歸分類 機器學習 邏輯回歸分類
分類問題 1 本質 決策面 decision su ce 2 評估分類演算法的指標,正確率 正確分類個數 總數 二分分類 邏輯回歸輸入 訓練資料的特徵和標籤 模型 邏輯回歸 輸出 分類結果 什麼是邏輯函式?在0到1之間取值,邏輯回歸是因為引數是邏輯函式 邏輯的數值 表示分類結果是1是y的結果 決策面...
機器學習 softmax回歸 python實現
恢復內容開始 softmax regression 可以看做是 lr 演算法在多分類上的推廣,即類標籤 y 的取值大於或者等於 2。假設資料樣本集為 left y right left x y right left x y right left x y right right 對於 sr 演算法,其...
機器學習(二) 邏輯回歸 python
由於公式使用的是latex,解析使用的google的chart api,所以顯示有問題,可以移步github 可以看出,當1,y 1,與 值一致,此時付出的代價cost趨於0,若0,y 1,此時的代價cost值非常大,我們最終的目的是最小化代價值 同理y 0 代價函式 defcostfunction...