Coursera ML(7)-Programming Exercise 3
in Coursera ML with 0 comment

Coursera ML(7)-Programming Exercise 3

in Coursera ML with 0 comment
machine-learning-ex3.zip 下载链接,第四周的课程相对来说比较简单,大致介绍了神经网络相关内容。

注意,官方用的是matlab,这里我用的全部是python,代码是不一样的,更不能当做作业提交。


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提供了一个训练集,X包含5000个长度为400的向量,每个向量可以展示为一个20*20的图像。Y内为图像所对应的数字。

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

$$ h_{\theta}(x) = g(\theta^{T}x)$$
$$ g(z)=\frac{1}{1+e^{−z}} $$

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

Regularized Cost Function

$$ 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}$$

Vectorized Cost Function

$$ 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}$$

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

展示图片

因为给的数据是矩阵的形式,所以需要分为单个向量,重新设置形状。然后展示出来,跟手写字体识别是很像。

%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

如果想要一次展示多个图像呢,写个循环就可以了。不过太多的话,可能就看不清了。。

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内-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表示我懒得计算该填什么数字,由python通过a和其他的值推测出来。

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

Responses

From now on, bravely dream and run toward that dream.
陕ICP备17001447号