/// <summary> /// Позволяе расчитать дистанцию между двумя объектами SampleSet.RowSample. /// Учитываются только выходной параметр. /// </summary> /// <param name="A">Первый входной вектор типа SampleSet.RowSample </param> /// <param name="B">Второй входной вектор типа SampleSet.RowSample</param> /// <param name="type">Тип вычисляемого расстояния Евклидово, Манхетенское и др.</param> /// <returns>Растояние типа double</returns> public static double getOutputDistance(this SampleSet.RowSample A, SampleSet.RowSample B, DistanceType type = DistanceType.Euclidean) { double result = 0; switch (type) { case DistanceType.Euclidean: { result += Math.Pow(A.DoubleOutput - B.DoubleOutput, 2.0); return(Math.Sqrt(result)); } case DistanceType.Manhattan: { result += Math.Abs(A.DoubleOutput - B.DoubleOutput); return(result); } // case DistanceType.Mahalanobis: throw new NotImplementedException("Нет реализации необходимы формулы"); // case DistanceType.Gaussian: throw new NotImplementedException("Нет реализации необходимы формулы"); default: { result += Math.Pow(A.DoubleOutput - B.DoubleOutput, 2.0); return(Math.Sqrt(result)); } } }
/// <summary> /// Позволяе расчитать отнормированную дистанцию между двумя объектами SampleSet.RowSample. /// Учитывает только выходной параметр. /// </summary> /// <param name="A">Первый входной вектор типа SampleSet.RowSample</param> /// <param name="B">Второй входной вектор типа SampleSet.RowSample</param> /// <param name="dataInfoA">SampleSet используемый для корректной нормировки значений вектора A</param> /// <param name="dataInfoB">SampleSet используемый для корректной нормировки значений вектора B</param> /// <param name="type">Тип вычисляемого расстояния Евклидово, Манхетенское и др.</param> /// <returns>Растояние типа double</returns> public static double getOutputNormalizedDistance(this SampleSet.RowSample A, SampleSet.RowSample B, SampleSet dataInfoA, SampleSet dataInfoB = null, DistanceType type = DistanceType.Euclidean) { if (dataInfoB == null) { dataInfoB = dataInfoA; } double result = 0; switch (type) { case DistanceType.Euclidean: { result += Math.Pow(dataInfoA.OutputAttribute.EvaluteNormalisedValue(A.DoubleOutput) - dataInfoB.OutputAttribute.EvaluteNormalisedValue(B.DoubleOutput), 2.0); return(Math.Sqrt(result)); } case DistanceType.Manhattan: { result += Math.Abs(dataInfoA.OutputAttribute.EvaluteNormalisedValue(A.DoubleOutput) - dataInfoB.OutputAttribute.EvaluteNormalisedValue(B.DoubleOutput)); return(result); } // case DistanceType.Mahalanobis: throw new NotImplementedException("Нет реализации необходимы формулы"); // case DistanceType.Gaussian: throw new NotImplementedException("Нет реализации необходимы формулы"); default: { result += Math.Pow(A.DoubleOutput - B.DoubleOutput, 2.0); return(Math.Sqrt(result)); } } }
public double PointYDifference(SampleSet.RowSample Point, PCFuzzySystem Approx) { //!!!!! double diff = Point.StringOutput.Equals(Approx.classifyBase(Point.InputAttributeValue, Approx.RulesDatabaseSet[0]), StringComparison.OrdinalIgnoreCase) ? 1.0 : 0.0; return(diff); }
/// <summary> /// Позволяет расчитать отнормированную дистанцию между двумя объектами SampleSet.RowSample. /// Учитывает входные и выходной параметры. /// </summary> /// <param name="A">Первый входной вектор типа SampleSet.RowSample</param> /// <param name="B">Второй входной вектор типа SampleSet.RowSample</param> /// <param name="dataInfoA">SampleSet используемый для корректной нормировки значений вектора A</param> /// <param name="dataInfoB">SampleSet используемый для корректной нормировки значений вектора B</param> /// <param name="type">Тип вычисляемого расстояния Евклидово, Манхетенское и др.</param> /// <returns>Растояние типа double</returns> public static double getFullNormalizedDistance(this SampleSet.RowSample A, SampleSet.RowSample B, SampleSet dataInfoA, SampleSet dataInfoB = null, DistanceType type = DistanceType.Euclidean) { if (A.InputAttributeValue.LongLength != B.InputAttributeValue.LongLength) { throw new InvalidOperationException("Входные данные разных размерностей"); } if (A.InputAttributeValue.LongLength != dataInfoA.InputAttributes.Count) { throw new InvalidOperationException("Описание не соотвествует данным"); } if (dataInfoB == null) { dataInfoB = dataInfoA; } if (B.InputAttributeValue.LongLength != dataInfoB.InputAttributes.Count) { throw new InvalidOperationException("Описание не соотвествует данным"); } double result = 0; switch (type) { case DistanceType.Euclidean: { for (int i = 0; i < A.InputAttributeValue.LongLength; i++) { result += Math.Pow((dataInfoA.InputAttributes[i].EvaluteNormalisedValue(A.InputAttributeValue[i])) - dataInfoB.InputAttributes[i].EvaluteNormalisedValue(B.InputAttributeValue[i]), 2.0); } result += Math.Pow(dataInfoA.OutputAttribute.EvaluteNormalisedValue(A.DoubleOutput) - dataInfoB.OutputAttribute.EvaluteNormalisedValue(B.DoubleOutput), 2.0); return(Math.Sqrt(result)); } case DistanceType.Manhattan: { for (int i = 0; i < A.InputAttributeValue.LongLength; i++) { result += Math.Abs(dataInfoA.InputAttributes[i].EvaluteNormalisedValue(A.InputAttributeValue[i]) - dataInfoB.InputAttributes[i].EvaluteNormalisedValue(B.InputAttributeValue[i])); } result += Math.Abs(dataInfoA.OutputAttribute.EvaluteNormalisedValue(A.DoubleOutput) - dataInfoB.OutputAttribute.EvaluteNormalisedValue(B.DoubleOutput)); return(result); } // case DistanceType.Mahalanobis: throw new NotImplementedException("Нет реализации необходимы формулы"); // case DistanceType.Gaussian: throw new NotImplementedException("Нет реализации необходимы формулы"); default: { for (int i = 0; i < A.InputAttributeValue.LongLength; i++) { result += Math.Pow((dataInfoA.InputAttributes[i].EvaluteNormalisedValue(A.InputAttributeValue[i])) - dataInfoB.InputAttributes[i].EvaluteNormalisedValue(B.InputAttributeValue[i]), 2.0); } result += Math.Pow(dataInfoA.OutputAttribute.EvaluteNormalisedValue(A.DoubleOutput) - dataInfoB.OutputAttribute.EvaluteNormalisedValue(B.DoubleOutput), 2.0); return(Math.Sqrt(result)); } } }
/// <summary> /// Позволяет найти ближайшую точку в массиве Array на основе заданного способа рассчета дистанции. /// Учитываются входные параметры. /// </summary> /// <param name="A">Точка для которой исчется ближайшая в массиве Array</param> /// <param name="Array">Вектор точек</param> /// <param name="dataInfoA">SampleSet используемый для корректной нормировки значений вектора A</param> /// <param name="dataInfoB">SampleSet используемый для корректной нормировки значений в списке ListValue</param> /// <param name="type">Тип вычисляемого расстояния Евклидово, Манхетенское и др.</param> /// <returns>Индекс ближайшей точки типа int</returns> public static int NearestNormalizedInputIndex(this SampleSet.RowSample A, SampleSet.RowSample[] Array, SampleSet dataInfoA, SampleSet dataInfoB = null, DistanceType type = DistanceType.Euclidean) { double[] dist = new double[Array.LongLength]; for (int i = 0; i < Array.LongLength; i++) { dist[i] = getInputNormalizedDistance(A, Array[i], dataInfoA, dataInfoB, type); } return(dist.ToList().IndexOf(dist.Min())); }
/// <summary> /// Позволяет найти ближайшую точку в списке ListValue на основе заданного способа рассчета нормированной дистанции. /// Учитываются входные параметры. /// </summary> /// <param name="A">Точка для которой исчется ближайшая в списке ListValue</param> /// <param name="ListValue">Вектор точек</param> /// <param name="dataInfoA">SampleSet используемый для корректной нормировки значений вектора A</param> /// <param name="dataInfoB">SampleSet используемый для корректной нормировки значений в списке ListValue</param> /// <param name="type">Тип вычисляемого расстояния Евклидово, Манхетенское и др.</param> /// <returns>Индекс ближайшей точки типа int</returns> public static int NearestNormalizedInputIndex(this SampleSet.RowSample A, List <SampleSet.RowSample> ListValue, SampleSet dataInfoA, SampleSet dataInfoB = null, DistanceType type = DistanceType.Euclidean) { double[] dist = new double[ListValue.Count]; for (int i = 0; i < ListValue.Count; i++) { dist[i] = getInputNormalizedDistance(A, ListValue[i], dataInfoA, dataInfoB, type); } return(dist.ToList().IndexOf(dist.Min())); }
/// <summary> /// Позволяет найти ближайшую точку в массиве Array на основе заданного способа рассчета дистанции. /// Учитываются входные и выходной параметры. /// </summary> /// <param name="A">Точка для которой исчется ближайшая в массиве Array</param> /// <param name="Array">Вектор точек</param> /// <param name="type">Тип вычисляемого расстояния Евклидово, Манхетенское и др.</param> /// <returns>Индекс ближайшей точки типа int</returns> public static int NearestFullIndex(this SampleSet.RowSample A, SampleSet.RowSample[] Array, DistanceType type = DistanceType.Euclidean) { double[] dist = new double[Array.LongLength]; for (int i = 0; i < Array.LongLength; i++) { dist[i] = getFullDistance(A, Array[i], type); } return(dist.ToList().IndexOf(dist.Min())); }
/// <summary> /// Позволяет найти ближайшую точку в списке ListValue на основе заданного способа рассчета дистанции. /// Учитываются входные и выходной параметры. /// </summary> /// <param name="A">Точка для которой исчется ближайшая в списке ListValue</param> /// <param name="ListValue">Вектор точек</param> /// <param name="type">Тип вычисляемого расстояния Евклидово, Манхетенское и др.</param> /// <returns>Индекс ближайшей точки типа int</returns> public static int NearestFullIndex(this SampleSet.RowSample A, List <SampleSet.RowSample> ListValue, DistanceType type = DistanceType.Euclidean) { double[] dist = new double[ListValue.Count]; for (int i = 0; i < ListValue.Count; i++) { dist[i] = getFullDistance(A, ListValue[i], type); } return(dist.ToList().IndexOf(dist.Min())); }
private static double calcWeigth(SampleSet.RowSample Value, List <Term> Terms) { double mul = 1.0; foreach (Term tr in Terms) { mul *= tr.LevelOfMembership(Value.InputAttributeValue[tr.NumVar + 1]); } return(mul); }
public void CalcFarPoint() { //Для создания модификаций double[] initValue = new double[originalSimpleSet[0].InputAttributeValue.LongLength]; double initOutput = ResultSystem.LearnSamplesSet.OutputAttribute.Min; for (int j = 0; j < initValue.LongLength; j++) { initValue[j] = ResultSystem.LearnSamplesSet.InputAttributes[j].Min; } SampleSet.RowSample initPoint = new SampleSet.RowSample(initValue, null, initOutput, ""); for (int i = 0; i < originalSimpleSet.Count; i++) { originalSimpleSetDistanteToPoint.Add(initPoint.getInputNormalizedDistance(originalSimpleSet[i], ResultSystem.LearnSamplesSet)); } }
/// <summary> /// Позволяе расчитать дистанцию между двумя объектами SampleSet.RowSample. /// Учитываются и входные и выходной параметры. /// </summary> /// <param name="A">Первый входной вектор типа SampleSet.RowSample </param> /// <param name="B">Второй входной вектор типа SampleSet.RowSample</param> /// <param name="type">Тип вычисляемого расстояния Евклидово, Манхетенское и др.</param> /// <returns>Растояние типа double</returns> public static double getFullDistance(this SampleSet.RowSample A, SampleSet.RowSample B, DistanceType type = DistanceType.Euclidean) { if (A.InputAttributeValue.LongLength != B.InputAttributeValue.LongLength) { throw new InvalidOperationException("Входные данные разных размерностей"); } double result = 0; switch (type) { case DistanceType.Euclidean: { for (int i = 0; i < A.InputAttributeValue.LongLength; i++) { result += Math.Pow(A.InputAttributeValue[i] - B.InputAttributeValue[i], 2.0); } result += Math.Pow(A.DoubleOutput - B.DoubleOutput, 2.0); return(Math.Sqrt(result)); } case DistanceType.Manhattan: { for (int i = 0; i < A.InputAttributeValue.LongLength; i++) { result += Math.Abs(A.InputAttributeValue[i] - B.InputAttributeValue[i]); } result += Math.Abs(A.DoubleOutput - B.DoubleOutput); return(result); } // case DistanceType.Mahalanobis: throw new NotImplementedException("Нет реализации необходимы формулы"); // case DistanceType.Gaussian: throw new NotImplementedException("Нет реализации необходимы формулы"); default: { for (int i = 0; i < A.InputAttributeValue.LongLength; i++) { result += Math.Pow(A.InputAttributeValue[i] - B.InputAttributeValue[i], 2.0); } result += Math.Pow(A.DoubleOutput - B.DoubleOutput, 2.0); return(Math.Sqrt(result)); } } }
double PointYDifference(SampleSet.RowSample x) { return(Math.Abs(x.DoubleOutput - approx.approx_base(x.InputAttributeValue, approx.RulesDatabaseSet[0]))); }
double PointYDifference(SampleSet.RowSample x) { return(x.StringOutput.Equals(approx.classifyBase(x.InputAttributeValue, approx.RulesDatabaseSet[0])) ? 1.0 : 0.0); // Math.Abs(x.DoubleOutput - approx.approx_base(x.InputAttributeValue)); }
public double PointYDifference(SampleSet.RowSample Point, TSAFuzzySystem Approx) { return(Math.Abs(Point.DoubleOutput - Approx.approx_base(Point.InputAttributeValue, Approx.RulesDatabaseSet[0]))); }
public static SampleSet LoadLearnFromUFS(XmlDocument Source) { //init SampleSet temp_set = null; List <SampleSet.AttributeInfo> input_Attribute = new List <SampleSet.AttributeInfo>(); List <SampleSet.RowSample> data_Row = new List <SampleSet.RowSample>(); SampleSet.AttributeInfo output_Attribute = new SampleSet.AttributeInfo(); string opened_dataset; //parse_start XmlNode table_node = Source.DocumentElement.SelectSingleNode("descendant::Table[@Type='Training'] "); //We get learning table if (table_node == null) { throw new System.FormatException("В файле нет таблиц данных"); } opened_dataset = table_node.Attributes.GetNamedItem("Name").Value; output_Attribute.Name = table_node.Attributes.GetNamedItem("Output").Value; XmlNode attrib_node = table_node.SelectSingleNode("Attributes"); //We get atribute's tags int count_attribs = XmlConvert.ToInt32(attrib_node.Attributes.GetNamedItem("Count").Value); for (int k = 0; k < count_attribs; k++) { SampleSet.AttributeInfo temp_attib = new SampleSet.AttributeInfo(); temp_attib.Name = attrib_node.ChildNodes[k].Attributes.GetNamedItem("Name").Value; // We get one attribute tag foreach (XmlNode Value in attrib_node.ChildNodes[k].ChildNodes) { switch (Value.Name) { case "Min": { temp_attib.Min = XmlConvert.ToDouble(Value.InnerXml); break; } case "Max": { temp_attib.Max = XmlConvert.ToDouble(Value.InnerXml); break; } case "Enum": { foreach (XmlNode tempValue in Value.ChildNodes) { temp_attib.LabelsValues.Add(tempValue.Attributes.GetNamedItem("Value").Value); } break; } } } if (temp_attib.LabelsValues.Count == 0) { temp_attib.Type = SampleSet.AttributeInfo.TypeAttribute.real; } else { temp_attib.Type = SampleSet.AttributeInfo.TypeAttribute.nominate; } if (temp_attib.Name.Equals(output_Attribute.Name, StringComparison.OrdinalIgnoreCase)) { output_Attribute = temp_attib; } else { input_Attribute.Add(temp_attib); } } XmlNode rows_node = table_node.SelectSingleNode("Rows"); //We get data rows int count_input_attrib = count_attribs - 1; int count_rows = XmlConvert.ToInt32(rows_node.Attributes.GetNamedItem("Count").Value); for (int r = 0; r < count_rows; r++) { string Classifier_value; double[] double_value = new double[count_input_attrib]; string[] string_value = new string[count_input_attrib]; for (int a = 0; a < count_input_attrib; a++) { XmlNode value = rows_node.ChildNodes[r].SelectSingleNode(XmlConvert.EncodeName(input_Attribute[a].Name)); try { double_value[a] = XmlConvert.ToDouble(value.InnerXml); } catch { string_value[a] = value.InnerText; } } XmlNode outvalue = rows_node.ChildNodes[r].SelectSingleNode(XmlConvert.EncodeName(output_Attribute.Name)); Classifier_value = outvalue.InnerText; double doublevalue = double.NaN; if (output_Attribute.Type == SampleSet.AttributeInfo.TypeAttribute.real) { doublevalue = XmlConvert.ToDouble(Classifier_value); Classifier_value = ""; } SampleSet.RowSample temp_rows = new SampleSet.RowSample(double_value, string_value, doublevalue, Classifier_value); data_Row.Add(temp_rows); } temp_set = new SampleSet(opened_dataset, data_Row, input_Attribute, output_Attribute); if (temp_set.OutputAttribute.Type == SampleSet.AttributeInfo.TypeAttribute.nominate) { temp_set.Type = SampleSet.TypeSampleSet.Classifier; } else { temp_set.Type = SampleSet.TypeSampleSet.Approximation; } GC.Collect(); return(temp_set); }
public static void kliGenerate(TSAFuzzySystem Approximate, TypeTermFuncEnum typeFunc, double mayError) { var ssr = new List <SampleSet.RowSample>(); for (int index = 0; index < Approximate.LearnSamplesSet.DataRows.Count; index++) { var row = new SampleSet.RowSample(); List <double> InputAttributeValueLIST = new List <double>(); for (int i = 0; i < Approximate.AcceptedFeatures.Count(); i++) { double q = Convert.ToDouble(Approximate.LearnSamplesSet.DataRows[index].InputAttributeValue[i].ToString()); if (Approximate.AcceptedFeatures[i]) { InputAttributeValueLIST.Add(q); } row.InputAttributeValue = InputAttributeValueLIST.ToArray(); row.DoubleOutput = Approximate.LearnSamplesSet.DataRows[index].DoubleOutput; } ssr.Add(row); } List <SampleSet.AttributeInfo> ss = new List <SampleSet.AttributeInfo>(Approximate.LearnSamplesSet.InputAttributes); for (int i = (Approximate.AcceptedFeatures.Count() - 1); i >= 0; i--) { if (!Approximate.AcceptedFeatures[i]) { ss.RemoveAt(i); } } if ((Approximate.RulesDatabaseSet == null) || (Approximate.RulesDatabaseSet.Count == 0)) { Approximate.RulesDatabaseSet.Add(new KnowlegeBaseTSARules()); //wtf????????????? что за, если null придет то всё плохо плохо, а мы его пропускаем выше лол } var originalSimpleSet = new List <SampleSet.RowSample>(ssr); int ruleIndex = 0; while (originalSimpleSet.Count > 0) { //а тут нормировка особой роли не играет, хммм ну или почти не играет var maxPoint = originalSimpleSet.OrderByDescending(x => (Math.Sqrt(x.InputAttributeValue.Sum(y => Math.Pow(y, 2.0)) / x.InputAttributeValue.Count()))).First(); var iterClasterPoints = new List <SampleSet.RowSample>() { maxPoint }; var mnk = new MNK() { n = maxPoint.InputAttributeValue.Count() }; var P = new Matrix(new[] { new double[] { 0 } }); var B = new HyperVector(0, 0); mnk.mnkIter(iterClasterPoints.Last().InputAttributeValue.ToList(), iterClasterPoints.Last().DoubleOutput, ref P, ref B, true); var errorIter = errorsMnk(B, iterClasterPoints); while (errorIter < mayError) { originalSimpleSet.RemoveAll(x => iterClasterPoints.Contains(x)); if (originalSimpleSet.Count == 0) { break; } //это без нормировки // var nextPoint = // originalSimpleSet.OrderBy(x =>(Math.Sqrt(x.InputAttributeValue.Sum(y => Math.Pow(y -maxPoint.InputAttributeValue[x.InputAttributeValue.ToList().IndexOf(y)],2.0))/x.InputAttributeValue.Count()))).First(); //а это с нормировкой var nextPoint = originalSimpleSet.OrderBy(simple => Math.Sqrt(simple.InputAttributeValue.Select((inputValue, index) => Math.Pow((inputValue - maxPoint.InputAttributeValue[index]) / (ss[index].Scatter), 2.0)).Sum())).First(); mnk.mnkIter(nextPoint.InputAttributeValue.ToList(), nextPoint.DoubleOutput, ref P, ref B, false); errorIter = errorsMnk(B, new List <SampleSet.RowSample>(iterClasterPoints) { nextPoint }); if (errorIter < mayError) { iterClasterPoints.Add(nextPoint); } } var numbersRule = new List <int>(); int spear = 0; for (int i = 0; i < Approximate.AcceptedFeatures.Count(); i++)//.CountVars { if (!Approximate.AcceptedFeatures[i]) { spear++; continue; } var parametrs = new double[Term.CountParamsinSelectedTermType(typeFunc)]; parametrs[0] = iterClasterPoints.Sum(x => x.InputAttributeValue[i - spear]) / iterClasterPoints.Count; parametrs[1] = Math.Sqrt( iterClasterPoints.Sum(x => Math.Pow(x.InputAttributeValue[i - spear] - parametrs[0], 2.0)) * 2 / iterClasterPoints.Count); var temp_term = new Term(parametrs, typeFunc, i); Approximate.RulesDatabaseSet[0].TermsSet.Add(temp_term); numbersRule.Add(ruleIndex + i - spear); } ruleIndex += Approximate.AcceptedFeatures.Where(x => x == true).Count();//.CountVars var temp_rule = new TSARule(Approximate.RulesDatabaseSet[0].TermsSet, numbersRule.ToArray(), B.Elements[0].Elements[0], B.Elements.Skip(1).Select(x => x.Elements[0]).ToArray()); Approximate.RulesDatabaseSet[0].RulesDatabase.Add(temp_rule); } }