Coursera ML(7)-Programming Exercise 3

machine-learning-ex3.zip 下載鏈接,第四周的課程相對(duì)來(lái)說(shuō)比較簡(jiǎn)單混聊,大致介紹了神經(jīng)網(wǎng)絡(luò)相關(guān)內(nèi)容。更多見(jiàn):iii.run


注意乾巧,官方用的是matlab句喜,這里我用的全部是python,代碼是不一樣的沟于,更不能當(dāng)做作業(yè)提交咳胃。


Programming Exercise 3 - Multi-class Classification and Neural Networks

題目介紹

For this exercise, you will use logistic regression and neural networks to recognize handwritten digits (from 0 to 9).

ex3data1.mat提供了一個(gè)訓(xùn)練集,X包含5000個(gè)長(zhǎng)度為400的向量旷太,每個(gè)向量可以展示為一個(gè)20*20的圖像拙绊。Y內(nèi)為圖像所對(duì)應(yīng)的數(shù)字。

Code

# %load ../../standard_import.txt
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

# load MATLAB files
from scipy.io import loadmat
from scipy.optimize import minimize

from sklearn.linear_model import LogisticRegression

pd.set_option('display.notebook_repr_html', False)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', 150)
pd.set_option('display.max_seq_items', None)
 
#%config InlineBackend.figure_formats = {'pdf',}
%matplotlib inline

import seaborn as sns
sns.set_context('notebook')
sns.set_style('white')

Load MATLAB datafiles

data = loadmat('data/ex3data1.mat')
data.keys()
dict_keys(['__header__', '__version__', '__globals__', 'X', 'y'])
weights = loadmat('data/ex3weights.mat')
weights.keys()
dict_keys(['__header__', '__version__', '__globals__', 'Theta1', 'Theta2'])
y = data['y']
# Add constant for intercept
X = np.c_[np.ones((data['X'].shape[0],1)), data['X']]

print('X: {} (with intercept)'.format(X.shape))
print('y: {}'.format(y.shape))
X: (5000, 401) (with intercept)
y: (5000, 1)
theta1, theta2 = weights['Theta1'], weights['Theta2']

print('theta1: {}'.format(theta1.shape))
print('theta2: {}'.format(theta2.shape))
theta1: (25, 401)
theta2: (10, 26)
sample = np.random.choice(X.shape[0], 20)
plt.imshow(X[sample,1:].reshape(-1,20).T)
plt.axis('off');

Multiclass Classification

Logistic regression hypothesis

{% raw %} $$ h_{\theta}(x) = g(\theta^{T}x)$${% endraw %}
{% raw %} $$ g(z)=\frac{1}{1+e^{?z}} $${% endraw %}

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

Regularized Cost Function

{% raw %} $$ J(\theta) = \frac{1}{m}\sum_{i=1}{m}\big[-y{(i)}, log,( h_\theta,(x{(i)}))-(1-y{(i)}),log,(1-h_\theta(x^{(i)}))\big] + \frac{\lambda}{2m}\sum_{j=1}{n}\theta_{j}{2}$${% endraw %}

Vectorized Cost Function

{% raw %} $$ J(\theta) = \frac{1}{m}\big((,log,(g(X\theta))Ty+(,log,(1-g(X\theta))T(1-y)\big) + \frac{\lambda}{2m}\sum_{j=1}{n}\theta_{j}{2}$${% endraw %}

def lrcostFunctionReg(theta, reg, X, y):
    m = y.size
    h = sigmoid(X.dot(theta))
    
    J = -1*(1/m)*(np.log(h).T.dot(y)+np.log(1-h).T.dot(1-y)) + (reg/(2*m))*np.sum(np.square(theta[1:]))
    
    if np.isnan(J[0]):
        return(np.inf)
    return(J[0])    
def lrgradientReg(theta, reg, X,y):
    m = y.size
    h = sigmoid(X.dot(theta.reshape(-1,1)))
      
    grad = (1/m)*X.T.dot(h-y) + (reg/m)*np.r_[[[0]],theta[1:].reshape(-1,1)]
        
    return(grad.flatten())

One-vs-all

One-vs-all Classification

def oneVsAll(features, classes, n_labels, reg):
    initial_theta = np.zeros((X.shape[1],1))  # 401x1
    all_theta = np.zeros((n_labels, X.shape[1])) #10x401

    for c in np.arange(1, n_labels+1):
        res = minimize(lrcostFunctionReg, initial_theta, args=(reg, features, (classes == c)*1), method=None,
                       jac=lrgradientReg, options={'maxiter':50})
        all_theta[c-1] = res.x
    return(all_theta)
theta = oneVsAll(X, y, 10, 0.1)

One-vs-all Prediction

def predictOneVsAll(all_theta, features):
    probs = sigmoid(X.dot(all_theta.T))
        
    # Adding one because Python uses zero based indexing for the 10 columns (0-9),
    # while the 10 classes are numbered from 1 to 10.
    return(np.argmax(probs, axis=1)+1)
pred = predictOneVsAll(theta, X)
print('Training set accuracy: {} %'.format(np.mean(pred == y.ravel())*100))
Training set accuracy: 93.24 %

Multiclass Logistic Regression with scikit-learn

clf = LogisticRegression(C=10, penalty='l2', solver='liblinear')
# Scikit-learn fits intercept automatically, so we exclude first column with 'ones' from X when fitting.
clf.fit(X[:,1:],y.ravel())
LogisticRegression(C=10, class_weight=None, dual=False, fit_intercept=True,
          intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,
          penalty='l2', random_state=None, solver='liblinear', tol=0.0001,
          verbose=0, warm_start=False)
pred2 = clf.predict(X[:,1:])
print('Training set accuracy: {} %'.format(np.mean(pred2 == y.ravel())*100))
Training set accuracy: 96.5 %

Neural Networks

def predict(theta_1, theta_2, features):
    z2 = theta_1.dot(features.T)
    a2 = np.c_[np.ones((data['X'].shape[0],1)), sigmoid(z2).T]
    
    z3 = a2.dot(theta_2.T)
    a3 = sigmoid(z3)
        
    return(np.argmax(a3, axis=1)+1) 
pred = predict(theta1, theta2, X)
print('Training set accuracy: {} %'.format(np.mean(pred == y.ravel())*100))
Training set accuracy: 97.52 %

Summary

展示圖片

因?yàn)榻o的數(shù)據(jù)是矩陣的形式泳秀,所以需要分為單個(gè)向量标沪,重新設(shè)置形狀。然后展示出來(lái)嗜傅,跟手寫(xiě)字體識(shí)別是很像金句。

%matplotlib inline
import scipy.io as sio 
import matplotlib.pyplot as plt
matfn='C:/Users/wing/Documents/MATLAB/ex3/ex3data1.mat'  
data=sio.loadmat(matfn)  
im = data['X'][0]
im = im.reshape(20,20)
plt.imshow(im , cmap='gray')
mark

如果想要一次展示多個(gè)圖像呢,寫(xiě)個(gè)循環(huán)就可以了吕嘀。不過(guò)太多的話违寞,可能就看不清了。偶房。

im = []
for i in range(500):
    plt.subplot(10, 50, i + 1)
    temp = data['X'][i]
    im.append(temp.reshape(20,20))
    plt.imshow(im[i], cmap='gray')
plt.show()

reshape內(nèi)-1的用法

官方文檔:numpy.reshape - NumPy v1.11 Manual

>>> a = np.array([[1,2,3], [4,5,6]])
>>> np.reshape(a, (3,-1))  # the unspecified value is inferred to be 2
array([[1, 2],
       [3, 4],
       [5, 6]])

-1表示我懶得計(jì)算該填什么數(shù)字趁曼,由python通過(guò)a和其他的值推測(cè)出來(lái)。

LogisticRegression

from sklearn.linear_model import LogisticRegression

http://www.cnblogs.com/xupeizhi/archive/2013/07/05/3174703.html
http://scikit-learn.org/stable/index.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末棕洋,一起剝皮案震驚了整個(gè)濱河市挡闰,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌掰盘,老刑警劉巖摄悯,帶你破解...
    沈念sama閱讀 218,122評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異愧捕,居然都是意外死亡奢驯,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)次绘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)瘪阁,“玉大人撒遣,你說(shuō)我怎么就攤上這事」芏澹” “怎么了义黎?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,491評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)伙菜。 經(jīng)常有香客問(wèn)我,道長(zhǎng)命迈,這世上最難降的妖魔是什么贩绕? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,636評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮壶愤,結(jié)果婚禮上淑倾,老公的妹妹穿的比我還像新娘。我一直安慰自己征椒,他們只是感情好娇哆,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著勃救,像睡著了一般碍讨。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上蒙秒,一...
    開(kāi)封第一講書(shū)人閱讀 51,541評(píng)論 1 305
  • 那天勃黍,我揣著相機(jī)與錄音,去河邊找鬼晕讲。 笑死覆获,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的瓢省。 我是一名探鬼主播弄息,決...
    沈念sama閱讀 40,292評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼勤婚!你這毒婦竟也來(lái)了摹量?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,211評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤馒胆,失蹤者是張志新(化名)和其女友劉穎荆永,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體国章,經(jīng)...
    沈念sama閱讀 45,655評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡具钥,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了液兽。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片骂删。...
    茶點(diǎn)故事閱讀 39,965評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡掌动,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出宁玫,到底是詐尸還是另有隱情粗恢,我是刑警寧澤,帶...
    沈念sama閱讀 35,684評(píng)論 5 347
  • 正文 年R本政府宣布欧瘪,位于F島的核電站眷射,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏佛掖。R本人自食惡果不足惜妖碉,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評(píng)論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望芥被。 院中可真熱鬧欧宜,春花似錦、人聲如沸拴魄。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,894評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)匹中。三九已至夏漱,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間顶捷,已是汗流浹背麻蹋。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,012評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留焊切,地道東北人扮授。 一個(gè)月前我還...
    沈念sama閱讀 48,126評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像专肪,于是被迫代替她去往敵國(guó)和親刹勃。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容