Coursera ML(7)-Programming Exercise 3

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# %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

1
2
data = loadmat('data/ex3data1.mat')
data.keys()
dict_keys(['__header__', '__version__', '__globals__', 'X', 'y'])
1
2
weights = loadmat('data/ex3weights.mat')
weights.keys()
dict_keys(['__header__', '__version__', '__globals__', 'Theta1', 'Theta2'])
1
2
3
4
5
6
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)
1
2
3
4
theta1, theta2 = weights['Theta1'], weights['Theta2']

print('theta1: {}'.format(theta1.shape))
print('theta2: {}'.format(theta2.shape))
theta1: (25, 401)
theta2: (10, 26)
1
2
3
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

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

Regularized Cost Function

Vectorized Cost Function

1
2
3
4
5
6
7
8
9
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])
1
2
3
4
5
6
7
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

1
2
3
4
5
6
7
8
9
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)
1
theta = oneVsAll(X, y, 10, 0.1)

One-vs-all Prediction

1
2
3
4
5
6
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)
1
2
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

1
2
3
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)
1
2
pred2 = clf.predict(X[:,1:])
print('Training set accuracy: {} %'.format(np.mean(pred2 == y.ravel())*100))
Training set accuracy: 96.5 %

Neural Networks

1
2
3
4
5
6
7
8
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)
1
2
pred = predict(theta1, theta2, X)
print('Training set accuracy: {} %'.format(np.mean(pred == y.ravel())*100))
Training set accuracy: 97.52 %

Summary

展示图片

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

1
2
3
4
5
6
7
8
%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

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

1
2
3
4
5
6
7
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

1
2
3
4
5
>>> 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

Coursera ML(7)-Programming Exercise 3

https://iii.run/archives/2779503e9fbb.html

作者

mmmwhy

发布于

2017-05-02

更新于

2022-10-30

许可协议

评论