当我在Microsoft Docs上进行ML.DOTNET练习时,发现了一个关于CS0029的错误。完整代码如下:
using System;using System.IO;using Microsoft.ML;using System.Collections.Generic;using Microsoft.ML.TimeSeries;namespace ProductSalesAnomalyDetection{ class Program { static readonly string _dataPath = Path.Combine(Environment.CurrentDirectory, "Data", "phone-calls.csv"); static void Main(string[] args) { MLContext mlContext = new MLContext(); IDataView dataView = mlContext.Data.LoadFromTextFile<PhoneCallsData>(path: _dataPath, hasHeader: true, separatorChar: ','); int period = DetectPeriod(mlContext, dataView); DetectAnomaly(mlContext, dataView, period); } static void DetectPeriod(MLContext mlContext, IDataView phoneCalls) { int period = mlContext.AnomalyDetection.DetectSeasonality(phoneCalls, nameof(PhoneCallsData.value)); Console.WriteLine("Period of the series is: {0}.", period); } static void DetectAnomaly(MLContext mlContext, IDataView phoneCalls, int period) { var options = new SrCnnEntireAnomalyDetectorOptions() { Threshold = 0.3, Sensitivity = 64.0, DetectMode = SrCnnDetectMode.AnomalyAndMargin, Period = period, }; var outputDataView = mlContext.AnomalyDetection.DetectEntireAnomalyBySrCnn(phoneCalls, nameof(PhoneCallsPrediction.Prediction), nameof(PhoneCallsData.value), options); var predictions = mlContext.Data.CreateEnumerable<PhoneCallsPrediction>( outputDataView, reuseRowObject: false); Console.WriteLine("Index\tData\tAnomaly\tAnomalyScore\tMag\tExpectedValue\tBoundaryUnit\tUpperBoundary\tLowerBoundary"); var index = 0; foreach (var p in predictions) { if (p.Prediction[0] == 1) { Console.WriteLine("{0},{1},{2},{3},{4} <-- alert is on, detecte anomaly", index, p.Prediction[0], p.Prediction[3], p.Prediction[5], p.Prediction[6]); } else { Console.WriteLine("{0},{1},{2},{3},{4}", index, p.Prediction[0], p.Prediction[3], p.Prediction[5], p.Prediction[6]); } ++index; } Console.WriteLine(""); } }}
错误出现在Main方法中:
int period = DetectPeriod(mlContext, dataView);
错误信息是无法将类型’void’隐式转换为’int’。
我只是按照提供的代码进行操作,但看起来代码中有一些错误。可能是我把错误的代码放错了位置,但我严格按照他们的指示操作。如果您能告诉我JAVA和C#中将类型’void’隐式转换为’int’的区别,我将非常感激。谢谢
回答:
static void DetectPeriod(MLContext mlContext, IDataView phoneCalls)
表示DetectPeriod()
不返回任何值。而您试图将这个不存在的返回值赋给int period
。
您需要将定义更改为返回int
,然后实际return
一个int
值。
static int DetectPeriod(MLContext mlContext, IDataView phoneCalls) { int period = mlContext.AnomalyDetection.DetectSeasonality(phoneCalls, nameof(PhoneCallsData.value)); Console.WriteLine("Period of the series is: {0}.", period); return period; }