Machine Learning(Andrew) ex3-Multi-class Classification and Neural Networks
椰汁笔记
Multi-class Classification
- 1.1 Dataset
这里的数据存储变成了.mat的格式,这样的数据选择借助scipy.io.loadmat()实现
import scipy.io as sio
data = sio.loadmat("ex3data1.mat")
print(data.keys())#查看其中包含的key-value键值对
X = data['X']#通过字典的访问方式得到数据
y = data['y']
其中X和y都是numpy数组,X(5000,400),y(5000,1),其中X存储的是5000张20x20pixel的图片,y是图片对应的数字
- 1.2 Visualizing the data
可视化其中一部分图片,图片是按照代表的数字大小顺序存储的,为了更好的呈现数据集,重其中随机选择若干张图片,并拼接成一个大的图片显示(这里是我想多了,可以直接通过matplotlib.pyplot的subplot实现,既然做了就这样吧)
def randomly_select(images, numbers):
"""
从images中选择numbers张图片
parameters:
----------
images : ndarray
多干张图片
numbers : int
随机选择的图片数量
"""
m = images.shape[0]
n = images.shape[1]
flags = np.zeros((m,), bool)
res = False
for i in range(numbers):
index = random.randint(0, m - 1)
while flags[index]:
index = random.randint(0, m)
if type(res) == bool:
res = images[index].reshape(1, n)
else:
res = np.concatenate((res, images[index].reshape(1, n)), axis=0)
return res
def mapping(images, images_dimension):
"""
将若干张图片,组成一张图片
parameters:
----------
images : ndarray
多干张图片
images_dimension : int
新的正方形大图片中一边上有多少张图片
"""
image_dimension = int(np.sqrt(images.shape[-1]))
image = False
im = False
for i in images:
if type(image) == bool:
image = i.reshape(image_dimension, image_dimension)
else:
if image.shape[-1] == image_dimension * images_dimension:
if type(im) == bool:
im = image
else:
im = np.concatenate((im, image), axis=0)
image = i.reshape(image_dimension, image_dimension)
else:
image = np.concatenate((image, i.reshape(image_dimension, image_dimension)), axis=1)
return np.concatenate