473,769 Members | 6,404 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generic logic/conditional class or library for classification of data

This topic is difficult to describe in one subject sentence...

Has anyone come across the application of the simple statement "if
(object1's attributes meet some conditions) then (set object2's
attributes to certain outcomes)", where "object1" and "object2" are
generic objects, and the "conditions " and "outcomes" are dynamic run-
time inputs? Typically, logic code for any application out there is
hard-coded. I have been working with Python for a year, and its
flexibility is nothing short of amazing. Wouldn't it be possible to
have a class or library that can do this sort of dynamic logic?

The main application of such code would be for classification
algorithms which, based on the attributes of a given object, can
classify the object into a scheme. In general, conditions for
classification can be complex, sometimes involving a collection of
"and", "or", "not" clauses. The simplest outcome would involve simply
setting a few attributes of the output object to given values if the
input condition is met. So each such "if-then" clause can be viewed as
a rule that is custom-defined at runtime.

As a very basic example, consider a set of uncategorized objects that
have text descriptions associated with them. The objects are some type
of tangible product, e.g., books. So the input object has a
Description attribute, and the output object (a categorized book)
would have some attributes like Discipline, Target audience, etc.
Let's say that one such rule is "if ( 'description' contains
'algebra') then ('discipline' = 'math', 'target' = 'student') ". Keep
in mind that all these attribute names and their values are not known
at design time.

Is there one obvious way to do this in Python?
Perhaps this is more along the lines of data mining methods?
Is there a library with this sort of functionality out there already?

Any help will be appreciated.

Apr 1 '07 #1
4 1882
On Sat, 31 Mar 2007 21:54:46 -0700, Basilisk96 wrote:
As a very basic example, consider a set of uncategorized objects that
have text descriptions associated with them. The objects are some type
of tangible product, e.g., books. So the input object has a
Description attribute, and the output object (a categorized book)
would have some attributes like Discipline, Target audience, etc.
Let's say that one such rule is "if ( 'description' contains
'algebra') then ('discipline' = 'math', 'target' = 'student')". Keep
in mind that all these attribute names and their values are not known at
design time.
Easy-peasy.

rules = {'algebra': {'discipline': 'math', 'target': 'student'},
'python': {'section': 'programming', 'os': 'linux, windows'}}

class Input_Book(obje ct):
def __init__(self, description):
self.descriptio n = description

class Output_Book(obj ect):
def __repr__(self):
return "Book - %s" % self.__dict__

def process_book(bo ok):
out = Output_Book()
for desc in rules:
if desc in book.descriptio n:
attributes = rules[desc]
for attr in attributes:
setattr(out, attr, attributes[attr])
return out

book1 = Input_Book('pyt hon for cheese-makers')
book2 = Input_Book('tea ching algebra in haikus')
book3 = Input_Book('how to teach algebra to python programmers')

>>process_book( book1)
Book - {'section': 'programming', 'os': 'linux, windows'}
>>process_book( book2)
Book - {'discipline': 'math', 'target': 'student'}
>>process_book( book3)
Book - {'discipline': 'math', 'section': 'programming',
'os': 'linux, windows', 'target': 'student'}
I've made some simplifying assumptions: the input object always has a
description attribute. Also the behaviour when two or more rules set the
same attribute is left undefined. If you want more complex rules you can
follow the same technique, except you'll need a set of meta-rules to
decide what rules to follow.

But having said that, I STRONGLY recommend that you don't follow that
approach of creating variable instance attributes at runtime. The reason
is, it's quite hard for you to know what to do with an Output_Book once
you've got it. You'll probably end up filling your code with horrible
stuff like this:

if hasattr(book, 'target'):
do_something_wi th(book.target)
elif hasattr(book, 'discipline'):
do_something_wi th(book.discipl ine)
elif ... # etc.
Replacing the hasattr() checks with try...except blocks isn't any
less icky.

Creating instance attributes at runtime has its place; I just don't think
this is it.

Instead, I suggest you encapsulate the variable parts of the book
attributes into a single attribute:

class Output_Book(obj ect):
def __init__(self, name, data):
self.name = name # common attribute(s)
self.data = data # variable attributes
Then, instead of setting each variable attribute individually with
setattr(), simply collect all of them in a dict and save them in data:

def process_book(bo ok):
data = {}
for desc in rules:
if desc in book.descriptio n:
data.update(rul es[desc])
return Output_Book(boo k.name, data)
Now you can do this:

outbook = process_book(bo ok)
# handle the common attributes that are always there
print outbook.name
# handle the variable attributes
print "Stock = %s" % output.data.set default('status ', 0)
print "discipline = %s" % output.data.get ('discipline', 'none')
# handle all the variable attributes
for key, value in output.data.ite ritems():
do_something_wi th(key, value)
Any time you have to deal with variable attributes that may or may not be
there, you have to use more complex code, but you can minimize the
complexity by keeping the variable attributes separate from the common
attributes.
--
Steven.

Apr 1 '07 #2

On Mar 31, 2007, at 11:54 PM, Basilisk96 wrote:
This topic is difficult to describe in one subject sentence...

Has anyone come across the application of the simple statement "if
(object1's attributes meet some conditions) then (set object2's
attributes to certain outcomes)", where "object1" and "object2" are
generic objects, and the "conditions " and "outcomes" are dynamic run-
time inputs? Typically, logic code for any application out there is
hard-coded. I have been working with Python for a year, and its
flexibility is nothing short of amazing. Wouldn't it be possible to
have a class or library that can do this sort of dynamic logic?

The main application of such code would be for classification
algorithms which, based on the attributes of a given object, can
classify the object into a scheme. In general, conditions for
classification can be complex, sometimes involving a collection of
"and", "or", "not" clauses. The simplest outcome would involve simply
setting a few attributes of the output object to given values if the
input condition is met. So each such "if-then" clause can be viewed as
a rule that is custom-defined at runtime.

As a very basic example, consider a set of uncategorized objects that
have text descriptions associated with them. The objects are some type
of tangible product, e.g., books. So the input object has a
Description attribute, and the output object (a categorized book)
would have some attributes like Discipline, Target audience, etc.
Let's say that one such rule is "if ( 'description' contains
'algebra') then ('discipline' = 'math', 'target' = 'student') ". Keep
in mind that all these attribute names and their values are not known
at design time.

Is there one obvious way to do this in Python?
Perhaps this is more along the lines of data mining methods?
Is there a library with this sort of functionality out there already?

Any help will be appreciated.
You may be interested in http://divmod.org/trac/wiki/DivmodReverend
-- it is a general purpose Bayesian classifier written in python.

hope this helps,
Michael
Apr 1 '07 #3
Thanks for the help, guys.
Dictionaries to the rescue!

Steven, it's certainly true that runtime creation of attributes does
not fit well here. At some point, an application needs to come out of
generics and deal with logic that is specific to the problem. The
example I gave was classification of books, which is relatively easy
to understand. The particular app I'm working with deals with
specialty piping valves, where the list of rules grows complicated
fairly quickly.

So, having said that "attributes are not known at design time", it
seems that dictionaries are best for the generic core functionality:
it's easy to iterate over arbitrary "key, value" pairs without
hiccups. I can even reference a custom function by a key, and call it
during the iteration to do what's necessary. The input/output
dictionaries would dictate that behavior, so that would be the
implementation-specific stuff. Easy enough, and the core functionality
remains generic enough for re-use.

Michael, I looked at the sample snippets at that link, and I'll have
to try it out. Thanks!

Apr 3 '07 #4
On Apr 3, 5:43 am, "Basilisk96 " <basilis...@gma il.comwrote:
Thanks for the help, guys.
Dictionaries to the rescue!

Steven, it's certainly true that runtime creation of attributes does
not fit well here. At some point, an application needs to come out of
generics and deal with logic that is specific to the problem. The
example I gave was classification of books, which is relatively easy
to understand. The particular app I'm working with deals with
specialty piping valves, where the list of rules grows complicated
fairly quickly.

So, having said that "attributes are not known at design time", it
seems that dictionaries are best for the generic core functionality:
it's easy to iterate over arbitrary "key, value" pairs without
hiccups. I can even reference a custom function by a key, and call it
during the iteration to do what's necessary. The input/output
dictionaries would dictate that behavior, so that would be the
implementation-specific stuff. Easy enough, and the core functionality
remains generic enough for re-use.

Michael, I looked at the sample snippets at that link, and I'll have
to try it out. Thanks!
Hello,

If your rules become more complicated and maybe increase in number
significantly,
it might be an idea to switch to a rule-based system. Take a look at
CLIPS and the
associated Python bindings:

http://www.ghg.net/clips/CLIPS.html
http://pyclips.sourceforge.net/

Kind regards,

Marco

Apr 3 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1980
by: Edward Diener | last post by:
Version 2.0 of the Python database API was written over 5 years ago, in 1999. While it has been used successfully by many implementations, there is no generic access into the data dictionary of relational databases except at the table column level. I am working on some Python which would hopefully give me a form of generic access to more common data dictionary functionality such as indices, constraints etc. but no such functionality...
49
2894
by: Steven Bethard | last post by:
I promised I'd put together a PEP for a 'generic object' data type for Python 2.5 that allows one to replace __getitem__ style access with dotted-attribute style access (without declaring another class). Any comments would be appreciated! Thanks! Steve ----------------------------------------------------------------------
6
4430
by: Joshua Weston | last post by:
I am new to C++ and I am very interested in becoming proficient. This post is two-fold. One, I am having problems with this small test program. It is meant to allow user input to control a "@" character as it moves around the screen. I understand that it does not have error checking. The problem I am having is that when I hit the arrow key it moves TWO spaces instead of one. As I understand it, the FlushConsoleInputBuffer(handle) should...
2
1473
by: Chakravarthy | last post by:
Given an XML stream as below, is there any possibility to convert the same into any treditional class style with . (dots) as seperator of the nodes of the xml file... for instance bank.code.tostring() should reslut me "5070" and bank.description.tostring() should result "ICICI - Bangalore"
3
3557
by: markww | last post by:
Hi, I have a wrapper around some 3rd party database library function. The pseudo code looks like the following - it is meant to open a table in a database, extract values from a table, then copy it into my own user defined structures. Since the process of opening and retrieving data from the database is exactly the same for all struct types, and the only part that's different is how the data is copied into the diff structs, I was...
3
11774
by: fstorck | last post by:
Hi, I'm kind of stuck with an serializing / deserializing problem using a generic dictionary holding references to various generic types. It goes as follows: <code> class MyBase : IXmlSerializable {
7
7103
by: Abhishek | last post by:
Hi I am using a generic list in my program to have a list of objects stored. I want to compare all the objects in this list with object of another class and find all the objects which meet the criteria. To make it more specific I have a class Employee and a class Salary which look like Employee { Name
10
1939
by: Egghead | last post by:
Hi all, Can someone kindly enough point me to some situations that we shall or "must" use Generic Class? I can foresee the Generic Method is powerful, but I can not find a single situation that I will need the Generic Class, given there are so many other options. -- cheers,
10
2957
by: fig000 | last post by:
HI, I'm new to generics. I've written a simple class to which I'm passing a generic list. I'm able to pass the list and even pass the type of the list so I can use it to traverse it. It's a generic list of business objects. I'm able to see that the type is the correct one in the debugger. However when I try to traverse the list using the type I can't compile. The same type variable I've verified as being passed
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10045
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9993
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7406
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3958
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.