diff --git a/AMAZON BEAUTY to BOOKS.rar b/AMAZON BEAUTY to BOOKS.rar new file mode 100644 index 0000000..d59f8a7 Binary files /dev/null and b/AMAZON BEAUTY to BOOKS.rar differ diff --git a/AMAZON BEAUTY to INDUSTRIAL.rar b/AMAZON BEAUTY to INDUSTRIAL.rar new file mode 100644 index 0000000..5175995 Binary files /dev/null and b/AMAZON BEAUTY to INDUSTRIAL.rar differ diff --git a/AMAZON BEAUTY to LUXURY.rar b/AMAZON BEAUTY to LUXURY.rar new file mode 100644 index 0000000..247feef Binary files /dev/null and b/AMAZON BEAUTY to LUXURY.rar differ diff --git a/AMAZON BEAUTY to MAGAZINE.rar b/AMAZON BEAUTY to MAGAZINE.rar new file mode 100644 index 0000000..cb3607d Binary files /dev/null and b/AMAZON BEAUTY to MAGAZINE.rar differ diff --git a/AMAZON BOOKS to BEAUTY.rar b/AMAZON BOOKS to BEAUTY.rar new file mode 100644 index 0000000..5ef921d Binary files /dev/null and b/AMAZON BOOKS to BEAUTY.rar differ diff --git a/AMAZON BOOKS to INDUSTRIAL.rar b/AMAZON BOOKS to INDUSTRIAL.rar new file mode 100644 index 0000000..aa7eb40 Binary files /dev/null and b/AMAZON BOOKS to INDUSTRIAL.rar differ diff --git a/AMAZON BOOKS to LUXURY.rar b/AMAZON BOOKS to LUXURY.rar new file mode 100644 index 0000000..171349e Binary files /dev/null and b/AMAZON BOOKS to LUXURY.rar differ diff --git a/AMAZON BOOKS to MAGAZINE.rar b/AMAZON BOOKS to MAGAZINE.rar new file mode 100644 index 0000000..c47e6ba Binary files /dev/null and b/AMAZON BOOKS to MAGAZINE.rar differ diff --git a/AMAZON INDUSTRIAL to BEAUTY.rar b/AMAZON INDUSTRIAL to BEAUTY.rar new file mode 100644 index 0000000..4296fa5 Binary files /dev/null and b/AMAZON INDUSTRIAL to BEAUTY.rar differ diff --git a/AMAZON INDUSTRIAL to BOOKS.rar b/AMAZON INDUSTRIAL to BOOKS.rar new file mode 100644 index 0000000..9636037 Binary files /dev/null and b/AMAZON INDUSTRIAL to BOOKS.rar differ diff --git a/AMAZON INDUSTRIAL to LUXURY.rar b/AMAZON INDUSTRIAL to LUXURY.rar new file mode 100644 index 0000000..7e4ff99 Binary files /dev/null and b/AMAZON INDUSTRIAL to LUXURY.rar differ diff --git a/AMAZON INDUSTRIAL to MAGAZINE.rar b/AMAZON INDUSTRIAL to MAGAZINE.rar new file mode 100644 index 0000000..5bd50c6 Binary files /dev/null and b/AMAZON INDUSTRIAL to MAGAZINE.rar differ diff --git a/AMAZON LUXURY to BEAUTY.rar b/AMAZON LUXURY to BEAUTY.rar new file mode 100644 index 0000000..ab1cac1 Binary files /dev/null and b/AMAZON LUXURY to BEAUTY.rar differ diff --git a/AMAZON LUXURY to BOOKS.rar b/AMAZON LUXURY to BOOKS.rar new file mode 100644 index 0000000..72ea3ab Binary files /dev/null and b/AMAZON LUXURY to BOOKS.rar differ diff --git a/AMAZON LUXURY to INDUSTRIAL.rar b/AMAZON LUXURY to INDUSTRIAL.rar new file mode 100644 index 0000000..c04e393 Binary files /dev/null and b/AMAZON LUXURY to INDUSTRIAL.rar differ diff --git a/AMAZON LUXURY to MAGAZINE.rar b/AMAZON LUXURY to MAGAZINE.rar new file mode 100644 index 0000000..fb80f43 Binary files /dev/null and b/AMAZON LUXURY to MAGAZINE.rar differ diff --git a/AMAZON MAGAZINE to BEAUTY.rar b/AMAZON MAGAZINE to BEAUTY.rar new file mode 100644 index 0000000..9e1311e Binary files /dev/null and b/AMAZON MAGAZINE to BEAUTY.rar differ diff --git a/AMAZON MAGAZINE to BOOKS.rar b/AMAZON MAGAZINE to BOOKS.rar new file mode 100644 index 0000000..76b8847 Binary files /dev/null and b/AMAZON MAGAZINE to BOOKS.rar differ diff --git a/AMAZON MAGAZINE to INDUSTRIAL.rar b/AMAZON MAGAZINE to INDUSTRIAL.rar new file mode 100644 index 0000000..8243064 Binary files /dev/null and b/AMAZON MAGAZINE to INDUSTRIAL.rar differ diff --git a/AMAZON MAGAZINE to LUXURY.rar b/AMAZON MAGAZINE to LUXURY.rar new file mode 100644 index 0000000..ce37b0a Binary files /dev/null and b/AMAZON MAGAZINE to LUXURY.rar differ diff --git a/Ablation A.rar b/Ablation A.rar new file mode 100644 index 0000000..64f6df5 Binary files /dev/null and b/Ablation A.rar differ diff --git a/Ablation B.rar b/Ablation B.rar new file mode 100644 index 0000000..a10c129 Binary files /dev/null and b/Ablation B.rar differ diff --git a/Ablation C.rar b/Ablation C.rar new file mode 100644 index 0000000..b502a1c Binary files /dev/null and b/Ablation C.rar differ diff --git a/Ablation D.rar b/Ablation D.rar new file mode 100644 index 0000000..434ab4b Binary files /dev/null and b/Ablation D.rar differ diff --git a/CIFAR_to_STL.rar b/CIFAR_to_STL.rar new file mode 100644 index 0000000..bf46987 Binary files /dev/null and b/CIFAR_to_STL.rar differ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0e525e2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 ACDC-paper-double-review + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/London_to_Washington.rar b/London_to_Washington.rar new file mode 100644 index 0000000..08c7c04 Binary files /dev/null and b/London_to_Washington.rar differ diff --git a/MNIST_to_USPS.rar b/MNIST_to_USPS.rar new file mode 100644 index 0000000..8c747f1 Binary files /dev/null and b/MNIST_to_USPS.rar differ diff --git a/MSC/README.md b/MSC/README.md new file mode 100644 index 0000000..43caf50 --- /dev/null +++ b/MSC/README.md @@ -0,0 +1,17 @@ +# Multistream Classification + +Classification (class label prediction) over two non-stationary data streams, one with labeled data (source) and the other with unlabeled data (target). Covariate shift is assumed between the source and target streams. + +The problem is to predict the class label data on target stream using labeled data from the source stream, both of which can have concept drift asynchronously. More details in the publication at [CIKM 2016](http://www.utdallas.edu/~swarup.chandra/papers/multistream_cikm16.pdf) + +# Environment + +1. Java code for change point detection is based from [this](http://www.aaai.org/ocs/index.php/AAAI/AAAI16/paper/download/12335/11786) paper. +2. We use the instance weighted libSVM code from [here](https://www.csie.ntu.edu.tw/~cjlin/libsvm/). +3. config.properties file specifies data path and other configurable items. +4. Python v2.7 + +# Execution +``` +$ python multistream.py +``` diff --git a/MSC/Results_run_1.rar b/MSC/Results_run_1.rar new file mode 100644 index 0000000..e20c0b1 Binary files /dev/null and b/MSC/Results_run_1.rar differ diff --git a/MSC/Results_run_2.rar b/MSC/Results_run_2.rar new file mode 100644 index 0000000..564c23b Binary files /dev/null and b/MSC/Results_run_2.rar differ diff --git a/MSC/Results_run_3.rar b/MSC/Results_run_3.rar new file mode 100644 index 0000000..7bcae2b Binary files /dev/null and b/MSC/Results_run_3.rar differ diff --git a/MSC/Results_run_4.rar b/MSC/Results_run_4.rar new file mode 100644 index 0000000..b8fe86e Binary files /dev/null and b/MSC/Results_run_4.rar differ diff --git a/MSC/Results_run_5.rar b/MSC/Results_run_5.rar new file mode 100644 index 0000000..50d1af5 Binary files /dev/null and b/MSC/Results_run_5.rar differ diff --git a/MSC/change_point.jar b/MSC/change_point.jar new file mode 100644 index 0000000..2b49ce9 Binary files /dev/null and b/MSC/change_point.jar differ diff --git a/MSC/changedetection.py b/MSC/changedetection.py new file mode 100644 index 0000000..752a93d --- /dev/null +++ b/MSC/changedetection.py @@ -0,0 +1,173 @@ +from properties import Properties +import math, numpy as np +from scipy.stats import beta, binom +from decimal import Decimal +import sys, random, time + + +class ChangeDetection(object): + + def __init__(self, gamma, sensitivity, maxWindowSize): + self.gamma = gamma + self.sensitivity = sensitivity + self.maxWindowSize = maxWindowSize + + + """ + Functions to estimate beta distribution parameters + """ + def __calcBetaDistAlpha(self, list, sampleMean, sampleVar): + if sampleMean == -1: + sampleMean = np.mean(list) + if sampleVar == -1: + sampleVar = np.var(list) + c = (sampleMean * (1-sampleMean)/sampleVar) - 1 + return sampleMean * c + + + def __calcBetaDistBeta(self, list, alphaChange, sampleMean): + if sampleMean == -1: + sampleMean = np.mean(list) + return alphaChange * ((1.0/sampleMean) - 1) + + + """ + input: The dynamic sliding window containing confidence of target classifier + output: -1 if no change found, otherwise the change point + """ + def detectTargetChange(self, slidingWindow): + estimatedChangePoint = -1 + N = len(slidingWindow) + cushion = max(Properties.CUSHION, int(math.floor(N ** self.gamma))) + + #If mean confidence fall below 0.3, must retrain the classifier, so return a changepoint + if N > self.maxWindowSize: + Properties.logger.info('Current target Window Size is: ' + str(N) + ', which exceeds max limit, so update classifier') + return 0 + if N > 2*cushion and np.mean(slidingWindow[0:N]) <= Properties.CONFCUTOFF: + Properties.logger.info('Current target Window Size is: ' + str(N)) + Properties.logger.info('But overall confidence fell below ' + str(Properties.CONFCUTOFF) + ', so update classifier') + return 0 + + threshold = -math.log(self.sensitivity) + w = 0.0 + kAtMaxW = -1 + + kindex = np.arange(cushion, N - cushion + 1) + for k in kindex: + xbar0 = np.mean(slidingWindow[:k]) + var0 = np.var(slidingWindow[:k]) + xbar1 = np.mean(slidingWindow[k:]) + var1 = np.mean(slidingWindow[k:]) + + if xbar1 <= 0.9*xbar0: + skn = 0.0 + alphaPreChange = self.__calcBetaDistAlpha(slidingWindow[:k], xbar0, var0) + betaPreChange = self.__calcBetaDistBeta(slidingWindow[:k], alphaPreChange, xbar0) + alphaPostChange = self.__calcBetaDistAlpha(slidingWindow[k:], xbar1, var1) + betaPostChange = self.__calcBetaDistBeta(slidingWindow[k:], alphaPostChange, xbar1) + + # for i in range(k, N): + # try: + # #Get Beta distribution + # denom = beta.pdf(float(slidingWindow[i]), alphaPreChange, betaPreChange) + # if denom == 0: + # Properties.logger.info('beta distribution pdf is zero for X = ' + str(float(slidingWindow[i]))) + # denom = 0.001 + # val = Decimal(beta.pdf(float(slidingWindow[i])/denom, alphaPostChange, betaPostChange)) + # skn += float(val.ln()) + # except: + # e = sys.exc_info() + # print str(e[1]) + # raise Exception('Error in calculating skn.') + + try: + swin = map(float, slidingWindow[k:]) + denom = [beta.pdf(s, alphaPreChange, betaPreChange) for s in swin] + nor_denom = np.array([0.001 if h == 0 else h for h in denom]) + nor_swin = swin/nor_denom + skn = sum([Decimal(beta.pdf(ns, alphaPostChange, betaPostChange)).ln() for ns in nor_swin]) + except: + e = sys.exc_info() + print str(e[1]) + raise Exception('Error in calculating skn') + + if skn > w: + w = skn + kAtMaxW = k + + if w >= threshold and kAtMaxW != -1: + estimatedChangePoint = kAtMaxW + Properties.logger.info('Estimated change point is ' + str(estimatedChangePoint) + ', detected at ' + str(N)) + + + return estimatedChangePoint + + + + """ + input: The dynamic sliding window containing accuracy of source classifier + output: -1 if no change found, otherwise the change point + """ + def detectSourceChange(self, slidingWindow): + estimatedChangePoint = -1 + N = len(slidingWindow) + cushion = max(Properties.CUSHION, int(math.floor(N ** self.gamma))) + + #If mean confidence fall below 0.3, must retrain the classifier, so return a changepoint + if N > self.maxWindowSize: + Properties.logger.info('Current target Window Size is: ' + str(N) + ', which exceeds max limit, so update classifier') + return 0 + if N > 2*cushion and np.mean(slidingWindow) <= Properties.CONFCUTOFF: + Properties.logger.info('Current target Window Size is: ' + str(N)) + Properties.logger.info('But overall confidence fell below ' + str(Properties.CONFCUTOFF) + ', so update classifier') + return 0 + + threshold = -math.log(self.sensitivity) + w = 0.0 + kAtMaxW = -1 + + kindex = np.arange(cushion, N - cushion + 1) + for k in kindex: + xbar0 = np.mean(slidingWindow[:k]) + xbar1 = np.mean(slidingWindow[k:]) + + # means should set 1=accurate, 0=erroneous + if xbar1 <= 0.9*xbar0: + skn = 0.0 + + # for i in range(k, N): + # try: + # denom = binom.pmf(float(slidingWindow[i]), k, xbar0) + # if denom == 0: + # Properties.logger.info('binomial distribution pmf is zero for X = ' + str(float(slidingWindow[i]))) + # denom = 0.001 + # val = Decimal(binom.pmf(float(slidingWindow[i])/denom, N-k, xbar1)) + # skn += float(val.ln()) + # except: + # e = sys.exc_info() + # print str(e[1]) + # raise Exception('Error in calculating skn') + + try: + swin = map(float, slidingWindow[k:N]) + denom = [binom.pmf(s, k, xbar0) for s in swin] + nor_denom = np.array([0.001 if h == 0 else h for h in denom]) + nor_swin = swin/nor_denom + skn = sum([Decimal(binom.pmf(ns, N-k, xbar1)).ln() for ns in nor_swin]) + except: + e = sys.exc_info() + print str(e[1]) + raise Exception('Error in calculating skn') + + if skn > w: + w = skn + kAtMaxW = k + + if w >= threshold and kAtMaxW != -1: + estimatedChangePoint = kAtMaxW + Properties.logger.info('Estimated change point is ' + str(estimatedChangePoint) + ', detected at: ' + str(N)) + Properties.logger.info('Value of w: ' + str(w) + ', Value of Threshold: ' + str(threshold)) + + + return estimatedChangePoint diff --git a/MSC/config.properties b/MSC/config.properties new file mode 100644 index 0000000..c991396 --- /dev/null +++ b/MSC/config.properties @@ -0,0 +1,14 @@ +baseDir= +srcfileAppend=_source.csv +trgfileAppend=_target.csv +gamma=0.5 +cushion=100 +sensitivity=0.01 +ensemble_size=10 +confthreshold=0.9 +confcutoff=0.5 +maxWindowSize=1000 +initialDataSize=10 +output_file_name=result.out +logfile=multistream.log +tempDir=temp/ diff --git a/MSC/ensemble.py b/MSC/ensemble.py new file mode 100644 index 0000000..2e8a891 --- /dev/null +++ b/MSC/ensemble.py @@ -0,0 +1,143 @@ +import math +from model import Model +from properties import Properties + + +class Ensemble(object): + + def __init__(self, ensemble_size): + self.models = [] + self.size = ensemble_size + + + """ + Update weights for all models in the ensemble. + """ + def updateWeight(self, data, isSource): + for m in self.models: + m.computeModelWeight(data, isSource, Properties.MAXVAR) + + """ + Adding a new model to the Ensemble. + Returns the index of the Ensemble array where the model is added. + """ + def __addModel(self, model): + index = 0 + if len(self.models) < self.size: + self.models.append(model) + index = len(self.models)-1 + else: + #replace least desirable model + index = self.__getLeastDesirableModel() + Properties.logger.info('Least desirable model removed at ' + str(index)) + self.models[index] = model + return index + + """ + Compute the least desirable model to be replaced when the ensemble size has reached its limit. + Least desirable is one having least target weight, but not the largest source weight. + Returns the array index of the least desired model. + """ + def __getLeastDesirableModel(self): + sweights = {} + tweights = {} + for i in xrange(len(self.models)): + sweights[i] = self.models[i].sweight + tweights[i] = self.models[i].tweight + + skeys = sorted(sweights, reverse=True, key=sweights.get) + tkeys = sorted(tweights, key=tweights.get) + + # skeys = sweights.keys() + # tkeys = tweights.keys() + + for i in xrange(len(skeys)): + if tkeys[i] == skeys[i]: + continue + else: + return tkeys[i] + + return tkeys[0] + + """ + Initiate the creation of appropriate model in the ensemble for given source or target data. + Also compute weights for the new model based on the current data. + """ + def generateNewModel(self, sourceData, targetData, isSource): + model = Model() + + if len(sourceData) == 0 or len(targetData) == 0: + raise Exception('Source or Target stream should have some elements') + + #Create new model + if isSource: + Properties.logger.info('Source model creation') + model.train(sourceData, None, Properties.MAXVAR) + else: + Properties.logger.info('Target model creation') + model.train(sourceData, targetData, Properties.MAXVAR) + + #compute source and target weight + Properties.logger.info('Computing model weights') + model.computeModelWeight(sourceData, True, Properties.MAXVAR) + model.computeModelWeight(targetData, False, Properties.MAXVAR) + + #update ensemble + index = self.__addModel(model) + Properties.logger.info('Ensemble updated at ' + str(index)) + + """ + Get prediction for a given data instance from each model. + For source data: Ensemble prediction is 1 if maximum weighted vote class label matches true class label, else 0. + For target data: Ensemble prediction class with max weighted vote class label, and average (for all class) confidence measure. + """ + def evaluateEnsemble(self, dataInstance, isSource): + + classSum = {} + for m in self.models: + #test data instance in each model + result = m.test([dataInstance], Properties.MAXVAR) + #gather result + if isSource: + if int(result[0][0]) in classSum: + classSum[int(result[0][0])] += m.sweight + else: + classSum[int(result[0][0])] = m.sweight + else: + if int(result[0][0]) in classSum: + classSum[int(result[0][0])] += result[0][1] + else: + classSum[int(result[0][0])] = result[0][1] + + #get maximum voted sum class label + classMax = 0.0 + sumMax = max(classSum.values()) + for i in classSum: + if classSum[i] == sumMax: + classMax = i + + if isSource: + #for source data, check true vs predicted class label + if classMax == dataInstance[-1]: + return [1, -1] + else: + return [0, -1] + else: + # for target data + return [classMax, sumMax/len(self.models)] + + """ + Get summary of models in ensemble. + """ + def getEnsembleSummary(self): + summry = '************************* E N S E M B L E S U M M A R Y ************************\n' + summry += 'Ensemble has currently ' + str(len(self.models)) + ' models.\n' + for i in xrange(len(self.models)): + summry += 'Model' + str(i+1) + ': weights<' + str(self.models[i].sweight) + ', ' + str(self.models[i].tweight) + '>\n' + return summry + + + + + + diff --git a/MSC/environment.yml b/MSC/environment.yml new file mode 100644 index 0000000..349db93 --- /dev/null +++ b/MSC/environment.yml @@ -0,0 +1,111 @@ +name: MSC +channels: + - conda-forge + - omnia + - defaults +dependencies: + - apipkg=1.5=py27_0 + - attrs=19.3.0=py_0 + - backports=1.0=py_2 + - backports.shutil_get_terminal_size=1.0.0=py27_2 + - backports.shutil_which=3.5.2=py27_0 + - backports_abc=0.5=py27h0ec6b72_0 + - blas=1.0=mkl + - bleach=3.1.0=py27_0 + - ca-certificates=2019.11.27=0 + - certifi=2019.11.28=py27_0 + - colorama=0.4.3=py_0 + - configparser=4.0.2=py27_0 + - cvxopt=1.1.8=py27_0 + - decorator=4.4.1=py_0 + - defusedxml=0.6.0=py_0 + - entrypoints=0.3=py27_0 + - enum34=1.1.6=py27_1 + - execnet=1.7.1=py_0 + - functools32=3.2.3.2=py27_1 + - futures=3.3.0=py27_0 + - icc_rt=2019.0.0=h0cc432a_1 + - icu=58.2=h2aa20d9_1 + - intel-openmp=2019.4=245 + - ipaddress=1.0.23=py_0 + - ipykernel=4.10.0=py27_0 + - ipython=5.8.0=py27_0 + - ipython_genutils=0.2.0=py27_0 + - ipywidgets=7.5.1=py_0 + - jinja2=2.10.3=py_0 + - jpeg=9b=ha175dff_2 + - jsonschema=3.0.2=py27_0 + - jupyter=1.0.0=py27_7 + - jupyter_client=5.3.4=py27_0 + - jupyter_console=5.2.0=py27_1 + - jupyter_core=4.6.1=py27_0 + - jupyterlab=0.33.11=py27_0 + - jupyterlab_launcher=0.11.2=py27h28b3542_0 + - libpng=1.6.37=h7a46e7a_0 + - libsodium=1.0.16=h8b3e59e_0 + - libsvm=323=0 + - m2w64-gcc-libgfortran=5.3.0=6 + - m2w64-gcc-libs=5.3.0=7 + - m2w64-gcc-libs-core=5.3.0=7 + - m2w64-gmp=6.1.0=2 + - m2w64-libwinpthread-git=5.0.0.4634.697f757=2 + - markupsafe=1.1.1=py27h0c8e037_0 + - mistune=0.8.4=py27h0c8e037_0 + - mkl=2019.4=245 + - mkl-service=2.3.0=py27h0b88c2a_0 + - mkl_fft=1.0.15=py27h44c1dab_0 + - msys2-conda-epoch=20160418=1 + - nbconvert=5.6.1=py27_0 + - nbformat=4.4.0=py27_0 + - notebook=5.7.8=py27_0 + - numpy=1.16.5=py27h5fc8d92_0 + - numpy-base=1.16.5=py27hb1d0314_0 + - openssl=1.0.2u=h0c8e037_0 + - pandas=0.24.2=py27hc56fc5f_0 + - pandoc=2.2.3.2=0 + - pandocfilters=1.4.2=py27_1 + - pathlib2=2.3.5=py27_0 + - pickleshare=0.7.5=py27_0 + - pip=19.3.1=py27_0 + - prometheus_client=0.7.1=py_0 + - prompt_toolkit=1.0.15=py27h3a8ec6a_0 + - py4j=0.10.8.1=py_0 + - pygments=2.5.2=py_0 + - pyqt=5.6.0=py27h6e61f57_6 + - pyrsistent=0.15.6=py27h0c8e037_0 + - python=2.7.17=h930f6bb_0 + - python-dateutil=2.8.1=py_0 + - pytz=2019.3=py_0 + - pywin32=227=py27h0c8e037_0 + - pywinpty=0.5.5=py27_1000 + - pyzmq=18.1.0=py27hc56fc5f_0 + - qt=5.6.2=vc9hc26998b_12 + - qtconsole=4.6.0=py_1 + - scandir=1.10.0=py27h0c8e037_0 + - scikit-learn=0.20.3=py27hf381715_0 + - scipy=1.2.1=py27h4c3ab11_0 + - send2trash=1.5.0=py27_0 + - setuptools=44.0.0=py27_0 + - simplegeneric=0.8.1=py27_2 + - singledispatch=3.4.0.3=py27h3f9d112_0 + - sip=4.18.1=py27hc56fc5f_2 + - six=1.13.0=py27_0 + - sqlite=3.30.1=h0c8e037_0 + - subprocess32=3.5.4=py27h0c8e037_0 + - terminado=0.8.3=py27_0 + - testpath=0.4.4=py_0 + - tornado=5.1.1=py27h0c8e037_0 + - traitlets=4.3.3=py27_0 + - vc=9=h7299396_1 + - vs2008_runtime=9.00.30729.1=hfaea7d5_1 + - wcwidth=0.1.7=py27_0 + - webencodings=0.5.1=py27_1 + - wheel=0.33.6=py27_0 + - widgetsnbextension=3.5.1=py27_0 + - win_unicode_console=0.5=py27hc037021_0 + - wincertstore=0.2=py27hf04cefb_0 + - winpty=0.4.3=4 + - zeromq=4.3.1=h2880e7c_3 + - zlib=1.2.11=h3cc03e0_3 +prefix: C:\Users\ivsuc\Miniconda3\envs\MSC + diff --git a/MSC/grid.py b/MSC/grid.py new file mode 100644 index 0000000..830bb22 --- /dev/null +++ b/MSC/grid.py @@ -0,0 +1,500 @@ +#!/usr/bin/env python +__all__ = ['find_parameters'] + +import os, sys, traceback, getpass, time, re +from threading import Thread +from subprocess import * + +if sys.version_info[0] < 3: + from Queue import Queue +else: + from queue import Queue + +telnet_workers = [] +ssh_workers = [] +nr_local_worker = 1 + +class GridOption: + def __init__(self, dataset_pathname, options): + dirname = os.path.dirname(__file__) + if sys.platform != 'win32': + self.svmtrain_pathname = os.path.join(dirname, 'libsvm-weights-3.20/svm-train') + self.gnuplot_pathname = '/usr/bin/gnuplot' + else: + # example for windows + self.svmtrain_pathname = os.path.join(dirname, r'libsvm-weights-3.20\windows\svm-train.exe') + # svmtrain_pathname = r'c:\Program Files\libsvm\windows\svm-train.exe' + self.gnuplot_pathname = r'c:\tmp\gnuplot\binary\pgnuplot.exe' + self.fold = 5 + self.c_begin, self.c_end, self.c_step = -5, 15, 2 + self.g_begin, self.g_end, self.g_step = 3, -15, -2 + self.grid_with_c, self.grid_with_g = True, True + self.dataset_pathname = dataset_pathname + self.dataset_title = os.path.split(dataset_pathname)[1] + self.out_pathname = '{0}.out'.format(self.dataset_title) + self.png_pathname = '{0}.png'.format(self.dataset_title) + self.pass_through_string = ' ' + self.resume_pathname = None + self.parse_options(options) + + def parse_options(self, options): + if type(options) == str: + options = options.split() + i = 0 + pass_through_options = [] + + while i < len(options): + if options[i] == '-log2c': + i = i + 1 + if options[i] == 'null': + self.grid_with_c = False + else: + self.c_begin, self.c_end, self.c_step = map(float,options[i].split(',')) + elif options[i] == '-log2g': + i = i + 1 + if options[i] == 'null': + self.grid_with_g = False + else: + self.g_begin, self.g_end, self.g_step = map(float,options[i].split(',')) + elif options[i] == '-v': + i = i + 1 + self.fold = options[i] + elif options[i] in ('-c','-g'): + raise ValueError('Use -log2c and -log2g.') + elif options[i] == '-svmtrain': + i = i + 1 + self.svmtrain_pathname = options[i] + elif options[i] == '-gnuplot': + i = i + 1 + if options[i] == 'null': + self.gnuplot_pathname = None + else: + self.gnuplot_pathname = options[i] + elif options[i] == '-out': + i = i + 1 + if options[i] == 'null': + self.out_pathname = None + else: + self.out_pathname = options[i] + elif options[i] == '-png': + i = i + 1 + self.png_pathname = options[i] + elif options[i] == '-resume': + if i == (len(options)-1) or options[i+1].startswith('-'): + self.resume_pathname = self.dataset_title + '.out' + else: + i = i + 1 + self.resume_pathname = options[i] + else: + pass_through_options.append(options[i]) + i = i + 1 + + self.pass_through_string = ' '.join(pass_through_options) + if not os.path.exists(self.svmtrain_pathname): + raise IOError('svm-train executable not found') + if not os.path.exists(self.dataset_pathname): + raise IOError('dataset not found') + if self.resume_pathname and not os.path.exists(self.resume_pathname): + raise IOError('file for resumption not found') + if not self.grid_with_c and not self.grid_with_g: + raise ValueError('-log2c and -log2g should not be null simultaneously') + if self.gnuplot_pathname and not os.path.exists(self.gnuplot_pathname): + sys.stderr.write('gnuplot executable not found\n') + self.gnuplot_pathname = None + +def redraw(db,best_param,gnuplot,options,tofile=False): + if len(db) == 0: return + begin_level = round(max(x[2] for x in db)) - 3 + step_size = 0.5 + + best_log2c,best_log2g,best_rate = best_param + + # if newly obtained c, g, or cv values are the same, + # then stop redrawing the contour. + if all(x[0] == db[0][0] for x in db): return + if all(x[1] == db[0][1] for x in db): return + if all(x[2] == db[0][2] for x in db): return + + if tofile: + gnuplot.write(b"set term png transparent small linewidth 2 medium enhanced\n") + gnuplot.write("set output \"{0}\"\n".format(options.png_pathname.replace('\\','\\\\')).encode()) + #gnuplot.write(b"set term postscript color solid\n") + #gnuplot.write("set output \"{0}.ps\"\n".format(options.dataset_title).encode().encode()) + elif sys.platform == 'win32': + gnuplot.write(b"set term windows\n") + else: + gnuplot.write( b"set term x11\n") + gnuplot.write(b"set xlabel \"log2(C)\"\n") + gnuplot.write(b"set ylabel \"log2(gamma)\"\n") + gnuplot.write("set xrange [{0}:{1}]\n".format(options.c_begin,options.c_end).encode()) + gnuplot.write("set yrange [{0}:{1}]\n".format(options.g_begin,options.g_end).encode()) + gnuplot.write(b"set contour\n") + gnuplot.write("set cntrparam levels incremental {0},{1},100\n".format(begin_level,step_size).encode()) + gnuplot.write(b"unset surface\n") + gnuplot.write(b"unset ztics\n") + gnuplot.write(b"set view 0,0\n") + gnuplot.write("set title \"{0}\"\n".format(options.dataset_title).encode()) + gnuplot.write(b"unset label\n") + gnuplot.write("set label \"Best log2(C) = {0} log2(gamma) = {1} accuracy = {2}%\" \ + at screen 0.5,0.85 center\n". \ + format(best_log2c, best_log2g, best_rate).encode()) + gnuplot.write("set label \"C = {0} gamma = {1}\"" + " at screen 0.5,0.8 center\n".format(2**best_log2c, 2**best_log2g).encode()) + gnuplot.write(b"set key at screen 0.9,0.9\n") + gnuplot.write(b"splot \"-\" with lines\n") + + db.sort(key = lambda x:(x[0], -x[1])) + + prevc = db[0][0] + for line in db: + if prevc != line[0]: + gnuplot.write(b"\n") + prevc = line[0] + gnuplot.write("{0[0]} {0[1]} {0[2]}\n".format(line).encode()) + gnuplot.write(b"e\n") + gnuplot.write(b"\n") # force gnuplot back to prompt when term set failure + gnuplot.flush() + + +def calculate_jobs(options): + + def range_f(begin,end,step): + # like range, but works on non-integer too + seq = [] + while True: + if step > 0 and begin > end: break + if step < 0 and begin < end: break + seq.append(begin) + begin = begin + step + return seq + + def permute_sequence(seq): + n = len(seq) + if n <= 1: return seq + + mid = int(n/2) + left = permute_sequence(seq[:mid]) + right = permute_sequence(seq[mid+1:]) + + ret = [seq[mid]] + while left or right: + if left: ret.append(left.pop(0)) + if right: ret.append(right.pop(0)) + + return ret + + + c_seq = permute_sequence(range_f(options.c_begin,options.c_end,options.c_step)) + g_seq = permute_sequence(range_f(options.g_begin,options.g_end,options.g_step)) + + if not options.grid_with_c: + c_seq = [None] + if not options.grid_with_g: + g_seq = [None] + + nr_c = float(len(c_seq)) + nr_g = float(len(g_seq)) + i, j = 0, 0 + jobs = [] + + while i < nr_c or j < nr_g: + if i/nr_c < j/nr_g: + # increase C resolution + line = [] + for k in range(0,j): + line.append((c_seq[i],g_seq[k])) + i = i + 1 + jobs.append(line) + else: + # increase g resolution + line = [] + for k in range(0,i): + line.append((c_seq[k],g_seq[j])) + j = j + 1 + jobs.append(line) + + resumed_jobs = {} + + if options.resume_pathname is None: + return jobs, resumed_jobs + + for line in open(options.resume_pathname, 'r'): + line = line.strip() + rst = re.findall(r'rate=([0-9.]+)',line) + if not rst: + continue + rate = float(rst[0]) + + c, g = None, None + rst = re.findall(r'log2c=([0-9.-]+)',line) + if rst: + c = float(rst[0]) + rst = re.findall(r'log2g=([0-9.-]+)',line) + if rst: + g = float(rst[0]) + + resumed_jobs[(c,g)] = rate + + return jobs, resumed_jobs + + +class WorkerStopToken: # used to notify the worker to stop or if a worker is dead + pass + +class Worker(Thread): + def __init__(self,name,job_queue,result_queue,options): + Thread.__init__(self) + self.name = name + self.job_queue = job_queue + self.result_queue = result_queue + self.options = options + + def run(self): + while True: + (cexp,gexp) = self.job_queue.get() + if cexp is WorkerStopToken: + self.job_queue.put((cexp,gexp)) + # print('worker {0} stop.'.format(self.name)) + break + try: + c, g = None, None + if cexp != None: + c = 2.0**cexp + if gexp != None: + g = 2.0**gexp + rate = self.run_one(c,g) + if rate is None: raise RuntimeError('get no rate') + except: + # we failed, let others do that and we just quit + + traceback.print_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]) + + self.job_queue.put((cexp,gexp)) + sys.stderr.write('worker {0} quit.\n'.format(self.name)) + break + else: + self.result_queue.put((self.name,cexp,gexp,rate)) + + def get_cmd(self,c,g): + options=self.options + cmdline = '"' + options.svmtrain_pathname + '"' + if options.grid_with_c: + cmdline += ' -c {0} '.format(c) + if options.grid_with_g: + cmdline += ' -g {0} '.format(g) + cmdline += ' -v {0} {1} {2} '.format\ + (options.fold,options.pass_through_string,options.dataset_pathname) + return cmdline + +class LocalWorker(Worker): + def run_one(self,c,g): + cmdline = self.get_cmd(c,g) + result = Popen(cmdline,shell=True,stdout=PIPE,stderr=PIPE,stdin=PIPE).stdout + for line in result.readlines(): + if str(line).find('Cross') != -1: + return float(line.split()[-1][0:-1]) + +class SSHWorker(Worker): + def __init__(self,name,job_queue,result_queue,host,options): + Worker.__init__(self,name,job_queue,result_queue,options) + self.host = host + self.cwd = os.getcwd() + def run_one(self,c,g): + cmdline = 'ssh -x -t -t {0} "cd {1}; {2}"'.format\ + (self.host,self.cwd,self.get_cmd(c,g)) + result = Popen(cmdline,shell=True,stdout=PIPE,stderr=PIPE,stdin=PIPE).stdout + for line in result.readlines(): + if str(line).find('Cross') != -1: + return float(line.split()[-1][0:-1]) + +class TelnetWorker(Worker): + def __init__(self,name,job_queue,result_queue,host,username,password,options): + Worker.__init__(self,name,job_queue,result_queue,options) + self.host = host + self.username = username + self.password = password + def run(self): + import telnetlib + self.tn = tn = telnetlib.Telnet(self.host) + tn.read_until('login: ') + tn.write(self.username + '\n') + tn.read_until('Password: ') + tn.write(self.password + '\n') + + # XXX: how to know whether login is successful? + tn.read_until(self.username) + # + print('login ok', self.host) + tn.write('cd '+os.getcwd()+'\n') + Worker.run(self) + tn.write('exit\n') + def run_one(self,c,g): + cmdline = self.get_cmd(c,g) + result = self.tn.write(cmdline+'\n') + (idx,matchm,output) = self.tn.expect(['Cross.*\n']) + for line in output.split('\n'): + if str(line).find('Cross') != -1: + return float(line.split()[-1][0:-1]) + +def find_parameters(dataset_pathname, options=''): + + def update_param(c,g,rate,best_c,best_g,best_rate,worker,resumed): + if (rate > best_rate) or (rate==best_rate and g==best_g and c J: + Jmin = J + beta = list(betaTrain) + + return beta + + +#MAIN METHOD +def main(): + #traindata = [[1,2,3],[4,7,4],[3,3,3],[4,4,4],[5,5,5],[3,4,5],[1,2,3],[4,7,4],[3,3,3],[4,4,4],[5,5,5],[3,4,5],[1,2,3],[4,7,4],[3,3,3],[4,4,4],[5,5,5],[3,4,5],[1,2,3],[4,7,4],[3,3,3],[4,4,4],[5,5,5],[3,4,5]] + #testdata = [[5,9,10],[4,5,6],[10,20,30],[1,2,3],[3,4,5],[5,6,7],[7,8,9],[100,100,100],[11,22,33],[12,11,5],[5,9,10],[4,5,6],[10,20,30],[1,2,3],[3,4,5],[5,6,7],[7,8,9],[100,100,100],[11,22,33],[12,11,5]] + #gammab = [0.001] + + if len(sys.argv) != 4: + print 'Incorrect number of arguments.' + print 'Arg: training_file, test_file, output_file.' + return + + traindata = getData(sys.argv[1]) + testdata = getData(sys.argv[2]) + gammab = [1/float(len(traindata)),0.0001,0.0005,0.001,0.005,0.01,0.05,0.1,0.5,1,5,10] + print 'Got training and test data.' + + beta = getBeta(traindata, testdata, gammab) + + writeFile(sys.argv[3], beta) + +if __name__ == '__main__': + main() diff --git a/MSC/libsvm-weights-3.20/COPYRIGHT b/MSC/libsvm-weights-3.20/COPYRIGHT new file mode 100644 index 0000000..89702bc --- /dev/null +++ b/MSC/libsvm-weights-3.20/COPYRIGHT @@ -0,0 +1,31 @@ + +Copyright (c) 2000-2014 Chih-Chung Chang and Chih-Jen Lin +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +3. Neither name of copyright holders nor the names of its contributors +may be used to endorse or promote products derived from this software +without specific prior written permission. + + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/MSC/libsvm-weights-3.20/FAQ.html b/MSC/libsvm-weights-3.20/FAQ.html new file mode 100644 index 0000000..9ab683e --- /dev/null +++ b/MSC/libsvm-weights-3.20/FAQ.html @@ -0,0 +1,2070 @@ + + + + +LIBSVM FAQ + + + +

LIBSVM FAQ

+last modified : +Thu, 20 Mar 2014 16:05:14 GMT + +
  • All Questions(81)
  • + + + + + + +
    +

    + + +Q: Some courses which have used libsvm as a tool +
    +

    +

    +[Go Top] +


    + +Q: Some applications/tools which have used libsvm +
    +(and maybe liblinear). + +

    +[Go Top] +


    + +Q: Where can I find documents/videos of libsvm ? +
    +

    + +

      +
    • +Official implementation document: +
      +C.-C. Chang and +C.-J. Lin. +LIBSVM +: a library for support vector machines. +ACM Transactions on Intelligent +Systems and Technology, 2:27:1--27:27, 2011. +pdf, ps.gz, +ACM digital lib. + + +
    • Instructions for using LIBSVM are in the README files in the main directory and some sub-directories. +
      +README in the main directory: details all options, data format, and library calls. +
      +tools/README: parameter selection and other tools +
    • +A guide for beginners: +
      +C.-W. Hsu, C.-C. Chang, and +C.-J. Lin. + +A practical guide to support vector classification + +
    • An introductory video +for windows users. + +
    +

    +[Go Top] +


    + +Q: Where are change log and earlier versions? +
    +

    See the change log. + +

    You can download earlier versions +here. +

    +[Go Top] +


    + +Q: How to cite LIBSVM? +
    +

    +Please cite the following paper: +

    +Chih-Chung Chang and Chih-Jen Lin, LIBSVM +: a library for support vector machines. +ACM Transactions on Intelligent Systems and Technology, 2:27:1--27:27, 2011. +Software available at http://www.csie.ntu.edu.tw/~cjlin/libsvm +

    +The bibtex format is +

    +@article{CC01a,
    + author = {Chang, Chih-Chung and Lin, Chih-Jen},
    + title = {{LIBSVM}: A library for support vector machines},
    + journal = {ACM Transactions on Intelligent Systems and Technology},
    + volume = {2},
    + issue = {3},
    + year = {2011},
    + pages = {27:1--27:27},
    + note =	 {Software available at \url{http://www.csie.ntu.edu.tw/~cjlin/libsvm}}
    +}
    +
    +

    +[Go Top] +


    + +Q: I would like to use libsvm in my software. Is there any license problem? +
    +

    +The libsvm license ("the modified BSD license") +is compatible with many +free software licenses such as GPL. Hence, it is very easy to +use libsvm in your software. +Please check the COPYRIGHT file in detail. Basically +you need to +

      +
    1. +Clearly indicate that LIBSVM is used. +
    2. +
    3. +Retain the LIBSVM COPYRIGHT file in your software. +
    4. +
    +It can also be used in commercial products. +

    +[Go Top] +


    + +Q: Is there a repository of additional tools based on libsvm? +
    +

    +Yes, see libsvm +tools +

    +[Go Top] +


    + +Q: On unix machines, I got "error in loading shared libraries" or "cannot open shared object file." What happened ? +
    + +

    +This usually happens if you compile the code +on one machine and run it on another which has incompatible +libraries. +Try to recompile the program on that machine or use static linking. +

    +[Go Top] +


    + +Q: I have modified the source and would like to build the graphic interface "svm-toy" on MS windows. How should I do it ? +
    + +

    +Build it as a project by choosing "Win32 Project." +On the other hand, for "svm-train" and "svm-predict" +you want to choose "Win32 Console Project." +After libsvm 2.5, you can also use the file Makefile.win. +See details in README. + + +

    +If you are not using Makefile.win and see the following +link error +

    +LIBCMTD.lib(wwincrt0.obj) : error LNK2001: unresolved external symbol
    +_wWinMain@16
    +
    +you may have selected a wrong project type. +

    +[Go Top] +


    + +Q: I am an MS windows user but why only one (svm-toy) of those precompiled .exe actually runs ? +
    + +

    +You need to open a command window +and type svmtrain.exe to see all options. +Some examples are in README file. +

    +[Go Top] +


    + +Q: What is the difference between "." and "*" outputed during training? +
    + +

    +"." means every 1,000 iterations (or every #data +iterations is your #data is less than 1,000). +"*" means that after iterations of using +a smaller shrunk problem, +we reset to use the whole set. See the +implementation document for details. +

    +[Go Top] +


    + +Q: Why occasionally the program (including MATLAB or other interfaces) crashes and gives a segmentation fault? +
    + +

    +Very likely the program consumes too much memory than what the +operating system can provide. Try a smaller data and see if the +program still crashes. +

    +[Go Top] +


    + +Q: How to build a dynamic library (.dll file) on MS windows? +
    +

    + +The easiest way is to use Makefile.win. +See details in README. + +Alternatively, you can use Visual C++. Here is +the example using Visual Studio .Net 2008: +

      +
    1. Create a Win32 empty DLL project and set (in Project->$Project_Name +Properties...->Configuration) to "Release." + About how to create a new dynamic link library, please refer to +http://msdn2.microsoft.com/en-us/library/ms235636(VS.80).aspx + +
    2. Add svm.cpp, svm.h to your project. +
    3. Add __WIN32__ and _CRT_SECURE_NO_DEPRECATE to Preprocessor definitions (in +Project->$Project_Name Properties...->C/C++->Preprocessor) +
    4. Set Create/Use Precompiled Header to Not Using Precompiled Headers +(in Project->$Project_Name Properties...->C/C++->Precompiled Headers) +
    5. Set the path for the Modulation Definition File svm.def (in +Project->$Project_Name Properties...->Linker->input +
    6. Build the DLL. +
    7. Rename the dll file to libsvm.dll and move it to the correct path. +
    + + +

    +[Go Top] +


    + +Q: On some systems (e.g., Ubuntu), compiling LIBSVM gives many warning messages. Is this a problem and how to disable the warning message? +
    + +

    +If you are using a version before 3.18, probably you see +a warning message like +

    +svm.cpp:2730: warning: ignoring return value of int fscanf(FILE*, const char*, ...), declared with attribute warn_unused_result
    +
    +This is not a problem; see this page for more +details of ubuntu systems. +To disable the warning message you can replace +
    +CFLAGS = -Wall -Wconversion -O3 -fPIC
    +
    +with +
    +CFLAGS = -Wall -Wconversion -O3 -fPIC -U_FORTIFY_SOURCE
    +
    +in Makefile. +

    After version 3.18, we have a better setting so that such warning messages do not appear. +

    +[Go Top] +


    + +Q: In LIBSVM, why you don't use certain C/C++ library functions to make the code shorter? +
    + +

    +For portability, we use only features defined in ISO C89. Note that features in ISO C99 may not be available everywhere. +Even the newest gcc lacks some features in C99 (see http://gcc.gnu.org/c99status.html for details). +If the situation changes in the future, +we might consider using these newer features. +

    +[Go Top] +


    + +Q: Why sometimes not all attributes of a data appear in the training/model files ? +
    +

    +libsvm uses the so called "sparse" format where zero +values do not need to be stored. Hence a data with attributes +

    +1 0 2 0
    +
    +is represented as +
    +1:1 3:2
    +
    +

    +[Go Top] +


    + +Q: What if my data are non-numerical ? +
    +

    +Currently libsvm supports only numerical data. +You may have to change non-numerical data to +numerical. For example, you can use several +binary attributes to represent a categorical +attribute. +

    +[Go Top] +


    + +Q: Why do you consider sparse format ? Will the training of dense data be much slower ? +
    +

    +This is a controversial issue. The kernel +evaluation (i.e. inner product) of sparse vectors is slower +so the total training time can be at least twice or three times +of that using the dense format. +However, we cannot support only dense format as then we CANNOT +handle extremely sparse cases. Simplicity of the code is another +concern. Right now we decide to support +the sparse format only. +

    +[Go Top] +


    + +Q: Why sometimes the last line of my data is not read by svm-train? +
    + +

    +We assume that you have '\n' in the end of +each line. So please press enter in the end +of your last line. +

    +[Go Top] +


    + +Q: Is there a program to check if my data are in the correct format? +
    + +

    +The svm-train program in libsvm conducts only a simple check of the input data. To do a +detailed check, after libsvm 2.85, you can use the python script tools/checkdata.py. See tools/README for details. +

    +[Go Top] +


    + +Q: May I put comments in data files? +
    + +

    +We don't officially support this. But, currently LIBSVM +is able to process data in the following +format: +

    +1 1:2 2:1 # your comments
    +
    +Note that the character ":" should not appear in your +comments. + +

    +[Go Top] +


    + +Q: How to convert other data formats to LIBSVM format? +
    + +

    +It depends on your data format. A simple way is to use +libsvmwrite in the libsvm matlab/octave interface. + +Take a CSV (comma-separated values) file +in UCI machine learning repository as an example. +We download SPECTF.train. +Labels are in the first column. The following steps produce +a file in the libsvm format. +

    +matlab> SPECTF = csvread('SPECTF.train'); % read a csv file
    +matlab> labels = SPECTF(:, 1); % labels from the 1st column
    +matlab> features = SPECTF(:, 2:end); 
    +matlab> features_sparse = sparse(features); % features must be in a sparse matrix
    +matlab> libsvmwrite('SPECTFlibsvm.train', labels, features_sparse);
    +
    +The tranformed data are stored in SPECTFlibsvm.train. + +

    +Alternatively, you can use convert.c +to convert CSV format to libsvm format. +

    +[Go Top] +


    + +Q: The output of training C-SVM is like the following. What do they mean? +
    +
    optimization finished, #iter = 219 +
    nu = 0.431030 +
    obj = -100.877286, rho = 0.424632 +
    nSV = 132, nBSV = 107 +
    Total nSV = 132 +

    +obj is the optimal objective value of the dual SVM problem. +rho is the bias term in the decision function +sgn(w^Tx - rho). +nSV and nBSV are number of support vectors and bounded support +vectors (i.e., alpha_i = C). nu-svm is a somewhat equivalent +form of C-SVM where C is replaced by nu. nu simply shows the +corresponding parameter. More details are in + +libsvm document. +

    +[Go Top] +


    + +Q: Can you explain more about the model file? +
    + +

    +In the model file, after parameters and other informations such as labels , each line represents a support vector. +Support vectors are listed in the order of "labels" shown earlier. +(i.e., those from the first class in the "labels" list are +grouped first, and so on.) +If k is the total number of classes, +in front of a support vector in class j, there are +k-1 coefficients +y*alpha where alpha are dual solution of the +following two class problems: +
    +1 vs j, 2 vs j, ..., j-1 vs j, j vs j+1, j vs j+2, ..., j vs k +
    +and y=1 in first j-1 coefficients, y=-1 in the remaining +k-j coefficients. + +For example, if there are 4 classes, the file looks like: + +

    ++-+-+-+--------------------+
    +|1|1|1|                    |
    +|v|v|v|  SVs from class 1  |
    +|2|3|4|                    |
    ++-+-+-+--------------------+
    +|1|2|2|                    |
    +|v|v|v|  SVs from class 2  |
    +|2|3|4|                    |
    ++-+-+-+--------------------+
    +|1|2|3|                    |
    +|v|v|v|  SVs from class 3  |
    +|3|3|4|                    |
    ++-+-+-+--------------------+
    +|1|2|3|                    |
    +|v|v|v|  SVs from class 4  |
    +|4|4|4|                    |
    ++-+-+-+--------------------+
    +
    +See also + an illustration using +MATLAB/OCTAVE. +

    +[Go Top] +


    + +Q: Should I use float or double to store numbers in the cache ? +
    + +

    +We have float as the default as you can store more numbers +in the cache. +In general this is good enough but for few difficult +cases (e.g. C very very large) where solutions are huge +numbers, it might be possible that the numerical precision is not +enough using only float. +

    +[Go Top] +


    + +Q: Does libsvm have special treatments for linear SVM? +
    + +

    + +No, libsvm solves linear/nonlinear SVMs by the +same way. +Some tricks may save training/testing time if the +linear kernel is used, +so libsvm is NOT particularly efficient for linear SVM, +especially when +C is large and +the number of data is much larger +than the number of attributes. +You can either +

    + +

    Please also see our SVM guide +on the discussion of using RBF and linear +kernels. +

    +[Go Top] +


    + +Q: The number of free support vectors is large. What should I do? +
    +

    +This usually happens when the data are overfitted. +If attributes of your data are in large ranges, +try to scale them. Then the region +of appropriate parameters may be larger. +Note that there is a scale program +in libsvm. +

    +[Go Top] +


    + +Q: Should I scale training and testing data in a similar way? +
    +

    +Yes, you can do the following: +

    +> svm-scale -s scaling_parameters train_data > scaled_train_data
    +> svm-scale -r scaling_parameters test_data > scaled_test_data
    +
    +

    +[Go Top] +


    + +Q: Does it make a big difference if I scale each attribute to [0,1] instead of [-1,1]? +
    + +

    +For the linear scaling method, if the RBF kernel is +used and parameter selection is conducted, there +is no difference. Assume Mi and mi are +respectively the maximal and minimal values of the +ith attribute. Scaling to [0,1] means +

    +                x'=(x-mi)/(Mi-mi)
    +
    +For [-1,1], +
    +                x''=2(x-mi)/(Mi-mi)-1.
    +
    +In the RBF kernel, +
    +                x'-y'=(x-y)/(Mi-mi), x''-y''=2(x-y)/(Mi-mi).
    +
    +Hence, using (C,g) on the [0,1]-scaled data is the +same as (C,g/2) on the [-1,1]-scaled data. + +

    Though the performance is the same, the computational +time may be different. For data with many zero entries, +[0,1]-scaling keeps the sparsity of input data and hence +may save the time. +

    +[Go Top] +


    + +Q: The prediction rate is low. How could I improve it? +
    +

    +Try to use the model selection tool grid.py in the tools +directory find +out good parameters. To see the importance of model selection, +please +see our guide for beginners: + +A practical guide to support vector +classification + +

    +[Go Top] +


    + +Q: My data are unbalanced. Could libsvm handle such problems? +
    +

    +Yes, there is a -wi options. For example, if you use +

    +> svm-train -s 0 -c 10 -w1 1 -w-1 5 data_file
    +
    +

    +the penalty for class "-1" is larger. +Note that this -w option is for C-SVC only. +

    +[Go Top] +


    + +Q: What is the difference between nu-SVC and C-SVC? +
    +

    +Basically they are the same thing but with different +parameters. The range of C is from zero to infinity +but nu is always between [0,1]. A nice property +of nu is that it is related to the ratio of +support vectors and the ratio of the training +error. +

    +[Go Top] +


    + +Q: The program keeps running (without showing any output). What should I do? +
    +

    +You may want to check your data. Each training/testing +data must be in one line. It cannot be separated. +In addition, you have to remove empty lines. +

    +[Go Top] +


    + +Q: The program keeps running (with output, i.e. many dots). What should I do? +
    +

    +In theory libsvm guarantees to converge. +Therefore, this means you are +handling ill-conditioned situations +(e.g. too large/small parameters) so numerical +difficulties occur. +

    +You may get better numerical stability by replacing +

    +typedef float Qfloat;
    +
    +in svm.cpp with +
    +typedef double Qfloat;
    +
    +That is, elements in the kernel cache are stored +in double instead of single. However, this means fewer elements +can be put in the kernel cache. +

    +[Go Top] +


    + +Q: The training time is too long. What should I do? +
    +

    +For large problems, please specify enough cache size (i.e., +-m). +Slow convergence may happen for some difficult cases (e.g. -c is large). +You can try to use a looser stopping tolerance with -e. +If that still doesn't work, you may train only a subset of the data. +You can use the program subset.py in the directory "tools" +to obtain a random subset. + +

    +If you have extremely large data and face this difficulty, please +contact us. We will be happy to discuss possible solutions. + +

    When using large -e, you may want to check if -h 0 (no shrinking) or -h 1 (shrinking) is faster. +See a related question below. + +

    +[Go Top] +


    + +Q: Does shrinking always help? +
    +

    +If the number of iterations is high, then shrinking +often helps. +However, if the number of iterations is small +(e.g., you specify a large -e), then +probably using -h 0 (no shrinking) is better. +See the +implementation document for details. +

    +[Go Top] +


    + +Q: How do I get the decision value(s)? +
    +

    +We print out decision values for regression. For classification, +we solve several binary SVMs for multi-class cases. You +can obtain values by easily calling the subroutine +svm_predict_values. Their corresponding labels +can be obtained from svm_get_labels. +Details are in +README of libsvm package. + +

    +If you are using MATLAB/OCTAVE interface, svmpredict can directly +give you decision values. Please see matlab/README for details. + +

    +We do not recommend the following. But if you would +like to get values for +TWO-class classification with labels +1 and -1 +(note: +1 and -1 but not things like 5 and 10) +in the easiest way, simply add +

    +		printf("%f\n", dec_values[0]*model->label[0]);
    +
    +after the line +
    +		svm_predict_values(model, x, dec_values);
    +
    +of the file svm.cpp. +Positive (negative) +decision values correspond to data predicted as +1 (-1). + + +

    +[Go Top] +


    + +Q: How do I get the distance between a point and the hyperplane? +
    +

    +The distance is |decision_value| / |w|. +We have |w|^2 = w^Tw = alpha^T Q alpha = 2*(dual_obj + sum alpha_i). +Thus in svm.cpp please find the place +where we calculate the dual objective value +(i.e., the subroutine Solve()) +and add a statement to print w^Tw. + +

    +[Go Top] +


    + +Q: On 32-bit machines, if I use a large cache (i.e. large -m) on a linux machine, why sometimes I get "segmentation fault ?" +
    +

    + +On 32-bit machines, the maximum addressable +memory is 4GB. The Linux kernel uses 3:1 +split which means user space is 3G and +kernel space is 1G. Although there are +3G user space, the maximum dynamic allocation +memory is 2G. So, if you specify -m near 2G, +the memory will be exhausted. And svm-train +will fail when it asks more memory. +For more details, please read + +this article. +

    +The easiest solution is to switch to a + 64-bit machine. +Otherwise, there are two ways to solve this. If your +machine supports Intel's PAE (Physical Address +Extension), you can turn on the option HIGHMEM64G +in Linux kernel which uses 4G:4G split for +kernel and user space. If you don't, you can +try a software `tub' which can eliminate the 2G +boundary for dynamic allocated memory. The `tub' +is available at +http://www.bitwagon.com/tub.html. + + + +

    +[Go Top] +


    + +Q: How do I disable screen output of svm-train? +
    +

    +For commend-line users, use the -q option: +

    +> ./svm-train -q heart_scale
    +
    +

    +For library users, set the global variable +

    +extern void (*svm_print_string) (const char *);
    +
    +to specify the output format. You can disable the output by the following steps: +
      +
    1. +Declare a function to output nothing: +
      +void print_null(const char *s) {}
      +
      +
    2. +
    3. +Assign the output function of libsvm by +
      +svm_print_string = &print_null;
      +
      +
    4. +
    +Finally, a way used in earlier libsvm +is by updating svm.cpp from +
    +#if 1
    +void info(const char *fmt,...)
    +
    +to +
    +#if 0
    +void info(const char *fmt,...)
    +
    +

    +[Go Top] +


    + +Q: I would like to use my own kernel. Any example? In svm.cpp, there are two subroutines for kernel evaluations: k_function() and kernel_function(). Which one should I modify ? +
    +

    +An example is "LIBSVM for string data" in LIBSVM Tools. +

    +The reason why we have two functions is as follows. +For the RBF kernel exp(-g |xi - xj|^2), if we calculate +xi - xj first and then the norm square, there are 3n operations. +Thus we consider exp(-g (|xi|^2 - 2dot(xi,xj) +|xj|^2)) +and by calculating all |xi|^2 in the beginning, +the number of operations is reduced to 2n. +This is for the training. For prediction we cannot +do this so a regular subroutine using that 3n operations is +needed. + +The easiest way to have your own kernel is +to put the same code in these two +subroutines by replacing any kernel. +

    +[Go Top] +


    + +Q: What method does libsvm use for multi-class SVM ? Why don't you use the "1-against-the rest" method? +
    +

    +It is one-against-one. We chose it after doing the following +comparison: +C.-W. Hsu and C.-J. Lin. + +A comparison of methods +for multi-class support vector machines +, +IEEE Transactions on Neural Networks, 13(2002), 415-425. + +

    +"1-against-the rest" is a good method whose performance +is comparable to "1-against-1." We do the latter +simply because its training time is shorter. +

    +[Go Top] +


    + +Q: I would like to solve L2-loss SVM (i.e., error term is quadratic). How should I modify the code ? +
    +

    +It is extremely easy. Taking c-svc for example, to solve +

    +min_w w^Tw/2 + C \sum max(0, 1- (y_i w^Tx_i+b))^2, +

    +only two +places of svm.cpp have to be changed. +First, modify the following line of +solve_c_svc from +

    +	s.Solve(l, SVC_Q(*prob,*param,y), minus_ones, y,
    +		alpha, Cp, Cn, param->eps, si, param->shrinking);
    +
    +to +
    +	s.Solve(l, SVC_Q(*prob,*param,y), minus_ones, y,
    +		alpha, INF, INF, param->eps, si, param->shrinking);
    +
    +Second, in the class of SVC_Q, declare C as +a private variable: +
    +	double C;
    +
    +In the constructor replace +
    +	for(int i=0;i<prob.l;i++)
    +		QD[i]= (Qfloat)(this->*kernel_function)(i,i);
    +
    +with +
    +        this->C = param.C;
    +	for(int i=0;i<prob.l;i++)
    +		QD[i]= (Qfloat)(this->*kernel_function)(i,i)+0.5/C;
    +
    +Then in the subroutine get_Q, after the for loop, add +
    +        if(i >= start && i < len) 
    +		data[i] += 0.5/C;
    +
    + +

    +For one-class svm, the modification is exactly the same. For SVR, you don't need an if statement like the above. Instead, you only need a simple assignment: +

    +	data[real_i] += 0.5/C;
    +
    + + +

    +For large linear L2-loss SVM, please use +LIBLINEAR. +

    +[Go Top] +


    + +Q: In one-class SVM, parameter nu should be an upper bound of the training error rate. Why sometimes I get a training error rate bigger than nu? +
    + +

    +At optimum, some training instances should satisfy +w^Tx - rho = 0. However, numerically they may be slightly +smaller than zero +Then they are wrongly counted +as training errors. You can use a smaller stopping tolerance +(by the -e option) to make this problem less serious. + +

    +This issue does not occur for nu-SVC for +two-class classification. +We have that +

      +
    1. nu is an upper bound on the ratio of training points +on the wrong side of the hyperplane, and +
    2. therefore, nu is also an upper bound on the training error rate. +
    +Numerical issues occur in calculating the first case +because some training points satisfying y(w^Tx + b) - rho = 0 +become negative. +However, we have no numerical problems for the second case because +we compare y(w^Tx + b) and 0 for counting training errors. +

    +[Go Top] +


    + +Q: Why the code gives NaN (not a number) results? +
    +

    +This rarely happens, but few users reported the problem. +It seems that their +computers for training libsvm have the VPN client +running. The VPN software has some bugs and causes this +problem. Please try to close or disconnect the VPN client. +

    +[Go Top] +


    + +Q: Why the sign of predicted labels and decision values are sometimes reversed? +
    +

    + +This situation may occur before version 3.17. +Nothing is wrong. Very likely you have two labels +1/-1 and the first instance in your data +has -1. We give the following explanation. + +

    +Internally class labels are ordered by their first occurrence in the training set. For a k-class data, internally labels +are 0, ..., k-1, and each two-class SVM considers pair +(i, j) with i < j. Then class i is treated as positive (+1) +and j as negative (-1). +For example, if the data set has labels +5/+10 and +10 appears +first, then internally the +5 versus +10 SVM problem +has +10 as positive (+1) and +5 as negative (-1). + +

    +By this setting, if you have labels +1 and -1, +it's possible that internally they correspond to -1 and +1, +respectively. Some new users have been confused about +this, so after version 3.17, if the data set has only +two labels +1 and -1, +internally we ensure +1 to be before -1. Then class +1 +is always treated as positive in the SVM problem. +Note that this is for two-class data only. +

    +[Go Top] +


    + +Q: I don't know class labels of test data. What should I put in the first column of the test file? +
    +

    Any value is ok. In this situation, what you will use is the output file of svm-predict, which gives predicted class labels. + + +

    +[Go Top] +


    + +Q: How can I use OpenMP to parallelize LIBSVM on a multicore/shared-memory computer? +
    + +

    It is very easy if you are using GCC 4.2 +or after. + +

    In Makefile, add -fopenmp to CFLAGS. + +

    In class SVC_Q of svm.cpp, modify the for loop +of get_Q to: +

    +#pragma omp parallel for private(j) 
    +			for(j=start;j<len;j++)
    +
    +

    In the subroutine svm_predict_values of svm.cpp, add one line to the for loop: +

    +#pragma omp parallel for private(i) 
    +		for(i=0;i<l;i++)
    +			kvalue[i] = Kernel::k_function(x,model->SV[i],model->param);
    +
    +For regression, you need to modify +class SVR_Q instead. The loop in svm_predict_values +is also different because you need +a reduction clause for the variable sum: +
    +#pragma omp parallel for private(i) reduction(+:sum) 
    +		for(i=0;i<model->l;i++)
    +			sum += sv_coef[i] * Kernel::k_function(x,model->SV[i],model->param);
    +
    + +

    Then rebuild the package. Kernel evaluations in training/testing will be parallelized. An example of running this modification on +an 8-core machine using the data set +ijcnn1: + +

    8 cores: +

    +%setenv OMP_NUM_THREADS 8
    +%time svm-train -c 16 -g 4 -m 400 ijcnn1
    +27.1sec
    +
    +1 core: +
    +%setenv OMP_NUM_THREADS 1
    +%time svm-train -c 16 -g 4 -m 400 ijcnn1
    +79.8sec
    +
    +For this data, kernel evaluations take 80% of training time. In the above example, we assume you use csh. For bash, use +
    +export OMP_NUM_THREADS=8
    +
    +instead. + +

    For Python interface, you need to add the -lgomp link option: +

    +$(CXX) -lgomp -shared -dynamiclib svm.o -o libsvm.so.$(SHVER)
    +
    + +

    For MS Windows, you need to add /openmp in CFLAGS of Makefile.win + +

    +[Go Top] +


    + +Q: How could I know which training instances are support vectors? +
    + +

    +It's very simple. Since version 3.13, you can use the function +

    +void svm_get_sv_indices(const struct svm_model *model, int *sv_indices)
    +
    +to get indices of support vectors. For example, in svm-train.c, after +
    +		model = svm_train(&prob, &param);
    +
    +you can add +
    +		int nr_sv = svm_get_nr_sv(model);
    +		int *sv_indices = Malloc(int, nr_sv);
    +		svm_get_sv_indices(model, sv_indices);
    +		for (int i=0; i<nr_sv; i++)
    +			printf("instance %d is a support vector\n", sv_indices[i]);
    +
    + +

    If you use matlab interface, you can directly check +

    +model.sv_indices
    +
    +

    +[Go Top] +


    + +Q: Why sv_indices (indices of support vectors) are not stored in the saved model file? +
    + +

    +Although sv_indices is a member of the model structure +to +indicate support vectors in the training set, +we do not store its contents in the model file. +The model file is mainly used in the future for +prediction, so it is basically independent +from training data. Thus +storing sv_indices is not necessary. +Users should find support vectors right after +the training process. See the previous FAQ. +

    +[Go Top] +


    + +Q: After doing cross validation, why there is no model file outputted ? +
    +

    +Cross validation is used for selecting good parameters. +After finding them, you want to re-train the whole +data without the -v option. +

    +[Go Top] +


    + +Q: Why my cross-validation results are different from those in the Practical Guide? +
    +

    + +Due to random partitions of +the data, on different systems CV accuracy values +may be different. +

    +[Go Top] +


    + +Q: On some systems CV accuracy is the same in several runs. How could I use different data partitions? In other words, how do I set random seed in LIBSVM? +
    +

    +If you use GNU C library, +the default seed 1 is considered. Thus you always +get the same result of running svm-train -v. +To have different seeds, you can add the following code +in svm-train.c: +

    +#include <time.h>
    +
    +and in the beginning of main(), +
    +srand(time(0));
    +
    +Alternatively, if you are not using GNU C library +and would like to use a fixed seed, you can have +
    +srand(1);
    +
    + +

    +For Java, the random number generator +is initialized using the time information. +So results of two CV runs are different. +To fix the seed, after version 3.1 (released +in mid 2011), you can add +

    +svm.rand.setSeed(0);
    +
    +in the main() function of svm_train.java. + +

    +If you use CV to select parameters, it is recommended to use identical folds +under different parameters. In this case, you can consider fixing the seed. +

    +[Go Top] +


    + +Q: Why on windows sometimes grid.py fails? +
    +

    + +This problem shouldn't happen after version +2.85. If you are using earlier versions, +please download the latest one. + + +

    +[Go Top] +


    + +Q: Why grid.py/easy.py sometimes generates the following warning message? +
    +
    +Warning: empty z range [62.5:62.5], adjusting to [61.875:63.125]
    +Notice: cannot contour non grid data!
    +
    +

    Nothing is wrong and please disregard the +message. It is from gnuplot when drawing +the contour. +

    +[Go Top] +


    + +Q: How do I choose the kernel? +
    + +

    +In general we suggest you to try the RBF kernel first. +A recent result by Keerthi and Lin +( +download paper here) +shows that if RBF is used with model selection, +then there is no need to consider the linear kernel. +The kernel matrix using sigmoid may not be positive definite +and in general it's accuracy is not better than RBF. +(see the paper by Lin and Lin +( +download paper here). +Polynomial kernels are ok but if a high degree is used, +numerical difficulties tend to happen +(thinking about dth power of (<1) goes to 0 +and (>1) goes to infinity). +

    +[Go Top] +


    + +Q: How does LIBSVM perform parameter selection for multi-class problems? +
    + +

    +LIBSVM implements "one-against-one" multi-class method, so there are +k(k-1)/2 binary models, where k is the number of classes. + +

    +We can consider two ways to conduct parameter selection. + +

      +
    1. +For any two classes of data, a parameter selection procedure is conducted. Finally, +each decision function has its own optimal parameters. +
    2. +
    3. +The same parameters are used for all k(k-1)/2 binary classification problems. +We select parameters that achieve the highest overall performance. +
    4. +
    + +Each has its own advantages. A +single parameter set may not be uniformly good for all k(k-1)/2 decision functions. +However, as the overall accuracy is the final consideration, one parameter set +for one decision function may lead to over-fitting. In the paper +

    +Chen, Lin, and Schölkopf, + +A tutorial on nu-support vector machines. + +Applied Stochastic Models in Business and Industry, 21(2005), 111-136, + +

    +they have experimentally +shown that the two methods give similar performance. +Therefore, currently the parameter selection in LIBSVM +takes the second approach by considering the same parameters for +all k(k-1)/2 models. +

    +[Go Top] +


    + +Q: How do I choose parameters for one-class SVM as training data are in only one class? +
    +

    +You have pre-specified true positive rate in mind and then search for +parameters which achieve similar cross-validation accuracy. +

    +[Go Top] +


    + +Q: Why training a probability model (i.e., -b 1) takes a longer time? +
    +

    +To construct this probability model, we internally conduct a +cross validation, which is more time consuming than +a regular training. +Hence, in general you do parameter selection first without +-b 1. You only use -b 1 when good parameters have been +selected. In other words, you avoid using -b 1 and -v +together. +

    +[Go Top] +


    + +Q: Why using the -b option does not give me better accuracy? +
    +

    +There is absolutely no reason the probability outputs guarantee +you better accuracy. The main purpose of this option is +to provide you the probability estimates, but not to boost +prediction accuracy. From our experience, +after proper parameter selections, in general with +and without -b have similar accuracy. Occasionally there +are some differences. +It is not recommended to compare the two under +just a fixed parameter +set as more differences will be observed. +

    +[Go Top] +


    + +Q: Why using svm-predict -b 0 and -b 1 gives different accuracy values? +
    +

    +Let's just consider two-class classification here. After probability information is obtained in training, +we do not have +

    +prob > = 0.5 if and only if decision value >= 0. +

    +So predictions may be different with -b 0 and 1. +

    +[Go Top] +


    + +Q: How can I save images drawn by svm-toy? +
    +

    +For Microsoft windows, first press the "print screen" key on the keyboard. +Open "Microsoft Paint" +(included in Windows) +and press "ctrl-v." Then you can clip +the part of picture which you want. +For X windows, you can +use the program "xv" or "import" to grab the picture of the svm-toy window. +

    +[Go Top] +


    + +Q: I press the "load" button to load data points but why svm-toy does not draw them ? +
    +

    +The program svm-toy assumes both attributes (i.e. x-axis and y-axis +values) are in (0,1). Hence you want to scale your +data to between a small positive number and +a number less than but very close to 1. +Moreover, class labels must be 1, 2, or 3 +(not 1.0, 2.0 or anything else). +

    +[Go Top] +


    + +Q: I would like svm-toy to handle more than three classes of data, what should I do ? +
    +

    +Taking windows/svm-toy.cpp as an example, you need to +modify it and the difference +from the original file is as the following: (for five classes of +data) +

    +30,32c30
    +< 	RGB(200,0,200),
    +< 	RGB(0,160,0),
    +< 	RGB(160,0,0)
    +---
    +> 	RGB(200,0,200)
    +39c37
    +< HBRUSH brush1, brush2, brush3, brush4, brush5;
    +---
    +> HBRUSH brush1, brush2, brush3;
    +113,114d110
    +< 	brush4 = CreateSolidBrush(colors[7]);
    +< 	brush5 = CreateSolidBrush(colors[8]);
    +155,157c151
    +< 	else if(v==3) return brush3;
    +< 	else if(v==4) return brush4;
    +< 	else return brush5;
    +---
    +> 	else return brush3;
    +325d318
    +< 	  int colornum = 5;
    +327c320
    +< 		svm_node *x_space = new svm_node[colornum * prob.l];
    +---
    +> 		svm_node *x_space = new svm_node[3 * prob.l];
    +333,338c326,331
    +< 			x_space[colornum * i].index = 1;
    +< 			x_space[colornum * i].value = q->x;
    +< 			x_space[colornum * i + 1].index = 2;
    +< 			x_space[colornum * i + 1].value = q->y;
    +< 			x_space[colornum * i + 2].index = -1;
    +< 			prob.x[i] = &x_space[colornum * i];
    +---
    +> 			x_space[3 * i].index = 1;
    +> 			x_space[3 * i].value = q->x;
    +> 			x_space[3 * i + 1].index = 2;
    +> 			x_space[3 * i + 1].value = q->y;
    +> 			x_space[3 * i + 2].index = -1;
    +> 			prob.x[i] = &x_space[3 * i];
    +397c390
    +< 				if(current_value > 5) current_value = 1;
    +---
    +> 				if(current_value > 3) current_value = 1;
    +
    +

    +[Go Top] +


    + +Q: What is the difference between Java version and C++ version of libsvm? +
    +

    +They are the same thing. We just rewrote the C++ code +in Java. +

    +[Go Top] +


    + +Q: Is the Java version significantly slower than the C++ version? +
    +

    +This depends on the VM you used. We have seen good +VM which leads the Java version to be quite competitive with +the C++ code. (though still slower) +

    +[Go Top] +


    + +Q: While training I get the following error message: java.lang.OutOfMemoryError. What is wrong? +
    +

    +You should try to increase the maximum Java heap size. +For example, +

    +java -Xmx2048m -classpath libsvm.jar svm_train ...
    +
    +sets the maximum heap size to 2048M. +

    +[Go Top] +


    + +Q: Why you have the main source file svm.m4 and then transform it to svm.java? +
    +

    +Unlike C, Java does not have a preprocessor built-in. +However, we need some macros (see first 3 lines of svm.m4). + + +

    +[Go Top] +


    + +Q: Except the python-C++ interface provided, could I use Jython to call libsvm ? +
    +

    Yes, here are some examples: + +

    +$ export CLASSPATH=$CLASSPATH:~/libsvm-2.91/java/libsvm.jar
    +$ ./jython
    +Jython 2.1a3 on java1.3.0 (JIT: jitc)
    +Type "copyright", "credits" or "license" for more information.
    +>>> from libsvm import *
    +>>> dir()
    +['__doc__', '__name__', 'svm', 'svm_model', 'svm_node', 'svm_parameter',
    +'svm_problem']
    +>>> x1 = [svm_node(index=1,value=1)]
    +>>> x2 = [svm_node(index=1,value=-1)]
    +>>> param = svm_parameter(svm_type=0,kernel_type=2,gamma=1,cache_size=40,eps=0.001,C=1,nr_weight=0,shrinking=1)
    +>>> prob = svm_problem(l=2,y=[1,-1],x=[x1,x2])
    +>>> model = svm.svm_train(prob,param)
    +*
    +optimization finished, #iter = 1
    +nu = 1.0
    +obj = -1.018315639346838, rho = 0.0
    +nSV = 2, nBSV = 2
    +Total nSV = 2
    +>>> svm.svm_predict(model,x1)
    +1.0
    +>>> svm.svm_predict(model,x2)
    +-1.0
    +>>> svm.svm_save_model("test.model",model)
    +
    +
    + +

    +[Go Top] +


    + +Q: I compile the MATLAB interface without problem, but why errors occur while running it? +
    +

    +Your compiler version may not be supported/compatible for MATLAB. +Please check this MATLAB page first and then specify the version +number. For example, if g++ X.Y is supported, replace +

    +CXX = g++
    +
    +in the Makefile with +
    +CXX = g++-X.Y
    +
    +

    +[Go Top] +


    + +Q: On 64bit Windows I compile the MATLAB interface without problem, but why errors occur while running it? +
    +

    + + +Please make sure that you use +the -largeArrayDims option in make.m. For example, +

    +mex -largeArrayDims -O -c svm.cpp
    +
    + +Moreover, if you use Microsoft Visual Studio, +probabally it is not properly installed. +See the explanation +here. +

    +[Go Top] +


    + +Q: Does the MATLAB interface provide a function to do scaling? +
    +

    +It is extremely easy to do scaling under MATLAB. +The following one-line code scale each feature to the range +of [0,1]: +

    +(data - repmat(min(data,[],1),size(data,1),1))*spdiags(1./(max(data,[],1)-min(data,[],1))',0,size(data,2),size(data,2))
    +
    +

    +[Go Top] +


    + +Q: How could I use MATLAB interface for parameter selection? +
    +

    +One can do this by a simple loop. +See the following example: +

    +bestcv = 0;
    +for log2c = -1:3,
    +  for log2g = -4:1,
    +    cmd = ['-v 5 -c ', num2str(2^log2c), ' -g ', num2str(2^log2g)];
    +    cv = svmtrain(heart_scale_label, heart_scale_inst, cmd);
    +    if (cv >= bestcv),
    +      bestcv = cv; bestc = 2^log2c; bestg = 2^log2g;
    +    end
    +    fprintf('%g %g %g (best c=%g, g=%g, rate=%g)\n', log2c, log2g, cv, bestc, bestg, bestcv);
    +  end
    +end
    +
    +You may adjust the parameter range in the above loops. +

    +[Go Top] +


    + +Q: I use MATLAB parallel programming toolbox on a multi-core environment for parameter selection. Why the program is even slower? +
    +

    +Fabrizio Lacalandra of University of Pisa reported this issue. +It seems the problem is caused by the screen output. +If you disable the info function +using

    #if 0,
    then the problem +may be solved. +

    +[Go Top] +


    + +Q: How do I use LIBSVM with OpenMP under MATLAB? +
    +

    +In Makefile, +you need to add -fopenmp to CFLAGS and -lgomp to MEX_OPTION. For Octave, you need the same modification. + +

    However, a minor problem is that +the number of threads cannot +be specified in MATLAB. We tried Version 7.12 (R2011a) and gcc-4.6.1. + +

    +% export OMP_NUM_THREADS=4; matlab
    +>> setenv('OMP_NUM_THREADS', '1');
    +
    + +Then OMP_NUM_THREADS is still 4 while running the program. Please contact us if you +see how to solve this problem. You can, however, +specify the number in the source code (thanks +to comments from Ricardo Santiago-mozos): +
    +#pragma omp parallel  for private(i) num_threads(4)
    +
    +

    +[Go Top] +


    + +Q: How could I generate the primal variable w of linear SVM? +
    +

    +Let's start from the binary class and +assume you have two labels -1 and +1. +After obtaining the model from calling svmtrain, +do the following to have w and b: +

    +w = model.SVs' * model.sv_coef;
    +b = -model.rho;
    +
    +if model.Label(1) == -1
    +  w = -w;
    +  b = -b;
    +end
    +
    +If you do regression or one-class SVM, then the if statement is not needed. + +

    For multi-class SVM, we illustrate the setting +in the following example of running the iris +data, which have 3 classes +

      
    +> [y, x] = libsvmread('../../htdocs/libsvmtools/datasets/multiclass/iris.scale');
    +> m = svmtrain(y, x, '-t 0')
    +
    +m = 
    +
    +    Parameters: [5x1 double]
    +      nr_class: 3
    +       totalSV: 42
    +           rho: [3x1 double]
    +         Label: [3x1 double]
    +         ProbA: []
    +         ProbB: []
    +           nSV: [3x1 double]
    +       sv_coef: [42x2 double]
    +           SVs: [42x4 double]
    +
    +sv_coef is like: +
    ++-+-+--------------------+
    +|1|1|                    |
    +|v|v|  SVs from class 1  |
    +|2|3|                    |
    ++-+-+--------------------+
    +|1|2|                    |
    +|v|v|  SVs from class 2  |
    +|2|3|                    |
    ++-+-+--------------------+
    +|1|2|                    |
    +|v|v|  SVs from class 3  |
    +|3|3|                    |
    ++-+-+--------------------+
    +
    +so we need to see nSV of each classes. +
      
    +> m.nSV
    +
    +ans =
    +
    +     3
    +    21
    +    18
    +
    +Suppose the goal is to find the vector w of classes +1 vs 3. Then +y_i alpha_i of training 1 vs 3 are +
      
    +> coef = [m.sv_coef(1:3,2); m.sv_coef(25:42,1)];
    +
    +and SVs are: +
      
    +> SVs = [m.SVs(1:3,:); m.SVs(25:42,:)];
    +
    +Hence, w is +
    +> w = SVs'*coef;
    +
    +For rho, +
    +> m.rho
    +
    +ans =
    +
    +    1.1465
    +    0.3682
    +   -1.9969
    +> b = -m.rho(2);
    +
    +because rho is arranged by 1vs2 1vs3 2vs3. + + + +

    +[Go Top] +


    + +Q: Is there an OCTAVE interface for libsvm? +
    +

    +Yes, after libsvm 2.86, the matlab interface +works on OCTAVE as well. Please use make.m by typing +

    +>> make 
    +
    +under OCTAVE. +

    +[Go Top] +


    + +Q: How to handle the name conflict between svmtrain in the libsvm matlab interface and that in MATLAB bioinformatics toolbox? +
    +

    +The easiest way is to rename the svmtrain binary +file (e.g., svmtrain.mexw32 on 32-bit windows) +to a different +name (e.g., svmtrain2.mexw32). +

    +[Go Top] +


    + +Q: On Windows I got an error message "Invalid MEX-file: Specific module not found" when running the pre-built MATLAB interface in the windows sub-directory. What should I do? +
    +

    + +The error usually happens +when there are missing runtime components +such as MSVCR100.dll on your Windows platform. +You can use tools such as +Dependency +Walker to find missing library files. + +

    +For example, if the pre-built MEX files are compiled by +Visual C++ 2010, +you must have installed +Microsoft Visual C++ Redistributable Package 2010 +(vcredist_x86.exe). You can easily find the freely +available file from Microsoft's web site. + +

    +For 64bit Windows, the situation is similar. If +the pre-built files are by +Visual C++ 2008, then you must have +Microsoft Visual C++ Redistributable Package 2008 +(vcredist_x64.exe). +

    +[Go Top] +


    + +Q: LIBSVM supports 1-vs-1 multi-class classification. If instead I would like to use 1-vs-rest, how to implement it using MATLAB interface? +
    + +

    +Please use code in the following directory. The following example shows how to +train and test the problem dna (training and testing). + +

    Load, train and predict data: +

    +[trainY trainX] = libsvmread('./dna.scale');
    +[testY testX] = libsvmread('./dna.scale.t');
    +model = ovrtrain(trainY, trainX, '-c 8 -g 4');
    +[pred ac decv] = ovrpredict(testY, testX, model);
    +fprintf('Accuracy = %g%%\n', ac * 100);
    +
    +Conduct CV on a grid of parameters +
    +bestcv = 0;
    +for log2c = -1:2:3,
    +  for log2g = -4:2:1,
    +    cmd = ['-q -c ', num2str(2^log2c), ' -g ', num2str(2^log2g)];
    +    cv = get_cv_ac(trainY, trainX, cmd, 3);
    +    if (cv >= bestcv),
    +      bestcv = cv; bestc = 2^log2c; bestg = 2^log2g;
    +    end
    +    fprintf('%g %g %g (best c=%g, g=%g, rate=%g)\n', log2c, log2g, cv, bestc, bestg, bestcv);
    +  end
    +end
    +
    +

    +[Go Top] +


    + +Q: I tried to install matlab interface on mac, but failed. What should I do? +
    + +

    +We assume that in a matlab command window you change directory to libsvm/matlab and type +

    +>> make
    +
    +We discuss the following situations. + +
      +
    1. An error message like "libsvmread.c:1:19: fatal error: +stdio.h: No such file or directory" appears. + +

      +Reason: "make" looks for a C++ compiler, but +no compiler is found. To get one, you can +

        +
      • Install XCode offered by Apple Inc. +
      • Install XCode Command Line Tools. +
      + +

      +

    2. On OS X with Xcode 4.2+, I got an error message like "llvm-gcc-4.2: +command not found." + +

      +Reason: Since Apple Inc. only ships llsvm-gcc instead of gcc-4.2, +llvm-gcc-4.2 cannot be found. + +

      +If you are using Xcode 4.2-4.6, +a related solution is offered at +http://www.mathworks.com/matlabcentral/answers/94092. + +

      +On the other hand, for Xcode 5 (including Xcode 4.2-4.6), in a Matlab command window, enter +

        +
      • cd (matlabroot) +
      • cd bin +
      • Backup your mexopts.sh first +
      • edit mexopts.sh +
      • Scroll down to "maci64" section. Change +
        +		CC='llvm-gcc-4.2'
        +		CXX='llvm-g++-4.2'
        +
        +to +
        +		CC='llvm-gcc'
        +		CXX='llvm-g++'
        +
        +
      + +Please also ensure that SDKROOT corresponds to the SDK version you are using. + +

      +

    3. Other errors: you may check http://www.mathworks.com/matlabcentral/answers/94092. + +
    +

    +[Go Top] +


    +

    +LIBSVM home page +

    + + diff --git a/MSC/libsvm-weights-3.20/Makefile b/MSC/libsvm-weights-3.20/Makefile new file mode 100644 index 0000000..bf2a6a6 --- /dev/null +++ b/MSC/libsvm-weights-3.20/Makefile @@ -0,0 +1,25 @@ +CXX ?= g++ +CFLAGS = -Wall -Wconversion -O3 -fPIC +SHVER = 2 +OS = $(shell uname) + +all: svm-train svm-predict svm-scale + +lib: svm.o + if [ "$(OS)" = "Darwin" ]; then \ + SHARED_LIB_FLAG="-dynamiclib -Wl,-install_name,libsvm.so.$(SHVER)"; \ + else \ + SHARED_LIB_FLAG="-shared -Wl,-soname,libsvm.so.$(SHVER)"; \ + fi; \ + $(CXX) $${SHARED_LIB_FLAG} svm.o -o libsvm.so.$(SHVER) + +svm-predict: svm-predict.c svm.o + $(CXX) $(CFLAGS) svm-predict.c svm.o -o svm-predict -lm +svm-train: svm-train.c svm.o + $(CXX) $(CFLAGS) svm-train.c svm.o -o svm-train -lm +svm-scale: svm-scale.c + $(CXX) $(CFLAGS) svm-scale.c -o svm-scale +svm.o: svm.cpp svm.h + $(CXX) $(CFLAGS) -c svm.cpp +clean: + rm -f *~ svm.o svm-train svm-predict svm-scale libsvm.so.$(SHVER) diff --git a/MSC/libsvm-weights-3.20/Makefile.win b/MSC/libsvm-weights-3.20/Makefile.win new file mode 100644 index 0000000..8ce36cb --- /dev/null +++ b/MSC/libsvm-weights-3.20/Makefile.win @@ -0,0 +1,33 @@ +#You must ensure nmake.exe, cl.exe, link.exe are in system path. +#VCVARS32.bat +#Under dosbox prompt +#nmake -f Makefile.win + +########################################## +CXX = cl.exe +CFLAGS = /nologo /O2 /EHsc /I. /D _WIN32 /D _CRT_SECURE_NO_DEPRECATE +TARGET = windows + +all: $(TARGET)\svm-train.exe $(TARGET)\svm-predict.exe $(TARGET)\svm-scale.exe $(TARGET)\svm-toy.exe lib + +$(TARGET)\svm-predict.exe: svm.h svm-predict.c svm.obj + $(CXX) $(CFLAGS) svm-predict.c svm.obj -Fe$(TARGET)\svm-predict.exe + +$(TARGET)\svm-train.exe: svm.h svm-train.c svm.obj + $(CXX) $(CFLAGS) svm-train.c svm.obj -Fe$(TARGET)\svm-train.exe + +$(TARGET)\svm-scale.exe: svm.h svm-scale.c + $(CXX) $(CFLAGS) svm-scale.c -Fe$(TARGET)\svm-scale.exe + +$(TARGET)\svm-toy.exe: svm.h svm.obj svm-toy\windows\svm-toy.cpp + $(CXX) $(CFLAGS) svm-toy\windows\svm-toy.cpp svm.obj user32.lib gdi32.lib comdlg32.lib -Fe$(TARGET)\svm-toy.exe + +svm.obj: svm.cpp svm.h + $(CXX) $(CFLAGS) -c svm.cpp + +lib: svm.cpp svm.h svm.def + $(CXX) $(CFLAGS) -LD svm.cpp -Fe$(TARGET)\libsvm -link -DEF:svm.def + +clean: + -erase /Q *.obj $(TARGET)\. + diff --git a/MSC/libsvm-weights-3.20/README b/MSC/libsvm-weights-3.20/README new file mode 100644 index 0000000..3e9a18f --- /dev/null +++ b/MSC/libsvm-weights-3.20/README @@ -0,0 +1,771 @@ +Libsvm is a simple, easy-to-use, and efficient software for SVM +classification and regression. It solves C-SVM classification, nu-SVM +classification, one-class-SVM, epsilon-SVM regression, and nu-SVM +regression. It also provides an automatic model selection tool for +C-SVM classification. This document explains the use of libsvm. + +Libsvm is available at +http://www.csie.ntu.edu.tw/~cjlin/libsvm +Please read the COPYRIGHT file before using libsvm. + +Table of Contents +================= + +- Quick Start +- Installation and Data Format +- `svm-train' Usage +- `svm-predict' Usage +- `svm-scale' Usage +- Tips on Practical Use +- Examples +- Precomputed Kernels +- Library Usage +- Java Version +- Building Windows Binaries +- Additional Tools: Sub-sampling, Parameter Selection, Format checking, etc. +- MATLAB/OCTAVE Interface +- Python Interface +- Additional Information + +Quick Start +=========== + +If you are new to SVM and if the data is not large, please go to +`tools' directory and use easy.py after installation. It does +everything automatic -- from data scaling to parameter selection. + +Usage: easy.py training_file [testing_file] + +More information about parameter selection can be found in +`tools/README.' + +Installation and Data Format +============================ + +On Unix systems, type `make' to build the `svm-train' and `svm-predict' +programs. Run them without arguments to show the usages of them. + +On other systems, consult `Makefile' to build them (e.g., see +'Building Windows binaries' in this file) or use the pre-built +binaries (Windows binaries are in the directory `windows'). + +The format of training and testing data file is: + +