def prepare_for_inference(self):
        """ Sets up the AndOrRegion nodes, but also trains the K means. """
        AndOrRegion.prepare_for_inference(self)

        # Train the K means
        self.kmeans_learners = []
        for widx in range(len(self.windows)):
            train_data = numpy.array(self.input_acts[widx], "float32")
            kfl = KmeansFeatureLearner(self.K, train_data, max_iter=self.max_iter)
            self.kmeans_learners.append(kfl)
 def train(self):
   """ Store a copy of every image in the iterator. """
   Experiment.train(self)
   start = time.time()
   
   num_images = len(self.image_iterator)
   print "Num images:", num_images
   assert num_images > 0
   
   gabor = self.gabor_region = GaborRegion((144, 192), rotations=3, 
                                           initial_wavelength=3, 
                                           num_wavelengths=2)
   
   kmeans = KmeansRegion(max(1,int(float(num_images) * self.compression)),
                         self.window_sampler)
   and_region = AndOrRegion(kmeans.image_shape, num_images)
   
   
   # Regions = [ GaborRegion, Kmeans, AndRegion, OrRegion (classifier) ]
   self.network = AndOrNetwork([gabor, kmeans, and_region])
   classifier = self.network.get_classifier()
   
   self.categories = []
   print "Extracting windows..."
   i = 0
   while self.image_iterator.has_next():
     image, category, img_idx = self.image_iterator.next()
     self.categories.append(category)
     gabor.do_inference(numpy.array(image))
     kmeans.do_learning()
     i += 1
     
   print "Training K-means..."
   kmeans.prepare_for_inference()
   
   # Send all of the images through the feature learner to save the image
   # activations.
   print "Storing classifier features..."
   self.image_iterator.reset()
   while self.image_iterator.has_next():
     image, category, img_idx = self.image_iterator.next()
     gabor.do_inference(numpy.array(image))
     kmeans.do_inference()
     cxns = kmeans.get_active_nodes()
     pos = and_region.create_node((0,0), cxns = cxns)
     classifier.create_node(category, pos)
   
   print "Preparing for inference..."
   self.network.prepare_for_inference(2)
    def __init__(self, K, window_sampler, max_iter=10):
        self.K = K
        self.max_iter = max_iter
        self.windows = window_sampler.sample()
        self.window_offsets = window_sampler.get_window_offsets()
        self.feature_shape = window_sampler.feature_shape
        self.window_sampler = window_sampler

        # This is for learning
        self.input_acts = [[] for i in range(len(self.windows))]

        last_offset = self.window_offsets[-1]
        image_shape = (last_offset[0] + 1, last_offset[1] + 1)
        estimated_num_nodes = numpy.prod(image_shape) * K

        AndOrRegion.__init__(self, image_shape, estimated_num_nodes)

        self.init_Knodes()