/// <summary> /// 傳入一個句子,將句子編碼為張量後透過onnx推估其意圖,並且產出機率前3高的結果 /// </summary> /// <param name="sentence"></param> /// <returns></returns> public static List <PredictIntent> Sentence2Intent(string sentence) { //將句子轉成onnx張量容器(最大長度128個字,每個字對應成長度為256的特徵向量) var container = TensorHelper.StringToEmbeddedTensor(sentence); //產生推論結果 var results = np.array(luis_session.Run(container).ToList()[0].AsEnumerable <float>().ToArray()); //將推論結果由大至小排序(argsort是由小至大,然後"::-1"是反轉)取前三名 var top_results = np.argsort <float>(results); //根據索引串回intent(透過index2intent)以及對應機率 List <PredictIntent> final_result = new List <PredictIntent>(); for (int i = -1; i > -4; i--) { int idx = top_results.GetData(new int[] { i }); float probs = results.GetData(new int[] { idx }); //top1機率過低判斷為意圖清單之外 if (i == -1 && probs < 0.6) { final_result.Add(new PredictIntent() { Intent = (intent)(-1), Ordinal = -i, Probability = 1.2f - probs }); } final_result.Add(new PredictIntent() { Intent = (intent)idx, Ordinal = -i, Probability = probs }); } return(final_result); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseDefaultFiles(); app.UseStaticFiles(); //app.UseStaticFiles(new StaticFileOptions //{ // FileProvider = new PhysicalFileProvider( // Path.Combine(Directory.GetCurrentDirectory(), "assets")), // RequestPath = "/assets" //}); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); //初始化相關物件 InferHelper.SettingSession("Models/text_cnn.onnx"); InferHelper.Prepare_mapping(Properties.Resources.intent_list); TensorHelper.Prepare_Embedding(); TensorHelper.chars_list = Properties.Resources.charlist.ToCharArray(); //天氣能力 string weatherJson = AbilityHelper.HttpGet(AbilityHelper.weather_url); var weather = Newtonsoft.Json.JsonConvert.DeserializeObject(weatherJson); Console.Write(weatherJson); }