pytorch模型转成java_djl⼊门-如何在你的JavaApp中优雅的调
⽤Pytorch模型
pytorch是主流的深度学习框架,不论是学术界还是⼯业界已有很多成熟的模型可以使⽤,苦⽆⾃⼰技术语⾔的壁垒,⽆法将他们很好的应⽤在⾃⼰的项⽬当中
Djl介绍
Djl是基于MxNet、Pytorch、TensorFlow作为backend的api框架,它屏蔽了不同模型的调⽤差异,⽤户⽆需了解底层框架的使⽤便能很快的开发出属于⾃⼰的深度学习模型
⽬前djl⽀持图像分类,图像检测,姿态预估,语义分割,Nlp模型等
将模型导⼊到pytorch
准备⾃⼰的模型,模型以pt结尾java调用python模型
1,并拷贝模型的位置替换下⾯代码中的模型路径
2,设置模型名字,对应模型外层⽂件夹名称
3,输⼊图⽚的⼤⼩要调整为模型⽀持的⼤⼩
4,最后⼀步是设置模型的分类映射⽂件,这个很重要,配置错误会导致预测异常或不准
public static void main(String[] args) throws Exception {
Path modelDir =
<("/Users/gxd/.djl.ai/cache/repo/model/cv/image_classification/ai/djl/pytorch/resnet/50/imagenet/0.0.1");
Model model = wInstance(Device.defaultDevice(),"PyTorch"); //MXNet
model.load(modelDir, "traced_resnet50");
Pipeline pipeline = new Pipeline();
pipeline.add(new CenterCrop()).add(new Resize(224, 224)).add(new ToTensor());
ImageClassificationTranslator translator = ImageClassificationTranslator.builder()
.setPipeline(pipeline)
.
setSynsetArtifactName("")
.optApplySoftmax(true)
.build();
BufferedImage img = BufferedImageUtils.fromUrl("s.yqxiu/banff-4380804_960_720.jpg");
Predictor predictor = wPredictor(translator);
long s1 = System.currentTimeMillis();
Classifications classifications = predictor.predict(img);
System.out.printf(classifications.best().toString()+"===="+(System.currentTimeMillis()-s1));
}

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