first commit

This commit is contained in:
pscgyLancer 2024-08-18 21:11:29 +08:00
commit e412a52f75
18 changed files with 1966 additions and 0 deletions

343
.gitignore vendored Normal file
View File

@ -0,0 +1,343 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# ASP.NET Core default setup: bower directory is configured as wwwroot/lib/ and bower restore is true
**/wwwroot/lib/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb

View File

@ -0,0 +1,30 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.ML;
using RatePlanNameAnalysis.Model;
namespace RatePlanNameAnalysis.Api.Controllers
{
[ApiController]
[Route("[controller]")]
public class DiscernController : ControllerBase
{
public DiscernController()
{
}
[HttpPost(Name = "Analysis")]
public IActionResult Analysis(string ratePlanName)
{
// 创建样例数据的单个实例对模型输入数据集的第一行
ModelInput input = new ModelInput()
{
RatePlanName = ratePlanName,
};
// 获取预测结果
var predictionResult = ConsumeModel.Predict(input);
//System.IO.File.Delete(filefullname);
return Ok(predictionResult.BedTypeName);
}
}
}

View File

@ -0,0 +1,23 @@
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@ -0,0 +1,31 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:15456",
"sslPort": 0
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5066",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\RatePlanNameAnalysis.Model\RatePlanNameAnalysis.Model.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

View File

@ -0,0 +1,25 @@
// <SnippetAddUsings>
using Microsoft.ML.Data;
// </SnippetAddUsings>
namespace RatePlanNameAnalysis
{
// <SnippetDeclareTypes>
public class RatePlanNameAnalysisData
{
[LoadColumn(0)]
public string BedTypeID { get; set; }
[LoadColumn(1)]
public string RatePlanName { get; set; }
[LoadColumn(2)]
public string BedTypeName { get; set; }
}
public class BedTypePrediction
{
[ColumnName("PredictedLabel")]
public string BedTypeName;
}
// </SnippetDeclareTypes>
}

View File

@ -0,0 +1,101 @@
BedTypeID,RatePlanName,BedTypeName
73,deluxe king room with river view - high floor,1 King
73,deluxe king room with balcony and river view,1 King
0,deluxe family of 5 room,Unknown
0,deluxe family of 6 room,Unknown
1,social deluxe times square doubles single occupancy breakfast included in the price,1 Single
0,",1 bedroom view apartment with balcony",Unknown
52,2 twin club regent city view,2 Single
52,harbor twin room (smoking),2 Single
73,"club room, 1 king bed (top floor) 1 king bed",1 King
0,"suite, ensuite (residential triple)",Unknown
254,"suite, ensuite (residential triple) (1 queen bed and 1 double futon)",1 Double 1 Queen
2,"standard double room,shared bathroom,residential",1 Double
6,"quadruple room, ensuite (residential deluxe) (2 double beds)",2 Double
2,residential double bed suite (ensuite),1 Double
0,"suite, ensuite (residential quad)",Unknown
6,"quadruple room, ensuite (residential standard)(2 double beds)",2 Double
2,residential double bed room shared bathroom,1 Double
86,"quadruple room, ensuite (residential deluxe)(2 queen beds)",2 Queen
0,deluxe accessible triple room,Unknown
48,"suite, ensuite (residential quad) (2 double beds and 1 double futon)",3 Double
0,family suite 1 bedroom kitchenette,Unknown
0,raden saleh suite non-refundable,Unknown
0,raden saleh suite - non-refundable,Unknown
173,"signature suite, 2 bedrooms- 1 king bed and 1 queen bed",1 King 1 Queen
0,family room - court view,Unknown
73,"suite, 1 bedroom (on the avenue)(1 king bed)",1 King
0,the hadiprana villa - non-refundable - breakfast included in the price,Unknown
0,one bedroom club pool villa non refundable,Unknown
0,deluxe premier - deluxe premier rb,Unknown
0,the hadiprana villa with club benefits non-refundable,Unknown
0,club 1 bedroom non refundable,Unknown
2,double room 1 bedroom club non refundable,1 Double
0,one bedroom pool villa with club benefits non-refundable,Unknown
0,suite room with private pool non-refundable,Unknown
0,suite room premiere with jungle view non-refundable,Unknown
73,superior deluxe king room - breakfast included in the price,1 King
52,superior deluxe twin room - non-refundable,2 Single
52,superior deluxe twin room - breakfast included in the price,2 Single
0,zamrud suite non-refundable,Unknown
0,executive suite - non smoking non refundable,Unknown
0,arum villa (mountain or garden view) non-refundable,Unknown
0,suite room with jungle view non-refundable,Unknown
0,plantation villa - non-refundable - breakfast included in the price,Unknown
0,plantation villa non-refundable,Unknown
73,gardner king room w/ balcony [no extrabed],1 King
0,executive suite with bosphorus view lounge accessible,Unknown
0,family apartment for 4 adults - no refundable,Unknown
2,suite - double - de luxe - no refundable,1 Double
2,double deluxe (undefined-deluxe pool access room. bed & breakfast. standard rate),1 Double
52,suite - twin - de luxe - no refundable,2 Single
0,deluxe one-bedroom villa with private pool and bathtub - breakfast included in the price,Unknown
0,deluxe villa 1 bedroom pool view,Unknown
0,penthouse suite - two bedrooms & skyline(city view),Unknown
0,junior suite lounge access(city view),Unknown
0,executive room lounge access(city view),Unknown
6,guest room 2 double airport view,2 Double
73,guest room 1 king airport view,1 King
0,five bedroom villa with private pool and bathtub - breakfast included in the price,Unknown
52,special offer - two deluxe double or twin rooms - breakfast included in the price,2 Single
0,2qn mobility/hearing access w/tub nonsmoking vis firealrm/door/phn alrt/50-in hdtv microwv/fridge/free wi-fi/hot brkfst included,Unknown
166,8 bedrooms pool villa (interconnecting of two units 3 bedroom villas and 1 unit of 2 bedroom villa)(8 king beds),8 King
0,quadruple room with private bathroom and kitchenette,Unknown
0,embassy suite 1 bed non refundable,Unknown
2,deluxe suite double(1 double bed),1 Double
0,suite (suite-harris suite),Unknown
0,1 double bed or 2 double beds and 2 queen beds or 2 double beds,Unknown
86,deluxe room (garden)(2 queen beds),2 Queen
0,the layonsari suite with pool view - breakfast included in the price,Unknown
86,premium villa(2 queen beds),2 Queen
0,the layonsari suite non refundable,Unknown
274,grand villa(2 queen beds and 1 large twin bed),2 Queen 2 Single
86,suite garden(2 queen beds),2 Queen
0,two bedroom villa with private pool - no refundable,Unknown
86,deluxe room (rooftop)(2 queen beds),2 Queen
0,pool villa premium vip,Unknown
254,"deluxe room, annex building(1 queen bed and 1 double futon)",1 Double 1 Queen
188,grand suite(3 queen beds),3 Queen
0,[sugga let's play] deluxe,Unknown
73,"presidential suite, 1 king bed, kitchen, sea view",1 King
0,eight bedroom villa with private pool and bathtub - non-refundable - breakfast included in the price,Unknown
0,embassy - suite room - non-refundable - breakfast included in the price,Unknown
0,nine bedrooms connecting villa non refundable,Unknown
0,8 bedrooms pool villa (interconnecting of two units 3 bedroom villas and 1 unit of 2 bedroom villa) non-refundable,Unknown
52,deluxe suite twin room - non-refundable - breakfast included in the price,2 Single
0,not refundable.1 x villa 2 rooms (3 pers),Unknown
0,1 x villa 2 rooms (3 pers),Unknown
73,signature suite club access king bed separate lounge city view high floor luxury amenities non refundable breakfast included in the price,1 King
0,studio swimout,Unknown
52,deluxe suite twin bed(nature view),2 Single
73,1 king bed w/walk in shower free wi-fi/breakfast included/55 in hdtv mini-refrigerator,1 King
52,special offer - two deluxe double or twin rooms - non-refundable - breakfast included in the price,2 Single
118,villa 3 bedrooms private pool(3 king beds),3 King
0,villa - honeymoon non refundable,Unknown
6,special offer - two deluxe rooms(2 double beds),2 Double
0,two bedrooms pool villa non refundable,Unknown
0,deluxe 2 beds suite non refundable,Unknown
0,embassy suite one bedroom - no refundable,Unknown
0,deluxe ocean villa non refundable,Unknown
0,villa 6 bedroom bathtub,Unknown
0,harris unique room with pool access - no refundable,Unknown
1 BedTypeID RatePlanName BedTypeName
2 73 deluxe king room with river view - high floor 1 King
3 73 deluxe king room with balcony and river view 1 King
4 0 deluxe family of 5 room Unknown
5 0 deluxe family of 6 room Unknown
6 1 social deluxe times square doubles single occupancy breakfast included in the price 1 Single
7 0 ,1 bedroom view apartment with balcony Unknown
8 52 2 twin club regent city view 2 Single
9 52 harbor twin room (smoking) 2 Single
10 73 club room, 1 king bed (top floor) 1 king bed 1 King
11 0 suite, ensuite (residential triple) Unknown
12 254 suite, ensuite (residential triple) (1 queen bed and 1 double futon) 1 Double 1 Queen
13 2 standard double room,shared bathroom,residential 1 Double
14 6 quadruple room, ensuite (residential deluxe) (2 double beds) 2 Double
15 2 residential double bed suite (ensuite) 1 Double
16 0 suite, ensuite (residential quad) Unknown
17 6 quadruple room, ensuite (residential standard)(2 double beds) 2 Double
18 2 residential double bed room shared bathroom 1 Double
19 86 quadruple room, ensuite (residential deluxe)(2 queen beds) 2 Queen
20 0 deluxe accessible triple room Unknown
21 48 suite, ensuite (residential quad) (2 double beds and 1 double futon) 3 Double
22 0 family suite 1 bedroom kitchenette Unknown
23 0 raden saleh suite non-refundable Unknown
24 0 raden saleh suite - non-refundable Unknown
25 173 signature suite, 2 bedrooms- 1 king bed and 1 queen bed 1 King 1 Queen
26 0 family room - court view Unknown
27 73 suite, 1 bedroom (on the avenue)(1 king bed) 1 King
28 0 the hadiprana villa - non-refundable - breakfast included in the price Unknown
29 0 one bedroom club pool villa non refundable Unknown
30 0 deluxe premier - deluxe premier rb Unknown
31 0 the hadiprana villa with club benefits non-refundable Unknown
32 0 club 1 bedroom non refundable Unknown
33 2 double room 1 bedroom club non refundable 1 Double
34 0 one bedroom pool villa with club benefits non-refundable Unknown
35 0 suite room with private pool non-refundable Unknown
36 0 suite room premiere with jungle view non-refundable Unknown
37 73 superior deluxe king room - breakfast included in the price 1 King
38 52 superior deluxe twin room - non-refundable 2 Single
39 52 superior deluxe twin room - breakfast included in the price 2 Single
40 0 zamrud suite non-refundable Unknown
41 0 executive suite - non smoking non refundable Unknown
42 0 arum villa (mountain or garden view) non-refundable Unknown
43 0 suite room with jungle view non-refundable Unknown
44 0 plantation villa - non-refundable - breakfast included in the price Unknown
45 0 plantation villa non-refundable Unknown
46 73 gardner king room w/ balcony [no extrabed] 1 King
47 0 executive suite with bosphorus view lounge accessible Unknown
48 0 family apartment for 4 adults - no refundable Unknown
49 2 suite - double - de luxe - no refundable 1 Double
50 2 double deluxe (undefined-deluxe pool access room. bed & breakfast. standard rate) 1 Double
51 52 suite - twin - de luxe - no refundable 2 Single
52 0 deluxe one-bedroom villa with private pool and bathtub - breakfast included in the price Unknown
53 0 deluxe villa 1 bedroom pool view Unknown
54 0 penthouse suite - two bedrooms & skyline(city view) Unknown
55 0 junior suite lounge access(city view) Unknown
56 0 executive room lounge access(city view) Unknown
57 6 guest room 2 double airport view 2 Double
58 73 guest room 1 king airport view 1 King
59 0 five bedroom villa with private pool and bathtub - breakfast included in the price Unknown
60 52 special offer - two deluxe double or twin rooms - breakfast included in the price 2 Single
61 0 2qn mobility/hearing access w/tub nonsmoking vis firealrm/door/phn alrt/50-in hdtv microwv/fridge/free wi-fi/hot brkfst included Unknown
62 166 8 bedrooms pool villa (interconnecting of two units 3 bedroom villas and 1 unit of 2 bedroom villa)(8 king beds) 8 King
63 0 quadruple room with private bathroom and kitchenette Unknown
64 0 embassy suite 1 bed non refundable Unknown
65 2 deluxe suite double(1 double bed) 1 Double
66 0 suite (suite-harris suite) Unknown
67 0 1 double bed or 2 double beds and 2 queen beds or 2 double beds Unknown
68 86 deluxe room (garden)(2 queen beds) 2 Queen
69 0 the layonsari suite with pool view - breakfast included in the price Unknown
70 86 premium villa(2 queen beds) 2 Queen
71 0 the layonsari suite non refundable Unknown
72 274 grand villa(2 queen beds and 1 large twin bed) 2 Queen 2 Single
73 86 suite garden(2 queen beds) 2 Queen
74 0 two bedroom villa with private pool - no refundable Unknown
75 86 deluxe room (rooftop)(2 queen beds) 2 Queen
76 0 pool villa premium vip Unknown
77 254 deluxe room, annex building(1 queen bed and 1 double futon) 1 Double 1 Queen
78 188 grand suite(3 queen beds) 3 Queen
79 0 [sugga let's play] deluxe Unknown
80 73 presidential suite, 1 king bed, kitchen, sea view 1 King
81 0 eight bedroom villa with private pool and bathtub - non-refundable - breakfast included in the price Unknown
82 0 embassy - suite room - non-refundable - breakfast included in the price Unknown
83 0 nine bedrooms connecting villa non refundable Unknown
84 0 8 bedrooms pool villa (interconnecting of two units 3 bedroom villas and 1 unit of 2 bedroom villa) non-refundable Unknown
85 52 deluxe suite twin room - non-refundable - breakfast included in the price 2 Single
86 0 not refundable.1 x villa 2 rooms (3 pers) Unknown
87 0 1 x villa 2 rooms (3 pers) Unknown
88 73 signature suite club access king bed separate lounge city view high floor luxury amenities non refundable breakfast included in the price 1 King
89 0 studio swimout Unknown
90 52 deluxe suite twin bed(nature view) 2 Single
91 73 1 king bed w/walk in shower free wi-fi/breakfast included/55 in hdtv mini-refrigerator 1 King
92 52 special offer - two deluxe double or twin rooms - non-refundable - breakfast included in the price 2 Single
93 118 villa 3 bedrooms private pool(3 king beds) 3 King
94 0 villa - honeymoon non refundable Unknown
95 6 special offer - two deluxe rooms(2 double beds) 2 Double
96 0 two bedrooms pool villa non refundable Unknown
97 0 deluxe 2 beds suite non refundable Unknown
98 0 embassy suite one bedroom - no refundable Unknown
99 0 deluxe ocean villa non refundable Unknown
100 0 villa 6 bedroom bathtub Unknown
101 0 harris unique room with pool access - no refundable Unknown

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@ -0,0 +1,210 @@
using System;
using System.IO;
using System.Linq;
using Microsoft.ML;
namespace RatePlanNameAnalysis
{
class Program
{
private static string _appPath => Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
private static string _trainDataPath => Path.Combine(_appPath, "..", "..", "..", "Data", "RatePlanNameAnalysis_train.csv");
private static string _testDataPath => Path.Combine(_appPath, "..", "..", "..", "Data", "RatePlanNameAnalysis_test.csv");
private static string _modelPath => Path.Combine(_appPath, "..", "..", "..", "Models", "model.zip");
private static MLContext _mlContext;
private static PredictionEngine<RatePlanNameAnalysisData, BedTypePrediction> _predEngine;
private static ITransformer _trainedModel;
static IDataView _trainingDataView;
// </SnippetDeclareGlobalVariables>
static void Main(string[] args)
{
// Create MLContext to be shared across the model creation workflow objects
// Set a random seed for repeatable/deterministic results across multiple trainings.
// <SnippetCreateMLContext>
_mlContext = new MLContext(seed: 0);
// </SnippetCreateMLContext>
// STEP 1: Common data loading configuration
// CreateTextReader<BedType>(hasHeader: true) - Creates a TextLoader by inferencing the dataset schema from the BedType data model type.
// .Read(_trainDataPath) - Loads the training text file into an IDataView (_trainingDataView) and maps from input columns to IDataView columns.
Console.WriteLine($"=============== Loading Dataset ===============");
// <SnippetLoadTrainData>
var loader = _mlContext.Data.CreateTextLoader<RatePlanNameAnalysisData>(separatorChar: ',',
hasHeader: true,
allowQuoting: true); // 支持引号
_trainingDataView = loader.Load(_trainDataPath);
//_trainingDataView = _mlContext.Data.LoadFromTextFile<RatePlanNameAnalysisData>(_trainDataPath, separatorChar: ',', hasHeader: true);
// </SnippetLoadTrainData>
Console.WriteLine($"=============== Finished Loading Dataset ===============");
// <SnippetSplitData>
// var (trainData, testData) = _mlContext.MulticlassClassification.TrainTestSplit(_trainingDataView, testFraction: 0.1);
// </SnippetSplitData>
// <SnippetCallProcessData>
var pipeline = ProcessData();
// </SnippetCallProcessData>
// <SnippetCallBuildAndTrainModel>
var trainingPipeline = BuildAndTrainModel(_trainingDataView, pipeline);
// </SnippetCallBuildAndTrainModel>
// <SnippetCallEvaluate>
Evaluate(_trainingDataView.Schema);
// </SnippetCallEvaluate>
// <SnippetCallPredictBedType>
PredictBedType();
// </SnippetCallPredictBedType>
}
public static IEstimator<ITransformer> ProcessData()
{
Console.WriteLine($"=============== Processing Data ===============");
// STEP 2: Common data process configuration with pipeline data transformations
// <SnippetMapValueToKey>
var pipeline = _mlContext.Transforms.Conversion.MapValueToKey(inputColumnName: "BedTypeName", outputColumnName: "Label")
// </SnippetMapValueToKey>
// <SnippetFeaturizeText>
.Append(_mlContext.Transforms.Text.FeaturizeText(inputColumnName: "RatePlanName", outputColumnName: "RatePlanNameFeaturized"))
// </SnippetFeaturizeText>
// <SnippetConcatenate>
.Append(_mlContext.Transforms.Concatenate("Features", "RatePlanNameFeaturized"))
// </SnippetConcatenate>
//Sample Caching the DataView so estimators iterating over the data multiple times, instead of always reading from file, using the cache might get better performance.
// <SnippetAppendCache>
.AppendCacheCheckpoint(_mlContext);
// </SnippetAppendCache>
Console.WriteLine($"=============== Finished Processing Data ===============");
// <SnippetReturnPipeline>
return pipeline;
// </SnippetReturnPipeline>
}
public static IEstimator<ITransformer> BuildAndTrainModel(IDataView trainingDataView, IEstimator<ITransformer> pipeline)
{
// STEP 3: Create the training algorithm/trainer
// Use the multi-class SDCA algorithm to predict the label using features.
//Set the trainer/algorithm and map label to value (original readable state)
// <SnippetAddTrainer>
var trainingPipeline = pipeline.Append(_mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy("Label", "Features"))
.Append(_mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
// </SnippetAddTrainer>
// STEP 4: Train the model fitting to the DataSet
Console.WriteLine($"=============== Training the model ===============");
// <SnippetTrainModel>
_trainedModel = trainingPipeline.Fit(trainingDataView);
// </SnippetTrainModel>
Console.WriteLine($"=============== Finished Training the model Ending time: {DateTime.Now.ToString()} ===============");
// (OPTIONAL) Try/test a single prediction with the "just-trained model" (Before saving the model)
Console.WriteLine($"=============== Single Prediction just-trained-model ===============");
// Create prediction engine related to the loaded trained model
// <SnippetCreatePredictionEngine1>
_predEngine = _mlContext.Model.CreatePredictionEngine<RatePlanNameAnalysisData, BedTypePrediction>(_trainedModel);
// </SnippetCreatePredictionEngine1>
// <SnippetCreateTestBedType1>
RatePlanNameAnalysisData BedType = new RatePlanNameAnalysisData()
{
RatePlanName = "double suite (double bed) (double king size bed, terrace)"
};
// </SnippetCreateTestBedType1>
// <SnippetPredict>
var prediction = _predEngine.Predict(BedType);
// </SnippetPredict>
// <SnippetOutputPrediction>
Console.WriteLine($"=============== Single Prediction just-trained-model - Result: {prediction.BedTypeName} ===============");
// </SnippetOutputPrediction>
// <SnippetReturnModel>
return trainingPipeline;
// </SnippetReturnModel>
}
public static void Evaluate(DataViewSchema trainingDataViewSchema)
{
// STEP 5: Evaluate the model in order to get the model's accuracy metrics
Console.WriteLine($"=============== Evaluating to get model's accuracy metrics - Starting time: {DateTime.Now.ToString()} ===============");
//Load the test dataset into the IDataView
// <SnippetLoadTestDataset>
// 创建数据加载器
var loader = _mlContext.Data.CreateTextLoader<RatePlanNameAnalysisData>(separatorChar: ',',
hasHeader: true,
allowQuoting: true); // 支持引号
// 加载数据
var testDataView = loader.Load(_testDataPath);
// var testDataView = _mlContext.Data.LoadFromTextFile<RatePlanNameAnalysisData>(_testDataPath, separatorChar: ',', hasHeader: true);
// </SnippetLoadTestDataset>
//Evaluate the model on a test dataset and calculate metrics of the model on the test data.
// <SnippetEvaluate>
var testMetrics = _mlContext.MulticlassClassification.Evaluate(_trainedModel.Transform(testDataView));
// </SnippetEvaluate>
Console.WriteLine($"=============== Evaluating to get model's accuracy metrics - Ending time: {DateTime.Now.ToString()} ===============");
// <SnippetDisplayMetrics>
Console.WriteLine($"*************************************************************************************************************");
Console.WriteLine($"* Metrics for Multi-class Classification model - Test Data ");
Console.WriteLine($"*------------------------------------------------------------------------------------------------------------");
Console.WriteLine($"* MicroAccuracy: {testMetrics.MicroAccuracy:0.###}");
Console.WriteLine($"* MacroAccuracy: {testMetrics.MacroAccuracy:0.###}");
Console.WriteLine($"* LogLoss: {testMetrics.LogLoss:#.###}");
Console.WriteLine($"* LogLossReduction: {testMetrics.LogLossReduction:#.###}");
Console.WriteLine($"*************************************************************************************************************");
// </SnippetDisplayMetrics>
// Save the new model to .ZIP file
// <SnippetCallSaveModel>
SaveModelAsFile(_mlContext, trainingDataViewSchema, _trainedModel);
// </SnippetCallSaveModel>
}
public static void PredictBedType()
{
// <SnippetLoadModel>
ITransformer loadedModel = _mlContext.Model.Load(_modelPath, out var modelInputSchema);
// </SnippetLoadModel>
// <SnippetAddTestBedType>
RatePlanNameAnalysisData singleBedType = new RatePlanNameAnalysisData() { RatePlanName = "double suite (double bed) (double king size bed, terrace)" };
// </SnippetAddTestBedType>
//Predict label for single hard-coded BedType
// <SnippetCreatePredictionEngine>
_predEngine = _mlContext.Model.CreatePredictionEngine<RatePlanNameAnalysisData, BedTypePrediction>(loadedModel);
// </SnippetCreatePredictionEngine>
// <SnippetPredictBedType>
var prediction = _predEngine.Predict(singleBedType);
// </SnippetPredictBedType>
// <SnippetDisplayResults>
Console.WriteLine($"=============== Single Prediction - Result: {prediction.BedTypeName} ===============");
// </SnippetDisplayResults>
}
private static void SaveModelAsFile(MLContext mlContext, DataViewSchema trainingDataViewSchema, ITransformer model)
{
// <SnippetSaveModel>
mlContext.Model.Save(model, trainingDataViewSchema, _modelPath);
// </SnippetSaveModel>
Console.WriteLine("The model is saved to {0}", _modelPath);
}
}
}

View File

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<Folder Include="Data\" />
<Folder Include="Models\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.ML" Version="3.0.1" />
<PackageReference Include="Microsoft.ML.FastTree" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="Data\issues_test.tsv">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Data\issues_train.tsv">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,37 @@
// This file was auto-generated by ML.NET Model Builder.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ML;
using System.IO;
namespace RatePlanNameAnalysis.Model
{
public class ConsumeModel
{
private static Lazy<PredictionEngine<ModelInput, ModelOutput>> PredictionEngine = new Lazy<PredictionEngine<ModelInput, ModelOutput>>(CreatePredictionEngine);
// For more info on consuming ML.NET models, visit https://aka.ms/mlnet-consume
// Method for consuming model in your app
public static ModelOutput Predict(ModelInput input)
{
ModelOutput result = PredictionEngine.Value.Predict(input);
return result;
}
public static PredictionEngine<ModelInput, ModelOutput> CreatePredictionEngine()
{
// Create new MLContext
MLContext mlContext = new MLContext();
// Load model & create prediction engine
string modelPath = Path.Combine(Directory.GetCurrentDirectory(), "..", "RatePlanNameAnalysis.ConsoleApp", "Models", "model.zip");
ITransformer loadedModel = mlContext.Model.Load(modelPath, out var modelInputSchema);
var predEngine = mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(loadedModel);
return predEngine;
}
}
}

View File

@ -0,0 +1,19 @@
// This file was auto-generated by ML.NET Model Builder.
using Microsoft.ML.Data;
namespace RatePlanNameAnalysis.Model
{
public class ModelInput
{
[ColumnName("BedTypeID"), LoadColumn(0)]
public string BedTypeID { get; set; }
[ColumnName("RatePlanName"), LoadColumn(1)]
public string RatePlanName { get; set; }
[ColumnName("BedTypeName"), LoadColumn(2)]
public string BedTypeName { get; set; }
}
}

View File

@ -0,0 +1,17 @@
// This file was auto-generated by ML.NET Model Builder.
using System;
using Microsoft.ML.Data;
namespace RatePlanNameAnalysis.Model
{
public class ModelOutput
{
// ColumnName attribute is used to change the column name from
// its default value, which is the name of the field.
[ColumnName("PredictedLabel")]
public string BedTypeName { get; set; }
public float[] Score { get; set; }
}
}

View File

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.ML" Version="3.0.1" />
</ItemGroup>
</Project>

37
RatePlanNameAnalysis.sln Normal file
View File

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34525.116
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RatePlanNameAnalysis.Api", "RatePlanNameAnalysis.Api\RatePlanNameAnalysis.Api.csproj", "{381B1DB8-6FAD-48BC-B324-5557B1E79060}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RatePlanNameAnalysis.Model", "RatePlanNameAnalysis.Model\RatePlanNameAnalysis.Model.csproj", "{B7F4729C-A7B0-40F9-B5E9-E0D8DE35AFA9}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RatePlanNameAnalysis.ConsoleApp", "RatePlanNameAnalysis.ConsoleApp\RatePlanNameAnalysis.ConsoleApp.csproj", "{E5049E66-2248-42E0-B1BF-1769EE49AC6C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{381B1DB8-6FAD-48BC-B324-5557B1E79060}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{381B1DB8-6FAD-48BC-B324-5557B1E79060}.Debug|Any CPU.Build.0 = Debug|Any CPU
{381B1DB8-6FAD-48BC-B324-5557B1E79060}.Release|Any CPU.ActiveCfg = Release|Any CPU
{381B1DB8-6FAD-48BC-B324-5557B1E79060}.Release|Any CPU.Build.0 = Release|Any CPU
{B7F4729C-A7B0-40F9-B5E9-E0D8DE35AFA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B7F4729C-A7B0-40F9-B5E9-E0D8DE35AFA9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B7F4729C-A7B0-40F9-B5E9-E0D8DE35AFA9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B7F4729C-A7B0-40F9-B5E9-E0D8DE35AFA9}.Release|Any CPU.Build.0 = Release|Any CPU
{E5049E66-2248-42E0-B1BF-1769EE49AC6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E5049E66-2248-42E0-B1BF-1769EE49AC6C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E5049E66-2248-42E0-B1BF-1769EE49AC6C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E5049E66-2248-42E0-B1BF-1769EE49AC6C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {758D48D0-1665-4B5D-835C-668857EC221B}
EndGlobalSection
EndGlobal