blog.Ring.idv.tw

KNN(K-nearest neighbor) algorithm in AS3

KNN(K-nearest neighbor) algorithm in AS3


最近本來想打算藉由Flash CS5的發佈來開發iPhone應用程式,無奈Apple的大刀一揮~ 導致就算用Flash CS5開發出來的iPhone程式也通過不了上架的審核... 一下子打亂了我的一些計劃... 不過還是要練習練習AS3,而本文主要就是用AS3來實現KNN的基本概念,簡單來說KNN是一種可以藉由訓練資料來推測可能結果的演算法(Supervised learning),詳細的程式細節如下:

(本範例初始化的K值為5,玩玩看吧>>knn.swf)

KNN.as

package
{
	import flash.display.*;
	import flash.events.*;
	import flash.geom.Point;
	import flash.utils.*;
	
	public class KNN extends MovieClip
	{
		private var k:uint = 5;
	
		public function KNN()
		{
			stage.addEventListener(MouseEvent.MOUSE_UP,put);
			init();
		}
		public function put(m:MouseEvent):void
		{
			var c:Circle = null;			
			var num:uint = this.numChildren;
			trace(num);
			var k_dict:Dictionary = new Dictionary(true);
			var k_arr:Array = new Array();
			for(var i = 0 ; i < num ; i++)
			{
				var cc:Circle = this.getChildAt(i) as Circle;
				var dist = Point.distance(new Point(stage.mouseX,stage.mouseY),new Point(cc.x,cc.y));
				k_dict[dist] = i;
				k_arr.push(dist);
			}
			k_arr.sort(Array.NUMERIC);
			var blue = 0;
			var red = 0;
			for(var j = 0 ; j < k ; j++)
			{
				var nid = k_dict[k_arr[j]];
				var c2:Circle = this.getChildAt(nid) as Circle;
				var cor:uint = c2.getColor();
				trace(nid+" "+k_arr[j]+" "+cor);
				if(cor == 0x0000FF)
					blue++;
				else
					red++;
			}
			if(blue > red)
				c = new Circle(0x0000FF);				
			else
				c = new Circle(0xFF0000);				
			
			c.x = stage.mouseX;
			c.y = stage.mouseY;
			addChild(c);
		}
		public function init():void
		{
			for(var i = 0 ; i < 10 ; i++)
			{
				var c:Circle = new Circle(0xff0000);				
				c.x = Math.random()*500;
				c.y = Math.random()*500;
				addChild(c);				
			}
			for(i = 0 ; i < 10 ; i++)
			{
				var c2:Circle = new Circle(0x0000FF);				
				c2.x = Math.random()*500;
				c2.y = Math.random()*500;
				addChild(c2);
			}
		}
	}
}

Circle.as

package
{
	import flash.display.*;
	
	public class Circle extends Sprite
	{
		private var color:uint = 0;
		
		public function Circle(c:uint)
		{
			this.color = c;
			this.graphics.lineStyle(5);
			this.graphics.beginFill(this.color);
			this.graphics.drawCircle(0,0,20);
			this.graphics.endFill();
		}
		public function getColor():uint
		{
			return this.color;
		}
	}
}

相關資源

KNN演算法

KNN演算法 (更正篇)

2010-04-19 23:14:37

2 comments on "KNN(K-nearest neighbor) algorithm in AS3"

  1. 1. hachu 說:

    寫得程式挺厲害的!
    這是用什麼程式語言寫的嗎?
    因為看起來好像是JAVA寫的

    2010-05-07 14:06:55

  2. 2. Shen 說:

    ActionScript 3 寫的,它和Java本來就很相似 :D

    2010-05-07 14:30:48

Leave a Comment

Copyright (C) Ching-Shen Chen. All rights reserved.

::: 搜尋 :::

::: 分類 :::

::: Ads :::

::: 最新文章 :::

::: 最新回應 :::

::: 訂閱 :::

Atom feed
Atom Comment

::: 人氣指數 :::

今日人氣:599

累積人氣:3194424


::: 線上人數 :::

counter