CoolFace
Modelpublic

promforge/sbert-questionclassifier

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes14downloads
Model Card

SetFit with sentence-transformers/all-mpnet-base-v2

This is a SetFit model that can be used for Text Classification. This SetFit model uses sentence-transformers/all-mpnet-base-v2 as the Sentence Transformer embedding model. A LogisticRegression instance is used for classification.

The model has been trained using an efficient few-shot learning technique that involves:

  1. 1.Fine-tuning a Sentence Transformer with contrastive learning.
  2. 2.Training a classification head with features from the fine-tuned Sentence Transformer.

Model Details

Model Description

Model Sources

Model Labels

LabelExamples
1<ul><li>'<p>I\'m looking to use Tensorflow to train a neural network model for classification, and I want to read data from a CSV file, such as the Iris data set.</p>\n\n<p>The <a href="https://www.tensorflow.org/versions/r0.10/tutorials/tflearn/index.html#tf-contrib-learn-quickstart" rel="nofollow noreferrer">Tensorflow documentation</a> shows an example of loading the Iris data and building a prediction model, but the example uses the high-level <code>tf.contrib.learn</code> API. I want to use the low-level Tensorflow API and run gradient descent myself. How would I do that?</p>\n'</li><li>'<p>In the following code, I want dense matrix <code>B</code> to left multiply a sparse matrix <code>A</code>, but I got errors.</p>\n\n<pre><code>import tensorflow as tf\nimport numpy as np\n\nA = tf.sparseplaceholder(tf.float32)\nB = tf.placeholder(tf.float32, shape=(5,5))\nC = tf.matmul(B,A,aissparse=False,bissparse=True)\nsess = tf.InteractiveSession()\nindices = np.array([[3, 2], [1, 2]], dtype=np.int64)\nvalues = np.array([1.0, 2.0], dtype=np.float32)\nshape = np.array([5,5], dtype=np.int64)\nSparseA = tf.SparseTensorValue(indices, values, shape)\nRandB = np.ones((5, 5))\nprint sess.run(C, feeddict={A: SparseA, B: RandB})\n</code></pre>\n\n<p>The error message is as follows:</p>\n\n<pre><code>TypeError: Failed to convert object of type &lt;class \'tensorflow.python.framework.sparsetensor.SparseTensor\'&gt; \nto Tensor. Contents: SparseTensor(indices=Tensor("Placeholder4:0", shape=(?, ?), dtype=int64), values=Tensor("Placeholder3:0", shape=(?,), dtype=float32), denseshape=Tensor("Placeholder2:0", shape=(?,), dtype=int64)). \nConsider casting elements to a supported type.\n</code></pre>\n\n<p>What\'s wrong with my code?</p>\n\n<p>I\'m doing this following the <a href="https://www.tensorflow.org/apidocs/python/tf/matmul" rel="nofollow noreferrer">documentation</a> and it says we should use <code>aissparse</code> to denote whether the first matrix is sparse, and similarly with <code>bissparse</code>. Why is my code wrong?</p>\n\n<p>As is suggested by vijay, I should use <code>C = tf.matmul(B,tf.sparsetensortodense(A),aissparse=False,bissparse=True)</code></p>\n\n<p>I tried this but I met with another error saying:</p>\n\n<pre><code>Caused by op u\'SparseToDense\', defined at:\n File "a.py", line 19, in &lt;module&gt;\n C = tf.matmul(B,tf.sparsetensortodense(A),aissparse=False,bissparse=True)\n File "/home/fengchao.pfc/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/sparseops.py", line 845, in sparsetensortodense\n name=name)\n File "/home/mypath/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/sparseops.py", line 710, in sparsetodense\n name=name)\n File "/home/mypath/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/gensparseops.py", line 1094, in sparsetodense\n validateindices=validateindices, name=name)\n File "/home/mypath/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/opdeflibrary.py", line 767, in applyop\n opdef=opdef)\n File "/home/mypath/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2506, in createop\n originalop=self.defaultoriginalop, opdef=opdef)\n File "/home/mypath/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1269, in _init\n self.traceback = extractstack()\n\nInvalidArgumentError (see above for traceback): indices[1] = [1,2] is out of order\n[Node: SparseToDense = SparseToDense[T=DT_FLOAT, Tindices=DT_INT64, validate_indices=true, _device="/job:localhost/replica:0/task:0/cpu:0"]]\n</code></pre>\n\n<p>Thank you all for helping me!</p>\n'</li><li>"<p>I am using <code>tf.estimator.trainandevaluate</code> and <code>tf.data.Dataset</code> to feed data to the estimator:</p>\n\n<p>Input Data function:</p>\n\n<pre><code> def datafn(datadict, batchsize, mode, numepochs=10):\n dataset = {}\n if mode == tf.estimator.ModeKeys.TRAIN:\n dataset = tf.data.Dataset.fromtensorslices(datadict['traindata'].astype(np.float32))\n dataset = dataset.cache()\n dataset = dataset.shuffle(buffersize= batchsize * 10).repeat(numepochs).batch(batchsize)\n else:\n dataset = tf.data.Dataset.fromtensorslices(datadict['validdata'].astype(np.float32))\n dataset = dataset.cache()\n dataset = dataset.batch(batchsize)\n\n iterator = dataset.makeoneshotiterator()\n nextelement = iterator.getnext()\n\n return nextelement\n</code></pre>\n\n<p>Train Function:</p>\n\n<pre><code>def trainmodel(data):\n tf.logging.setverbosity(tf.logging.INFO)\n config = tf.ConfigProto(allowsoftplacement=True,\n logdeviceplacement=False)\n config.gpuoptions.allowgrowth = True\n runconfig = tf.contrib.learn.RunConfig(\n savecheckpointssteps=10,\n keepcheckpointmax=10,\n sessionconfig=config\n )\n\n traininput = lambda: datafn(data, 100, tf.estimator.ModeKeys.TRAIN, numepochs=1)\n evalinput = lambda: datafn(data, 1000, tf.estimator.ModeKeys.EVAL)\n estimator = tf.estimator.Estimator(modelfn=modelfn, params=hps, config=runconfig)\n trainspec = tf.estimator.TrainSpec(traininput, maxsteps=100)\n evalspec = tf.estimator.EvalSpec(evalinput,\n steps=None,\n throttlesecs = 30)\n\n tf.estimator.trainandevaluate(estimator, trainspec, evalspec)\n</code></pre>\n\n<p>The training goes fine, but when it comes to evaluation I get this error:</p>\n\n<pre><code>OutOfRangeError (see above for traceback): End of sequence \n</code></pre>\n\n<p>If I don't use <code>Dataset.batch</code> on evaluation dataset (by omitting the line <code>dataset[name] = dataset[name].batch(batchsize)</code> in <code>data_fn</code>) I get the same error but after a much longer time.</p>\n\n<p>I can only avoid this error if I don't batch the data and use <code>steps=1</code> for evaluation, but does that perform the evaluation on the whole dataset?</p>\n\n<p>I don't understand what causes this error as the documentation suggests I should be able to evaluate on batches too.</p>\n\n<p>Note: I get the same error when using <code>tf.estimator.evaluate</code> on data batches.</p>\n"</li></ul>
0<ul><li>'<p>I\'m working on a project where I have trained a series of binary classifiers with <strong>Keras</strong>, with <strong>Tensorflow</strong> as the backend engine. The input data I have is a series of images, where each binary classifier must make the prediction on the images, later I save the predictions on a CSV file.</p>\n<p>The problem I have is when I get the predictions from the first series of binary classifiers there isn\'t any warning, but when the 5th or 6th binary classifier calls the method <strong>predict</strong> on the input data I get the following warning:</p>\n<blockquote>\n<p>WARNING:tensorflow:5 out of the last 5 calls to &lt;function\nModel.makepredictfunction..predictfunction at\n0x2b280ff5c158&gt; triggered tf.function retracing. Tracing is expensive\nand the excessive number of tracings could be due to (1) creating\n@tf.function repeatedly in a loop, (2) passing tensors with different\nshapes, (3) passing Python objects instead of tensors. For (1), please\ndefine your @tf.function outside of the loop. For (2), @tf.function\nhas experimentalrelaxshapes=True option that relaxes argument shapes\nthat can avoid unnecessary retracing. For (3), please refer to\n<a href="https://www.tensorflow.org/tutorials/customization/performance#pythonortensorargs" rel="noreferrer">https://www.tensorflow.org/tutorials/customization/performance#pythonortensorargs</a>\nand <a href="https://www.tensorflow.org/apidocs/python/tf/function" rel="noreferrer">https://www.tensorflow.org/apidocs/python/tf/function</a> for more\ndetails.</p>\n</blockquote>\n<p>To answer each point in the parenthesis, here are my answers:</p>\n<ol>\n<li>The <strong>predict</strong> method is called inside a for loop.</li>\n<li>I don\'t pass tensors but a list of <strong>NumPy arrays</strong> of gray scale images, all of them with the same size in width and height. The only thing that can change is the batch size because the list can have only 1 image or more than one.</li>\n<li>As I wrote in point 2, I pass a list of NumPy arrays.</li>\n</ol>\n<p>I have debugged my program and found that this warning always happens when the method predict is called. To summarize the code I have written is the following:</p>\n<pre><code>import cv2 as cv\nimport tensorflow as tf\nfrom tensorflow.keras.models import loadmodel\n# Load the models\nbinaryclassifiers = [loadmodel(path) for path in path2models]\n# Get the images\nimages = [#Load the images with OpenCV]\n# Apply the resizing and reshapes on the images.\nmylist = list()\nfor image in images:\n imagereworked = # Apply the resizing and reshaping on images\n mylist.append(imagereworked)\n\n# Get the prediction from each model\n# This is where I get the warning\npredictions = [model.predict(x=mylist,verbose=0) for model in binaryclassifiers]\n</code></pre>\n<h3>What I have tried</h3>\n<p>I have defined a function as tf.function and putted the code of the predictions inside the tf.function like this</p>\n<pre><code>@tf.function\ndef testing(models, faces):\n return [model.predict(x=faces,verbose=0) for model in models]\n</code></pre>\n<p>But I ended up getting the following error:</p>\n<blockquote>\n<p>RuntimeError: Detected a call to <code>Model.predict</code> inside a\n<code>tf.function</code>. Model.predict is a high-level endpoint that manages\nits own <code>tf.function</code>. Please move the call to <code>Model.predict</code> outside\nof all enclosing <code>tf.function</code>s. Note that you can call a <code>Model</code>\ndirectly on Tensors inside a <code>tf.function</code> like: <code>model(x)</code>.</p>\n</blockquote>\n<p>So calling the method <code>predict</code> is basically already a tf.function. So it\'s useless to define a tf.function when the warning I get it\'s from that method.</p>\n<p>I have also checked those other two questions:</p>\n<ol>\n<li><a href="https://stackoverflow.com/questions/61647404/tensorflow-2-getting-warningtensorflow9-out-of-the-last-9-calls-to-function">Tensorflow 2: Getting &quot;WARNING:tensorflow:9 out of the last 9 calls to triggered tf.function retracing. Tracing is expensive&quot;</a></li>\n<li><a href="https://stackoverflow.com/questions/65563185/loading-multiple-saved-tensorflow-keras-models-for-prediction">Loading multiple saved tensorflow/keras models for prediction</a></li>\n</ol>\n<p>But neither of the two questions answers my question about how to avoid this warning. Plus I have also checked the links in the warning message but I couldn\'t solve my problem.</p>\n<h3>What I want</h3>\n<p>I simply want to avoid this warning. While I\'m still getting the predictions from the models I noticed that the python program takes way too much time on doing predictions for a list of images.</p>\n<h3>What I\'m using</h3>\n<ul>\n<li>Python 3.6.13</li>\n<li>Tensorflow 2.3.0</li>\n</ul>\n<h3>Solution</h3>\n<p>After some tries to suppress the warning from the <code>predict</code> method, I have checked the documentation of Tensorflow and in one of the first tutorials on how to use Tensorflow it is explained that, by default, Tensorflow is executed in eager mode, which is useful for testing and debugging the network models. Since I have already tested my models many times, it was only required to disable the eager mode by writing this single python line of code:</p>\n<p><code>tf.compat.v1.disableeagerexecution()</code></p>\n<p>Now the warning doesn\'t show up anymore.</p>\n'</li><li>'<p>I try to export a Tensorflow model but I can not find the best way to add the exogenous feature to the <code>tf.contrib.timeseries.StructuralEnsembleRegressor.buildrawservinginputreceiverfn</code>. </p>\n\n<p>I use the sample from the Tensorflow contrib: <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/timeseries/examples/knownanomaly.py" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/timeseries/examples/knownanomaly.py</a> and I just try to save the model.</p>\n\n<pre><code># this is the exogenous column \nstringfeature = tf.contrib.layers.sparsecolumnwithkeys(\n columnname="ischangepoint", keys=["no", "yes"])\n\nonehotfeature = tf.contrib.layers.onehotcolumn(\n sparseidcolumn=stringfeature)\n\nestimator = tf.contrib.timeseries.StructuralEnsembleRegressor(\n periodicities=12, \n cyclenumlatentvalues=3,\n numfeatures=1,\n exogenousfeaturecolumns=[onehotfeature],\n exogenousupdatecondition=\n lambda times, features: tf.equal(features["ischangepoint"], "yes"))\n\nreader = tf.contrib.timeseries.CSVReader(\n csvfilename,\n\n columnnames=(tf.contrib.timeseries.TrainEvalFeatures.TIMES,\n tf.contrib.timeseries.TrainEvalFeatures.VALUES,\n "ischangepoint"),\n\n columndtypes=(tf.int64, tf.float32, tf.string),\n\n skipheaderlines=1)\n\ntraininputfn = tf.contrib.timeseries.RandomWindowInputFn(reader, batchsize=4, windowsize=64)\nestimator.train(inputfn=traininputfn, steps=trainsteps)\nevaluationinputfn = tf.contrib.timeseries.WholeDatasetInputFn(reader)\nevaluation = estimator.evaluate(inputfn=evaluationinputfn, steps=1)\n\nexportdirectory = tempfile.mkdtemp()\n\n###################################################### \n# the exogenous column must be provided to the buildrawservinginputreceiverfn. \n# But How ?\n######################################################\n\ninputreceiverfn = estimator.buildrawservinginputreceiverfn()\n# -&gt; error missing \'ischangepoint\' key \n\n#inputreceiverfn = estimator.buildrawservinginputreceiverfn({\'ischangepoint\' : stringfeature}) \n# -&gt; cast exception\n\nexportlocation = estimator.exportsavedmodel(exportdirectory, inputreceiverfn)\n</code></pre>\n\n<p>According to the <a href="https://www.tensorflow.org/apidocs/python/tf/contrib/timeseries/StructuralEnsembleRegressor" rel="nofollow noreferrer">documentation</a>, buildrawservinginputreceiverfn <strong>exogenousfeatures</strong> parameter : <em>A dictionary mapping feature keys to exogenous features (either Numpy arrays or Tensors). Used to determine the shapes of placeholders for these features</em>.</p>\n\n<p>So what is the best way to transform the <em>onehotcolumn</em> or <em>sparsecolumnwithkeys</em> to a <em>Tensor</em> object ?</p>\n'</li><li>"<p>I am currently working on an optical flow project and I come across a strange error. </p>\n\n<p>I have uint16 images stored in bytes in my TFrecords. When I read the TFrecords from my local machine it is giving me uint16 values, but when I deploy the same code and read it from the docker I am getting uint8 values eventhough my dtype is uint16. I mean the uint16 values are getting reduced to uint8 like 32768 --> 128.</p>\n\n<p>What is causing this error?</p>\n\n<p>My local machine has: Tensorflow 1.10.1 and python 3.6\nMy Docker Image has: Tensorflow 1.12.0 and python 3.5</p>\n\n<p>I am working on tensorflow object detection API\nWhile creating the TF records I use:</p>\n\n<pre><code>with tf.gfile.GFile(flows, 'rb') as fid:\n flowimages = fid.read()\n</code></pre>\n\n<p>While reading it back I am using: tf.image.decoderaw</p>\n\n<p>Dataset: KITTI FLOW 2015</p>\n"</li></ul>

Evaluation

Metrics

LabelAccuracyPrecisionRecallF1
all0.850.85350.850.8496

Uses

Direct Use for Inference

First install the SetFit library:

bash
pip install setfit

Then you can load this model and run inference.

python
from setfit import SetFitModel

# Download from the 🤗 Hub
model = SetFitModel.from_pretrained("sharukat/sbert-questionclassifier")
# Run inference
preds = model("<p>In the documentation it seems they focus on how to save and restore tf.keras.models, but i was wondering how do you save and restore models trained customly through some basic iteration loop?</p>

<p>Now that there isnt a graph or a session, how do we save structure defined in a tf function that is customly built without using layer abstractions?</p>
")

<!--

Downstream Use

List how someone could finetune this model on their own dataset. -->

<!--

Out-of-Scope Use

List how the model may foreseeably be misused and address what users ought not to do with the model. -->

<!--

Bias, Risks and Limitations

What are the known or foreseeable issues stemming from this model? You could also flag here known failure cases or weaknesses of the model. -->

<!--

Recommendations

What are recommendations with respect to the foreseeable issues? For example, filtering explicit content. -->

Training Details

Training Set Metrics

Training setMinMedianMax
Word count15330.06673755
LabelTraining Sample Count
0450
1450

Training Hyperparameters

  • batch_size: (16, 2)
  • num_epochs: (1, 16)
  • max_steps: -1
  • sampling_strategy: unique
  • bodylearningrate: (2e-05, 1e-05)
  • headlearningrate: 0.01
  • loss: CosineSimilarityLoss
  • distancemetric: cosinedistance
  • margin: 0.25
  • endtoend: False
  • use_amp: False
  • warmup_proportion: 0.1
  • max_length: 256
  • seed: 42
  • evalmaxsteps: -1
  • loadbestmodelatend: True

Training Results

EpochStepTraining LossValidation Loss
0.000010.2951-
1.0253410.00.2473
  • The bold row denotes the saved checkpoint.

Framework Versions

  • Python: 3.10.13
  • SetFit: 1.0.3
  • Sentence Transformers: 2.5.0
  • Transformers: 4.38.1
  • PyTorch: 2.1.2
  • Datasets: 2.17.1
  • Tokenizers: 0.15.2

Citation

BibTeX

bibtex
@article{https://doi.org/10.48550/arxiv.2209.11055,
    doi = {10.48550/ARXIV.2209.11055},
    url = {https://arxiv.org/abs/2209.11055},
    author = {Tunstall, Lewis and Reimers, Nils and Jo, Unso Eun Seo and Bates, Luke and Korat, Daniel and Wasserblat, Moshe and Pereg, Oren},
    keywords = {Computation and Language (cs.CL), FOS: Computer and information sciences, FOS: Computer and information sciences},
    title = {Efficient Few-Shot Learning Without Prompts},
    publisher = {arXiv},
    year = {2022},
    copyright = {Creative Commons Attribution 4.0 International}
}

<!--

Glossary

Clearly define terms in order to be accessible across audiences. -->

<!--

Model Card Authors

Lists the people who create the model card, providing recognition and accountability for the detailed work that goes into its construction. -->

<!--

Model Card Contact

Provides a way for people who have updates to the Model Card, suggestions, or questions, to contact the Model Card authors. -->