首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >ML.NET二进制分类模型不起作用

ML.NET二进制分类模型不起作用
EN

Stack Overflow用户
提问于 2018-11-10 14:48:34
回答 1查看 1.4K关注 0票数 2

关于ML.Net的文档似乎不多,因为它似乎是相对较新的。我遇到了一个又一个问题,试图学习如何使用它,我终于想出了足够的方法,至少可以让它在没有出现错误的情况下运行;然而,我的模型似乎有问题。它总是以50%的概率返回0。我已经在下面列出了我的代码。有谁知道我可以探索的最新版本的ML.Net的好资源吗?下面的代码应该是建立一个二进制分类模型,可以预测一支球队是否会进入季后赛。数据只是上个赛季的最后结果,大部分数据都被删除了,所以剩下的数据只有平均年龄、胜利、输球和季后赛状态(1 =季后赛&0=没有季后赛)。

Program.cs

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.ML;
using Microsoft.ML.Core.Data;
using Microsoft.ML.Runtime.Api;
using Microsoft.ML.Runtime.Data;

namespace MachineLearning2
{
    class Program
    {
        static readonly string _trainDataPath = Path.Combine(Environment.CurrentDirectory, "trainingNHL.txt");
        static readonly string _testDataPath = Path.Combine(Environment.CurrentDirectory, "testingNHL.txt");
        static readonly string _modelPath = Path.Combine(Environment.CurrentDirectory, "Model.zip");
        static TextLoader _textLoader;

        static void Main(string[] args)
        {
            MLContext mlContext = new MLContext(seed: 0);
            _textLoader = mlContext.Data.TextReader(new TextLoader.Arguments()
            {
                Separator = ",",
                HasHeader = false,
                Column = new[]
                    {
                        new TextLoader.Column("Age", DataKind.R4, 0),
                        new TextLoader.Column("Wins", DataKind.R4, 1),
                        new TextLoader.Column("Losses", DataKind.R4, 2),
                        new TextLoader.Column("Label", DataKind.R4, 3)
                    }
            });
            var model = Train(mlContext, _trainDataPath);
            Evaluate(mlContext, model);
            Predict(mlContext, model);
            PredictWithModelLoadedFromFile(mlContext);

        }

        public static ITransformer Train(MLContext mlContext, string dataPath)
        {
            IDataView dataView = _textLoader.Read(dataPath);
            var pipeline = mlContext.Transforms.Concatenate("Features","Age", "Wins", "Losses")
                .Append(mlContext.BinaryClassification.Trainers.FastTree(numLeaves: 50, numTrees: 50, minDatapointsInLeafs: 20));
            Console.WriteLine("=============== Create and Train the Model ===============");
            var model = pipeline.Fit(dataView);
            Console.WriteLine("=============== End of training ===============");
            Console.WriteLine();
            return model;
        }

        public static void Evaluate(MLContext mlContext, ITransformer model)
        {
            IDataView dataView = _textLoader.Read(_testDataPath);
            Console.WriteLine("=============== Evaluating Model accuracy with Test data===============");
            var predictions = model.Transform(dataView);
            var metrics = mlContext.BinaryClassification.Evaluate(predictions, "Label");
            Console.WriteLine();
            Console.WriteLine("Model quality metrics evaluation");
            Console.WriteLine("--------------------------------");
            Console.WriteLine($"Accuracy: {metrics.Accuracy:P2}");
            Console.WriteLine($"Auc: {metrics.Auc:P2}");
            Console.WriteLine($"F1Score: {metrics.F1Score:P2}");
            Console.WriteLine("=============== End of model evaluation ===============");
            SaveModelAsFile(mlContext, model);
        }

        private static void SaveModelAsFile(MLContext mlContext, ITransformer model)
        {
            using (var fs = new FileStream(_modelPath, FileMode.Create, FileAccess.Write, FileShare.Write))
                mlContext.Model.Save(model, fs);
            Console.WriteLine("The model is saved to {0}", _modelPath);

        }

        public static void Predict(MLContext mlContext, ITransformer model)
        {
            var predictionFunction = model.MakePredictionFunction<NHLData, NHLPrediction>(mlContext);
            NHLData sampleTeam = new NHLData
            {
                Age = 29,
                Wins = 60,
                Losses = 22
            };
            var resultprediction = predictionFunction.Predict(sampleTeam);
            Console.WriteLine();
            Console.WriteLine("=============== Prediction Test of model with a single sample and test dataset ===============");

            Console.WriteLine();
            Console.WriteLine($"Age: {sampleTeam.Age} | Wins: {sampleTeam.Wins} | Losses: {sampleTeam.Losses} | Prediction: {(Convert.ToBoolean(resultprediction.Prediction) ? "Yes" : "No")} | Probability: {resultprediction.Probability} ");
            Console.WriteLine("=============== End of Predictions ===============");
            Console.WriteLine();
        }

        public static void PredictWithModelLoadedFromFile(MLContext mlContext)
        {
            IEnumerable<NHLData> teams = new[]
            {
                new NHLData
                {
                    Age = 29,
                    Wins = 30,
                    Losses = 52
                },
                new NHLData
                {
                    Age = 35,
                    Wins = 80,
                    Losses = 2
                }
            };
            ITransformer loadedModel;
            using (var stream = new FileStream(_modelPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                loadedModel = mlContext.Model.Load(stream);
            }
            // Create prediction engine
            var nhlStreamingDataView = mlContext.CreateStreamingDataView(teams);
            var predictions = loadedModel.Transform(nhlStreamingDataView);

            // Use the model to predict whether comment data is toxic (1) or nice (0).
            var predictedResults = predictions.AsEnumerable<NHLPrediction>(mlContext, reuseRowObject: false);
            Console.WriteLine();

            Console.WriteLine("=============== Prediction Test of loaded model with a multiple samples ===============");
            var teamsAndPredictions = teams.Zip(predictedResults, (team, prediction) => (team, prediction));
            foreach (var item in teamsAndPredictions)
            {
                Console.WriteLine($"Age: {item.team.Age} | Wins: {item.team.Wins} | Losses: {item.team.Losses} | Prediction: {(Convert.ToBoolean(item.prediction.Prediction) ? "Yes" : "No")} | Probability: {item.prediction.Probability} ");
            }
            Console.WriteLine("=============== End of predictions ===============");
        }
    }
}

NHLData.cs

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.ML.Runtime.Api;

namespace MachineLearning2
{
    public class NHLData
    {
        [Column(ordinal: "0")]
        public float Age;
        [Column(ordinal: "1")]
        public float Wins;
        [Column(ordinal: "2")]
        public float Losses;
        [Column(ordinal: "3", name: "Label")]
        public float Playoffs;
    }

    public class NHLPrediction
    {
        [ColumnName("PredictedLabel")]
        public bool Prediction { get; set; }

        [ColumnName("Probability")]
        public float Probability { get; set; }

        [ColumnName("Score")]
        public float Score { get; set; }
    }
}

trainingNHL.txt (专栏:年龄,赢,输,季后赛)

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
28.4,53,18,1
27.5,54,23,1
28,51,24,1
28.3,49,26,1
29.5,45,26,1
28.8,45,27,1
29.1,45,29,1
27.7,44,29,1
26.4,43,30,1
28.5,42,32,0
27,36,35,0
26.8,36,40,0
28,33,39,0
30.2,30,39,0
26.5,29,41,0
27.1,25,45,0

testingNHL.txt (专栏:年龄,赢,输,季后赛)

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
26.8,52,20,1
28.6,50,20,1
28.4,49,26,1
28.7,44,25,1
27.7,47,29,1
27.4,42,26,1
26.4,45,30,1
27.8,44,30,0
28.5,44,32,0
28.4,37,35,0
28.4,35,37,0
28.7,34,39,0
28.2,31,40,0
27.8,29,40,0
29.3,28,43,0
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-10 15:32:54

trainingNHL.txt是您正在使用的完整数据集还是其中的一个示例?我只是试着用FastTree进行训练,我看到了“警告: 50次增强迭代都无法生长一棵树,这通常是因为叶超参数中的最小文档设置得太高,不适合这个数据集。”

给定您在FastTree中设置的参数,您将需要更多的数据来训练一个有意义的模型。当我将minDatapointsInLeafs改为2时,我可以训练一个非平凡的模型(尽管由于数据量的原因,结果仍然不太可靠)。您也可以尝试使用类似于AveragedPerceptron或SDCA的东西。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53244185

复制
相关文章
MySQL是如何打开和关闭表?
当我们在执行mysqladmin status 命令或连接通过mysql客户端连接到实例后,执行\s的时候,应该看到类似以下的内容:
SEian.G
2021/07/29
3.6K0
HTTP的KeepAlive是开启还是关闭?
http://itindex.net/detail/50719-http-keepalive
跟着阿笨一起玩NET
2018/09/20
2.2K0
Android获取软键盘的高度、键盘的打开与关闭、监听键盘处于打开还是关闭状态
最近在项目中,需要获取到软键盘的高度,再将底部的布局上移键盘的高度,话不多说,直接上代码:
SoullessCoder
2019/08/07
7.8K0
如何判断是关闭还是刷新网页
我们在写js代码的时候,经常要判断网页是否被关闭了,如果是被关闭了,就执行某段代码,这个可以用HTML的onbeforeunload事件来执行一段js代码,但是如果网页只是被刷新的话,也同样会触发onbeforeunload事件,下面这段js代码可以判断是否关闭 //判断是关闭还是刷新 if(event.clientX>document.body.clientWidth&&event.clientY<0||event.altKey) {     alert("你关闭了浏览器"); } 这段代码就是判断触发onbeforeunload事件时,鼠标是否点击了关闭按钮,或者按了ALT+F4来关闭网页,如果是,则认为系统是关闭网页,否则在认为系统是刷新网页
源哥
2018/08/28
3.1K0
mysql or条件可以使用索引而避免全表
CREATE TABLE IF NOT EXISTS `t_myisam` ( `id` int(1) NOT NULL AUTO_INCREMENT, `uid` int(11) NOT NULL, `aNum` char(20) DEFAULT NULL, PRIMARY KEY (`id`), KEY `uid` (`uid`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
黄规速
2022/04/14
1.5K0
mysql or条件可以使用索引而避免全表
导出SAP数据库表的字段和数据元素等详细信息
SAP→SE16N→DD03L 然后筛选表名,获取该表所有数据,然后进行导出,选择导出格式为自定义XMXL 缺点:导出字段顺序无法控制,按字母顺序排列;无法导出字段描述。
不会写代码的杰尼
2022/05/19
2K0
导出SAP数据库表的字段和数据元素等详细信息
HTTPKeepAlive,开启还是关闭
所谓「HTTP Keep-Alive」,在维基百科里称为「HTTP Persistent Connection」,说白了就是复用HTTP连接,如此一来理论上客户端的用户体验会更流畅,但是与之相对服务端不得不维持大量的连接。开启还是关闭,这是个问题。
LA0WAN9
2021/12/14
4870
oracle可以更改表名,sql – 更改Oracle表名
CONSTRAINT ORDER_SOURCE_PK PRIMARY KEY(OS_ID)
全栈程序员站长
2022/08/30
1.8K0
Tiktok 根据主播id(uniqueId)获取个人详细信息
https://download.csdn.net/download/qq_38154948/87942615
拉灯的小手
2023/06/23
9470
es 更改索引类型-存档
POST /livingdata/_mapping/?pretty { "properties": { "totalCount":{ "type": "text",
用户9347382
2022/02/17
5610
10.2 打开与关闭文件
例如:fopen(“a1”,“r”),表示要打开名字为“a1”的文件,使用文件方式为“读入”。
小林C语言
2019/07/12
7430
10.2 打开与关闭文件
文件的打开与关闭
使用完一个文件后应该关闭它,以防止程序对文件误操作而导致出错。文件关闭是指撤销文件信息区和文件缓冲区,使文件指针变量不再指向该文件。
pigeon
2022/04/11
1.3K0
文件的打开与关闭
判断网页是通过PC端还是移动终端打开的
通过判断浏览器的 userAgent,用正则来判断手机是否是ios和Android客户端。代码如下:
德顺
2019/11/13
5.3K0
Redis跳跃表是如何添加元素的?
Java 面试不可能不问 Redis,问到 Redis 不可能不问 Redis 的常用数据类型,问到 Redis 的常用数据类型,不可能不问跳跃表,当问到跳跃表经常会被问到跳跃表的查询和添加流程,所以接下来我们一起来看这道题的答案吧。
磊哥
2023/07/09
1910
Redis跳跃表是如何添加元素的?
Redis跳跃表是如何添加元素的?
Java 面试不可能不问 Redis,问到 Redis 不可能不问 Redis 的常用数据类型,问到 Redis 的常用数据类型,不可能不问跳跃表,当问到跳跃表经常会被问到跳跃表的查询和添加流程,所以接下来我们一起来看这道题的答案吧。
磊哥
2023/06/27
2230
Redis跳跃表是如何添加元素的?
如何更改伪元素的样式
在前端开发中我们会经常用到伪元素,有时候需要通过js来修改伪元素的样式,那么有哪几种方式来修改伪元素的样式呢?
挥刀北上
2021/01/27
9.4K0
如何更改伪元素的样式
SQL server无法更改表
在设计器中,选择表设计器和数据库设计器,将阻止保存要求重新创建表的更改选项取消勾选 再次编辑表中内容时就不会再有错误弹窗。
magize
2023/07/11
2730
SQL server无法更改表
点击加载更多

相似问题

为什么‘a’标签需要`tabindex=0`?

20

如何在tabIndex = '0‘中添加TypeScript div?

29

为什么IE7要在没有表索引的元素中添加tabindex="0“?

12

动态添加tabindex

40

<a> click="“在tabindex='0‘时不起作用

151
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文