各位集美兄得看过来! 利用AI给青春有你2的选手们做数据分析挖掘(一):爬虫选手信息
各位集美兄得看过来! 利用AI给青春有你2的选手们做数据分析挖掘(二):统计并展示数据
各位集美兄得看过来! 利用AI给青春有你2的选手们做数据分析挖掘(三):看图像识选手
各位集美兄得看过来! 利用AI给青春有你2的选手们做数据分析挖掘(四):AI分析谁最容易出道
!pip install paddlehub==1.6.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
import paddlehub as hub
module = hub.Module(name="resnet_v2_50_imagenet")
hub.Module(name="resnet_v2_50_imagenet")
执行出错
---------------------------------------------------------------------------FileNotFoundError Traceback (most recent call last)<ipython-input-102-8f639df7a42a> in <module>
----> 1 module = hub.Module(name="resnet_v2_50_imagenet")
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddlehub/module/module.py in __new__(cls, name, directory, module_dir, version)
142 self._serving_func_name = self._get_func_name(self.__class__,
143 _module_serving_func)
--> 144 self._directory = directory
145 self._initialize(**kwargs)
146 self._is_initialize = True
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddlehub/module/module.py in init_with_name(cls, name, version)
200 break
201 sys.path.pop(0)
--> 202 return user_module
203
204 @property
FileNotFoundError: [Errno 2] No such file or directory: '/home/aistudio/.paddlehub/cache/resnet_v2_50_imagenet'
找不到模型,终端输入以下命令下载模型
hub install resnet_v2_50_imagenet
import numpy as np
\## 读取label
f = open(r"dataset/label_list.txt")
line = f.readline()
label_list = []
while line:
label_list.append(line.replace("\n",""))
line = f.readline()
f.close()
主要通过百度图片进行搜索爬取,,使用正则表达式获取所有图片
import re
import requests
from urllib import error
from bs4 import BeautifulSoup
import os
## name:选手名称 basepath:图片下载目录 pn: 百度图片分页参数 pic_num:下载图片数量
def crawl_pic_urls(name,basepath,pn,pic_num):
pic_urls=[]
# 数据源主要是通过百度
url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + name+' 青春有你 高清' + '&pn='
tmp = url
num=0
while num < pic_num:
try:
url = tmp + str(pn)
print(url)
result = requests.get(url, timeout=10)
pic_url = re.findall('"objURL":"(.*?)",', result.text, re.S) # 先利用正则表达式找到图片url
if len(pic_url)>pic_num:
pic_url=pic_url[0:pic_num]
down_pic(name,pic_url,basepath)
num+=len(pic_url)
pn+=60
except error.HTTPError as e:
print('网络错误,请调整网络后重试')
for name in label_list:
crawl_pic_urls(name,'dataset/train/',0,15)
crawl_pic_urls(name,'dataset/validate/',0,5)
上面为什么加“青春有你 高清”,爬过安崎的图片的都懂
下载图片,沿用上一篇
def down_pic(name,pic_urls,basepath):
'''
根据图片链接列表pic_urls, 下载所有图片,保存在以name命名的文件夹中,
'''
path =basepath+name+'/'
if not os.path.exists(path):
os.makedirs(path)
print("正在下载:%s" %(str(name)))
for i, pic_url in enumerate(pic_urls):
try:
pic = requests.get(pic_url, timeout=15)
string = str(i + 1) + '.jpg'
with open(path+string, 'wb') as f:
f.write(pic.content)
# 生成训练集
print('成功下载第%s张图片: %s' % (str(i + 1), str(pic_url)))
except Exception as e:
print('下载第%s张图片时失败: %s' % (str(i + 1), str(pic_url)))
print(e)
continue
根据刚刚我们download好的图片路径生成train_list.txt以及validate_list.txt
def make_trainlist(path,output_txt):
f_train=open(output_txt,'w')
for (dirpath,dirnames,filenames) in os.walk(path):
for filename in filenames:
cur_name = dirpath.split('/')[2]
f_train.write(os.path.join(dirpath,filename).replace("dataset/","")+' '+str(label_list.index(cur_name))+'\n')
f_train.close
make_trainlist('dataset/train','dataset/train_list.txt')
make_trainlist('dataset/validate','dataset/validate_list.txt')
初始化dataset
from paddlehub.dataset.base_cv_dataset import BaseCVDataset
class DemoDataset(BaseCVDataset):
def __init__(self):
# 数据集存放位置
self.dataset_dir = "dataset"
super(DemoDataset, self).__init__(
base_path=self.dataset_dir,
train_list_file="train_list.txt",
validate_list_file="validate_list.txt",
test_list_file="test_list.txt",
label_list_file="label_list.txt",
)
dataset = DemoDataset()
生成部分train_list.txt如下:
train/王承渲/6.jpg 4
train/王承渲/3.jpg 4
train/王承渲/12.jpg 4
train/王承渲/23.jpg 4
train/王承渲/13.jpg 4
train/王承渲/29.jpg 4
train/王承渲/20.jpg 4
train/王承渲/7.jpg 4
train/王承渲/14.jpg 4
train/王承渲/30.jpg 4
train/王承渲/17.jpg 4
train/王承渲/4.jpg 4
train/王承渲/2.jpg 4
train/王承渲/22.jpg 4
train/王承渲/18.jpg 4
train/王承渲/25.jpg 4
train/王承渲/5.jpg 4
train/王承渲/24.jpg 4
train/王承渲/21.jpg 4
train/王承渲/8.jpg 4
train/王承渲/10.jpg 4
train/王承渲/1.jpg 4
train/王承渲/9.jpg 4
train/王承渲/26.jpg 4
train/王承渲/27.jpg 4
train/王承渲/15.jpg 4
train/王承渲/19.jpg 4
train/王承渲/28.jpg 4
train/王承渲/11.jpg 4
train/王承渲/16.jpg 4
接着生成一个图像分类的reader,reader负责将dataset的数据进行预处理,接着以特定格式组织并输入给模型进行训练。
当我们生成一个图像分类的reader时,需要指定输入图片的大小
data_reader = hub.reader.ImageClassificationReader(
image_width=module.get_expected_image_width(),
image_height=module.get_expected_image_height(),
images_mean=module.get_pretrained_images_mean(),
images_std=module.get_pretrained_images_std(),
dataset=dataset)
在进行Finetune前,我们可以设置一些运行时的配置,例如如下代码中的配置,表示:
use_cuda
:设置为False表示使用CPU进行训练。如果您本机支持GPU,且安装的是GPU版本的PaddlePaddle,我们建议您将这个选项设置为True;epoch
:迭代轮数;batch_size
:每次训练的时候,给模型输入的每批数据大小为32,模型训练时能够并行处理批数据,因此batch_size越大,训练的效率越高,但是同时带来了内存的负荷,过大的batch_size可能导致内存不足而无法训练,因此选择一个合适的batch_size是很重要的一步;log_interval
:每隔10 step打印一次训练日志;eval_interval
:每隔50 step在验证集上进行一次性能评估;checkpoint_dir
:将训练的参数和数据保存到cv_finetune_turtorial_demo目录中;strategy
:使用DefaultFinetuneStrategy策略进行finetune;更多运行配置,请查看RunConfig
同时PaddleHub提供了许多优化策略,如AdamWeightDecayStrategy
、ULMFiTStrategy
、DefaultFinetuneStrategy
等,详细信息参见策略
config = hub.RunConfig(
use_cuda=True, #是否使用GPU训练,默认为False;
num_epoch=3, #Fine-tune的轮数;
checkpoint_dir="cv_finetune_turtorial_demo",#模型checkpoint保存路径, 若用户没有指定,程序会自动生成;
batch_size=3, #训练的批大小,如果使用GPU,请根据实际情况调整batch_size;
eval_interval=10, #模型评估的间隔,默认每100个step评估一次验证集;
strategy=hub.finetune.strategy.DefaultFinetuneStrategy()) #Fine-tune优化策略;
有了合适的预训练模型和准备要迁移的数据集后,我们开始组建一个Task。
由于该数据设置是一个二分类的任务,而我们下载的分类module是在ImageNet数据集上训练的千分类模型,所以我们需要对模型进行简单的微调,把模型改造为一个二分类模型:
input_dict, output_dict, program = module.context(trainable=True)
img = input_dict["image"]
feature_map = output_dict["feature_map"]
feed_list = [img.name]
task = hub.ImageClassifierTask(
data_reader=data_reader,
feed_list=feed_list,
feature=feature_map,
num_classes=dataset.num_labels,
config=config)
OSError: cannot identify image file 'dataset/train/王承渲/10.jpg'
---------------------------------------------------------------------------EnforceNotMet Traceback (most recent call last) in
----> 1 run_states = task.finetune_and_eval()
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddlehub/finetune/task/base_task.py in finetune_and_eval(self)
861
862 def finetune_and_eval(self):
--> 863 return self.finetune(do_eval=True)
864
865 def finetune(self, do_eval=False):
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddlehub/finetune/task/base_task.py in finetune(self, do_eval)
882 while self.current_epoch <= self.config.num_epoch:
883 self.config.strategy.step()
--> 884 run_states = self._run(do_eval=do_eval)
885 self.env.current_epoch += 1
出现以上错误就是下载的图片有问题,建议删除图片重新生成dataset
我们选择finetune_and_eval
接口来进行模型训练,这个接口在finetune的过程中,会周期性的进行模型效果的评估,以便我们了解整个训练过程的性能变化。
run_states = task.finetune_and_eval()
输出训练结果:loss=1.78397 acc=0.58333
2020-04-26 09:18:55,378] [ EVAL] - [dev dataset evaluation result] loss=0.28385 acc=0.91667 [step/sec: 11.43]
[2020-04-26 09:18:55,379] [ INFO] - Load the best model from cv_finetune_turtorial_demo/best_model
[2020-04-26 09:18:55,640] [ INFO] - Evaluation on test dataset start
[2020-04-26 09:18:55,918] [ EVAL] - [test dataset evaluation result] loss=1.78397 acc=0.58333 [step/sec: 24.63]
[2020-04-26 09:18:55,919] [ INFO] - Saving model checkpoint to cv_finetune_turtorial_demo/step_250
[2020-04-26 09:18:56,963] [ INFO] - PaddleHub finetune finished.
然后分析我们爬取的图片实在是不高清又模糊,又找不到好的数据源,唯有增大数据量了,增大到每个30张
for name in label_list:
crawl_pic_urls(name,'dataset/train/',0,30)
crawl_pic_urls(name,'dataset/validate/',10,5)
增大数据量后 loss=0.83253 acc=0.83333 明显好多了
2020-04-26 09:39:56,898] [ EVAL] - [test dataset evaluation result] loss=0.83253 acc=0.83333 [step/sec: 23.87]
[2020-04-26 09:39:56,899] [ INFO] - Saving model checkpoint to cv_finetune_turtorial_demo/step_440
[2020-04-26 09:39:57,992] [ INFO] - PaddleHub finetune finished.
然后我们来预测一下,看看结果怎样?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
with open("dataset/test_list2.txt","r") as f:
filepath = f.readlines()
data = [filepath[0].split(" ")[0],filepath[1].split(" ")[0],filepath[2].split(" ")[0],filepath[3].split(" ")[0],filepath[4].split(" ")[0]]
label_map = dataset.label_dict()
index = 0
run_states = task.predict(data=data)
results = [run_state.run_results for run_state in run_states]
for batch_result in results:
print(batch_result)
batch_result = np.argmax(batch_result, axis=2)[0]
print(batch_result)
for result in batch_result:
index += 1
result = label_map[result]
print("input %i is %s, and the predict result is %s" %
(index, data[index - 1], result))
输出结果,除了许佳琪分类不出来之外,其他都可以分类出来,准确率确实是80%左右
input 1 is dataset/test/yushuxin.jpg, and the predict result is 虞书欣
input 2 is dataset/test/xujiaqi.jpg, and the predict result is 虞书欣
input 3 is dataset/test/zhaoxiaotang.jpg, and the predict result is 赵小棠
[array([[0.16966 , 0.06858681, 0.31148672, 0.33854154, 0.11172493],
[0.03498123, 0.01839942, 0.11435075, 0.01962213, 0.81264645]],
dtype=float32)]
[3 4]
input 4 is dataset/test/anqi.jpg, and the predict result is 安崎
input 5 is dataset/test/wangchengxuan.jpg, and the predict result is 王承渲
https://github.com/PaddlePaddle/PaddleHub