【学习自CS231n课程】

转载请注明出处:http://www.cnblogs.com/GraceSkyer/p/8735908.html

图像分类:

  一张图像的表示:长度、宽度、通道(3个颜色通道,分别是红R、绿G、蓝B)。

  对于计算机来说,图像是一个由数字组成的巨大的三维数组,数组元素是取值范围从0到255的整数,其中0表示全黑,255表示全白。

图像分类的任务:对于一个给定的图像,预测它属于的那个分类标签。

如何写图像分类算法呢?

数据驱动方法:

收集足够代表性的样本(数据),运用数学找到一个或者一组模型的组合使得它和真实的情况非常接近。之所以被称为数据驱动方法是因为它是现有大量的数据,而不是预设模型,然后用很多简单的模型来契合数据。
虽然通过这种方法找到的模型可能和真实模型存在一定的偏差,但是在误差允许的范围内,单从结果上和精确的模型是等效的。可以看出来数据驱动的方法目标就是近似替代,它甚至不是为了追求真实,仅仅是为了能够说明问题。
 

图像分类流程:

  图像分类:输入一个元素为像素值的数组,然后给它分配一个分类标签。完整流程如下:

  • 输入:输入是包含N个图像的集合,每个图像的标签是K种分类标签中的一种。这个集合称为训练集。
  • 学习:这一步的任务是使用训练集来学习每个类到底长什么样。一般该步骤叫做训练分类器或者学习一个模型
  • 评价:让分类器来预测它未曾见过的图像的分类标签,并以此来评价分类器的质量。我们会把分类器预测的标签和图像真正的分类标签对比。毫无疑问,分类器预测的分类标签和图像真正的分类标签如果一致,那就是好事,这样的情况越多越好。

Nearest Neighbor Classifier

最简单的分类器......

最近邻算法:在训练机器的过程中,我们什么也不做,我们只是单纯记录所有的训练数据,在图片预测的步骤,我们会拿一些新的图片去在训练数据中寻找与新图片最相似的,然后基于此,来给出一个标签。

例:用最近邻算法用于这数据集中的图片,在训练集中找到最接近的样本:图像分类数据集:CIFAR-10

  这个数据集包含了60000张32X32的小图像。每张图像都有10种分类标签中的一种。这60000张图像被分为包含50000张图像的训练集和包含10000张图像的测试集。

  我们需要的是,输入一张测试图片,从训练集中找出与它L1距离最近的一张训练图,将其所对应的分类标签作为答案,也就是作为测试图片的分类标签。

  下面,让我们看看如何用代码来实现这个分类器。首先,我们将CIFAR-10的数据加载到内存中,并分成4个数组:训练数据和标签,测试数据和标签。在下面的代码中,Xtr(大小是50000x32x32x3)存有训练集中所有的图像,Ytr是对应的长度为50000的1维数组,存有图像对应的分类标签(从0到9):

Xtr, Ytr, Xte, Yte = load_CIFAR10('data/cifar10/') # a magic function we provide
# flatten out all images to be one-dimensional
Xtr_rows = Xtr.reshape(Xtr.shape[0], 32 * 32 * 3) # Xtr_rows becomes 50000 x 3072
Xte_rows = Xte.reshape(Xte.shape[0], 32 * 32 * 3) # Xte_rows becomes 10000 x 3072

  现在我们得到所有的图像数据,并且把他们拉长成为行向量了。接下来展示如何训练并评价一个分类器:

nn = NearestNeighbor() # create a Nearest Neighbor classifier class
nn.train(Xtr_rows, Ytr) # train the classifier on the training images and labels
Yte_predict = nn.predict(Xte_rows) # predict labels on the test images
# and now print the classification accuracy, which is the average number
# of examples that are correctly predicted (i.e. label matches)
print 'accuracy: %f' % ( np.mean(Yte_predict == Yte) )

  作为评价标准,我们常常使用准确率,它描述了我们预测正确的得分。请注意以后我们实现的所有分类器都需要有这个API:train(X, y)函数。该函数使用训练集的数据和标签来进行训练。从其内部来看,类应该实现一些关于标签和标签如何被预测的模型。这里还有个predict(X)函数,它的作用是预测输入的新数据的分类标签。

L1距离(即两尺寸相同图对应位置间差异的和):

完整代码:

Python3 实现:【使用L1距离的Nearest Neighbor分类器】

【我是将cifar-10-batches-py数据放在代码同一目录下,代码中具体文件位置请根据情况自行设置】

 import numpy as np
import pickle
import os class NearestNeighbor(object):
def __init__(self):
pass def train(self, X, y):
""" X is N x D where each row is an example. Y is 1-dimension of size N """
# the nearest neighbor classifier simply remembers all the training data
self.Xtr = X
self.ytr = y def predict(self, X):
""" X is N x D where each row is an example we wish to predict label for """
num_test = X.shape[0]
# lets make sure that the output type matches the input type
Ypred = np.zeros(num_test, dtype=self.ytr.dtype) # loop over all test rows
for i in range(num_test):
# find the nearest training image to the i'th test image
# using the L1 distance (sum of absolute value differences)
distances = np.sum(np.abs(self.Xtr - X[i, :]), axis=1)
min_index = np.argmin(distances) # get the index with smallest distance
Ypred[i] = self.ytr[min_index] # predict the label of the nearest example return Ypred def load_CIFAR_batch(file):
""" load single batch of cifar """
with open(file, 'rb') as f:
datadict = pickle.load(f, encoding='latin1')
X = datadict['data']
Y = datadict['labels']
X = X.reshape(10000, 3, 32, 32).transpose(0, 2, 3, 1).astype("float")
Y = np.array(Y)
return X, Y def load_CIFAR10(ROOT):
""" load all of cifar """
xs = []
ys = []
for b in range(1,6):
f = os.path.join(ROOT, 'data_batch_%d' % (b, ))
X, Y = load_CIFAR_batch(f)
xs.append(X)
ys.append(Y)
Xtr = np.concatenate(xs) # 使变成行向量
Ytr = np.concatenate(ys)
del X, Y
Xte, Yte = load_CIFAR_batch(os.path.join(ROOT, 'test_batch'))
return Xtr, Ytr, Xte, Yte Xtr, Ytr, Xte, Yte = load_CIFAR10('data/cifar-10-batches-py/') # a magic function we provide
# flatten out all images to be one-dimensional
Xtr_rows = Xtr.reshape(Xtr.shape[0], 32 * 32 * 3) # Xtr_rows becomes 50000 x 3072
Xte_rows = Xte.reshape(Xte.shape[0], 32 * 32 * 3) # Xte_rows becomes 10000 x 3072 nn = NearestNeighbor() # create a Nearest Neighbor classifier class
nn.train(Xtr_rows, Ytr) # train the classifier on the training images and labels
Yte_predict = nn.predict(Xte_rows) # predict labels on the test images
# and now print the classification accuracy, which is the average number
# of examples that are correctly predicted (i.e. label matches)
print('accuracy: %f' % (np.mean(Yte_predict == Yte)))

然后我运行了很久......几个小时?

运行结果:accuracy: 0.385900

若用L2距离(欧式距离):

修改上面代码1行就可以:

distances = np.sqrt(np.sum(np.square(self.Xtr - X[i,:]), axis = 1))

关于简单分类器的问题:

  • 如果我们有N个实例,训练和测试的过程可以有多快?
  • Train:O(1),predict:O(n)

  这是糟糕的。训练是连续的过程,因为我们并不需要做任何事情, 我们只需存储数据。但在测试时,我们需要停下来,将数据集中N个训练实例 与我们的测试图像进行比较,这是个很慢的过程。

  但是在实际使用中,我们希望训练过程比较慢,而测试过程快。因为,训练过程是在数据中心中完成的,它可以负担起非常大的运算量,从而训练出一个优秀的分类器。 然而,当你在测试过程部署分类器时,你希望它运行在手机上、浏览器、或其他低功耗设备,但你又希望分类器能够快速地运行,由此看来,最近邻算法有点落后了。。。

参考:

https://www.bilibili.com/video/av17204303/?from=search&seid=6625954842411789830

https://zhuanlan.zhihu.com/p/20894041?refer=intelligentunit

https://blog.csdn.net/dawningblue/article/details/75119639

https://www.cnblogs.com/hans209/p/6919851.html

【cs231n】图像分类-Nearest Neighbor Classifier(最近邻分类器)【python3实现】的更多相关文章

  1. 【cs231n】图像分类 k-Nearest Neighbor Classifier(K最近邻分类器)【python3实现】

    [学习自CS231n课程] 转载请注明出处:http://www.cnblogs.com/GraceSkyer/p/8763616.html k-Nearest Neighbor(KNN)分类器 与其 ...

  2. CS231n——图像分类(KNN实现)

    图像分类   目标:已有固定的分类标签集合,然后对于输入的图像,从分类标签集合中找出一个分类标签,最后把分类标签分配给该输入图像.   图像分类流程 输入:输入是包含N个图像的集合,每个图像的标签是K ...

  3. cs231n笔记 (一) 线性分类器

    Liner classifier 线性分类器用作图像分类主要有两部分组成:一个是假设函数, 它是原始图像数据到类别的映射.另一个是损失函数,该方法可转化为一个最优化问题,在最优化过程中,将通过更新假设 ...

  4. Nearest neighbor graph | 近邻图

    最近在开发一套自己的单细胞分析方法,所以copy paste事业有所停顿. 实例: R eNetIt v0.1-1 data(ralu.site) # Saturated spatial graph ...

  5. Approximate Nearest Neighbors.接近最近邻搜索

    (一):次优最近邻:http://en.wikipedia.org/wiki/Nearest_neighbor_search 有少量修改:如有疑问,请看链接原文.....1.Survey:Neares ...

  6. K Nearest Neighbor 算法

    文章出处:http://coolshell.cn/articles/8052.html K Nearest Neighbor算法又叫KNN算法,这个算法是机器学习里面一个比较经典的算法, 总体来说KN ...

  7. Visualizing MNIST with t-SNE, MDS, Sammon’s Mapping and Nearest neighbor graph

    MNIST 可视化 Visualizing MNIST: An Exploration of Dimensionality Reduction At some fundamental level, n ...

  8. Nearest Neighbor Search

    ## Nearest Neighbor Search ## Input file: standard input Output file: standard output Time limit: 1 ...

  9. K NEAREST NEIGHBOR 算法(knn)

    K Nearest Neighbor算法又叫KNN算法,这个算法是机器学习里面一个比较经典的算法, 总体来说KNN算法是相对比较容易理解的算法.其中的K表示最接近自己的K个数据样本.KNN算法和K-M ...

随机推荐

  1. (二)this、call和apply

    在javascript中,this关键字总让一些初学者迷惑,Function.prototype.call, Function.prototype.apply这两个方法广泛的运用.我们有必要理解这几个 ...

  2. Error creating bean with name 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0': Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: org.springframework

    昨晚在 使用spring aop, 然后Tomcat启动的时候, 报了这么个错: Caused by: org.springframework.beans.factory.BeanCreationEx ...

  3. c#无边窗体实现移动的两种方式

    转载:http://blog.csdn.net/dxsh126/article/details/2940226 首先,要用到一个WimdowsAPI函数,因此必须引入 using System.Run ...

  4. js dictionary字典 遍历

    var dic={A:"AA",B:"BB",C:"CC"} //不能length去for循环(length:undefined) dic[ ...

  5. C# 生成缩略图 去除图片旋转角度

    图片生成缩略图会有旋转角度 /// <summary> /// 测试JRE图片压缩后图片会旋转问题 /// </summary> public void Uploadimg1( ...

  6. 企业实施ERP的先后步骤,你真的了解吗?

    信息化是我国加快实现工业化和现代化的必然选择.坚持以信息化带动工业化,以工业化促进信息化,在国民经济和社会领域广泛采用信息技术.国民经济信息化中企业的信息化工作是基础, ERP管理系统是IT技术和先进 ...

  7. is_palindrome 回文递归

    # coding=utf-8def is_palindrome(n,start,end): if start>end: return 1 else: return is_palindrome(n ...

  8. maven 编译插件指定jdk版本的两种方式

    第一种方式: <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration&g ...

  9. Python Socket实现简单web服务器

    #!/usr/bin/python env # coding:utf-8 import socket ip_port = ('127.0.0.1', 80) back_log = 10 buffer_ ...

  10. Linux 加阿里yum源

    阿里 yum 源设置 阿里云Linux安装镜像源地址:http://mirrors.aliyun.com/CentOS系统更换软件安装源 第一步:备份你的原镜像文件,以免出错后可以恢复.mv /etc ...