I am a complete Drools noob. I have been tasked with implementing a set rule which, in the absence of nested rules, seems very complex to me. The problem is as follows:
I have a fact called Person with attributes age, gender, income, height, weight and a few others. A person may be classified as level_1, level_2, ..., level_n based on the values of the attributes. For example,
when age < a and any value for other attributes then
classification = level_1.
when gender == female and any
value for other attributes then classification = level_2.
when age < a and gender == female and any value for other
attributes then classification = level_10.
...
So, in any rule any arbitrary combination of attributes may be used. Can anyone help me in expressing this?
The second part of the problem is that the levels are ordered and if a person satisfies more than 1 rule, the highest level is chosen. The only way I can think of of ordering levels is to order the rules themselves using salience. So rules resulting is higher levels will have higher salience. Is there a more elegant way of doing this?
I found a similar question here but that seems to deal with only 1 rule and the OP is probably more familiar with Drools than I am because I have not understood the solution. That talks about introducing a separate control fact but I didn't get how that works.
EDIT:
I would eventually have to create a template and supply the data using a csv. It probably does not matter for this problem, but, if it helps in any way...
The problem of assigning a discrete value to facts of a type based on attribute combinations is what I call "classification problem" (cf. Design Patterns in Production Systems). The simple approach is to write one rule for each discrete value, with constraints separating the attribute value cleanly from all other attribute sets. Note that statements such as
when attribute value age < a and any value for other attributes then classify as level 1
are misleading and must not be used to derive rules, because, evidently, this isn't a correct requirement since we have
when age < a && gender == female (...) then classify as level 10
and this contradicts the former requirement, correctly written as
when age < a && gender == male then classify as level 1
Likewise, the specification for level 2 must also be completed (and it'll become evident that there is no country for old men). With this approach, a classification based on i attributes with just 2 intervals each results in 2n rules. If the number of resulting levels is anywhere near this number, this approach is best. For implementation a decision table is suitable.
If major subsets of the n-dimensional space should fall into the same class, a more economical solution should be used. If, for instance, all women should fall into the same level, a rule selecting all women can be written and given highest precedence; the remaining rules will have to deal with n-1 dimenions. Thus, the simplest scenario would require just n rules, one for each dimension.
It is also possible to describe other intervals in an n-dimensional space, providing the full set of values for all dimensions with each interval. Using the appropriate subset of values for each interval avoids the necessity of ordering the rules (using salience) and ensures that really all cases are handled. Of course, a "fall-through" rule firing with low priority if the level hasn't been set is only prudent.
Related
I'm trying to solve a special case of the general constraint satisfaction problem in java.
Basically I have multiple variables, each one taking discrete values, and every variable is defined by the set of all possible values it has (think of it like an enumeration in Java, that would help).
I also have multiple groupements of conditions (think of a condition as a system of multiple equations on the variables, and they are all unary constraints: in other words of the form variable = possible value), the goal is to find if there's a set of variable values that satisfies at least one condition from each group (it might satisfy multiple ones from the same group). I will call this particular set a solution. What I'm looking for is all possible solutions.
The only Idea I have so far is basically brute force.
This is a concrete example so things are clearer:
s = {a,b,c}, v = {1,2,3}, n = {p,k,m}.
First condition group:
c1 = {s=a and v=2}, c2 = {s=b}.
Second condition group:
c1={n=p and v=2}.
Third condition group:
c1={s=a and n=p}, c2 = {s=c}.
In this situation, if we take (s=a,v=2,n=p): it satisfies the first condition of all three groups, and is, therefore, a solution to the problem.
(s=b,v=2,n=p) however is not a solution, because it doesn't verify any of the third group's conditions. In fact, the number of possible solutions here is 1.
Please note that the conditions within a group are not necessarily mutually exclusive.
Any insight into a possible way to go more efficiently than by brute force be it a data structure or an algorithm would be great since I will have to solve millions of such systems of quite the number of variables (thirty variables tops of around 15 values each, and a hundred such conditions tops).
Edit1: Data Constraints
If N is the number of variables each problem will have then N<=30.
If |V| is the maximum number of elements a variable V can have, then I know that Max(|Vi|)<=15 for every variable Vi in a problem.
I also know that if C is the number of constraints per problem, then C<100.
Lastly, I know that statistically speaking, the number of solutions for the problem will be small, meaning that most problems will have one single solution, and the likelihood of having more than 8 solutions is less than 99% of the time. For the sake of optimization, we can even assume that I'm never interested in any problem that has more than 10 solutions ever.
I have a List<String[]> of customer records in Java (from a database). I know from manually eyeballing the data that 25%+ are duplicates.
The duplicates are far from exact though. Sometimes they have different zips, but the same name and address. Other times the address is missing completely, etc...
After a day of research; I'm still really stumped as to how to even begin to attack this problem?
What are the "terms" that I should be googling for that describe this area (from a solve this in Java perspective)? And I don't suppose there is fuzzymatch.jar out there that makes it all just to easy?
I've done similar systems before for matching place information and people information. These are complex objects with many features and figuring out whether two different objects describe the same place or person is tricky. The way to do it is to break it down to the essentials.
Here's a few things that you can do:
0) If this is a oneoff, load the data into openrefine and fix things interactively. Maximum this solves your problem, minimum it will show you where your possible matches are.
1) there are several ways you can compare strings. Basically they differ in how reliable they are in producing negative and false matches. A negative match is when it matches when it shouldn't have. A positive match is when it should match and does. String equals will not produce negative matches but will miss a lot of potential matches due to slight variations. Levenstein with a small factor is a slightly better. Ngrams produce a lot of matches, but many of them will be false. There are a few more algorithms, take a look at e.g. the openrefine code to find various ways of comparing and clustering strings. Lucene implements a lot of this stuff in its analyzer framework but is a bit of a beast to work with if you are not very familiar with its design.
2) Separate the process of comparing stuff from the process of deciding whether you have a match. What I did in the past was qualify my comparisons, using a simple numeric score e.g. this field matched exactly (100) but that field was a partial match (75) and that field did not match at all. The resulting vector of qualified comparisons, e.g. (100, 75,0,25) can be compared to a reference vector that defines your perfect or partial match criteria. For example if first name, last name, and street match, the two records are the same regardless of the rest of the fields. Or if phonenumbers and last names match, that's a valid match too. You can encode such perfect matches as a vector and then simply compare it with your comparison vectors to determine whether it was a match, not a match, or a partial match. This is sort of a manual version of what machine learning does which is to extract vectors of features and then build up a probability model of which vectors mean what from reference data. Doing it manually, can work for simple problems.
3) Build up a reference data set with test cases that you know to match or not match and evaluate your algorithm against that reference set. That way you will know when you are improving things or making things worse when you tweak e.g. the factor that goes into Levinstein or whatever.
Jilles' answer is great and comes from experience. I've also had to work on cleaning up large messy tables and sadly didn't know much about my options at that time (I ended up using Excel and a lot of autofilters). Wish I'd known about OpenRefine.
But if you get to the point where you have to write custom code to do this, I want to make a suggestion as to how: The columns are always the same, right? For instance, the first String is always the key, the second is the First name, the sixth is the ZIP code, tenth is the fax number, etc.?
Assuming there's not an unreasonable number of fields, I would start with a custom Record type which has each DB field as member rather than a position in an array. Something like
class CustomerRow {
public final String id;
public final String firstName;
// ...
public CustomerRow(String[] data) {
id = data[0];
// ...
}
You could also include some validation code in the constructor, if you knew there to be garbage values you always want to filter out.
(Note that you're basically doing what an ORM would do automatically, but getting started with one would probably be more work than just writing the Record type.)
Then you'd implement some Comparator<CustomerRow>s which only look at particular fields, or define equality in fuzzy terms (there's where the edit distance algorithms would come in handy), or do special sorts.
Java uses a stable sort for objects, so to sort by e.g. name, then address, then key, you would just do each sort, but choose your comparators in the reverse order.
Also if you have access to the actual database, and it's a real relational database, I'd recommend doing some of your searches as queries where possible. And if you need to go back and forth between your Java objects and the DB, then using an ORM may end up being a good option.
Given two names that have variations in the way they are represented, is there any API/tool/algorithm that can give a score of how similar/different the names are?
Tim O' Reilly is one input and T Reilly is another input. The score returned between these two should be lesser than that got between Tim O' Reilly and Tim Reilly.
I am looking for such score calculation mechanisms. Few challenges that the algorithm should be capable of handling are:
1) The first names and last names could be swapped when a name is given as input
2) There might be initials in place of names
3) One of the names may not have the last name while the other may have both first name and last name.
... and so on which are common errors in name representations.
Two libraries including a handful of distance scores for name similarity are:
SimPack:
SecondString
No single method covers the cases that you mention but for 1) and 3) Feature and Set similarity measures (jaccard, tfidf for instance) work- For 2) besides soundex (as mentioned by #houman001) you may consider levensthein or jaro. Experiment with some examples of your use case and combine.
For the "API/tool/algorithm that can give a score of how similar/different the names are" part, I can give you a hint:
There are a few heuristic libraries that search engines use, but there is also this coding called soundex that computes a number out of a word. Words with the same soundex code are those that are slightly different. There are some Java implementations around as well.
On the points you mentioned later about names, look for contact management libraries/utilities and do some coding as these requirements are pretty specific.
I have responses from users to multiple choice questions, e.g. (roughly):
Married/Single
Male/Female
American/Latin American/European/Asian/African
What I want is to estimate similarity by aggregating all responses into a single field which can be compared across users in the database - rather than running queries against each column.
So, for example, some responses might look like:
Married-Female-American
Single-Female-European
But I don't want to store a massive text object to represent all of the possible concatenated responses since there are maybe 50 of them.
So, is there some way to represent a set of responses more concisely using a Java library method of some kind.
In other words, this method would take Married-Female-American and generate a code, say of abc while Single-Female-European would generate a code of, say, def?
This way if I want to find out if two users are Married-Female-Americans I can simply query a single column for the code abc.
Well, if it was a multiple choice question, you have choices enumerated. That is, numbered. Why not use 1-1-2 and 23-1-75 then? Even if you have 50 answers, it's still manageable.
Now if you happen to need the similarity, aggregating is the last thing you want. What you want is a simple array of ids of the answers given and a function defining a distance between two answer arrays. Do not use Strings, do not aggregate. Leave clean nice vectors, and all the ML libraries will be at your service.
To quote a Java ML library, try http://www.cs.waikato.ac.nz/~ml/weka/
Update: One more thing you may want to try is locality sensitive hashing. I don't think it's a good idea in your case, but your question looks like a request for it. Give it a try.
Do you have a finite number of options (multiple-choice seems to imply this)?
It is a common technique for performance to go from strings to a numerical data set, by essentially indexing the available strings. As long as you only need identity, this is perfect. Comparing an integer is much faster than comparing a string, and they usually take less memory, too.
A character is essentially an integer in 0-255, so you can of course use this.
So just define an alphabet:
a Married
b Single
c Male
d Female
e American
f Latin American
g European
h Asian
i African
You can in fact use this even when you have more than 256 words, if they are positional (and no single question has more than 256 choices). You would then use
a Q1: Married
b Q1: Single
a Q2: Male
b Q2: Female
a Q3: American
b Q3: Latin American
c Q3: European
d Q3: Asian
e Q3: African
Your examples would then be encoded as either (variant 1) ade and bdg or (variant 2) aba and bbc. The string should then have a fixed length of 50 (if you have 50 questions) and can be stored very effectively.
For comparing answers, just access the nth character of the string. Maybe your database allows for indexed substring queries, too. As you can see in above example, both strings agree only on the second character, just like the answers agreed.
I have a large (more than 100K objects) collection of Java objects like below.
public class User
{
//declared as public in this example for brevity...
public String first_name;
public String last_name;
public String ssn;
public String email;
public String blog_url;
...
}
Now, I need to search this list for an object where at least 3 (any 3 or more) attributes match those of the object being searched.
For example, if I am searching for an object that has
first_name="John",
last_name="Gault",
ssn="000-00-0000",
email="xyz#abc.com",
blog_url="http://myblog.wordpress.com"
The search should return me all objects where first_name,last_name and ssn match or those where last_name, ssn, email and blog_url match. Likewise, there could be other combinations.
I would like to know what's the best data-structure/algorithm to use in this case. For an exact search, I could have used a hashset or binary search with a custom comparator, but I am not sure what's the most efficient way to perform this type of search.
P.S.
This is not a homework exercise.
I am not sure if the question title is appropriate. Please feel free to edit.
EDIT
Some of you have pointed out the fact that I could use ssn (for ex.) for the search as it is more or less unique. The exmaple above is only illustrative of the real scenario. In reality, I have several objects where some of the fields are null so I would like to search on other fields.
I don't think that there are any specific data structures to make this kind of matching / comparison fast.
At the simple level of comparing two objects, you might implement a method like this:
public boolean closeEnough(User other) {
int count = 0;
count += firstName.equals(other.firstName) ? 1 : 0;
count += lastName.equals(other.lastName) ? 1 : 0;
count += ssn.equals(other.ssn) ? 1 : 0;
count += email.equals(other.email) ? 1 : 0;
...
return count >= 3;
}
To do a large scale search, the only way I can think of that would improve on a simple linear scan (using the method above) would be
create a series of multimaps for each of the properties,
populate them with the User records
Then each time you want to do a query:
query each multimap to get a set of possible candidates,
iterate all of the sets using closeEnough() to find the matches.
You could improve on this by treating the SSN, email address and blog URL properties differently to the name properties. Multiple users with matches on the first three properties should be a rare occurrence, compared with (say) finding multiple users called "John". The way that you have posed the question requires at least 1 of SSN, email or URL to match (to get 3 matches), so maybe you could not bother indexing the name properties at all.
Basically, search for results where ANY of the attributes matches the attribute in the query. This should narrow down the search space to quite a small number of entries. From those results, look for entries that match your criteria. This means you need to go through and count how many attributes match, if this is more than 3 then you've got a match. (This process is relatively slow and you wouldn't want to do it over your whole database.)
In this case, a potential optimisation would be to remove first_name and last_name from the initial filter phase, since they are much more likely to get you multiple results for a query than the other attributes (e.g. a lot of people called "John").
Since three attributes are required to match, removing two from the filter phase won't affect the final outcome.
Just a thought; if you are searching for someone with SSN, you should be able to narrow it down really quickly with that, since only one person is supposed to have one specific SSN.