Hi folks,

嗨伙计,

Today we are going to understand how active learning can be used in data labeling.

今天,我们将了解如何在数据标记中使用主动学习。

Machine learning algorithms require -generally lots of- enough amount of data to be trained. In this stage obviously humans can label data by their hands. But what will be happened if there is no enough money to use AMT like services?

机器学习算法通常需要大量的数据才能进行训练。 在这个阶段,显然人类可以用手标记数据。 但是,如果没有足够的资金来使用类似AMT的服务,将会发生什么?

If you’re suffering from this situation, yes there is one more salvation way to label your data. And your hero’s name is Active Learning!

如果您正遭受这种情况的困扰,是的,还有另一种挽救方式来标记您的数据。 而你的英雄的名字叫主动学习!

By the way this post is my first tutorial on Medium so i’m not going talk to much :)

顺便说一句,这篇文章是我关于Medium的第一个教程,所以我不打算讨论太多:)

So i’m going to give you naive active learning labeling strategy to implement yourself using Python, Scikit-learn on FashionMnist dataset.

因此,我将为您提供天真的主动学习标签策略,以使用Python和FashionMnist数据集上的Scikit-learn实现自己。

Here are the steps;

步骤如下;

1- Label only small part of your data — lets call it “df_labeled”

1-仅标记您数据的一小部分-让我们称其为“ df_labeled”

2- Train a classifier (Linear SVM will be used in here) with these data

2-使用这些数据训练分类器(此处将使用线性SVM)

3- Using your trained classifier -which comes from in step 2- predict the class probabilities for your unlabeled data — lets call it “df_unlabeled”

3-使用受过训练的分类器-来自步骤2-预测未标记数据的分类概率-称之为“ df_unlabeled”

4- Foreach sample if predicted class probability is above from your pre-defined threshold, -yes, its a hyperparam :(- move that sample from “df_unlabeled” to “df_labeled”

4- Foreach样本,如果预测的类别概率高于您的预定义阈值-是,则为超参数:(-将样本从“ df_unlabeled”移到“ df_labeled”

5- Repeat 2–4 step until some sort of stopping criteria

5-重复2–4步,直到达到某种停止标准

Of course, there are many different starategies can be existed. For example, after 4.th step you can define one more threshold for lowest boundary and if predicted class probability is below from that threshold, this sample can be labeled manually and then will be moved to “df_labeled”.

当然,可以存在许多不同的starategies。 例如,在第4步之后,您可以为最低边界再定义一个阈值,并且如果预测的类别概率低于该阈值,则可以手动标记该样本,然后将其移至“ df_labeled”。

Yes, i hope we got the main concept for active labeling. And the time comes to the coding section.

是的,我希望我们掌握了有源标签的主要概念。 时间到了编码部分。

Import libraries which will be used in this notebook

导入将在此笔记本中使用的库

import pandas as pdimport numpy as npfrom tensorflow.keras.datasets import fashion_mnistimport matplotlib.pyplot as pltimport randomimport cv2from sklearn import svmfrom sklearn.metrics import confusion_matrix, classification_report

Now import FashionMnist dataset;

现在导入FashionMnist数据集;

((trainX, trainY), (testX, testY)) = fashion_mnist.load_data()

Now define HoG features to transform raw pixels to feature set;

现在定义HoG特征以将原始像素转换为特征集;

def hog_feature_extractor(hog_extractor, im):

    descriptor = hog_extractor.compute(im)

    return descriptor# Hog ParameterswinSize = (28,28)blockSize = (14,14)blockStride = (7,7)cellSize = (7,7)nbins = 9derivAperture = 1winSigma = -1.histogramNormType = 0L2HysThreshold = 0.2gammaCorrection = 1nlevels = 64useSignedGradients = Truehog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins,derivAperture,winSigma,histogramNormType,L2HysThreshold,gammaCorrection,nlevels, useSignedGradients)

To see data sample in visual;

以可视方式查看数据样本;

def show_sample(x,y,i):    print("Label: {}".format(y[i]))    plt.imshow(x[i], cmap="gray");

For name convention;

为了命名惯例;

df_x = trainXdf_y = trainY

Lets see our labels

让我们看看我们的标签

nclasses = set(df_y)print(nclasses)

Now, its time to select subset from our data — be aware; our dataset has already labelled otherwise we have to do it manually-

现在,是时候从我们的数据中选择子集了。 我们的数据集已经标记了,否则我们必须手动进行操作-

# what percentage of data is used initiallypercentage = 1selected_indices = []for c in nclasses:

    indices_c = list(np.where(df_y == c))[0]    len_c = len(list(np.where(df_y == c))[0])    len_c_subset = int(len_c * percentage / 100)

    df_c_subset = random.sample(list(indices_c), len_c_subset)    selected_indices += df_c_subset

    print("There are '{}' images for class label '{}' and selected only '{}' for active learning.".format(len_c, c, len_c_subset))    print("----")

df_subset_x = df_x[selected_indices]df_subset_y = df_y[selected_indices]

Lets see how many samples we have;

让我们看看我们有多少样本;

print("Subset {}, {}".format(df_subset_x.shape, df_subset_y.shape))

And see what is the remaning set;

看看还剩下什么?

df_remainder_x = np.delete(df_x, selected_indices, axis=0)df_remainder_y = np.delete(df_y, selected_indices, axis=0)print("Remainder {}, {}".format(df_remainder_x.shape, df_remainder_y.shape))

Now its time to extract HoG features from images;

现在是时候从图像中提取HoG功能了;

# Feature Extractiondf_subset_x_hog = []for elem in df_subset_x:    df_subset_x_hog.append(hog_feature_extractor(hog, elem).reshape(-1))df_remainder_x_hog = []for elem in df_remainder_x:    df_remainder_x_hog.append(hog_feature_extractor(hog, elem).reshape(-1))df_subset_y_hog = list(df_subset_y.copy())df_remainder_y_hog = list(df_remainder_y.copy())

Now check how many sample is recognized as a labeled

现在检查有多少样品被识别为标记

print("Labeled {}, Unlabelled {}".format(len(df_subset_x_hog),len(df_remainder_x_hog)))

As mentioned in step 5, i used no evaluation criteria, just number of iteration is used in here; -For 10 iteration, we repeat our process with decreasing upper threshold from 0.75 to 0.25-

如第5步所述,我没有使用评估标准,这里只使用了迭代次数; -对于10次迭代,我们将上限阈值从0.75降低到0.25,以重复进行此过程-

for iteration in range(10):

    clf=svm.LinearSVC()    clf.fit(df_subset_x_hog, df_subset_y_hog)

    res = clf._predict_proba_lr(df_remainder_x_hog)

    # Params for unlabeled samples    threshold = 0.75 - (iteration * 0.05)del_indices = []    for sample_counter in range(len(res)):

        if res[sample_counter][np.argmax(res[sample_counter])] > threshold:            predicted_label = np.argmax(res[sample_counter])df_subset_x_hog.append(list(df_remainder_x_hog[sample_counter]))            df_subset_y_hog.append(df_remainder_y_hog[sample_counter])del_indices.append(sample_counter)

    df_remainder_x_hog = [i for j, i in enumerate(df_remainder_x_hog) if j not in del_indices]    df_remainder_y_hog = [i for j, i in enumerate(df_remainder_y_hog) if j not in del_indices]

    print("Iteration: {} has done...".format(iteration))

And the finally 21009 of data sample from unlabeled set is still unlabeled;

来自未标记集合的最后21009个数据样本仍未标记;

print("Remain: {}, Labeled: {}".format(len(df_remainder_x_hog), len(df_subset_x_hog)))

Now we decrease our upper-threshold to 0.10 and make training again

现在我们将上限阈值降低到0.10,然后再次进行训练

# Finally label without thresholdclf=svm.LinearSVC()clf.fit(df_subset_x_hog, df_subset_y_hog)res = clf._predict_proba_lr(df_remainder_x_hog)

# Params for unlabeled samplesthreshold = 0.1del_indices = []for sample_counter in range(len(res)):if res[sample_counter][np.argmax(res[sample_counter])] > threshold:        predicted_label = np.argmax(res[sample_counter])df_subset_x_hog.append(list(df_remainder_x_hog[sample_counter]))        df_subset_y_hog.append(df_remainder_y_hog[sample_counter])del_indices.append(sample_counter)df_remainder_x_hog = [i for j, i in enumerate(df_remainder_x_hog) if j not in del_indices]df_remainder_y_hog = [i for j, i in enumerate(df_remainder_y_hog) if j not in del_indices]

Finally, lets see our performance on test set;

最后,让我们看一下测试集的性能;

# Test this model with test setdf_test_x_hog = []for elem in testX:    df_test_x_hog.append(hog_feature_extractor(hog, elem).reshape(-1))test_res = clf.predict(df_test_x_hog)print(confusion_matrix(testY, test_res,  labels=[0,1,2,3,4,5,6,7,8,9]))print(classification_report(testY, test_res, labels=[0,1,2,3,4,5,6,7,8,9]))

And this is our active labeling based classifier performance on test set;

这是我们在测试集上基于主动标记的分类器性能;

precision    recall  f1-score   support

           0       0.83      0.81      0.82      1000           1       0.95      0.96      0.96      1000           2       0.78      0.80      0.79      1000           3       0.83      0.86      0.85      1000           4       0.75      0.83      0.79      1000           5       0.98      0.96      0.97      1000           6       0.70      0.58      0.63      1000           7       0.94      0.97      0.95      1000           8       0.96      0.97      0.96      1000           9       0.97      0.96      0.96      1000

    accuracy                           0.87     10000   macro avg       0.87      0.87      0.87     10000weighted avg       0.87      0.87      0.87     10000

Actually you may want to ask this; what will be happened if we use all training set? Now we are going to train another classifier that uses all training set

实际上,您可能想问这个; 如果我们使用所有训练集会发生什么? 现在我们要训练另一个使用所有训练集的分类器

## What happen if we use all training samples# Test this model with test setdf_train_x_hog = []for elem in trainX:    df_train_x_hog.append(hog_feature_extractor(hog, elem).reshape(-1))clf=svm.LinearSVC()clf.fit(df_train_x_hog, trainY)test_res = clf.predict(df_test_x_hog)print(confusion_matrix(testY, test_res,  labels=[0,1,2,3,4,5,6,7,8,9]))print(classification_report(testY, test_res, labels=[0,1,2,3,4,5,6,7,8,9]))

And its classification report looks like this;

其分类报告如下:

precision    recall  f1-score   support

           0       0.84      0.87      0.86      1000           1       0.99      0.98      0.98      1000           2       0.84      0.83      0.83      1000           3       0.88      0.92      0.90      1000           4       0.80      0.84      0.82      1000           5       0.98      0.97      0.98      1000           6       0.74      0.66      0.69      1000           7       0.94      0.97      0.96      1000           8       0.97      0.97      0.97      1000           9       0.97      0.96      0.97      1000

    accuracy                           0.90     10000   macro avg       0.90      0.90      0.90     10000weighted avg       0.90      0.90      0.90     10000

结论 (Conclusion)

When we analyze the results; if we have only 600 images labeled, this strategy obtains 0.87 F1-Score. And in the case of usage of all labeled data -60k- we obtain 0.90 F1-Score.

当我们分析结果时; 如果我们仅标记了600张图像,则此策略可获得0.87 F1-Score。 在使用所有标记数据-60k的情况下,我们得到0.90 F1-得分。

Of course we have low performance on 6.th class with 0.63 F1-Score but fortunately it doesn’t change too much when we use all the data.

当然,使用0.63 F1-Score在6.th类中的性能较低,但是幸运的是,使用所有数据时,它的变化不会太大。

Thank you for your reading. And all contributions of corrections are warmly welcome :)

感谢您的阅读。 热烈欢迎所有更正的贡献:)

Peace at home, peace in the world!

家庭的和谐才能使世界和平!

翻译自: https://medium.com/@eroltak/active-learning-for-labeling-in-python-cde06d54baf1


http://www.taodudu.cc/news/show-5240823.html

相关文章:

  • 有源医疗器械说明书如何编写?附核查清单
  • 【mcuclub】声光报警
  • 物联网与有源电子标签
  • 有源标签方案SI24R2H单发射2.4G内置单片机+125KHz低频唤醒芯片分享
  • 物联网新产品 | 凸版推出可远距离通讯的有源标签“ZETag”
  • windows创建虚拟磁盘
  • 使用grub实现虚拟软盘
  • dd写入虚拟软盘第一扇区而不截断
  • 我的世界网易服务器聊天消息记录,我的世界更新汇总:版本更新,网易爆料,周边消息...
  • [转] 亚洲销售女神徐鹤宁经典语录——太过精辟,不学必悔
  • 第二代交友网站暗潮涌动
  • 专注95后 “友加”打造最受年轻人喜爱的交友社区
  • 诉说一个站长屌丝20多年的点点滴滴
  • 我给网上交友看看病
  • 关于2022年卡塔尔世界杯
  • 亚洲销售女神徐鹤宁经典语录——太过精辟,不学必悔
  • 张曼玉 杨思敏 陈慧琳等众多明星成为亚洲交友代言人
  • 2022第五届上海国际网红品牌博览会
  • 探花交友day3,4
  • 原:亚洲交友联盟注册全攻略
  • 申请亚洲交友中心广告联盟教程
  • 亚洲交友中心
  • HTML 模仿百度首页 (html+css)
  • 百度地图api html信息窗口,百度地图API实战
  • 引用百度地图做的导航路径
  • Android 百度地图开发--- 导航功能输入起始地址实现导航,地址解析与反解析的使用
  • PHP实现百度人脸识别
  • 百度地图定位开发流程
  • 百度地图的使用方法,如何在Vue项目中使用百度地图
  • java 接入百度地图api

主动学习python中的标签相关推荐

  1. python中continue用法案例_记录今天学习python中for与while循环针对break和continue的用法...

    python中有两个主要的循环for与while,其中针对这两个循环有两种不同的中断用法break与continue. 首先先看下面的循环代码: 1: for i in range(10):#变量i带 ...

  2. php video标签使用方法,HTML_HTML5 video标签(播放器)学习笔记(一):使用入门,近有在学习html5中video标签(播 - phpStudy...

    HTML5 video标签(播放器)学习笔记(一):使用入门 近有在学习html5中video标签(播放器)的使用,这里做一些学习笔记,方便自己查阅和记录,本文是第一篇,将介绍的是使用该标签初始化该做 ...

  3. Python基础学习-Python中最常见括号()、[]、{}的区别 2015-08-13 07:54 by xuxiaoxiaoxiaolu, 1138 阅读, 0 评论, 收藏, 编辑 Pytho

    Python基础学习-Python中最常见括号().[].{}的区别 2015-08-13 07:54 by xuxiaoxiaoxiaolu, 1138 阅读, 0 评论, 收藏, 编辑 Pytho ...

  4. 中英文学习Python中的字典类型

    中英文学习Python中的字典类型 请看视频: Python中的字典类型,中英文学习,并简单介绍了哈希

  5. 更少标注的机器学习方法——主动学习(python示例)

    本文尝试使用GIF演示,具体细节可见下面文章~ 准备工作 假设我们正要完成手写数字识别的任务.我们可以使用著名的mnist数据集来训练这样的机器学习模型.数字示例如下: 总共有1797个数字,每个数字 ...

  6. python自学教程推荐-学习python中的pandas有没有好的教程推荐?

    上来就丢教程和资料,其实是把路带偏了!找到学习Pandas的方法比找教程重要的多!现在无论是学习Python还是Pandas,最大的问题不是没有资料,而恰恰是太多资料和教程,让人抓不住头绪. 很多凭着 ...

  7. 在学习Python中,这个知识我们一定要看一遍,记不住没关系单一定要知道,字符串常用函数用法

    str.index(sub, start=None, end=None) 作用:查看sub是否在字符串中,在的话返回索引,且只返回第一次匹配到的索引:若找不到则报错:可以指定统计的范围,[start, ...

  8. python中填充颜色结束的程序_在ttk/python中更改标签小部件的填充颜色

    我试图用python中的ttk/tkinter显示图像.图像有一个白色的边框,我想在一个更大的白色背景上显示这个图像,所以它周围有很多空白.在 为此,我在标签中使用"padx"和& ...

  9. python中的文件处理_python学习——python中的文件处理

    python对文件的处理. python对文件的处理的两个内建函数: open().file(),这个两函数提供了初始化输入\输出(I\O)操作的通用接口.两函数的功能相同. 基本用法: file_o ...

最新文章

  1. 将动态aspx页面转换成为静态html页面的几种方法
  2. CWNA考试常见RF术语
  3. 贵州2021高考状元成绩查询,2021年贵州高考最高分多少分,历年贵州高考状元
  4. 关于haproxy的重定向
  5. SVN 本地文件锁/服务端文件锁清除步骤
  6. js中 javascript:void(0) 用法详解
  7. loj2245 [NOI2014]魔法森林 LCT
  8. 如何更好的掌握一个知识点_如何成为一个更好的讲故事的人3个关键点
  9. String,StringBuffer,StringBuilder简单对比
  10. 日志单例log4cpp简述
  11. 外边距的典型应用-让块级盒子水平居中(HTML、CSS)
  12. 三国演义人物出场统计代码含义_用python分析小说人物关系(二)——实战篇
  13. [影视源码]全民影院源码 综合影视HTML源码 无需更新搭建即可用
  14. (2021.10.25-10.31)小结
  15. 11-23-day05-python入门-字典与集合及文件
  16. HTML_多媒体效果_embed标签详解
  17. 联合国基金会 广告投放 策略
  18. 误删c盘user文件夹后,如何恢复文件
  19. 【C++学习笔记】函数基础和参数传递
  20. Python 入门打卡1

热门文章

  1. Autoruns使用介绍
  2. 在保研中脱颖而出的个人简历模板
  3. Docker: docker network 容器网络
  4. 【现代信号处理】 12 - 深入探讨奇异值分解
  5. 众昂矿业架构师刘金海:萤石助力氟聚合物全产业链共振
  6. uefi gpt装ghost win7系统
  7. android2.2刷机,中兴 V880 Android 2.2.2 ROM 刷机包 省电 流畅
  8. 动态规划 冒泡排序 爱奇艺2018招聘
  9. Java实现身份证识别注册
  10. iptables tc限速笔记