我在Visual Studio中创建了一个机器学习模型,并使用Visual Studio将Web应用程序上传到了Azure。然而,当我在网站上填写我的机器学习模型的字段并点击“运行”时,我得到了这个错误,这是我直接从Azure App Service Editor复制的错误信息。
这个错误只在我尝试在Azure网站上运行机器学习模型时出现,如果我在自己的电脑上运行Web应用程序,则不会出现任何错误。
谢谢你 🙂
错误信息:2020-07-18 01:12:59.138 +00:00 [Error] Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware: 在执行请求时发生了未处理的异常。System.IO.FileNotFoundException: 无法找到文件 'C:\Users\X\X\X\fileML.Model\MLModel.zip'。文件名: 'C:\Users\X\X\X\fileML.Model\MLModel.zip'____________________我的代码:// 此文件由ML.NET模型构建器自动生成。 using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using Microsoft.ML;using fileML.Model;namespace fileML.Model{ public class ConsumeModel { private static readonly Lazy<PredictionEngine<ModelInput, ModelOutput>> PredictionEngine = new Lazy<PredictionEngine<ModelInput, ModelOutput>>(CreatePredictionEngine); // 有关在您的应用中使用ML.NET模型的更多信息,请访问 https://aka.ms/mlnet-consume // 在您的应用中使用模型的方法 public static ModelOutput Predict(ModelInput input) { ModelOutput result = PredictionEngine.Value.Predict(input); return result; } public static PredictionEngine<ModelInput, ModelOutput> CreatePredictionEngine() { // 创建新的MLContext MLContext mlContext = new MLContext(); // 加载模型并创建预测引擎 string modelPath = @"C:\Users\X\X\X\fileML.Model\MLModel.zip"; ITransformer mlModel = mlContext.Model.Load(modelPath, out _); var predEngine = mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(mlModel); return predEngine; } }}
回答:
欢迎来到stackoverflow。
您缺少的是:
您试图访问您电脑上的本地路径,但在Azure上没有本地机器,因此每当您的代码尝试访问您硬编码的相同路径时,就会导致错误。
我的建议是将您的zip文件添加到您的项目中,添加后右键点击该文件,并选择“复制到输出目录 – 始终复制”。
请看下图
这样可以帮助您从输出目录中获取本地文件路径。现在是时候更改您的代码以动态获取文件了。
您可以使用
string directoryPath = Directory.GetCurrentDirectory();string modelPath= Path.Combine(directoryPath ,"MLModel.zip");
这将为您获取文件路径。请在本地测试您的代码,然后部署应用程序。
好消息是,现在您的模型文件将与您的代码一起部署。每当您更改模型时,只需替换文件并再次部署代码。
使其更动态的提示:- 您还可以使用Azure Blob存储来保存您的zip文件,通过这种方式,您不需要反复部署代码。只需替换blob中的文件即可。