Skip to content

Commit 2cb6f20

Browse files
committed
Add KNN solution in .net
1 parent 15ef0ad commit 2cb6f20

File tree

7 files changed

+509
-0
lines changed

7 files changed

+509
-0
lines changed
Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
## Ignore Visual Studio temporary files, build results, and
2+
## files generated by popular Visual Studio add-ons.
3+
4+
# User-specific files
5+
*.suo
6+
*.userprefs
7+
*.user
8+
*.sln.docstates
9+
10+
# Build results
11+
[Dd]ebug/
12+
[Dd]ebugPublic/
13+
[Rr]elease/
14+
x64/
15+
build/
16+
bld/
17+
[Bb]in/
18+
[Oo]bj/
19+
20+
# Roslyn cache directories
21+
*.ide/
22+
23+
# MSTest test Results
24+
[Tt]est[Rr]esult*/
25+
[Bb]uild[Ll]og.*
26+
27+
#NUNIT
28+
*.VisualState.xml
29+
TestResult.xml
30+
31+
# Build Results of an ATL Project
32+
[Dd]ebugPS/
33+
[Rr]eleasePS/
34+
dlldata.c
35+
36+
*_i.c
37+
*_p.c
38+
*_i.h
39+
*.ilk
40+
*.meta
41+
*.obj
42+
*.pch
43+
*.pdb
44+
*.pgc
45+
*.pgd
46+
*.rsp
47+
*.sbr
48+
*.tlb
49+
*.tli
50+
*.tlh
51+
*.tmp
52+
*.tmp_proj
53+
*.log
54+
*.vspscc
55+
*.vssscc
56+
.builds
57+
*.pidb
58+
*.svclog
59+
*.scc
60+
61+
# Chutzpah Test files
62+
_Chutzpah*
63+
64+
# Visual C++ cache files
65+
ipch/
66+
*.aps
67+
*.ncb
68+
*.opensdf
69+
*.sdf
70+
*.cachefile
71+
72+
# Visual Studio profiler
73+
*.psess
74+
*.vsp
75+
*.vspx
76+
77+
# TFS 2012 Local Workspace
78+
$tf/
79+
80+
# Guidance Automation Toolkit
81+
*.gpState
82+
83+
# ReSharper is a .NET coding add-in
84+
_ReSharper*/
85+
*.[Rr]e[Ss]harper
86+
*.DotSettings.user
87+
88+
# JustCode is a .NET coding addin-in
89+
.JustCode
90+
91+
# TeamCity is a build add-in
92+
_TeamCity*
93+
94+
# DotCover is a Code Coverage Tool
95+
*.dotCover
96+
97+
# NCrunch
98+
_NCrunch_*
99+
.*crunch*.local.xml
100+
101+
# MightyMoose
102+
*.mm.*
103+
AutoTest.Net/
104+
105+
# Web workbench (sass)
106+
.sass-cache/
107+
108+
# Installshield output folder
109+
[Ee]xpress/
110+
111+
# DocProject is a documentation generator add-in
112+
DocProject/buildhelp/
113+
DocProject/Help/*.HxT
114+
DocProject/Help/*.HxC
115+
DocProject/Help/*.hhc
116+
DocProject/Help/*.hhk
117+
DocProject/Help/*.hhp
118+
DocProject/Help/Html2
119+
DocProject/Help/html
120+
121+
# Click-Once directory
122+
publish/
123+
124+
# Publish Web Output
125+
*.[Pp]ublish.xml
126+
*.azurePubxml
127+
## TODO: Comment the next line if you want to checkin your
128+
## web deploy settings but do note that will include unencrypted
129+
## passwords
130+
#*.pubxml
131+
132+
# NuGet Packages Directory
133+
packages/*
134+
## TODO: If the tool you use requires repositories.config
135+
## uncomment the next line
136+
#!packages/repositories.config
137+
138+
# Enable "build/" folder in the NuGet Packages folder since
139+
# NuGet packages use it for MSBuild targets.
140+
# This line needs to be after the ignore of the build folder
141+
# (and the packages folder if the line above has been uncommented)
142+
!packages/build/
143+
144+
# Windows Azure Build Output
145+
csx/
146+
*.build.csdef
147+
148+
# Windows Store app package directory
149+
AppPackages/
150+
151+
# Others
152+
sql/
153+
*.Cache
154+
ClientBin/
155+
[Ss]tyle[Cc]op.*
156+
~$*
157+
*~
158+
*.dbmdl
159+
*.dbproj.schemaview
160+
*.pfx
161+
*.publishsettings
162+
node_modules/
163+
164+
# RIA/Silverlight projects
165+
Generated_Code/
166+
167+
# Backup & report files from converting an old project file
168+
# to a newer Visual Studio version. Backup files are not needed,
169+
# because we have git ;-)
170+
_UpgradeReport_Files/
171+
Backup*/
172+
UpgradeLog*.XML
173+
UpgradeLog*.htm
174+
175+
# SQL Server files
176+
*.mdf
177+
*.ldf
178+
179+
# Business Intelligence projects
180+
*.rdl.data
181+
*.bim.layout
182+
*.bim_*.settings
183+
184+
# Microsoft Fakes
185+
FakesAssemblies/
186+
187+
# LightSwitch generated files
188+
GeneratedArtifacts/
189+
_Pvt_Extensions/
190+
ModelManifest.xml
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio 2012
4+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KNN", "KNN\KNN.csproj", "{89931ED6-8476-4C07-84D8-B728F9A7DCEB}"
5+
EndProject
6+
Global
7+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
8+
Debug|x86 = Debug|x86
9+
Release|x86 = Release|x86
10+
EndGlobalSection
11+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
12+
{89931ED6-8476-4C07-84D8-B728F9A7DCEB}.Debug|x86.ActiveCfg = Debug|x86
13+
{89931ED6-8476-4C07-84D8-B728F9A7DCEB}.Debug|x86.Build.0 = Debug|x86
14+
{89931ED6-8476-4C07-84D8-B728F9A7DCEB}.Release|x86.ActiveCfg = Release|x86
15+
{89931ED6-8476-4C07-84D8-B728F9A7DCEB}.Release|x86.Build.0 = Release|x86
16+
EndGlobalSection
17+
EndGlobal
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3+
<PropertyGroup>
4+
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
5+
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
6+
<ProjectGuid>{89931ED6-8476-4C07-84D8-B728F9A7DCEB}</ProjectGuid>
7+
<OutputType>Exe</OutputType>
8+
<RootNamespace>KNN</RootNamespace>
9+
<AssemblyName>KNN</AssemblyName>
10+
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
11+
</PropertyGroup>
12+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
13+
<DebugSymbols>true</DebugSymbols>
14+
<DebugType>full</DebugType>
15+
<Optimize>false</Optimize>
16+
<OutputPath>bin\Debug</OutputPath>
17+
<DefineConstants>DEBUG;</DefineConstants>
18+
<ErrorReport>prompt</ErrorReport>
19+
<WarningLevel>4</WarningLevel>
20+
<Externalconsole>true</Externalconsole>
21+
<PlatformTarget>x86</PlatformTarget>
22+
</PropertyGroup>
23+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
24+
<DebugType>full</DebugType>
25+
<Optimize>true</Optimize>
26+
<OutputPath>bin\Release</OutputPath>
27+
<ErrorReport>prompt</ErrorReport>
28+
<WarningLevel>4</WarningLevel>
29+
<Externalconsole>true</Externalconsole>
30+
<PlatformTarget>x86</PlatformTarget>
31+
</PropertyGroup>
32+
<ItemGroup>
33+
<Reference Include="System" />
34+
</ItemGroup>
35+
<ItemGroup>
36+
<Compile Include="Program.cs" />
37+
<Compile Include="Properties\AssemblyInfo.cs" />
38+
<Compile Include="Specimen.cs" />
39+
</ItemGroup>
40+
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
41+
<ItemGroup>
42+
<Content Include="iris.data">
43+
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
44+
</Content>
45+
</ItemGroup>
46+
</Project>
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
using System;
2+
using System.IO;
3+
using System.Linq;
4+
using System.Collections.Generic;
5+
6+
namespace KNN
7+
{
8+
class MainClass
9+
{
10+
const int k = 3;
11+
const int testingFraction = 4;
12+
13+
public static void Main(string[] args) {
14+
var specimens = File.ReadAllLines("iris.data")
15+
.Select((l, i) => new { Data=ParseLine(l), Index = i})
16+
.ToList();
17+
18+
var trainingSet = specimens.Where(x => x.Index % testingFraction != 0).Select(x => x.Data).ToList();
19+
var testingSet = specimens.Where(x => x.Index % testingFraction == 0).Select(x => x.Data).ToList();
20+
21+
var correct = 0;
22+
foreach (var item in testingSet) {
23+
var predicted = Majority(FindKNearest(item, trainingSet));
24+
Console.WriteLine("{0} read from file was predicted to be {1}", item.Class, predicted);
25+
if (predicted == item.Class)
26+
correct++;
27+
}
28+
Console.WriteLine("Accuracy: {0:0.00} %", ((double)correct * 100.0d / (double)testingSet.Count));
29+
}
30+
31+
static Specimen ParseLine(string line) {
32+
var data = line.Split(',');
33+
return new Specimen {
34+
SepalLength = double.Parse(data[0]),
35+
SepalWidth = double.Parse(data[1]),
36+
PetalLength = double.Parse(data[2]),
37+
PetalWidth = double.Parse(data[3]),
38+
Class = data[4]
39+
};
40+
}
41+
42+
static double Distance (Specimen a, Specimen b) {
43+
var d1 = Math.Pow(a.SepalLength - b.SepalLength, 2);
44+
var d2 = Math.Pow(a.SepalWidth - b.SepalWidth, 2);
45+
var d3 = Math.Pow(a.PetalLength - b.PetalLength, 2);
46+
var d4 = Math.Pow(a.PetalWidth - b.PetalWidth, 2);
47+
48+
return d1 + d2 + d3 + d4;
49+
}
50+
51+
static List<Specimen> FindKNearest (Specimen input, IEnumerable<Specimen> trainingSet) {
52+
return trainingSet.Select(t => new { Item = t, Dist = Distance(input, t)})
53+
.OrderBy(d => d.Dist)
54+
.Take(k)
55+
.Select(x => x.Item)
56+
.ToList();
57+
}
58+
59+
static string Majority (List<Specimen> nearest) {
60+
var majorityGroup = nearest.GroupBy(x => x.Class)
61+
.OrderByDescending(g => g.Count())
62+
.First();
63+
var majorityClass = majorityGroup
64+
.First()
65+
.Class;
66+
return majorityClass;
67+
}
68+
}
69+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using System.Reflection;
2+
using System.Runtime.CompilerServices;
3+
4+
// Information about this assembly is defined by the following attributes.
5+
// Change them to the values specific to your project.
6+
7+
[assembly: AssemblyTitle("KNN")]
8+
[assembly: AssemblyDescription("")]
9+
[assembly: AssemblyConfiguration("")]
10+
[assembly: AssemblyCompany("")]
11+
[assembly: AssemblyProduct("")]
12+
[assembly: AssemblyCopyright("pav")]
13+
[assembly: AssemblyTrademark("")]
14+
[assembly: AssemblyCulture("")]
15+
16+
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
17+
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
18+
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
19+
20+
[assembly: AssemblyVersion("1.0.*")]
21+
22+
// The following attributes are used to specify the signing key for the assembly,
23+
// if desired. See the Mono documentation for more information about signing.
24+
25+
//[assembly: AssemblyDelaySign(false)]
26+
//[assembly: AssemblyKeyFile("")]
27+
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
namespace KNN
2+
{
3+
class Specimen {
4+
public double SepalLength { get; set; }
5+
public double SepalWidth { get; set; }
6+
public double PetalLength { get; set; }
7+
public double PetalWidth { get; set; }
8+
public string Class { get; set; }
9+
}
10+
}

0 commit comments

Comments
 (0)