Skip to content

Instantly share code, notes, and snippets.

@TakuTsuzuki
Last active August 29, 2015 14:25
Show Gist options
  • Save TakuTsuzuki/89bcd8f08f840f2b9195 to your computer and use it in GitHub Desktop.
Save TakuTsuzuki/89bcd8f08f840f2b9195 to your computer and use it in GitHub Desktop.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn import datasets
import brica1
# PCA Component Definition
class PCAComponent(brica1.Component):
def __init__(self,n_in,dimention=3):
super(PCAComponent, self).__init__()
self.pca = PCA(n_components=dimention)
self.make_in_port("in0",n_in)
self.make_out_port("out0",dimention)
def fire(self):
x = self.inputs["in0"]
z = self.pca.transform(x)
self.results["out0"] = z
def fit(self,dataset):
return self.pca.fit_transform(dataset)
# KMeans Component Definition
class KMeansComponent(brica1.Component):
def __init__(self, n_in,n_clusters=3 ):
super(KMeansComponent, self).__init__()
self.kmeans = KMeans(n_clusters = n_clusters )
self.make_in_port("in0", n_in)
self.make_out_port("out0", 1)
def fire(self):
x = self.inputs["in0"]
z = self.kmeans.predict(x)
self.results["out0"] = z
def fit(self, dataset):
self.kmeans.fit(dataset)
# Load iris dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target
# Setup data feeder component
feeder = brica1.ConstantComponent()
feeder.make_out_port("out0", len(X[0]))
# Setup PCA component
dim = 3
pca = PCAComponent(n_in=len(X[0]), dimention = dim)
Z = pca.fit(X)
# Setup KMeans Component
kmeans = KMeansComponent(n_in= dim)
kmeans.fit(Z)
# Connect the components
brica1.connect((feeder,"out0"),(pca,"in0"))
brica1.connect((pca,"out0"),(kmeans,"in0"))
# Add components to the module
mod = brica1.Module()
mod.add_component("feeder",feeder)
mod.add_component("pca",pca)
mod.add_component("kmeans",kmeans)
# Setup scheduler and agent
s = brica1.VirtualTimeSyncScheduler()
a = brica1.Agent(s)
a.add_submodule("mod",mod)
# Test the pca and kmeans clustering
kmeans_results=[]
for i in xrange(len(X)):
feeder.set_state("out0",X[i])
a.step()
a.step()
kmeans_results.append(kmeans.get_out_port("out0").buffer[0])
hoge =[]
for e in kmeans_results:
if e ==1:
hoge.append(0)
elif e ==2:
hoge.append(1)
elif e ==0:
hoge.append(2)
for i in xrange(len(X)):
print "Label: {}\tKMeans_Result: {}\tTrue or Faluse: {}".format(y[i], hoge[i], y[i]==hoge[i])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment