File: CombinedStringDistanceLearner.java

package info (click to toggle)
libsecondstring-java 0.1~dfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 764 kB
  • sloc: java: 9,592; xml: 114; makefile: 6
file content (356 lines) | stat: -rwxr-xr-x 12,943 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package com.wcohen.ss;

import com.wcohen.ss.api.*;
import java.util.*;

/**
 * Abstract StringDistanceLearner class which combines results of a number of
 * inner distance metrics, learned by a number of inner distance learners.
 */

public abstract class CombinedStringDistanceLearner implements StringDistanceLearner
{
	protected StringDistanceLearner[] innerLearners;
	protected String delim;

	// use some reasonable defaults
	public CombinedStringDistanceLearner() {
		innerLearners = 
			new StringDistanceLearner[] { 
				new JaroWinkler()
				,new ScaledLevenstein()
				,new Jaccard()
				,new TFIDF()
				,new JaroWinklerTFIDF() 
			};
		delim = null;
	}

	public CombinedStringDistanceLearner(StringDistanceLearner[] innerLearners,String delim) { 
		this.innerLearners = innerLearners;
		this.delim = delim;
	}

	//
	// stuff for subclasses to implement
	//

	/** Pass an iterator over unlabeled string wrappers to the score-combination learner,
	 * just in case that's useful.
	 */
	abstract protected void comboSetStringWrapperPool(Iterator i); // on unlabeled StringWrapper's

	/** Set up a pool of (possibly unlabeled) instance distances, for the learner
	 * to make queries from.
	 */
	abstract protected void comboSetDistanceInstancePool(Iterator i); // on list of MyMultiDistanceInstance's

	/**
	 * Poll the routine that learns to combine inner distance scores to see if it
	 * wants to make more queries.
	 */
	abstract protected boolean comboHasNextQuery();  // active learning

	/** Get the next query from the score-combination learner.
	 */
	abstract protected DistanceInstance comboNextQuery(); // active learning

	/** Pass a labeled example to the score-combination learner.
	 */
	abstract protected void comboAddExample(DistanceInstance di); // ac

	/** Get the final string distance, which will be based on the distances learned by the
	 * inner learners, as well as the combination scheme learned by comboSetAnswer, comboTrain,
	 * and etc.
	 */
	abstract public StringDistance getDistance();

	//
	// routines for delegating
	//

	/** Pass the training data along to the inner learners. */
	public void setStringWrapperPool(StringWrapperIterator it) 
	{ 
		// train i-th learner on i-th field of string wrapper
		List buffer = asMultiStringWrapperList(it);
		if (buffer.size()==0) throw new IllegalStateException("need some unlabeled strings");
		MultiStringWrapper prototype = (MultiStringWrapper)buffer.get(0);
		for (int i=0; i<prototype.size(); i++) {
			int j = prototype.getDistanceLearnerIndex(i);
			innerLearners[j].setStringWrapperPool( new JthStringWrapperValueIterator( j, buffer.iterator() ));
		}
		comboSetStringWrapperPool( buffer.iterator() );
	}

	/** Pass the training data along to the inner learners. */
	public void setDistanceInstancePool(DistanceInstanceIterator it) 
	{
		// need to save out the i-th field, if it's been prepared.
		List buffer = asMultiDistanceInstanceList(it);
		if (buffer.size()==0) return;
		MyMultiDistanceInstance instance = (MyMultiDistanceInstance)buffer.get(0);
		MultiStringWrapper prototype = asMultiStringWrapper( instance.getA() );
		for (int i=0; i<prototype.size(); i++) {
			int j = prototype.getDistanceLearnerIndex(i);
			innerLearners[j].setDistanceInstancePool( new JthDistanceInstanceIterator( j, buffer.iterator() ) );
		}
		comboSetDistanceInstancePool( buffer.iterator() );
	}

	/** See if someone has a query */
	public boolean hasNextQuery() {
		for (int i=0; i<innerLearners.length; i++) {
			if (innerLearners[i].hasNextQuery()) return true;
		}
		return comboHasNextQuery();
	}

	/** Get a next query from one of the sublearners
	 */
	public DistanceInstance nextQuery() {
		// need to save out the i-th field, if it's been prepared.
		// poll sublearners in random order, to be fair
		// indices [0,innerLearners.length-1] are the inner learners,
		// index innerLearners.length is the comboLearner
		ArrayList indices = new ArrayList(innerLearners.length+1);
		for (int i=0; i<indices.size(); i++) indices.set(i, new Integer(i) );
		Collections.shuffle(indices);
		for (int i=0; i<indices.size(); i++) {
			int k = ((Integer)indices.get(i)).intValue();
			if ( k==innerLearners.length && comboHasNextQuery() ) {
				return comboNextQuery();
			} else if (innerLearners[k].hasNextQuery()) {
				return innerLearners[k].nextQuery();
			}
		}
		throw new IllegalStateException("someone seems to have forgotten they want a query");
	}

	/** Pass new labels to the sublearners. 
	 */
	public void addExample(DistanceInstance answeredQuery) {
		MyMultiDistanceInstance di = asMultiDistanceInstance( answeredQuery );
		for (int i=0; i<innerLearners.length; i++) {
			innerLearners[i].addExample( di.get(i) );
		}
		comboAddExample( di );
	}

	/** Prepare data for the sublearners.
	 */
	public StringWrapperIterator prepare(StringWrapperIterator it) 
	{
		List multiWrappers = asMultiStringWrapperList(it);
		if (multiWrappers.size()==0) return new BasicStringWrapperIterator( Collections.EMPTY_SET.iterator() );
		MultiStringWrapper prototype = (MultiStringWrapper)multiWrappers.get(0);
		for (int i=0; i<prototype.size(); i++) {
			int j = prototype.getDistanceLearnerIndex(i);
			StringDistanceLearner learner = innerLearners[j];
			StringWrapperIterator prepped = learner.prepare( new JthStringWrapperValueIterator( j, multiWrappers.iterator() ) );
			for (int k=0; k<multiWrappers.size(); k++) {
				MultiStringWrapper msw = (MultiStringWrapper)multiWrappers.get(k);
				StringWrapper w = prepped.nextStringWrapper();
				msw.set( i, w );
			}
		}
		return new BasicStringWrapperIterator( multiWrappers.iterator() );
	}

	/** Prepare data for the learners.
	 */
	public DistanceInstanceIterator prepare(DistanceInstanceIterator it) 
	{
		List multiDistances = asMultiDistanceInstanceList(it);
		return new BasicDistanceInstanceIterator( multiDistances.iterator() );
	}

	//
	// support routines for splitting and merging multiple StringWrapper's and DistanceInstance's
	//

	/* lazily convert to a List of MultiStringWrapper list */
	protected List asMultiStringWrapperList(StringWrapperIterator i) {
		List buffer = new ArrayList();
		while (i.hasNext()) {
			StringWrapper w = i.nextStringWrapper();
			MultiStringWrapper mw = asMultiStringWrapper(w);
			buffer.add(mw);
		}
		return buffer;
	}

	/* lazily convert to a MultiStringWrapper */
	protected MultiStringWrapper asMultiStringWrapper(StringWrapper w) 
	{
		if (w instanceof MultiStringWrapper) return (MultiStringWrapper)w;
		else 	{
			MultiStringWrapper mw = new MultiStringWrapper( w.unwrap(), innerLearners.length, delim);
			for (int i=0; i<mw.size(); i++) {
				mw.set(i, prepareForLearner( mw.get(i), innerLearners[mw.getDistanceLearnerIndex(i)] ) );
			}
			return mw;
		}
	}

	/** Prepare a single StringWrapper for a learner */
	private StringWrapper prepareForLearner(StringWrapper w,StringDistanceLearner learner) {
		StringWrapperIterator it = new BasicStringWrapperIterator( Collections.singleton(w).iterator() ); 
		return learner.prepare(it).nextStringWrapper();
	}


	/** Iterate over the j-th field of MultiStringWrapper */
	protected class JthStringWrapperValueIterator implements StringWrapperIterator {
		private Iterator i;
		private int j;
		public JthStringWrapperValueIterator(int j,Iterator i) { this.j=j; this.i=i; }
		public boolean hasNext() { return i.hasNext(); }
		public Object next() { return ((MultiStringWrapper)i.next()).get(j); }
		public StringWrapper nextStringWrapper() { return (StringWrapper) next(); }
		public void remove() { throw new UnsupportedOperationException("can't remove"); }
	}

	/* lazily convert to a List of DistanceInstance's with MultiStringWrapper's in each place */
	protected List asMultiDistanceInstanceList(DistanceInstanceIterator i) {
		List buffer = new ArrayList();
		while (i.hasNext()) {
			DistanceInstance di = i.nextDistanceInstance();
			buffer.add( asMultiDistanceInstance( i.nextDistanceInstance() ) );
		}
		return buffer;
	}

	protected MyMultiDistanceInstance asMultiDistanceInstance(DistanceInstance di) {
		if (di instanceof MyMultiDistanceInstance) return (MyMultiDistanceInstance)di;
		else return new MyMultiDistanceInstance( di.getA(), di.getB(), di.isCorrect(),  di.getDistance());
	}

	protected class MyDistanceInstance implements DistanceInstance {
		protected StringWrapper a,b;
		protected boolean correct;
		protected double distance;
		public MyDistanceInstance(StringWrapper a,StringWrapper b,boolean correct,double distance) {
			this.a = a;
			this.b = b;
			this.correct = correct;
			this.distance = distance;
		}
		public StringWrapper getA() { return a; }
		public StringWrapper getB() { return b; }
		public boolean isCorrect() { return correct; }
		public double getDistance() { return distance; }
		public void setDistance(double distance) { this.distance = distance; }
	}

	protected class MyMultiDistanceInstance extends MyDistanceInstance {
		MultiStringWrapper ma,mb;
		public MyMultiDistanceInstance(StringWrapper a,StringWrapper b,boolean correct,double distance) {
			super(a,b,correct,distance);
			ma = asMultiStringWrapper(a);
			mb = asMultiStringWrapper(b);
		}
		public StringWrapper getA(int j) { return ma.get(j); }
		public StringWrapper getB(int j) { return mb.get(j); }
		public DistanceInstance get(int j) { return new MyDistanceInstance( ma.get(j), mb.get(j), correct, distance); }
		public String toString() { return "["+ma+";"+mb+"]"; }
	}

	/** Iterate over the j-th field of MultiStringWrapper's in a DistanceInstance of MultiStringWrapper's */
	protected class JthDistanceInstanceIterator implements DistanceInstanceIterator {
		private Iterator i;
		private int j;
		public JthDistanceInstanceIterator(int j, Iterator i) { this.j=j; this.i=i; }
		public boolean hasNext() { return i.hasNext(); }
		public DistanceInstance nextDistanceInstance() { return (DistanceInstance)next(); }
		public Object next() { return ((MyMultiDistanceInstance) i.next()).get(j); }
		public void remove() { throw new UnsupportedOperationException("can't remove"); }
	}

	/** Get an array of trained inner distances. */
	protected StringDistance[] getInnerDistances() 
	{
		StringDistance[] innerDistances = new StringDistance[ innerLearners.length ];
		for (int j=0; j<innerLearners.length; j++) {
			innerDistances[j] = innerLearners[j].getDistance();
		}
		return innerDistances;
	}

	/**
	 * Abstract class for combining innerDistances's
	 */
	protected abstract class CombinedStringDistance implements StringDistance
	{
		protected StringDistance[] innerDistances;
		protected MultiStringWrapper prototype;

		public CombinedStringDistance(StringDistance[] innerDistances, MultiStringWrapper prototype) 
		{
			this.innerDistances = innerDistances;
			this.prototype = prototype;
		}

		final public double score(String s, String t) 
		{	
			return score(prepare(s), prepare(t));	
		}

		final public String explainScore(String s, String t) 
		{ 
			return explainScore(prepare(s), prepare(t));	
		}

		final public StringWrapper prepare(String s) 
		{ 
			MultiStringWrapper ms = asMultiStringWrapper(new BasicStringWrapper(s));
			ms.prepare( innerDistances );
			return ms;
		}

		final public double score(StringWrapper s,StringWrapper t) 
		{
			MultiStringWrapper ms = asMultiStringWrapper(s);
			MultiStringWrapper mt = asMultiStringWrapper(t);
			ms.prepare(innerDistances);
			mt.prepare(innerDistances);
			if (ms.size() != mt.size() || ms.size()!=prototype.size()) {
				throw new IllegalStateException("ms,mt="+ms+","+mt+" expected MultiStringWrapper's of size "+prototype.size()); 
			}
			return doScore(ms,mt);
		}
		
		final public String explainScore(StringWrapper s, StringWrapper t) { 
			StringBuffer buf = new StringBuffer();
			MultiStringWrapper ms = asMultiStringWrapper(s);
			MultiStringWrapper mt = asMultiStringWrapper(t);
			if (ms.size() != mt.size() || ms.size()!=prototype.size()) {
				throw new IllegalStateException("expected MultiStringWrapper's of size "+prototype.size()); 
			}
			for (int i=0; i<ms.size(); i++) {
				StringDistance d = innerDistances[ ms.getDistanceLearnerIndex(i) ];
				buf.append("score of "+d+" on '"+ms.get(i)+"' and '"+mt.get(i)+"' = "+d.score( ms.get(i), mt.get(i) )+"\n");
			}
			buf.append( explainCombination(ms, mt) );
			return buf.toString(); 
		}

		/** Produce a score, assuming ms and mt are the correct sizes, and fully prepared. */
		abstract protected double doScore(MultiStringWrapper ms,MultiStringWrapper mt);

		/** Explain how the primitive scores were combined. */
		abstract protected String explainCombination(MultiStringWrapper ms,MultiStringWrapper mt);

		/** Help class for 'toString()' which produces a description of the distances being combined. */
		protected String innerDistanceString() 
		{
			StringBuffer buf = new StringBuffer("");
			for (int i=0; i<innerDistances.length; i++) 
			{
				buf.append(" "+innerDistances[i]);
			}
			return buf.toString();
		}
	}

}