Ex3_机器学习_吴恩达课程作业(Python):多分类和神经网络(Multi-class Classification & Neural Networks)
文章目录
- Ex3_机器学习_吴恩达课程作业(Python):多分类和神经网络(Multi-class Classification & Neural Networks)
- 0. Pre-condition
- 00. Self-created Functions
-
-
-
- loadData(path):读取.mat数据
- loadWeight(path):用于前置传播算法,读取神经网络各层的权重数据
- plotOneImage(X, y):读取并处理被压缩的灰度图像数据,可视化之
- plot100Images(X):读取并处理100条被压缩的灰度图像数据,可视化之
- sigmoid(z):激活函数
- logisticRegCost(theta, X, y, l):计算正规化逻辑回归的损失
- logisticRegGradient(theta, X, y, l):计算正规化逻辑回归的梯度
- oneVsAll(X, y, l, K):训练一对多分类的分类器,返回参数数组
- predictOneVsAll(X, all_theta):用训练得到的多分类器进行预测
-
-
- 1. Multi-class Classification
- 2. Neural Networks
使用说明:
本文章为关于吴恩达老师在Coursera上的机器学习课程的学习笔记。
- 本文第一部分首先介绍课程对应周次的知识回顾以及重点笔记,以及代码实现的库引入。
- 本文第二部分包括代码实现部分中的自定义函数实现细节。
- 本文第三部分即为与课程练习题目相对应的具体代码实现。
0. Pre-condition
This section includes some introductions of libraries.
# This file includes self-created functions used in exercise 3
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as opt
from scipy.io import loadmat
00. Self-created Functions
This section includes self-created functions.
-
loadData(path):读取.mat数据
# Load data from the given file 读取数据 def loadData(path): df = loadmat(path) X = df['X'] y = df['y'] return X, y
-
loadWeight(path):用于前置传播算法,读取神经网络各层的权重数据
# Load weight data from the given file 读取权重数据 def loadWeight(path): df = loadmat(path) return df['Theta1'], df['Theta2']
-
plotOneImage(X, y):读取并处理被压缩的灰度图像数据,可视化之
# Randomly pick a training example and visualize it # 随机选取一个训练样本,并且将其可视化 def plotOneImage(X, y): # Randomly pick a number ranging from 0 to the size of given training examples index = np.random.randint(0, X.shape[0]) # Get the data of the random image 获取灰度图像数据 image_data = X[index, :] # Reshape the vector into the gray image matrix 还原被压缩的图像数据向量为20x20数组 image = image_data.reshape((20, 20)) # Plot the figure 可视化 fig, fig_image = plt.subplots(figsize=[4, 4]) fig_image.matshow(image, cmap='gray_r') plt.xticks([]) # 去除图像上的刻度 plt.yticks([]) plt.title('Image: ' + format(y[index])) # print('This image should be ', format(y[index])) plt.show()
-
plot100Images(X):读取并处理100条被压缩的灰度图像数据,可视化之
# Randomly pick 100 training examples and visualize them # 随机选取100个训练样本,并且将其可视化 def plot100Images(X): # Randomly pick 100 numbers ranging from 0 to the size of given training examples indexes = np.random.choice(np.arange(X.shape[0])