明经CAD社区

 找回密码
 注册

QQ登录

只需一步,快速开始

搜索
查看: 280|回复: 6

CAD2025调用微软的机器学习库Microsoft.ML

  [复制链接]
发表于 2024-3-29 12:47 | 显示全部楼层 |阅读模式
本帖最后由 伊江痕 于 2024-3-29 13:07 编辑

软件平台:CAD2025
开发规范:.NET Standard
开发框架:.NET8.0
开发语言:C#
涉及库:CAD开发基本类库及Microsoft.ML,如图1(nuget上自行下载)
演示算法类别:线性支持向量机算法
说明:目前测试的结果是,应该只有CAD2025能很好的调用这个机器学习库,因为25支持.NET8。其他仅支持Framework框架的CAD版本,在开发的时候调用Microsoft.ML都会产生各种意想不到的问题。


本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册

x
 楼主| 发表于 2024-3-29 12:47 | 显示全部楼层
源代码:
  1. using Autodesk.AutoCAD.DatabaseServices;
  2. using Autodesk.AutoCAD.Geometry;
  3. using Microsoft.ML;
  4. using Microsoft.ML.Data;
  5. using Microsoft.ML.Trainers;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;

  11. namespace Net8Cad
  12. {
  13.     public class MLTest
  14.     {
  15.         [CommandMethod("mssvm")]
  16.         public void Run()
  17.         {
  18.             Document doc = Application.DocumentManager.MdiActiveDocument;
  19.             Editor editor = doc.Editor;
  20.             Database db = HostApplicationServices.WorkingDatabase;
  21.             try
  22.             {
  23.                 // 数据集的获取
  24.                 var circles = GetAllT_viaSelection<Circle>(doc);
  25.                 List<PointData> pointsData = new List<PointData>();
  26.                 foreach ( var circle in circles )
  27.                 {
  28.                     PointData pd=new PointData();
  29.                     pd.PointX = (float)circle.Center.X;
  30.                     pd.PointY = (float)circle.Center.Y;
  31.                     pd.PointZ = (float)circle.Center.Z;
  32.                     if (circle.Color.ColorIndex == 1)
  33.                     {
  34.                         pd.PointLabel = true;
  35.                     }
  36.                     else
  37.                     {
  38.                         pd.PointLabel = false;
  39.                     }
  40.                     pointsData.Add(pd);
  41.                 }

  42.                 // 构建机器学习的训练模型
  43.                 var mlContext = new MLContext();
  44.                 var trainingDataView = mlContext.Data.LoadFromEnumerable<PointData>(pointsData);
  45.                 var trainer=mlContext.BinaryClassification.Trainers.LinearSvm(
  46.                     labelColumnName:"Label",
  47.                     featureColumnName: "Features",
  48.                     numberOfIterations:100);

  49.                 var trainingPipeline = mlContext.Transforms.Concatenate(
  50.                         outputColumnName: "NumFeatures",
  51.                         nameof(PointData.PointX),
  52.                         nameof(PointData.PointY),
  53.                         nameof(PointData.PointZ))
  54.                     
  55.                     .Append(mlContext.Transforms.Concatenate(outputColumnName: "Features", "NumFeatures"))
  56.                     .Append(mlContext.Transforms.CopyColumns(outputColumnName: "Label",
  57.                                                              inputColumnName: nameof(PointData.PointLabel)))
  58.                     .Append(trainer);

  59.                 var model = trainingPipeline.Fit(trainingDataView);
  60.                 var svmModel = model.LastTransformer.Model;
  61.                 var weights = svmModel.Weights;  // w1*x+w2*y+b=0
  62.                 var bias=svmModel.Bias;
  63.                 WriteMessage(doc, "训练模型为:" + $"{model}");
  64.                 WriteMessage(doc, $"weights 个数:{weights.Count} bias 值为:{bias}");
  65.                 WriteMessage(doc, $"第一个:{weights[0]} 第二个{weights[1]} 第三个{weights[2]}");

  66.                 // w1*x+w2*y+b=0
  67.                 double x1 = 100;
  68.                 double x2 = 200;
  69.                 double y1 = (weights[0] * x1 + bias) / (-weights[1]);
  70.                 double y2 = (weights[0] * x2 + bias) / (-weights[1]);

  71.                 Xline xl = new Xline();
  72.                 xl.BasePoint = new Point3d(x1, y1, 0);
  73.                 xl.SecondPoint=new Point3d(x2, y2, 0);
  74.                 ToModelSpace(doc, xl);
  75.                 WriteMessage(doc, "done");
  76.             }
  77.             catch (System.Exception ex)
  78.             {

  79.                 string msg = "报错为:" + ex.Message + "\n" + "位置为:" + ex.StackTrace;
  80.                 WriteMessage(doc, msg);

  81.             }
  82.         }
  83.         List<T> GetAllT_viaSelection<T>(Document doc) where T : Entity
  84.         {
  85.             List<T> selectedLines = new List<T>();

  86.             using (Transaction tr = doc.Database.TransactionManager.StartTransaction())
  87.             {
  88.                 // 设置提示词
  89.                 PromptSelectionOptions opts = new PromptSelectionOptions();
  90.                 opts.MessageForAdding = "\n请框选:\n";
  91.                 // 提示用户框选实体
  92.                 PromptSelectionResult result = doc.Editor.GetSelection(opts);
  93.                 if (result.Status != PromptStatus.OK)
  94.                     return null;

  95.                 // 获取选中实体的ObjectId数组
  96.                 ObjectId[] objectIds = result.Value.GetObjectIds();

  97.                 // 遍历选中实体
  98.                 foreach (ObjectId objectId in objectIds)
  99.                 {
  100.                     // 通过ObjectId打开实体
  101.                     Entity entity = (Entity)objectId.GetObject(OpenMode.ForRead, false);

  102.                     // 判断实体是否为Line类型
  103.                     if (entity.GetType() == typeof(T))
  104.                     {
  105.                         T line = (T)entity;
  106.                         selectedLines.Add(line);
  107.                     }
  108.                 }

  109.                 tr.Commit();
  110.             }
  111.             return selectedLines;
  112.         }
  113.         void WriteMessage(Document doc, string message)
  114.         {
  115.             Editor editor = doc.Editor;
  116.             editor.WriteMessage("\n" + message);
  117.         }
  118.         ObjectId ToModelSpace(Document doc, Entity entity)
  119.         {
  120.             ObjectId objectId;

  121.             using (doc.LockDocument())
  122.             {
  123.                 Database database = doc.Database;
  124.                 using (Transaction trans = database.TransactionManager.StartTransaction())
  125.                 {
  126.                     BlockTable blockTable = (BlockTable)trans.GetObject(database.BlockTableId, OpenMode.ForWrite, false);
  127.                     BlockTableRecord blockTableRecord = (BlockTableRecord)trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
  128.                     objectId = blockTableRecord.AppendEntity(entity);
  129.                     trans.AddNewlyCreatedDBObject(entity, true);
  130.                     trans.Commit();

  131.                 }

  132.             }

  133.             return objectId;
  134.         }



  135.     }
  136.     public class PointData
  137.     {
  138.         [LoadColumn(0)]
  139.         public bool PointLabel { get; set; }
  140.         [LoadColumn(1)]
  141.         public float PointX { get; set; }
  142.         [LoadColumn(2)]
  143.         public float PointY { get; set; }
  144.         [LoadColumn(3)]
  145.         public float PointZ { get; set; }
  146.     }
  147. }
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2024-3-29 12:47 | 显示全部楼层
演示结果:如图
测试文件:见附件
视频演示:b站 伊江痕 链接为:伊江痕的b站演示_Microsoft.ML的使用

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册

x
 楼主| 发表于 2024-3-29 16:23 | 显示全部楼层

装装掰                     
发表于 2024-3-29 18:22 | 显示全部楼层
哇塞,有点东西
 楼主| 发表于 2024-3-29 19:12 | 显示全部楼层

我预测你会发 多线程读取数据库 的帖子
您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|CAD论坛|CAD教程|CAD下载|联系我们|关于明经|明经通道 ( 粤ICP备05003914号 )  
©2000-2023 明经通道 版权所有 本站代码,在未取得本站及作者授权的情况下,不得用于商业用途

GMT+8, 2024-4-28 06:12 , Processed in 0.281097 second(s), 24 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表