機器學習實踐一 logistic regression regularize

Logistic regression

數據內容: 兩個參數 x1 x2 y值 0 或 1

Potting

def read_file(file):data = pd.read_csv(file, names=['exam1', 'exam2', 'admitted'])data = np.array(data)return datadef plot_data(X, y):plt.figure(figsize=(6, 4), dpi=150)X1 = X[y == 1, :]X2 = X[y == 0, :]plt.plot(X1[:, 0], X1[:, 1], 'yo')plt.plot(X2[:, 0], X2[:, 1], 'k+')plt.xlabel('Exam1 score')plt.ylabel('Exam2 score')plt.legend(['Admitted', 'Not admitted'], loc='upper right')plt.show()print('Plotting data with + indicating (y = 1) examples and o indicating (y = 0) examples.')
plot_data(X, y)

在這里插入圖片描述
從圖上可以看出admitted 和 not admitted 存在一個明顯邊界,下面進行邏輯回歸:
logistic 回歸的假設函數

在這里插入圖片描述
g(x)為logistics function:

def sigmoid(x):return 1 / (np.exp(-x) + 1)

看一下邏輯函數的函數圖:
在這里插入圖片描述
cost function
邏輯回歸的代價函數:
在這里插入圖片描述
Gradient descent

  • 批處理梯度下降(batch gradient descent)
  • 向量化計算公式:
    1/mXT(sigmoid(XθT)?y)1/mX^{T}(sigmoid(Xθ^{T}) - y) 1/mXT(sigmoid(XθT)?y)
def gradient(initial_theta, X, y):m, n = X.shapeinitial_theta = initial_theta.reshape((n, 1))grad = X.T.dot(sigmoid(X.dot(initial_theta)) - y) / mreturn grad.flatten()

computer Cost and grad

m, n = X.shape
X = np.c_[np.ones(m), X]
initial_theta = np.zeros((n + 1, 1))
y = y.reshape((m, 1))# cost, grad = costFunction(initial_theta, X, y)
cost, grad = cost_function(initial_theta, X, y), gradient(initial_theta, X, y)
print('Cost at initial theta (zeros): %f' % cost);
print('Expected cost (approx): 0.693');
print('Gradient at initial theta (zeros): ');
print('%f %f %f' % (grad[0], grad[1], grad[2]))
print('Expected gradients (approx): -0.1000 -12.0092 -11.2628')
#
theta1 = np.array([[-24], [0.2], [0.2]], dtype='float64')
cost, grad = cost_function(theta1, X, y), gradient(theta1, X, y)
# cost, grad = costFunction(theta1, X, y)
print('Cost at initial theta (zeros): %f' % cost);
print('Expected cost (approx): 0.218');
print('Gradient at initial theta (zeros): ');
print('%f %f %f' % (grad[0], grad[1], grad[2]))
print('Expected gradients (approx): 0.043 2.566 2.647')

學習 θ 參數
使用scipy庫里的optimize庫進行訓練, 得到最終的theta結果
Optimizing using fminunc

initial_theta = np.zeros(n + 1)
result = opt.minimize(fun=cost_function, x0=initial_theta, args=(X, y), method='SLSQP', jac=gradient)print('Cost at theta found by fminunc: %f' % result['fun'])
print('Expected cost (approx): 0.203')
print('theta:')
print('%f %f %f' % (result['x'][0], result['x'][1], result['x'][2]))
print('Expected theta (approx):')
print(' -25.161 0.206 0.201')

predict and Accuracies
學習好了參數θ, 開始進行預測, 當hθ 大于等于0.5, 預測y = 1
當hθ小于0.5時, 預測y =0

def predict(theta, X):m = np.size(theta, 0)rst = sigmoid(X.dot(theta.reshape(m, 1)))rst = rst > 0.5return rst# predict and Accuraciesprob = sigmoid(np.array([1, 45, 85], dtype='float64').dot(result['x']))
print('For a student with scores 45 and 85, we predict an admission ' \'probability of %.3f' % prob)
print('Expected value: 0.775 +/- 0.002\n')p = predict(result['x'], X)print('Train Accuracy: %.1f%%' % (np.mean(p == y) * 100))
print('Expected accuracy (approx): 89.0%\n')

也可以用skearn 來檢驗:

from sklearn.metrics import classification_report
print(classification_report(predictions, y))

Decision boundary (決策邊界)

X × θ = 0

θ0 + x1θ1 + x2θ2 = 0

x1 = np.arange(70, step=0.1)
x2 = -(final_theta[0] + x1*final_theta[1]) / final_theta[2]fig, ax = plt.subplots(figsize=(8,5))
positive = X[y == 1, :]
negative = X[y == 0, :]
ax.scatter(positive[:, 0], positive[:, 1], c='b', label='Admitted')
ax.scatter(negative[:, 0], negative[:, 1], s=50, c='r', marker='x', label='Not Admitted')
ax.plot(x1, x2)
ax.set_xlim(30, 100)
ax.set_ylim(30, 100)
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_title('Decision Boundary')
plt.show()

Regularized logistic regression

正則化可以減少過擬合, 也就是高方差,直觀原理是,當超參數lambda 非常大的時候,參數θ相對較小, 所以函數曲線就變得簡單, 也就減少了剛方差。
可視化數據

data2 = pd.read_csv('ex2data2.txt', names=[' column1', 'column2', 'Accepted'])
data2.head()
def plot_data():positive = data2[data2['Accepted'].isin([1])]negative = data2[data2['Accepted'].isin([0])]fig, ax = plt.subplots(figsize=(8,5))ax.scatter(positive['column1'], positive['column2'], s=50, c='b', marker='o', label='Accepted')ax.scatter(negative['column1'], negative['column2'], s=50, c='r', marker='x', label='Rejected')ax.legend()ax.set_xlabel('Test 1 Score')ax.set_ylabel('Test 2 Score')plot_data()	

Feature mapping

盡可能將兩個特征 x1 x2 相結合,組成一個線性表達式,方法是映射到所有的x1 和x2 的多項式上,直到第六次冪

for i in 0..powerfor p in 0..i:output x1^(i-p) * x2^p```
def feature_mapping(x1, x2, power):data = {}for i in np.arange(power + 1):for p in np.arange(i + 1):data["f{}{}".format(i - p, p)] = np.power(x1, i - p) * np.power(x2, p)return pd.DataFrame(data)

在這里插入圖片描述
Regularized Cost function
在這里插入圖片描述
Regularized gradient decent
在這里插入圖片描述
決策邊界
X × θ = 0

x = np.linspace(-1, 1.5, 250)
xx, yy = np.meshgrid(x, x)z = feature_mapping(xx.ravel(), yy.ravel(), 6).as_matrix()
z = z.dot(final_theta)
z = z.reshape(xx.shape)plot_data()
plt.contour(xx, yy, z, 0)
plt.ylim(-.8, 1.2)

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/389034.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/389034.shtml
英文地址,請注明出處:http://en.pswp.cn/news/389034.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

ajax+webservice

版本為AJAX November CTP 三個示例分別為:1 帶參數的WS方法2 不帶參數的WS方法3 參數類型為DataTable的WS方法 一、WebMethod注意要點:1 WebMethod類需要添加命名空間 Microsoft.Web.Script.Services,此空間需要引用Microsoft.Web.Preview.dl…

深度學習數據擴張_適用于少量數據的深度學習結構

作者:Gorkem Polat編譯:ronghuaiyang導讀一些最常用的few shot learning的方案介紹及對比。傳統的CNNs (AlexNet, VGG, GoogLeNet, ResNet, DenseNet…)在數據集中每個類樣本數量較多的情況下表現良好。不幸的是,當你擁有一個小數據集時&…

時間管理

時間管理 時間管理是運用策略和技術,幫助你盡可能有效地利用你的時間。 不僅僅是要將時間用在正確的地方, 而且還要將盡可能有效地加以利用。 目前是如何利用時間的: 意識是時間管理的先決條件。目標提供路線圖。選擇是難點。 意識 第一條…

基于邊緣計算的實時績效_基于績效的營銷中的三大錯誤

基于邊緣計算的實時績效We’ve gone through 20% of the 21st century. It’s safe to say digitalization isn’t a new concept anymore. Things are fully or at least mostly online, and they tend to escalate in the digital direction. That’s why it’s important to…

本線程鉤子

鉤子其實就是調用一下API而已: 1、安裝鉤子:   SetWindowsHookEx 函數原形:HHOOK SetWindowsHookEx( int idHook, // 鉤子類型, HOOKPROC lpfn, // 鉤子函數地址…

Maven Web項目解決跨域問題

跨域問題目前筆者所用到的方案大致有三種:jsonp,SpringMVC 4以上注解方式和cros三方過濾器。 Jsonp JSONP(JSON with Padding)是一個非官方的協議,它允許在服務器端集成Script tags返回至客戶端,通過javascript callback的形式實現跨域訪問(這…

為什么Facebook的API以一個循環作為開頭?

作者 | Antony Garand譯者 | 無明如果你有在瀏覽器中查看過發給大公司 API 的請求,你可能會注意到,JSON 前面會有一些奇怪的 JavaScript:為什么他們會用這幾個字節來讓 JSON 失效?為了保護你的數據 如果沒有這些字節,那…

城市軌道交通運營票務管理論文_城市軌道交通運營管理專業就業前景怎么樣?中職優選告訴你...

??城市軌道交通運營管理專業,專業就業前景怎么樣?就業方向有哪些?有很多同學都感覺很迷忙,為了讓更多的同學們了解城市軌道交通運營管理專業的就業前景與就業方向,整理出以下內容希望可以幫助同學們。城市軌道交通運…

計算機視覺對掃描文件分類 OCR

通過計算機視覺對掃描文件分類 一種解決掃描文檔分類問題的深度學習方法 在數字經濟時代, 銀行、保險、治理、醫療、法律等部門仍在處理各種手寫票據和掃描文件。在業務生命周期的后期, 手動維護和分類這些文檔變得非常繁瑣。 對這些非機密文檔進行簡…

從錢龍數據中讀取股票權息信息導入到數據庫

從錢龍數據中讀取股票權息信息導入到數據庫 前面寫了如果讀股票代碼和日線數據,下面是如何讀股票的權息信息。 錢龍中權息數據存儲在QLDATA/history/shase/weight和QLDATA/history/sznse/weight目錄下,每個文件對應一只股票。 與前文一樣,只貼…

笑話生成器_爸爸笑話發生器

笑話生成器(If you’re just here for the generated jokes, scroll down to the bottom!)(如果您只是在這里生成笑話,請向下滾動到底部!) I thought: what is super easy to build, yet would still get an approving chuckle if someone found it on …

AWS Amplify Console:賦予應用程序快速部署的能力

AWS re:Invent 2018大會發布了很多新功能和服務,包括新的AWS Amplify Console,一種針對移動Web應用程序的持續部署服務。 AWS Amplify Console承諾可以支持快速發布新功能,避免在部署應用程序時停機,并降低同時更新應用程序客戶端…

機器學習實踐二 -多分類和神經網絡

本次練習的任務是使用邏輯歸回和神經網絡進行識別手寫數字(form 0 to 9, 自動手寫數字問題已經應用非常廣泛,比如郵編識別。 使用邏輯回歸進行多分類分類 練習2 中的logistic 回歸實現了二分類分類問題,現在將進行多分類,one vs…

Hadoop 倒排索引

倒排索引是文檔檢索系統中最常用的數據結構,被廣泛地應用于全文搜索引擎。它主要是用來存儲某個單詞(或詞組)在一個文檔或一組文檔中存儲位置的映射,即提供了一種根據內容來查找文檔的方式。由于不是根據文檔來確定文檔所包含的內…

koa2異常處理_讀 koa2 源碼后的一些思考與實踐

koa2的特點優勢什么是 koa2Nodejs官方api支持的都是callback形式的異步編程模型。問題:callback嵌套問題koa2 是由 Express原班人馬打造的,是現在比較流行的基于Node.js平臺的web開發框架,Koa 把 Express 中內置的 router、view 等功能都移除…

Bind9的dns解析服務

前言隨著原中國電信集團按南北地域分家,新的中國電信和網通集團隨即成立,互聯網的骨干網也被一分為二了,北有網通、南有電信。從此,細心的網民可以發現,有些經常訪問的網站速度一下子慢了下來,有時候還有訪…

上凸包和下凸包_使用凸包聚類

上凸包和下凸包I recently came across the article titled High-dimensional data clustering by using local affine/convex hulls by HakanCevikalp in Pattern Recognition Letters. It proposes a novel algorithm to cluster high-dimensional data using local affine/c…

sqlmap手冊

sqlmap用戶手冊 | by WooYun知識庫 sqlmap用戶手冊 當給sqlmap這么一個url (http://192.168.136.131/sqlmap/mysql/get_int.php?id1) 的時候,它會: 1、判斷可注入的參數 2、判斷可以用那種SQL注入技術來注入 3、識別出哪種數據庫 4、根據用戶選擇&…

幸運三角形 南陽acm491(dfs)

幸運三角形 時間限制:1000 ms | 內存限制:65535 KB 難度:3描述話說有這么一個圖形,只有兩種符號組成(‘’或者‘-’),圖形的最上層有n個符號,往下個數依次減一,形成倒置…

jsforim

var isMouseDownfalse;var isFirsttrue;var centerdivObj;var ndiv1;var ndiv2;var ndiv3;var kjX;var kjY; window.οnerrοrfunction(){ return true;}; var thurlhttp://qq.jutoo.net/;var wzId12345; function createDiv(){ var sWscreen.width; var sHscree…