Skip to content

Instantly share code, notes, and snippets.

@grej
Created September 6, 2012 02:39
Show Gist options
  • Save grej/3650170 to your computer and use it in GitHub Desktop.
Save grej/3650170 to your computer and use it in GitHub Desktop.
Rank order centroid implementation for Python
#-------------------------------------------------------------------------------
# Name: Rank Order Centroid
# Purpose: Generate rank order centroid weights
#
# Author: Greg Jennings
#
# Created: 5 Sep 2012
# Copyright: (c) Greg 2012
# Licence: MIT
#-------------------------------------------------------------------------------
import numpy #requires numpy
class RankOrderCentroid():
def __init__(self):
self.__weight_array_dict = {} # cache weight vectors to avoid recalculation
def __vector_centroid(self,vec):
veclen = len(vec)
temp_weight_array = numpy.array(xrange(1,veclen+1))
inverse_vec = 1./temp_weight_array
tempsum = 0
weight_array = []
for idx, elem in enumerate(reversed(inverse_vec)):
tempsum += elem
weight_array.append(tempsum/veclen)
self.__weight_array_dict[veclen] = weight_array[::-1] #reverse array
def get_ROC_weight(self, array_length, array_rank):
"""INT array_length: length of vector (number of items)
INT array_rank: rank of item in the item vector with 1 being highest"""
if array_length in self.__weight_array_dict:
return self.__weight_array_dict[array_length][array_rank-1]
else:
self.__vector_centroid(numpy.array(xrange(1,array_length+1)))
return self.get_ROC_weight(array_length,array_rank)
def get_ROC_array(self, array_length):
"""Returns entire ROC weight array for n items
INT array_length: length of vector (number of items)"""
if array_length in self.__weight_array_dict:
return self.__weight_array_dict[array_length]
else:
self.__vector_centroid(numpy.array(xrange(1,array_length+1)))
return self.get_ROC_array(array_length)
#END CLASS
#tests / usage
roc = RankOrderCentroid() #instantiate
print roc.get_ROC_weight(3,2) # 0.2778
print roc.get_ROC_array(4) # [0.521, 0.271, 0.145, 0.063]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment