python底層的邏輯演算法:
回歸:回歸是統計學的乙個重要概念,其本意是根據之前的資料**乙個準確的輸出值。
邏輯回歸是《機器學習》這門課的第三個演算法,它是目前使用最為廣泛的一種學習演算法,用於解決分類問題。與線性回歸演算法一樣,也是監督學習演算法。
諸如:新聞分類、基因序列、市場劃分等的一些根據特徵劃分的,用的都是邏輯回歸。
輸出的最終**結果為:正向類(1)、負向類(0)。
邏輯回歸模型是乙個「s」形的函式:
代價函式:代價函式 — 誤差的平方和 — 非凸函式—區域性最小點 。
梯度下降
#特徵縮放
x -=np.mean(x,axis=0)
x /=np.std(x,axis=0,ddof=1)
x=np.c_[np.ones(len(x)),x]
y=np.c_[y]
return x,y
train_x,train_y=preproess(train_x,train_y)
test_x,test_y=preproess(test_x,test_y)
def g(x):
return 1/(1+np.exp(-x))
x=np.linspace(-10,10,500)
y=g(x)
plt.plot(x,y)
plt.show()
def model(x,theta):
z=np.dot(x,theta)
h=g(z)
return h
def costfunc(h,y):
m=len(y)
j=-(1.0/m)*np.sum(y*np.log(h)+(1-y)*np.log(1-h))
return j
def graddesc(x,y,max_iter=15000,alpha=0.1):
m,n=x.shape
theta=np.zeros((n,1))
j_history=np.zeros(max_iter)
for i in range(max_iter):
h=model(x,theta)
j_history[i]=costfunc(h,y)
deltatheta = (1.0/m)*np.dot(x.t,h-y)
theta -= deltatheta*alpha
return j_history,theta
def score(h,y):
m=len(y)
count=0
for i in range(m):
h[i]=np.where(h[i]>=0.5,1,0)
if h[i]==y[i]:
count+=1
return count/m
#**結果函式,結果不是0就是1
def predict(h):
y_pre=[1 if i>=0.5 else 0 for i in h]
return y_pre
print(train_x.shape,train_y.shape)
j_history,theta=graddesc(train_x,train_y)
print(theta)
plt.title("代價函式")
plt.plot(j_history)
plt.show()
train_h=model(train_x,theta)
test_h=model(test_x,theta)
print(train_h,test_h)
def showdivide(x,theta,y,title):
plt.title(title)
plt.scatter(x[y[:,0]==0,1],x[y[:,0]==0,2],label="負樣本")
plt.scatter(x[y[:,0]==1,1],x[y[:,0]==1,2],label="正樣本")
min_x1,max_x1=np.min(x),np.max(x)
min_x2,max_x2=-(theta[0]+theta[1]*min_x1)/theta[2],-(theta[0]+theta[1]*max_x1)/theta[2]
plt.plot([min_x1,max_x1],[min_x2,max_x2])
plt.legend()
plt.show()
showdivide(train_x,theta,train_y,'訓練集')
showdivide(test_x,theta,test_y,'測試集集')
train_y1=predict(train_h)
print('**的結果是:',train_y1)
機器學習 邏輯回歸 Python實現邏輯回歸
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...
Python 邏輯回歸分析
以某銀行貸款拖欠率資料進行邏輯回歸建模,資料示例如下 特徵篩選 本例採用穩定性選擇方法中的隨機邏輯回歸 建立模型 利用篩選後的特徵建立邏輯回歸模型 輸出平均正確率 coding utf 8 邏輯回歸 自動建模 import pandas as pd 引數初始化 filename data bankl...
線性邏輯回歸python
例項描述 假設腫瘤醫院想要用神經網路對已有的病例資料進行分類,資料的樣本特徵包括病人的年齡和腫瘤的大小,對應的標籤應該是良性腫瘤還是惡性腫瘤 1.生成樣本集 利用python生成乙個二維陣列 病人的年紀,腫瘤的大小 樣本集,下面 中generate為生成樣本的函式,意思是按照指定的均值和方差生成固定...