我将介绍如何
建立开发人工智能的生态系统
使用fastai 创建和训练 AI 模型
部署模型并在您的项目中使用它
创建一个 Jupyter 笔记本
要创建 AI,我们将使用fastai。这是一个 python 库,它建立在pytorch之上。不用担心,您不需要知道如何编写 Python 代码。我们将学习这些东西是如何工作的:)
您可以自己安装和设置所有库以运行 python 文件中的代码。但通常 AI 会在称为Jupyter Notebooks的东西中编码。
使用 Jupyter Notebook 有两种选择。
使用免费的托管服务,如Kaggle
在本地运行笔记本。您可以在他们的文档中找到有关如何设置 Jupyter 的指南
Jupyter 笔记本有 python 代码或 markdown 的单元格。您可以通过按顶部导航中或单元格旁边的“运行”按钮直接在浏览器中运行代码。它将在代码单元下方为您提供代码输出。
![](https://img-blog.csdnimg.cn/img_convert/b9cfad5d5f0ad7cc1047f86f11f87d2d.png)
现在让我们直接进入代码。本指南的其余部分也将在此 Kaggle 笔记本中提供:
https://www.kaggle.com/vincentwill/fastai-tutorial
在 Kaggle 上,要使代码正常工作,您必须先激活侧边栏菜单中的“Internet”开关。要打开边栏,请单击右下角的小箭头。仅当您验证了您的电话号码后,互联网交换机才可用。
准备数据以训练 AI
在本教程中,我们将编写一个能够识别图片中内容的 AI。
为此,我们首先需要一些图片来训练 AI。
以下函数是从duckduckgo快速下载图片的帮手。我不会在这里详细介绍,因为它对训练我们的 AI 并不重要。您也可以手动下载图片或使用任何其他抓取工具来获取数据。
# import libraries | imports will be available in all following cells as well
fromfastcore.allimport*fromfastai.vision.allimport*importtimeimportjsondefsearch_images(term,max_images=100):# define search_images function
url='https://duckduckgo.com/'res=urlread(url,data={'q':term})time.sleep(2)searchObj=re.search(r'vqd=([d-]+)&',res)requestUrl=url+'i.js'# the duckduck go api url
params=dict(l='us-en',o='json',q=term,vqd=searchObj.group(1),f=',,,',p='1',v7exp='a')headers=dict(referer='https://duckduckgo.com/')urls,data=set(),{'next':1}# loop through pages until we have enough images
whilelen(urls)<max_imagesand'next'indata:res=urlread(requestUrl,data=params,headers=headers)data=json.loads(res)ifreselse{}urls.update(L(data['results']).itemgot('image'))requestUrl=url+data['next']time.sleep(4)returnL(urls)[:max_images]`
我建议首先遵循本指南,然后尝试使用不同的图像训练 AI。我们将从测试我们的search_images功能开始。输出将显示一个链接。
在本教程中,我将创建一个识别不同类型恐龙的人工智能。
# "search_images" depends on duckduckgo.com, which doesn't always return correct responses.
# If you get a JSON error, just try running it again (it may take a couple of tries).
urls=search_images('t-rex',max_images=1)urls[0]# 'https://preview.redd.it/dwthh8wdl9k21.jpg?auto=webp&s=e0af431550ed710c2ffb11eae6ca325806c9f46b'`
既然我们验证了该功能可以正常工作,我们就可以使用它来下载和显示图片了。
fromfastdownloadimportdownload_urldest='t-rex.jpg'download_url(urls[0],dest,show_progress=False)im=Image.open(dest)# open the downloaded image
im.to_thumb(256,256)# display the image in a 256x256 thumbnail
现在我们需要获取不同事物的图片,让 AI 知道什么不是霸王龙。我们将使用相同的函数来获取三角龙的图像。
download_url(search_images('triceratops',max_images=1)[0],'triceratops.jpg',show_progress=False)Image.open('triceratops.jpg').to_thumb(256,256)
现在我们确保搜索和保存工作正常,我们可以使用它们来下载我们的数据集。下一个函数将遍历我们的类别并下载每个类别的 100 张图片。
searches='t-rex','triceratops'# define search terms
path=Path('images')foroinsearches:dest=(path/o)dest.mkdir(exist_ok=True,parents=True)# create folder for categories
download_images(dest,urls=search_images(f'{o}'))time.sleep(5)resize_images(path/o,max_size=400,dest=path/o)# resize to save time training the AI
Itmighthappenthatdownloadsfail.That's why we need to verify the images and delete the invalid ones.
failed = verify_images(get_image_files(path))
failed.map(Path.unlink)
len(failed)
训练人工智能
为了训练人工智能,我们首先需要一个数据块。它就像关于如何组装数据的蓝图。有了这个数据块,我们就可以通过调用它的函数来创建一个数据加载器.dataloader。我将在下面的代码中解释不同的参数。您可以在此处找到所有内容的更详细解释。
dls=DataBlock(blocks=(ImageBlock,CategoryBlock),# input = images, output = categories
get_items=get_image_files,# Get image files in path recursive
splitter=RandomSplitter(valid_pct=0.2,seed=42),# split data into training / validation set randomly
get_y=parent_label,# label the items - in this case take the parent (folder) as label
item_tfms=[Resize(192,method='squish')]# method to transform the items - in this case resize
).dataloaders(path,bs=32)# bs = size of batch
# show an example batch of the items we loaded
dls.show_batch(max_n=6)
现在我们已经准备好用这些数据训练我们的 AI。首先,我们加载一个预训练模型。在这种情况下,预训练模型被训练为识别照片。之后,我们在我们的数据集上微调这个模型。我们将数据加载器传递给视觉学习器,然后传递给我们将使用的预训练模型。在这种情况下,它是resnet18.
learn=vision_learner(dls,resnet18,metrics=error_rate)learn.fine_tune(3)
测试和部署 AI
现在我们的 AI 已准备好接受测试。为此,我们可以使用最初下载的照片来测试我们的下载功能。
prediction,_,probs=learn.predict('t-rex.jpg')# run a prediction
print(f"This is a: {prediction}.")print(f"Probability it's a t-rex: {probs[0]:.4f}")print(f"Probability it's a triceratops: {probs[1]:.4f}")
如果我们对结果和准确性感到满意,我们就可以部署该模型。我们通过简单地调用export学习者的功能来做到这一点。
learn.export('model.pkl')
您现在可以加载和使用导出的模型。这意味着您可以将其导入任何 Python 应用程序并使用该.predict函数。
path=Path()path.ls(file_exts='.pkl')# double check if model exists
learn_inf=load_learner('model.pkl')learn_inf.predict('t-rex.jpg')
但是有一种比实现您自己的 Python API 更容易使用您的模型的方法。我们可以使用Gradio和Hugging Face轻松创建 API 并使用我们的模型。为此,我们需要编写一个函数来告诉 Gradio 如何使用我们的模型。
labels=learn.dls.vocab# read labels from Data Loader
defpredict(img):pred,pred_idx,probs=learn.predict(img)# use passed image for prediction
return{labels[i]:float(probs[i])foriinrange(len(labels))}# return all results
现在我们需要安装 gradio。然后我们已经可以通过定义一个接口来启动它。我们将预测函数以及输入和输出定义传递给该接口。然后我们可以调用启动函数,它将启动一个界面来与我们的模型进行交互。
!pipinstall-Uqqgradioimportgradioasgrgradio_interface=gr.Interface(fn=predict,inputs=gr.inputs.Image(shape=(512,512)),outputs=gr.outputs.Label(num_top_classes=3))gradio_interface.launch(share=True)
这将创建一个 UI 以轻松地与我们的模型交互
在底部,您可以看到通过 API 使用文本。
如果你点击它,它会告诉你如何通过 API 与你的 AI 交互。您可以使用 Gradio 创建自己的 Python 微服务。但最简单的托管方式是使用 Hugging Face。所以去那里创建一个帐户。确认您的电子邮件后,您可以创建一个“空间”。
单击右上角的菜单,然后单击“新空间”。输入项目名称并选择 Gradio 作为 SDK。然后选择一个License,其他选项保持原样。现在您可以创建空间。
![](https://img-blog.csdnimg.cn/img_convert/eb1dd416eb46ec24a85726a6707385ce.png)
之后,我们需要将模型和代码添加到 Hugging Face 存储库中。如果您在本地运行笔记本,您的工作目录中应该有导出的模型。如果你在 Kaggle 上,你必须点击右下角的小箭头。在那里您应该会看到带有导出的 model.pkl 文件的“数据”选项卡。
现在克隆您的 Hugging Face Space 的存储库。然后将 model.pkl 文件添加到存储库并创建一个文件app.py。在那里我们添加了上面已经使用过的代码来加载模型并创建渐变界面。
importgradioasgrimportskimagefromfastai.vision.allimport*path=Path()learn=load_learner('model.pkl')labels=learn.dls.vocab# read labels from Data Loader
defpredict(img):pred,pred_idx,probs=learn.predict(img)# use passed image for prediction
return{labels[i]:float(probs[i])foriinrange(len(labels))}# return all results
gradio_interface=gr.Interface(fn=predict,inputs=gr.inputs.Image(shape=(512,512)),outputs=gr.outputs.Label(num_top_classes=3))gradio_interface.launch()
最后添加一个 requirements.txt 文件以提供运行我们的模型所需的库。
fastai
scikit-image
在提交之前我们需要先安装git-lfs,因为我们的 model.pkl 文件太大了。按照链接和说明为您的操作系统安装它。
现在我们可以为我们的 model.pkl 使用 git-lfs:
git lfs install
git lfs track "*.pkl"
之后,我们准备提交和部署我们的模型。
git add .
git commit -m "initial commit"
git push
如果您返回到您的 Hugging Face Space,您应该会看到您的应用程序正在构建。片刻之后,您应该能够看到与 jupyter notebook 中相同的界面。
恭喜!您已成功创建并部署了您的 AI。您现在可以在应用程序中使用 Hugging Face Space 的 API。