repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
JSAT
JSAT-master/JSAT/src/jsat/text/wordweighting/WordWeighting.java
package jsat.text.wordweighting; import java.util.List; import jsat.linear.Vec; import jsat.math.IndexFunction; /** * WordWeighting is an index function specifically mean for modifying the values * of a vectors used for a bag-of-words representation of text data. <br> * Some Word weighting schemes may need information about the document * collection as a whole before constructing the weightings, and this class * provides the facilities for this to be done in a standardized manner. * * @author Edward Raff */ public interface WordWeighting extends IndexFunction { /** * Prepares the word weighting to be performed on a data set. This should be * called once before being applied to any vectors. Different WordWeightings * may require different amounts of computation to set up. * * @param allDocuments the list of all vectors that make up the set of * documents. The word vectors should be unmodified, containing the value of * how many times a word appeared in the document for each index. * @param df a list mapping each integer index of a word to how many times * that word occurred in total */ public void setWeight(List<? extends Vec> allDocuments, List<Integer> df); /** * The implementation may want to pre compute come values based on the * vector it is about to be applied to. This should be called in place of * {@link Vec#applyIndexFunction(jsat.math.IndexFunction) } . The vector * should be in a bag-of-words form where each index value indicates how * many times the word for that index occurred in the document represented * by the vector. * * @param vec the vector to set up for and then alter by invoking * {@link Vec#applyIndexFunction(jsat.math.IndexFunction) } on */ public void applyTo(Vec vec); }
1,869
39.652174
81
java
JSAT
JSAT-master/JSAT/src/jsat/utils/ArrayUtils.java
package jsat.utils; import java.util.Arrays; import java.util.Random; /** * Extra utilities for working on array types * * @author Edward Raff */ public class ArrayUtils { /** * No constructing! */ private ArrayUtils() { } /** * Converts the return value from binarySearch code such as {@link Arrays#binarySearch(double[], double) * } into a value that is guaranteed to be positive. It will be the either * the index that had the exact value, or the next position at which the * search value should be inserted. * * @param indx * @return */ public static int bsIndex2Insert(int indx) { if (indx < 0) indx = -indx - 1; return indx; } /** * Swaps values in the given array * * @param array the array to swap values in * @param rand the source of randomness for shuffling */ static public void shuffle(int[] array, Random rand) { shuffle(array, 0, array.length, rand); } /** * Shuffles the values in the given array * @param array the array to shuffle values in * @param from the first index, inclusive, to shuffle from * @param to the last index, exclusive, to shuffle from * @param rand the source of randomness for shuffling */ static public void shuffle(int[] array, int from, int to, Random rand) { for(int i = to-1; i > from; i--) swap(array, i, rand.nextInt(i)); } /** * Swaps two indices in the given array * @param array the array to perform the sawp in * @param a the first index * @param b the second index */ static public void swap(int[] array, int a, int b) { int tmp = array[a]; array[a] = array[b]; array[b] = tmp; } }
1,824
23.662162
108
java
JSAT
JSAT-master/JSAT/src/jsat/utils/BooleanList.java
package jsat.utils; import java.io.Serializable; import java.util.*; import jsat.linear.DenseVector; import jsat.linear.Vec; /** * Provides a modifiable implementation of a List using a boolean array. This provides considerable * memory efficency improvements over using an {@link ArrayList} to store booleans. <br> * Null is not allowed into the list. * * @author Edward Raff */ public class BooleanList extends AbstractList<Boolean> implements Serializable, RandomAccess { private static final long serialVersionUID = 653930294509274337L; private boolean[] array; //Exclusive private int end; private BooleanList(boolean[] array, int end) { this.array = array; this.end = end; } @Override public void clear() { end = 0; } /** * Creates a new empty BooleanList */ public BooleanList() { this(10); } /** * Creates a new empty BooealList * * @param capacity the starting internal capacity of the list */ public BooleanList(int capacity) { this(new boolean[capacity], 0); } /** * Creates a new BooleanList containing the values of the given collection * @param c the collection of values to fill this boolean list with */ public BooleanList(Collection<Boolean> c) { this(c.size()); this.addAll(c); } @Override public int size() { return end; } /** * Performs exactly the same as {@link #add(java.lang.Boolean) }. * @param e the value to add * @return true if it was added, false otherwise */ public boolean add(boolean e) { enlageIfNeeded(1); array[end] = e; increasedSize(1); return true; } /** * This method treats the underlying list as a stack. * Pushes an item onto the top of this "stack". * @param e the item to push onto the stack * @return the value added to the stack */ public boolean push(boolean e) { add(e); return e; } /** * This method treats the underlying list as a stack. Removes the item at * the top of this "stack" and returns that item as the value. * * @return the item at the top of this stack (the last item pushed onto it) */ public boolean pop() { if(isEmpty()) throw new EmptyStackException(); return removeB(size()-1); } /** * This method treats the underlying list as a stack. Gets the item at the * top of this "stack" and returns that item as the value, but leaves it on * the stack. * * @return the item at the top of this stack (the last item pushed onto it) */ public boolean peek() { if(isEmpty()) throw new EmptyStackException(); return get(size()-1); } /** * Makes the changes indicating that a number of items have been removed * @param removed the number of items that were removed */ private void decreaseSize(int removed) { end-=removed; } /** * Marks the increase of size of this list, and reflects the change in the parent */ private void increasedSize(int added) { end+=added; } private void boundsCheck(int index) throws IndexOutOfBoundsException { if(index >= size()) throw new IndexOutOfBoundsException("List is of size " + size() + ", index requested " + index); } /** * Enlarge the storage array if needed * @param i the amount of elements we will need to add */ private void enlageIfNeeded(int i) { while(end+i > array.length) array = Arrays.copyOf(array, Math.max(array.length*2, 8)); } @Override public boolean add(Boolean e) { if(e == null) return false; return add(e.booleanValue()); } /** * Operates exactly as {@link #get(int) } * @param index the index of the value to get * @return the value at the given index */ public boolean getB(int index) { boundsCheck(index); return array[index]; } @Override public Boolean get(int index) { return getB(index); } /** * Operates exactly as {@link #set(int, java.lang.Boolean) } * @param index the index to set * @param element the value to set * @return the previous value at said index */ public boolean set(int index, boolean element) { boundsCheck(index); boolean ret = get(index); array[index] = element; return ret; } @Override public Boolean set(int index, Boolean element) { return set(index, element.booleanValue()); } /** * Operates exactly as {@link #add(int, java.lang.Boolean) } * @param index the index to add at * @param element the value to add */ public void add(int index, boolean element) { if(index == size())//special case, just appending { add(element); } else { boundsCheck(index); enlageIfNeeded(1); System.arraycopy(array, index, array, index+1, size()-index); set(index, element); increasedSize(1); } } @Override public void add(int index, Boolean element) { add(index, element.booleanValue()); } /** * Operates exactly as {@link #remove(int) } * @param index the index to remove * @return the value removed */ public boolean removeB(int index) { boundsCheck(index); boolean ret = array[index]; for(int i = index; i < end-1; i++) array[i] = array[i+1]; decreaseSize(1); return ret; } @Override public Boolean remove(int index) { return removeB(index); } /** * Returns the reference to the array that backs this list. * Alterations to the array will be visible to the DoubelList * and vise versa. The array returned may not the the same * size as the value returned by {@link #size() } * @return the underlying array used by this BooleanList */ public boolean[] getBackingArray() { return array; } /** * Creates an returns an unmodifiable view of the given boolean array that requires * only a small object allocation. * * @param array the array to wrap into an unmodifiable list * @param length the number of values of the array to use, starting from zero * @return an unmodifiable list view of the array */ public static List<Boolean> unmodifiableView(boolean[] array, int length) { return Collections.unmodifiableList(view(array, length)); } /** * Creates and returns a view of the given boolean array that requires only * a small object allocation. Changes to the list will be reflected in the * array up to a point. If the modification would require increasing the * capacity of the array, a new array will be allocated - at which point * operations will no longer be reflected in the original array. * * @param array the array to wrap by a BooleanList object * @param length the initial length of the list * @return a BoolaenList backed by the given array, unless modified to the * point of requiring the allocation of a new array */ public static BooleanList view(boolean[] array, int length) { if(length > array.length || length < 0) throw new IllegalArgumentException("length must be non-negative and no more than the size of the array("+array.length+"), not " + length); return new BooleanList(array, length); } }
7,912
26.006826
150
java
JSAT
JSAT-master/JSAT/src/jsat/utils/BoundedSortedList.java
package jsat.utils; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; /** * * @author Edward Raff */ public class BoundedSortedList<E extends Comparable<E>> extends ArrayList<E> implements Serializable { private static final long serialVersionUID = 5503813399376102571L; private final int maxSize; public BoundedSortedList(int maxSize, int initialCapacity) { super(initialCapacity); if(maxSize < 1) throw new RuntimeException("Invalid max size"); this.maxSize = maxSize; } public BoundedSortedList(int maxSize) { if(maxSize < 1) throw new RuntimeException("Invalid max size"); this.maxSize = maxSize; } @Override public boolean add(E e) { if(isEmpty()) { super.add(e); return true; } else { int ind = Collections.binarySearch(this, e); if (ind >= 0)//it is already in the list, { if (size() == maxSize)//pop the last, put this { this.remove(maxSize - 1); super.add(ind, e); } else//not full yet, can jsut add { if(ind > size()) super.add(e); else super.add(ind, e); } return true; } else { ind = -(ind + 1);//Now it is the point where it should be inserted if (size() < maxSize) super.add(ind, e); else if (ind < maxSize) { this.remove(maxSize - 1); super.add(ind, e); } else return false; return true; } } } public E first() { if(isEmpty()) return null; return get(0); } public E last() { if(isEmpty()) return null; return get(size()-1); } @Override public void add(int index, E element) { add(element); } /** * Returns the maximum size allowed for the bounded list * @return the maximum size allowed for the bounded list */ public int maxSize() { return maxSize; } }
2,477
21.944444
100
java
JSAT
JSAT-master/JSAT/src/jsat/utils/BoundedSortedSet.java
package jsat.utils; import java.util.*; /** * * A Sorted set that has a maximum number of values it will hold. * * @author Edward Raff */ public class BoundedSortedSet<V> extends TreeSet<V> { private static final long serialVersionUID = -4774987058243433217L; private final int maxSize; public BoundedSortedSet(int max) { super(); this.maxSize = max; } public BoundedSortedSet(int max, Comparator<? super V> cmp) { super(cmp); this.maxSize = max; } @Override public boolean add(V e) { super.add(e); if(size() > maxSize) remove(last()); return true; } @Override public boolean addAll(Collection<? extends V> clctn) { super.addAll(clctn); while (size() > maxSize) remove(last()); return true; } /** * Returns the maximum size allowed for the bounded set * @return the maximum size allowed for the bounded set */ public int getMaxSize() { return maxSize; } }
1,091
17.508475
68
java
JSAT
JSAT-master/JSAT/src/jsat/utils/ClosedHashingUtil.java
package jsat.utils; import java.util.Arrays; /** * This class provides some useful methods and utilities for implementing Closed * Hashing structures * * @author Edward Raff */ public class ClosedHashingUtil { /** * Applying this bitwise AND mask to a long will give the bits corresponding * to an integer. */ public static final int INT_MASK = -1; /** * This value indicates that that status of an open addressing space is * EMPTY, meaning any value can be stored in it */ public static final byte EMPTY = 0; /** * This value indicates that the status of an open addressing space is * OCCUPIED, meaning it is in use. */ public static final byte OCCUPIED = EMPTY + 1; /** * This value indicates that the status of an open addressing space is * DELETED, meaning i should not stop a search for a value - but the code * is free to overwrite the values at this location and change the status * to {@link #OCCUPIED}. <br> * This can not be set to {@link #EMPTY} unless we can guarantee that no * value is stored in a index chain that stops at this location. */ public static final byte DELETED = OCCUPIED + 1; /** * This store the value {@link Integer#MIN_VALUE} in the upper 32 bits of a * long, so that the lower 32 bits can store any regular integer. This * allows a fast way to return 2 integers from one method in the form of a * long. The two values can then be recovered from the upper and lower 32 * bits of the long. This is meant to be used as a nonsense default value, * indicating that no information is present in the upper 32 bits. */ public static final long EXTRA_INDEX_INFO = ((long) Integer.MIN_VALUE) << 32; /** * Gets the next twin prime that is near a power of 2 and greater than or * equal to the given value * * @param m the integer to get a twine prime larger than * @return the a twin prime greater than or equal to */ public static int getNextPow2TwinPrime(int m) { int pos = Arrays.binarySearch(twinPrimesP2, m+1); if(pos >= 0) return twinPrimesP2[pos]; else return twinPrimesP2[-pos - 1]; } /** * This array lits twin primes that are just larger than a power of 2. The * prime in the list will be the larger of the twins, so the smaller can be * obtained by subtracting 2 from the value stored. The list is stored in * sorted order.<br> * Note, the last value stored is just under 2<sup>31</sup>, where the other * values are just over 2<sup>x</sup> for x &lt; 31 * */ public static final int[] twinPrimesP2 = { 7, //2^2 , twin with 5 13, //2^3 , twin with 11 19, //2^4 , twin with 17 43, //2^5 , twin with 41 73, //2^6 , twin with 71 139, //2^7 , twin with 137 271, //2^8 , twin with 269 523, //2^9 , twin with 632 1033, //2^10 , twin with 1031 2083, //2^11 , twin with 2081 4129, //2^12 , twin with 4127 8221, //2^13 , twin with 8219 16453, //2^14 , twin with 16451 32803, //2^15 , twin with 32801 65539, //2^16 , twin with 65537 131113, //2^17 , twin with 131111 262153, //2^18 , twin with 262151 524353, //2^19 , twin with 524351 1048891, //2^20 , twin with 1048889 2097259, //2^21 , twin with 2097257 4194583, //2^22 , twin with 4194581 8388619, //2^23 , twin with 8388617 16777291, //2^24 , twin with 16777289 33554503, //2^25 , twin with 33554501 67109323, //2^26 , twin with 67109321 134217781, //2^27 , twin with 134217779 268435579, //2^28 , twin with 268435577 536871019, //2^29 , twin with 536871017 1073741833, //2^30 , twin with 1073741831 2147482951, //first twin under 2^31, twin with 2147482949 }; }
4,031
36.682243
81
java
JSAT
JSAT-master/JSAT/src/jsat/utils/DoubleList.java
package jsat.utils; import java.io.Serializable; import java.util.*; import java.util.stream.DoubleStream; import jsat.linear.DenseVector; import jsat.linear.Vec; /** * Provides a modifiable implementation of a List using a double array. This provides considerable * memory efficency improvements over using an {@link ArrayList} to store doubles. <br> * Null is not allowed into the list. * * @author Edward Raff */ public class DoubleList extends AbstractList<Double> implements Serializable, RandomAccess { private static final long serialVersionUID = 653930294509274337L; private double[] array; //Exclusive private int end; private DoubleList(double[] array, int end) { this.array = array; this.end = end; } @Override public void clear() { end = 0; } /** * Creates a new empty DoubleList */ public DoubleList() { this(10); } /** * Creates a new empty DoubleList * * @param capacity the starting internal capacity of the list */ public DoubleList(int capacity) { this(new double[capacity], 0); } /** * Creates a new DoubleList containing the values of the given collection * @param c the collection of values to fill this double list with */ public DoubleList(Collection<Double> c) { this(c.size()); this.addAll(c); } @Override public int size() { return end; } /** * Performs exactly the same as {@link #add(java.lang.Double) }. * @param e the value to add * @return true if it was added, false otherwise */ public boolean add(double e) { enlageIfNeeded(1); array[end] = e; increasedSize(1); return true; } /** * This method treats the underlying list as a stack. * Pushes an item onto the top of this "stack". * @param e the item to push onto the stack * @return the value added to the stack */ public double push(double e) { add(e); return e; } /** * This method treats the underlying list as a stack. Removes the item at * the top of this "stack" and returns that item as the value. * * @return the item at the top of this stack (the last item pushed onto it) */ public double pop() { if(isEmpty()) throw new EmptyStackException(); return removeD(size()-1); } /** * This method treats the underlying list as a stack. Gets the item at the * top of this "stack" and returns that item as the value, but leaves it on * the stack. * * @return the item at the top of this stack (the last item pushed onto it) */ public double peek() { if(isEmpty()) throw new EmptyStackException(); return get(size()-1); } /** * Makes the changes indicating that a number of items have been removed * @param removed the number of items that were removed */ private void decreaseSize(int removed) { end-=removed; } /** * Marks the increase of size of this list, and reflects the change in the parent */ private void increasedSize(int added) { end+=added; } private void boundsCheck(int index) throws IndexOutOfBoundsException { if(index >= size()) throw new IndexOutOfBoundsException("List is of size " + size() + ", index requested " + index); } /** * Enlarge the storage array if needed * @param i the amount of elements we will need to add */ private void enlageIfNeeded(int i) { while(end+i > array.length) array = Arrays.copyOf(array, Math.max(array.length*2, 8)); } @Override public boolean add(Double e) { if(e == null) return false; return add(e.doubleValue()); } /** * Operates exactly as {@link #get(int) } * @param index the index of the value to get * @return the value at the given index */ public double getD(int index) { boundsCheck(index); return array[index]; } @Override public Double get(int index) { return getD(index); } /** * Operates exactly as {@link #set(int, java.lang.Double) } * @param index the index to set * @param element the value to set * @return the previous value at said index */ public double set(int index, double element) { boundsCheck(index); double ret = get(index); array[index] = element; return ret; } @Override public Double set(int index, Double element) { return set(index, element.doubleValue()); } /** * Operates exactly as {@link #add(int, java.lang.Double) } * @param index the index to add at * @param element the value to add */ public void add(int index, double element) { if(index == size())//special case, just appending { add(element); } else { boundsCheck(index); enlageIfNeeded(1); System.arraycopy(array, index, array, index+1, size()-index); set(index, element); increasedSize(1); } } @Override public void add(int index, Double element) { add(index, element.doubleValue()); } /** * Operates exactly as {@link #remove(int) } * @param index the index to remove * @return the value removed */ public double removeD(int index) { boundsCheck(index); double ret = array[index]; for(int i = index; i < end-1; i++) array[i] = array[i+1]; decreaseSize(1); return ret; } @Override public Double remove(int index) { return removeD(index); } /** * Returns the reference to the array that backs this list. * Alterations to the array will be visible to the DoubelList * and vise versa. The array returned may not the the same * size as the value returned by {@link #size() } * @return the underlying array used by this DoubleList */ public double[] getBackingArray() { return array; } /** * Obtains a view of this double list as a dense vector with equal length. * This is a soft reference, and altering the values in the matrix with * alter the double list, and vise versa. * <br><br> * While no error will be thrown if the size of the underlying list changes, * this view should be discarded if the size of the list changes. Once the * list has changed sizes, there is no guarantee on the behavior that will * occur if the vector is used. * * @return a vector view of this list */ public Vec getVecView() { return new DenseVector(array, 0, end); } /** * Creates an returns an unmodifiable view of the given double array that requires * only a small object allocation. * * @param array the array to wrap into an unmodifiable list * @param length the number of values of the array to use, starting from zero * @return an unmodifiable list view of the array */ public static List<Double> unmodifiableView(double[] array, int length) { return Collections.unmodifiableList(view(array, length)); } /** * Creates and returns a view of the given double array that requires only * a small object allocation. Changes to the list will be reflected in the * array up to a point. If the modification would require increasing the * capacity of the array, a new array will be allocated - at which point * operations will no longer be reflected in the original array. * * @param array the array to wrap by a DoubleList object * @param length the initial length of the list * @return a DoubleList backed by the given array, unless modified to the * point of requiring the allocation of a new array */ public static DoubleList view(double[] array, int length) { if(length > array.length || length < 0) throw new IllegalArgumentException("length must be non-negative and no more than the size of the array("+array.length+"), not " + length); return new DoubleList(array, length); } /** * * @return the maximum value stored in this list. */ public double max() { if(isEmpty()) throw new EmptyStackException(); double max = 0; for(int i = 0; i < end; i++) max = Math.max(max, array[i]); return max; } }
8,861
26.351852
150
java
JSAT
JSAT-master/JSAT/src/jsat/utils/FakeExecutor.java
package jsat.utils; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * * Provides a fake {@link ExecutorService} that immediatly runs any * given runnable on the main thread. This will not use any given * threads and will never create a thread. * * @author Edward Raff */ public class FakeExecutor implements ExecutorService { public void shutdown() { } public List<Runnable> shutdownNow() { return null; } public boolean isShutdown() { return false; } public boolean isTerminated() { return false; } public boolean awaitTermination(long l, TimeUnit tu) throws InterruptedException { return true; } public <T> Future<T> submit(final Callable<T> clbl) { return new Future<T>() { public boolean cancel(boolean bln) { return false; } public boolean isCancelled() { return false; } public boolean isDone() { return false; } public T get() throws InterruptedException, ExecutionException { try { return clbl.call(); } catch (Exception ex) { return null; } } public T get(long l, TimeUnit tu) throws InterruptedException, ExecutionException, TimeoutException { return get(); } }; } public <T> Future<T> submit(Runnable r, T t) { r.run(); return null; } public Future<?> submit(Runnable r) { r.run(); return null; } public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> clctn) throws InterruptedException { throw new UnsupportedOperationException("Not supported yet."); } public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> clctn, long l, TimeUnit tu) throws InterruptedException { throw new UnsupportedOperationException("Not supported yet."); } public <T> T invokeAny(Collection<? extends Callable<T>> clctn) throws InterruptedException, ExecutionException { throw new UnsupportedOperationException("Not supported yet."); } public <T> T invokeAny(Collection<? extends Callable<T>> clctn, long l, TimeUnit tu) throws InterruptedException, ExecutionException, TimeoutException { throw new UnsupportedOperationException("Not supported yet."); } public void execute(Runnable r) { r.run(); } }
2,979
22.84
154
java
JSAT
JSAT-master/JSAT/src/jsat/utils/FibHeap.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.utils; import java.util.*; /** * * @author Edward Raff <[email protected]> * @param <T> */ public class FibHeap<T> { /** * We access a given Fibonacci heap H by a pointer H:min to the root of a tree containing the minimum key. When a Fibonacci heap H is empty, H:min is NIL. */ FibNode<T> min; /** * We rely on one other attribute for a Fibonacci heap H: H:n, the number of * nodes currently in H */ int n; List<FibNode<T>> H; public FibHeap() { /** * To make an empty Fibonacci heap, the MAKE-FIB-HEAP procedure * allocates and returns the Fibonacci heap object H, where H:n D 0 and * H:min D NIL; there are no trees in H. */ this.min = null; this.n = 0; } public int size() { return n; } public FibNode<T> insert(T value, double weight) { //FIB-HEAP-INSERT @SuppressWarnings("unchecked") FibNode<T> x = new FibNode(value, weight); x.p = null; x.child = null; if(min == null) { //6| create a root list for H containing just x // H = new ArrayList<FibNode<T>>(); // H.add(x); //7| H.min D x min = x; } else { //8| insert x into H ’s root list min = merge(min, x);//9 & 10 handled implicitly by the behavior of merge method } //11| H.n = H.n+1 this.n++; return x; } public static <T> FibHeap<T> union(FibHeap<T> A, FibHeap<T> B) { FibHeap<T> H = new FibHeap<T>(); H.min = merge(A.min, B.min); H.n = A.n + B.n; return H; } private void consolidate() { ArrayList<FibNode<T>> A = new ArrayList<FibNode<T>>(); ArrayList<FibNode<T>> rootListCopy = new ArrayList<FibNode<T>>(); FibNode<T> startingNode = min; FibNode<T> runner = startingNode; do { rootListCopy.add(runner); //go to the next item in the list runner = runner.right; } while(runner != startingNode);//Yes, intentionally comparing objects. Circular link list. So once we reach the starting object we are done for(FibNode<T> w : rootListCopy) delink(w);//we will fix this later by re-merging at the end //4| for each node w in the root list of H for(FibNode<T> w : rootListCopy) { FibNode<T> x = w;//5 int d = x.degree;//6 //7| while A[d] != NIL while(A.size() <= d) A.add(null); while(A.get(d) != null) { //8| y = A[d] // another node with the same degree as x FibNode<T> y = A.get(d); if(x.key > y.key) { FibNode<T> tmp = y; y = x; x = tmp; } //11| FIB-HEAP-LINK(H,y,x) // if(startingNode == y )//if y was our starting node, we need to change the start to avoid a loop // startingNode = y.right;//otherwise looping through root list will never reach the original starting node // if(y == w)//move w left so that when we move right later we get to the correct position // w = w.left;//otherwise w will start looping through the child list isntead of the root list link(y, x); //12| A[d]=NIL A.set(d, null); //13| d=d+1 d++; while(A.size() <= d) A.add(null); } //14| A[d] = x A.set(d, x); } //15| H.min = NIL min = null; for(FibNode<T> x : A) min = merge(min, x); } private void link(FibNode<T> y, FibNode<T> x) { //1| remove y from the root list of H delink(y); //2| make y a child of x, incrementing x.degree x.addChild(y); x.degree++;//adding y as a child x.degree += y.degree;//and all of y's children //3| y.mark = FALSE y.mark = false; } public double getMinKey() { return min.key; } public T getMinValue() { return min.value; } public FibNode<T> peekMin() { return min; } public FibNode<T> removeMin() { //FIB-HEAP-EXTRACT-MIN //1| z = H.min FibNode<T> z = min; if(z != null) { min = delink(z); //3| for each child x of z if (z.child != null) { final FibNode<T> startingNode = z.child; FibNode<T> x = startingNode; do { x.p = null;//set parrent to null, we will add to the root list later //go to the next item in the list x = x.right; } while (x != startingNode);//Yes, intentionally comparing objects. Circular link list. So once we reach the starting object we are done //now all the children are added to the root list in one call min = merge(min, z.child); z.child = null;//z has no more children z.degree = 0; } else if (n == 1)//z had no children and was the only item in the whole heap { //so just set min to null min = null; } if(min != null) consolidate();//this will set min correctly no matter what n--; } return z; } public void decreaseKey(FibNode<T> x, double k) { if(k > x.key) throw new RuntimeException("new key is greater than current key"); x.key = k; FibNode<T> y = x.p; if(y != null && x.key < y.key) { cut(x, y); cascadingCut(y); } if(x.key < min.key) min = x; } /** * * @param x the child * @param y the parent */ private void cut(FibNode<T> x, FibNode<T> y) { //1| remove x from the child list of y, decrementing y.degree if(y.child == x)//if we removed but x was the child pointer, we would get messed up y.child = delink(x); else delink(x); y.degree--;//removal of 'x' from y y.degree-= x.degree;//removal of everyone x owned from y //2| add x to the root list of H min = merge(min, x); //3| x.p = NIL x.p = null; //4| x.mark = FALSE x.mark = false; } private void cascadingCut(FibNode<T> y) { //1. FibNode<T> z = y.p; if(z != null)//2. { if(y.mark == false)//3. y.mark = true;//4. else { cut(y, z); cascadingCut(z); } } } public static class FibNode<T> { T value; double key; /** * We store the number of children in the child list of node x in x.degree */ int degree; /** * The boolean-valued attribute x:mark indicates whether node x has lost * a child since the last time x was made the child of another node. * Newly created nodes are unmarked, and a node x becomes unmarked * whenever it is made the child of another node. */ boolean mark = false; /** * a pointer to its parent */ FibNode<T> p; /** * a pointer to any one of its children */ FibNode<T> child; FibNode<T> left, right; public FibNode(T value, double key) { this.degree = 0; this.value = value; this.key = key; this.left = this.right = this;//yes, this is intentional. We make a linked list of 1 item, ourselves. } public T getValue() { return value; } public double getPriority() { return key; } /** * Adds the given node directly to the children list of this node. THe * {@link #p} value for {@code x} will be set automatically. The * {@link #degree} of this node will not be adjusted, and must be * incremented correctly by the caller<br> * * @param x the node to add as a child of this node. Should be a * singular item */ public void addChild(FibNode<T> x) { if(this.child == null) this.child = x; else this.child = merge(this.child, x); x.p = this; } @Override public String toString() { return value + "," + key; } } /** * Disconnects the given node from the list it is currently in. * * @param <T> * @param a the node to disconnect from its current list * @return a node in the list that 'a' was originally apart of. Returns * {@code null} if a was its own list (ie: a list of size 1, or no "list"). */ private static <T> FibNode<T> delink(FibNode<T> a) { if(a.left == a)//a is on its own, nothing to return return null; //else, a is in a list FibNode<T> a_left_orig = a.left;//link to the rest of the list that we can return a.left.right = a.right; a.right.left = a_left_orig; //a no longer is in its original list, return link //fix a's links to point to itself not that it has been de-linked from everyone else a.left = a.right = a; return a_left_orig; } /** * Merges the two lists given by the two nodes. Works if either node represents a list of size 1 / is on its own. The node with the smaller value will be returned. * @param <T> * @param a * @param b * @return the node with the smallest key value */ private static <T> FibNode<T> merge(FibNode<T> a, FibNode<T> b) { if(a == b)//handles a and b == null (returns null) or a and b are the same object (return the obj, don't make weird cycles return a; if(a == null) return b; if(b == null) return a; //else, two different non-null nodes, make a the smaller priority one so we always return smallest priority if(a.key > b.key) { FibNode<T> tmp = a; a = b; b = tmp; } //linked list insert. Indertion used since links can point to themselves if list is empty FibNode<T> a_right_orig = a.right; a.right = b.right; a.right.left = a; b.right = a_right_orig; b.right.left = b; return a; } }
12,096
28.36165
168
java
JSAT
JSAT-master/JSAT/src/jsat/utils/GridDataGenerator.java
package jsat.utils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import jsat.SimpleDataSet; import jsat.classifiers.CategoricalData; import jsat.classifiers.DataPoint; import jsat.distributions.ContinuousDistribution; import jsat.distributions.Uniform; import jsat.linear.DenseVector; import jsat.utils.random.RandomUtil; /** * This is a utility to generate data in a grid fashion. * Each data point will belong to a different class. By default, * the data is generated such that the classes are trivially separable. * <br><br> * All data points belong to a specific axis, and have noises added to them. * For example, a 1 dimensional grid with 2 classes would have data points * of the form 0+noise, and 1+noise. So long as the noise is less than 0.5, * the data can be easily separated. * * @author Edward Raff */ public class GridDataGenerator { private ContinuousDistribution noiseSource; private int[] dimensions; private Random rand; private CategoricalData[] catDataInfo; /** * Creates a new Grid data generator, that can be queried for new data sets. * * @param noiseSource the distribution that describes the noise that will be added to each data point. If no noise is used, each data point would lie exactly on its local axis. * @param rand the source of randomness that the noise will use * @param dimensions an array describing how many groups there will be. * The length of the array dictates the number of dimensions in the data * set, each value describes how many axis of that dimensions to use. The * total number of classes is the product of these values. * * @throws ArithmeticException if one of the dimension values is not a positive value, or a zero number of dimensions is given */ public GridDataGenerator(ContinuousDistribution noiseSource, Random rand, int... dimensions) { this.noiseSource = noiseSource; this.rand = rand; this.dimensions = dimensions; for(int i = 0; i < dimensions.length; i++) if(dimensions[i] <= 0) throw new ArithmeticException("The " + i + "'th dimensino contains the non positive value " + dimensions[i]); } /** * Creates a new Grid data generator, that can be queried for new data sets. * * @param noiseSource the distribution that describes the noise that will be added to each data point. If no noise is used, each data point would lie exactly on its local axis. * @param dimensions an array describing how many groups there will be. * The length of the array dictates the number of dimensions in the data * set, each value describes how many axis of that dimensions to use. The * total number of classes is the product of these values. * * @throws ArithmeticException if one of the dimension values is not a positive value, or a zero number of dimensions is given */ public GridDataGenerator(ContinuousDistribution noiseSource, int... dimensions) { this(noiseSource, RandomUtil.getRandom(), dimensions); } /** * Creates a new grid data generator for a 2 x 5 with uniform noise in the range [-1/4, 1/4] */ public GridDataGenerator() { this(new Uniform(-0.25, 0.25), RandomUtil.getRandom(), 2, 5); } /** * Helper function * @param curClass used as a pointer to an integer so that we dont have to add class tracking logic * @param curDim the current dimension to split on. If we are at the last dimension, we add data points instead. * @param samples the number of samples to take for each class * @param dataPoints the location to put the data points in * @param dim the array specifying the current point we are working from. */ private void addSamples(int[] curClass, int curDim, int samples, List<DataPoint> dataPoints, int[] dim) { if(curDim < dimensions.length-1) for(int i = 0; i < dimensions[curDim+1]; i++ ) { int[] nextDim = Arrays.copyOf(dim, dim.length); nextDim[curDim+1] = i; addSamples(curClass, curDim+1, samples, dataPoints, nextDim); } else//Add data points! { for(int i = 0; i < samples; i++) { DenseVector dv = new DenseVector(dim.length); for(int j = 0; j < dim.length; j++) dv.set(j, dim[j]+noiseSource.invCdf(rand.nextDouble())); dataPoints.add(new DataPoint(dv, new int[]{ curClass[0] }, catDataInfo)); } curClass[0]++; } } /** * Generates a new data set. * * @param samples the number of sample data points to create for each class in the data set. * @return A data set the contains the data points with matching class labels. */ public SimpleDataSet generateData(int samples) { int totalClasses = 1; for(int d : dimensions) totalClasses *= d; catDataInfo = new CategoricalData[] { new CategoricalData(totalClasses) } ; List<DataPoint> dataPoints = new ArrayList<DataPoint>(totalClasses*samples); int[] curClassPointer = new int[1]; for(int i = 0; i < dimensions[0]; i++) { int[] curDim = new int[dimensions.length]; curDim[0] = i; addSamples(curClassPointer, 0, samples, dataPoints, curDim); } return new SimpleDataSet(dataPoints); } }
5,645
39.913043
183
java
JSAT
JSAT-master/JSAT/src/jsat/utils/IndexTable.java
package jsat.utils; import java.io.Serializable; import java.util.*; /** * The index table provides a way of accessing the sorted view of an array or list, * without ever sorting the elements of said list. Given an array of elements, the * index table creates an array of index values, and sorts the indices based on * the values they point to. The IndexTable can then be used to find the index * of the i'th sorted element in the array. <br> * <br> * The IndexTable can be sorted multiple times by calling the * {@link #sort(java.util.List, java.util.Comparator) } methods. This can be * called on inputs of varying size, and the internal order will be expanded * when necessary. * * @author Edward Raff */ public class IndexTable implements Serializable { private static final long serialVersionUID = -1917765351445664286L; static private final Comparator defaultComp = (Comparator) (Object o1, Object o2) -> { Comparable co1 = (Comparable) o1; Comparable co2 = (Comparable) o2; return co1.compareTo(co2); }; /** * Obtains the reverse order comparator * @param <T> the data type * @param cmp the original comparator * @return the reverse order comparator */ public static <T> Comparator<T> getReverse(final Comparator<T> cmp) { return (T o1, T o2) -> -cmp.compare(o1, o2); } /** * We use an array of Integer objects instead of integers because we need * the arrays.sort function that accepts comparators. */ private IntList index; /** * The size of the previously sorted array or list */ private int prevSize; /** * Creates a new index table of a specified size that is in linear order. * @param size the size of the index table to create */ public IndexTable(int size) { index = new IntList(size); ListUtils.addRange(index, 0, size, 1); } /** * Creates a new index table using the provided order. It is assumed that for an array of length {@code order.length}, every value from 0 to {@code order.length-1} will be included once. * @param order the order that should be used as the index. */ public IndexTable(int[] order) { index = new IntList(order.length); for(int i : order) index.add(i); } /** * Creates a new index table based on the given array. The array will not be altered. * @param array the array to create an index table for. */ public IndexTable(double[] array) { this(DoubleList.unmodifiableView(array, array.length)); } /** * Creates a new index table based on the given array. The array will not be altered. * @param array the array to create an index table for */ public <T extends Comparable<T>> IndexTable(T[] array) { index = new IntList(array.length); ListUtils.addRange(index, 0, array.length, 1); Collections.sort(index, new IndexViewCompG(array)); } /** * Creates a new index table based on the given list. The list will not be altered. * @param list the list to create an index table for */ public <T extends Comparable<T>> IndexTable(List<T> list) { this(list, defaultComp); } /** * Creates a new index table based on the given list and comparator. The * list will not be altered. * * @param list the list of points to obtain a sorted IndexTable for * @param comparator the comparator to determined the sorted order */ public <T> IndexTable(List<T> list, Comparator<T> comparator) { index = new IntList(list.size()); ListUtils.addRange(index, 0, list.size(), 1); sort(list, comparator); } /** * Resets the index table so that the returned indices are in linear order, * meaning the original input would be returned in its original order * instead of sorted order. */ public void reset() { for(int i = 0; i < index.size(); i++) index.set(i, i); } /** * Reverse the current index order */ public void reverse() { Collections.reverse(index); } /** * Adjusts this index table to contain the sorted index order for the given * array * @param array the input to get sorted order of */ public void sort(double[] array) { sort(DoubleList.unmodifiableView(array, array.length)); } /** * Adjusts this index table to contain the reverse sorted index order for * the given array * @param array the input to get sorted order of */ public void sortR(double[] array) { sortR(DoubleList.unmodifiableView(array, array.length)); } /** * Adjust this index table to contain the sorted index order for the given * list * @param <T> the data type * @param list the list of objects */ public <T extends Comparable<T>> void sort(List<T> list) { sort(list, defaultComp); } /** * Adjusts this index table to contain the reverse sorted index order for * the given list * @param <T> the data type * @param list the list of objects */ public <T extends Comparable<T>> void sortR(List<T> list) { sort(list, getReverse(defaultComp)); } /** * Sets up the index table based on the given list of the same size and * comparator. * * @param <T> the type in use * @param list the list of points to obtain a sorted IndexTable for * @param cmp the comparator to determined the sorted order */ public <T> void sort(List<T> list, Comparator<T> cmp) { if(index.size() < list.size()) for(int i = index.size(); i < list.size(); i++ ) index.add(i); if(list.size() == index.size()) Collections.sort(index, new IndexViewCompList(list, cmp)); else { Collections.sort(index);//so [0, list.size) is at the front Collections.sort(index.subList(0, list.size()), new IndexViewCompList(list, cmp)); } prevSize = list.size(); } private class IndexViewCompG<T extends Comparable<T>> implements Comparator<Integer> { T[] base; public IndexViewCompG(T[] base) { this.base = base; } @Override public int compare(Integer t, Integer t1) { return base[t].compareTo(base[t1]); } } private class IndexViewCompList<T> implements Comparator<Integer> { final List<T> base; final Comparator<T> comparator; public IndexViewCompList(List<T> base, Comparator<T> comparator) { this.base = base; this.comparator = comparator; } @Override public int compare(Integer t, Integer t1) { return comparator.compare(base.get(t), base.get(t1)); } } /** * Swaps the given indices in the index table. * @param i the second index to swap * @param j the first index to swap */ public void swap(int i, int j) { Collections.swap(index, i, j); } /** * Given the index <tt>i</tt> into what would be the sorted array, the index in the unsorted original array is returned. <br> * If the original array was a double array, <i>double[] vals</i>, then the sorted order can be printed with <br> * <pre><code> * for(int i = 0; i &lt; indexTable.{@link #length() length}(); i++) * System.out.println(vals[indexTable.get(i)]); * </code></pre> * @param i the index of the i'th sorted value * @return the index in the original list that would be in the i'th position */ public int index(int i) { if(i >= prevSize || i < 0) throw new IndexOutOfBoundsException("The size of the previously sorted array/list is " + prevSize + " so index " + i + " is not valid"); return index.get(i); } /** * The length of the previous array that was sorted * @return the length of the original array */ public int length() { return prevSize; } /** * Applies this index table to the specified target, putting {@code target} * into the same ordering as this IndexTable. * * @param target the array to re-order into the sorted order defined by this index table * @throws RuntimeException if the length of the target array is not the same as the index table */ public void apply(double[] target) { //use DoubleList view b/d we are only using set ops, so we wont run into an issue of re-allocating the array apply(DoubleList.view(target, target.length), new DoubleList(target.length)); } /** * Applies this index table to the specified target, putting {@code target} * into the same ordering as this IndexTable. * * @param target the array to re-order into the sorted order defined by this index table * @throws RuntimeException if the length of the target array is not the same as the index table */ public void apply(int[] target) { //use DoubleList view b/d we are only using set ops, so we wont run into an issue of re-allocating the array apply(IntList.view(target, target.length), new IntList(target.length)); } /** * Applies this index table to the specified target, putting {@code target} * into the same ordering as this IndexTable. * * @param target the list to re-order into the sorted order defined by this index table * @throws RuntimeException if the length of the target List is not the same as the index table */ public void apply(List target) { apply(target, new ArrayList(target.size())); } /** * Applies this index table to the specified target, putting {@code target} * into the same ordering as this IndexTable. It will use the provided * {@code tmp} space to store the original values in target in the same * ordering. It will be modified, and may be expanded using the {@link * List#add(java.lang.Object) add} method if it does not contain sufficient * space. Extra size in the tmp list will be ignored. After this method is * called, {@code tmp} will contain the same ordering that was in * {@code target} <br> * <br> * This method is provided as a means to reducing memory use when multiple * lists need to be sorted. * * @param target the list to sort, that should be the same size as the * previously sorted list. * @param tmp the temp list that may be of any size */ public void apply(List target, List tmp) { if (target.size() != length()) throw new RuntimeException("target array does not have the same length as the index table"); //fill tmp with the original ordering or target, adding when needed for (int i = 0; i < target.size(); i++) if (i >= tmp.size()) tmp.add(target.get(i)); else tmp.set(i, target.get(i)); //place back into target from tmp to get sorted order for(int i = 0; i < target.size(); i++) target.set(i, tmp.get(index(i))); } }
11,558
32.798246
191
java
JSAT
JSAT-master/JSAT/src/jsat/utils/IntDoubleMap.java
package jsat.utils; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import static jsat.utils.ClosedHashingUtil.*; /** * A hash map for storing the primitive types of integers (as keys) to doubles * (as table). The implementation is based on Algorithm D (Open addressing with * double hashing) from Knuth's TAOCP page 528. * * @author Edward Raff */ public final class IntDoubleMap extends AbstractMap<Integer, Double> { private float loadFactor; private int used = 0; private byte[] status; private int[] keys; private double[] table; public IntDoubleMap() { this(32); } public IntDoubleMap(int capacity) { this(capacity, 0.75f); } public IntDoubleMap(Map<Integer, Double> collection) { this(Math.max(1, collection.size())); for(Entry<Integer, Double> entry : collection.entrySet()) put(entry.getKey(), entry.getValue()); } public IntDoubleMap(int capacity, float loadFactor) { if(capacity < 1) throw new IllegalArgumentException("Capacity must be a positive value, not " + capacity); if(loadFactor <= 0 || loadFactor >= 1 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("loadFactor must be in (0, 1), not " + loadFactor); this.loadFactor = loadFactor; int size = getNextPow2TwinPrime((int) Math.max(capacity/loadFactor, 4)); status = new byte[size]; keys = new int[size]; table = new double[size]; } @Override public int size() { return used; } public int[] getRawKeyTable() { return keys; } public double[] getRawValueTable() { return table; } public byte[] getRawStatusTable() { return status; } @Override public Double put(Integer key, Double value) { double prev = put(key.intValue(), value.doubleValue()); if(Double.isNaN(prev)) return null; else return prev; } public double put(int key, double value) { if(Double.isNaN(value)) throw new IllegalArgumentException("NaN is not an allowable value"); long pair_index = getIndex(key); int deletedIndex = (int) (pair_index >>> 32); int valOrFreeIndex = (int) (pair_index & INT_MASK); double prev; if(status[valOrFreeIndex] == OCCUPIED)//easy case { prev = table[valOrFreeIndex]; table[valOrFreeIndex] = value; return prev; } //else, not present prev = Double.NaN; int i = valOrFreeIndex; if(deletedIndex >= 0)//use occupied spot instead i = deletedIndex; status[i] = OCCUPIED; keys[i] = key; table[i] = value; used++; enlargeIfNeeded(); return prev; } /** * * @param key the key whose associated value is to be incremented. All * non-present keys behave as having an implicit value of zero, in which * case the delta value is directly inserted into the map. * @param delta the amount by which to increment the key's stored value. * @return the new value stored for the given key */ public double increment(int key, double delta) { if(Double.isNaN(delta)) throw new IllegalArgumentException("NaN is not an allowable value"); long pair_index = getIndex(key); int deletedIndex = (int) (pair_index >>> 32); int valOrFreeIndex = (int) (pair_index & INT_MASK); if(status[valOrFreeIndex] == OCCUPIED)//easy case return (table[valOrFreeIndex] += delta); //else, not present double toReturn; int i = valOrFreeIndex; if(deletedIndex >= 0)//use occupied spot instead i = deletedIndex; status[i] = OCCUPIED; keys[i] = key; toReturn = table[i] = delta; used++; enlargeIfNeeded(); return toReturn; } /** * Returns the value to which the specified key is mapped, or * {@link Double#NaN} if this map contains no mapping for the key. * * @param key the key whose associated value is to be returned * @return the value to which the specified key is mapped, or * {@link Double#NaN} if this map contains no mapping for the key */ public double get(int key) { long pair_index = getIndex(key); int valOrFreeIndex = (int) (pair_index & INT_MASK); if(status[valOrFreeIndex] == OCCUPIED)//easy case return table[valOrFreeIndex]; //else, return NaN for missing return Double.NaN; } @Override public Double get(Object key) { if(key == null) return null; if(key instanceof Integer) { double d = get( ((Integer)key).intValue()); if(Double.isNaN(d)) return null; return d; } else throw new ClassCastException("Key not of integer type"); } @Override public Double remove(Object key) { if(key instanceof Integer) { double oldValue = remove(((Integer)key).intValue()); if(Double.isNaN(oldValue)) return null; else return oldValue; } return null; } /** * * @param key * @return the old value stored for this key, or {@link Double#NaN} if the * key was not present in the map */ public double remove(int key) { long pair_index = getIndex(key); int valOrFreeIndex = (int) (pair_index & INT_MASK); if(status[valOrFreeIndex] == EMPTY)//ret index is always EMPTY or OCCUPIED return Double.NaN; //else double toRet = table[valOrFreeIndex]; status[valOrFreeIndex] = DELETED; used--; return toRet; } @Override public void clear() { used = 0; Arrays.fill(status, EMPTY); } private void enlargeIfNeeded() { if(used < keys.length*loadFactor) return; //enlarge final byte[] oldSatus = status; final int[] oldKeys = keys; final double[] oldTable = table; int newSize = getNextPow2TwinPrime(status.length*3/2);//it will actually end up doubling in size since we have twin primes spaced that was status = new byte[newSize]; keys = new int[newSize]; table = new double[newSize]; used = 0; for(int oldIndex = 0; oldIndex < oldSatus.length; oldIndex++) if(oldSatus[oldIndex] == OCCUPIED) put(oldKeys[oldIndex], oldTable[oldIndex]); } @Override public boolean containsKey(Object key) { if(key instanceof Integer) return containsKey( ((Integer)key).intValue()); else return false; } public boolean containsKey(int key) { int index = (int) (getIndex(key) & INT_MASK); return status[index] == OCCUPIED;//would be FREE if we didn't have the key } private final static long EXTRA_INDEX_INFO = ((long)Integer.MIN_VALUE) << 32; /** * Gets the index of the given key. Based on that {@link #status} variable, * the index is either the location to insert OR the location of the key. * * This method returns 2 integer table in the long. The lower 32 bits are * the index that either contains the key, or is the first empty index. * * The upper 32 bits is the index of the first position marked as * {@link #DELETED} either {@link Integer#MIN_VALUE} if no position was * marked as DELETED while searching. * * @param key they key to search for * @return the mixed long containing the index of the first DELETED position * and the position that the key is in or the first EMPTY position found */ private long getIndex(int key) { long extraInfo = EXTRA_INDEX_INFO; //D1 final int hash = h(key) & INT_MASK; int i = hash % keys.length; //D2 int satus_i = status[i]; if((keys[i] == key && satus_i != DELETED) || satus_i == EMPTY) return extraInfo | i; if(extraInfo == EXTRA_INDEX_INFO && satus_i == DELETED) extraInfo = ((long)i) << 32; //D3 final int c = 1 + (hash % (keys.length -2)); while(true)//this loop will terminate { //D4 i -= c; if(i < 0) i += keys.length; //D5 satus_i = status[i]; if( (keys[i] == key && satus_i != DELETED) || satus_i == EMPTY) return extraInfo | i; if(extraInfo == EXTRA_INDEX_INFO && satus_i == DELETED) extraInfo = ((long)i) << 32; } } /** * Returns a non-negative hash value * @param key * @return */ public static int h(int key) { //http://stackoverflow.com/questions/664014/what-integer-hash-function-are-good-that-accepts-an-integer-hash-key key = ((key >>> 16) ^ key ) & 0x45f9f3b; key = ((key >>> 16) ^ key ) & 0x45f9f3b; key = ((key >>> 16) ^ key ) ; return key; } @Override public Set<Entry<Integer, Double>> entrySet() { return new EntrySet(this); } /** * EntrySet class supports remove operations */ private final class EntrySet extends AbstractSet<Entry<Integer, Double>> { final IntDoubleMap parentRef; public EntrySet(IntDoubleMap parent) { this.parentRef = parent; } @Override public Iterator<Entry<Integer, Double>> iterator() { //find the first starting inded int START = 0; while(START < status.length && status[START] != OCCUPIED) START++; if(START == status.length) return Collections.emptyIterator(); final int startPos = START; return new Iterator<Entry<Integer, Double>>() { int pos = startPos; int prevPos = -1; @Override public boolean hasNext() { return pos < status.length; } @Override public Entry<Integer, Double> next() { //final int make so that object remains good after we call next again final int oldPos = prevPos = pos++; //find next while (pos < status.length && status[pos] != OCCUPIED) pos++; //and return new object return new Entry<Integer, Double>() { @Override public Integer getKey() { return keys[oldPos]; } @Override public Double getValue() { return table[oldPos]; } @Override public Double setValue(Double value) { double old = table[oldPos]; table[oldPos] = value; return old; } }; } @Override public void remove() { //its ok to just call remove b/c nothing is re-ordered when we remove an element, we just set the status to DELETED parentRef.remove(keys[prevPos]); } }; } @Override public int size() { return used; } } }
12,480
28.367059
146
java
JSAT
JSAT-master/JSAT/src/jsat/utils/IntDoubleMapArray.java
/* * Copyright (C) 2016 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.utils; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Arrays; import java.util.Iterator; import java.util.Set; /** * Provides a map from integers to doubles backed by index into an array. * {@link Double#NaN} may not be inserted and negative numbers may not be used * for the key. This is meant as a convenience class, and should be used * sparingly. * * @author Edward Raff */ public class IntDoubleMapArray extends AbstractMap<Integer, Double> { private int used = 0; private double[] table; public IntDoubleMapArray() { this(1); } public IntDoubleMapArray(int max_index) { table = new double[max_index]; Arrays.fill(table, Double.NaN); } @Override public Double put(Integer key, Double value) { double prev = put(key.intValue(), value.doubleValue()); if(Double.isNaN(prev)) return null; else return prev; } public double put(int key, double value) { if(Double.isNaN(value)) throw new IllegalArgumentException("NaN is not an allowable value"); //epand with NaNs to fit index if(table.length <= key) { int oldLen = table.length; table = Arrays.copyOf(table, key+1); Arrays.fill(table, oldLen, table.length, Double.NaN); } double prev = table[key]; table[key] = value; if(Double.isNaN(prev)) used++; return prev; } /** * * @param key the key whose associated value is to be incremented. All * non-present keys behave as having an implicit value of zero, in which * case the delta value is directly inserted into the map. * @param delta the amount by which to increment the key's stored value. * @return the new value stored for the given key */ public double increment(int key, double delta) { if(Double.isNaN(delta)) throw new IllegalArgumentException("NaN is not an allowable value"); if(table.length <= key) put(key, delta); else if(Double.isNaN(table[key])) { table[key] = delta; used++; } else table[key] += delta; return table[key]; } /** * Returns the value to which the specified key is mapped, or * {@link Double#NaN} if this map contains no mapping for the key. * * @param key the key whose associated value is to be returned * @return the value to which the specified key is mapped, or * {@link Double#NaN} if this map contains no mapping for the key */ public double get(int key) { if(table.length <= key) return Double.NaN; return table[key]; } @Override public Double get(Object key) { if(key == null) return null; if(key instanceof Integer) { double d = get( ((Integer)key).intValue()); if(Double.isNaN(d)) return null; return d; } else throw new ClassCastException("Key not of integer type"); } @Override public Double remove(Object key) { if(key instanceof Integer) { double oldValue = remove(((Integer)key).intValue()); if(Double.isNaN(oldValue)) return null; else return oldValue; } return null; } /** * * @param key * @return the old value stored for this key, or {@link Double#NaN} if the * key was not present in the map */ public double remove(int key) { if(table.length <= key) return Double.NaN; double toRet = table[key]; table[key] = Double.NaN; if(!Double.isNaN(toRet)) used--; return toRet; } @Override public void clear() { used = 0; Arrays.fill(table, Double.NaN); } @Override public boolean containsKey(Object key) { if(key instanceof Integer) return containsKey( ((Integer)key).intValue()); else return false; } public boolean containsKey(int key) { if(table.length <= key) return false; return !Double.isNaN(table[key]); } @Override public Set<Entry<Integer, Double>> entrySet() { return new EntrySet(this); } /** * EntrySet class supports remove operations */ private final class EntrySet extends AbstractSet<Entry<Integer, Double>> { final IntDoubleMapArray parentRef; public EntrySet(IntDoubleMapArray parentRef) { this.parentRef = parentRef; } @Override public Iterator<Entry<Integer, Double>> iterator() { return new Iterator<Entry<Integer, Double>>() { int curPos = -1; int nexPos = curPos; @Override public boolean hasNext() { if(nexPos < curPos)//indicates we are out return false; else if(nexPos > curPos && nexPos < table.length) return true; //else, not sure yet - lets find the next pos nexPos = curPos+1; while(nexPos < table.length && Double.isNaN(table[nexPos])) nexPos++; if(nexPos >= table.length) return false; return true; } @Override public Entry<Integer, Double> next() { if(!hasNext()) throw new RuntimeException(); curPos = nexPos; return new Entry<Integer, Double>() { @Override public Integer getKey() { return curPos; } @Override public Double getValue() { return table[curPos]; } @Override public Double setValue(Double value) { double old = table[curPos]; table[curPos] = value; return old; } }; } @Override public void remove() { table[curPos] = Double.NaN; used--; } }; } @Override public int size() { return used; } } }
7,869
26.517483
80
java
JSAT
JSAT-master/JSAT/src/jsat/utils/IntList.java
package jsat.utils; import java.io.Serializable; import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; /** * Provides a modifiable implementation of a List using a int array. This provides considerable * memory efficency improvements over using an {@link ArrayList} to store integers. * Null is not allowed into the list. * * @author Edward Raff */ public class IntList extends AbstractList<Integer> implements Serializable, RandomAccess { private static final long serialVersionUID = 8189142393005394477L; private int[] array; private int end; private IntList(int[] array, int end) { this.array = array; this.end = end; } /** * Creates a new IntList */ public IntList() { this(10); } @Override public void clear() { end = 0; } /** * Creates a new IntList with the given initial capacity * @param capacity the starting internal storage space size */ public IntList(int capacity) { array = new int[capacity]; end = 0; } public IntList(Collection<Integer> c) { this(c.size()); addAll(c); } /** * Operates exactly as {@link #set(int, java.lang.Integer) } * @param index the index to set * @param element the value to set * @return the previous value at the index */ public int set(int index, int element) { boundsCheck(index); int prev = array[index]; array[index] = element; return prev; } @Override public Integer set(int index, Integer element) { return set(index, element.intValue()); } /** * Operates exactly as {@link #add(int, java.lang.Integer) } * @param index the index to add the value into * @param element the value to add */ public void add(int index, int element) { if (index == size())//special case, just appending { add(element); } else { boundsCheck(index); enlargeIfNeeded(1); System.arraycopy(array, index, array, index+1, end-index); array[index] = element; end++; } } @Override public void add(int index, Integer element) { add(index, element.intValue()); } /** * Operates exactly as {@link #add(java.lang.Integer) } * @param e the value to add * @return true if it was added, false otherwise */ public boolean add(int e) { enlargeIfNeeded(1); array[end++] = e; return true; } @Override public boolean add(Integer e) { if(e == null) return false; return add(e.intValue()); } /** * Operates exactly as {@link #get(int) } * @param index the index of the value to get * @return the value at the index */ public int getI(int index) { boundsCheck(index); return array[index]; } @Override public Integer get(int index) { return getI(index); } private void boundsCheck(int index) throws IndexOutOfBoundsException { if(index >= end) throw new IndexOutOfBoundsException("List of of size " + size() + ", index requested was " + index); } @Override public int size() { return end; } @Override public boolean addAll(Collection<? extends Integer> c) { int initSize = size(); enlargeIfNeeded(c.size()); for(int i : c) add(i); return initSize != size(); } @Override public Integer remove(int index) { if(index < 0 || index > size()) throw new IndexOutOfBoundsException("Can not remove invalid index " + index); int removed = array[index]; for(int i = index; i < end-1; i++) array[i] = array[i+1]; end--; return removed; } private void enlargeIfNeeded(int i) { while(end+i > array.length) array = Arrays.copyOf(array, Math.max(array.length*2, 8)); } /** * Efficiently sorts this list of integers using {@link Arrays#sort(int[]) * }. */ public void sort() { Arrays.sort(array, 0, end); } /** * Creates and returns an unmodifiable view of the given int array that * requires only a small object allocation. * * @param array the array to wrap into an unmodifiable list * @param length the number of values of the array to use, starting from zero * @return an unmodifiable list view of the array */ public static List<Integer> unmodifiableView(int[] array, int length) { return Collections.unmodifiableList(view(array, length)); } /** * Creates and returns a view of the given int array that requires only * a small object allocation. Changes to the list will be reflected in the * array up to a point. If the modification would require increasing the * capacity of the array, a new array will be allocated - at which point * operations will no longer be reflected in the original array. * * @param array the array to wrap by an IntList object * @param length the initial length of the list * @return an IntList backed by the given array, unless modified to the * point of requiring the allocation of a new array */ public static IntList view(int[] array, int length) { if(length > array.length || length < 0) throw new IllegalArgumentException("length must be non-negative and no more than the size of the array("+array.length+"), not " + length); return new IntList(array, length); } /** * Creates and returns a view of the given int array that requires only * a small object allocation. Changes to the list will be reflected in the * array up to a point. If the modification would require increasing the * capacity of the array, a new array will be allocated - at which point * operations will no longer be reflected in the original array. * * @param array the array to wrap by an IntList object * @return an IntList backed by the given array, unless modified to the * point of requiring the allocation of a new array */ public static IntList view(int[] array) { return view(array, array.length); } /** * * @return a sequential stream of integers with <tt>this</tt> as its source */ public IntStream streamInts() { return IntStream.of(array).limit(end); } /** * Returns a new IntList containing values in the given range * @param start the starting value (inclusive) * @param end the ending value (exclusive) * @param step the step size * @return a new IntList populated by integer values as if having run through a for loop */ public static IntList range(int start, int end, int step) { IntList l = new IntList((end-start)/step +1); for(int i = start; i < end; i++) l.add(i); return l; } /** * Returns a new IntList containing values in the given range * @param start the starting value (inclusive) * @param end the ending value (exclusive) * @return a new IntList populated by integer values as if having run through a for loop */ public static IntList range(int start, int end) { return range(start, end, 1); } /** * Returns a new IntList containing values in the range [0, <tt>end</tt>) * * @param end the ending value (exclusive) * @return a new IntList populated by integer values as if having run * through a for loop */ public static IntList range(int end) { return range(0, end); } }
8,015
26.546392
150
java
JSAT
JSAT-master/JSAT/src/jsat/utils/IntPriorityQueue.java
package jsat.utils; import java.io.Serializable; import java.util.*; /** * This class represents a priority queue specifically designed to contain * integer keys, and uses less memory then a {@link PriorityQueue} filled with * integers. This queue can optionally support <i>log(n)</i> removal of key * values at increased memory cost. * @author Edward Raff */ public class IntPriorityQueue extends AbstractQueue<Integer> implements Serializable { private static final long serialVersionUID = -310756323843109562L; public static final Comparator<Integer> naturalComparator = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }; /** * Sets the mode used for the priority queue. */ public static enum Mode { /** * Sets the priority queue to use the standard queue implementation with * the standard complexity for the following operations <br> * <br> * O(1) time for {@link #peek() } <br> * O(log n) time for {@link #poll() }, {@link #add(java.lang.Object) } <br> * O(n) time for {@link #remove(java.lang.Object) } and {@link #contains(java.lang.Object) }<br> * And calling {@link Iterator#remove() } is O(log n), but the iteration is in no particular order<br> * */ STANDARD, /** * Sets the priority queue to use a backing hashtable to map values to * their position in the heap. This changes the complexity to <br> * <br> * O(1) time for {@link #peek() } and {@link #contains(java.lang.Object) } <br> * O(log n) time for {@link #poll() }, {@link #add(java.lang.Object) }, * and {@link #remove(java.lang.Object) } <br> * And calling {@link Iterator#remove() } is O(log n), but the iteration * is in no particular order<br> */ HASH, /** * Sets the priority queue to use a backing array that indexes into the * heap. This provides the fastest version if fast * {@link #remove(java.lang.Object) } and {@link #contains(java.lang.Object) } * are needed. However, it must create an array as large as the largest * int value put into the queue, and negative values will not be accepted. * This method is best when the size of the queue is known to be bounded * and all values are in the range [0, N].<br> * <br> * O(1) time for {@link #peek() } and {@link #contains(java.lang.Object) } <br> * O(log n) time for {@link #poll() }, {@link #add(java.lang.Object) }, * and {@link #remove(java.lang.Object) } <br> * And calling {@link Iterator#remove() } is O(log n), but the iteration * is in no particular order<br> */ BOUNDED } private int[] heap; private int size; private Comparator<Integer> comparator; private final HashMap<Integer, Integer> valueIndexMap; private int[] valueIndexStore; private final Mode fastValueRemove; /** * Creates a new integer priority queue using {@link Mode#STANDARD} */ public IntPriorityQueue() { this(8, naturalComparator); } /** * Creates a new integer priority queue using the specified comparison and {@link Mode#STANDARD} * @param initialSize the initial storage size of the queue * @param comparator the comparator to determine the order of elements in the queue */ public IntPriorityQueue(int initialSize, Comparator<Integer> comparator) { this(initialSize, comparator, Mode.STANDARD); } /** * Creates a new integer priority queue * @param initialSize the initial storage size of the queue * @param fastValueRemove the mode that whether or not, and how, fast * arbitrary object removal from the queue will be done. */ public IntPriorityQueue(int initialSize, Mode fastValueRemove) { this(initialSize, naturalComparator, fastValueRemove); } /** * Creates a new integer priority queue * @param initialSize the initial storage size of the queue * @param comparator the comparator to determine the order of elements in the queue * @param fastValueRemove the mode that whether or not, and how, fast * arbitrary object removal from the queue will be done. */ public IntPriorityQueue( int initialSize, Comparator<Integer> comparator, Mode fastValueRemove) { this.heap = new int[initialSize]; this.comparator = comparator; this.size = 0; this.fastValueRemove = fastValueRemove; valueIndexStore = null; if(fastValueRemove == Mode.HASH) valueIndexMap = new HashMap<Integer, Integer>(initialSize); else if(fastValueRemove == Mode.BOUNDED) { valueIndexStore = new int[initialSize]; Arrays.fill(valueIndexStore, -1); valueIndexMap = null; } else valueIndexMap = null; } @Override public Iterator<Integer> iterator() { //Return a itterator that itterats the heap array in reverse. This is //slower (against cache line), but allows for simple implementaiton of //remove(). Becase removing an item is done by pulling the last element //in the heap and then pushing down, all changes for removing node i //will occur after index i return new Iterator<Integer>() { int pos = size-1; boolean canRemove = false; @Override public boolean hasNext() { return pos >= 0; } @Override public Integer next() { canRemove = true; return heap[pos--]; } @Override public void remove() { if(!canRemove) throw new IllegalStateException("An element can not currently be removed"); else { canRemove = false; removeHeapNode(pos+1); } } }; } @Override public int size() { return size; } @Override public boolean offer(Integer e) { if(e == null) return false; return offer((int)e); } public boolean offer(int e) { int i = size++; if(heap.length < size) heap = Arrays.copyOf(heap, heap.length*2); heap[i] = e; if(fastValueRemove == Mode.HASH) valueIndexMap.put(e, i); else if (fastValueRemove == Mode.BOUNDED ) if(e >= 0) indexArrayStore(e, i); else { heap[i] = 0; size--; return false; } heapifyUp(i); return true; } /** * Sets the given index to use the specific value * @param e the value to store the index of * @param i the index of the value */ private void indexArrayStore(int e, int i) { if (valueIndexStore.length < e) { int oldLength = valueIndexStore.length; valueIndexStore = Arrays.copyOf(valueIndexStore, e + 2); Arrays.fill(valueIndexStore, oldLength, valueIndexStore.length, -1); } valueIndexStore[e] = i; } @SuppressWarnings("unused") private int getRightMostChild(int i) { int rightMostChild = i; //Get the right most child in this tree while(rightChild(rightMostChild) < size) rightMostChild = rightChild(rightMostChild); //Could be at a level with a left but no right while(leftChild(rightMostChild) < size) rightMostChild = leftChild(rightMostChild); return rightMostChild; } private int cmp(int i, int j) { return comparator.compare(heap[i], heap[j]); } private void heapDown(int i) { int iL = leftChild(i); int iR = rightChild(i); //While we have two children, make sure we are smaller while (childIsSmallerAndValid(i, iL) || childIsSmallerAndValid(i, iR)) { //we are larger then one of ours children, so swap with the smallest of the two if ( iR < size && cmp(iL, iR) > 0 )//Right is the smallest { swapHeapValues(i, iR); i = iR; } else//Left is smallest or lef tis only option { swapHeapValues(i, iL); i = iL; } iL = leftChild(i); iR = rightChild(i); } } /** * Heapify up from the given index in the heap and make sure everything is * correct. Stops when the child value is in correct order with its parent. * @param i the index in the heap to start checking from. */ private void heapifyUp(int i) { int iP = parent(i); while(i != 0 && cmp(i, iP) < 0)//Should not be greater then our parent { swapHeapValues(iP, i); i = iP; iP = parent(i); } } /** * Swaps the values stored in the heap for the given indices * @param i the first index to be swapped * @param j the second index to be swapped */ private void swapHeapValues(int i, int j) { if(fastValueRemove == Mode.HASH) { valueIndexMap.put(heap[i], j); valueIndexMap.put(heap[j], i); } else if(fastValueRemove == Mode.BOUNDED) { //Already in the array, so just need to set valueIndexStore[heap[i]] = j; valueIndexStore[heap[j]] = i; } int tmp = heap[i]; heap[i] = heap[j]; heap[j] = tmp; } private int parent(int i) { return (i-1)/2; } private int leftChild(int i) { return 2*i+1; } /** * Removes the node specified from the heap * @param i the valid heap node index to remove from the heap * @return the value that was stored in the heap node */ protected int removeHeapNode(int i) { int val = heap[i]; int rightMost = --size; heap[i] = heap[rightMost]; heap[rightMost] = 0; if(fastValueRemove == Mode.HASH) { valueIndexMap.remove(val); if(size != 0) valueIndexMap.put(heap[i], i); } else if(fastValueRemove == Mode.BOUNDED) { valueIndexStore[val] = -1; } heapDown(i); return val; } private int rightChild(int i) { return 2*i+2; } private boolean childIsSmallerAndValid(int i, int child) { return child < size && cmp(i, child) > 0; } @Override public Integer poll() { if(isEmpty()) return null; return removeHeapNode(0); } @Override public Integer peek() { if(isEmpty()) return null; return heap[0]; } @Override public boolean contains(Object o) { if(fastValueRemove == Mode.HASH) return valueIndexMap.containsKey(o); else if(fastValueRemove == Mode.BOUNDED) { if( o instanceof Integer) { int val = ((Integer) o).intValue(); return val >= 0 && valueIndexStore[val] >= 0; } return false; } return super.contains(o); } @Override public void clear() { Arrays.fill(heap, 0, size, 0); size = 0; if(fastValueRemove == Mode.HASH) valueIndexMap.clear(); else if(fastValueRemove == Mode.BOUNDED) Arrays.fill(valueIndexStore, -1); } @Override public boolean remove(Object o) { if(fastValueRemove == Mode.HASH) { Integer index = valueIndexMap.get(o); if(index == null) return false; removeHeapNode(index); return true; } else if(fastValueRemove == Mode.BOUNDED) { if(o instanceof Integer) { int val = ((Integer) o).intValue(); if(val <0 || val >= valueIndexStore.length) return false; int index = valueIndexStore[val]; if(index == -1) return false; removeHeapNode(index); return true; } return false; } return super.remove(o); } }
12,931
29.428235
110
java
JSAT
JSAT-master/JSAT/src/jsat/utils/IntSet.java
package jsat.utils; import java.io.Serializable; import java.util.*; import static jsat.utils.ClosedHashingUtil.*; import static jsat.utils.IntDoubleMap.h; /** * A utility class for efficiently storing a set of integers. The implementation * is based on Algorithm D (Open addressing with double hashing) from Knuth's * TAOCP page 528. * * @author Edward Raff */ public class IntSet extends AbstractSet<Integer> implements Serializable { private static final long serialVersionUID = -2175363824037596497L; private static final int DEFAULT_CAPACITY = 8; private float loadFactor; private int used = 0; /** * Number of indices marked "free". It is possible for used= 0 and free = * 0, if everything was deleted. When nothig is free, we need to re-insert * and clear the index to avoid corner case infinite loop that was not * accounted for in original algo description */ private int free = 0; private byte[] status; private int[] keys; /** * Creates a new empty integer set */ public IntSet() { this(DEFAULT_CAPACITY); } /** * Creates an empty integer set pre-allocated to store a specific number of * items * * @param capacity the number of items to store */ public IntSet(int capacity) { this(capacity, 0.75f); } /** * Creates an empty integer set pre-allocated to store a specific number of * items * * @param capacity the number of items to store * @param loadFactor the maximum ratio of used to un-used storage */ public IntSet(int capacity, float loadFactor) { this.loadFactor = loadFactor; int size = getNextPow2TwinPrime((int) Math.max(capacity / loadFactor, 4)); status = new byte[size]; keys = new int[size]; used = 0; free = size; } /** * Creates a new set of integers from the given set * @param set the set of integers to create a copy of */ public IntSet(Set<Integer> set) { this(set.size()); for(Integer integer : set) this.add(integer); } /** * Creates a set of integers from the given collection * @param collection a collection of integers to create a set from */ public IntSet(Collection<Integer> collection) { this(); for(Integer integer : collection) this.add(integer); } /** * Creates a set of integers from the given list of integers. * @param ints a list of integers to create a set from * @return a set of integers of all the unique integers in the given list */ public static IntSet from(int... ints) { return new IntSet(IntList.view(ints, ints.length)); } /** * Gets the index of the given key. Based on that {@link #status} variable, * the index is either the location to insert OR the location of the key. * * This method returns 2 integer table in the long. The lower 32 bits are * the index that either contains the key, or is the first empty index. * * The upper 32 bits is the index of the first position marked as * {@link #DELETED} either {@link Integer#MIN_VALUE} if no position was * marked as DELETED while searching. * * @param key they key to search for * @param inserting {@code true} if a value is being inserted into the index, false otherwise * @return the mixed long containing the index of the first DELETED position * and the position that the key is in or the first EMPTY position found */ private long getIndex(int key, boolean inserting) { long extraInfo = EXTRA_INDEX_INFO; //D1 final int hash = h(key) & INT_MASK; int i = hash % keys.length; //D2 int satus_i = status[i]; if((keys[i] == key && satus_i != DELETED) || satus_i == EMPTY) return extraInfo | i; if(extraInfo == EXTRA_INDEX_INFO && satus_i == DELETED) extraInfo = ((long)i) << 32; //D3 final int c = 1 + (hash % (keys.length -2)); while(true)//this loop will terminate { //D4 i -= c; if(i < 0) i += keys.length; //D5 satus_i = status[i]; if( (keys[i] == key && satus_i != DELETED) || satus_i == EMPTY || (satus_i == DELETED && inserting)) return extraInfo | i; if(extraInfo == EXTRA_INDEX_INFO && satus_i == DELETED) extraInfo = ((long)i) << 32; } } private void enlargeIfNeeded() { if(used < keys.length*loadFactor && free > 0) return; //enlarge final byte[] oldSatus = status; final int[] oldKeys = keys; int newSize; if(used > keys.length*loadFactor) newSize = getNextPow2TwinPrime(status.length*3/2);//it will actually end up doubling in size since we have twin primes spaced that was else//Don't expand, but free = 0, so re-hash to avoild infinite chaning { newSize = oldSatus.length; } status = new byte[newSize]; keys = new int[newSize]; used = 0; free = newSize; for(int oldIndex = 0; oldIndex < oldSatus.length; oldIndex++) if(oldSatus[oldIndex] == OCCUPIED) add(oldKeys[oldIndex]); } @Override public void clear() { used = 0; Arrays.fill(status, EMPTY); } @Override public boolean add(Integer e) { if(e == null) return false; return add(e.intValue()); } /** * * @param e element to be added to this set * @return true if this set did not already contain the specified element */ public boolean add(int e) { final int key = e; long pair_index = getIndex(key, true); int deletedIndex = (int) (pair_index >>> 32); int valOrFreeIndex = (int) (pair_index & INT_MASK); byte origStatus = status[valOrFreeIndex]; if(origStatus == OCCUPIED)//easy case { return false;//we already had this item in the set! } //else, not present int i = valOrFreeIndex; if(deletedIndex >= 0)//use occupied spot instead { i = deletedIndex; origStatus = status[i]; } status[i] = OCCUPIED; keys[i] = key; used++; if(origStatus == EMPTY) free--; enlargeIfNeeded(); return true;//item was not in the set previously } public boolean contains(int o) { int index = (int) (getIndex(o, false) & INT_MASK); return status[index] == OCCUPIED;//would be FREE if we didn't have the key } @Override public boolean remove(Object key) { if(key instanceof Integer) return remove(((Integer)key).intValue()); return false; } /** * * @param key the value from the set to remove * @return true if this set contained the specified element */ public boolean remove(int key) { long pair_index = getIndex(key, false); int valOrFreeIndex = (int) (pair_index & INT_MASK); if(status[valOrFreeIndex] == EMPTY)//ret index is always EMPTY or OCCUPIED return false; //else status[valOrFreeIndex] = DELETED; used--; return true; } @Override public boolean contains(Object o) { if(o != null && o instanceof Integer) return contains(((Integer)o).intValue()); else return false; } @Override public Iterator<Integer> iterator() { final IntSet parentRef = this; //find the first starting inded int START = 0; while (START < status.length && status[START] != OCCUPIED) START++; if (START == status.length) return Collections.emptyIterator(); final int startPos = START; return new Iterator<Integer>() { int pos = startPos; int prevPos = -1; @Override public boolean hasNext() { return pos < status.length; } @Override public Integer next() { //final int make so that object remains good after we call next again final int oldPos = prevPos = pos++; //find next while (pos < status.length && status[pos] != OCCUPIED) pos++; //and return new object return keys[oldPos]; } @Override public void remove() { //its ok to just call remove b/c nothing is re-ordered when we remove an element, we just set the status to DELETED parentRef.remove(keys[prevPos]); } }; } @Override public int size() { return used; } }
9,293
27.953271
146
java
JSAT
JSAT-master/JSAT/src/jsat/utils/IntSetFixedSize.java
package jsat.utils; import java.io.Serializable; import java.util.AbstractSet; import java.util.Iterator; /** * A set for integers that is of a fixed initial size, and can only accept * integers in the range [0, size). Insertions, removals, and checks are all * constant time with a fast iterator. <br> * Null values are not supported * * @author Edward Raff */ public class IntSetFixedSize extends AbstractSet<Integer> implements Serializable { private static final long serialVersionUID = 7743166074116253587L; private static final int STOP = -1; private int nnz = 0; private int first = -1; private boolean[] has; //Use as a linked list private int[] prev; private int[] next; /** * Creates a new fixed size int set * @param size the size of the int set */ public IntSetFixedSize(int size) { has = new boolean[size]; prev = new int[size]; next = new int[size]; first = STOP; } @Override public boolean add(Integer e) { return add(e.intValue()); } /** * Adds a new integer into the set * @param e the value to add into the set * @return {@code true} if the operation modified the set, {@code false} * otherwise. */ public boolean add(int e) { if(e < 0 || e >= has.length) throw new IllegalArgumentException("Input must be in range [0, " + has.length + ") not " + e); else if(contains(e) ) return false; else { if (nnz == 0) { first = e; next[e] = prev[e] = STOP; } else { prev[first] = e; next[e] = first; prev[e] = STOP; first = e; } nnz++; return has[e] = true; } } @Override public boolean remove(Object o) { if(o instanceof Integer) return remove_int((Integer)o); return super.remove(o); } /** * Removes the specified integer from the set * @param val the value to remove * @return {@code true} if the set was modified by this operation, * {@code false} if it was not. */ public boolean remove(int val) { return remove_int(val); } @Override public boolean contains(Object o) { if(o instanceof Integer) { int val = (Integer)o; return contains(val); } else return false; } /** * Checks if the given value is contained in this set * @param val the value to check for * @return {@code true} if the value is in the set, {@code false} otherwise. */ public boolean contains(int val) { if(val < 0 || val >= has.length) return false; return has[val]; } private boolean remove_int(int index) { if (contains(index)) { if (first == index) first = next[index]; else next[prev[index]] = next[index]; if (next[index] != STOP) prev[next[index]] = prev[index]; next[index] = STOP; has[index] = false; nnz--; return true; } else return false; } @Override public Iterator<Integer> iterator() { final Iterator<Integer> iterator = new Iterator<Integer>() { int prev = STOP; int runner = first; @Override public boolean hasNext() { return runner != STOP; } @Override public Integer next() { prev = runner; runner = next[runner]; return prev; } @Override public void remove() { remove_int(prev); } }; return iterator; } @Override public int size() { return nnz; } }
4,187
22.52809
106
java
JSAT
JSAT-master/JSAT/src/jsat/utils/IntSortedSet.java
package jsat.utils; import java.io.Serializable; import java.util.*; /** * A utility class for efficiently storing a set of integers. In order to do * this, the integers are stored in their natural order. * * @author Edward Raff */ public class IntSortedSet extends AbstractSet<Integer> implements Serializable, SortedSet<Integer> { private static final long serialVersionUID = -2675363824037596497L; private static final int defaultSize = 8; private int[] store; private int size; public IntSortedSet(int initialSize) { store = new int[initialSize]; size = 0; } /** * Creates a new set of integers from the given set * @param set the set of integers to create a copy of */ public IntSortedSet(Set<Integer> set) { this(set.size()); batch_insert(set, false); } /** * Creates a new set of integers from the given set * * @param set the set of integers to create a copy of * @param parallel {@code true} if sorting should be done in parallel, or * {@code false} for serial sorting. */ public IntSortedSet(Collection<Integer> set, boolean parallel) { this(set.size()); batch_insert(set, parallel); } /** * Creates a set of integers from the given collection * @param collection a collection of integers to create a set from */ public IntSortedSet(Collection<Integer> collection) { this(collection.size()); batch_insert(collection, false); } /** * more efficient insertion of many items by placing them all into the * backing store, and then doing one large sort. * * @param set * @param parallel */ private void batch_insert(Collection<Integer> set, boolean parallel) { for(int i : set) store[size++] = i; if(parallel) Arrays.parallelSort(store, 0, size); else Arrays.sort(store, 0, size); } /** * Creates a set of integers from the given list of integers. * @param ints a list of integers to create a set from * @return a set of integers of all the unique integers in the given list */ public static IntSortedSet from(int... ints) { return new IntSortedSet(IntList.view(ints, ints.length)); } /** * This method provides direct access to the integer array used to store all * ints in this object. Altering this will alter the set, and may cause * incorrect behavior if the sorted order is violated. * * @return the sorted int array used to back this current object. */ public int[] getBackingStore() { return store; } public IntSortedSet() { this(defaultSize); } @Override public boolean add(Integer e) { if(e == null) return false; //Increase store size if needed //checking here means we will actually expand 1 value early, but avoids a double check later //so small cost, I'll take it to simplify code if(size >= store.length) store = Arrays.copyOf(store, Math.max(1, store.length)*2); //fast path for when we are filling a set, and iterating from smallest to largest index. //avoids needlessly expensive binary search for common insertion pattern if(size > 0 && store[size-1] < e) { store[size++] = e; return true; } //else, do a search to find where we should be placing this value int insertionPoint = Arrays.binarySearch(store, 0, size, e); if(insertionPoint >= 0 ) return false;//Already in the set //Fix up to where we would like to place it insertionPoint = (-(insertionPoint) - 1); for(int i = size; i > insertionPoint; i--) store[i] = store[i-1]; store[insertionPoint] = e; size++; return true; } public boolean contains(int o) { int insertionPoint = Arrays.binarySearch(store, 0, size, o); if(insertionPoint >= 0 ) return true;//Already in the set else return false; } @Override public boolean contains(Object o) { if(o != null && o instanceof Integer) return contains(((Integer)o).intValue()); else return false; } @Override public Iterator<Integer> iterator() { final Iterator<Integer> iterator = new Iterator<Integer>() { int index = 0; boolean canRemove = false; @Override public boolean hasNext() { return index < size; } @Override public Integer next() { if(!hasNext()) throw new NoSuchElementException("The whole set has been iterated"); canRemove = true; return store[index++]; } @Override public void remove() { if(!canRemove) throw new IllegalStateException("Can not remove, remove can only occur after a successful call to next"); for(int i = index; i < size; i++ ) store[i-1] = store[i]; index--; size--; canRemove = false; } }; return iterator; } @Override public int size() { return size; } @Override public void clear() { size = 0; } @Override public Comparator<? super Integer> comparator() { return new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }; } @Override public SortedSet<Integer> subSet(Integer fromElement, Integer toElement) { if(fromElement > toElement) throw new IllegalArgumentException("fromKey was > toKey"); return new IntSortedSubSet(fromElement, toElement-1, this); } @Override public SortedSet<Integer> headSet(Integer toElement) { return new IntSortedSubSet(Integer.MIN_VALUE, toElement-1, this); } @Override public SortedSet<Integer> tailSet(Integer fromElement) { return new IntSortedSubSet(fromElement, Integer.MAX_VALUE-1, this); } @Override public Integer first() { return store[0]; } @Override public Integer last() { return store[size-1]; } private class IntSortedSubSet extends AbstractSet<Integer> implements Serializable, SortedSet<Integer> { int minValidValue; int maxValidValue; IntSortedSet parent; public IntSortedSubSet(int minValidValue, int maxValidValue, IntSortedSet parent) { this.minValidValue = minValidValue; this.maxValidValue = maxValidValue; this.parent = parent; } @Override public boolean add(Integer e) { if(e == null) return false; if(e < minValidValue || e > maxValidValue) throw new IllegalArgumentException("You can not add to a sub-set view outside of the constructed range"); return parent.add(e); } public boolean contains(int o) { if(o < minValidValue || o > maxValidValue) return false; return parent.contains(o); } @Override public boolean contains(Object o) { if(o != null && o instanceof Integer) return contains(((Integer)o).intValue()); else return false; } @Override public Iterator<Integer> iterator() { int start = Arrays.binarySearch(store, 0, size, minValidValue); if (start < 0) start = (-(start) - 1); final int start_pos = start; final Iterator<Integer> iterator = new Iterator<Integer>() { int index = start_pos; boolean canRemove = false; @Override public boolean hasNext() { return index < size && store[index] <= maxValidValue; } @Override public Integer next() { if(!hasNext()) throw new NoSuchElementException("The whole set has been iterated"); canRemove = true; return store[index++]; } @Override public void remove() { if(!canRemove) throw new IllegalStateException("Can not remove, remove can only occur after a successful call to next"); for(int i = index; i < size; i++ ) store[i-1] = store[i]; index--; size--; canRemove = false; } }; return iterator; } @Override public int size() { int start = Arrays.binarySearch(store, 0, size, minValidValue); if (start < 0) start = (-(start) - 1); int end = Arrays.binarySearch(store, 0, size, maxValidValue); if (end < 0) end = (-(end) - 1); if(end < size && store[end] == maxValidValue)//should only happen once b/c we are a set end++; return end-start; } @Override public Comparator<? super Integer> comparator() { return parent.comparator(); } @Override public SortedSet<Integer> subSet(Integer fromElement, Integer toElement) { if(fromElement > toElement) throw new IllegalArgumentException("fromKey was > toKey"); return parent.subSet(Math.max(minValidValue, fromElement), Math.min(maxValidValue+1, toElement)); } @Override public SortedSet<Integer> headSet(Integer toElement) { return new IntSortedSubSet(Math.max(Integer.MIN_VALUE, minValidValue), Math.min(toElement-1, maxValidValue), parent); // return parent.headSet(Math.min(toElement, maxValidValue+1)); } @Override public SortedSet<Integer> tailSet(Integer fromElement) { return new IntSortedSubSet(Math.max(fromElement, minValidValue), Math.min(Integer.MAX_VALUE-1, maxValidValue), parent); // return parent.tailSet(Math.max(fromElement, minValidValue)); } @Override public Integer first() { int start = Arrays.binarySearch(store, 0, size, minValidValue); if (start < 0) start = (-(start) - 1); return store[start]; } @Override public Integer last() { int pos = Arrays.binarySearch(store, 0, size, maxValidValue); if (pos < 0) pos = (-(pos) - 1); //can end up at a pos out of valid range, so back up if needed while(pos >= 0 && store[pos] > maxValidValue) pos--; return store[pos]; } } }
11,707
27.766585
131
java
JSAT
JSAT-master/JSAT/src/jsat/utils/IterableIterator.java
package jsat.utils; import java.util.Iterator; /** * Convenience object for being able to use the for each loop on an iterator. * * @author Edward Raff */ public final class IterableIterator<T> implements Iterable<T> { private final Iterator<T> iterator; public IterableIterator(Iterator<T> iterator) { this.iterator = iterator; } @Override public Iterator<T> iterator() { return iterator; } }
457
16.615385
78
java
JSAT
JSAT-master/JSAT/src/jsat/utils/ListUtils.java
package jsat.utils; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import jsat.utils.random.RandomUtil; /** * * @author Edward Raff */ public class ListUtils { private ListUtils() { } /** * This method takes a list and breaks it into <tt>count</tt> lists backed by the original * list, with elements being equally spaced among the lists. The lists will be returned in * order of the consecutive values they represent in the source list. * <br><br><b>NOTE</b>: Because the implementation uses {@link List#subList(int, int) }, * changes to the returned lists will be reflected in the source list. * * @param <T> the type contained in the list * @param source the source list that will be used to back the <tt>count</tt> lists * @param count the number of lists to partition the source into. * @return a lists of lists, each of with the same size with at most a difference of 1. */ public static <T> List<List<T>> splitList(List<T> source, int count) { if(count <= 0) throw new RuntimeException("Chunks must be greater then 0, not " + count); List<List<T>> chunks = new ArrayList<List<T>>(count); int baseSize = source.size() / count; int remainder = source.size() % count; int start = 0; for(int i = 0; i < count; i++) { int end = start+baseSize; if(remainder-- > 0) end++; chunks.add(source.subList(start, end)); start = end; } return chunks; } /** * Returns a new unmodifiable view that is the merging of two lists * @param <T> the type the lists hold * @param left the left portion of the merged view * @param right the right portion of the merged view * @return a list view that contains bot the left and right lists */ public static <T> List<T> mergedView(final List<T> left, final List<T> right) { List<T> merged = new AbstractList<T>() { @Override public T get(int index) { if(index < left.size()) return left.get(index); else if(index-left.size() < right.size()) return right.get(index-left.size()); else throw new IndexOutOfBoundsException("List of lengt " + size() + " has no index " + index); } @Override public int size() { return left.size() + right.size(); } }; return merged; } /** * Swaps the values in the list at the given positions * @param list the list to perform the swap in * @param i the first position to swap * @param j the second position to swap */ public static void swap(List list, int i, int j) { Object tmp = list.get(i); list.set(i, list.get(j)); list.set(j, tmp); } /** * Collects all future values in a collection into a list, and returns said list. This method will block until all future objects are collected. * @param <T> the type of future object * @param futures the collection of future objects * @return a list containing the object from the future. * @throws ExecutionException * @throws InterruptedException */ public static <T> List<T> collectFutures(Collection<Future<T>> futures) throws ExecutionException, InterruptedException { ArrayList<T> collected = new ArrayList<T>(futures.size()); for (Future<T> future : futures) collected.add(future.get()); return collected; } /** * Adds values into the given collection using integer in the specified range and step size. * If the <tt>start</tt> value is greater or equal to the <tt>to</tt> value, nothing will * be added to the collection. * * @param c the collection to add to * @param start the first value to add, inclusive * @param to the last value to add, exclusive * @param step the step size. * @throws RuntimeException if the step size is zero or negative. */ public static void addRange(Collection<Integer> c, int start, int to, int step) { if(step <= 0) throw new RuntimeException("Would create an infinite loop"); for(int i = start; i < to; i+= step) c.add(i); } /** * Returns a list of integers with values in the given range * @param start the starting integer value (inclusive) * @param to the ending integer value (exclusive) * @return a list of integers containing the specified range of integers */ public static IntList range(int start, int to) { return range(start, to, 1); } /** * Returns a list of integers with values in the given range * @param start the starting integer value (inclusive) * @param to the ending integer value (exclusive) * @param step the step size between values * @return a list of integers containing the specified range of integers */ public static IntList range(int start, int to, int step) { if(to < start) throw new RuntimeException("starting index " + start + " must be less than or equal to ending index" + to); else if(step < 1) throw new RuntimeException("Step size must be a positive integer, not " + step); IntList toRet = new IntList((to-start)/step); for(int i = start; i < to; i+=step) toRet.add(i); return toRet; } /** * Obtains a random sample without replacement from a source list and places * it in the destination list. This is done without modifying the source list. * * @param <T> the list content type involved * @param source the source of values to randomly sample from * @param dest the list to store the random samples in. The list does not * need to be empty for the sampling to work correctly * @param samples the number of samples to select from the source * @param rand the source of randomness for the sampling * @throws IllegalArgumentException if the sample size is not positive or l * arger than the source population. */ public static <T> void randomSample(List<T> source, List<T> dest, int samples, Random rand) { randomSample((Collection<T>)source, dest, samples, rand); } /** * Obtains a random sample without replacement from a source collection and * places it in the destination collection. This is done without modifying * the source collection. <br> * This random sampling is oblivious to failures to add to a collection that * may occur, such as if the collection is a {@link Set} * * @param <T> the list content type involved * @param source the source of values to randomly sample from * @param dest the collection to store the random samples in. It does * not need to be empty for the sampling to work correctly * @param samples the number of samples to select from the source * @param rand the source of randomness for the sampling * @throws IllegalArgumentException if the sample size is not positive or l * arger than the source population. */ public static <T> void randomSample(Collection<T> source, Collection<T> dest, int samples, Random rand) { if(samples > source.size()) throw new IllegalArgumentException("Can not obtain a number of samples larger than the source population"); else if(samples <= 0) throw new IllegalArgumentException("Sample size must be positive"); //Use samples to keep track of how many more samples we need int remainingPopulation = source.size(); for(T member : source) { if(rand.nextInt(remainingPopulation) < samples) { dest.add(member); samples--; } remainingPopulation--; } } /** * Obtains a random sample without replacement from a source list and places * it in the destination list. This is done without modifying the source list. * * @param <T> the list content type involved * @param source the source of values to randomly sample from * @param dest the list to store the random samples in. The list does not * need to be empty for the sampling to work correctly * @param samples the number of samples to select from the source * @throws IllegalArgumentException if the sample size is not positive or l * arger than the source population. */ public static <T> void randomSample(List<T> source, List<T> dest, int samples) { randomSample(source, dest, samples, RandomUtil.getRandom()); } }
9,213
37.07438
149
java
JSAT
JSAT-master/JSAT/src/jsat/utils/LongDoubleMap.java
package jsat.utils; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.Set; import static jsat.utils.ClosedHashingUtil.*; /** * A hash map for storing the primitive types of long (as keys) to doubles * (as table). The implementation is based on Algorithm D (Open addressing with * double hashing) from Knuth's TAOCP page 528. * * @author Edward Raff */ public final class LongDoubleMap extends AbstractMap<Long, Double> { private float loadFactor; private int used = 0; private byte[] status; private long[] keys; private double[] table; public LongDoubleMap() { this(32); } public LongDoubleMap(int capacity) { this(capacity, 0.7f); } public LongDoubleMap(int capacity, float loadFactor) { if(capacity < 1) throw new IllegalArgumentException("Capacity must be a positive value, not " + capacity); if(loadFactor <= 0 || loadFactor >= 1 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("loadFactor must be in (0, 1), not " + loadFactor); this.loadFactor = loadFactor; int size = getNextPow2TwinPrime(Math.max(capacity, 3)); status = new byte[size]; keys = new long[size]; table = new double[size]; } @Override public int size() { return used; } @Override public Double put(Long key, Double value) { double prev = put(key.longValue(), value.doubleValue()); if(Double.isNaN(prev)) return null; else return prev; } public double put(long key, double value) { if(Double.isNaN(value)) throw new IllegalArgumentException("NaN is not an allowable value"); long pair_index = getIndex(key); int deletedIndex = (int) (pair_index >>> 32); int valOrFreeIndex = (int) (pair_index & INT_MASK); double prev; if(status[valOrFreeIndex] == OCCUPIED)//easy case { prev = table[valOrFreeIndex]; table[valOrFreeIndex] = value; return prev; } //else, not present prev = Double.NaN; int i = valOrFreeIndex; if(deletedIndex >= 0)//use occupied spot instead i = deletedIndex; status[i] = OCCUPIED; keys[i] = key; table[i] = value; used++; enlargeIfNeeded(); return prev; } /** * * @param key * @param delta * @return the new value stored for the given key */ public double increment(long key, double delta) { if(Double.isNaN(delta)) throw new IllegalArgumentException("NaN is not an allowable value"); long pair_index = getIndex(key); int deletedIndex = (int) (pair_index >>> 32); int valOrFreeIndex = (int) (pair_index & INT_MASK); if(status[valOrFreeIndex] == OCCUPIED)//easy case return (table[valOrFreeIndex] += delta); //else, not present double toReturn; int i = valOrFreeIndex; if(deletedIndex >= 0)//use occupied spot instead i = deletedIndex; status[i] = OCCUPIED; keys[i] = key; toReturn = table[i] = delta; used++; enlargeIfNeeded(); return toReturn; } @Override public Double remove(Object key) { if(key instanceof Long) { double oldValue = remove(((Long)key).longValue()); if(Double.isNaN(oldValue)) return null; else return oldValue; } return null; } /** * * @param key * @return the old value stored for this key, or {@link Double#NaN} if the * key was not present in the map */ public double remove(long key) { long pair_index = getIndex(key); int valOrFreeIndex = (int) (pair_index & INT_MASK); if(status[valOrFreeIndex] == EMPTY)//ret index is always EMPTY or OCCUPIED return Double.NaN; //else double toRet = table[valOrFreeIndex]; status[valOrFreeIndex] = DELETED; used--; return toRet; } @Override public void clear() { used = 0; Arrays.fill(status, EMPTY); } private void enlargeIfNeeded() { if(used < keys.length*loadFactor) return; //enlarge final byte[] oldSatus = status; final long[] oldKeys = keys; final double[] oldTable = table; int newSize = getNextPow2TwinPrime(status.length*3/2);//it will actually end up doubling in size since we have twin primes spaced that way status = new byte[newSize]; keys = new long[newSize]; table = new double[newSize]; used = 0; for(int oldIndex = 0; oldIndex < oldSatus.length; oldIndex++) if(oldSatus[oldIndex] == OCCUPIED) put(oldKeys[oldIndex], oldTable[oldIndex]); } @Override public boolean containsKey(Object key) { if(key instanceof Integer) return containsKey( ((Integer)key).longValue()); else if(key instanceof Long) return containsKey(((Long)key).longValue()); else return false; } public boolean containsKey(long key) { int index = (int) (getIndex(key) & INT_MASK); return status[index] == OCCUPIED;//would be FREE if we didn't have the key } /** * Gets the index of the given key. Based on that {@link #status} variable, * the index is either the location to insert OR the location of the key. * * This method returns 2 integer table in the long. The lower 32 bits are * the index that either contains the key, or is the first empty index. * * The upper 32 bits is the index of the first position marked as * {@link #DELETED} either {@link Integer#MIN_VALUE} if no position was * marked as DELETED while searching. * * @param key they key to search for * @return the mixed long containing the index of the first DELETED position * and the position that the key is in or the first EMPTY position found */ private long getIndex(long key) { long extraInfo = EXTRA_INDEX_INFO; //D1 final int hash = h(key); int i = hash % keys.length; //D2 int satus_i = status[i]; if((keys[i] == key && satus_i != DELETED) || satus_i == EMPTY) return extraInfo | i; if(extraInfo == EXTRA_INDEX_INFO && satus_i == DELETED) extraInfo = ((long)i) << 32; //D3 final int c = 1 + (hash % (keys.length -2)); while(true)//this loop will terminate { //D4 i -= c; if(i < 0) i += keys.length; //D5 satus_i = status[i]; if( (keys[i] == key && satus_i != DELETED) || satus_i == EMPTY) return extraInfo | i; if(extraInfo == EXTRA_INDEX_INFO && satus_i == DELETED) extraInfo = ((long)i) << 32; } } /** * Returns a non-negative hash value * @param key * @return */ public static int h(long key) { return (int) ((int) ( key >> 32) ^ Integer.reverseBytes((int) (key & 0xFFFFFFFF))) & 0x7fffffff; } @Override public Set<Entry<Long, Double>> entrySet() { return new EntrySet(this); } /** * EntrySet class supports remove operations */ private final class EntrySet extends AbstractSet<Entry<Long, Double>> { final LongDoubleMap parentRef; public EntrySet(LongDoubleMap parent) { this.parentRef = parent; } @Override public Iterator<Entry<Long, Double>> iterator() { //find the first starting inded int START = 0; while(START < status.length && status[START] != OCCUPIED) START++; if(START == status.length) return Collections.emptyIterator(); final int startPos = START; return new Iterator<Entry<Long, Double>>() { int pos = startPos; int prevPos = -1; @Override public boolean hasNext() { return pos < status.length; } @Override public Entry<Long, Double> next() { //final int make so that object remains good after we call next again final int oldPos = prevPos = pos++; //find next while (pos < status.length && status[pos] != OCCUPIED) pos++; //and return new object return new Entry<Long, Double>() { @Override public Long getKey() { return keys[oldPos]; } @Override public Double getValue() { return table[oldPos]; } @Override public Double setValue(Double value) { double old = table[oldPos]; table[oldPos] = value; return old; } }; } @Override public void remove() { //its ok to just call remove b/c nothing is re-ordered when we remove an element, we just set the status to DELETED parentRef.remove(keys[prevPos]); } }; } @Override public int size() { return used; } } }
10,448
27.785124
146
java
JSAT
JSAT-master/JSAT/src/jsat/utils/LongList.java
package jsat.utils; import java.io.Serializable; import java.util.*; /** * Provides a modifiable implementation of a List using an array of longs. This * provides considerable memory efficency improvements over using an * {@link ArrayList} to store longs. * Null is not allowed into the list. * * @author Edward Raff */ public class LongList extends AbstractList<Long> implements Serializable { private static final long serialVersionUID = 3060216677615816178L; private long[] array; private int end; private LongList(long[] array, int end) { this.array = array; this.end = end; } /** * Creates a new LongList */ public LongList() { this(10); } @Override public void clear() { end = 0; } /** * Creates a new LongList with the given initial capacity * @param capacity the starting internal storage space size */ public LongList(int capacity) { array = new long[capacity]; end = 0; } public LongList(Collection<Long> c) { this(c.size()); addAll(c); } /** * Operates exactly as {@link #set(int, java.lang.Long) } * @param index the index to set * @param element the value to set * @return the previous value at the index */ public long set(int index, long element) { boundsCheck(index); long prev = array[index]; array[index] = element; return prev; } @Override public Long set(int index, Long element) { return set(index, element.longValue()); } /** * Operates exactly as {@link #add(int, java.lang.Long) } * @param index the index to add the value into * @param element the value to add */ public void add(int index, long element) { if (index == size())//special case, just appending { add(element); } else { boundsCheck(index); enlargeIfNeeded(1); System.arraycopy(array, index, array, index+1, end-index); array[index] = element; end++; } } @Override public void add(int index, Long element) { add(index, element.longValue()); } /** * Operates exactly as {@link #add(java.lang.Long) } * @param e the value to add * @return true if it was added, false otherwise */ public boolean add(long e) { enlargeIfNeeded(1); array[end++] = e; return true; } @Override public boolean add(Long e) { if(e == null) return false; return add(e.longValue()); } /** * Operates exactly as {@link #get(int) } * @param index the index of the value to get * @return the value at the index */ public long getL(int index) { boundsCheck(index); return array[index]; } @Override public Long get(int index) { return getL(index); } private void boundsCheck(int index) throws IndexOutOfBoundsException { if(index >= end) throw new IndexOutOfBoundsException("List of of size " + size() + ", index requested was " + index); } @Override public int size() { return end; } @Override public Long remove(int index) { if(index < 0 || index > size()) throw new IndexOutOfBoundsException("Can not remove invalid index " + index); long removed = array[index]; for(int i = index; i < end-1; i++) array[i] = array[i+1]; end--; return removed; } private void enlargeIfNeeded(int i) { while(end+i > array.length) array = Arrays.copyOf(array, Math.max(array.length*2, 8)); } /** * Creates and returns a view of the given long array that * requires only a small object allocation. * * @param array the array to wrap into a list * @param length the number of values of the array to use, starting from zero * @return a list view of the array */ public static List<Long> view(long[] array, int length) { return new LongList(array, length); } }
4,326
22.263441
112
java
JSAT
JSAT-master/JSAT/src/jsat/utils/ModifiableCountDownLatch.java
package jsat.utils; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicInteger; /** * Provides a {@link CountDownLatch} that can have the number of counts increased as well as decreased. * @author Edward Raff */ public class ModifiableCountDownLatch { private Semaphore awaitSemaphore; private AtomicInteger count; public ModifiableCountDownLatch(int count) { this.count = new AtomicInteger(count); awaitSemaphore = new Semaphore(0); } /** * Waits until the count gets reduced to zero, and then all threads waiting will get to run. * * @throws InterruptedException */ public void await() throws InterruptedException { awaitSemaphore.acquire(); awaitSemaphore.release(); } /** * Decrements the counter. Allowing threads that have called {@link #await() } to run once the count reaches zero. */ public void countDown() { if(count.get() == 0) return; else if( count.decrementAndGet() == 0) awaitSemaphore.release(); } /** * Increments the count. Once the count has reached zero once, incrementing the count back above zero will have no affect. */ public void countUp() { count.addAndGet(1); } }
1,380
25.056604
127
java
JSAT
JSAT-master/JSAT/src/jsat/utils/Pair.java
package jsat.utils; import java.util.Objects; /** * A simple object to hold a pair of values * @author Edward Raff */ public class Pair<X, Y> { private X firstItem; private Y secondItem; public Pair(X firstItem, Y secondItem) { setFirstItem(firstItem); setSecondItem(secondItem); } public void setFirstItem(X firstItem) { this.firstItem = firstItem; } public X getFirstItem() { return firstItem; } public void setSecondItem(Y secondItem) { this.secondItem = secondItem; } public Y getSecondItem() { return secondItem; } @Override public String toString() { return "(" + firstItem + ", " + secondItem + ")"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Pair<?, ?> other = (Pair<?, ?>) obj; if (!Objects.equals(this.firstItem, other.firstItem)) return false; if (!Objects.equals(this.secondItem, other.secondItem)) return false; return true; } @Override public int hashCode() { int hash = 3; hash = 41 * hash + Objects.hashCode(this.firstItem); hash = 41 * hash + Objects.hashCode(this.secondItem); return hash; } }
1,475
18.945946
63
java
JSAT
JSAT-master/JSAT/src/jsat/utils/PairedReturn.java
package jsat.utils; /** * * Utility class that allows the returning of 2 different objects as one. * * @author Edwartd Raff */ public class PairedReturn<T, V> { private final T firstItem; private final V secondItem; public PairedReturn(T t, V v) { this.firstItem = t; this.secondItem = v; } /** * Returns the first object stored. * @return the first object stored */ public T getFirstItem() { return firstItem; } /** * Returns the second object stored * @return the second object stored */ public V getSecondItem() { return secondItem; } @Override public String toString() { return "(" + getFirstItem() + ", " + getSecondItem() + ")"; } }
790
16.577778
74
java
JSAT
JSAT-master/JSAT/src/jsat/utils/PoisonRunnable.java
package jsat.utils; import java.util.concurrent.BlockingQueue; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.logging.Level; import java.util.logging.Logger; /** * A helper class for using the reader / writer model to implement parallel algorithms. * When using the a {@link BlockingQueue}, <tt>null</tt> is an invalid value. However, * if several threads have been started that are simply reading from the queue for * jobs, we want to let the threads know when to stop. Polling can not be used since * the {@link BlockingQueue#take() } operations blocks until a value is added. If * the queue is a queue of {@link Runnable} jobs, this class solves the problem. * An <tt>instanceof</tt> check can be done on the returned runnable. If it is a poisoned * one, the worker knows to stop consuming and terminate. * <br><br> * By default, the {@link #run() } method does not perform any action. The * poison runnable can be used to perform ending clean up work, such as posting * to a semaphore, by giving the work job to the * {@link #PoisonRunnable(java.lang.Runnable) } constructor. The runnable given * will be run when the Poison runnable's run method is called. * * @author Edward Raff */ public final class PoisonRunnable implements Runnable { private Runnable lastStep; private CountDownLatch latch; private CyclicBarrier barrier; /** * Creates a new PoisonRunnable that will run the given runnable when it is called. * @param lastStep the runnable to call when this runnable is finally called. */ public PoisonRunnable(Runnable lastStep) { this.lastStep = lastStep; } /** * Creates a new PoisonRunnable that will call the * {@link CountDownLatch#countDown() } method on the given latch when its * run method is finally called. * * @param latch the latch to decrement */ public PoisonRunnable(CountDownLatch latch) { this.latch = latch; } /** * Creates a new PoisonRunnable that will call the * {@link CyclicBarrier#await() } method of the given barrier when its run * method is finally called. * @param barrier the barrier to wait on. */ public PoisonRunnable(CyclicBarrier barrier) { this.barrier = barrier; } /** * Creates a new PoisonRunnable that will do nothing when its run method is called. */ public PoisonRunnable() { } @Override public void run() { try { if(lastStep != null) lastStep.run(); if(latch != null) latch.countDown(); if(barrier != null) barrier.await(); } catch (InterruptedException ex) { Logger.getLogger(PoisonRunnable.class.getName()).log(Level.SEVERE, null, ex); } catch (BrokenBarrierException ex) { Logger.getLogger(PoisonRunnable.class.getName()).log(Level.SEVERE, null, ex); } } }
3,171
31.367347
89
java
JSAT
JSAT-master/JSAT/src/jsat/utils/ProbailityMatch.java
package jsat.utils; import java.io.Serializable; /** * Class allows the arbitrary association of some object type with a probability. * @author Edward Raff */ public class ProbailityMatch<T> implements Comparable<ProbailityMatch<T>>, Serializable { private static final long serialVersionUID = -1544116376166946986L; private double probability; private T match; public ProbailityMatch(double probability, T match) { this.probability = probability; this.match = match; } public int compareTo(ProbailityMatch t) { return new Double(probability).compareTo(t.probability); } public double getProbability() { return probability; } public void setProbability(double probability) { this.probability = probability; } public T getMatch() { return match; } public void setMatch(T match) { this.match = match; } }
951
18.833333
87
java
JSAT
JSAT-master/JSAT/src/jsat/utils/QuickSort.java
package jsat.utils; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Provides implementations of quicksort. This is for use to obtain explicitly * desired behavior, as well as aovid overhead by explicitly allowing extra * Lists when sorting that are swapped when the array/list being sorted is * swapped. <br> * <br> * This class exist solely for performance reasons. * * @author Edward Raff */ public class QuickSort { private QuickSort() { } private static int med3(double[] x, int a, int b, int c) { return (x[a] < x[b] ? (x[b] < x[c] ? b : x[a] < x[c] ? c : a) : (x[b] > x[c] ? b : x[a] > x[c] ? c : a)); } private static int med3(float[] x, int a, int b, int c) { return (x[a] < x[b] ? (x[b] < x[c] ? b : x[a] < x[c] ? c : a) : (x[b] > x[c] ? b : x[a] > x[c] ? c : a)); } protected static void vecswap(double[] x, int a, int b, int n) { for (int i = 0; i < n; i++) swap(x, a++, b++); } protected static void vecswap(float[] x, int a, int b, int n) { for (int i = 0; i < n; i++) swap(x, a++, b++); } private static void vecswap(double[] x, int a, int b, int n, Collection<List<?>> paired) { for (int i = 0; i < n; i++) { for (List l : paired) Collections.swap(l, a, b); swap(x, a++, b++); } } private static void vecswap(float[] x, int a, int b, int n, Collection<List<?>> paired) { for (int i = 0; i < n; i++) { for (List l : paired) Collections.swap(l, a, b); swap(x, a++, b++); } } public static void swap(double[] array, int i, int j) { double tmp = array[i]; array[i] = array[j]; array[j] = tmp; } public static void swap(float[] array, int i, int j) { float tmp = array[i]; array[i] = array[j]; array[j] = tmp; } /** * Conditional swap, only swaps the values if array[i] &gt; array[j] * @param array the array to potentially swap values in * @param i the 1st index * @param j the 2nd index */ public static void swapC(double[] array, int i, int j) { double tmp_i= array[i]; double tmp_j = array[j]; if(tmp_i > tmp_j) { array[i] = tmp_j; array[j] = tmp_i; } } /** * * @param array the array to swap values in * @param i the 1st index * @param j the 2nd index * @param paired a collection of lists, every list will have its indices swapped as well */ public static void swap(double[] array, int i, int j, Collection<List<?>> paired) { double t = array[i]; array[i] = array[j]; array[j] = t; for(List l : paired) Collections.swap(l, i, j); } /** * * @param array the array to swap values in * @param i the 1st index * @param j the 2nd index * @param paired a collection of lists, every list will have its indices swapped as well */ public static void swap(float[] array, int i, int j, Collection<List<?>> paired) { float t = array[i]; array[i] = array[j]; array[j] = t; for(List l : paired) Collections.swap(l, i, j); } /** * Performs sorting based on the double values natural comparator. * {@link Double#NaN} values will not be handled appropriately. * * @param x the array to sort * @param start the starting index (inclusive) to sort * @param end the ending index (exclusive) to sort */ public static void sort(double[] x, int start, int end) { int a = start; int n = end-start; if (n < 7)/* Insertion sort on smallest arrays */ { insertionSort(x, a, end); return; } int pm = a + (n/2); /* Small arrays, middle element */ if (n > 7) { int pl = a; int pn = a + n - 1; if (n > 40) /* Big arrays, pseudomedian of 9 */ { int s = n / 8; pl = med3(x, pl, pl + s, pl + 2 * s); pm = med3(x, pm - s, pm, pm + s); pn = med3(x, pn - 2 * s, pn - s, pn); } pm = med3(x, pl, pm, pn); /* Mid-size, med of 3 */ } double pivotValue = x[pm]; int pa = a, pb = pa, pc = end - 1, pd = pc; while (true) { while (pb <= pc && x[pb] <= pivotValue) { if (x[pb] == pivotValue) swap(x, pa++, pb); pb++; } while (pc >= pb && x[pc] >= pivotValue) { if (x[pc] == pivotValue) swap(x, pc, pd--); pc--; } if (pb > pc) break; swap(x, pb++, pc--); } int s; int pn = end; s = Math.min(pa - a, pb - pa); vecswap(x, a, pb - s, s); s = Math.min(pd - pc, pn - pd - 1); vecswap(x, pb, pn - s, s); //recurse if ((s = pb - pa) > 1) sort(x, a, a+s); if ((s = pd - pc) > 1) sort(x, pn - s, pn); } /** * * @param x * @param start inclusive * @param end exclusive */ public static void insertionSort(double[] x, int start, int end) { for (int i = start; i < end; i++) for (int j = i; j > start && x[j - 1] > x[j]; j--) swap(x, j, j - 1); } /** * Performs sorting based on the double values natural comparator. * {@link Double#NaN} values will not be handled appropriately. * * @param x the array to sort * @param start the starting index (inclusive) to sort * @param end the ending index (exclusive) to sort * @param paired a collection of lists, every list will have its indices swapped as well */ public static void sort(double[] x, int start, int end, Collection<List<?>> paired) { int a = start; int n = end-start; if (n < 7)/* Insertion sort on smallest arrays */ { for (int i = a; i < end; i++) for (int j = i; j > a && x[j - 1] > x[j]; j--) swap(x, j, j - 1, paired); return; } int pm = a + (n/2); /* Small arrays, middle element */ if (n > 7) { int pl = a; int pn = a + n - 1; if (n > 40) /* Big arrays, pseudomedian of 9 */ { int s = n / 8; pl = med3(x, pl, pl + s, pl + 2 * s); pm = med3(x, pm - s, pm, pm + s); pn = med3(x, pn - 2 * s, pn - s, pn); } pm = med3(x, pl, pm, pn); /* Mid-size, med of 3 */ } double pivotValue = x[pm]; int pa = a, pb = pa, pc = end - 1, pd = pc; while (true) { while (pb <= pc && x[pb] <= pivotValue) { if (x[pb] == pivotValue) swap(x, pa++, pb, paired); pb++; } while (pc >= pb && x[pc] >= pivotValue) { if (x[pc] == pivotValue) swap(x, pc, pd--, paired); pc--; } if (pb > pc) break; swap(x, pb++, pc--, paired); } int s; int pn = end; s = Math.min(pa - a, pb - pa); vecswap(x, a, pb - s, s, paired); s = Math.min(pd - pc, pn - pd - 1); vecswap(x, pb, pn - s, s, paired); //recurse if ((s = pb - pa) > 1) sort(x, a, a+s, paired); if ((s = pd - pc) > 1) sort(x, pn - s, pn, paired); } /** * Performs sorting based on the double values natural comparator. * {@link Double#NaN} values will not be handled appropriately. * * @param x the array to sort * @param start the starting index (inclusive) to sort * @param end the ending index (exclusive) to sort * @param paired a collection of lists, every list will have its indices swapped as well */ public static void sort(float[] x, int start, int end, Collection<List<?>> paired) { int a = start; int n = end-start; if (n < 7)/* Insertion sort on smallest arrays */ { for (int i = a; i < end; i++) for (int j = i; j > a && x[j - 1] > x[j]; j--) swap(x, j, j - 1, paired); return; } int pm = a + (n/2); /* Small arrays, middle element */ if (n > 7) { int pl = a; int pn = a + n - 1; if (n > 40) /* Big arrays, pseudomedian of 9 */ { int s = n / 8; pl = med3(x, pl, pl + s, pl + 2 * s); pm = med3(x, pm - s, pm, pm + s); pn = med3(x, pn - 2 * s, pn - s, pn); } pm = med3(x, pl, pm, pn); /* Mid-size, med of 3 */ } double pivotValue = x[pm]; int pa = a, pb = pa, pc = end - 1, pd = pc; while (true) { while (pb <= pc && x[pb] <= pivotValue) { if (x[pb] == pivotValue) swap(x, pa++, pb, paired); pb++; } while (pc >= pb && x[pc] >= pivotValue) { if (x[pc] == pivotValue) swap(x, pc, pd--, paired); pc--; } if (pb > pc) break; swap(x, pb++, pc--, paired); } int s; int pn = end; s = Math.min(pa - a, pb - pa); vecswap(x, a, pb - s, s, paired); s = Math.min(pd - pc, pn - pd - 1); vecswap(x, pb, pn - s, s, paired); //recurse if ((s = pb - pa) > 1) sort(x, a, a+s, paired); if ((s = pd - pc) > 1) sort(x, pn - s, pn, paired); } }
10,468
27.682192
92
java
JSAT
JSAT-master/JSAT/src/jsat/utils/RunnableConsumer.java
package jsat.utils; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.logging.Level; import java.util.logging.Logger; /** * The RunnableConsumer is meant to be used in conjunction with * {@link PoisonRunnable} and an {@link ExecutorService} to implement a * consumer / produce model. It will consume runnables from a queue and * immediately call its run method. Termination occurs when a * {@link PoisonRunnable} is encountered, after it's run method is called. * * @author Edward Raff */ public class RunnableConsumer implements Runnable { final private BlockingQueue<Runnable> jobQueue; /** * Creates a new runnable that will consume and run other runnables. * @param jobQueue the queue from which to obtain runnable objects. */ public RunnableConsumer(BlockingQueue<Runnable> jobQueue) { this.jobQueue = jobQueue; } @Override public void run() { while(true) { try { Runnable toRun = jobQueue.take(); toRun.run(); if(toRun instanceof PoisonRunnable) return; } catch (InterruptedException ex) { Logger.getLogger(RunnableConsumer.class.getName()).log(Level.SEVERE, null, ex); } } } }
1,411
25.641509
95
java
JSAT
JSAT-master/JSAT/src/jsat/utils/SimpleList.java
package jsat.utils; import java.io.Serializable; import java.util.AbstractList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.ConcurrentModificationException; /** * An alternative implementation of an {@link ArrayList}. The behavior is the * same and performance is almost exactly the same. The major difference is * SimpleList does not perform the same checks on modification as ArrayList, and * will never throw a {@link ConcurrentModificationException}. This means * SimpleList can have unexpected behavior when asked in a multi threaded * environment, but can also be used by multiple threads where an ArrayList * could not be. * * @author Edward Raff */ public class SimpleList<E> extends AbstractList<E> implements Serializable { private static final long serialVersionUID = -1641584937585415217L; private Object[] source; private int size; /** * Creates a new SimpleList * @param initialCapacity the initial storage size of the list */ public SimpleList(int initialCapacity) { source = new Object[initialCapacity]; size = 0; } /** * Creates a new SimpleList */ public SimpleList() { this(50); } /** * Creates a new SimpleList * @param c the collection of elements to place into the list. */ public SimpleList(Collection<? extends E> c) { this(c.size()); this.addAll(c); } @Override public E get(int index) { if(index >= size()) throw new IndexOutOfBoundsException(); return (E) source[index]; } @Override public int size() { return size; } @Override public void add(int index, E element) { if(index > size()) throw new IndexOutOfBoundsException(); if(size == source.length) source = Arrays.copyOf(source, size*2); if(index == size) source[size++] = element; else { System.arraycopy(source, index, source, index+1, size-index); source[index] = element; size++; } } @Override public E remove(int index) { if(index >= size()) throw new IndexOutOfBoundsException(); E removed = (E) source[index]; System.arraycopy(source, index+1, source, index, size-index-1); size--; return removed; } @Override public E set(int index, E element) { if(index >= size()) throw new IndexOutOfBoundsException(); E prev = (E) source[index]; source[index] = element; return prev; } }
2,737
24.119266
80
java
JSAT
JSAT-master/JSAT/src/jsat/utils/SortedArrayList.java
package jsat.utils; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; /** * * @author Edward Raff */ public class SortedArrayList<T extends Comparable<T>> extends ArrayList<T> implements Serializable { private static final long serialVersionUID = -8728381865616791954L; public SortedArrayList(Collection<? extends T> c) { super(c); Collections.sort(this); } public SortedArrayList(int initialCapacity) { super(initialCapacity); } public SortedArrayList() { super(); } @Override public boolean add(T e) { if(isEmpty()) { return super.add(e); } else { int ind = Collections.binarySearch(this, e); if (ind < 0) ind = -(ind + 1);//Now it is the point where it should be inserted if (ind > size()) super.add(e); else super.add(ind, e); return true; } } @Override public void add(int index, T element) { this.add(element); } public T first() { if(isEmpty()) return null; return get(0); } public T last() { if(isEmpty()) return null; return get(size()-1); } @Override public boolean addAll(Collection<? extends T> c) { if(c.isEmpty()) return false; else if(c.size() > this.size()*3/2)//heuristic when is it faster to just add them all and sort the whole thing? { boolean did = super.addAll(c); if(did) Collections.sort(this); return did; } else { for(T t : c) this.add(t); return true; } } @Override public boolean addAll(int index, Collection<? extends T> c) { return this.addAll(c); } }
2,028
18.892157
119
java
JSAT
JSAT-master/JSAT/src/jsat/utils/StringUtils.java
package jsat.utils; /** * * @author Edward Raff */ public class StringUtils { public static int parseInt(CharSequence s, int start, int end, int radix) { boolean negative = false; int val = 0; for(int i = start; i < end; i++) { char c = s.charAt(i); if (c == '-') if (i == start) negative = true; else throw new NumberFormatException("Negative sign did not occur at begining of sequence"); else if (c == '+') if (i == start) negative = false;//do nothing really else throw new NumberFormatException("Positive sign did not occur at begining of sequence"); else { int digit = Character.digit(c, radix); if(digit < 0) throw new NumberFormatException("Non digit character '" + c + "' encountered"); val *= radix; val += digit; } } if(negative) return -val; else return val; } public static int parseInt(CharSequence s, int start, int end) { return parseInt(s, start, end, 10); } //Float/Double to String follows algo laid out here http://krashan.ppa.pl/articles/stringtofloat/ private enum States { /** * Either '+' or '-', or not sign present */ SIGN, /** * skipping leading zeros in the integer part of mantissa */ LEADING_ZEROS_MANTISSA, /** * reading leading zeros in the fractional part of mantissa. */ LEADING_ZEROS_FRAC, /** * reading integer part of mantissa */ MANTISSA_INT_PART, /** * reading fractional part of mantissa. */ MANTISSA_FRAC_PART, /** * reading sign of exponent */ EXPO_SIGN, EXPO_LEADING_ZERO, /** * reading exponent digits */ EXPO, } public static double parseDouble(CharSequence s, int start, int end) { //hack check for NaN at the start if((end-start) == 3 && s.length() >= end && s.charAt(start) == 'N') if(s.subSequence(start, end).toString().equals("NaN")) return Double.NaN; States state = States.SIGN; int pos = start; int sign = 1; long mantissa = 0; /** * Mantissa can only be incremented 18 times, then any more will * overflow (2^63-1 ~= 9.2* 10^18 */ byte mantisaIncrements = 0; int implicitExponent = 0; //used for (val)e(val) case int expoSign = 1; int explicitExponent = 0; while(pos < end)//run the state machine { char c = s.charAt(pos); switch(state) { case SIGN: if (c == '-') { sign = -1; pos++; } else if(c == '+') pos++; else if (!Character.isDigit(c) && c != '.')//not a '-', '+', '.', or digit, so error throw new NumberFormatException(); state = States.LEADING_ZEROS_MANTISSA; continue; case LEADING_ZEROS_MANTISSA: if(c == '0') pos++; else if(c == '.') { pos++; state = States.LEADING_ZEROS_FRAC; } else if (Character.isDigit(c)) state = States.MANTISSA_INT_PART; else if(c == 'e' || c == 'E')//could be something like +0e0 state = States.MANTISSA_FRAC_PART;//this is where that case is handeled else throw new NumberFormatException(); continue; case LEADING_ZEROS_FRAC: if(c == '0') { pos++; implicitExponent--; } else if(Character.isDigit(c)) state = States.MANTISSA_FRAC_PART; else if(c == 'e' || c == 'E')//could be something like +0.000e0 state = States.MANTISSA_FRAC_PART;//this is where that case is handeled else throw new NumberFormatException(); continue; case MANTISSA_INT_PART: if (c == '.') { pos++; state = States.MANTISSA_FRAC_PART; } else if (Character.isDigit(c)) { if(mantisaIncrements < 18) { mantissa = mantissa * 10 + Character.digit(c, 10); mantisaIncrements++; } else//we are going to lose these, compencate with an implicit *= 10 implicitExponent++; pos++; } else state = States.MANTISSA_FRAC_PART; //if we hit a invalid char it will get erred on in FRAC_PART continue; case MANTISSA_FRAC_PART: if (Character.isDigit(c)) { if (mantisaIncrements < 18) { mantissa = mantissa * 10 + Character.digit(c, 10); implicitExponent--; mantisaIncrements++; } else//we are going to lose these { //we would have incresed the implicit exponent //but we would have subtracted if we could //so do nothing } pos++; } else if (c == 'e' || c == 'E') { pos++; state = States.EXPO_SIGN; } else throw new NumberFormatException(); continue; case EXPO_SIGN: if (c == '-') { expoSign = -1; pos++; } else if(c == '+') pos++; else if (!Character.isDigit(c))//not a '-', '+', or digit, so error throw new NumberFormatException(); state = States.EXPO_LEADING_ZERO; continue; case EXPO_LEADING_ZERO: if(c == '0') { pos++; } else if(Character.isDigit(c)) state = States.EXPO; else throw new NumberFormatException(); continue; case EXPO: if(Character.isDigit(c)) { explicitExponent = explicitExponent * 10 + Character.digit(c, 10); pos++; } else throw new NumberFormatException(); continue; } } int finalExpo = expoSign*explicitExponent + implicitExponent; if(mantissa == 0)//easiest case! if (sign == -1) return -0.0; else return 0.0; if(finalExpo == 0)//easy case! return sign*mantissa; return sign * (mantissa*Math.pow(10, finalExpo)); } }
8,348
33.217213
107
java
JSAT
JSAT-master/JSAT/src/jsat/utils/SystemInfo.java
package jsat.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.logging.Level; import java.util.logging.Logger; /** * * This class provides Static system information that may be useful for * algorithms that want to adjust their behavior based on the system's * hardware information. All information supposes that hardware is * consistent, ie: all memory installed is of the same type and all * CPUs installed are the same model and stepping. * * @author Edward Raff */ public class SystemInfo { public final static int LogicalCores = Runtime.getRuntime().availableProcessors(); public final static String OS_String = System.getProperty("os.name"); /** * * @return true if this machine is running some version of Windows */ public static boolean isWindows() { return OS_String.contains("Win"); } /** * * @return true is this machine is running some version of Mac OS X */ public static boolean isMac() { return OS_String.contains("Mac"); } /** * * @return true if this machine is running some version of Linux */ public static boolean isLinux() { return OS_String.contains("Lin"); } /** * Contains the per core L2 Cache size. The value returned will be '0' if there was an error obtaining the size */ public final static int L2CacheSize; static { int sizeToUse = 0; try { if(isWindows()) { String output = null; try { //On windows, the comand line tool WMIC is used, see http://msdn.microsoft.com/en-us/library/aa394531(v=vs.85).aspx Process pr = Runtime.getRuntime().exec("wmic cpu get L2CacheSize, NumberOfCores"); /* * Will print out the total L2 Cache for each CPU, and the number of cores - something like this (2 CPUs) * L2CacheSize NumberOfCores * 1024 4 * 1024 4 */ BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; while( (line = br.readLine()) != null) sb.append(line).append("\n"); output = sb.toString(); } catch (IOException ex) { Logger.getLogger(SystemInfo.class.getName()).log(Level.WARNING, null, ex); } output = output.replaceAll("L2CacheSize\\s+NumberOfCores", "").trim();//Remove header if(output.indexOf("\n") > 0)//Multi line is bad! output = output.substring(0, output.indexOf("\n")).trim();//Get first line String[] vals = output.split("\\s+");//Seperate into 2 seperate numbers, first is total L2 cahce, 2nd is # CPU cores sizeToUse = (Integer.valueOf(vals[0]) / Integer.valueOf(vals[1]))*1024 ; //the value is in KB, we want it in bytes } else if(isLinux()) { String output = null; try { //Nix, use /proc/cpuinfo Process pr = Runtime.getRuntime().exec("cat /proc/cpuinfo"); BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = null; while( (line = br.readLine()) != null) if(line.startsWith("cache size") && output == null)//We just need one line that says "cache size" output = line; } catch (IOException ex) { //This can fail on Google App Engine b/c we aren't allowed to run other programs. So lets check if thats the case String appEngineVersion = System.getProperty("com.google.appengine.runtime.version"); if(appEngineVersion == null)//not in app engine, give out a warning Logger.getLogger(SystemInfo.class.getName()).log(Level.WARNING, null, ex); //else, lets not do anything stupid } output = output.substring(output.indexOf(":")+1); String[] vals = output.trim().split(" "); int size = Integer.parseInt(vals[0]); if(vals[1].equals("KB")) size*=1024; else if(vals[1].equals("MB")) size*=1024*1024; sizeToUse = size; } else if(isMac()) { String output = null; try { //Nix, use /proc/cpuinfo Process pr = Runtime.getRuntime().exec("sysctl -a hw"); BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = null; while( (line = br.readLine()) != null) { if(line.contains("l1icachesize") && output == null)//We just need one line that says "cache size" output = line; } } catch (IOException ex) { Logger.getLogger(SystemInfo.class.getName()).log(Level.WARNING, null, ex); } String[] vals = output.split("\\s+"); sizeToUse = Integer.parseInt(vals[1]); } else//We dont know what we are running on. sizeToUse = 0; } catch(Exception ex) { //make sure we at least set the default by avoiding any possible weird exception } //TODO is there a good way to approximate this? if(sizeToUse == 0)//we couldn't set it for some reason? 256KB seems to be a good default (modern P4 to i7s use this size, Anthalon 64 used this as the min size too) sizeToUse = 256*1024; else if(sizeToUse < 128*1024)//A weird value? 128KB would be very small for an L2 - the P2 had more than that! sizeToUse = 128*1024; L2CacheSize = sizeToUse; } }
6,559
36.701149
172
java
JSAT
JSAT-master/JSAT/src/jsat/utils/Tuple3.java
/* * Copyright (C) 2016 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.utils; import java.util.Arrays; /** * * @author Edward Raff * @param <X> * @param <Y> * @param <Z> */ public class Tuple3<X, Y, Z> { X x; Y y; Z z; public Tuple3(X x, Y y, Z z) { this.x = x; this.y = y; this.z = z; } public Tuple3() { } public void setX(X x) { this.x = x; } public void setY(Y y) { this.y = y; } public void setZ(Z z) { this.z = z; } public X getX() { return x; } public Y getY() { return y; } public Z getZ() { return z; } @Override public String toString() { return "(" + x +", " + y + ", " + z + ")"; } @Override public boolean equals(Object obj) { if(obj instanceof Tuple3) { Tuple3 other = (Tuple3) obj; return this.x.equals(other.x) && this.y.equals(other.y) && this.z.equals(other.z); } return false; } @Override public int hashCode() { return Arrays.hashCode(new int[]{x.hashCode(), y.hashCode(), z.hashCode()}); } }
1,869
17.888889
94
java
JSAT
JSAT-master/JSAT/src/jsat/utils/UnionFind.java
/* * Copyright (C) 2016 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.utils; /** * * @author Edward Raff */ public class UnionFind<X> { protected UnionFind<X> parent; /** * Really the depth of the tree, but terminology usually is rank */ protected int rank; protected X item; public UnionFind() { this(null); } public X getItem() { return item; } public UnionFind(X item) { this.parent = this;//yes, this is intentional. this.rank = 0; this.item = item; } public UnionFind<X> find() { if(this.parent != this) this.parent = this.parent.find(); return this.parent; } public void union(UnionFind<X> y) { UnionFind<X> xRoot = this.find(); UnionFind<X> yRoot = y.find(); if (xRoot == yRoot) return; // x and y are not already in same set. Merge them. if (xRoot.rank < yRoot.rank) xRoot.parent = yRoot; else if (xRoot.rank > yRoot.rank) yRoot.parent = xRoot; else { yRoot.parent = xRoot; xRoot.rank = xRoot.rank + 1; } } }
1,860
23.813333
72
java
JSAT
JSAT-master/JSAT/src/jsat/utils/concurrent/AtomicDouble.java
package jsat.utils.concurrent; import java.util.concurrent.atomic.AtomicLong; import static java.lang.Double.doubleToRawLongBits; import static java.lang.Double.longBitsToDouble; import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleUnaryOperator; import java.util.function.LongUnaryOperator; /** * * @author Edward Raff */ final public class AtomicDouble { private final AtomicLong base; public AtomicDouble(double value) { base = new AtomicLong(); set(value); } public void set(double val) { base.set(Double.doubleToRawLongBits(val)); } public double get() { return longBitsToDouble(base.get()); } public double getAndAdd(double delta) { while(true) { double orig = get(); double newVal = orig + delta; if(compareAndSet(orig, newVal)) return orig; } } /** * Atomically adds the given value to the current value. * * @param delta the value to add * @return the updated value */ public final double addAndGet(double delta) { while(true) { double orig = get(); double newVal = orig + delta; if (compareAndSet(orig, newVal)) return newVal; } } /** * Atomically updates the current value with the results of applying the * given function, returning the updated value. The function should be * side-effect-free, since it may be re-applied when attempted updates fail * due to contention among threads. * * @param updateFunction a side-effect-free function * @return the updated value */ public final double updateAndGet(DoubleUnaryOperator updateFunction) { double prev, next; do { prev = get(); next = updateFunction.applyAsDouble(prev); } while (!compareAndSet(prev, next)); return next; } /** * Atomically updates the current value with the results of applying the * given function, returning the previous value. The function should be * side-effect-free, since it may be re-applied when attempted updates fail * due to contention among threads. * * @param updateFunction a side-effect-free function * @return the previous value */ public final double getAndUpdate(DoubleUnaryOperator updateFunction) { double prev, next; do { prev = get(); next = updateFunction.applyAsDouble(prev); } while (!compareAndSet(prev, next)); return prev; } /** * Atomically updates the current value with the results of * applying the given function to the current and given values, * returning the previous value. The function should be * side-effect-free, since it may be re-applied when attempted * updates fail due to contention among threads. The function * is applied with the current value as its first argument, * and the given update as the second argument. * * @param x the update value * @param accumulatorFunction a side-effect-free function of two arguments * @return the previous value */ public final double getAndAccumulate(double x, DoubleBinaryOperator accumulatorFunction) { double prev, next; do { prev = get(); next = accumulatorFunction.applyAsDouble(prev, x); } while (!compareAndSet(prev, next)); return prev; } /** * Atomically updates the current value with the results of * applying the given function to the current and given values, * returning the updated value. The function should be * side-effect-free, since it may be re-applied when attempted * updates fail due to contention among threads. The function * is applied with the current value as its first argument, * and the given update as the second argument. * * @param x the update value * @param accumulatorFunction a side-effect-free function of two arguments * @return the updated value */ public final double accumulateAndGet(double x, DoubleBinaryOperator accumulatorFunction) { double prev, next; do { prev = get(); next = accumulatorFunction.applyAsDouble(prev, x); } while (!compareAndSet(prev, next)); return next; } public boolean compareAndSet(double expect, double update) { return base.compareAndSet(doubleToRawLongBits(expect), doubleToRawLongBits(update)); } public boolean weakCompareAndSet(double expect, double update) { return base.weakCompareAndSet(doubleToRawLongBits(expect), doubleToRawLongBits(update)); } @Override public String toString() { return ""+get(); } }
5,038
28.127168
96
java
JSAT
JSAT-master/JSAT/src/jsat/utils/concurrent/AtomicDoubleArray.java
package jsat.utils.concurrent; import java.io.Serializable; import java.util.concurrent.atomic.AtomicLongArray; import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleUnaryOperator; /** * Provides a double array that can have individual values updated * atomically. It is backed by and mimics the implementation of * {@link AtomicLongArray}. As such, the methods have the same documentation * * @author Edward Raff */ public class AtomicDoubleArray implements Serializable { private static final long serialVersionUID = -8799170460903375842L; private AtomicLongArray larray; /** * Creates a new AtomicDoubleArray of the given length, with all values * initialized to zero * @param length the length of the array */ public AtomicDoubleArray(int length) { larray = new AtomicLongArray(length); long ZERO = Double.doubleToRawLongBits(0.0); for(int i = 0; i < length; i++) larray.set(i, ZERO); } /** * Creates a new AtomixDouble Array that is of the same length * as the input array. The values will be copied into the * new object * @param array the array of values to copy */ public AtomicDoubleArray(double[] array) { this(array.length); for(int i = 0; i < array.length; i++) set(i, array[i]); } /** * Atomically increments by one the element at index {@code i}. * * @param i the index * @return the previous value */ public double getAndIncrement(int i) { return getAndAdd(i, 1.0); } /** * Atomically decrements by one the element at index {@code i}. * * @param i the index * @return the previous value */ public double getAndDecrement(int i) { return getAndAdd(i, -1.0); } /** * Atomically adds the given value to the element at index {@code i}. * * @param i the index * @param delta the value to add * @return the previous value */ public double getAndAdd(int i, double delta) { while(true) { double orig = get(i); double newVal = orig + delta; if(compareAndSet(i, orig, newVal)) return orig; } } /** * Atomically adds the given value to the element at index {@code i}. * * @param i the index * @param delta the value to add * @return the updated value */ public double addAndGet(int i, double delta) { while(true) { double orig = get(i); double newVal = orig + delta; if(compareAndSet(i, orig, newVal)) return newVal; } } /** * Atomically sets the element at position {@code i} to the given value * and returns the old value. * * @param i the index * @param newValue the new value * @return the previous value */ public double getAndSet(int i, double newValue) { long oldL = larray.getAndSet(i, Double.doubleToRawLongBits(newValue)); return Double.longBitsToDouble(oldL); } /** * Sets the element at position {@code i} to the given value. * * @param i the index * @param newValue the new value */ public void set(int i, double newValue) { larray.set(i, Double.doubleToRawLongBits(newValue)); } /** * Eventually sets the element at position {@code i} to the given value. * * @param i the index * @param newValue the new value */ public void lazySet(int i, double newValue) { larray.lazySet(i, Double.doubleToRawLongBits(newValue)); } /** * Atomically sets the element at position {@code i} to the given * updated value if the current value {@code ==} the expected value. * * @param i the index * @param expected the expected value * @param update the new value * @return true if successful. False return indicates that * the actual value was not equal to the expected value. */ public boolean compareAndSet(int i, double expected, double update) { long expectedL = Double.doubleToRawLongBits(expected); long updateL = Double.doubleToRawLongBits(update); return larray.compareAndSet(i, expectedL, updateL); } /** * Atomically sets the element at position {@code i} to the given * updated value if the current value {@code ==} the expected value. * * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * * @param i the index * @param expected the expected value * @param update the new value * @return true if successful. */ public boolean weakCompareAndSet(int i, double expected, double update) { long expectedL = Double.doubleToRawLongBits(expected); long updateL = Double.doubleToRawLongBits(update); return larray.weakCompareAndSet(i, expectedL, updateL); } /** * Atomically updates the element at index {@code i} with the results * of applying the given function, returning the updated value. The * function should be side-effect-free, since it may be re-applied * when attempted updates fail due to contention among threads. * * @param i the index * @param updateFunction a side-effect-free function * @return the updated value */ public final double updateAndGet(int i, DoubleUnaryOperator updateFunction) { double prev, next; do { prev = get(i); next = updateFunction.applyAsDouble(prev); } while (!compareAndSet(i, prev, next)); return next; } /** * Atomically updates the element at index {@code i} with the results * of applying the given function, returning the previous value. The * function should be side-effect-free, since it may be re-applied * when attempted updates fail due to contention among threads. * * @param i the index * @param updateFunction a side-effect-free function * @return the previous value */ public final double getAndUpdate(int i, DoubleUnaryOperator updateFunction) { double prev, next; do { prev = get(i); next = updateFunction.applyAsDouble(prev); } while (!compareAndSet(i, prev, next)); return prev; } /** * Atomically updates the element at index {@code i} with the * results of applying the given function to the current and * given values, returning the previous value. The function should * be side-effect-free, since it may be re-applied when attempted * updates fail due to contention among threads. The function is * applied with the current value at index {@code i} as its first * argument, and the given update as the second argument. * * @param i the index * @param x the update value * @param accumulatorFunction a side-effect-free function of two arguments * @return the previous value */ public final double getAndAccumulate(int i, double x, DoubleBinaryOperator accumulatorFunction) { double prev, next; do { prev = get(i); next = accumulatorFunction.applyAsDouble(prev, x); } while (!compareAndSet(i, prev, next)); return prev; } /** * Atomically updates the element at index {@code i} with the * results of applying the given function to the current and * given values, returning the updated value. The function should * be side-effect-free, since it may be re-applied when attempted * updates fail due to contention among threads. The function is * applied with the current value at index {@code i} as its first * argument, and the given update as the second argument. * * @param i the index * @param x the update value * @param accumulatorFunction a side-effect-free function of two arguments * @return the updated value */ public final double accumulateAndGet(int i, double x, DoubleBinaryOperator accumulatorFunction) { double prev, next; do { prev = get(i); next = accumulatorFunction.applyAsDouble(prev, x); } while (!compareAndSet(i, prev, next)); return next; } /** * Gets the current value at position {@code i}. * * @param i the index * @return the current value */ public double get(int i) { return Double.longBitsToDouble(larray.get(i)); } /** * Returns the length of the array. * * @return the length of the array */ public int length() { return larray.length(); } /** * This is a convenience method to set every value in this array to a specified value * @param value the value fill with */ public void fill(double value) { for(int i = 0; i < length(); i++) set(i, value); } }
9,357
29.581699
99
java
JSAT
JSAT-master/JSAT/src/jsat/utils/concurrent/ConcurrentCacheLRU.java
/* * Copyright (C) 2016 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.utils.concurrent; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import jsat.utils.Pair; /** * This class defines a Concurrent LRU cache. The current implementation may not * be the most consistent, as it uses a time stamp from last access to determine * LRU items. It is also designed for read-heavy work loads * * @author Edward Raff */ public class ConcurrentCacheLRU<K, V> { private final ConcurrentHashMap<K, Pair<V, AtomicLong>> cache; private final int maxEntries; public ConcurrentCacheLRU(int max_entries) { this.maxEntries = max_entries; cache = new ConcurrentHashMap<K, Pair<V, AtomicLong>>(max_entries); } public V putIfAbsentAndGet(K key, V value) { Pair<V, AtomicLong> pair = cache.putIfAbsent(key, new Pair<V, AtomicLong>(value, new AtomicLong(System.currentTimeMillis()))); evictOld(); if(pair == null) return null; return pair.getFirstItem(); } private void evictOld() { while(cache.size() > maxEntries) { K oldest_key = null; long oldest_time = Long.MAX_VALUE; for(Map.Entry<K, Pair<V, AtomicLong>> entry : cache.entrySet()) if(entry.getValue().getSecondItem().get() < oldest_time) { oldest_time = entry.getValue().getSecondItem().get(); oldest_key = entry.getKey(); } if(cache.size() > maxEntries)//anotehr thread may have already evicted things cache.remove(oldest_key); } } public void put(K key, V value) { cache.put(key, new Pair<V, AtomicLong>(value, new AtomicLong(System.currentTimeMillis()))); evictOld(); } public V get(K key) { Pair<V, AtomicLong> pair = cache.get(key); if(pair == null) return null; pair.getSecondItem().set(System.currentTimeMillis()); return pair.getFirstItem(); } }
2,793
31.114943
134
java
JSAT
JSAT-master/JSAT/src/jsat/utils/concurrent/IndexReducer.java
/* * Copyright (C) 2017 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.utils.concurrent; /** * * @author Edward Raff * @param <T> The object type that the IndexReducer will return */ public interface IndexReducer<T> { public T run(int indx); }
885
30.642857
72
java
JSAT
JSAT-master/JSAT/src/jsat/utils/concurrent/IndexRunnable.java
/* * Copyright (C) 2017 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.utils.concurrent; /** * * @author Edward Raff */ public interface IndexRunnable { public void run(int indx); }
822
29.481481
72
java
JSAT
JSAT-master/JSAT/src/jsat/utils/concurrent/LoopChunkReducer.java
/* * Copyright (C) 2017 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.utils.concurrent; import java.util.function.BinaryOperator; /** * This functional interface is similar to that of {@link LoopChunkReducer}, * allowing convieniently processing of a range of values for parallel * computing. However, the Reducer returns an object implementing the * {@link BinaryOperator} interface. The goal is that all chunks will eventually * be merged into a single result. This interface is preffered over using normal * streams to reduce unecessary object creation and reductions. * * @author Edward Raff * @param <T> The object type that the Loop Chunk Reducer will return */ public interface LoopChunkReducer<T> { /** * Runs a process over the given loop portion, returning a single object of type {@link T}. * @param start the starting index to process * @param end the ending index to process * @return the object to return */ public T run(int start, int end); }
1,639
38.047619
96
java
JSAT
JSAT-master/JSAT/src/jsat/utils/concurrent/LoopChunkRunner.java
/* * Copyright (C) 2017 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.utils.concurrent; /** * * @author Edward Raff */ public interface LoopChunkRunner { /** * Runs a process over the given loop portion * @param start the starting index to process * @param end the ending index to process */ public void run(int start, int end); }
997
30.1875
72
java
JSAT
JSAT-master/JSAT/src/jsat/utils/concurrent/ParallelUtils.java
package jsat.utils.concurrent; import static java.lang.Math.min; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.BinaryOperator; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.Stream; import jsat.utils.FakeExecutor; import jsat.utils.ListUtils; import jsat.utils.SystemInfo; /** * * @author Edward Raff */ public class ParallelUtils { /** * This object provides a re-usable source of threads for use without having * to create a new thread pool. The cached executor service is used because * no threads are created until needed. If the pool is unused for a long * enough time, the threads will be destroyed. This avoids the user needing * to do anything. This pool is filled with daemon threads, and so will not * prevent program termination. */ public static final ExecutorService CACHED_THREAD_POOL = Executors.newCachedThreadPool((Runnable r) -> { Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); return t; }); /** * This helper method provides a convenient way to break up a computation * across <tt>N</tt> items into contiguous ranges that can be processed * independently in parallel. * * @param parallel a boolean indicating if the work should be done in * parallel. If false, it will run single-threaded. This is for code * convenience so that only one set of code is needed to handle both cases. * @param N the total number of items to process * @param lcr the runnable over a contiguous range */ public static void run(boolean parallel, int N, LoopChunkRunner lcr) { ExecutorService threadPool = Executors.newFixedThreadPool(SystemInfo.LogicalCores); run(parallel, N, lcr, threadPool); threadPool.shutdownNow(); } /** * This helper method provides a convenient way to break up a computation * across <tt>N</tt> items into contiguous ranges that can be processed * independently in parallel. * * @param parallel a boolean indicating if the work should be done in * parallel. If false, it will run single-threaded. This is for code * convenience so that only one set of code is needed to handle both cases. * @param N the total number of items to process. * @param lcr the runnable over a contiguous range * @param threadPool the source of threads for the computation */ public static void run(boolean parallel, int N, LoopChunkRunner lcr, ExecutorService threadPool) { if(!parallel) { lcr.run(0, N); return; } int cores_to_use = Math.min(SystemInfo.LogicalCores, N); final CountDownLatch latch = new CountDownLatch(cores_to_use); IntStream.range(0, cores_to_use).forEach(threadID -> { threadPool.submit(() -> { int start = ParallelUtils.getStartBlock(N, threadID, cores_to_use); int end = ParallelUtils.getEndBlock(N, threadID, cores_to_use); lcr.run(start, end); latch.countDown(); }); }); try { latch.await(); } catch (InterruptedException ex) { Logger.getLogger(ParallelUtils.class.getName()).log(Level.SEVERE, null, ex); } } public static <T> T run(boolean parallel, int N, LoopChunkReducer<T> lcr, BinaryOperator<T> reducer, ExecutorService threadPool) { if(!parallel) { return lcr.run(0, N); } int cores_to_use = Math.min(SystemInfo.LogicalCores, N); final List<Future<T>> futures = new ArrayList<>(cores_to_use); IntStream.range(0, cores_to_use).forEach(threadID -> { futures.add(threadPool.submit(() -> { int start = ParallelUtils.getStartBlock(N, threadID, cores_to_use); int end = ParallelUtils.getEndBlock(N, threadID, cores_to_use); return lcr.run(start, end); })); }); T cur = null; for(Future<T> ft : futures) { try { T chunk = ft.get(); if(cur == null) cur = chunk; else cur = reducer.apply(cur, chunk); } catch (InterruptedException | ExecutionException ex) { Logger.getLogger(ParallelUtils.class.getName()).log(Level.SEVERE, null, ex); } } return cur; } public static <T> T run(boolean parallel, int N, LoopChunkReducer<T> lcr, BinaryOperator<T> reducer) { ExecutorService threadPool = Executors.newWorkStealingPool(SystemInfo.LogicalCores); T toRet = run(parallel, N, lcr, reducer, threadPool); threadPool.shutdownNow(); return toRet; } public static <T> T run(boolean parallel, int N, IndexReducer<T> ir, BinaryOperator<T> reducer) { if(!parallel) { T runner = ir.run(0); for(int i = 1; i < N; i++) runner = reducer.apply(runner, ir.run(i)); return runner; } return range(N, parallel).mapToObj(j -> ir.run(j)).reduce(reducer).orElse(null); } public static void run(boolean parallel, int N, IndexRunnable ir) { ExecutorService threadPool = Executors.newWorkStealingPool(SystemInfo.LogicalCores); run(parallel, N, ir, threadPool); threadPool.shutdownNow(); } /** * This helper method provides a convenient way to break up a computation * across <tt>N</tt> items into individual indices to be processed. This * method is meant for when the execution time of any given index is highly * variable, and so for load balancing purposes, should be treated as * individual jobs. If runtime is consistent, look at {@link #run(boolean, int, jsat.utils.concurrent.LoopChunkRunner, java.util.concurrent.ExecutorService) * }. * * @param parallel a boolean indicating if the work should be done in * parallel. If false, it will run single-threaded. This is for code * convenience so that only one set of code is needed to handle both cases. * @param N the total number of items to process. * @param ir the runnable over a contiguous range * @param threadPool the source of threads for the computation */ public static void run(boolean parallel, int N, IndexRunnable ir, ExecutorService threadPool) { if(!parallel) { for(int i = 0; i < N; i++) ir.run(i); return; } final CountDownLatch latch = new CountDownLatch(N); IntStream.range(0, N).forEach(threadID -> { threadPool.submit(() -> { ir.run(threadID); latch.countDown(); }); }); try { latch.await(); } catch (InterruptedException ex) { Logger.getLogger(ParallelUtils.class.getName()).log(Level.SEVERE, null, ex); } } public static ExecutorService getNewExecutor(boolean parallel) { if(parallel) return Executors.newFixedThreadPool(SystemInfo.LogicalCores); else return new FakeExecutor(); } public static <T> Stream<T> streamP(Stream<T> source, boolean parallel) { if(parallel) return source.parallel(); else return source; } public static IntStream streamP(IntStream source, boolean parallel) { if(parallel) return source.parallel(); else return source; } public static DoubleStream streamP(DoubleStream source, boolean parallel) { if(parallel) return source.parallel(); else return source; } public static IntStream range(int end, boolean parallel) { return range(0, end, parallel); } public static IntStream range(int start, int end, boolean parallel) { if(parallel) { /* * Why do this weirndes instead of call IntStream directly? * IntStream has a habit of not returning a stream that actually * executes in parallel when the range is small. That would make * sense for most cases, but we probably are doing course * parallelism into chunks. So this approach gurantees we get * something that will actually run in parallel. */ return ListUtils.range(start, end).stream().parallel().mapToInt(i -> i); } else return IntStream.range(start, end); } /** * Gets the starting index (inclusive) for splitting up a list of items into * {@code P} evenly sized blocks. In the event that {@code N} is not evenly * divisible by {@code P}, the size of ranges will differ by at most 1. * @param N the number of items to split up * @param ID the block number in [0, {@code P}) * @param P the number of blocks to break up the items into * @return the starting index (inclusive) of the blocks owned by the * {@code ID}'th process. */ public static int getStartBlock(int N, int ID, int P) { int rem = N%P; int start = (N/P)*ID+min(rem, ID); return start; } /** * Gets the starting index (inclusive) for splitting up a list of items into * {@link SystemInfo#LogicalCores} evenly sized blocks. In the event that * {@code N} is not evenly divisible by {@link SystemInfo#LogicalCores}, the * size of ranges will differ by at most 1. * * @param N the number of items to split up * @param ID the block number in [0, {@link SystemInfo#LogicalCores}) * @return the starting index (inclusive) of the blocks owned by the * {@code ID}'th process. */ public static int getStartBlock(int N, int ID) { return getStartBlock(N, ID, SystemInfo.LogicalCores); } /** * Gets the ending index (exclusive) for splitting up a list of items into * {@code P} evenly sized blocks. In the event that {@code N} is not evenly * divisible by {@code P}, the size of ranges will differ by at most 1. * @param N the number of items to split up * @param ID the block number in [0, {@code P}) * @param P the number of blocks to break up the items into * @return the ending index (exclusive) of the blocks owned by the * {@code ID}'th process. */ public static int getEndBlock(int N, int ID, int P) { int rem = N%P; int start = (N/P)*(ID+1)+min(rem, ID+1); return start; } /** * Gets the ending index (exclusive) for splitting up a list of items into * {@link SystemInfo#LogicalCores} evenly sized blocks. In the event that * {@link SystemInfo#LogicalCores} is not evenly divisible by * {@link SystemInfo#LogicalCores}, the size of ranges will differ by at * most 1. * * @param N the number of items to split up * @param ID the block number in [0, {@link SystemInfo#LogicalCores}) * @return the ending index (exclusive) of the blocks owned by the * {@code ID}'th process. */ public static int getEndBlock(int N, int ID) { return getEndBlock(N, ID, SystemInfo.LogicalCores); } }
12,070
34.090116
160
java
JSAT
JSAT-master/JSAT/src/jsat/utils/concurrent/TreeBarrier.java
package jsat.utils.concurrent; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Tree Barrier is a barrier that requires only log(n) communication * for barrier with n threads. To use this barrier, each thread must * know its own unique ID that is sequential in [0, number of threads) * <br><br> * NOTE: The Tree Barrier implementation is not safe for accessing * multiple times in a row. If accessed while some threads are still * attempting to exit, corruption and deadlock can occur. If needed, * two TreeBarriers can be used by alternating back and forth. * * @author Edward Raff */ public class TreeBarrier { final private int parties; private Lock[] locks; private volatile boolean competitionCondition; /** * Creates a new Tree Barrier for synchronization * @param parties the number of threads that must arrive to synchronize */ public TreeBarrier(int parties) { this.parties = parties; locks = new Lock[parties-1]; for(int i = 0; i < locks.length; i++) locks[i] = new ReentrantLock(false); competitionCondition = true; } /** * Waits for all threads to reach this barrier. * * @param ID the id of the thread attempting to reach the barrier. * @throws InterruptedException if one of the threads was interrupted * while waiting on the barrier */ public void await(int ID) throws InterruptedException { if(parties == 1)//what are you doing?! return; final boolean startCondition = competitionCondition; int competingFor = (locks.length*2-1-ID)/2; while (competingFor >= 0) { final Lock node = locks[competingFor]; if (node.tryLock())//we lose, must wait { synchronized (node)//ignore warning, its correct. We are using the lock both for competition AND to do an internal wait { while(competitionCondition == startCondition) node.wait(); } node.unlock(); wakeUpTarget(competingFor*2+1); wakeUpTarget(competingFor*2+2); return; } else //we win, comete for another round! { if(competingFor == 0) break;//we have won the last round! competingFor = (competingFor-1)/2; } } //We won! Inform the losers competitionCondition = !competitionCondition; wakeUpTarget(0);//biggest loser } private void wakeUpTarget(int nodeID) { if(nodeID < locks.length) { synchronized(locks[nodeID]) { locks[nodeID].notify(); } } } }
2,922
30.771739
135
java
JSAT
JSAT-master/JSAT/src/jsat/utils/random/CMWC4096.java
package jsat.utils.random; import java.util.Random; /** * A Complement-Multiply-With-Carry PRNG. It is a fast high quality generator * that passes the Diehard tests. It has a period of over 2<sup>131083</sup> * <br><br> * See: Marsaglia, G. (2005). * <i>On the randomness of Pi and other decimal expansions</i>. Interstat 5 * * @author Edward Raff */ public class CMWC4096 extends Random { private static final long serialVersionUID = -5061963074440046713L; private static final long a = 18782; private int c = 362436; private int i = 4095; private int[] Q; /** * Creates a new PRNG with a random seed */ public CMWC4096() { super(); } /** * Creates a new PRNG * @param seed the seed that controls the initial state of the PRNG * @see #setSeed(long) */ public CMWC4096(long seed) { super(seed); } @Override public synchronized void setSeed(long seed) { super.setSeed(seed); if(Q == null) Q = new int[4096]; for (int j = 0; j < Q.length; j++) Q[j] = super.next(32); } @Override protected int next(int bits) { long t; long x, r = 0xfffffffe; i = (i + 1) & 4095; t = a * Q[i] + c; c = (int) (t >>> 32); x = t + c; if (x < c) { x++; c++; } return (Q[i] = (int) (r - x)) >>> 32 - bits; } }
1,505
20.211268
78
java
JSAT
JSAT-master/JSAT/src/jsat/utils/random/RandomUtil.java
/* * Copyright (C) 2017 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.utils.random; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; /** * This class provides assorted utilities related to random number generation * and use. * * @author Edward Raff <[email protected]> */ public class RandomUtil { private static final ThreadLocal<Random> localRandoms = ThreadLocal.withInitial(RandomUtil::getRandom); private RandomUtil() { } /** * If not specified, this will be the seed used for random objects used * internally within JSAT.<br> * <br> * You may change this to any desired value at the start of any experiments * to consistently get new experimental results. You may also change it at * any point without ill effect, but the purpose is for consistent and * repeatable experiments. */ public static AtomicInteger DEFAULT_SEED = new AtomicInteger(963863937); /** * This controls whether or not {@link #getRandom() } will cause a change in * the {@link #DEFAULT_SEED} each time it is called. This is the default to * ensure that multiple calls to getRandom will not return an equivalent * object. */ public static boolean INCREMENT_SEEDS = true; /** * A large prime value to increment by so that we can take many steps before * repeating. */ private static final int SEED_INCREMENT = 1506369103; /** * Returns a new Random object that can be used. The Random object returned * is promised to be a reasonably high quality PSRND with low memory * overhead that is faster to sample from than the default Java * {@link Random}. Essentially, it will be better than Java's default PRNG * in every way. <br> * <br> * By default, multiple calls to this method will result in multiple, * different, seeds. Controlling the base seed and its behavior can be done * using {@link #DEFAULT_SEED} and {@link #INCREMENT_SEEDS}. * * @return a new random number generator to use. */ public static Random getRandom() { int seed; if(INCREMENT_SEEDS) seed = DEFAULT_SEED.getAndAdd(SEED_INCREMENT); else seed = DEFAULT_SEED.get(); return new XORWOW(seed); } /** * Returns a new Random object that can be used, initiated with the given * seed. The Random object returned is promised to be a reasonably high * quality PSRND with low memory overhead that is faster to sample from than * the default Java {@link Random}. Essentially, it will be better than * Java's default PRNG in every way. <br> * * @param seed the seed of the PRNG, which determines the sequence generated * by the returned object * @return a new random number generator to use. */ public static Random getRandom(int seed) { return new XORWOW(seed); } /** * Returns a Random object that is local to a given thread context, allowing * re-usability at lower overhead. Once a Random object is created for a * thread, it will continue to exist. * * @return a Random object for use */ public static Random getLocalRandom() { return localRandoms.get(); } }
3,989
34.625
107
java
JSAT
JSAT-master/JSAT/src/jsat/utils/random/XOR128.java
package jsat.utils.random; import java.util.Random; /** * A fast PRNG that produces medium quality random numbers that passes the * diehard tests. It has a period of 2<sup>128</sup>-1 * <br><br> * See: G. Marsaglia. <i>Xorshift RNGs</i>. Journal of Statistical Software, 8, * 14:1–9, 2003 * @author Edward Raff */ public class XOR128 extends Random { private static final long serialVersionUID = -5218902638864900490L; private long x, y, z, w; /** * Creates a new PRNG with a random seed */ public XOR128() { super(); } /** * Creates a new PRNG * @param seed the seed that controls the initial state of the PRNG * @see #setSeed(long) */ public XOR128(long seed) { super(seed); } @Override public synchronized void setSeed(long seed) { super.setSeed(seed); x = super.next(32); x = x << 32; x += super.next(32); y = super.next(32); y = y << 32; y += super.next(32); z = super.next(32); z = z << 32; z += super.next(32); w = super.next(32); w = w << 32; w += super.next(32); } @Override protected int next(int bits) { return (int)(nextLong() >>> (64 - bits)); } @Override public long nextLong() { long t; t = (x ^ (x << 11)); x = y; y = z; z = w; w = (w ^ (w >>> 19)) ^ (t ^ (t >>> 8)); return w; } @Override public double nextDouble() { long l = nextLong() >>> 11; return l / (double)(1L << 53); } }
1,683
19.289157
80
java
JSAT
JSAT-master/JSAT/src/jsat/utils/random/XOR96.java
package jsat.utils.random; import java.util.Random; /** * A fast PRNG that produces medium quality random numbers. It has a period of * 2<sup>96</sup>-1 * <br><br> * See: G. Marsaglia. <i>Xorshift RNGs</i>. Journal of Statistical Software, 8, * 14:1–9, 2003 * @author Edward Raff */ public class XOR96 extends Random { private static final long serialVersionUID = 1247900882148980639L; private static final long a = 13, b = 19, c = 3;//magic from paper private long x, y, z; /** * Creates a new PRNG with a random seed */ public XOR96() { super(); } /** * Creates a new PRNG * @param seed the seed that controls the initial state of the PRNG * @see #setSeed(long) */ public XOR96(long seed) { super(seed); } @Override public synchronized void setSeed(long seed) { super.setSeed(seed); x = super.next(32); x = x << 32; x += super.next(32); y = super.next(32); y = y << 32; y += super.next(32); z = super.next(32); z = z << 32; z += super.next(32); } @Override protected int next(int bits) { return (int)(nextLong() >>> (64 - bits)); } @Override public long nextLong() { long t = (x ^ (x << a)); x = y; y = z; z = (z ^ (z >>> c)) ^ (t ^ (t >>> b)); return z; } @Override public double nextDouble() { long l = nextLong() >>> 11; return l / (double)(1L << 53); } }
1,606
19.0875
80
java
JSAT
JSAT-master/JSAT/src/jsat/utils/random/XORWOW.java
package jsat.utils.random; import java.util.Random; /** * A very fast PRNG that passes the Diehard tests. It has a period * of 2<sup>192</sup>−2<sup>32</sup> * <br><br> * See: G. Marsaglia. <i>Xorshift RNGs</i>. Journal of Statistical Software, 8, * 14:1–9, 2003 * @author EdwardRaff */ public class XORWOW extends Random { private static final long serialVersionUID = 4516396552618366318L; private long x, y, z, w, v, d; /** * Creates a new PRNG with a random seed */ public XORWOW() { super(); } /** * Creates a new PRNG * @param seed the seed that controls the initial state of the PRNG * @see #setSeed(long) */ public XORWOW(long seed) { super(seed); } @Override public synchronized void setSeed(long seed) { super.setSeed(seed); x = super.next(32); x = x << 32; x += super.next(32); y = super.next(32); y = y << 32; y += super.next(32); z = super.next(32); z = z << 32; z += super.next(32); w = super.next(32); w = w << 32; w += super.next(32); v = super.next(32); v = v << 32; v += super.next(32); d = super.next(32); d = d << 32; d += super.next(32); } @Override protected int next(int bits) { return (int)(nextLong() >>> (64 - bits)); } @Override public long nextLong() { long t; t = (x ^ (x >> 2)); x = y; y = z; z = w; w = v; v = (v ^ (v << 4)) ^ (t ^ (t << 1)); t = (d += 362437) + v; return t; } @Override public double nextDouble() { long l = nextLong() >>> 11; return l / (double)(1L << 53); } }
1,885
19.06383
80
java
JSAT
JSAT-master/JSAT/test/jsat/FixedProblems.java
package jsat; import java.util.Random; import jsat.classifiers.CategoricalData; import jsat.classifiers.ClassificationDataSet; import jsat.distributions.multivariate.NormalM; import jsat.linear.DenseVector; import jsat.linear.Matrix; import jsat.linear.Vec; import jsat.regression.RegressionDataSet; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; /** * Contains pre determined code for generating specific data sets. * The form and values of the data set are fixed, and do not need * to be specified. Training and testing sets are generated by the * same methods. * * @author Edward Raff */ public class FixedProblems { private static final Vec c2l_m0 = new DenseVector(new double[]{12, 14, 25, 31, 10, 9, 1}); private static final Vec c2l_m1 = new DenseVector(new double[]{-9, -7, -13, -6, -11, -9, -1}); private static final NormalM c2l_c0 = new NormalM(c2l_m0, Matrix.eye(c2l_m0.length())); private static final NormalM c2l_c1 = new NormalM(c2l_m1, Matrix.eye(c2l_m0.length())); /** * Generates a linearly separable binary classification problem * @param dataSetSize the number of points to generated * @param rand the source of randomness * @return a binary classification data set that is linearly separable */ public static ClassificationDataSet get2ClassLinear(int dataSetSize, Random rand) { ClassificationDataSet train = new ClassificationDataSet(c2l_m0.length(), new CategoricalData[0], new CategoricalData(2)); for(Vec s : c2l_c0.sample(dataSetSize, rand)) train.addDataPoint(s, new int[0], 0); for(Vec s : c2l_c1.sample(dataSetSize, rand)) train.addDataPoint(s, new int[0], 1); return train; } /** * Creates a 2D linearly separable problem * @param dataSetSize0 size of the first class * @param dataSetSize1 size of the second class * @param sep the separation between the two classes. The true decision * boundary stays in the same location regardless of this value * @param rand source of randomness * @return a 2d testing set */ public static ClassificationDataSet get2ClassLinear2D(int dataSetSize0, int dataSetSize1, double sep, Random rand) { ClassificationDataSet train = new ClassificationDataSet(2, new CategoricalData[0], new CategoricalData(2)); NormalM a = new NormalM(DenseVector.toDenseVec(sep, sep), Matrix.eye(2)); NormalM b = new NormalM(DenseVector.toDenseVec(-sep, -sep), Matrix.eye(2)); for(Vec s : a.sample(dataSetSize0, rand)) train.addDataPoint(s, new int[0], 0); for(Vec s : b.sample(dataSetSize1, rand)) train.addDataPoint(s, new int[0], 1); return train; } /** * Generates a linearly separable binary classification problem * @param dataSetSize0 the number of points to generated for the first class * @param dataSetSize1 the number of points to generated for the second class * @param rand the source of randomness * @return a binary classification data set that is linearly separable */ public static ClassificationDataSet get2ClassLinear(int dataSetSize0, int dataSetSize1, Random rand) { ClassificationDataSet train = new ClassificationDataSet(c2l_m0.length(), new CategoricalData[0], new CategoricalData(2)); for(Vec s : c2l_c0.sample(dataSetSize0, rand)) train.addDataPoint(s, new int[0], 0); for(Vec s : c2l_c1.sample(dataSetSize1, rand)) train.addDataPoint(s, new int[0], 1); return train; } /** * Generates a linearly separable multi class problem * @param dataSetSize the number of data points to generate per class * @param K the number of classes to generate * @return a new multi class data set */ public static ClassificationDataSet getSimpleKClassLinear(int dataSetSize, int K) { return getSimpleKClassLinear(dataSetSize, K, RandomUtil.getRandom()); } /** * Generates a linearly separable multi class problem * @param dataSetSize the number of data points to generate per class * @param K the number of classes to generate * @param rand the source of randomness * @return a new multi class data set */ public static ClassificationDataSet getSimpleKClassLinear(int dataSetSize, int K, Random rand) { ClassificationDataSet train = new ClassificationDataSet(K, new CategoricalData[0], new CategoricalData(K)); for(int k = 0; k < K; k++) { for(int i = 0; i <dataSetSize; i++) { Vec dv = DenseVector.random(K, rand); dv.set(k, 10+rand.nextGaussian()); train.addDataPoint(dv, new int[0], k); } } return train; } /** * Generates a regression problem that can be solved by linear regression methods * @param dataSetSize the number of data points to get * @param rand the randomness to use * @return a regression data set */ public static RegressionDataSet getLinearRegression(int dataSetSize, Random rand) { return getLinearRegression(dataSetSize, rand, c2l_m0); } /** * Generates a 2D regression problem that can be solved by linear regression methods * @param dataSetSize the number of data points to get * @param rand the randomness to use * @return a regression data set */ public static RegressionDataSet get2DLinearRegression(int dataSetSize, Random rand) { return getLinearRegression(dataSetSize, rand, DenseVector.toDenseVec(0.8, -0.15)); } /** * Generates a regression problem that can be solved by linear regression methods * @param dataSetSize the number of data points to get * @param rand the randomness to use * @param coef the coefficients to use for the linear regression * @return a regression data set */ public static RegressionDataSet getLinearRegression(int dataSetSize, Random rand, Vec coef) { RegressionDataSet rds = new RegressionDataSet(coef.length(), new CategoricalData[0]); for(int i = 0; i < dataSetSize; i++) { Vec s = new DenseVector(coef.length()); for(int j = 0; j < s.length(); j++) s.set(j, rand.nextDouble()); rds.addDataPoint(s, new int[0], s.dot(coef)); } return rds; } /** * Creates a new Regression problem of the for * x<sub>2</sub>+c sin(x<sub>2</sub>) = y. It is meant to be an easy test case * for non-linear regression algorithms. * * @param dataSetSize the number of data points to generate * @param rand the source of randomness * @return a new regression data set */ public static RegressionDataSet getSimpleRegression1(int dataSetSize, Random rand) { RegressionDataSet rds = new RegressionDataSet(2, new CategoricalData[0]); for(int i = 0; i < dataSetSize; i++) { Vec s = new DenseVector(new double[]{rand.nextDouble()*4, rand.nextDouble()*4}); rds.addDataPoint(s, new int[0], s.get(0)+4*Math.cos(s.get(1))); } return rds; } /** * Returns a classification problem with small uniform noise where there is * a small circle of radius 1 within a circle of radius 4. Each circle * shares the same center. * * @param dataSetSize the even number of data points to create * @param rand the source of randomness * @return a classification data set with two classes */ public static ClassificationDataSet getInnerOuterCircle(int dataSetSize, Random rand) { return getInnerOuterCircle(dataSetSize, rand, 1, 4); } public static ClassificationDataSet getInnerOuterCircle(int dataSetSize, Random rand, double r1, double r2) { return getCircles(dataSetSize, rand, r1, r2); } public static ClassificationDataSet getCircles(int dataSetSize, double... radi ) { return getCircles(dataSetSize, RandomUtil.getRandom(), radi); } public static ClassificationDataSet getCircles(int dataSetSize, Random rand, double... radi ) { return getCircles(dataSetSize, 1.0/5.0, rand, radi); } public static ClassificationDataSet getCircles(int dataSetSize, double randNoiseMultiplier, Random rand, double... radi ) { ClassificationDataSet train = new ClassificationDataSet(2, new CategoricalData[0], new CategoricalData(radi.length)); int n = dataSetSize / 2; for(int r_i = 0; r_i < radi.length; r_i++) for (int i = 0; i < n; i++) { double t = 2 * Math.PI * i / n; double x = radi[r_i] * Math.cos(t) + (rand.nextDouble() - 0.5) * randNoiseMultiplier; double y = radi[r_i] * Math.sin(t) + (rand.nextDouble() - 0.5) * randNoiseMultiplier; train.addDataPoint(DenseVector.toDenseVec(x, y), new int[0], r_i); } return train; } public static ClassificationDataSet getHalfCircles(int dataSetSize, Random rand, double... radi ) { ClassificationDataSet train = new ClassificationDataSet(2, new CategoricalData[0], new CategoricalData(radi.length)); int n = dataSetSize/2 ; for(int r_i = 0; r_i < radi.length; r_i++) for (int i = 0; i < n; i++) { double t = 2 * Math.PI * (i/2) / n; double x = radi[r_i] * Math.cos(t) + (rand.nextDouble() - 0.5) / 5; double y = radi[r_i] * Math.sin(t) + (rand.nextDouble() - 0.5) / 5; train.addDataPoint(DenseVector.toDenseVec(x, y), new int[0], r_i); } return train; } }
10,012
38.734127
129
java
JSAT
JSAT-master/JSAT/test/jsat/NormalClampedSample.java
package jsat; import java.util.Random; import jsat.distributions.Normal; import jsat.linear.DenseVector; /** * Helper class to avoid issues with sampling from the normal distribution when * testing since the normal can have extreme values * @author Edward Raff */ public class NormalClampedSample extends Normal { private static final long serialVersionUID = 3970933766374506189L; double min, max; public NormalClampedSample(double mean, double stndDev) { this(mean, stndDev, mean-3*stndDev, mean+3*stndDev); } public NormalClampedSample(double mean, double stndDev, double min, double max) { super(mean, stndDev); this.min = Math.min(min, max); this.max = Math.max(min, max); } @Override public double invCdf(double d) { return Math.max(min, Math.min(max, super.invCdf(d))); } @Override public double[] sample(int numSamples, Random rand) { double[] ret = super.sample(numSamples, rand); for(int i = 0; i < ret.length; i++) ret[i] = Math.max(min, Math.min(max, ret[i])); return ret; } @Override public DenseVector sampleVec(int numSamples, Random rand) { DenseVector ret = super.sampleVec(numSamples, rand); for(int i = 0; i < ret.length(); i++) ret.set(i, Math.max(min, Math.min(max, ret.get(i)))); return ret; } }
1,429
25
83
java
JSAT
JSAT-master/JSAT/test/jsat/TestTools.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat; import java.io.*; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import jsat.classifiers.DataPoint; import jsat.regression.NadarayaWatson; import jsat.regression.RegressionDataSet; import jsat.regression.RegressionModelEvaluation; import jsat.regression.Regressor; import jsat.utils.IntSet; import jsat.utils.random.RandomUtil; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals; /** * * @author Edward Raff */ public class TestTools { public static void assertEqualsRelDiff(double expected, double actual, double delta) { double denom = expected; if(expected == 0) denom = 1e-6; double relError = Math.abs(expected-actual)/denom; assertEquals(0.0, relError, delta); } /** * Creates a deep copy of the given object via serialization. * @param <O> The class of the object * @param orig the object to make a copy of * @return a copy of the object via serialization */ public static <O extends Object> O deepCopy(O orig) { Object obj = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(orig); out.flush(); out.close(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); obj = in.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); throw new RuntimeException("Object couldn't be copied", e); } return (O) obj; } /** * Evaluates a given clustering by assuming that the true cluster label is in the first categorical feature. Checks to make sure that each cluster is pure in the label * @param clusters the clustering to evaluate * @return true if the clustering is good, false otherwise */ public static boolean checkClusteringByCat(List<List<DataPoint>> clusters) { Set<Integer> seenBefore = new IntSet(); for (List<DataPoint> cluster : clusters) { int thisClass = cluster.get(0).getCategoricalValue(0); if(seenBefore.contains(thisClass) != false) return false; for (DataPoint dp : cluster) if(thisClass != dp.getCategoricalValue(0)) return false; } return true; } /** * Evaluate regressor on linear problem * @param instance regressor to use * @return <tt>true</tt> if the model passed the test, <tt>false</tt> if it failed */ public static boolean regressEvalLinear(Regressor instance) { return regressEvalLinear(instance, 500, 100); } /** * Evaluate regressor on linear problem * @param instance regressor to use * @param N_train size of the training set to use * @param N_test size of the testing set * @return <tt>true</tt> if the model passed the test, <tt>false</tt> if it failed */ public static boolean regressEvalLinear(Regressor instance, int N_train, int N_test) { RegressionDataSet train = FixedProblems.getLinearRegression(N_train, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(N_test, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train); rme.evaluateTestSet(test); return rme.getMeanError() <= test.getTargetValues().mean() * 1.5; } /** * Evaluate regressor on linear problem * @param instance regressor to use * @param ex source of threads to use * @return <tt>true</tt> if the model passed the test, <tt>false</tt> if it failed */ public static boolean regressEvalLinear(Regressor instance, ExecutorService ex) { return regressEvalLinear(instance, false, 500, 100); } /** * Evaluate regressor on linear problem * @param instance regressor to use * @param ex source of threads to use * @param N_train size of the training set to use * @param N_test size of the testing set * @return <tt>true</tt> if the model passed the test, <tt>false</tt> if it failed */ public static boolean regressEvalLinear(Regressor instance, boolean parallel, int N_train, int N_test) { RegressionDataSet train = FixedProblems.getLinearRegression(N_train, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(N_test, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train, parallel); rme.evaluateTestSet(test); return rme.getMeanError() <= test.getTargetValues().mean() * 1.5; } }
5,627
36.271523
171
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/DDAGTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.svm.DCDs; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class DDAGTest { public DDAGTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); for(boolean conc : new boolean[]{true, false}) { DDAG instance = new DDAG(new DCDs(), conc); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(1000, 7); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(100, 7); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train, true); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); } } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); for(boolean conc : new boolean[]{true, false}) { DDAG instance = new DDAG(new DCDs(), conc); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(1000, 7); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(100, 7); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); } } @Test public void testClone() { System.out.println("clone"); ClassificationDataSet t1 = FixedProblems.getSimpleKClassLinear(1000, 7); ClassificationDataSet t2 = FixedProblems.getSimpleKClassLinear(1000, 9); DDAG instance = new DDAG(new DCDs()); instance = instance.clone(); instance.train(t1); DDAG result = instance.clone(); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), result.classify(t1.getDataPoint(i)).mostLikely()); result.train(t2); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), instance.classify(t1.getDataPoint(i)).mostLikely()); for(int i = 0; i < t2.size(); i++) assertEquals(t2.getDataPointCategory(i), result.classify(t2.getDataPoint(i)).mostLikely()); } }
3,604
27.611111
105
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/OneVSAllTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.svm.DCDs; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class OneVSAllTest { public OneVSAllTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); for(boolean conc : new boolean[]{true, false}) { OneVSAll instance = new OneVSAll(new DCDs(), conc); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(1000, 7); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(100, 7); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train, true); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); } } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); for(boolean conc : new boolean[]{true, false}) { OneVSAll instance = new OneVSAll(new DCDs(), conc); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(1000, 7); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(100, 7); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); } } @Test public void testClone() { System.out.println("clone"); ClassificationDataSet t1 = FixedProblems.getSimpleKClassLinear(1000, 7); ClassificationDataSet t2 = FixedProblems.getSimpleKClassLinear(1000, 9); OneVSAll instance = new OneVSAll(new DCDs()); instance = instance.clone(); instance.train(t1); OneVSAll result = instance.clone(); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), result.classify(t1.getDataPoint(i)).mostLikely()); result.train(t2); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), instance.classify(t1.getDataPoint(i)).mostLikely()); for(int i = 0; i < t2.size(); i++) assertEquals(t2.getDataPointCategory(i), result.classify(t2.getDataPoint(i)).mostLikely()); } }
3,631
28.056
105
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/OneVSOneTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.svm.DCDs; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class OneVSOneTest { public OneVSOneTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); for(boolean conc : new boolean[]{true, false}) { OneVSOne instance = new OneVSOne(new DCDs(), conc); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(1000, 7); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(100, 7); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train, true); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); } } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); for(boolean conc : new boolean[]{true, false}) { OneVSOne instance = new OneVSOne(new DCDs(), conc); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(1000, 7); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(100, 7); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); } } @Test public void testClone() { System.out.println("clone"); ClassificationDataSet t1 = FixedProblems.getSimpleKClassLinear(1000, 7); ClassificationDataSet t2 = FixedProblems.getSimpleKClassLinear(1000, 9); OneVSOne instance = new OneVSOne(new DCDs()); instance = instance.clone(); instance.train(t1); OneVSOne result = instance.clone(); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), result.classify(t1.getDataPoint(i)).mostLikely()); result.train(t2); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), instance.classify(t1.getDataPoint(i)).mostLikely()); for(int i = 0; i < t2.size(); i++) assertEquals(t2.getDataPointCategory(i), result.classify(t2.getDataPoint(i)).mostLikely()); } }
3,626
28.25
105
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/RocchioTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class RocchioTest { public RocchioTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); Rocchio instance = new Rocchio(); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(10000, 3); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(1000, 3); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train, true); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); Rocchio instance = new Rocchio(); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(10000, 3); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(1000, 3); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); } @Test public void testClone() { System.out.println("clone"); ClassificationDataSet t1 = FixedProblems.getSimpleKClassLinear(10000, 3); ClassificationDataSet t2 = FixedProblems.getSimpleKClassLinear(10000, 6); Rocchio instance = new Rocchio(); instance = instance.clone(); instance.train(t1); Rocchio result = instance.clone(); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), result.classify(t1.getDataPoint(i)).mostLikely()); result.train(t2); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), instance.classify(t1.getDataPoint(i)).mostLikely()); for(int i = 0; i < t2.size(); i++) assertEquals(t2.getDataPointCategory(i), result.classify(t2.getDataPoint(i)).mostLikely()); } }
3,390
27.737288
105
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/bayesian/AODETest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.bayesian; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.ClassificationModelEvaluation; import jsat.datatransform.DataTransformProcess; import jsat.datatransform.NumericalToHistogram; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class AODETest { public AODETest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testSubEpochs() { System.out.println("getSubEpochs"); AODE instance = new AODE(); instance.setM(0.1); assertEquals(0.1, instance.getM(), 0.0); for (int i = -3; i < 0; i++) try { instance.setM(i); fail("Invalid value should have thrown an error"); } catch (Exception ex) { } } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); AODE instance = new AODE(); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(10000, 3, RandomUtil.getRandom()); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(1000, 3, RandomUtil.getRandom()); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train, true); cme.setDataTransformProcess(new DataTransformProcess(new NumericalToHistogram())); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); AODE instance = new AODE(); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(10000, 3, RandomUtil.getRandom()); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(1000, 3, RandomUtil.getRandom()); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.setDataTransformProcess(new DataTransformProcess(new NumericalToHistogram())); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); } @Test public void testClone() { System.out.println("clone"); ClassificationDataSet t1 = FixedProblems.getSimpleKClassLinear(10000, 3, RandomUtil.getRandom()); ClassificationDataSet t2 = FixedProblems.getSimpleKClassLinear(10000, 6, RandomUtil.getRandom()); t1.applyTransform(new NumericalToHistogram(t1)); t2.applyTransform(new NumericalToHistogram(t2)); AODE instance = new AODE(); instance = instance.clone(); instance.train(t1); AODE result = instance.clone(); result.train(t2); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), instance.classify(t1.getDataPoint(i)).mostLikely()); for(int i = 0; i < t2.size(); i++) assertEquals(t2.getDataPointCategory(i), result.classify(t2.getDataPoint(i)).mostLikely()); } }
4,379
28.795918
108
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/bayesian/MultinomialNaiveBayesTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.bayesian; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.ClassificationModelEvaluation; import jsat.datatransform.DataTransformProcess; import jsat.datatransform.NumericalToHistogram; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class MultinomialNaiveBayesTest { public MultinomialNaiveBayesTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); for(boolean useCatFeatures : new boolean[]{true, false}) { MultinomialNaiveBayes instance = new MultinomialNaiveBayes(); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(10000, 3, RandomUtil.getRandom()); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(1000, 3, RandomUtil.getRandom()); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train, true); if(useCatFeatures) cme.setDataTransformProcess(new DataTransformProcess(new NumericalToHistogram())); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); } } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); for(boolean useCatFeatures : new boolean[]{true, false}) { MultinomialNaiveBayes instance = new MultinomialNaiveBayes(); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(10000, 3, RandomUtil.getRandom()); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(1000, 3, RandomUtil.getRandom()); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); if(useCatFeatures) cme.setDataTransformProcess(new DataTransformProcess(new NumericalToHistogram())); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); } } @Test public void testClone() { System.out.println("clone"); for(boolean useCatFeatures : new boolean[]{true, false}) { MultinomialNaiveBayes instance = new MultinomialNaiveBayes(); ClassificationDataSet t1 = FixedProblems.getSimpleKClassLinear(1000, 3, RandomUtil.getRandom()); ClassificationDataSet t2 = FixedProblems.getSimpleKClassLinear(1000, 6, RandomUtil.getRandom()); if(useCatFeatures) { t1.applyTransform(new NumericalToHistogram(t1)); t2.applyTransform(new NumericalToHistogram(t2)); } instance = instance.clone(); instance.train(t1); MultinomialNaiveBayes result = instance.clone(); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), result.classify(t1.getDataPoint(i)).mostLikely()); result.train(t2); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), instance.classify(t1.getDataPoint(i)).mostLikely()); for(int i = 0; i < t2.size(); i++) assertEquals(t2.getDataPointCategory(i), result.classify(t2.getDataPoint(i)).mostLikely()); } } }
4,648
31.062069
113
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/bayesian/MultivariateNormalsTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.bayesian; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.ClassificationModelEvaluation; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class MultivariateNormalsTest { public MultivariateNormalsTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); MultivariateNormals instance = new MultivariateNormals(); ClassificationDataSet train = FixedProblems.getCircles(1000, 3, 0.1, 1.0, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, 3, 0.1, 1.0, 10.0); ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); ex.shutdownNow(); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); MultivariateNormals instance = new MultivariateNormals(); ClassificationDataSet train = FixedProblems.getCircles(1000, 3, 0.1, 1.0, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, 3, 0.1, 1.0, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); } @Test public void testClone() { System.out.println("clone"); ClassificationDataSet t1 = FixedProblems.getSimpleKClassLinear(1000, 3, RandomUtil.getRandom()); ClassificationDataSet t2 = FixedProblems.getSimpleKClassLinear(1000, 6, RandomUtil.getRandom()); MultivariateNormals instance = new MultivariateNormals(); instance = instance.clone(); instance.train(t1); MultivariateNormals result = instance.clone(); result.train(t2); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), instance.classify(t1.getDataPoint(i)).mostLikely()); for(int i = 0; i < t2.size(); i++) assertEquals(t2.getDataPointCategory(i), result.classify(t2.getDataPoint(i)).mostLikely()); } }
3,679
28.918699
105
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/bayesian/NaiveBayesTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.classifiers.bayesian; import java.util.Random; import java.util.concurrent.Executors; import jsat.utils.GridDataGenerator; import jsat.utils.SystemInfo; import java.util.concurrent.ExecutorService; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.Classifier; import jsat.distributions.Normal; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class NaiveBayesTest { static private ClassificationDataSet easyTrain; static private ClassificationDataSet easyTest; static private NaiveBayes nb; public NaiveBayesTest() { GridDataGenerator gdg = new GridDataGenerator(new Normal(0, 0.05), new Random(12), 2); easyTrain = new ClassificationDataSet(gdg.generateData(40).getList(), 0); easyTest = new ClassificationDataSet(gdg.generateData(40).getList(), 0); } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { nb = new NaiveBayes(); } /** * Test of train method, of class NaiveBayes. */ @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); nb.train(easyTrain); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), nb.classify(easyTest.getDataPoint(i)).mostLikely()); } /** * Test of clone method, of class NaiveBayes. */ @Test public void testClone() { System.out.println("clone"); nb.train(easyTrain); Classifier clone = nb.clone(); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), clone.classify(easyTest.getDataPoint(i)).mostLikely()); } /** * Test of train method, of class NaiveBayes. */ @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); nb.train(easyTrain, true); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), nb.classify(easyTest.getDataPoint(i)).mostLikely()); } }
2,468
26.433333
114
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/bayesian/NaiveBayesUpdateableTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.classifiers.bayesian; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.classifiers.*; import jsat.distributions.Normal; import jsat.utils.GridDataGenerator; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class NaiveBayesUpdateableTest { static private ClassificationDataSet easyTrain; static private ClassificationDataSet easyTest; static private NaiveBayesUpdateable nb; public NaiveBayesUpdateableTest() { } @BeforeClass public static void setUpClass() { GridDataGenerator gdg = new GridDataGenerator(new Normal(0, 0.05), new Random(12), 2); easyTrain = new ClassificationDataSet(gdg.generateData(40).getList(), 0); easyTest = new ClassificationDataSet(gdg.generateData(40).getList(), 0); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { nb = new NaiveBayesUpdateable(); } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); nb.train(easyTrain); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), nb.classify(easyTest.getDataPoint(i)).mostLikely()); } @Test public void testSetUpUpdate() { System.out.println("testSetUpUpdate"); nb.setUp(easyTrain.getCategories(), easyTrain.getNumNumericalVars(), easyTrain.getPredicting()); for(int i = 0; i < easyTrain.size(); i++) nb.update(easyTrain.getDataPoint(i), easyTrain.getDataPointCategory(i)); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), nb.classify(easyTest.getDataPoint(i)).mostLikely()); } @Test public void testClone() { System.out.println("clone"); nb.train(easyTrain); Classifier clone = nb.clone(); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), clone.classify(easyTest.getDataPoint(i)).mostLikely()); } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); nb.train(easyTrain, true); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), nb.classify(easyTest.getDataPoint(i)).mostLikely()); } }
2,838
27.676768
114
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/boosting/AdaBoostM1Test.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.boosting; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.*; import jsat.classifiers.trees.DecisionStump; import jsat.classifiers.trees.DecisionTree; import jsat.classifiers.trees.TreePruner; import jsat.datatransform.LinearTransform; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class AdaBoostM1Test { public AdaBoostM1Test() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); AdaBoostM1 instance = new AdaBoostM1(new DecisionStump(), 50); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train, true); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.15); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); AdaBoostM1 instance = new AdaBoostM1(new DecisionStump(), 50); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.15); } @Test public void testClone() { System.out.println("clone"); AdaBoostM1 instance = new AdaBoostM1(new DecisionTree(10, 10, TreePruner.PruningMethod.NONE, 0.1), 50); ClassificationDataSet t1 = FixedProblems.getCircles(1000, 0.1, 10.0); ClassificationDataSet t2 = FixedProblems.getCircles(1000, 0.1, 10.0); t2.applyTransform(new LinearTransform(t2)); int errors; instance = instance.clone(); instance.train(t1); AdaBoostM1 result = instance.clone(); errors = 0; for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - result.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); result.train(t2); for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - instance.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); for (int i = 0; i < t2.size(); i++) errors += Math.abs(t2.getDataPointCategory(i) - result.classify(t2.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); } }
3,911
27.764706
113
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/boosting/ArcX4Test.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.boosting; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.*; import jsat.classifiers.trees.DecisionStump; import jsat.classifiers.trees.DecisionTree; import jsat.classifiers.trees.TreePruner; import jsat.datatransform.LinearTransform; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class ArcX4Test { public ArcX4Test() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); ArcX4 instance = new ArcX4(new DecisionStump(), 50); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train, true); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.05); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); ArcX4 instance = new ArcX4(new DecisionStump(), 50); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.05); } @Test public void testClone() { System.out.println("clone"); ArcX4 instance = new ArcX4(new DecisionTree(10, 10, TreePruner.PruningMethod.NONE, 0.1), 50); ClassificationDataSet t1 = FixedProblems.getCircles(1000, 0.1, 10.0); ClassificationDataSet t2 = FixedProblems.getCircles(1000, 0.1, 10.0); t2.applyTransform(new LinearTransform(t2)); int errors; instance = instance.clone(); instance.train(t1); ArcX4 result = instance.clone(); errors = 0; for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - result.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); result.train(t2); for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - instance.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); for (int i = 0; i < t2.size(); i++) errors += Math.abs(t2.getDataPointCategory(i) - result.classify(t2.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); } }
3,866
27.433824
113
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/boosting/BaggingTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.boosting; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.*; import jsat.classifiers.trees.*; import jsat.datatransform.LinearTransform; import jsat.regression.RegressionDataSet; import jsat.regression.RegressionModelEvaluation; import jsat.regression.Regressor; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.*; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class BaggingTest { public BaggingTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_RegressionDataSet() { System.out.println("train"); Bagging instance = new Bagging((Regressor)new DecisionTree()); RegressionDataSet train = FixedProblems.getLinearRegression(5000, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.5); } @Test public void testTrainC_RegressionDataSet_ExecutorService() { System.out.println("train"); Bagging instance = new Bagging((Regressor)new DecisionTree()); RegressionDataSet train = FixedProblems.getLinearRegression(5000, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train, true); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.5); } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); Bagging instance = new Bagging((Classifier)new DecisionTree()); ClassificationDataSet train = FixedProblems.getCircles(5000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train, true); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.05); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); Bagging instance = new Bagging((Classifier)new DecisionTree()); ClassificationDataSet train = FixedProblems.getCircles(5000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.05); } @Test public void testClone() { System.out.println("clone"); Bagging instance = new Bagging((Classifier)new DecisionTree()); ClassificationDataSet t1 = FixedProblems.getCircles(1000, 0.1, 10.0); ClassificationDataSet t2 = FixedProblems.getCircles(1000, 0.1, 10.0); t2.applyTransform(new LinearTransform(t2)); int errors; instance = instance.clone(); instance.train(t1); Bagging result = instance.clone(); errors = 0; for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - result.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); result.train(t2); for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - instance.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); for (int i = 0; i < t2.size(); i++) errors += Math.abs(t2.getDataPointCategory(i) - result.classify(t2.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); } }
5,045
28.508772
113
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/boosting/EmphasisBoostTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.boosting; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.*; import jsat.classifiers.trees.DecisionStump; import jsat.classifiers.trees.DecisionTree; import jsat.classifiers.trees.TreePruner; import jsat.datatransform.LinearTransform; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class EmphasisBoostTest { public EmphasisBoostTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); EmphasisBoost instance = new EmphasisBoost(new DecisionStump(), 50, 0.5); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train, true); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.15); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); EmphasisBoost instance = new EmphasisBoost(new DecisionStump(), 50, 0.5); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.15); } @Test public void testClone() { System.out.println("clone"); EmphasisBoost instance = new EmphasisBoost(new DecisionTree(10, 10, TreePruner.PruningMethod.NONE, 0.1), 50, 0.5); ClassificationDataSet t1 = FixedProblems.getCircles(1000, 0.1, 10.0); ClassificationDataSet t2 = FixedProblems.getCircles(1000, 0.1, 10.0); t2.applyTransform(new LinearTransform(t2)); int errors; instance = instance.clone(); instance.train(t1); EmphasisBoost result = instance.clone(); errors = 0; for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - result.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); result.train(t2); for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - instance.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); for (int i = 0; i < t2.size(); i++) errors += Math.abs(t2.getDataPointCategory(i) - result.classify(t2.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); } }
3,954
27.868613
122
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/boosting/LogitBoostPLTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.boosting; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.ClassificationModelEvaluation; import jsat.classifiers.trees.DecisionStump; import jsat.classifiers.trees.DecisionTree; import jsat.classifiers.trees.TreePruner; import jsat.datatransform.LinearTransform; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class LogitBoostPLTest { public LogitBoostPLTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); LogitBoostPL instance = new LogitBoostPL(new DecisionStump(), 50); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train, true); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.15); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); LogitBoostPL instance = new LogitBoostPL(new DecisionStump(), 50); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.15); } @Test public void testClone() { System.out.println("clone"); LogitBoostPL instance = new LogitBoostPL(new DecisionTree(10, 10, TreePruner.PruningMethod.NONE, 0.1), 50); ClassificationDataSet t1 = FixedProblems.getCircles(1000, 0.1, 10.0); ClassificationDataSet t2 = FixedProblems.getCircles(1000, 0.1, 10.0); t2.applyTransform(new LinearTransform(t2)); int errors; instance = instance.clone(); instance.train(t1); LogitBoostPL result = instance.clone(); errors = 0; for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - result.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); result.train(t2); for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - instance.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); for (int i = 0; i < t2.size(); i++) errors += Math.abs(t2.getDataPointCategory(i) - result.classify(t2.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); } }
4,004
28.233577
115
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/boosting/LogitBoostTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.boosting; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.*; import jsat.classifiers.trees.DecisionStump; import jsat.classifiers.trees.DecisionTree; import jsat.classifiers.trees.TreePruner; import jsat.datatransform.LinearTransform; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class LogitBoostTest { public LogitBoostTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); LogitBoost instance = new LogitBoost(new DecisionStump(), 50); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train, true); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.15); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); LogitBoost instance = new LogitBoost(new DecisionStump(), 50); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.15); } @Test public void testClone() { System.out.println("clone"); LogitBoost instance = new LogitBoost(new DecisionTree(10, 10, TreePruner.PruningMethod.NONE, 0.1), 50); ClassificationDataSet t1 = FixedProblems.getCircles(1000, 0.1, 10.0); ClassificationDataSet t2 = FixedProblems.getCircles(1000, 0.1, 10.0); t2.applyTransform(new LinearTransform(t2)); int errors; instance = instance.clone(); instance.train(t1); LogitBoost result = instance.clone(); errors = 0; for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - result.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); result.train(t2); for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - instance.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); for (int i = 0; i < t2.size(); i++) errors += Math.abs(t2.getDataPointCategory(i) - result.classify(t2.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); } }
3,911
27.764706
113
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/boosting/ModestAdaBoostTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.boosting; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.*; import jsat.classifiers.trees.DecisionStump; import jsat.classifiers.trees.DecisionTree; import jsat.classifiers.trees.TreePruner; import jsat.datatransform.LinearTransform; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class ModestAdaBoostTest { public ModestAdaBoostTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); ModestAdaBoost instance = new ModestAdaBoost(new DecisionStump(), 50); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train, true); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.15); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); ModestAdaBoost instance = new ModestAdaBoost(new DecisionStump(), 50); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.15); } @Test public void testClone() { System.out.println("clone"); ModestAdaBoost instance = new ModestAdaBoost(new DecisionTree(10, 10, TreePruner.PruningMethod.NONE, 0.1), 50); ClassificationDataSet t1 = FixedProblems.getCircles(1000, 0.1, 10.0); ClassificationDataSet t2 = FixedProblems.getCircles(1000, 0.1, 10.0); t2.applyTransform(new LinearTransform(t2)); int errors; instance = instance.clone(); instance.train(t1); ModestAdaBoost result = instance.clone(); errors = 0; for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - result.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); result.train(t2); for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - instance.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); for (int i = 0; i < t2.size(); i++) errors += Math.abs(t2.getDataPointCategory(i) - result.classify(t2.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); } }
3,947
28.029412
119
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/boosting/SAMMETest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.boosting; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.*; import jsat.classifiers.trees.*; import jsat.utils.SystemInfo; import org.junit.*; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class SAMMETest { public SAMMETest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); SAMME instance = new SAMME(new DecisionTree(2, 2, TreePruner.PruningMethod.NONE, 0.1), 50); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0, 100.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0, 100.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train, true); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.15); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); SAMME instance = new SAMME(new DecisionTree(2, 2, TreePruner.PruningMethod.NONE, 0.1), 50); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0, 100.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0, 100.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.15); } @Test public void testClone() { System.out.println("clone"); SAMME instance = new SAMME(new DecisionTree(10, 10, TreePruner.PruningMethod.NONE, 0.1), 50); ClassificationDataSet t1 = FixedProblems.getCircles(1000, 0.1, 10.0, 100.0); ClassificationDataSet t2 = FixedProblems.getCircles(1000, 0.1, 10.0); int errors; instance = instance.clone(); instance.train(t1); SAMME result = instance.clone(); errors = 0; for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - result.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); result.train(t2); for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - instance.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); for (int i = 0; i < t2.size(); i++) errors += Math.abs(t2.getDataPointCategory(i) - result.classify(t2.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); } }
3,674
27.937008
113
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/boosting/StackingTest.java
package jsat.classifiers.boosting; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.DataPointPair; import jsat.classifiers.OneVSAll; import jsat.classifiers.linear.LinearBatch; import jsat.classifiers.linear.LogisticRegressionDCD; import jsat.classifiers.svm.DCDs; import jsat.lossfunctions.AbsoluteLoss; import jsat.lossfunctions.HuberLoss; import jsat.lossfunctions.SoftmaxLoss; import jsat.lossfunctions.SquaredLoss; import jsat.regression.RegressionDataSet; import jsat.regression.Regressor; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class StackingTest { public StackingTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testClassifyBinary() { System.out.println("binary classifiation"); Stacking stacking = new Stacking(new LogisticRegressionDCD(), new LinearBatch(new SoftmaxLoss(), 1e-15), new LinearBatch(new SoftmaxLoss(), 100), new LinearBatch(new SoftmaxLoss(), 1e10)); ClassificationDataSet train = FixedProblems.get2ClassLinear(500, RandomUtil.getRandom()); stacking = stacking.clone(); stacking.train(train); stacking = stacking.clone(); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), stacking.classify(dpp.getDataPoint()).mostLikely()); } @Test public void testClassifyBinaryMT() { System.out.println("binary classifiation MT"); Stacking stacking = new Stacking(new LogisticRegressionDCD(), new LinearBatch(new SoftmaxLoss(), 1e-15), new LinearBatch(new SoftmaxLoss(), 100), new LinearBatch(new SoftmaxLoss(), 1e10)); ClassificationDataSet train = FixedProblems.get2ClassLinear(500, RandomUtil.getRandom()); stacking = stacking.clone(); stacking.train(train, true); stacking = stacking.clone(); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), stacking.classify(dpp.getDataPoint()).mostLikely()); } @Test public void testClassifyMulti() { Stacking stacking = new Stacking(new OneVSAll(new LogisticRegressionDCD(), true), new LinearBatch(new SoftmaxLoss(), 1e-15), new LinearBatch(new SoftmaxLoss(), 100), new LinearBatch(new SoftmaxLoss(), 1e10)); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(500, 6, RandomUtil.getRandom()); stacking = stacking.clone(); stacking.train(train); stacking = stacking.clone(); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(200, 6, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), stacking.classify(dpp.getDataPoint()).mostLikely()); } @Test public void testClassifyMultiMT() { System.out.println("multi class classification MT"); Stacking stacking = new Stacking(new OneVSAll(new LogisticRegressionDCD(), true), new LinearBatch(new SoftmaxLoss(), 1e-15), new LinearBatch(new SoftmaxLoss(), 100), new LinearBatch(new SoftmaxLoss(), 1e10)); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(500, 6, RandomUtil.getRandom()); stacking = stacking.clone(); stacking.train(train, true); stacking = stacking.clone(); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(200, 6, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), stacking.classify(dpp.getDataPoint()).mostLikely()); } @Test public void testRegression() { System.out.println("regression"); Stacking stacking = new Stacking((Regressor)new DCDs(1000, true), new DCDs(1000, false), new DCDs(1000, 1e-3, 0.5, true)); RegressionDataSet train = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); stacking = stacking.clone(); stacking.train(train); stacking = stacking.clone(); RegressionDataSet test = FixedProblems.getLinearRegression(200, RandomUtil.getRandom()); for(DataPointPair<Double> dpp : test.getAsDPPList()) { double truth = dpp.getPair(); double pred = stacking.regress(dpp.getDataPoint()); double relErr = (truth-pred)/truth; assertEquals(0, relErr, 0.1); } } @Test public void testRegressionMT() { System.out.println("regression MT"); Stacking stacking = new Stacking((Regressor)new DCDs(1000, true), new DCDs(1000, false), new DCDs(1000, 1e-3, 0.5, true)); RegressionDataSet train = FixedProblems.get2DLinearRegression(500, RandomUtil.getRandom()); stacking = stacking.clone(); stacking.train(train, true); stacking = stacking.clone(); RegressionDataSet test = FixedProblems.get2DLinearRegression(200, RandomUtil.getRandom()); for(DataPointPair<Double> dpp : test.getAsDPPList()) { double truth = dpp.getPair(); double pred = stacking.regress(dpp.getDataPoint()); double relErr = (truth-pred)/truth; assertEquals(0, relErr, 0.1); } } }
6,290
33.95
216
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/boosting/UpdatableStackingTest.java
package jsat.classifiers.boosting; import java.util.*; import jsat.FixedProblems; import jsat.classifiers.*; import jsat.classifiers.linear.*; import jsat.linear.*; import jsat.lossfunctions.*; import jsat.regression.*; import jsat.utils.random.RandomUtil; import org.junit.*; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class UpdatableStackingTest { public UpdatableStackingTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testClassifyBinary() { System.out.println("binary classifiation"); UpdatableStacking stacking = new UpdatableStacking((UpdateableClassifier)new PassiveAggressive(), new LinearSGD(new SoftmaxLoss(), 1e-15, 0), new LinearSGD(new SoftmaxLoss(), 100, 0), new LinearSGD(new SoftmaxLoss(), 0, 100)); ClassificationDataSet train = FixedProblems.get2ClassLinear(500, RandomUtil.getRandom()); stacking = stacking.clone(); stacking.train(train); stacking = stacking.clone(); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), stacking.classify(dpp.getDataPoint()).mostLikely()); } @Test public void testClassifyMulti() { UpdatableStacking stacking = new UpdatableStacking(new SPA(), new LinearSGD(new SoftmaxLoss(), 1e-15, 0), new LinearSGD(new SoftmaxLoss(), 100, 0), new LinearSGD(new SoftmaxLoss(), 0, 100)); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(500, 6, RandomUtil.getRandom()); stacking = stacking.clone(); stacking.train(train); stacking = stacking.clone(); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(200, 6, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), stacking.classify(dpp.getDataPoint()).mostLikely()); } @Test public void testRegression() { System.out.println("regression"); Vec coef = DenseVector.toDenseVec(2.5, 1.5, 1, 0.2); List<UpdateableRegressor> models = new ArrayList<UpdateableRegressor>(); LinearSGD tmp = new LinearSGD(new SquaredLoss(), 1e-15, 0); tmp.setUseBias(false); models.add(tmp.clone()); tmp.setLambda1(0.9); models.add(tmp.clone()); tmp.setLambda1(0); tmp.setLambda0(0.9); models.add(tmp.clone()); UpdatableStacking stacking = new UpdatableStacking(new PassiveAggressive(), models); RegressionDataSet train = FixedProblems.getLinearRegression(15000, RandomUtil.getRandom(), coef); stacking = stacking.clone(); stacking.train(train); stacking = stacking.clone(); RegressionDataSet test = FixedProblems.getLinearRegression(500, RandomUtil.getRandom(), coef); for(DataPointPair<Double> dpp : test.getAsDPPList()) { double truth = dpp.getPair(); double pred = stacking.regress(dpp.getDataPoint()); assertEquals(0, (truth-pred), 0.3); } } }
3,578
28.825
234
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/boosting/WaggingNormalTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.boosting; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.ClassificationModelEvaluation; import jsat.classifiers.Classifier; import jsat.classifiers.trees.DecisionTree; import jsat.datatransform.LinearTransform; import jsat.regression.RegressionDataSet; import jsat.regression.RegressionModelEvaluation; import jsat.regression.Regressor; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class WaggingNormalTest { public WaggingNormalTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_RegressionDataSet() { System.out.println("train"); WaggingNormal instance = new WaggingNormal((Regressor)new DecisionTree(), 50); RegressionDataSet train = FixedProblems.getLinearRegression(1000, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 1.0); } @Test public void testTrainC_RegressionDataSet_ExecutorService() { System.out.println("train"); WaggingNormal instance = new WaggingNormal((Regressor)new DecisionTree(), 50); RegressionDataSet train = FixedProblems.getLinearRegression(1000, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train, true); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 1.0); } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); WaggingNormal instance = new WaggingNormal((Classifier)new DecisionTree(), 50); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.05); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); WaggingNormal instance = new WaggingNormal((Classifier)new DecisionTree(), 50); ClassificationDataSet train = FixedProblems.getCircles(1000, .1, 10.0); ClassificationDataSet test = FixedProblems.getCircles(100, .1, 10.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.05); } @Test public void testClone() { System.out.println("clone"); WaggingNormal instance = new WaggingNormal((Classifier)new DecisionTree(), 50); ClassificationDataSet t1 = FixedProblems.getCircles(1000, 0.1, 10.0); ClassificationDataSet t2 = FixedProblems.getCircles(1000, 0.1, 10.0); t2.applyTransform(new LinearTransform(t2)); int errors; instance = instance.clone(); instance.train(t1); WaggingNormal result = instance.clone(); errors = 0; for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - result.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); result.train(t2); for (int i = 0; i < t1.size(); i++) errors += Math.abs(t1.getDataPointCategory(i) - instance.classify(t1.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); for (int i = 0; i < t2.size(); i++) errors += Math.abs(t2.getDataPointCategory(i) - result.classify(t2.getDataPoint(i)).mostLikely()); assertTrue(errors < 100); } }
5,365
29.488636
113
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/calibration/IsotonicCalibrationTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.calibration; import jsat.FixedProblems; import jsat.classifiers.CategoricalData; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.DataPoint; import jsat.classifiers.svm.DCDs; import jsat.datatransform.LinearTransform; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class IsotonicCalibrationTest { public IsotonicCalibrationTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrain() { System.out.println("calibrate"); ClassificationDataSet cds = new ClassificationDataSet(1, new CategoricalData[0], new CategoricalData(2)); for(double pos = 0; pos < 2; pos += 0.01) cds.addDataPoint(DenseVector.toDenseVec(pos), 0); for(double pos = 1; pos < 3; pos += 0.01) cds.addDataPoint(DenseVector.toDenseVec(pos), 1); for(BinaryCalibration.CalibrationMode mode : BinaryCalibration.CalibrationMode.values()) { IsotonicCalibration pc = new IsotonicCalibration(new DCDs(), mode); pc.train(cds); for(int i = 0; i < cds.size(); i++) { DataPoint dp = cds.getDataPoint(i); Vec v = dp.getNumericalValues(); if(v.get(0) < 0.75) assertEquals(1.0, pc.classify(dp).getProb(0), 0.2); else if(1.3 < v.get(0) && v.get(0) < 1.7) assertEquals(0.5, pc.classify(dp).getProb(0), 0.25); else if(2.25 < v.get(0)) assertEquals(0.0, pc.classify(dp).getProb(0), 0.2); } } } @Test public void testClone() { System.out.println("clone"); ClassificationDataSet t1 = FixedProblems.getSimpleKClassLinear(1000, 2, RandomUtil.getRandom()); ClassificationDataSet t2 = FixedProblems.getSimpleKClassLinear(1000, 2, RandomUtil.getRandom()); t2.applyTransform(new LinearTransform(t2, 100, 105)); IsotonicCalibration instance = new IsotonicCalibration(new DCDs(), BinaryCalibration.CalibrationMode.NAIVE); instance = instance.clone(); instance.train(t1); IsotonicCalibration result = instance.clone(); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), result.classify(t1.getDataPoint(i)).mostLikely()); result.train(t2); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), instance.classify(t1.getDataPoint(i)).mostLikely()); for(int i = 0; i < t2.size(); i++) assertEquals(t2.getDataPointCategory(i), result.classify(t2.getDataPoint(i)).mostLikely()); } }
4,008
29.838462
116
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/calibration/PlattCalibrationTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.calibration; import jsat.FixedProblems; import jsat.classifiers.CategoricalData; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.DataPoint; import jsat.classifiers.linear.LogisticRegressionDCD; import jsat.classifiers.svm.DCDs; import jsat.datatransform.LinearTransform; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class PlattCalibrationTest { public PlattCalibrationTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrain() { System.out.println("calibrate"); ClassificationDataSet cds = new ClassificationDataSet(1, new CategoricalData[0], new CategoricalData(2)); for(double pos = 0; pos < 2; pos += 0.01) cds.addDataPoint(DenseVector.toDenseVec(pos), 0); for(double pos = 1; pos < 3; pos += 0.01) cds.addDataPoint(DenseVector.toDenseVec(pos), 1); for(BinaryCalibration.CalibrationMode mode : BinaryCalibration.CalibrationMode.values()) { PlattCalibration pc = new PlattCalibration(new DCDs(), mode); pc.train(cds); for(int i = 0; i < cds.size(); i++) { DataPoint dp = cds.getDataPoint(i); Vec v = dp.getNumericalValues(); if(v.get(0) < 0.25) assertEquals(1.0, pc.classify(dp).getProb(0), 0.2); else if(1.3 < v.get(0) && v.get(0) < 1.7) assertEquals(0.5, pc.classify(dp).getProb(0), 0.35); else if(2.75 < v.get(0)) assertEquals(0.0, pc.classify(dp).getProb(0), 0.2); } } } @Test public void testClone() { System.out.println("clone"); ClassificationDataSet t1 = FixedProblems.getSimpleKClassLinear(1000, 2, RandomUtil.getRandom()); ClassificationDataSet t2 = FixedProblems.getSimpleKClassLinear(1000, 2, RandomUtil.getRandom()); t2.applyTransform(new LinearTransform(t2, 100, 105)); PlattCalibration instance = new PlattCalibration(new DCDs(), BinaryCalibration.CalibrationMode.NAIVE); instance = instance.clone(); instance.train(t1); PlattCalibration result = instance.clone(); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), result.classify(t1.getDataPoint(i)).mostLikely()); result.train(t2); for(int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), instance.classify(t1.getDataPoint(i)).mostLikely()); for(int i = 0; i < t2.size(); i++) assertEquals(t2.getDataPointCategory(i), result.classify(t2.getDataPoint(i)).mostLikely()); } }
4,042
29.628788
113
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/evaluation/AUCTest.java
package jsat.classifiers.evaluation; import jsat.classifiers.evaluation.AUC; import jsat.classifiers.CategoricalData; import jsat.classifiers.CategoricalResults; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class AUCTest { public AUCTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getScore method, of class AUC. */ @Test public void testGetScore() { System.out.println("getScore"); AUC scorer = new AUC(); AUC otherHalf = scorer.clone(); assertEquals(scorer, otherHalf); assertEquals(scorer.hashCode(), otherHalf.hashCode()); assertFalse(scorer.lowerIsBetter()); assertFalse(scorer.equals("")); assertFalse(scorer.hashCode() == "".hashCode()); scorer.prepare(new CategoricalData(2)); otherHalf.prepare(new CategoricalData(2)); scorer.addResult(new CategoricalResults(new double[]{0.2, 0.8}), 1, 3.0); scorer.addResult(new CategoricalResults(new double[]{0.4, 0.6}), 0, 2.0); scorer.addResult(new CategoricalResults(new double[]{0.6, 0.4}), 1, 1.0); otherHalf.addResult(new CategoricalResults(new double[]{0.7, 0.3}), 0, 1.0); otherHalf.addResult(new CategoricalResults(new double[]{0.9, 0.1}), 1, 1.0); otherHalf.addResult(new CategoricalResults(new double[]{1.0, 0.0}), 0, 1.0); scorer.addResults(otherHalf); double P = 2.0+1.0+1.0; double N = 3.0+1.0+1.0; //AUC dosn't make as much sense with so few data points... assertEquals((3+2)/(P*N), scorer.getScore(), 1e-1); assertEquals((3+2)/(P*N), scorer.clone().getScore(), 1e-1); } }
2,139
23.883721
84
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/evaluation/AccuracyTest.java
package jsat.classifiers.evaluation; import jsat.classifiers.evaluation.Accuracy; import jsat.classifiers.CategoricalData; import jsat.classifiers.CategoricalResults; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class AccuracyTest { public AccuracyTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getScore method, of class Accuracy. */ @Test public void testGetScore() { System.out.println("getScore"); Accuracy scorer = new Accuracy(); Accuracy otherHalf = scorer.clone(); assertEquals(scorer, otherHalf); assertEquals(scorer.hashCode(), otherHalf.hashCode()); assertFalse(scorer.lowerIsBetter()); assertFalse(scorer.equals("")); assertFalse(scorer.hashCode() == "".hashCode()); scorer.prepare(new CategoricalData(4)); otherHalf.prepare(new CategoricalData(4)); //from "On Using and Computing the Kappa Statistic" //correct scorer.addResult(new CategoricalResults(new double[]{1.0, 0.0, 0.0, 0.0}), 0, 317.0); otherHalf.addResult(new CategoricalResults(new double[]{0.0, 1.0, 0.0, 0.0}), 1, 120.0); scorer.addResult(new CategoricalResults(new double[]{0.0, 0.0, 1.0, 0.0}), 2, 60.0); otherHalf.addResult(new CategoricalResults(new double[]{0.0, 0.0, 0.0, 1.0}), 3, 8.0); //wrong scorer.addResult(new CategoricalResults(new double[]{0.0, 1.0, 0.0, 0.0}), 0, 23.0); otherHalf.addResult(new CategoricalResults(new double[]{1.0, 0.0, 0.0, 0.0}), 1, 61.0); scorer.addResult(new CategoricalResults(new double[]{0.0, 1.0, 0.0, 0.0}), 2, 4.0); otherHalf.addResult(new CategoricalResults(new double[]{1.0, 0.0, 0.0, 0.0}), 2, 2.0); scorer.addResult(new CategoricalResults(new double[]{0.0, 1.0, 0.0, 0.0}), 3, 29.0); otherHalf.addResult(new CategoricalResults(new double[]{1.0, 0.0, 0.0, 0.0}), 3, 35.0); scorer.addResults(otherHalf); assertEquals((317+120+60+8)/(317+120+60+8+23+61+4+2+29+35.0), scorer.getScore(), 1e-3); assertEquals((317+120+60+8)/(317+120+60+8+23+61+4+2+29+35.0), scorer.clone().getScore(), 1e-3); } }
2,619
29.823529
103
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/evaluation/F1ScoreTest.java
package jsat.classifiers.evaluation; import jsat.classifiers.evaluation.F1Score; import jsat.classifiers.CategoricalData; import jsat.classifiers.CategoricalResults; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class F1ScoreTest { public F1ScoreTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getScore method, of class F1Score. */ @Test public void testGetScore() { System.out.println("getScore"); F1Score scorer = new F1Score(); F1Score otherHalf = scorer.clone(); assertEquals(scorer, otherHalf); assertEquals(scorer.hashCode(), otherHalf.hashCode()); assertFalse(otherHalf.lowerIsBetter()); assertFalse(scorer.equals("")); assertFalse(scorer.hashCode() == "".hashCode()); scorer.prepare(new CategoricalData(2)); otherHalf.prepare(new CategoricalData(2)); //correct scorer.addResult(new CategoricalResults(new double[]{1.0, 0.0}), 0, 1.0); otherHalf.addResult(new CategoricalResults(new double[]{0.2, 0.8}), 1, 3.0); scorer.addResult(new CategoricalResults(new double[]{7.0, 0.3}), 0, 1.0); //wrong otherHalf.addResult(new CategoricalResults(new double[]{0.6, 0.4}), 1, 1.0); scorer.addResult(new CategoricalResults(new double[]{0.4, 0.6}), 0, 2.0); otherHalf.addResult(new CategoricalResults(new double[]{0.9, 0.1}), 1, 1.0); scorer.addResults(otherHalf); double tp = 2, tn = 3, fp = 2, fn = 2; assertEquals(2*tp/(2*tp+fp+fn), scorer.getScore(), 1e-2); assertEquals(2*tp/(2*tp+fp+fn), scorer.clone().getScore(), 1e-2); } }
2,091
24.82716
84
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/evaluation/FbetaScoreTest.java
package jsat.classifiers.evaluation; import jsat.classifiers.evaluation.FbetaScore; import jsat.classifiers.CategoricalData; import jsat.classifiers.CategoricalResults; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class FbetaScoreTest { public FbetaScoreTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getScore method, of class FbetaScore. */ @Test public void testGetScore() { System.out.println("getScore"); FbetaScore scorer = new FbetaScore(1.0); FbetaScore otherHalf = scorer.clone(); assertEquals(scorer, otherHalf); assertEquals(scorer.hashCode(), otherHalf.hashCode()); assertFalse(otherHalf.lowerIsBetter()); assertFalse(scorer.equals("")); assertFalse(scorer.hashCode() == "".hashCode()); scorer.prepare(new CategoricalData(2)); otherHalf.prepare(new CategoricalData(2)); //correct scorer.addResult(new CategoricalResults(new double[]{1.0, 0.0}), 0, 1.0); otherHalf.addResult(new CategoricalResults(new double[]{0.2, 0.8}), 1, 3.0); scorer.addResult(new CategoricalResults(new double[]{7.0, 0.3}), 0, 1.0); //wrong otherHalf.addResult(new CategoricalResults(new double[]{0.6, 0.4}), 1, 1.0); scorer.addResult(new CategoricalResults(new double[]{0.4, 0.6}), 0, 2.0); otherHalf.addResult(new CategoricalResults(new double[]{0.9, 0.1}), 1, 1.0); scorer.addResults(otherHalf); double tp = 2, tn = 3, fp = 2, fn = 2; assertEquals(2*tp/(2*tp+fp+fn), scorer.getScore(), 1e-2); assertEquals(2*tp/(2*tp+fp+fn), scorer.clone().getScore(), 1e-2); scorer = new FbetaScore(2.0); assertFalse(scorer.equals(otherHalf)); assertFalse(scorer.hashCode() == otherHalf.hashCode()); scorer.prepare(new CategoricalData(2)); //correct scorer.addResult(new CategoricalResults(new double[]{1.0, 0.0}), 0, 1.0); scorer.addResult(new CategoricalResults(new double[]{0.2, 0.8}), 1, 3.0); scorer.addResult(new CategoricalResults(new double[]{7.0, 0.3}), 0, 1.0); //wrong scorer.addResult(new CategoricalResults(new double[]{0.6, 0.4}), 1, 1.0); scorer.addResult(new CategoricalResults(new double[]{0.4, 0.6}), 0, 2.0); scorer.addResult(new CategoricalResults(new double[]{0.9, 0.1}), 1, 1.0); assertEquals(5*tp/(5*tp+fp+4*fn), scorer.getScore(), 1e-2); } }
2,932
29.552083
84
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/evaluation/KappaTest.java
package jsat.classifiers.evaluation; import jsat.classifiers.evaluation.Kappa; import jsat.classifiers.CategoricalData; import jsat.classifiers.CategoricalResults; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class KappaTest { public KappaTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getScore method, of class Kappa. */ @Test public void testGetScore() { System.out.println("getScore"); Kappa scorer = new Kappa(); Kappa otherHalf = scorer.clone(); assertEquals(scorer, otherHalf); assertEquals(scorer.hashCode(), otherHalf.hashCode()); assertFalse(otherHalf.lowerIsBetter()); assertFalse(scorer.equals("")); assertFalse(scorer.hashCode() == "".hashCode()); scorer.prepare(new CategoricalData(4)); otherHalf.prepare(new CategoricalData(4)); //from "On Using and Computing the Kappa Statistic" //correct scorer.addResult(new CategoricalResults(new double[]{1.0, 0.0, 0.0, 0.0}), 0, 317.0); otherHalf.addResult(new CategoricalResults(new double[]{0.0, 1.0, 0.0, 0.0}), 1, 120.0); scorer.addResult(new CategoricalResults(new double[]{0.0, 0.0, 1.0, 0.0}), 2, 60.0); otherHalf.addResult(new CategoricalResults(new double[]{0.0, 0.0, 0.0, 1.0}), 3, 8.0); //wrong scorer.addResult(new CategoricalResults(new double[]{0.0, 1.0, 0.0, 0.0}), 0, 23.0); otherHalf.addResult(new CategoricalResults(new double[]{1.0, 0.0, 0.0, 0.0}), 1, 61.0); scorer.addResult(new CategoricalResults(new double[]{0.0, 1.0, 0.0, 0.0}), 2, 4.0); otherHalf.addResult(new CategoricalResults(new double[]{1.0, 0.0, 0.0, 0.0}), 2, 2.0); scorer.addResult(new CategoricalResults(new double[]{0.0, 1.0, 0.0, 0.0}), 3, 29.0); otherHalf.addResult(new CategoricalResults(new double[]{1.0, 0.0, 0.0, 0.0}), 3, 35.0); scorer.addResults(otherHalf); assertEquals(0.605, scorer.getScore(), 1e-3); assertEquals(0.605, scorer.clone().getScore(), 1e-3); } }
2,508
28.869048
96
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/evaluation/LogLossTest.java
package jsat.classifiers.evaluation; import jsat.classifiers.evaluation.LogLoss; import jsat.classifiers.CategoricalData; import jsat.classifiers.CategoricalResults; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class LogLossTest { public LogLossTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getScore method, of class LogLoss. */ @Test public void testGetScore() { System.out.println("getScore"); LogLoss scorer = new LogLoss(); LogLoss otherHalf = scorer.clone(); assertEquals(scorer, otherHalf); assertEquals(scorer.hashCode(), otherHalf.hashCode()); assertTrue(otherHalf.lowerIsBetter()); assertFalse(scorer.equals("")); assertFalse(scorer.hashCode() == "".hashCode()); scorer.prepare(new CategoricalData(4)); otherHalf.prepare(new CategoricalData(4)); //from "On Using and Computing the Kappa Statistic" //correct scorer.addResult(new CategoricalResults(new double[]{0.9, 0.1, 0.0, 0.0}), 0, 317.0); otherHalf.addResult(new CategoricalResults(new double[]{0.0, 0.8, 0.2, 0.0}), 1, 120.0); scorer.addResult(new CategoricalResults(new double[]{0.0, 0.0, 0.9, 0.0}), 2, 60.0); otherHalf.addResult(new CategoricalResults(new double[]{0.0, 0.0, 0.0, 1.0}), 3, 8.0); //wrong scorer.addResult(new CategoricalResults(new double[]{0.1, 0.9, 0.0, 0.0}), 0, 23.0); otherHalf.addResult(new CategoricalResults(new double[]{0.0, 0.2, 0.9, 0.0}), 1, 61.0); scorer.addResults(otherHalf); double loss = 317*Math.log(0.9); loss += 120*Math.log(0.8); loss += 60*Math.log(0.9); loss += 8*Math.log(1.0); loss += 23*Math.log(0.1); loss += 61*Math.log(0.2); assertEquals(-loss/(317+120+60+8+23+61), scorer.getScore(), 1e-3); assertEquals(-loss/(317+120+60+8+23+61), scorer.clone().getScore(), 1e-3); } }
2,409
26.386364
96
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/evaluation/MatthewsCorrelationCoefficientTest.java
package jsat.classifiers.evaluation; import jsat.classifiers.evaluation.MatthewsCorrelationCoefficient; import jsat.classifiers.CategoricalData; import jsat.classifiers.CategoricalResults; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class MatthewsCorrelationCoefficientTest { public MatthewsCorrelationCoefficientTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getScore method, of class MatthewsCorrelationCoefficient. */ @Test public void testGetScore() { System.out.println("getScore"); MatthewsCorrelationCoefficient scorer = new MatthewsCorrelationCoefficient(); MatthewsCorrelationCoefficient otherHalf = scorer.clone(); assertEquals(scorer, otherHalf); assertEquals(scorer.hashCode(), otherHalf.hashCode()); assertFalse(otherHalf.lowerIsBetter()); assertFalse(scorer.equals("")); assertFalse(scorer.hashCode() == "".hashCode()); scorer.prepare(new CategoricalData(2)); otherHalf.prepare(new CategoricalData(2)); //correct scorer.addResult(new CategoricalResults(new double[]{1.0, 0.0}), 0, 1.0); otherHalf.addResult(new CategoricalResults(new double[]{0.2, 0.8}), 1, 3.0); scorer.addResult(new CategoricalResults(new double[]{7.0, 0.3}), 0, 1.0); //wrong otherHalf.addResult(new CategoricalResults(new double[]{0.6, 0.4}), 1, 1.0); scorer.addResult(new CategoricalResults(new double[]{0.4, 0.6}), 0, 2.0); otherHalf.addResult(new CategoricalResults(new double[]{0.9, 0.1}), 1, 1.0); scorer.addResults(otherHalf); double tp = 2, tn = 3, fp = 2, fn = 2; assertEquals((tp*tn-fp*fn)/Math.sqrt((tp+fp)*(tp+fn)*(tn+fp)*(tn+fn)), scorer.getScore(), 1e-2); assertEquals((tp*tn-fp*fn)/Math.sqrt((tp+fp)*(tp+fn)*(tn+fp)*(tn+fn)), scorer.clone().getScore(), 1e-2); } }
2,316
28.329114
112
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/evaluation/PrecisionTest.java
package jsat.classifiers.evaluation; import jsat.classifiers.evaluation.Precision; import jsat.classifiers.CategoricalData; import jsat.classifiers.CategoricalResults; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class PrecisionTest { public PrecisionTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getScore method, of class Precision. */ @Test public void testGetScore() { System.out.println("getScore"); Precision scorer = new Precision(); Precision otherHalf = scorer.clone(); assertEquals(scorer, otherHalf); assertEquals(scorer.hashCode(), otherHalf.hashCode()); assertFalse(otherHalf.lowerIsBetter()); assertFalse(scorer.equals("")); assertFalse(scorer.hashCode() == "".hashCode()); scorer.prepare(new CategoricalData(2)); otherHalf.prepare(new CategoricalData(2)); //correct scorer.addResult(new CategoricalResults(new double[]{1.0, 0.0}), 0, 1.0); otherHalf.addResult(new CategoricalResults(new double[]{0.2, 0.8}), 1, 3.0); scorer.addResult(new CategoricalResults(new double[]{7.0, 0.3}), 0, 1.0); //wrong otherHalf.addResult(new CategoricalResults(new double[]{0.6, 0.4}), 1, 1.0); scorer.addResult(new CategoricalResults(new double[]{0.4, 0.6}), 0, 2.0); otherHalf.addResult(new CategoricalResults(new double[]{0.9, 0.1}), 1, 1.0); scorer.addResults(otherHalf); double tp = 2, tn = 3, fp = 2, fn = 2; assertEquals(tp/(tp*+fp), scorer.getScore(), 1e-2); assertEquals(tp/(tp*+fp), scorer.clone().getScore(), 1e-2); } }
2,088
25.1125
84
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/evaluation/RecallTest.java
package jsat.classifiers.evaluation; import jsat.classifiers.evaluation.Recall; import jsat.classifiers.CategoricalData; import jsat.classifiers.CategoricalResults; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class RecallTest { public RecallTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getScore method, of class Recall. */ @Test public void testGetScore() { System.out.println("getScore"); Recall scorer = new Recall(); Recall otherHalf = scorer.clone(); assertEquals(scorer, otherHalf); assertEquals(scorer.hashCode(), otherHalf.hashCode()); assertFalse(otherHalf.lowerIsBetter()); assertFalse(scorer.equals("")); assertFalse(scorer.hashCode() == "".hashCode()); scorer.prepare(new CategoricalData(2)); otherHalf.prepare(new CategoricalData(2)); //correct scorer.addResult(new CategoricalResults(new double[]{1.0, 0.0}), 0, 1.0); otherHalf.addResult(new CategoricalResults(new double[]{0.2, 0.8}), 1, 3.0); scorer.addResult(new CategoricalResults(new double[]{7.0, 0.3}), 0, 1.0); //wrong otherHalf.addResult(new CategoricalResults(new double[]{0.6, 0.4}), 1, 1.0); scorer.addResult(new CategoricalResults(new double[]{0.4, 0.6}), 0, 2.0); otherHalf.addResult(new CategoricalResults(new double[]{0.9, 0.1}), 1, 1.0); double tp = 2, tn = 3, fp = 2, fn = 2; assertEquals(tp/(tp*+fn), scorer.getScore(), 1e-2); assertEquals(tp/(tp*+fn), scorer.clone().getScore(), 1e-2); } }
2,020
24.910256
84
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/imbalance/BorderlineSMOTETest.java
/* * Copyright (C) 2017 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.imbalance; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.DataPointPair; import jsat.classifiers.linear.LogisticRegressionDCD; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * To make sure these tests exercise the danger list code in SMOTE, we push the * two target classes closer together during training time to increase overlap. * But then use a wider separate at testing time to make sure we get a * consistently runnable test case. * * @author Edward Raff */ public class BorderlineSMOTETest { static boolean parallelTrain = true; public BorderlineSMOTETest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); ClassificationDataSet train = FixedProblems.get2ClassLinear2D(200, 20, 0.5, RandomUtil.getRandom()); BorderlineSMOTE smote = new BorderlineSMOTE(new LogisticRegressionDCD(), false); smote.train(train, parallelTrain); ClassificationDataSet test = FixedProblems.get2ClassLinear2D(200, 200, 4.0, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), smote.classify(dpp.getDataPoint()).mostLikely()); smote = smote.clone(); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), smote.classify(dpp.getDataPoint()).mostLikely()); smote = new BorderlineSMOTE(new LogisticRegressionDCD(), true); smote.train(train, parallelTrain); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), smote.classify(dpp.getDataPoint()).mostLikely()); smote = smote.clone(); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), smote.classify(dpp.getDataPoint()).mostLikely()); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); ClassificationDataSet train = FixedProblems.get2ClassLinear2D(200, 20, 0.5, RandomUtil.getRandom()); BorderlineSMOTE smote = new BorderlineSMOTE(new LogisticRegressionDCD(), true); smote.train(train); ClassificationDataSet test = FixedProblems.get2ClassLinear2D(200, 200, 4.0, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), smote.classify(dpp.getDataPoint()).mostLikely()); smote = smote.clone(); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), smote.classify(dpp.getDataPoint()).mostLikely()); smote = new BorderlineSMOTE(new LogisticRegressionDCD(), false); smote.train(train); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), smote.classify(dpp.getDataPoint()).mostLikely()); smote = smote.clone(); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), smote.classify(dpp.getDataPoint()).mostLikely()); } }
4,641
33.902256
108
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/imbalance/SMOTETest.java
/* * Copyright (C) 2017 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.imbalance; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.DataPointPair; import jsat.classifiers.linear.LogisticRegressionDCD; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class SMOTETest { public SMOTETest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); ClassificationDataSet train = FixedProblems.get2ClassLinear(200, 20, RandomUtil.getRandom()); SMOTE smote = new SMOTE(new LogisticRegressionDCD()); smote.train(train, true); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, 200, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), smote.classify(dpp.getDataPoint()).mostLikely()); smote = smote.clone(); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), smote.classify(dpp.getDataPoint()).mostLikely()); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); ClassificationDataSet train = FixedProblems.get2ClassLinear(200, 20, RandomUtil.getRandom()); SMOTE smote = new SMOTE(new LogisticRegressionDCD()); smote.train(train); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, 200, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), smote.classify(dpp.getDataPoint()).mostLikely()); smote = smote.clone(); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), smote.classify(dpp.getDataPoint()).mostLikely()); } }
3,203
29.807692
101
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/knn/DANNTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.classifiers.knn; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.Classifier; import jsat.distributions.Normal; import jsat.utils.GridDataGenerator; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * @author Edward Raff */ public class DANNTest { static private ClassificationDataSet easyTrain; static private ClassificationDataSet easyTest; static private DANN dann; public DANNTest() { } @BeforeClass public static void setUpClass() { GridDataGenerator gdg = new GridDataGenerator(new Normal(0, 0.05), new Random(12), 2); easyTrain = new ClassificationDataSet(gdg.generateData(80).getList(), 0); easyTest = new ClassificationDataSet(gdg.generateData(40).getList(), 0); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { dann = new DANN(20, 1); } @After public void tearDown() { } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); dann.train(easyTrain); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), dann.classify(easyTest.getDataPoint(i)).mostLikely()); } @Test public void testClone() { System.out.println("clone"); dann.train(easyTrain); Classifier clone = dann.clone(); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), clone.classify(easyTest.getDataPoint(i)).mostLikely()); } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); dann.train(easyTrain, true); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), dann.classify(easyTest.getDataPoint(i)).mostLikely()); } }
2,324
25.420455
114
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/knn/LWLTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.classifiers.knn; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.ClassificationModelEvaluation; import jsat.classifiers.bayesian.NaiveBayesUpdateable; import jsat.classifiers.svm.DCDs; import jsat.linear.distancemetrics.EuclideanDistance; import jsat.regression.*; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.*; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class LWLTest { public LWLTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_RegressionDataSet() { System.out.println("train"); LWL instance = new LWL((Regressor)new DCDs(), 30, new EuclideanDistance()); RegressionDataSet train = FixedProblems.getLinearRegression(5000, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(200, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.3); } @Test public void testTrainC_RegressionDataSet_ExecutorService() { System.out.println("train"); LWL instance = new LWL((Regressor)new DCDs(), 15, new EuclideanDistance()); RegressionDataSet train = FixedProblems.getLinearRegression(5000, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(200, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train, true); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.3); } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); LWL instance = new LWL(new NaiveBayesUpdateable(), 15, new EuclideanDistance()); ClassificationDataSet train = FixedProblems.getCircles(5000, 1.0, 10.0, 100.0); ClassificationDataSet test = FixedProblems.getCircles(200, 1.0, 10.0, 100.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train, true); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); LWL instance = new LWL(new NaiveBayesUpdateable(), 15, new EuclideanDistance()); ClassificationDataSet train = FixedProblems.getCircles(5000, 1.0, 10.0, 100.0); ClassificationDataSet test = FixedProblems.getCircles(200, 1.0, 10.0, 100.0); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(instance, train); cme.evaluateTestSet(test); assertTrue(cme.getErrorRate() <= 0.001); } @Test public void testClone() { System.out.println("clone"); LWL instance = new LWL(new NaiveBayesUpdateable(), 15, new EuclideanDistance()); ClassificationDataSet t1 = FixedProblems.getSimpleKClassLinear(100, 3); ClassificationDataSet t2 = FixedProblems.getSimpleKClassLinear(100, 6); instance = instance.clone(); instance.train(t1); LWL result = instance.clone(); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), result.classify(t1.getDataPoint(i)).mostLikely()); result.train(t2); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getDataPointCategory(i), instance.classify(t1.getDataPoint(i)).mostLikely()); for (int i = 0; i < t2.size(); i++) assertEquals(t2.getDataPointCategory(i), result.classify(t2.getDataPoint(i)).mostLikely()); } }
4,859
29.186335
105
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/knn/NearestNeighbourTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.classifiers.knn; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.Classifier; import jsat.distributions.Normal; import jsat.regression.RegressionDataSet; import jsat.regression.RegressionModelEvaluation; import jsat.utils.GridDataGenerator; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class NearestNeighbourTest { static private ClassificationDataSet easyTrain; static private ClassificationDataSet easyTest; static private NearestNeighbour nn; static private NearestNeighbour nn2; public NearestNeighbourTest() { } @BeforeClass public static void setUpClass() { GridDataGenerator gdg = new GridDataGenerator(new Normal(0, 0.05), new Random(12), 2); easyTrain = new ClassificationDataSet(gdg.generateData(80).getList(), 0); easyTest = new ClassificationDataSet(gdg.generateData(40).getList(), 0); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { nn = new NearestNeighbour(1, false); nn2 = new NearestNeighbour(1, true); } @After public void tearDown() { } @Test public void testTrainC_RegressionDataSet() { System.out.println("train"); NearestNeighbour instance = new NearestNeighbour(7); RegressionDataSet train = FixedProblems.getLinearRegression(1000, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.5); //test weighted instances instance = new NearestNeighbour(7, true); rme = new RegressionModelEvaluation(instance, train); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.5); } @Test public void testTrainC_RegressionDataSet_ExecutorService() { System.out.println("train"); NearestNeighbour instance = new NearestNeighbour(7); RegressionDataSet train = FixedProblems.getLinearRegression(1000, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train, true); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.5); //test weighted instances instance = new NearestNeighbour(7, true); rme = new RegressionModelEvaluation(instance, train, true); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.5); } @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); nn.train(easyTrain); nn2.train(easyTrain); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), nn.classify(easyTest.getDataPoint(i)).mostLikely()); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), nn2.classify(easyTest.getDataPoint(i)).mostLikely()); } @Test public void testClone() { System.out.println("clone"); nn.train(easyTrain); nn2.train(easyTrain); Classifier clone = nn.clone(); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), clone.classify(easyTest.getDataPoint(i)).mostLikely()); clone = nn2.clone(); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), clone.classify(easyTest.getDataPoint(i)).mostLikely()); } @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); nn.train(easyTrain, true); nn2.train(easyTrain, true); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), nn.classify(easyTest.getDataPoint(i)).mostLikely()); for(int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), nn2.classify(easyTest.getDataPoint(i)).mostLikely()); } }
4,953
31.379085
114
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/linear/ALMA2Test.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.classifiers.linear; import java.util.Random; import jsat.FixedProblems; import jsat.classifiers.*; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class ALMA2Test { public ALMA2Test() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of classify method, of class ALMA2. */ @Test public void testTrain_C() { System.out.println("classify"); ClassificationDataSet train = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); ALMA2 alma = new ALMA2(); alma.setEpochs(1); alma.train(train); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), alma.classify(dpp.getDataPoint()).mostLikely()); } }
1,425
18.805556
100
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/linear/AROWTest.java
package jsat.classifiers.linear; import java.util.Random; import jsat.FixedProblems; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.DataPointPair; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class AROWTest { public AROWTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of classify method, of class AROW. */ @Test public void testTrain_C() { System.out.println("train_C"); ClassificationDataSet train = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); AROW arow0 = new AROW(1, true); AROW arow1 = new AROW(1, false); arow0.train(train); arow1.train(train); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), arow0.classify(dpp.getDataPoint()).mostLikely()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), arow1.classify(dpp.getDataPoint()).mostLikely()); } }
1,586
21.041667
101
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/linear/BBRTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.classifiers.linear; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.Classifier; import jsat.classifiers.DataPointPair; import jsat.parameters.Parameter; import jsat.parameters.Parameterized; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class BBRTest { public BBRTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of train method, of class BBR. */ @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); ClassificationDataSet train = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); for (BBR.Prior prior : BBR.Prior.values()) { BBR lr = new BBR(0.01, 1000, prior); lr.train(train, true); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); for (DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), lr.classify(dpp.getDataPoint()).mostLikely()); } } /** * Test of train method, of class BBR. */ @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); ClassificationDataSet train = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); for (BBR.Prior prior : BBR.Prior.values()) { BBR lr = new BBR(0.01, 1000, prior); lr.train(train); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); for (DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), lr.classify(dpp.getDataPoint()).mostLikely()); } } @Test public void test_reported_bug_params() { Classifier classifier = new jsat.classifiers.linear.BBR(7); if (classifier instanceof Parameterized) { List<Parameter> list = ((Parameterized) classifier).getParameters(); for (final Parameter p : list) { assertNotNull(p.getName()); assertNotNull(p.getValueString()); } } } }
2,934
24.745614
102
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/linear/LinearBatchTest.java
package jsat.classifiers.linear; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.DataPointPair; import jsat.classifiers.svm.DCD; import jsat.classifiers.svm.DCDs; import jsat.datatransform.LinearTransform; import jsat.lossfunctions.*; import jsat.math.OnLineStatistics; import jsat.math.optimization.LBFGS; import jsat.math.optimization.WolfeNWLineSearch; import jsat.regression.RegressionDataSet; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class LinearBatchTest { public LinearBatchTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testClassifyBinary() { System.out.println("binary classifiation"); for(boolean useBias : new boolean[]{false, true}) { LinearBatch linearBatch = new LinearBatch(new HingeLoss(), 1e-4); ClassificationDataSet train = FixedProblems.get2ClassLinear(500, RandomUtil.getRandom()); linearBatch.setUseBiasTerm(useBias); linearBatch.train(train); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), linearBatch.classify(dpp.getDataPoint()).mostLikely()); } } @Test() public void testTrainWarmCFast() { ClassificationDataSet train = FixedProblems.get2ClassLinear(10000, RandomUtil.getRandom()); LinearSGD warmModel = new LinearSGD(new SoftmaxLoss(), 1e-4, 0); warmModel.setEpochs(20); warmModel.train(train); long start, end; LinearBatch notWarm = new LinearBatch(new SoftmaxLoss(), 1e-4); start = System.currentTimeMillis(); notWarm.train(train); end = System.currentTimeMillis(); long normTime = (end-start); LinearBatch warm = new LinearBatch(new SoftmaxLoss(), 1e-4); start = System.currentTimeMillis(); warm.train(train, warmModel); end = System.currentTimeMillis(); long warmTime = (end-start); assertTrue("Warm start wasn't faster? "+warmTime + " vs " + normTime,warmTime < normTime*0.95); } @Test public void testClassifyBinaryMT() { System.out.println("binary classifiation MT"); for(boolean useBias : new boolean[]{false, true}) { LinearBatch linearBatch = new LinearBatch(new LogisticLoss(), 1e-4); ClassificationDataSet train = FixedProblems.get2ClassLinear(500, RandomUtil.getRandom()); linearBatch.setUseBiasTerm(useBias); linearBatch.train(train, true); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), linearBatch.classify(dpp.getDataPoint()).mostLikely()); } } @Test public void testClassifyMulti() { System.out.println("multi class classification"); for(boolean useBias : new boolean[]{false, true}) { LinearBatch linearBatch = new LinearBatch(new HingeLoss(), 1e-4); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(500, 6, RandomUtil.getRandom()); linearBatch.setUseBiasTerm(useBias); linearBatch.train(train); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(200, 6, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), linearBatch.classify(dpp.getDataPoint()).mostLikely()); } } @Test() public void testTrainWarmCMultieFast() { System.out.println("testTrainWarmCMultieFast"); ClassificationDataSet train = FixedProblems.getHalfCircles(1000, RandomUtil.getRandom(), 0.1, 1.0, 5.0); LinearBatch warmModel = new LinearBatch(new HingeLoss(), 1e-2); warmModel.train(train); LinearBatch notWarm = new LinearBatch(new SoftmaxLoss(), 1e-2); notWarm.train(train); LinearBatch warm = new LinearBatch(new SoftmaxLoss(), 1e-2); warm.train(train, warmModel); int origErrors = 0; for(int i = 0; i < train.size(); i++) if(notWarm.classify(train.getDataPoint(i)).mostLikely() != train.getDataPointCategory(i)) origErrors++; int warmErrors = 0; for(int i = 0; i < train.size(); i++) if(warm.classify(train.getDataPoint(i)).mostLikely() != train.getDataPointCategory(i)) warmErrors++; assertTrue("Warm was less acurate? "+warmErrors + " vs " + origErrors,warmErrors <= origErrors*1.15); } @Test public void testClassifyMultiMT() { System.out.println("multi class classification MT"); for(boolean useBias : new boolean[]{false, true}) { LinearBatch linearBatch = new LinearBatch(new SoftmaxLoss(), 1e-4); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(500, 6, RandomUtil.getRandom()); linearBatch.setUseBiasTerm(useBias); linearBatch.train(train, true); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(200, 6, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), linearBatch.classify(dpp.getDataPoint()).mostLikely()); } } @Test public void testRegression() { System.out.println("regression"); for(boolean useBias : new boolean[]{false, true}) { LinearBatch linearBatch = new LinearBatch(new SquaredLoss(), 1e-4); RegressionDataSet train = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); linearBatch.setUseBiasTerm(useBias); linearBatch.train(train); RegressionDataSet test = FixedProblems.getLinearRegression(200, RandomUtil.getRandom()); for(DataPointPair<Double> dpp : test.getAsDPPList()) { double truth = dpp.getPair(); double pred = linearBatch.regress(dpp.getDataPoint()); double relErr = (truth-pred)/truth; assertEquals(0, relErr, 0.1); } } } @Test public void testRegressionMT() { System.out.println("regression MT"); for(boolean useBias : new boolean[]{false, true}) { LinearBatch linearBatch = new LinearBatch(new SquaredLoss(), 1e-4); RegressionDataSet train = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); linearBatch.setOptimizer(new LBFGS(10, 10000, new WolfeNWLineSearch())); linearBatch.setTolerance(1e-4); linearBatch.setUseBiasTerm(useBias); linearBatch.train(train, true); RegressionDataSet test = FixedProblems.getLinearRegression(200, RandomUtil.getRandom()); OnLineStatistics avgRelErr = new OnLineStatistics(); for(DataPointPair<Double> dpp : test.getAsDPPList()) { double truth = dpp.getPair(); double pred = linearBatch.regress(dpp.getDataPoint()); double relErr = (truth-pred)/truth; avgRelErr.add(relErr); } assertEquals(0, avgRelErr.getMean(), 0.05); } } @Test() public void testTrainWarmRFast() { RegressionDataSet train = FixedProblems.getLinearRegression(100000, RandomUtil.getRandom()); train.applyTransform(new LinearTransform(train));//make this range better for convergence check LinearBatch warmModel = new LinearBatch(new SquaredLoss(), 1e-4); warmModel.train(train); long start, end; LinearBatch notWarm = new LinearBatch(new SquaredLoss(), 1e-4); start = System.currentTimeMillis(); notWarm.train(train); end = System.currentTimeMillis(); long normTime = (end-start); LinearBatch warm = new LinearBatch(new SquaredLoss(), 1e-4); start = System.currentTimeMillis(); warm.train(train, warmModel); end = System.currentTimeMillis(); long warmTime = (end-start); assertTrue("Warm start slower? "+warmTime + " vs " + normTime,warmTime <= normTime*1.05); assertTrue(warm.getRawWeight(0).equals(notWarm.getRawWeight(0), 1e-2)); } }
9,423
32.183099
112
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/linear/LinearL1SCDTest.java
package jsat.classifiers.linear; import java.util.Random; import jsat.FixedProblems; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.DataPointPair; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward */ public class LinearL1SCDTest { public LinearL1SCDTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of train method, of class LinearL1SCD. */ @Test public void testTrain_RegressionDataSet() { System.out.println("train"); Random rand = new Random(123); LinearL1SCD scd = new LinearL1SCD(); scd.setMinScaled(-1); scd.setLoss(StochasticSTLinearL1.Loss.SQUARED); scd.train(FixedProblems.getLinearRegression(400, rand)); for(DataPointPair<Double> dpp : FixedProblems.getLinearRegression(400, rand).getAsDPPList()) { double truth = dpp.getPair(); double pred = scd.regress(dpp.getDataPoint()); double relErr = (truth-pred)/truth; assertEquals(0.0, relErr, 0.1);//Give it a decent wiggle room b/c of regularization } } /** * Test of train method, of class LinearL1SCD. */ @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); ClassificationDataSet train = FixedProblems.get2ClassLinear(400, RandomUtil.getRandom()); LinearL1SCD scd = new LinearL1SCD(); scd.setLoss(StochasticSTLinearL1.Loss.LOG); scd.train(train); ClassificationDataSet test = FixedProblems.get2ClassLinear(400, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), scd.classify(dpp.getDataPoint()).mostLikely()); } }
2,227
23.217391
100
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/linear/LinearSGDTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.classifiers.linear; import java.util.Random; import jsat.FixedProblems; import jsat.TestTools; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.DataPointPair; import jsat.lossfunctions.HingeLoss; import jsat.lossfunctions.SquaredLoss; import jsat.math.optimization.stochastic.AdaGrad; import jsat.math.optimization.stochastic.GradientUpdater; import jsat.math.optimization.stochastic.RMSProp; import jsat.math.optimization.stochastic.SimpleSGD; import jsat.regression.RegressionDataSet; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class LinearSGDTest { public LinearSGDTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } static boolean[] useBiasOptions = new boolean[]{true, false}; static GradientUpdater[] updaters = new GradientUpdater[]{new SimpleSGD(), new AdaGrad(), new RMSProp()}; @Test public void testClassifyBinary() { System.out.println("binary classifiation"); for(boolean useBias : useBiasOptions) { for(GradientUpdater gu : updaters) { LinearSGD linearsgd = new LinearSGD(new HingeLoss(), 1e-4, 1e-5); linearsgd.setUseBias(useBias); linearsgd.setGradientUpdater(gu); ClassificationDataSet train = FixedProblems.get2ClassLinear(500, RandomUtil.getRandom()); linearsgd.train(train); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), linearsgd.classify(dpp.getDataPoint()).mostLikely()); } } } @Test public void testClassifyMulti() { System.out.println("multi class classification"); for(boolean useBias : useBiasOptions) { for(GradientUpdater gu : updaters) { LinearSGD linearsgd = new LinearSGD(new HingeLoss(), 1e-4, 1e-5); linearsgd.setUseBias(useBias); linearsgd.setGradientUpdater(gu); ClassificationDataSet train = FixedProblems.getSimpleKClassLinear(500, 6, RandomUtil.getRandom()); linearsgd.train(train); ClassificationDataSet test = FixedProblems.getSimpleKClassLinear(200, 6, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), linearsgd.classify(dpp.getDataPoint()).mostLikely()); } } } @Test public void testRegression() { System.out.println("regression"); for(boolean useBias : useBiasOptions) { for(GradientUpdater gu : updaters) { LinearSGD linearsgd = new LinearSGD(new SquaredLoss(), 0.0, 0.0); linearsgd.setUseBias(useBias); linearsgd.setGradientUpdater(gu); //SGD needs more iterations/data to learn a really close fit linearsgd.setEpochs(50); if(!(gu instanceof SimpleSGD))//the others need a higher learning rate than the default { linearsgd.setEta(0.5); linearsgd.setEpochs(100);//more iters b/c RMSProp probably isn't the best for this overly simple problem } int tries = 4; do { if(TestTools.regressEvalLinear(linearsgd, 10000, 200)) break; } while(tries-- > 0); assertTrue(tries > 0); } } } }
4,294
29.034965
124
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/linear/LogisticRegressionDCDTest.java
package jsat.classifiers.linear; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.*; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class LogisticRegressionDCDTest { public LogisticRegressionDCDTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of train method, of class LogisticRegressionDCD. */ @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); ClassificationDataSet train = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); LogisticRegressionDCD lr = new LogisticRegressionDCD(); lr.train(train, true); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), lr.classify(dpp.getDataPoint()).mostLikely()); } /** * Test of train method, of class LogisticRegressionDCD. */ @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); ClassificationDataSet train = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); LogisticRegressionDCD lr = new LogisticRegressionDCD(); lr.train(train); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), lr.classify(dpp.getDataPoint()).mostLikely()); } }
2,154
24.352941
98
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/linear/NHERDTest.java
package jsat.classifiers.linear; import java.util.Random; import jsat.FixedProblems; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.DataPointPair; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class NHERDTest { public NHERDTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Test public void testTrain_C() { System.out.println("train_C"); ClassificationDataSet train = FixedProblems.get2ClassLinear(200, new Random(132)); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, new Random(231)); for (NHERD.CovMode mode : NHERD.CovMode.values()) { NHERD nherd0 = new NHERD(1, mode); nherd0.train(train); for (DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), nherd0.classify(dpp.getDataPoint()).mostLikely()); } } }
1,164
20.574074
106
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/linear/NewGLMNETTest.java
package jsat.classifiers.linear; import java.util.Random; import java.util.concurrent.ExecutorService; import jsat.SimpleWeightVectorModel; import jsat.classifiers.*; import jsat.linear.*; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class NewGLMNETTest { /* * This test case is based off of the grouping example in the Elatic Net * Paper Zou, H.,&amp;Hastie, T. (2005). Regularization and variable selection * via the elastic net. Journal of the Royal Statistical Society, Series B, * 67(2), 301–320. doi:10.1111/j.1467-9868.2005.00503.x */ public NewGLMNETTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of setC method, of class NewGLMNET. */ @Test public void testSetC() { System.out.println("train"); Random rand = new XORWOW(45678); ClassificationDataSet data = new ClassificationDataSet(6, new CategoricalData[0], new CategoricalData(2)); for(int i = 0; i < 500; i++) { double Z1 = rand.nextDouble()*20-10; double Z2 = rand.nextDouble()*20-10; Vec v = DenseVector.toDenseVec(Z1, -Z1, Z1, Z2, -Z2, Z2); data.addDataPoint(v, (int) (Math.signum(Z1+0.1*Z2)+1)/2); } Vec w; NewGLMNET glmnet = new NewGLMNET(); glmnet.setUseBias(false); glmnet.setC(1e-2); glmnet.setAlpha(1); do { glmnet.setC(glmnet.getC()-0.0001); glmnet.train(data); w = glmnet.getRawWeight(); } while (w.nnz() > 1);//we should be able to find this pretty easily assertEquals(1, w.nnz()); int nonZeroIndex = w.getNonZeroIterator().next().getIndex(); assertTrue(nonZeroIndex < 3);//should be one of the more important weights if(nonZeroIndex == 1) //check the sign is correct assertEquals(-1, (int)Math.signum(w.get(nonZeroIndex))); else assertEquals(1, (int)Math.signum(w.get(nonZeroIndex))); glmnet.setC(1); glmnet.setAlpha(0.5);//now we should get the top 3 on do { glmnet.setC(glmnet.getC()*0.9); glmnet.train(data); w = glmnet.getRawWeight(); } while (w.nnz() > 3);//we should be able to find this pretty easily assertEquals(3, w.nnz()); assertEquals( 1, (int)Math.signum(w.get(0))); assertEquals(-1, (int)Math.signum(w.get(1))); assertEquals( 1, (int)Math.signum(w.get(2))); //also want to make sure that they are all about equal in size assertTrue(Math.abs((w.get(0)+w.get(1)*2+w.get(2))/3) < 0.4); glmnet.setC(1e-3); glmnet.setAlpha(0);//now everyone should turn on glmnet.train(data); w = glmnet.getRawWeight(); assertEquals(6, w.nnz()); assertEquals( 1, (int)Math.signum(w.get(0))); assertEquals(-1, (int)Math.signum(w.get(1))); assertEquals( 1, (int)Math.signum(w.get(2))); assertEquals( 1, (int)Math.signum(w.get(3))); assertEquals(-1, (int)Math.signum(w.get(4))); assertEquals( 1, (int)Math.signum(w.get(5))); } private static class DumbWeightHolder implements Classifier, SimpleWeightVectorModel { public Vec w; public double b; @Override public CategoricalResults classify(DataPoint data) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void train(ClassificationDataSet dataSet, boolean parallel) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void train(ClassificationDataSet dataSet) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean supportsWeightedData() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public DumbWeightHolder clone() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Vec getRawWeight(int index) { return w; } @Override public double getBias(int index) { return b; } @Override public int numWeightsVecs() { return 1; } } @Test public void testWarmOther() { //Had difficulty making a problem hard enough to show improvment in warms tart but also fast to run. //so made test check that warm from some weird value gets to the same places Random rand = new XORWOW(5679); ClassificationDataSet train = new ClassificationDataSet(600, new CategoricalData[0], new CategoricalData(2)); for(int i = 0; i < 200; i++) { double Z1 = rand.nextDouble()*20-10; double Z2 = rand.nextDouble()*20-10; Vec v = new DenseVector(train.getNumNumericalVars()); for(int j = 0; j < v.length(); j++) { if (j > 500) { if (j % 2 == 0) v.set(j, Z2 * ((j + 1) / 600.0) + rand.nextGaussian() / (j + 1)); else v.set(j, Z1 * ((j + 1) / 600.0) + rand.nextGaussian() / (j + 1)); } else v.set(j, rand.nextGaussian()*20); } train.addDataPoint(v, (int) (Math.signum(Z1+0.1*Z2)+1)/2); } NewGLMNET truth = new NewGLMNET(0.001); truth.setTolerance(1e-11); truth.train(train); DumbWeightHolder dumb = new DumbWeightHolder(); dumb.w = DenseVector.random(train.getNumNumericalVars()).normalized(); dumb.b = rand.nextDouble(); NewGLMNET warm = new NewGLMNET(0.001); warm.setTolerance(1e-7); warm.train(train, dumb); assertEquals(0, warm.getRawWeight().subtract(truth.getRawWeight()).pNorm(2), 1e-4); assertEquals(0, warm.getBias()-truth.getBias(), 1e-4); } }
7,126
29.719828
139
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/linear/PassiveAggressiveTest.java
package jsat.classifiers.linear; import java.util.Random; import jsat.FixedProblems; import jsat.classifiers.*; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class PassiveAggressiveTest { public PassiveAggressiveTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of train method, of class PassiveAggressive. */ @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); ClassificationDataSet train = FixedProblems.get2ClassLinear(400, RandomUtil.getRandom()); for(PassiveAggressive.Mode mode : PassiveAggressive.Mode.values()) { PassiveAggressive pa = new PassiveAggressive(); pa.setMode(mode); pa.train(train); ClassificationDataSet test = FixedProblems.get2ClassLinear(400, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), pa.classify(dpp.getDataPoint()).mostLikely()); } } /** * Test of train method, of class PassiveAggressive. */ @Test public void testTrain_RegressionDataSet() { System.out.println("train"); Random rand = new Random(123); for(PassiveAggressive.Mode mode : PassiveAggressive.Mode.values()) { PassiveAggressive pa = new PassiveAggressive(); pa.setMode(mode); pa.setEps(0.00001); pa.setEpochs(10); pa.setC(20); pa.train(FixedProblems.getLinearRegression(400, rand)); for(DataPointPair<Double> dpp : FixedProblems.getLinearRegression(100, rand).getAsDPPList()) { double truth = dpp.getPair(); double pred = pa.regress(dpp.getDataPoint()); double relErr = (truth-pred)/truth; assertEquals(0.0, relErr, 0.1);//Give it a decent wiggle room b/c of regularization } } } }
2,433
23.836735
104
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/linear/ROMMATest.java
package jsat.classifiers.linear; import java.util.Random; import jsat.FixedProblems; import jsat.classifiers.*; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class ROMMATest { public ROMMATest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of supportsWeightedData method, of class ROMMA. */ @Test public void testTrain_C() { System.out.println("supportsWeightedData"); ROMMA nonAggro = new ROMMA(); ROMMA aggro = new ROMMA(); ClassificationDataSet train = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); nonAggro.setEpochs(1); nonAggro.train(train); aggro.setEpochs(1); aggro.train(train); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), aggro.classify(dpp.getDataPoint()).mostLikely()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) assertEquals(dpp.getPair().longValue(), nonAggro.classify(dpp.getDataPoint()).mostLikely()); } }
1,611
21.388889
104
java
JSAT
JSAT-master/JSAT/test/jsat/classifiers/linear/SCDTest.java
package jsat.classifiers.linear; import java.util.Random; import jsat.FixedProblems; import jsat.classifiers.*; import jsat.lossfunctions.LogisticLoss; import jsat.lossfunctions.SquaredLoss; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class SCDTest { public SCDTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of train method, of class SCD. */ @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); ClassificationDataSet train = FixedProblems.get2ClassLinear(400, RandomUtil.getRandom()); SCD scd = new SCD(new LogisticLoss(), 1e-6, 100); scd.train(train); ClassificationDataSet test = FixedProblems.get2ClassLinear(400, RandomUtil.getRandom()); for(DataPointPair<Integer> dpp : test.getAsDPPList()) { assertEquals(dpp.getPair().longValue(), scd.classify(dpp.getDataPoint()).mostLikely()); } } /** * Test of train method, of class SCD. */ @Test public void testTrain_RegressionDataSet() { System.out.println("train"); Random rand = new Random(123); SCD scd = new SCD(new SquaredLoss(), 1e-6, 1000);//needs more iters for regression scd.train(FixedProblems.getLinearRegression(500, rand)); for(DataPointPair<Double> dpp : FixedProblems.getLinearRegression(100, rand).getAsDPPList()) { double truth = dpp.getPair(); double pred = scd.regress(dpp.getDataPoint()); double relErr = (truth-pred)/truth; assertEquals(0.0, relErr, 0.1);//Give it a decent wiggle room b/c of regularization } } }
2,176
22.923077
100
java