『开发』网页端展示深度学习模型Gradio上手教程

『开发』⽹页端展⽰深度学习模型Gradio上⼿教程
安装
Gradio需要。⼀旦你有Python,你可以下载gradio使⽤pip 的最新版本,如下所⽰:
pip install gradio
或者,pip3 install gradio如果您有多个Python安装,则可能需要执⾏此操作。
基本⽤法
使⽤gradio创建界⾯只需在现有代码中添加⼏⾏。例如,以下是gradio使⽤预训练keras模型创建界⾯的⽅法:
import gradio, tensorflow as tf
image_mdl = tf.keras.applications.inception_v3.InceptionV3()
io = gradio.Interface(inputs="imageupload", outputs="label", model_type="keras", model=image_mdl)
io.launch()
运⾏上⾯的代码将打开⼀个带有图像上传的新浏览器窗⼝。⽤户可以拖放⾃⼰的图像,这会产⽣如下输出
基本参数
运⾏GradIO接⼝需要创建⼀个对象,该对象作为输⼊参数:- 表⽰要使⽤的输⼊接⼝的字符串,或者⽤于其他⾃定义的⼦类(参见)。- 表⽰要使⽤的输出接⼝的字符串,或者⽤于其他⾃定义的⼦类(参见)。 - 表⽰传⼊模型类型的字符串。⽀持的类型包括keras。 - ⽤于处理的实际模型。Interface(inputs : str, outputs : str, model_type : str, model : Any)
inputs gradio.AbstractInput
outputs gradio.AbstractOutput
model_type
model
可以提供表⽰输⼊和输出接⼝的对象,⽽不是为inputs和提供字符串名称outputs。例如,Basic Usage部分中的代码执⾏⽅式如下:
import gradio, tensorflow as tf
image_mdl = tf.keras.applications.inception_v3.InceptionV3()
inp = gradio.inputs.ImageUpload()
out = gradio.outputs.Label()
io = gradio.Interface(inputs=inp, outputs=out, model_type="keras", model=mdl)
io.launch()
功能复合材料
这允许通过将参数传递给输⼊和输出构造函数来定制接⼝。每个接⼝构造函数接受的参数如下所述。
⽀持的接⼝
这是GradIO中当前⽀持的接⼝列表。所有输⼊接⼝都可以与任何输出接⼝配对。
输⼊接⼝
inputs=“text”
使⽤此界⾯输⼊⽂本作为输⼊。参数:⽆
输⼊
inputs=“imageupload”
使⽤此界⾯将图像上载到模型。参数:
shape- ⼀个元组,其形状应在传⼊模型之前将上传的图像调整⼤⼩。默认值:(224, 224, 3)
image_mode- PIL图像模式,⽤于将图像转换为numpy数组。通常为“RGB”(3通道RGB)或“L”(1通道灰度)。默认值:'RGB' scale- ⽤于重新缩放图像中每个像素值的浮点数。默认值:1/127.5
shift- ⽤于在缩放后移动图像中的每个像素值的浮点数。默认值:-1
cropper_aspect_ratio- ⽆或者浮点数是裁剪器的纵横⽐。默认:None
输⼊
在此处删除图像
- 或 -
单击上载
inputs=“snapshot”
使⽤此界⾯从⽤户的⽹络摄像头拍摄快照。参数:
shape- ⼀个元组,其形状应在传⼊模型之前将上传的图像调整⼤⼩。默认值:(224, 224, 3)
image_mode- PIL图像模式,⽤于将图像转换为numpy数组。通常为“RGB”(3通道RGB)或“L”(1通道灰度)。默认值:'RGB' scale- ⽤于重新缩放图像中每个像素值的浮点数。默认值:1/127.5
shift- ⽤于在缩放后移动图像中的每个像素值的浮点数。默认值:-1
cropper_aspect_ratio- ⽆或者浮点数是裁剪器的纵横⽐。默认:None
输⼊
单击以从⽹络摄像头上载快照。
inputs=“sketchpad”
使⽤此界⾯将简单的单⾊cketches作为输⼊。参数:
shape- ⼀个元组,其形状应在传⼊模型之前将上传的图像调整⼤⼩。默认值:(224, 224, 3)
invert_colors- ⼀个布尔值,指定在传⼊模型之前是否应该反转颜⾊。默认:True
输⼊
inputs=“microphone”
干2019快速 localhost将此接⼝⽤于麦克风的⾳频输⼊。
阿荣旗一中输⼊
单击以从麦克风上载⾳频。
inputs=“audio_file”
使⽤此界⾯将⾳频上传到模型。
输⼊
在此处删除⾳频⽂件
-
或 -
单击上传
输出接⼝
outputs=“classifier”
使⽤此界⾯进⾏分类。以置信区间回应。
产量
快乐
快乐
吃惊
伤⼼
愤怒
outputs=“text”
使⽤此界⾯显⽰输出⽂本。
产量
outputs=“image”
使⽤此界⾯显⽰输出⽂本。
产量
⾃定义界⾯
实际上,定制输⼊和输出接⼝是相当典型的,因此它们以模型接受的⽅式预处理输⼊,或者以适当的⽅式对模型的结果进⾏后处理,以便输出接⼝可以显⽰结果。例如,您可能需要调整图像上载界⾯的预处理,以便在将图像输⼊模型之前将图像调整为正确的尺⼨。这可以通过以下两种⽅式之⼀完成:(1)使⽤⾃定义参数实例化gradio.Input/ gradio.Output对象,或(2)提供⾃定义预处理/后处理功能。
具有⾃定义参数的输⼊/输出对象
对于输⼊和输出接⼝的⼩的常见更改,您通常可以简单地更改输⼊和输出对象的构造函数中的参数,以影响预处理/后处理。下⾯是⼀个⽰例,在将图像输⼊模型之前将图像调整为不同⼤⼩,并调整输出界⾯以隐藏置信区并显⽰前5个类⽽不是默认3:
import gradio, tensorflow as tf
image_mdl = tf.keras.applications.inception_v3.InceptionV3()
inp = gradio.inputs.ImageUpload(shape=(299, 299, 3))
out = gradio.outputs.Label(num_top_classes=5)
io = gradio.Interface(inputs=inp, outputs=out, model_type="keras", model=mdl)
io.launch()
⾃定义预处理/后处理功能
或者,您可以通过提供⾃⼰的功能完全覆盖默认的预处理/后处理功能。例如,这⾥我们修改ImageUpload接⼝的预处理功能,在将图像输⼊模型之前为图像添加⼀些噪声。
import gradio, base64, numpy as np, tensorflow as tf
from io import BytesIO
from PIL import Image
image_mdl = tf.keras.applications.inception_v3.InceptionV3()
def pre(inp):
im = gradio.ding_to_image(inp)网络孔子学院
im = gradio.size_and_crop(im, (299, 299))
im = np.array(im).flatten()
im = im * 1/127.5 - 1
im = im + al(0, 0.1, im.shape)  # Adding the noise
array = im.reshape(1, 299, 299, 3)
return array
inp = gradio.inputs.ImageUpload(preprocessing_fn=pre)
io = gradio.Interface(inputs=inp, outputs="label", model_type="keras", model=mdl)
io.launch()
型号类型
我们⽬前⽀持以下⼏种型号:
model_type="sklearn"
这允许您传⼊scikit-learn模型,并从模型中获取预测。这是⼀个训练sklearn模型并gradio围绕它创建界⾯的完整⽰例。
from sklearn import datasets, svm
import gradio
digits = datasets.load_digits()
n_samples = len(digits.images)
data = shape((n_samples, -1))  # flatten the images
魔音组合
# Create a classifier: a support vector classifier
classifier = svm.SVC(gamma=0.001)
classifier.fit(data, digits.target)
# The sklearn digits dataset is different from MNIST: it is 8x8 and consists of black digits on a white background.
inp = gradio.inputs.Sketchpad(shape=(8, 8), flatten=True, scale=16/255, invert_colors=False)
io = gradio.Interface(inputs=inp, outputs="label", model_type="sklearn", model=classifier)
io.launch()
model_type="keras"
这允许您传⼊keras模型,并从模型中获取预测。这是⼀个训练keras模型并gradio围绕它创建界⾯的完整⽰例。
import gradio, tensorflow as tf
(x_train, y_train),(x_test, y_test) = tf.ist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = dels.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, lu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, softmax)
])
modelpile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
loss, accuracy = model.evaluate(x_test, y_test)
io = gradio.Interface(inputs="sketchpad", outputs="label", model=model, model_type='keras')
io.launch(inline=True, share=True)
以查看嵌⼊在笔记本中的界⾯。
model_type="pytorch"
这允许您传⼊pytorch模型,并从模型中获取预测。这是⼀个训练pytorch模型并gradio围绕它创建界⾯的完整⽰例。
import torch
as nn
import torchvision
ansforms as transforms
import gradio
# Device configuration
device = torch.device('cpu')
# Hyper-parameters
input_size = 784
hidden_size = 500
num_classes = 10
num_epochs = 2
batch_size = 100
learning_rate = 0.001
# MNIST dataset
train_dataset = torchvision.datasets.MNIST(root='../../data', train=True, transform=transforms.ToTensor(), download=True) test_dataset = torchvision.datasets.MNIST(root='../../data',train=False, transform=transforms.ToTensor())
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size,shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)
# Fully connected neural network with one hidden layer
class NeuralNet(nn.Module):
def__init__(self, input_size, hidden_size, num_classes):
super(NeuralNet, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, num_classes)
def forward(self, x):
out = self.fc1(x)
out = lu(out)
out = self.fc2(out)
return outoperators
model = NeuralNet(input_size, hidden_size, num_classes).to(device)

本文发布于:2024-09-21 15:25:59,感谢您对本站的认可!

本文链接:https://www.17tex.com/xueshu/452397.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:模型   图像   预处理   参数   输出   功能
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议