category stringclasses 107
values | title stringlengths 15 179 | question_link stringlengths 59 147 | question_body stringlengths 53 33.8k | answer_html stringlengths 0 28.8k | __index_level_0__ int64 0 1.58k |
|---|---|---|---|---|---|
BERT model | How to download bert models and load in python? | https://stackoverflow.com/questions/67950523/how-to-download-bert-models-and-load-in-python | <p>How to download bert models and load in python?</p>
<pre class="lang-py prettyprint-override"><code>from sentence_transformers import SentenceTransformer
model = SentenceTransformer('bert-base-nli-mean-tokens')
</code></pre>
<p><strong>How to save the pretrained model and load in python?</strong></p>
| 134 | |
BERT model | How to add LSTM layer on top of Huggingface BERT model | https://stackoverflow.com/questions/65763465/how-to-add-lstm-layer-on-top-of-huggingface-bert-model | <p>I am working on a binary classification task and would like to try adding lstm layer on top of the last hidden layer of huggingface BERT model, however, I couldn't reach the last hidden layer. Is it possible to combine BERT with LSTM?</p>
<pre class="lang-py prettyprint-override"><code>tokenizer = BertTokenizer.from... | <p>Indeed it is possible, but you need to implement it yourself. <a href="https://github.com/huggingface/transformers/blob/master/src/transformers/models/bert/modeling_bert.py#L1449" rel="nofollow noreferrer"><code>BertForSequenceClassification</code></a> class is a wrapper for <code>BertModel</code>. It runs the model... | 135 |
BERT model | Slow training of BERT model Hugging face | https://stackoverflow.com/questions/68871329/slow-training-of-bert-model-hugging-face | <p>I am training the binary classfier using BERT model implement in hugging face library</p>
<pre><code>training_args = TrainingArguments(
"deleted_tweets_trainer",
num_train_epochs = 1,
#logging_steps=100,
evaluation_strategy='steps',
remove_unused_colu... | <p>You are currently evaluating every 500 steps and have a training and eval batch size of 8.</p>
<p>Depending on your current memory consumption, you can increase the batch sizes (eval much more as training consumes more memory):</p>
<ul>
<li>per_device_train_batch_size</li>
<li>per_device_eval_batch_size</li>
</ul>
<... | 136 |
BERT model | One single-batch training on Huggingface Bert model "ruins" the model | https://stackoverflow.com/questions/69127607/one-single-batch-training-on-huggingface-bert-model-ruins-the-model | <p>For some reason, I need to do further (2nd-stage) pre-training on Huggingface Bert model, and I find my training outcome is very bad.</p>
<p>After debugging for hours, surprisingly, I find even training one single batch after loading the base model, will cause the model to predict a very bad choice when I ask it to ... | 137 | |
BERT model | How to make BERT model converge? | https://stackoverflow.com/questions/60732018/how-to-make-bert-model-converge | <p>I am trying to use BERT for sentiment analysis but I suspect I am doing something wrong. In my code I am fine tuning bert using <code>bert-for-tf2</code> but after 1 epoch I am getting an accuracy of 42% when a simple GRU model was getting around 73% accuracy. What should I be doing different to effectively use BERT... | <p>I think your learning rate LR (default for adam : 0.001) is too high, leading to <code>catastrophic forgetting</code> . <strong>Refer: How to Fine-Tune BERT for Text Classification?</strong> <a href="https://arxiv.org/pdf/1905.05583.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1905.05583.pdf</a></p>
<p>Ideal... | 138 |
BERT model | What does the embedding elements stand for in huggingFace bert model? | https://stackoverflow.com/questions/75491528/what-does-the-embedding-elements-stand-for-in-huggingface-bert-model | <p>Prior to passing my tokens through encoder in BERT model, I would like to perform some processing on their embeddings. I extracted the embedding weight using:</p>
<pre><code>from transformers import TFBertModel
# Load a pre-trained BERT model
model = TFBertModel.from_pretrained('bert-base-uncased')
# Get the embed... | <p>In bert model, there is a post-processing of the embedding tensor that uses layer normalization followed by dropout ,
<a href="https://github.com/google-research/bert/blob/eedf5716ce1268e56f0a50264a88cafad334ac61/modeling.py#L362" rel="nofollow noreferrer">https://github.com/google-research/bert/blob/eedf5716ce1268e... | 139 |
BERT model | Does BERT model and tokenizer should be trained with same data? | https://stackoverflow.com/questions/71547846/does-bert-model-and-tokenizer-should-be-trained-with-same-data | <p>I want to make BERT model by training with more data (not a fine-tuning, the base model which will be trained is 'bert-base-uncased'). However, do i always need to create own tokenizer for one model? when i use 'bert-base-uncased' tokenizer to train model, it give me some error.</p>
<pre><code>Traceback (most recent... | <p>I recommend you to actually resize the embeedding matrix to match the size of the tokenizer you want to use:</p>
<pre class="lang-py prettyprint-override"><code>model.resize_token_embeddings(len(tokenizer))
</code></pre>
<p>Huggingface docs: <a href="https://huggingface.co/docs/transformers/master/en/main_classes/mo... | 140 |
BERT model | Can't save model in saved_model format when finetune bert model | https://stackoverflow.com/questions/72674057/cant-save-model-in-saved-model-format-when-finetune-bert-model | <p>When training the bert model, the weights are saved well, but the entire model is not saved.</p>
<p>After <code>model.fit</code>,
save model as <code>model.save_weights('bert_xxx.h5')</code> and <code>load_weights</code> works fine,
but since only weights are saved, the model frame must be loaded separately.</p>
<p>... | 141 | |
BERT model | Debugging TensorFlow serving on BERT model | https://stackoverflow.com/questions/60777281/debugging-tensorflow-serving-on-bert-model | <p>I was able to deploy a NLP model using BERT embedding following this example (using TF 1.14.0 on CPU and tensorflow-model-server):
<a href="https://mc.ai/how-to-ship-machine-learning-models-into-production-with-tensorflow-serving-and-kubernetes/" rel="nofollow noreferrer">https://mc.ai/how-to-ship-machine-learning-... | <p>My bad! A Response [200] doesn't mean that it's not working, you can see the results with</p>
<pre><code>predictions = json.loads(json_response.text)['predictions']
predictions
</code></pre>
| 142 |
BERT model | Make sure BERT model does not load pretrained weights? | https://stackoverflow.com/questions/65072694/make-sure-bert-model-does-not-load-pretrained-weights | <p>I want to make sure my BertModel does not loads pre-trained weights. I am using auto class (hugging face) which loads model automatically.</p>
<p>My question is how do I load bert model without pretrained weights?</p>
| <p>Use AutoConfig instead of AutoModel:</p>
<pre><code>from transformers import AutoConfig, AutoModel
config = AutoConfig.from_pretrained('bert-base-uncased')
model = AutoModel.from_config(config)
</code></pre>
<p>this should set up the model without loading the weights.</p>
<p><a href="https://huggingface.co/transfor... | 143 |
BERT model | Persist BERT model on disk as pickle file | https://stackoverflow.com/questions/59881819/persist-bert-model-on-disk-as-pickle-file | <p>I have managed to get the BERT model to work on johnsnowlabs-spark-nlp library. I am able to save the "trained model" on disk as follows.</p>
<h1>Fit Model</h1>
<pre><code>df_bert_trained = bert_pipeline.fit(textRDD)
df_bert=df_bert_trained.transform(textRDD)
</code></pre>
<h1>save model</h1>
<pre><code>df_bert... | <p>In Spark NLP, BERT comes as a pre-trained model. It means it's already a model that was trained, fit, etc. and saved in the right format. </p>
<p>That's being said, there is no reason to fit or save it again. You can, however, save the result of it once you transform your DataFrame to a new DataFrame that has BERT ... | 144 |
BERT model | How to Fine-tune HuggingFace BERT model for Text Classification | https://stackoverflow.com/questions/69025750/how-to-fine-tune-huggingface-bert-model-for-text-classification | <p>Is there a <em>Step by step explanation</em> on how to <strong>Fine-tune HuggingFace BERT</strong> model for text classification?</p>
| <h1>Fine Tuning Approach</h1>
<p>There are multiple approaches to fine-tune BERT for the target tasks.</p>
<ol>
<li>Further Pre-training the base BERT model</li>
<li>Custom classification layer(s) on top of the base BERT model being trainable</li>
<li>Custom classification layer(s) on top of the base BERT model being ... | 145 |
BERT model | Training the BERT model with pytorch | https://stackoverflow.com/questions/72753200/training-the-bert-model-with-pytorch | <p>I am unable to figure out why my BERT model dosen't get pas the training command. I am using pytorch-lightning. I am running the code on AWS EC2(p3.2xLarge) and it does show me the available GPU but I can't really figure out the device side error. Could someone please guide me towards a direction? I really appreciat... | 146 | |
BERT model | bert model as model.ckpt-1400000 | https://stackoverflow.com/questions/63484093/bert-model-as-model-ckpt-1400000 | <p>It is the first time that I want to use BERT. I'm trying to execute this code.</p>
<pre><code>from keras_bert import load_trained_model_from_checkpoint
config_path = './model/bert_config.json'
checkpoint_path = './model/model.ckpt-1400000'
bert = load_trained_model_from_checkpoint(config_path, checkpoint_path)
bert.... | 147 | |
BERT model | How many neurons (units) are there in the BERT model? | https://stackoverflow.com/questions/75844264/how-many-neurons-units-are-there-in-the-bert-model | <p>How to estimate the number of neurons (units) in the BERT model?
<strong>Note</strong> this is different from the number of model parameters.</p>
| <p>Depending on which field you come from the "neurons" definition might differ.</p>
<p>In general, people in computer science conflates <code>num_neurons = num_parameters</code>. But this might not be the case if one is interested in more neurological/biological perspective.</p>
<h3>Q: Why do computer scient... | 148 |
BERT model | Unable to import BERT model with all packages | https://stackoverflow.com/questions/73359430/unable-to-import-bert-model-with-all-packages | <p>I am trying to learn NLP using BERT. While trying to import bert model and tokenizer in colab. I am facing the below error.</p>
<pre><code>ImportError: cannot import name '_LazyModule' from 'transformers.file_utils' (/usr/local/lib/python3.7/dist-packages/transformers/file_utils.py)
</code></pre>
<p>Here is my code<... | <p>Based on these links <a href="https://github.com/Lightning-AI/lightning-flash/issues/630#issuecomment-891031269" rel="nofollow noreferrer">1</a>, <a href="https://stackoverflow.com/questions/71901851/importerror-cannot-import-name-lazymodule-from-transformers-utils">2</a></p>
<p>This should help -</p>
<pre><code>pip... | 149 |
BERT model | ValueError when pre-training BERT model using Trainer API | https://stackoverflow.com/questions/70263251/valueerror-when-pre-training-bert-model-using-trainer-api | <p>I'm trying to fine-tune/pre-train an existing BERT model for sentiment analysis by using Trainer API in <code>transformers</code> library. My training dataset looks like this:</p>
<pre><code>Text Sentiment
This was good place 1
This was bad place 0
</cod... | <p>There are several points here to which you need to pay attention in order to have your code working.</p>
<p>First of all, you are working on a sequence classification task, specifically a binary classification, so you need to instantiate your model accordingly:</p>
<pre><code># replace this:
# model = transformers.B... | 150 |
BERT model | CNN model and bert with text | https://stackoverflow.com/questions/71309113/cnn-model-and-bert-with-text | <p>I got error in linear function</p>
<pre><code>class MixModel(nn.Module):
def __init__(self,pre_trained='bert-base-uncased'):
super().__init__()
self.bert = AutoModel.from_pretrained('distilbert-base-uncased')
self.hidden_size = self.bert.config.hidden_size
self.conv = nn.... | <pre><code>class MixModel(nn.Module):
def __init__(self,pre_trained='bert-base-uncased'):
super().__init__()
self.bert = AutoModel.from_pretrained('distilbert-base-uncased')
self.hidden_size = self.bert.config.hidden_size
self.conv = nn.Conv1d(in_channels=768, out_channels=2... | 151 |
BERT model | Fine-tuning a BERT model without answers | https://stackoverflow.com/questions/77783666/fine-tuning-a-bert-model-without-answers | <p>I come here after I have been googling during many hours for to know if it's was possible to make a fine-tune <code>BERT</code> Question Answering with only question and context ? I am beginner with BERT model so I don't know the deep mechanism that it have even after many search. Thanks you for your answer</p>
| 152 | |
BERT model | pre-trained BERT model learning wrong way | https://stackoverflow.com/questions/69757233/pre-trained-bert-model-learning-wrong-way | <p>I have trained my pre-trained BERT model from the Hugging Face library on the <code>Jigsaw Toxic Comment Classification dataset</code> to detect hateful comments. However, when I try to do infer with the positive sentences, it is giving me wrong results.</p>
<p>For example, if I provide the sentence: <code>You are a... | 153 | |
BERT model | How to reuse the BERT model using tensorflow.contrib | https://stackoverflow.com/questions/58115439/how-to-reuse-the-bert-model-using-tensorflow-contrib | <p>I have tried below codes for reusing the saved BERT model.</p>
<pre><code>def serving_input_receiver_fn():
feature_spec = {
"input_ids" : tf.FixedLenFeature([MAX_SEQ_LENGTH], tf.int64),
"input_mask" : tf.FixedLenFeature([MAX_SEQ_LENGTH], tf.int64),
"segment_ids" : tf.FixedLenFeature([MAX_SEQ_LENGTH], ... | 154 | |
BERT model | Adding new labels to an already trained BERT model | https://stackoverflow.com/questions/62337074/adding-new-labels-to-an-already-trained-bert-model | <p>I am using BERT for Named Entity Recognition. Initially I had only 18 labels, and I trained the model using the 18 labels and saved the model. Now I added 2 more new labels, and when I updated the previously saved model I am getting the following error:</p>
<pre class="lang-sh prettyprint-override"><code>C:/w/1/s/w... | 155 | |
BERT model | Bert model not learning using JAX. Results don't change | https://stackoverflow.com/questions/79383687/bert-model-not-learning-using-jax-results-dont-change | <p>I am training a BERT model on spam classification using JAX on TPUs. My model hasn't been learning nor its results have changed.</p>
<pre><code>Epoch 0: Train Loss = 2.7961559295654297: Train Accuracy: 0.30608975887298584 Eval Loss = 3.6600053310394287: Eval Accuracy = 0.0
Epoch 1: Train Loss = 2.7961559295654297: T... | 156 | |
BERT model | How to convert bert model output to json? | https://stackoverflow.com/questions/73830782/how-to-convert-bert-model-output-to-json | <p>I have fine-tuned a Bert model and testing my output from different layers. I tested this in sagemaker , with my own custom script (see below) and the output i get is of BaseModelOutputWithPoolingAndCrossAttentions class. How can i convert the output of this , specially the tensor values from the last_hidden_state t... | <p>Grab the output, access <code>last_hidden_state</code>, and convert it to a list.</p>
<pre class="lang-py prettyprint-override"><code>import json
output = predict_fn()
tensor = output.last_hidden_state
tensor_as_list = tensor.tolist()
json_str = json.dumps(tensor_as_list)
</code></pre>
| 157 |
BERT model | Cannot load German BERT model in spaCy | https://stackoverflow.com/questions/61899118/cannot-load-german-bert-model-in-spacy | <p>Here is my problem: I am working on the German text classification project. I use spacy for that and decided to fine-tune its pretrained BERT model to get better results. However, when I try to load it to the code, it shows me errors.</p>
<p>Here is what I've done:</p>
<ol>
<li>Installed spacy-transformers: <code>... | <p>It's probably a problem with your installation of <code>torch</code>. Start in a clean virtual environment and install <code>torch</code> using the instructions here with CUDA as None: <a href="https://pytorch.org/get-started/locally/" rel="nofollow noreferrer">https://pytorch.org/get-started/locally/</a>. Then inst... | 158 |
BERT model | i have an error while training BERT model | https://stackoverflow.com/questions/62991456/i-have-an-error-while-training-bert-model | <p>I'm trying to train my model using GPUs.</p>
<p>When I execute it I get this error below:</p>
<pre><code>File "main.py", line 95, in train loss.backward()
File "/opt/conda/lib/python3.7/site-packages/torch/tensor.py", line 198, in backward torch.autograd.backward(self, gradient, retain_graph, cre... | <p>What is your <code>device.inputs</code> in the following code.</p>
<pre><code>positions = torch.arange(inputs.size(1), device=inputs.device, dtype=inputs.dtype).expand(inputs.size(0), inputs.size(1)).contiguous() + 1
</code></pre>
<p>Can you set specific gpu and try:</p>
<pre><code>torch.cuda.set_device(device_num)
... | 159 |
BERT model | Assigning weights during testing the bert model | https://stackoverflow.com/questions/65925640/assigning-weights-during-testing-the-bert-model | <p>I have a basic conceptual doubt. When i train a bert model on sentence say:</p>
<pre><code>Train: "went to get loan from bank"
Test :"received education loan from bank"
</code></pre>
<p>How does the test sentence assigns the weights for each token because i however dont pass exact sentence for t... | <p>The vector representation of a token (keep in mind that token != word) is stored in an embedding layer. When we load the 'bert-base-uncased' model, we can see that it "knows" 30522 tokens and that the vector representation of each token consists of 768 elements:</p>
<pre class="lang-py prettyprint-override... | 160 |
BERT model | How to solve Attribute Error after running BERT model | https://stackoverflow.com/questions/67046637/how-to-solve-attribute-error-after-running-bert-model | <p>Receiving an error once running the BERT model. Up till this point the code runs successfully. Error I receive is AttributeError: 'str' object has no attribute 'shape'. The previous step before the code was creating a custom data generator. Using this the model was created. To provide context the model I used is fou... | <p>The input to the model must not be a string. It should be a numpy array or a tensor. You should encode your string, converting the characters to a numpy array.</p>
<p>From <a href="https://keras.io/examples/nlp/semantic_similarity_with_bert/" rel="nofollow noreferrer">https://keras.io/examples/nlp/semantic_similarit... | 161 |
BERT model | Weights of pre-trained BERT model not initialized | https://stackoverflow.com/questions/66561880/weights-of-pre-trained-bert-model-not-initialized | <p>I am using the <a href="https://github.com/pair-code/lit" rel="nofollow noreferrer">Language Interpretability Toolkit</a> (LIT) to load and analyze a BERT model that I pre-trained on an NER task.</p>
<p>However, when I'm starting the LIT script with the path to my pre-trained model passed to it, it fails to initiali... | <p>This actually seems to be expected behaviour. In the <a href="https://huggingface.co/docs/transformers/training" rel="nofollow noreferrer">documentation of the GPT models</a> the HuggingFace team writes:</p>
<blockquote>
<p>This will issue a warning about some of the pretrained weights not being used and some weight... | 162 |
BERT model | Error with using BERT model from Tensorflow | https://stackoverflow.com/questions/65298391/error-with-using-bert-model-from-tensorflow | <p>I have tried to follow Tensorflow instructions to use BERT model: (<a href="https://www.tensorflow.org/tutorials/text/classify_text_with_bert" rel="noreferrer">https://www.tensorflow.org/tutorials/text/classify_text_with_bert</a>)</p>
<p>However, when I run these lines:</p>
<pre><code>text_test = ['this is such an a... | <p>I found this bug report on GitHub: <a href="https://github.com/tensorflow/text/issues/476" rel="nofollow noreferrer">https://github.com/tensorflow/text/issues/476</a></p>
<p>It appears that they've acknowledged it as a bug and are trying to fix it.</p>
| 163 |
BERT model | How to use the outputs of bert model? | https://stackoverflow.com/questions/63673511/how-to-use-the-outputs-of-bert-model | <p>The bert model gives us the two outputs, one gives us the [batch,maxlen,hiddenstates] and other one is [batch, hidden States of cls token]. But I did not understood when to use the specific output. Can anyone tell me for which task which output should be used??</p>
| <p>The output is usually <code>[batch, maxlen, hidden_state]</code>, it can be narrowed down to <code>[batch, 1, hidden_state]</code> for <code>[CLS]</code> token, as the <code>[CLS]</code> token is 1st token in the sequence. Here , <code>[batch, 1, hidden_state]</code> can be equivalently considered as <code>[batch, ... | 164 |
BERT model | Spacy's BERT model doesn't learn | https://stackoverflow.com/questions/61943409/spacys-bert-model-doesnt-learn | <p>I've been trying to use <code>spaCy</code>'s pretrained BERT model <code>de_trf_bertbasecased_lg</code> to increase accuracy in my classification project. I used to build a model from scratch using <code>de_core_news_sm</code> and everything worked fine: I had an accuracy around 70%. But now I am using BERT pretrain... | <p>Received an answer to my question on <a href="https://github.com/explosion/spacy-transformers/issues/180" rel="nofollow noreferrer">GitHub</a> and it looks like there must be some optimizer parameters specified, just like in <a href="https://github.com/explosion/spacy-transformers/blob/v0.6.x/examples/train_textcat.... | 165 |
BERT model | Issues calculating accuracy for custom BERT model | https://stackoverflow.com/questions/67420868/issues-calculating-accuracy-for-custom-bert-model | <p>I'm having some issues trying to calculate the accuracy of a custom BERT model which also uses the pretrained model from Huggingface. This is the code that I have :</p>
<pre><code>import numpy as np
import pandas as pd
from sklearn import metrics, linear_model
import torch
from torch.utils.data import Dataset, DataL... | 166 | |
BERT model | How to use a different pre-trained BERT model with bert_score | https://stackoverflow.com/questions/76306997/how-to-use-a-different-pre-trained-bert-model-with-bert-score | <p>I want you to use different pretrain bert model embeddings for the bert score. How can I do that?
P, R, F1 = score(cand, ref, lang="bn", model_type="distilbert-base-uncased", verbose=True)
In model_type if use my pretain model then it gives a keyError.</p>
| <p>You need to pass num_layers configuration parameter (if it is not given, the library will search for predefined defaults in utils.py file ).</p>
<pre><code>bert_score.score(['Hello world'], ['Whats up'], model_type='/home/user/bart_large', num_layers=10)
</code></pre>
| 167 |
BERT model | How to get intermediate layers' output of pre-trained BERT model in HuggingFace Transformers library? | https://stackoverflow.com/questions/61465103/how-to-get-intermediate-layers-output-of-pre-trained-bert-model-in-huggingface | <p>(I'm following <a href="https://mccormickml.com/2019/05/14/BERT-word-embeddings-tutorial/" rel="noreferrer">this</a> pytorch tutorial about BERT word embeddings, and in the tutorial the author is access the intermediate layers of the BERT model.)</p>
<p>What I want is to access the last, lets say, 4 last layers of ... | <p>The third element of the BERT model's output is a tuple which consists of output of embedding layer as well as the intermediate layers hidden states. From <a href="https://huggingface.co/transformers/model_doc/bert.html#tfbertmodel" rel="noreferrer">documentation</a>:</p>
<blockquote>
<p><strong>hidden_states (<c... | 168 |
BERT model | Why is BERT model with pytorch native approach not learning? | https://stackoverflow.com/questions/68596995/why-is-bert-model-with-pytorch-native-approach-not-learning | <p>My custom BERT model's architecture:</p>
<pre><code>class BertArticleClassifier(nn.Module):
def __init__(self, n_classes, freeze_bert_weights=False):
super(BertArticleClassifier, self).__init__()
self.bert = AutoModel.from_pretrained('bert-base-uncased')
if freeze_bert_weights:
... | 169 | |
BERT model | BERT model does not learn new task | https://stackoverflow.com/questions/56769943/bert-model-does-not-learn-new-task | <p>I am trying to fine-tune a pretrained BERT model on amazon-review dataset. For that I extended the <code>run_classifier</code> file by the following processor:</p>
<pre><code>class AmazonProcessor(DataProcessor):
"""Processor for the Amazon data set."""
def get_train_examples(self, data_dir):
"""See base c... | 170 | |
BERT model | Using Pretrained BERT model to add additional words that are not recognized by the model | https://stackoverflow.com/questions/64816669/using-pretrained-bert-model-to-add-additional-words-that-are-not-recognized-by-t | <p>I want some help regarding adding additional words in the existing BERT model. I have two quires kindly guide me:</p>
<p>I am working on NER task for a domain:</p>
<p>There are few words (not sure the exact numbers) that BERT recognized as [UNK], but those entities are required for the model to recognize. The pretra... | <p>BERT works well because it is pre-trained on a very large textual dataset of 3.3 billion words. Training BERT from skratch is resource-demanding and does not pay of in most reasonable use cases.</p>
<p>BERT uses the wordpiece algorithm for input segmentation. This shoudl in theory ensure that there no out-of-vocabul... | 171 |
BERT model | Try to run an NLP model with an Electra instead of a BERT model | https://stackoverflow.com/questions/72680932/try-to-run-an-nlp-model-with-an-electra-instead-of-a-bert-model | <p>I want to run the <a href="https://github.com/vdobrovolskii/wl-coref" rel="nofollow noreferrer">wl-coref</a> model with an Electra model instead of a Bert model. However, I get an error message with the Electra model and can't find a hint in the Huggingface documentation on how to fix it.</p>
<p>I try different BERT... | <p>Just remove the underscore <code>_</code>. <a href="https://huggingface.co/docs/transformers/model_doc/electra#transformers.ElectraModel.forward" rel="nofollow noreferrer">ELECTRA</a> does not return a pooling output like <a href="https://huggingface.co/docs/transformers/model_doc/bert#transformers.BertModel.forward... | 172 |
BERT model | Predicting Sentiment of Raw Text using Trained BERT Model, Hugging Face | https://stackoverflow.com/questions/69820318/predicting-sentiment-of-raw-text-using-trained-bert-model-hugging-face | <p>I'm predicting sentiment analysis of Tweets with positive, negative, and neutral classes. I've trained a BERT model using Hugging Face. Now I'd like to make predictions on a dataframe of unlabeled Twitter text and I'm having difficulty.</p>
<p>I've followed the following tutorial (<a href="https://curiousily.com/pos... | <p>You can use the same code to predict texts from the dataframe column.</p>
<pre><code>model = ...
tokenizer = ...
def predict(review_text):
encoded_review = tokenizer.encode_plus(
review_text,
max_length=MAX_LEN,
add_special_tokens=True,
return_token_type_ids=False,
pad_to_max_length=True... | 173 |
BERT model | Retraining existing base BERT model with additional data | https://stackoverflow.com/questions/62948266/retraining-existing-base-bert-model-with-additional-data | <p>I have generated new Base BERT model(<strong>dataset1_model_cased_L-12_H-768_A-12</strong>) using <strong>cased_L-12_H-768_A-12</strong> as trained multi label classification from <a href="https://github.com/dmis-lab/biobert/blob/master/run_classifier.py" rel="nofollow noreferrer">biobert-run_classifier</a></p>
<p>I... | <p>Tensorflow Hub is a platform for sharing pre-trained model pieces or whole models, and an API to facilitate this sharing. In TF 1.x, this API was a stand-alone API and in TF 2.x this API (SavedModel: <a href="https://www.tensorflow.org/guide/saved_model" rel="nofollow noreferrer">https://www.tensorflow.org/guide/sav... | 174 |
BERT model | TypeError: dropout(): argument 'input' (position 1) must be Tensor, not str Bert Model | https://stackoverflow.com/questions/72442319/typeerror-dropout-argument-input-position-1-must-be-tensor-not-str-bert | <p>Hi I encounter this error when I was training my Bert Model for sentiment analysis, where my classes have 3 outcomes and my input data is text.</p>
<p>So I got the above error when I am training the model. I have searched some of the guides and tried to set this parameter to my bert model <code>bert_model = BertMode... | 175 | |
BERT model | How do I retrain BERT model with new data | https://stackoverflow.com/questions/72040423/how-do-i-retrain-bert-model-with-new-data | <p>I have already trained a bert model and saved it in the .pb format and I want to retrain the model with new datasets that i custom made, so in order to not to lose the previous training and such, how do I train the model with the new data so the model could update it self
any approaches?
this is my training code dow... | 176 | |
BERT model | Retrieve the "relevant tokens" with a BERT model (already fine-tuned) | https://stackoverflow.com/questions/66860788/retrieve-the-relevant-tokens-with-a-bert-model-already-fine-tuned | <p>I already fine-tuned a BERT model ( with the huggingface library) for a classification task to predict a post category in two types (1 and 0, for example). But, I would need to retrieve the "relevant tokens" for the documents that are predicted as category 1 (for example). I know that I can use the traditi... | <p>With transformer models, you can perform some explainability analysis, which is probably what you want. I would recommend looking at the transformer section of <a href="https://github.com/slundberg/shap#natural-language-example-transformers" rel="nofollow noreferrer">SHAP</a>. You just have to wrap your model in the... | 177 |
BERT model | Train BERT model from scratch on a different language | https://stackoverflow.com/questions/67957446/train-bert-model-from-scratch-on-a-different-language | <p>First i create tokenizer as follow</p>
<pre><code>from tokenizers import Tokenizer
from tokenizers.models import BPE,WordPiece
tokenizer = Tokenizer(WordPiece(unk_token="[UNK]"))
from tokenizers.trainers import BpeTrainer,WordPieceTrainer
trainer = WordPieceTrainer(vocab_size=5000,min_frequency=3,
... | 178 | |
BERT model | Huggingface pre trained bert model is not working | https://stackoverflow.com/questions/64365122/huggingface-pre-trained-bert-model-is-not-working | <p>I have pre-trained a bert model with custom corpus then got vocab file, checkpoints, model.bin, tfrecords, etc.</p>
<p>Then I loaded the model as below :</p>
<pre class="lang-py prettyprint-override"><code># Load pre-trained model (weights)
model = BertModel.from_pretrained('/content/drive/My Drive/Anirban_test_pyto... | 179 | |
BERT model | tensor type attributes in bert model returned as string | https://stackoverflow.com/questions/65461593/tensor-type-attributes-in-bert-model-returned-as-string | <p>I am new to nlp and i want to build a bert model for sentiment Analysis so i am following this tuto
<a href="https://curiousily.com/posts/sentiment-analysis-with-bert-and-hugging-face-using-pytorch-and-python/" rel="nofollow noreferrer">https://curiousily.com/posts/sentiment-analysis-with-bert-and-hugging-face-using... | <p>it seems there was A couple of changes were introduced when the switch from version 3 to version 4 was done in hugging face and can be solved like below</p>
<pre><code>bert_model = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME, return_dict=False)
</code></pre>
| 180 |
BERT model | I get error while downloading BERT models for summarization | https://stackoverflow.com/questions/63832094/i-get-error-while-downloading-bert-models-for-summarization | <p>I'm a novice in writing neural networks. I have just started using BERT models, while running BERT for text summarization using the examples in <a href="https://pypi.org/project/bert-extractive-summarizer/" rel="nofollow noreferrer">bert extractive summarizer</a> I get the following error with the pretrained model g... | 181 | |
BERT model | BERT model : "enable_padding() got an unexpected keyword argument 'max_length'" | https://stackoverflow.com/questions/66743649/bert-model-enable-padding-got-an-unexpected-keyword-argument-max-length | <p>I am trying to implement the BERT model architecture using Hugging Face and KERAS. I am learning this from the Kaggle (<a href="https://www.kaggle.com/tanulsingh077/deep-learning-for-nlp-zero-to-transformers-bert" rel="noreferrer">link</a>) and try to understand it. When I tokenized my data, I face some problems and... | <p>The tokenizer used here is not the regular tokenizer, but the fast tokenizer provided by an older version of the Huggingface <code>tokenizer</code> library.</p>
<p>If you wish to create the fast tokenizer using the older version of huggingface <code>transformers</code> from the notebook, you can do this:</p>
<pre cl... | 182 |
BERT model | Index out of Range in Self - BERT Model Tuning Pytorch | https://stackoverflow.com/questions/75622232/index-out-of-range-in-self-bert-model-tuning-pytorch | <p>I am working on training the BERT Model for Pytorch. I'm quite new to Pytorch as well. My code as replicated from: <a href="https://towardsdatascience.com/text-classification-with-bert-in-pytorch-887965e5820f" rel="nofollow noreferrer">https://towardsdatascience.com/text-classification-with-bert-in-pytorch-887965e58... | 183 | |
BERT model | How can I integrate BERT model in my notebook (Python)? | https://stackoverflow.com/questions/66356324/how-can-i-integrate-bert-model-in-my-notebook-python | <p>I am doing text classification with keras model (sequential). Now, what can I do to improve the model performance (the accuracy, the val accuracy, the prediction, etc).
This is my model architecture:</p>
<pre><code>from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.utils.vis_utils impor... | 184 | |
BERT model | BERT Model Evaluation Measure in terms of Syntax Correctness and Semantic Coherence | https://stackoverflow.com/questions/58840538/bert-model-evaluation-measure-in-terms-of-syntax-correctness-and-semantic-cohere | <p>For example I have an original sentence. The word <strong>barking</strong> corresponds to the word that is missing.</p>
<pre><code>Original Sentence : The dog is barking.
Incomplete Sentence : The dog is ___________.
</code></pre>
<p>For example, using the BERT model, it predicts the word crying instead of the wo... | <p>For <em>syntax</em>, you can use for instance <a href="https://github.com/delph-in/erg" rel="nofollow noreferrer">English Resource Grammar</a> to decide if a sentence is grammatical. It is the biggest manually curated description of English grammar, you can try an <a href="http://erg.delph-in.net/logon" rel="nofollo... | 185 |
BERT model | "gcloud ai endpoints deploy-model" fails with "Model server exited unexpectedly" (BERT model deployment on Vertex AI) | https://stackoverflow.com/questions/79502332/gcloud-ai-endpoints-deploy-model-fails-with-model-server-exited-unexpectedly | <p>I'm encountering persistent issues deploying a custom container to Vertex AI using gcloud ai endpoints deploy-model. I'm trying to deploy a BERT model packaged in a Docker image, but I'm consistently facing errors despite providing the correct Artifact Registry image path.</p>
<p>Here's a breakdown of my setup:</p>
... | 186 | |
BERT model | Bert model train don't want to stop | https://stackoverflow.com/questions/65073823/bert-model-train-dont-want-to-stop | <p>I am using this code to train Bert for Turkish language model classification with 2 labels. But when I run the following code:</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.read_excel (r'preparedDataNoId.xlsx')
df = df.sample(frac = 1)
from sklearn.model_selection import train_test_split
train_df,... | <p>As the error suggests you should wrap your code with an <code>if __name__ == '__main__':</code></p>
<p>So your code would be:</p>
<pre><code>import numpy as np
import pandas as pd
if __name__ == '__main__':
df = pd.read_excel(r'preparedDataNoId.xlsx')
df = df.sample(frac=1)
from sklearn.model_selection... | 187 |
BERT model | BERT model bug encountered during training | https://stackoverflow.com/questions/67360987/bert-model-bug-encountered-during-training | <p>So, I made a custom dataset consisting of reviews form several E-learning sites. What I am trying to do is build a model that can recognize emotions based on text and for training I am using the dataset I've made via scraping. While working on BERT, I encountered this error</p>
<p><code>normalize() argument 2 must b... | <p>It sounds like you may have a float value in your <code>data['Text']</code> column somehow.</p>
<p>You can try something like this to shed more light on what's happening:</p>
<pre class="lang-py prettyprint-override"><code>for i, s in enumerate(data['Text']):
if not isinstance(s, str): print('Text in row %s is ... | 188 |
BERT model | Weird behaviour when finetuning Huggingface Bert model with Tensorflow | https://stackoverflow.com/questions/72139450/weird-behaviour-when-finetuning-huggingface-bert-model-with-tensorflow | <p>I am trying to fine tune a Huggingface Bert model using Tensorflow (on ColabPro GPU enabled) for tweets sentiment analysis. I followed step by step the guide on the Huggingface website, but I am experiencing a weird training time. This happens with all the Bert models I tried.
I have two datasets of different sizes ... | <p>For your first question i haven't used the bert model before so i can't say.</p>
<p>For your second question well from what I understand, steps per epoch is the number of sample batches that will be used to fit the model during 1 epoch.</p>
<p>So let's say your number of epochs was 2 instead of 1 and you set your st... | 189 |
BERT model | Fine-tuning BERT sentence transformer model | https://stackoverflow.com/questions/69562624/fine-tuning-bert-sentence-transformer-model | <p>I am using a pre-trained BERT sentence transformer model, as described here <a href="https://www.sbert.net/docs/training/overview.html" rel="noreferrer">https://www.sbert.net/docs/training/overview.html</a> , to get embeddings for sentences.</p>
<p>I want to fine-tune these pre-trained embeddings, and I am following... | <p>That actually depend on your requirement.
If you have a lot of computational resources and you want to get a perfect sentence representation then you should finetune all the layers.(Which was done in the original sentence bert model)</p>
<p>But if you are a student and want to create an almost good sentence represen... | 190 |
BERT model | FastAPI return BERT model result and metrics | https://stackoverflow.com/questions/65885841/fastapi-return-bert-model-result-and-metrics | <p>I have sentiment analysis model using BERT and I want to get the result from predicting text via FastAPI but it always give negative answer (I think it is because the prediction didn't give prediction result).</p>
<p>This is my code:</p>
<pre><code>import uvicorn
from fastapi import FastAPI
import joblib
# models
s... | <p>You are using a <a href="https://fastapi.tiangolo.com/tutorial/path-params/" rel="nofollow noreferrer">Path parameter</a> construction. Meaning that to call your API endpoint, you need to do such a call: <code>http://localhost:8000/predict/some_text</code>. The issue is that <code>some_text</code> contains spaces in... | 191 |
BERT model | RuntimeError, working on IA tryna use a pre-trained BERT model | https://stackoverflow.com/questions/60561504/runtimeerror-working-on-ia-tryna-use-a-pre-trained-bert-model | <p>Hi here is a part of my code to use a pre-trained bert model for classification: </p>
<pre><code> model = BertForSequenceClassification.from_pretrained(
"bert-base-uncased", # Use the 12-layer BERT model, with an uncased vocab.
num_labels = 2, # The number of output labels--2 for binary classification.... | <p>Finally succeed using .to(torch.int64)</p>
| 192 |
BERT model | How to use pretrained checkpoints of BERT model on semantic text similarity task? | https://stackoverflow.com/questions/57461607/how-to-use-pretrained-checkpoints-of-bert-model-on-semantic-text-similarity-task | <p>I am unaware to use the derived checkpoints from pre-trained BERT model for the task of semantic text similarity.</p>
<p>I have run a pre-trained BERT model with some domain of corpora from scratch. I have got the checkpoints and graph.pbtxt file from the code below. But I am unaware on how to use those files for e... | 193 | |
BERT model | BERT model loss function from one hot encoded labels | https://stackoverflow.com/questions/68104425/bert-model-loss-function-from-one-hot-encoded-labels | <p>For the line: loss = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels)
I have labels hot encoded such that it is a tensor of 32x17, since the batch size is 32 and there are 17 classes for the text categories. However, BERT model only takes for the label with a single dimension vec... | <p>As stated in the comment, Bert for sequence classification expects the target tensor as a <code>[batch]</code> sized tensors with values spanning the range <em>[0, num_labels)</em>. A one-hot encoded tensor can be converted by <code>argmax</code>ing it over the label dim, i.e. <code>labels=b_labels.argmax(dim=1)</co... | 194 |
BERT model | How to load a fine tuned pytorch huggingface bert model from a checkpoint file? | https://stackoverflow.com/questions/71561761/how-to-load-a-fine-tuned-pytorch-huggingface-bert-model-from-a-checkpoint-file | <p>I had fine tuned a bert model in pytorch and saved its checkpoints via <code>torch.save(model.state_dict(), 'model.pt')</code></p>
<p>Now When I want to reload the model, I have to explain whole network again and reload the weights and then push to the device.</p>
<p>Can anyone tell me how can I save the bert model ... | <p>Just save your model using model.save_pretrained, here is an example:</p>
<pre><code>model.save_pretrained("<path_to_dummy_folder>")
</code></pre>
<p>You can download the model from colab, save it on your gdrive or at any other location of your choice. While doing inference, you can just give path to... | 195 |
BERT model | Can't get 'bert' model to run using ktrain and pandas dataframe | https://stackoverflow.com/questions/73791130/cant-get-bert-model-to-run-using-ktrain-and-pandas-dataframe | <p>I try to work with ktrain to finetune bert model. I'm using pandas dataframe named train_df to store my data.</p>
<p><code>x_train, x_val, y_train, y_val = train_test_split(train_df['text'], train_df['target'], shuffle=True, test_size = 0.2, random_state=random_seed, stratify=train_df['target'])</code></p>
<br>
I'm ... | <p>I found solution and now it is working correctly.</p>
<pre><code>(x_train_bert, y_train_bert), (x_val_bert, y_val_bert), preproc = text.texts_from_array(x_train=x_train.tolist(), y_train=y_train.tolist(), x_test = x_val.tolist(), y_test=y_val.tolist(),class_names= ["0", "1"],preprocess_mode='bert... | 196 |
BERT model | How to Extract Features from Text based on Fine-Tuned BERT Model | https://stackoverflow.com/questions/58061775/how-to-extract-features-from-text-based-on-fine-tuned-bert-model | <p>I am trying to make a binary predictor on some data which has one columns with text and some additional columns with numerical values. My first solution was to use word2vec on the text to extract 30 features and use them with the other values in a Random Forest. It produces good result. I am interested in improving ... | <p>I am dealing with this problem too. As far I know, you must fine-tune the BERT language model; according to <a href="https://github.com/google-research/bert/issues/145" rel="nofollow noreferrer">this issue</a>, <a href="https://github.com/google-research/bert#pre-training-with-bert" rel="nofollow noreferrer">masked ... | 197 |
BERT model | How to Answer Subjective/descriptive types of lQuestions using BERT Model? | https://stackoverflow.com/questions/74654341/how-to-answer-subjective-descriptive-types-of-lquestions-using-bert-model | <p>I am trying to implement BERT Model for Question Answering tasks, but Its a little different from the existing Q&A models,
The Model will be given some text(3-4 pages) and will be asked questions based on the text, and the expected answer may be asked in short or descriptive subjective type</p>
<p>I tried to im... | <p>Try longformer which can have input length 0f 4096 tokens, or even 16384 tokens with gradient checkpointing. See details in <a href="https://github.com/allenai/longformer" rel="nofollow noreferrer">https://github.com/allenai/longformer</a>. Or on huggingface model hub <a href="https://huggingface.co/docs/transformer... | 198 |
BERT model | Fine tuning BERT model for text generation (crossword solver) | https://stackoverflow.com/questions/78636736/fine-tuning-bert-model-for-text-generation-crossword-solver | <p>I need assistance in my NLP project, where the goal is to predict a list of possible answers for a given crossword clue. The idea is to <strong>fine tune a BERT model using a dataset of crossword clue - answer pairs</strong>.</p>
<p>train.source looks like this :
Line at an airport, Kind of omelet, Susa was its capi... | 199 | |
implement regression | How to implement Poisson Regression? | https://stackoverflow.com/questions/37941881/how-to-implement-poisson-regression | <p>There are 2 types of Generalized Linear Models:
<br>1. Log-Linear Regression, also known as Poisson Regression
<br>2. Logistic Regression</p>
<p>How to implement the Poisson Regression in Python for Price Elasticity prediction?</p>
| <p>Have a look at the <a href="https://pypi.python.org/pypi/statsmodels" rel="noreferrer">statmodels</a> package in python.</p>
<p>Here is an <a href="http://nbviewer.jupyter.org/urls/umich.box.com/shared/static/ir0bnkup9rywmqd54zvm.ipynb" rel="noreferrer">example</a></p>
<p>A bit more of input to avoid the <strong><... | 0 |
implement regression | Problems implementing regression neural network | https://stackoverflow.com/questions/51189147/problems-implementing-regression-neural-network | <p>I've been trying for a while to implement my first regression neural network in MATLAB, following the example from figure 5.3 in page 231 from '<a href="http://users.isr.ist.utl.pt/~wurmd/Livros/school/Bishop%20-%20Pattern%20Recognition%20And%20Machine%20Learning%20-%20Springer%20%202006.pdf" rel="nofollow noreferre... | 1 | |
implement regression | How to implement L1 logistic regression? | https://stackoverflow.com/questions/59881343/how-to-implement-l1-logistic-regression | <p>As part of pursuing a course, I was trying to implement L1 logistic regression using scikit-learn in Python. Unfortunately for the code</p>
<pre><code>clf, pred = fit_and_plot_classifier(LogisticRegression(penalty = 'l1', C=1000000))
</code></pre>
<p>I get the error message</p>
<pre><code>ValueError: Solver lbfgs... | <p>You can do it like you are doing in the first code snippet, but you have to define another solver. Use either ‘liblinear’ or ‘saga’, <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression" rel="nofollow noreferrer">check more in... | 2 |
implement regression | implement ordinal regression in Theano | https://stackoverflow.com/questions/44666127/implement-ordinal-regression-in-theano | <p>I want to implement <a href="https://en.wikipedia.org/wiki/Ordinal_regression" rel="nofollow noreferrer">ordinal regression</a> in Theano. But I've no idea how to implement the middle part: threshold definition and usage.</p>
<p>For example(simply say): </p>
<pre><code>X = T.matrix('X', dtype='float32') # Feature ... | 3 | |
implement regression | Manually implementing Regression Likelihood Ratio Test | https://stackoverflow.com/questions/49764026/manually-implementing-regression-likelihood-ratio-test | <p>I'm trying to implement my own linear regression likelihood ratio test.</p>
<p>The test is where you take the sum of squares of a reduced model and the sum of squares of a full model and compare it to the F statistic.</p>
<p>However, I am having some trouble implementing the function, especially when dealing with ... | <p>The error originates from line</p>
<pre><code>beta_hat_full <- qr.solve(t(mat)%*%mat)%*%t(mat)%*%response
</code></pre>
<p>If you go through your function step-by-step you will see an error</p>
<blockquote>
<p>Error in qr.solve(t(mat) %*% mat) : singular matrix 'a' in solve</p>
</blockquote>
<p>The problem ... | 4 |
implement regression | How can I implement regression after multi-class multi-label classification? | https://stackoverflow.com/questions/78572569/how-can-i-implement-regression-after-multi-class-multi-label-classification | <p>I have a dataset where some objects (15%) belong to different classes and have a property value for each of those classes. How can I make a model that predicts multi-label or multi-class and then make a regression prediction based on the output of the classifier? I also need to output the probabilities for each clas... | 5 | |
implement regression | ms access: How to implement linear regression | https://stackoverflow.com/questions/30661809/ms-access-how-to-implement-linear-regression | <p>In excel it is possible to implement linear regression graph. But in ms access I could not find anything similar to excel. If there is nothing built in then how can I implement it.?</p>
| <p>just take the data that you generated in Excel for the line regression and export it to Access.Then click on chart to get the line regression! This is the basic method.</p>
| 6 |
implement regression | Vectorized Implementation of Softmax Regression | https://stackoverflow.com/questions/8998321/vectorized-implementation-of-softmax-regression | <p>I’m implementing softmax regression in Octave. Currently I’m using a non-vectorized implementation using following cost function and derivatives.</p>
<p><a href="https://i.sstatic.net/l6AQf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/l6AQf.png" alt="alt text"></a> </p>
<p><a href="https://i.ssta... | <p>This is very similar to an exercise in Andrew Ng's deep learning class, they give some hints
<a href="http://ufldl.stanford.edu/wiki/index.php/Exercise:Vectorization" rel="nofollow">http://ufldl.stanford.edu/wiki/index.php/Exercise:Vectorization</a></p>
| 7 |
implement regression | Implement Logistic Regression | https://stackoverflow.com/questions/47278604/implement-logistic-regression | <p>I am applying multiple ML algorithm to this dataset so I tried logistic regression and I plotted the predictions and it seems completely off since the plot only shows data points from one class. Here is the data and what I attempted</p>
<pre><code>set.seed(10)
x1 <- runif(500) - 0.5
x2 <- runif(500) - 0.5
... | <p><code>predict</code> returns log-odds for a logistic regression by default. To get predicted classes, use <code>type = "resp"</code> to get predicted probabilities and then use a decision rule like <code>p > 0.5</code> to turn them into classes:</p>
<pre><code>y.hat.3 <- predict(fit.glm,dat, type = "resp") &g... | 8 |
implement regression | How to implement regressors in a Hierarchical Series in R, with the Fable package? | https://stackoverflow.com/questions/65685672/how-to-implement-regressors-in-a-hierarchical-series-in-r-with-the-fable-packag | <p>I am new to exploring the fable package, and I was wanting to implement Regressors in a Hierarchical Time Series model. How should the Dimensionality of the data be? Should there be an additional column inside the <code>tsibble</code> object? For example, in an ARIMA model. Thank you very much in advance.</p>
| <p>The approach for modelling hierarchical data with exogenous regressors is the same as modelling regular data. The exogenous regressors should be a column of the tsibble object used to estimate the model, for each node in the hierarchy.</p>
<p>The code below shows how a simple hierarchy (<code>T = M + F</code>) can b... | 9 |
implement regression | Problem with implement a 4-D Gaussian Processes Regression through GPML | https://stackoverflow.com/questions/69673457/problem-with-implement-a-4-d-gaussian-processes-regression-through-gpml | <p>I refer to the link <a href="https://stats.stackexchange.com/questions/105516/how-to-implement-a-2-d-gaussian-processes-regression-through-gpml-matlab">https://stats.stackexchange.com/questions/105516/how-to-implement-a-2-d-gaussian-processes-regression-through-gpml-matlab</a> and create a 2-d Gaussian Process regre... | <p>You may create n- dimensional grids using <a href="https://de.mathworks.com/help/matlab/ref/ndgrid.html" rel="nofollow noreferrer">ndgrid</a>, but please keep in mind that it does not directly create the same output as meshgrid, you have to convert it first. (How to do that is also explained in the documentation)</p... | 10 |
implement regression | How to implement multiple regression? | https://stackoverflow.com/questions/61335228/how-to-implement-multiple-regression | <p>I am practicing simple regression models as an intro to machine learning. I have reviewed a few sample models for multiple regression, which is, I believe, an extension of linear regression, but with more than 1 feature. From the examples I have seen, the syntax is the same for linear regression and multiple regress... | <p>You have a mistake in your <code>train_test_split</code> - the order of results matters; the correct usage is:</p>
<pre><code>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=0)
</code></pre>
<p>Check the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_s... | 11 |
implement regression | Logistic regression Python implementation | https://stackoverflow.com/questions/66051281/logistic-regression-python-implementation | <p>I tried to implement logistic regression only with numpy in Python, but the result is not satisfying. The predictions seems incorrect and loss is not improving so it is probably something wrong with the code. Does anyone know what could fix it? Thank you very much!</p>
<p>Here is algorithm:</p>
<pre><code>import num... | <p>At first glance you are missing you intercept term (typically called b_0, or bias) and its gradient update. Also in the backward_pass and loss calculations you are not dividing by the amount of data samples.</p>
<p>You can see two examples of how to implement it from scratch here:</p>
<p>1: <a href="https://towardsd... | 12 |
implement regression | How do you properly implement regression with categorical explanatory variables missing values when gtsummary tbl_uvregression? | https://stackoverflow.com/questions/63180323/how-do-you-properly-implement-regression-with-categorical-explanatory-variables | <p>I am using <code>tbl_uvregression</code> doing logistic regression but some of the categorical explanatory variables have missing values. The missing value category is being chosen as the reference category. How do I implement the function such that I only use complete cases for each variable?</p>
<p>Sample data bel... | <p>It looks like the issue is there are no missing values in the column <code>HTN</code>. There are, however, 4 observations that are blank, but this is not missing.</p>
<p><a href="https://i.sstatic.net/1cm3u.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/1cm3u.png" alt="enter image description here" /... | 13 |
implement regression | Python Implementation of Logistic Regression as Regression (Not Classification!) | https://stackoverflow.com/questions/65268985/python-implementation-of-logistic-regression-as-regression-not-classification | <p>I have a regression problem on which I want to use logistic regression - not logistic classification - because my target variables <code>y</code> are continuopus quantities between 0 and 1. However, the common implementations of logistic regression in Python seem to be exclusively logistic classification. I've also ... | <p>In statsmodels both GLM with family Binomial and discrete model Logit allow for a continuous target variable as long as the values are restricted to interval [0, 1].</p>
<p>Similarly, Poisson is very useful to model non-negative valued continuous data.</p>
<p>In these cases, the model is estimated by quasi maximum l... | 14 |
implement regression | Implementing Kernel Ridge Regression in R | https://stackoverflow.com/questions/33863234/implementing-kernel-ridge-regression-in-r | <p>I want to implement kernel ridge regression in R. My problem is that I can't figure out how to generate the kernel values and I do not know how to use them for the ridge regression. I want to use the following kernel function:</p>
<pre><code>kernel.eval <- function(x1,x2,ker) { k=0 if (kertype == 'RBF') {
# ... | <p>Following is the code for polynomial kernel with degree 2, hope that helps!</p>
<pre><code>poly.kernel <- function(v1, v2=v1, p=2) {
((as.matrix(v1) %*% t(v2))+1)^p
}
KernelRidgeReg <- function(TrainObjects,TrainLabels,TestObjects,lambda){
X <- TrainObjects
y <- TrainLabels ... | 15 |
implement regression | Random Forest Regression Implementation in PySpark | https://stackoverflow.com/questions/57587475/random-forest-regression-implementation-in-pyspark | <p>I want to implement Random forest regression in pyspark after all data preparation. I want sample code for implementation.</p>
| <p>From the doc (<a href="https://spark.apache.org/docs/latest/api/python/pyspark.ml.html#pyspark.ml.regression.RandomForestRegressor" rel="nofollow noreferrer">https://spark.apache.org/docs/latest/api/python/pyspark.ml.html#pyspark.ml.regression.RandomForestRegressor</a>) :</p>
<pre><code>>>> from numpy impo... | 16 |
implement regression | What is the easiest to implement linear regression algorithm? | https://stackoverflow.com/questions/31735595/what-is-the-easiest-to-implement-linear-regression-algorithm | <p>I want to implement single variable regression using ordinary least squares. I have no access to linear algebra or calculus libraries, so any matrix operations or differentiation methods needs to be implemented by me. What is the least complex method?</p>
| <p>John D. Cook has an <a href="http://www.johndcook.com/blog/running_regression/" rel="nofollow">excelent post</a> on the subject with a simple C++ implementation. His implementation uses constant memory and can be parallelized with little effort. </p>
<p>I wrote a simple Python version of it. Use with caution, there... | 17 |
implement regression | How to implement multivariate regularized linear regression in Dlib? | https://stackoverflow.com/questions/54633033/how-to-implement-multivariate-regularized-linear-regression-in-dlib | <p>I implemented simple linear regression in <a href="http://dlib.net/" rel="nofollow noreferrer">Dlib</a> as a single-layer perceptron with MSE-loss with a single output. The network type is:</p>
<pre><code>dlib::loss_mean_squared<dlib::fc<1,dlib::input<dlib::matrix<float>>>>
</code></pre>
<p... | 18 | |
implement regression | method for implementing regression tree on raster data - python | https://stackoverflow.com/questions/26104434/method-for-implementing-regression-tree-on-raster-data-python | <p>I'm trying to build and implement a regression tree algorithm on some raster data in python, and can't seem to find the best way to do so. I will attempt to explain what I'm trying to do:</p>
<p>My desired output is a raster image, whose values represent lake depth, call it depth.tif. I have a series of raster imag... | <p>I have had some experience using LandSat Data for the prediction of environmental properties of soil, which seems to be somewhat related to the problem that you have described above. Although I developed my own models at the time, I could describe the general process that I went through in order to map the predicte... | 19 |
implement regression | How to implement a weighted logistic regression in JAGS? | https://stackoverflow.com/questions/67762244/how-to-implement-a-weighted-logistic-regression-in-jags | <p>I am performing a resource selection function using use and availability locations for a set of animals. For this type of analysis, an infinitely weighted logistic regression is suggested (Fithian and Hastie 2013) and is done by setting weights of used locations to 1 and available locations to some large number (e.g... | 20 | |
implement regression | GridSearch implementation for Keras Regression | https://stackoverflow.com/questions/52551511/gridsearch-implementation-for-keras-regression | <p>Trying to understand and implement GridSearch method for the Keras Regression. Here is my simple producible regression application. </p>
<pre><code>import pandas as pd
import numpy as np
import sklearn
from sklearn.model_selection import train_test_split
from sklearn import metrics
from keras.models import Sequenti... | <p>I have tested your code, and I have seen that you are not using a scoring function in GridSearchCV so according to documentation <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV" rel="nofollow noreferrer">scikit-learn documentat... | 21 |
implement regression | How to Implement GridSearch for Models other than Regression Models? | https://stackoverflow.com/questions/73031371/how-to-implement-gridsearch-for-models-other-than-regression-models | <p>Is it possible to use GridsearchCV for models which doesn't deal with regression? I have been able to implement HyperOpt and Bayes_Opt for the said model.</p>
| 22 | |
implement regression | Getting NaN while implementing Linear regression | https://stackoverflow.com/questions/49600778/getting-nan-while-implementing-linear-regression | <p>I am trying to implement linear regression in R. Below is my code:</p>
<pre><code>library(ggplot2)
df <- data.frame()
df<-cbind(c(10000,20000,5000,5123,5345,5454,11000,23000,6000,6100,6300),
c(5600,21000,1000,2000,2300,3000,7000,21400,3200,3250,3300))
df <- as.data.frame(df)
colnames(df)<-c("Populatio... | <p>If we use the <code>print</code> for one of the 'temp', the values are getting to infinite at certain point and then for the next iteration onwards it becomes NaN</p>
<pre><code>iterations <- 62
for(i in 1:iterations){
temp1 <- theta[1] - alpha * (1/m) * sum(((X%*%theta)- Y))
temp2 <- theta[2] <- t... | 23 |
implement regression | Multiclass logistic regression - implementation question | https://stackoverflow.com/questions/57911771/multiclass-logistic-regression-implementation-question | <p>This is my try to implement multi-class logistic regression in python using softmax as activation function and mnist digit data set as training and test set.</p>
<pre><code>import numpy as np
def softmax(z):
return np.array([(np.exp(el)/np.sum(np.exp(el))) for el in z])
def cost(W,F,L):
m = F.shape[0] #get ... | 24 | |
implement regression | Trying to Implement Linear Regression with Stochastic Gradient Descent | https://stackoverflow.com/questions/66756559/trying-to-implement-linear-regression-with-stochastic-gradient-descent | <p>[<a href="https://docs.google.com/spreadsheets/d/1AVNrWBwn22c1QWc6X9zG8FkvTMXHXZGuZH2sPAT9a00/edit?usp=sharing" rel="nofollow noreferrer">Dataset</a>]<a href="https://docs.google.com/spreadsheets/d/1AVNrWBwn22c1QWc6X9zG8FkvTMXHXZGuZH2sPAT9a00/edit?usp=sharing" rel="nofollow noreferrer">1</a>I'm attempting to impleme... | <p>Adding on to the answer from @Agni</p>
<p>The CSV file that you are reading has a header line</p>
<p><code>num_preg PlGlcConc BloodP tricept insulin BMI ped_func Age HasDiabetes</code></p>
<p>When you use <code>reader(file)</code> to read the file and then iterate over it, the first line also gets added in <... | 25 |
implement regression | How to use regression in python-weka-wrapper? | https://stackoverflow.com/questions/66135163/how-to-use-regression-in-python-weka-wrapper | <p>I would like to implement regression algorithms using python-weka-wrapper in Jupyter Notebook. However, I couldn't find the correct function in <a href="https://fracpete.github.io/python-weka-wrapper/api.html#classifiers" rel="nofollow noreferrer">https://fracpete.github.io/python-weka-wrapper/api.html#classifiers</... | <p>In the olden days, Weka distinguished between classification and regression algorithms, but that got dropped in favor of just a single super class.</p>
<p>The <em>capabilities</em> of a <code>weka.classifiers.Classifier</code> determine what types of attributes and class attributes an algorithm can handle. Some algo... | 26 |
implement regression | How does one implement a conditional poisson regression in R? | https://stackoverflow.com/questions/49024652/how-does-one-implement-a-conditional-poisson-regression-in-r | <p>I am keen to implement a conditional (bivariate?) poisson regression in R to assess the change in rates of a variable (stratified by treatment condition) pre- / post- an intervention. Is anyone familiar with a package that runs this type of analysis?</p>
| <p>Check out this <a href="https://cran.r-project.org/web/packages/gnm/gnm.pdf" rel="nofollow noreferrer">"gnm"</a> package in R. It has a function of gnm() where you can specify you model formula, family=poisson(), offset, dataset and strata id in "eliminate". Please read it.</p>
| 27 |
implement regression | Trying to implement linear regression in python | https://stackoverflow.com/questions/26678708/trying-to-implement-linear-regression-in-python | <p>I am implementing linear regression in Python, and I think I am doing something wrong while converting matrix to numpy array, but cannot seem to figure it out.
Any help will be appreciated.</p>
<p>I am loading data from a csv file that has 100 columns. y is the last column. I am not using col 1 and 2 for regressio... | <p>I'm not quite sure what the last <code>dot</code> is supposed to do. But you can't multiple <code>error</code> with itself this way. <code>dot</code> does a matrix multiplication, thus the dimensions have to align.</p>
<p>See, e.g., the following example:</p>
<pre><code>import numpy as np
A = np.ones((3, 4))
B = n... | 28 |
implement regression | Problem in the linear regression implementation | https://stackoverflow.com/questions/60133065/problem-in-the-linear-regression-implementation | <p>I am new to Machine learning and I was trying to implement vectorized linear regression from scratch using numpy. I tried testing out the implementation using y=x. But my loss is increasing and I am unable to understand why. It will be great if someone could point out why is this happening. Thanks in advance!</p>
<... | <p>Nothing is wrong with your implementation. Your step size is just too high to converge. You are bouncing around the optimization crest to higher and higher error.
<a href="https://i.sstatic.net/cSd1H.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/cSd1H.png" alt="enter image description here" /></a>
e... | 29 |
implement regression | Linear Regression using fminunc Implementation | https://stackoverflow.com/questions/44848279/linear-regression-using-fminunc-implementation | <p>I'm trying to implement linear regression with only one feature using <code>fminunc</code> in Octave.</p>
<p>Here is my code.</p>
<pre class="lang-matlab prettyprint-override"><code>x = load('/home/battousai/Downloads/ex2Data/ex2x.dat');
y = load('/home/battousai/Downloads/ex2Data/ex2y.dat');
m = length(y);
x =... | <p>From the documentation for fminunc:</p>
<blockquote>
<p>FCN should accept a vector (array) defining the unknown variables</p>
</blockquote>
<p>and</p>
<blockquote>
<p>X0 determines a starting guess. </p>
</blockquote>
<p>Since your input is a <em>cost</em> function (i.e. it associates your choice of paramete... | 30 |
implement regression | Scratch implementation of ridge regression | https://stackoverflow.com/questions/79299410/scratch-implementation-of-ridge-regression | <p>I am trying to implement Ridge regression but I feel like I am missing something with the Python operators. Here is my code:</p>
<pre><code>import numpy as np
x = np.random.rand(10, 2)
y = np.random.rand(10, 1)
lambda_reg = 0.1
alpha = 0.1
num_iterations = 100000
X_train = np.hstack((np.ones((x.shape[0... | <p>Some observations about your optimization function:</p>
<ol>
<li>Why are you dividing by N? You're making your gradient smaller than necessary, and you're not applying that scaling to the second term in your gradient, changing the relationship between the components of your gradient (making the residual-driven term ... | 31 |
implement regression | Logistic Regression, Gradient Descent Octave implementation | https://stackoverflow.com/questions/63046676/logistic-regression-gradient-descent-octave-implementation | <p>I'm taking the Machine Learning class by Prof. Ng.
There is a homework need to implement logistic regression gradient descent.
And here is my code:</p>
<pre><code>function [J, grad] = costFunction(theta, X, y)
%COSTFUNCTION Compute cost and gradient for logistic regression
% J = COSTFUNCTION(theta, X, y) computes ... | <p>I believe you were supposed to get the average of the gradient <code>grad = grad / m</code> as well, just like for the cost <code>J</code>. But it has been a while since I last did Andrew Ng's course, so I might be wrong.</p>
| 32 |
implement regression | Logistic regression implementation not working | https://stackoverflow.com/questions/56041493/logistic-regression-implementation-not-working | <p>Recently, I have been reading about machine learning of which logistic regression is one. After reading, to test my understanding, I tried to implement LR in Java. When I tested it on Logical OR and Logical AND, it seemed to work. But, when I tried it on marks to decide accepted or rejected job applicants, it failed... | <p>The problem you are having with Logistic Regression is called underfitting, this is a very common problem for simple machine learning models. By this I mean that the model does not adjust correctly to the data. There are different reasons for this to happen:</p>
<ul>
<li><p>The model is to simple (or the dataset is... | 33 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.