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 |
|---|---|---|---|---|---|
keras | Keras 2 code is executing keras 1 compatibility code | https://stackoverflow.com/questions/47017035/keras-2-code-is-executing-keras-1-compatibility-code | <p>I am trying to run an example that uses keras/tensorflow. I am using Keras 2.0.8.
When I write this simple code:</p>
<pre><code>from keras.layers import ZeroPadding2D
pad = ZeroPadding2D(padding=(1, 1), data_format=None)
</code></pre>
<p>and try to debug <code>ZeroPadding2D</code> I am directed to a file named <co... | <p>Your code is Keras 2, it's everything OK with it. </p>
<p>Although you import the layer from <code>keras.layers</code>, internally it's imported from <code>keras.layers.convolutional</code>. You can inspect keras 2.0.8 code, and there is no <code>ZeroPadding2D</code> in the <a href="https://github.com/fchollet/kera... | 834 |
keras | Keras: the difference between LSTM dropout and LSTM recurrent dropout | https://stackoverflow.com/questions/44924690/keras-the-difference-between-lstm-dropout-and-lstm-recurrent-dropout | <p>From the Keras documentation:</p>
<p>dropout: Float between 0 and 1. Fraction of the units to drop for the
linear transformation of the inputs.</p>
<p>recurrent_dropout: Float between 0 and 1. Fraction of the units to
drop for the linear transformation of the recurrent state.</p>
<p>Can anyone point to where on... | <p>I suggest taking a look at (the first part of) <a href="https://arxiv.org/pdf/1512.05287.pdf" rel="noreferrer">this paper</a>. Regular dropout is applied on the inputs and/or the outputs, meaning the vertical arrows from <code>x_t</code> and to <code>h_t</code>. In your case, if you add it as an argument to your lay... | 835 |
keras | Exact model converging on keras-tf but not on keras | https://stackoverflow.com/questions/57396482/exact-model-converging-on-keras-tf-but-not-on-keras | <p>I am working on predicting the <a href="https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average" rel="nofollow noreferrer">EWMA (exponential weighted moving average) formula</a> on a time series using a simple RNN. Already posted about it <a href="https://stackoverflow.com/questions/57348091/predict-... | <p>This might be because of difference (1 liner) in implementation of SimpleRNN, between <a href="https://github.com/tensorflow/tensorflow/blob/r1.14/tensorflow/python/keras/layers/recurrent.py#L1364-L1375" rel="nofollow noreferrer">TF Keras</a> and <a href="https://github.com/keras-team/keras/blob/master/keras/layers/... | 836 |
keras | Unexpected keyword argument 'ragged' in Keras | https://stackoverflow.com/questions/58878421/unexpected-keyword-argument-ragged-in-keras | <p>Trying to run a trained keras model with the following python code:</p>
<pre class="lang-py prettyprint-override"><code>from keras.preprocessing.image import img_to_array
from keras.models import load_model
from imutils.video import VideoStream
from threading import Thread
import numpy as np
import imutils
import ... | <p>So I tried link above which you have mentioned <a href="https://teachablemachine.withgoogle.com/" rel="noreferrer">teachable machine</a><br>
As it turns out model you have exported is from <code>tensorflow.keras</code> and not directly from <code>keras</code> API. These two are different. So while loading it might b... | 837 |
keras | What does the standard Keras model output mean? What is epoch and loss in Keras? | https://stackoverflow.com/questions/34673396/what-does-the-standard-keras-model-output-mean-what-is-epoch-and-loss-in-keras | <p>I have just built my first model using Keras and this is the output. It looks like the standard output you get after building any Keras artificial neural network. Even after looking in the documentation, I do not fully understand what the epoch is and what the loss is which is printed in the output.</p>
<p><strong>... | <p>Just to answer the questions more specifically, here's a definition of epoch and loss:</p>
<p><strong>Epoch</strong>: A full pass over all of your <em>training</em> data. </p>
<p>For example, in your view above, you have 1213 observations. So an epoch concludes when it has finished a training pass over all 1213 of... | 838 |
keras | Keras model.summary() result - Understanding the # of Parameters | https://stackoverflow.com/questions/36946671/keras-model-summary-result-understanding-the-of-parameters | <p>I have a simple NN model for detecting hand-written digits from a 28x28px image written in python using Keras (Theano backend):</p>
<pre><code>model0 = Sequential()
#number of epochs to train for
nb_epoch = 12
#amount of data each iteration in an epoch sees
batch_size = 128
model0.add(Flatten(input_shape=(1, img_... | <p>The number of parameters is 7850 because with every hidden unit you have 784 input weights and one weight of connection with bias. This means that every hidden unit gives you 785 parameters. You have 10 units so it sums up to 7850. </p>
<p>The role of this additional bias term is really important. It significantly ... | 839 |
keras | Saving best model in keras | https://stackoverflow.com/questions/48285129/saving-best-model-in-keras | <p>I use the following code when training a model in keras</p>
<pre><code>from keras.callbacks import EarlyStopping
model = Sequential()
model.add(Dense(100, activation='relu', input_shape = input_shape))
model.add(Dense(1))
model_2.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy'])
model.f... | <p><a href="https://keras.io/callbacks/#earlystopping" rel="noreferrer">EarlyStopping</a> and <a href="https://keras.io/callbacks/#modelcheckpoint" rel="noreferrer">ModelCheckpoint</a> is what you need from Keras documentation.</p>
<p>You should set <code>save_best_only=True</code> in ModelCheckpoint. If any other adj... | 840 |
keras | Keras backend (tensorflow) vs Keras | https://stackoverflow.com/questions/52534202/keras-backend-tensorflow-vs-keras | <p>I would like to custom a Keras loss function but I do not really understand something.</p>
<p>If I use tensorflow as a backend for Keras, do I need to use functions from <code>keras.backend</code> or can I use functions directly from tensorflow.</p>
<p>I only see posts where people are using functions from <code>k... | <p>As pointed in the comments and stated in <a href="https://stackoverflow.com/questions/52184478/math-ops-floor-equivalent-in-keras/52186294#52186294">this answer</a> "using Keras backend functions (i.e. keras.backend.*) is necessary in those cases when 1) there is a need to pre-process or augment the argument(s) pass... | 841 |
keras | Keras installation | https://stackoverflow.com/questions/47659318/keras-installation | <p>I create an virtual environment in my conda named 'keras_ev' and install the keras in it
by </p>
<pre><code>conda install keras
</code></pre>
<p>after that when i </p>
<pre><code>activate keras_ev
jupyter notebook
</code></pre>
<p>the notebook does not show my keras_ev environment <a href="https://i.sstatic.net... | <p>Try <code>conda install ipykernel</code> in your <code>keras_ev</code> environment. Then it should appear in your Jupyter notebook.</p>
<p>You can also install Python dependencies while using your Jupyter notebook. First, activate the environment <code>keras_ev</code> in another terminal tab. Then install your depe... | 842 |
keras | keras and keras-applications dependencies | https://stackoverflow.com/questions/54402523/keras-and-keras-applications-dependencies | <p>I am trying to install keras on a Windows pc (procedure has to be done offline) I have downloaded (through another pc then transfered to this one) wheels for both modules and I am trying to install them by pip install . However, keras needs keras-applications installed and keras-applications needs keras installed, a... | <p>So I did manage to solve it this way : </p>
<p>I passed --find-links argument in this way :</p>
<pre><code>pip install --find-links C:\mdependency_packages_path\ C:\package_to_install_path
</code></pre>
| 843 |
keras | How to calculate precision and recall in Keras | https://stackoverflow.com/questions/43076609/how-to-calculate-precision-and-recall-in-keras | <p>I am building a multi-class classifier with Keras 2.02 (with Tensorflow backend),and I do not know how to calculate precision and recall in Keras. Please help me.</p>
| <p>Python package <a href="https://pypi.org/project/keras-metrics/" rel="noreferrer" title="keras-metrics">keras-metrics</a> could be useful for this (I'm the package's author).</p>
<pre class="lang-py prettyprint-override"><code>import keras
import keras_metrics
model = models.Sequential()
model.add(keras.layers.Den... | 844 |
keras | Keras crossentropy | https://stackoverflow.com/questions/47555568/keras-crossentropy | <p>I'm working with Keras and I'm trying to rewrite categorical_crossentropy by using the Keras abstract backend, but I'm stuck. </p>
<p>This is my custom function, I want just the weighted sum of crossentropy:</p>
<pre><code>def custom_entropy( y_true, y_pred):
y_pred /= K.sum(y_pred, axis=-1, keepdims=True)
... | <p>Keras backend functions such <code>K.categorical_crossentropy</code> expect tensors.</p>
<p>It's not obvious from your question what type <code>label</code> is. However, we know that <code>model.predict</code> always returns NumPy <code>ndarrays</code>, so we know <code>label_pred</code> is not a tensor. It is easy... | 845 |
keras | How to change Keras backend (where's the json file)? | https://stackoverflow.com/questions/40310035/how-to-change-keras-backend-wheres-the-json-file | <p>I have installed Keras, and wanted to switch the backend to Theano. I checked out <a href="https://stackoverflow.com/questions/40036748/keras-backend-importerror-cannot-import-name-ctc-ops">this post</a>, but still have no idea where to put the created json file. Also, below is the error I got when running <code>imp... | <p>After looking at keras sources (<a href="https://github.com/fchollet/keras/blob/25dbe8097fba9a6a429e19d0625d78c3b8731527/keras/backend/__init__.py#L18" rel="noreferrer">this place</a>):</p>
<p>Start up your python-binary and do the following</p>
<pre><code>import os
print(os.path.expanduser('~'))
# >>> C:... | 846 |
keras | keras bidirectional lstm seq2seq | https://stackoverflow.com/questions/47923370/keras-bidirectional-lstm-seq2seq | <p>I am trying to modify the lstm_seq2seq.py example of keras, to modify it to a bidirectional lstm model.</p>
<p><a href="https://github.com/keras-team/keras/blob/master/examples/lstm_seq2seq.py" rel="noreferrer">https://github.com/keras-team/keras/blob/master/examples/lstm_seq2seq.py</a></p>
<p>I try different appr... | <p>The error you're seeing is because the <code>Bidirectional</code> wrapper does not handle the state tensors properly. I've fixed it in <a href="https://github.com/keras-team/keras/pull/8977" rel="noreferrer">this PR</a>, and it's in the latest 2.1.3 release already. So the lines in the question should work now if yo... | 847 |
keras | Tensorflow compatibility with Keras | https://stackoverflow.com/questions/62690377/tensorflow-compatibility-with-keras | <p>I am using Python 3.6 and Tensorflow 2.0, and have some Keras codes:</p>
<pre><code>import keras
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(1))
model.compile(optimizer='adam',loss='mean_squared_error',metrics=['accuracy'])
</code></pre>
<p>When I run this... | <p>The problem is that the latest <code>keras</code> version (2.4.x) is just a wrapper on top of <code>tf.keras</code>, which I do not think is that you want, and this is why it requires specifically TensorFlow 2.2 or newer.</p>
<p>What you can do is install Keras 2.3.1, which supports TensorFlow 2.x and 1.x, and is th... | 848 |
keras | Differences in SciKit Learn, Keras, or Pytorch | https://stackoverflow.com/questions/54527439/differences-in-scikit-learn-keras-or-pytorch | <p>Are these libraries fairly interchangeable?</p>
<p>Looking here, <a href="https://stackshare.io/stackups/keras-vs-pytorch-vs-scikit-learn" rel="noreferrer">https://stackshare.io/stackups/keras-vs-pytorch-vs-scikit-learn</a>, it seems the major difference is the underlying framework (at least for PyTorch).</p>
| <p>Yes, there is a major difference.</p>
<p>SciKit Learn is a general machine learning library, built on top of NumPy. It features a lot of machine learning algorithms such as support vector machines, random forests, as well as a lot of utilities for general pre- and postprocessing of data. It is not a neural network ... | 849 |
keras | How to return history of validation loss in Keras | https://stackoverflow.com/questions/36952763/how-to-return-history-of-validation-loss-in-keras | <p>Using Anaconda Python 2.7 Windows 10.</p>
<p>I am training a language model using the Keras exmaple:</p>
<pre><code>print('Build model...')
model = Sequential()
model.add(GRU(512, return_sequences=True, input_shape=(maxlen, len(chars))))
model.add(Dropout(0.2))
model.add(GRU(512, return_sequences=False))
model.add... | <p>It's been solved.</p>
<p>The losses only save to the History over the epochs. I was running iterations instead of using the Keras built in epochs option.</p>
<p>so instead of doing 4 iterations I now have</p>
<pre><code>model.fit(......, nb_epoch = 4)
</code></pre>
<p>Now it returns the loss for each epoch run:</p>
... | 850 |
keras | Keras not using multiple cores | https://stackoverflow.com/questions/36908978/keras-not-using-multiple-cores | <p>Based on the famous <code>check_blas.py</code> script, I wrote this one to check that theano can in fact use multiple cores:</p>
<pre class="lang-py prettyprint-override"><code>import os
os.environ['MKL_NUM_THREADS'] = '8'
os.environ['GOTO_NUM_THREADS'] = '8'
os.environ['OMP_NUM_THREADS'] = '8'
os.environ['THEANO... | <p>Keras and TF themselves don't use whole cores and capacity of CPU! If you are interested in using all 100% of your CPU then the <code>multiprocessing.Pool</code> basically creates a pool of jobs that need doing. The processes will pick up these jobs and run them. When a job is finished, the process will pick up anot... | 851 |
keras | Read only mode in keras | https://stackoverflow.com/questions/53212672/read-only-mode-in-keras | <p>I have cloned human pose estimation keras model from this link <a href="https://github.com/michalfaber/keras_Realtime_Multi-Person_Pose_Estimation" rel="noreferrer">human pose estimation keras</a> </p>
<p>When I try to load the model on google colab, I get the following error</p>
<p>code</p>
<pre><code>from keras... | <p>Here is an example Git gist created on Google Collab for you: <a href="https://gist.github.com/kolygri/835ccea6b87089fbfd64395c3895c01f" rel="noreferrer">https://gist.github.com/kolygri/835ccea6b87089fbfd64395c3895c01f</a></p>
<p>As far as I understand:</p>
<blockquote>
<p>You have to set and define the architec... | 852 |
keras | Make a custom loss function in keras | https://stackoverflow.com/questions/45961428/make-a-custom-loss-function-in-keras | <p>Hi I have been trying to make a custom loss function in keras for dice_error_coefficient. It has its implementations in <strong>tensorboard</strong> and I tried using the same function in keras with tensorflow but it keeps returning a <strong>NoneType</strong> when I used <strong>model.train_on_batch</strong> or <st... | <p>In addition, you can extend an existing loss function by inheriting from it. For example masking the <code>BinaryCrossEntropy</code>:</p>
<pre class="lang-py prettyprint-override"><code>class MaskedBinaryCrossentropy(tf.keras.losses.BinaryCrossentropy):
def call(self, y_true, y_pred):
mask = y_true != -1... | 853 |
keras | Backward propagation in Keras? | https://stackoverflow.com/questions/47416861/backward-propagation-in-keras | <p>can anyone tell me how is backpropagation done in Keras? I read that it is really easy in Torch and complex in Caffe, but I can't find anything about doing it with Keras. I am implementing my own layers in Keras (A very beginner) and would like to know how to do the backward propagation. </p>
<p>Thank you in advanc... | <p>You simply don't. (Late edit: except when you are creating custom training loops, only for advanced uses)</p>
<p>Keras does backpropagation automatically. There's absolutely nothing you need to do for that except for training the model with one of the <code>fit</code> methods.</p>
<p>You just need to take care of a ... | 854 |
keras | keras loss function(from keras input) | https://stackoverflow.com/questions/66287143/keras-loss-functionfrom-keras-input | <p>I reference the link: <a href="https://stackoverflow.com/questions/46464549/keras-custom-loss-function-accessing-current-input-pattern">Keras custom loss function: Accessing current input pattern</a>.</p>
<p>But I get error: " TypeError: Cannot convert a symbolic Keras input/output to a numpy array. This erro... | <p>In the tf 2.0, eager mode is on by default. It's not possible to get this functionality in eager mode as the above example is currently written. I think there are ways to do it in eager mode with some more advanced programming. But otherwise it's a simple matter to turn eager mode off and run in graph mode with:</p>... | 855 |
keras | Keras No module named models | https://stackoverflow.com/questions/44612653/keras-no-module-named-models | <p>Try to run Keras in MacOSX, using a virtual environment</p>
<p><strong>Versions</strong></p>
<ul>
<li>MacOSX: 10.12.4 (16E195) </li>
<li>Python 2.7</li>
</ul>
<p><strong>Troubleshooting</strong></p>
<ul>
<li>Recreate Virtualenv</li>
<li>Reinstall keras</li>
</ul>
<p><strong>Logs</strong></p>
<pre><code>(venv) ... | <p>The underlying problem here is what when you use <code>sudo</code>, <code>pip</code> points to the global, system-level python and not the virtual-env python. That is why, when you install without <code>sudo</code>, it works seamlessly for you. You can check this by running <code>sudo pip install --upgrade keras</co... | 856 |
keras | "Cannot import name 'keras'" error when importing keras | https://stackoverflow.com/questions/63687206/cannot-import-name-keras-error-when-importing-keras | <pre><code>import tensorflow as tf
from tensorflow import keras
</code></pre>
<p>Results are</p>
<pre><code>ImportError Traceback (most recent call last)
<ipython-input-1-75a28e3c6620> in <module>
1 import tensorflow as tf
----> 2 from tensorflow import keras
3
... | <p>You are using old version of tensorflow. You can update to latest version using below code</p>
<pre><code>! pip install tensorflow --upgrade
</code></pre>
<p>From <code>Tensorflow V2.0</code> onwards, keras is integrated in tensorflow as <code>tf.keras</code>, so no need to import keras separately.</p>
<p>To create ... | 857 |
keras | no module named keras after installing keras | https://stackoverflow.com/questions/61069835/no-module-named-keras-after-installing-keras | <p>I'm using anaconda ver 3, and I have installed python as well separately from anaconda. I installed python ver 2.7 and ver 3.6 from python website. </p>
<p>Now, I have installed keras from anaconda command prompt by using conda install keras. However, when I open jupyter notebook and write :</p>
<pre><code>import ... | <p>As far as i know, keras is a version of tensorflow. You should try installing tensorflow instead and then run</p>
<pre><code>import tensorflow as tf
tf.__version__
</code></pre>
<p>if you get <code>'2.1.0'</code> or any 2., you should be all set!</p>
<p>EDIT1: Keras is part of tensorflow not a version (as pointe... | 858 |
keras | Implementing skip connections in keras | https://stackoverflow.com/questions/42384602/implementing-skip-connections-in-keras | <p>I am implementing ApesNet in keras. It has an ApesBlock that has skip connections. How do I add this to a sequential model in keras? The ApesBlock has two parallel layers that merge at the end by element-wise addition.<img src="https://i.sstatic.net/UrFP8.png" alt="enter image description here"></p>
| <p>The easy answer is don't use a sequential model for this, use the functional API instead, implementing skip connections (also called residual connections) are then very easy, as shown in this example from the <a href="https://keras.io/getting-started/functional-api-guide/" rel="noreferrer">functional API guide</a>:<... | 859 |
keras | Getting "cannot import name 'layers' from 'keras'" while importing keras | https://stackoverflow.com/questions/77083867/getting-cannot-import-name-layers-from-keras-while-importing-keras | <p>I was importing keras in my jupyter notebook, but I'm getting <strong>cannot import name 'layers' from 'keras'</strong></p>
<p>Traceback:</p>
<pre><code>ImportError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_9104\626967271.py in <module>
1 import tensor... | 860 | |
keras | How to update Keras with conda | https://stackoverflow.com/questions/58268587/how-to-update-keras-with-conda | <p>I'd like to update Keras to version 2.3.0 with conda.
Currently, I've got Keras 2.2.4 running. </p>
<p>First, I tried </p>
<pre><code>conda update keras
</code></pre>
<p>which didn't work.
Then I tried</p>
<pre><code>conda install -c conda-forge keras
conda install -c conda-forge/label/broken keras
conda install... | <ol>
<li><p><code>keras</code> is collected in both the official channel and the conda-forge channel. Both of the two packages on Anaconda Cloud are not built the keras team, which explains why the package is outdated.</p></li>
<li><p>For the time being, 20191007, package <code>keras</code> 2.3.0 is available in the <s... | 861 |
keras | How to compute Receiving Operating Characteristic (ROC) and AUC in keras? | https://stackoverflow.com/questions/41032551/how-to-compute-receiving-operating-characteristic-roc-and-auc-in-keras | <p>I have a multi output(200) binary classification model which I wrote in keras.</p>
<p>In this model I want to add additional metrics such as ROC and AUC but to my knowledge keras dosen't have in-built ROC and AUC metric functions.</p>
<p>I tried to import ROC, AUC functions from scikit-learn</p>
<pre><code>from skle... | <p>Due to that you can't calculate ROC&AUC by mini-batches, you can only calculate it on the end of one epoch. There is a solution from <a href="https://github.com/fchollet/keras/issues/3230#issuecomment-319208366" rel="nofollow noreferrer">jamartinh</a>, I patch the code below for convenience:</p>
<pre class="lang... | 862 |
keras | How to find Number of parameters of a keras model? | https://stackoverflow.com/questions/35792278/how-to-find-number-of-parameters-of-a-keras-model | <p>For a Feedforward Network (FFN), it is easy to compute the number of parameters. Given a CNN, LSTM etc is there a quick way to find the number of parameters in a keras model?</p>
| <p>Models and layers have special method for that purpose:</p>
<pre><code>model.count_params()
</code></pre>
<p>Also, to get a short summary of each layer dimensions and parameters, you might find useful the following method </p>
<pre><code>model.summary()
</code></pre>
| 863 |
keras | Diff between importing Keras as "from tensorflow.python import keras" vs "from tensorflow import keras" | https://stackoverflow.com/questions/64749519/diff-between-importing-keras-as-from-tensorflow-python-import-keras-vs-from-t | <p>I understand that tensorflow version 2.x are eager execution enabled. However, I see a big performance and speed difference if I import Keras from tensorflow via <code>tensorflow.python.keras</code> vs <code>tensorflow.keras</code>. I am using tensorflow version 2.3.1.</p>
<p>I can train my model much faster in 50 e... | 864 | |
keras | Why the keras code get error messages when changing from Keras 1.2.2 to Keras 2.0.5 | https://stackoverflow.com/questions/46994409/why-the-keras-code-get-error-messages-when-changing-from-keras-1-2-2-to-keras-2 | <p>This is a piece of code I get from github for hierarchical attention network,the code is originally in Keras 1.2.2. now I have to change it to compile with Keras 2.0.5, however, it has such error messages that I could not solve.</p>
<p>The original code is the following</p>
<pre class="lang-py prettyprint-override... | <p>The problem is on the build method of your custom layer, according to <a href="https://keras.io/layers/writing-your-own-keras-layers/#writing-your-own-keras-layers" rel="nofollow noreferrer">keras' documentation</a>, you need to create the weights with the <code>self.add_weight</code> function:</p>
<pre><code>def b... | 865 |
keras | Using sparse matrices with Keras and Tensorflow | https://stackoverflow.com/questions/41538692/using-sparse-matrices-with-keras-and-tensorflow | <p>My data can be viewed as a matrix of 10B entries (100M x 100), which is very sparse (< 1/100 * 1/100 of entries are non-zero). I would like to feed the data into into a Keras Neural Network model which I have made, using a Tensorflow backend.</p>
<p>My first thought was to expand the data to be dense, that is, ... | <p>Sorry, don't have the reputation to comment, but I think you should take a look at the answer here: <a href="https://stackoverflow.com/questions/37609892/keras-sparse-matrix-issue">Keras, sparse matrix issue</a>. I have tried it and it works correctly, just one note though, at least in my case, the shuffling led to ... | 866 |
keras | How to use keras layers in custom keras layer | https://stackoverflow.com/questions/54194724/how-to-use-keras-layers-in-custom-keras-layer | <p>I am trying to write my own keras layer. In this layer, I want to use some other keras layers. Is there any way to do something like this:</p>
<pre><code>class MyDenseLayer(tf.keras.layers.Layer):
def __init__(self, num_outputs):
super(MyDenseLayer, self).__init__()
self.num_outputs = num_outputs
def b... | <p>It's much more comfortable and concise to put existing layers in the tf.keras.models.Model class. If you define non-custom layers such as layers, conv2d, the parameters of those layers are not trainable by default. </p>
<pre><code>class MyDenseLayer(tf.keras.Model):
def __init__(self, num_outputs):
super(MyDe... | 867 |
keras | Keras Custom Loss | https://stackoverflow.com/questions/52661518/keras-custom-loss | <p>I am kinda new to keras. I managed to build a network which has two outputs:</p>
<pre><code>q_dot_P : <tf.Tensor 'concatenate_1/concat:0' shape=(?, 7) dtype=float32>
q_dot_N : <tf.Tensor 'concatenate_2/concat:0' shape=(?, 10) dtype=float32>
</code></pre>
<p><a href="https://i.sstatic.net/HhJB1.png" rel... | <p>You could define your loss function as follows:</p>
<pre><code>import keras.backend as K
nN = 10
nP = 7
def custom_loss(y_true, y_pred):
q_dot_P = ... # Extract q_dot_P from y_pred
q_dot_N = ... # Extract q_dot_N from y_pred
epsilon = ... # Your epsilon here
zeros = K.zeros((nP, nN), dtype='f... | 868 |
keras | What is the difference between keras and keras-gpu? | https://stackoverflow.com/questions/52988311/what-is-the-difference-between-keras-and-keras-gpu | <p>I am setting up my computer to run DL with a GPU and I couldn't find info on whether one should install keras or keras-gpu. Currently I have it running with conda and keras using tensorflow-gpu as backend. What would be the difference if I switch keras to keras-gpu? </p>
| <p>this is a paragraph borrowed from Wikipedia:<br>
Keras was conceived to be an interface rather than a standalone machine-learning framework. It offers a higher-level, more intuitive set of abstractions that make it easy to develop deep learning models regardless of the computational backend used.<br>
<a href="https:... | 869 |
keras | ModuleNotFoundError: No module named 'keras' Can't import keras | https://stackoverflow.com/questions/65682994/modulenotfounderror-no-module-named-keras-cant-import-keras | <p>I have tried reinstalling anaconda. I also tried uninstalling and reinstalling keras.
I have tensorflow 2.3.0 and keras 2.4.3 installed. But I just can't seem to be able to import keras.
This is my import statement.</p>
<pre><code>from keras.models import Sequential
from keras.layers import Dense, LSTM
from pandas ... | <p>With tensorflow 2.X keras is a part of tensorflow</p>
<p>maybe try:</p>
<pre><code>from tensorflow import keras
</code></pre>
<p>and remove keras
Its not so good too run keras and tensorflow in one enviroment</p>
| 870 |
keras | Importing keras | https://stackoverflow.com/questions/53689722/importing-keras | <p>I'm trying to import keras and the code returns an error about tensorflow.</p>
<pre><code>import numpy
import matplotlib.pyplot as plt
import pandas
import math
from keras.models import Sequential
from keras.layers import Dense
</code></pre>
<p>and the error says:</p>
<pre><code>Using TensorFlow backend.
Tracebac... | <p>It seems like tensorflow is not found. You need to install tensorflow in order to use keras library.</p>
<p>If you already installed tensorflow, try to uninstall and install it again.</p>
<pre><code> sudo pip3 uninstall tensorflow
pip3 install --upgrade tensorflow
</code></pre>
<p>You can verify the insta... | 871 |
keras | Trouble installing keras | https://stackoverflow.com/questions/74640526/trouble-installing-keras | <p>I have a problem with keras; I've installed it once but somehow I cannot import it anymore since I recently installed some other packages. If I want to import keras, I get the following error (among many other warnings etc.):</p>
<pre><code>ModuleNotFoundError: No module named 'tensorflow.tsl'
</code></pre>
<p>I tri... | <p>You need to upgrade <code>Tensorflow</code> or downgrade <code>keras</code></p>
<pre><code>pip install keras==2.8
</code></pre>
<p>and do the same for the other two libraries</p>
| 872 |
keras | How to tell Keras stop training based on loss value? | https://stackoverflow.com/questions/37293642/how-to-tell-keras-stop-training-based-on-loss-value | <p>Currently I use the following code:</p>
<pre><code>callbacks = [
EarlyStopping(monitor='val_loss', patience=2, verbose=0),
ModelCheckpoint(kfold_weights_path, monitor='val_loss', save_best_only=True, verbose=0),
]
model.fit(X_train.astype('float32'), Y_train, batch_size=batch_size, nb_epoch=nb_epoch,
... | <p>I found the answer. I looked into Keras sources and find out code for EarlyStopping. I made my own callback, based on it:</p>
<pre><code>class EarlyStoppingByLossVal(Callback):
def __init__(self, monitor='val_loss', value=0.00001, verbose=0):
super(Callback, self).__init__()
self.monitor = monit... | 873 |
keras | What values are returned from model.evaluate() in Keras? | https://stackoverflow.com/questions/51299836/what-values-are-returned-from-model-evaluate-in-keras | <p>I've got multiple outputs from my model from multiple Dense layers. My model has <code>'accuracy'</code> as the only metric in compilation. I'd like to know the loss and accuracy for each output. This is some part of my code.</p>
<pre><code>scores = model.evaluate(X_test, [y_test_one, y_test_two], verbose=1)
</code... | <p>Quoted from <a href="https://keras.io/api/models/model_training_apis/#evaluate-method" rel="noreferrer"><code>evaluate()</code> method documentation</a>:</p>
<blockquote>
<p><strong>Returns</strong></p>
<p>Scalar test loss (if the model has a single output and no metrics) or
list of scalars (if the model has multipl... | 874 |
keras | Getting worse result using keras 2 than keras 1 | https://stackoverflow.com/questions/43637515/getting-worse-result-using-keras-2-than-keras-1 | <p>I ran the same code (with the same data) on CPU first using keras 1.2.0 and then keras 2.0.3 in both codes keras is with TensorFlow backend and also I used sklearn for model selection, plus pandas to read data. </p>
<p>I was surprised when I got the MSE(Mean squared error) of 42 using keras 2.0.3 and 21 using keras... | <p>Is really the MSE increased, or is it the <em>loss</em>? If you use regularizers, this may not be the same (even when using <code>mean_squared_error</code> as loss function), since the regularizer gives a <a href="https://keras.io/regularizers/" rel="nofollow noreferrer">penalty to the loss</a>.</p>
<p>I think earl... | 875 |
keras | Convert Keras-Fuctional-API into a Keras Subclassed Model | https://stackoverflow.com/questions/61140515/convert-keras-fuctional-api-into-a-keras-subclassed-model | <p>I'm relatively new to Keras and Tensorflow and I want to learn the basic implementations. For this I want to build a model that can learn/detect/predict handwritten digits, therefore I use the MNIST-dataset from Keras. I already created this model with the Keras Functional API and everything works fine. Now I wanted... | <p>Actually you don't need to implement Input in the call method as you are passing data directly to the subclass. I updated the code and it works well as expected. Please check below.</p>
<pre><code>#Create a keras-subclassing-model:
class MyModel(tf.keras.Model):
def __init__(self):
super(MyModel, self)... | 876 |
keras | What do I need K.clear_session() and del model for (Keras with Tensorflow-gpu)? | https://stackoverflow.com/questions/50895110/what-do-i-need-k-clear-session-and-del-model-for-keras-with-tensorflow-gpu | <p><strong><em>What I am doing</em></strong><br>
I am training and using a convolutional neuron network (CNN) for image-classification using Keras with Tensorflow-gpu as backend.</p>
<p><strong><em>What I am using</em></strong><br>
- PyCharm Community 2018.1.2<br>
- both Python 2.7 and 3.5 (but not both at a time)<br>... | <p><code>K.clear_session()</code> is useful when you're creating multiple models in succession, such as during hyperparameter search or cross-validation. Each model you train adds nodes (potentially numbering in the thousands) to the graph. TensorFlow executes the entire graph whenever you (or Keras) call <code>tf.Sess... | 877 |
keras | PyCharm can't find Keras | https://stackoverflow.com/questions/39523550/pycharm-cant-find-keras | <p>I'm trying to add Keras module into PyCharm. Keras is installed into <code>/usr/local/lib/python2.7/site-packages/Keras-1.0.8-py2.7.egg</code>.</p>
<p>PyCharm interpreter settings looks like that:</p>
<p><a href="https://i.sstatic.net/WKhcW.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/WKhcW.png" ... | <p>Check that the version of python you are utilizing is matched with the python version the Keras uses.</p>
<ul>
<li>Check your default python version by running this command in your cmd or terminal: <code>python --version</code></li>
<li>Check your python version in PyCharm Interpreter by <code>File > Settings &... | 878 |
keras | ModuleNotFoundError: No module named 'keras' | https://stackoverflow.com/questions/52174530/modulenotfounderror-no-module-named-keras | <p>I can't import <code>Keras</code> in PyCharm IDE on a Mac. I have tried installing and uninstalling Keras using both <code>pip</code>, <code>pip3</code>, <code>conda</code>, and easy install, but none worked. I have tried changing interpreters (Python 2.7 and 3.6) but neither worked.</p>
<p>In a terminal, when I ru... | <p>I think this has a relation with the environment the <code>pycharm</code> using
try to install Keras using <code>pycharm</code> terminal </p>
<p>in pycharm terminal apply the following </p>
<pre><code>pip install Keras
</code></pre>
| 879 |
keras | Anaconda Keras Installation issue | https://stackoverflow.com/questions/50784067/anaconda-keras-installation-issue | <p>I am trying to install keras using my conda environment. I have been instructed to install the keras with Tensorflow backend using the following command:</p>
<blockquote>
<p>install -c hesi_m keras</p>
</blockquote>
<p>But the problem is it downloads some packages and then errors outs follows:</p>
<pre><code>Do... | <p>When in doubt, try installing via pip:</p>
<p>Go into your environment where you have TensorFlow installed and run this:</p>
<pre><code>pip install keras
</code></pre>
| 880 |
keras | Loading model with custom loss + keras | https://stackoverflow.com/questions/48373845/loading-model-with-custom-loss-keras | <p>In Keras, if you need to have a custom loss with additional parameters, we can use it like mentioned on <a href="https://datascience.stackexchange.com/questions/25029/custom-loss-function-with-additional-parameter-in-keras">https://datascience.stackexchange.com/questions/25029/custom-loss-function-with-additional-pa... | <p>Yes, there is! custom_objects expects the exact function that you used as loss function (the inner one in your case):</p>
<pre><code>model = load_model(modelFile, custom_objects={ 'loss': penalized_loss(noise) })
</code></pre>
<p>Unfortunately keras won't store in the model the value of noise, so you need to feed ... | 881 |
keras | Installed Keras with pip3, but getting the "No Module Named keras" error | https://stackoverflow.com/questions/54050581/installed-keras-with-pip3-but-getting-the-no-module-named-keras-error | <p>I am Creating a leaf Identification Classifier using the CNN, the Keras and the Tensorflow backends on Windows. I have installed Anaconda, Tensorflow, numpy, scipy and keras.</p>
<p>I installed keras using pip3:</p>
<pre><code>C:\> pip3 list | grep -i keras
Keras 2.2.4
Keras-Applications 1.0.6
Ke... | <p>Installing Anaconda and then install packages with pip seams like confusing the goal of Anaconda(or any other package management tools)</p>
<p>Anaconda is there to help you organize your environments and their dependences.</p>
<p>Assuming you have conda on your system path, Do:</p>
<p>Update conda</p>
<pre><cod... | 882 |
keras | Keras Version Error | https://stackoverflow.com/questions/48211904/keras-version-error | <p>I am working on Udacity Self-driving Car project which teaches a car to run autonomously(Behavior Clonning).</p>
<p>I am getting a weird Unicode error.</p>
<p>The Error Stated is as follows:</p>
<blockquote>
<p>(dl) Vidits-MacBook-Pro-2:BehavioralClonning-master ViditShah$ python drive.py model.h5
Using Tens... | <p>You are getting this error because it seems that the model you are attempting to load was trained and saved in a previous version of Keras than the one you are using, as suggested by:</p>
<blockquote>
<p>You are using Keras version b'2.1.2' , but the model was built using b'1.2.1' Traceback (most recent call last... | 883 |
keras | Pytorch vs. Keras: Pytorch model overfits heavily | https://stackoverflow.com/questions/50079735/pytorch-vs-keras-pytorch-model-overfits-heavily | <p>For several days now, I'm trying to replicate my keras training results with pytorch. Whatever I do, the pytorch model will overfit far earlier and stronger to the validation set then in keras. For pytorch I use the same XCeption Code from <a href="https://github.com/Cadene/pretrained-models.pytorch" rel="noreferrer... | <p>it may be because type of weight initialization you are using
otherwise this should not happen
try with same initializer in both the models</p>
| 884 |
keras | How can I print the values of Keras tensors? | https://stackoverflow.com/questions/43448029/how-can-i-print-the-values-of-keras-tensors | <p>I am implementing own Keras loss function. How can I access tensor values?</p>
<p>What I've tried</p>
<pre><code>def loss_fn(y_true, y_pred):
print y_true
</code></pre>
<p>It prints</p>
<pre><code>Tensor("target:0", shape=(?, ?), dtype=float32)
</code></pre>
<p>Is there any Keras function to access <code>y_... | <p>Keras' backend has <code>print_tensor</code> which enables you to do this. You can use it this way:</p>
<pre><code>import keras.backend as K
def loss_fn(y_true, y_pred):
y_true = K.print_tensor(y_true, message='y_true = ')
y_pred = K.print_tensor(y_pred, message='y_pred = ')
...
</code></pre>
<p>The f... | 885 |
keras | Keras: model.predict for a single image | https://stackoverflow.com/questions/43017017/keras-model-predict-for-a-single-image | <p>I'd like to make a prediction for a single image with Keras. I've trained my model so I'm just loading the weights. </p>
<pre><code>from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout,... | <p>Since you trained your model on mini-batches, your input is a tensor of shape <code>[batch_size, image_width, image_height, number_of_channels]</code>.</p>
<p>When predicting, you have to respect this shape even if you have only one image. Your input should be of shape: <code>[1, image_width, image_height, number_o... | 886 |
keras | Keras - Reuse weights from a previous layer - converting to keras tensor | https://stackoverflow.com/questions/39564579/keras-reuse-weights-from-a-previous-layer-converting-to-keras-tensor | <p>I am trying to reuse the weight matrix from a previous layer. As a toy example I want to do something like this:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from keras.layers import Dense, Input
from keras.layers import merge
from keras import backend as K
from keras.models import Model
... | <p>It seems that you want to share weights between layers.
I think You can use denselayer as shared layer for inputs and inputs2.</p>
<pre><code>merge1=dense_layer(inputs2)
</code></pre>
<p>Do check out shared layers @ <a href="https://keras.io/getting-started/functional-api-guide/#shared-layers" rel="nofollow norefe... | 887 |
keras | How do I check if keras is using gpu version of tensorflow? | https://stackoverflow.com/questions/44544766/how-do-i-check-if-keras-is-using-gpu-version-of-tensorflow | <p>When I run a keras script, I get the following output:</p>
<pre><code>Using TensorFlow backend.
2017-06-14 17:40:44.621761: W
tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow
library wasn't compiled to use SSE4.1 instructions, but these are
available on your machine and could speed up CPU computa... | <p>You are using the GPU version. You can list the available tensorflow devices with (also check <a href="https://stackoverflow.com/questions/38559755/how-to-get-current-available-gpus-in-tensorflow">this</a> question):</p>
<pre><code>from tensorflow.python.client import device_lib
print(device_lib.list_local_devices(... | 888 |
keras | Keras + IndexError | https://stackoverflow.com/questions/33380897/keras-indexerror | <p>I am very new to keras. Trying to build a binary classifier for an NLP task. (My code is motivated from imdb example - <a href="https://github.com/fchollet/keras/blob/master/examples/imdb_cnn.py" rel="noreferrer">https://github.com/fchollet/keras/blob/master/examples/imdb_cnn.py</a>)</p>
<p>Below is my code snippet... | <p>You need to Pad the imdb sequences you are using, add those lines:</p>
<pre><code>from keras.preprocessing import sequence
Train_X = sequence.pad_sequences(Train_X, maxlen=maxlen)
Test_X = sequence.pad_sequences(Test_X, maxlen=maxlen)
</code></pre>
<p>Before building the actual model.</p>
| 889 |
keras | keras vs. tensorflow.python.keras - which one to use? | https://stackoverflow.com/questions/48893528/keras-vs-tensorflow-python-keras-which-one-to-use | <p>Which one is the recommended (or more future-proof) way to use Keras?</p>
<p>What are the advantages/disadvantages of each?</p>
<p>I guess there are more differences than simply saving one <code>pip install</code> step and writing <code>tensorflow.python.keras</code> instead of <code>keras</code>.</p>
| <p><a href="https://www.tensorflow.org/api_docs/python/tf/keras" rel="noreferrer"><code>tensorflow.python.keras</code></a> is just a bundle of keras with a single backend inside <code>tensorflow</code> package. This allows you to start using keras by installing just <code>pip install tensorflow</code>.</p>
<p><a href=... | 890 |
keras | Multiple outputs in Keras | https://stackoverflow.com/questions/44036971/multiple-outputs-in-keras | <p>I have a problem which deals with predicting two outputs when given a vector of predictors.
Assume that a predictor vector looks like <code>x1, y1, att1, att2, ..., attn</code>, which says <code>x1, y1</code> are coordinates and <code>att's </code> are the other attributes attached to the occurrence of <code>x1, y1<... | <pre><code>from keras.models import Model
from keras.layers import *
#inp is a "tensor", that can be passed when calling other layers to produce an output
inp = Input((10,)) #supposing you have ten numeric values as input
#here, SomeLayer() is defining a layer,
#and calling it with (inp) produces the output t... | 891 |
keras | Why does prediction needs batch size in Keras? | https://stackoverflow.com/questions/37911321/why-does-prediction-needs-batch-size-in-keras | <p>In Keras, to predict class of a datatest, the <code>predict_classes()</code> is used.</p>
<p>For example:</p>
<pre><code>classes = model.predict_classes(X_test, batch_size=32)
</code></pre>
<p>My question is, I know the usage of <code>batch_size</code> in training, but why does it need a <code>batch_size</code> f... | <p>Keras can predict multiple values at the same time, like if you input a vector of 100 elements, Keras can compute one prediction for each element, giving 100 outputs. This computation can also be done in batches, defined by the batch_size.</p>
<p>This is just in case you cannot fit all the data in the CPU/GPU RAM a... | 892 |
keras | Causal padding in keras | https://stackoverflow.com/questions/52578950/causal-padding-in-keras | <p>Can someone explain the intuition behind 'causal' padding in Keras. Is there any particular application where this can be used?</p>
<p>The keras manual says this type of padding results in dilated convolution. What exactly it means by 'dilated' convolution?</p>
| <p>This is a great concise explanation about what is "causal" padding:</p>
<blockquote>
<p>One thing that Conv1D does allow us to specify is padding="causal". This simply pads the layer's input with zeros in the front so that we can also predict the values of early time steps in the frame:</p>
</blockquote>
<p><a h... | 893 |
keras | Trouble importing Keras | https://stackoverflow.com/questions/59548311/trouble-importing-keras | <p>Here is the complete code<br>
top part runs fine till i import keras.
I have tried installing and uninstalling keras, however the error is still there</p>
<h1>Classification template</h1>
<pre><code># Importing the libraries
import numpy as my
import matplotlib.pyplot as plt
import pandas as pd
# Importing the d... | <blockquote>
<p>AttributeError: module 'tensorflow.python.keras.backend' has no attribute 'get_graph'</p>
</blockquote>
<p>Solution (as found in comments) was to install keras version 2.2.4 </p>
<p>e.g:</p>
<pre><code>pip install 'keras==2.2.4'
</code></pre>
<p>if you are above that version, you may try using thi... | 894 |
keras | Keras mixture of models | https://stackoverflow.com/questions/40074730/keras-mixture-of-models | <p>Is it possible to implement MLP mixture of expert methodology in Keras?
Could you please guide me by a simple code in Keras for a binary problem with 2 experts.</p>
<p>It needs to define a cost function like this:</p>
<pre class="lang-python prettyprint-override"><code>g = gate.layers[-1].output
o1 = mlp1.layers[-... | <h2>Model</h2>
<p>You can definitely model such a structure in Keras, with <a href="https://keras.io/getting-started/sequential-model-guide/#the-merge-layer" rel="noreferrer">a merge layer</a>, which enables you to combine different inputs.
Here is a <a href="http://sscce.org/" rel="noreferrer">SSCCE</a> that you'll h... | 895 |
keras | How to Properly Combine TensorFlow's Dataset API and Keras? | https://stackoverflow.com/questions/46135499/how-to-properly-combine-tensorflows-dataset-api-and-keras | <p>Keras' <code>fit_generator()</code> model method expects a generator which produces tuples of the shape (input, targets), where both elements are NumPy arrays. <a href="https://keras.io/models/model/" rel="noreferrer">The documentation</a> seems to imply that if I simply wrap a <a href="https://www.tensorflow.org/pr... | <p>There is indeed a more efficient way to use <code>Dataset</code> without having to convert the tensors into numpy arrays. However, it is not (yet?) on the official documentation. From the release note, it's a feature introduced in Keras 2.0.7. You may have to install keras>=2.0.7 in order to use it.</p>
<pre><code>... | 896 |
keras | I can't import Keras | https://stackoverflow.com/questions/76937613/i-cant-import-keras | <p>I am using Anaconda and already have TensorFlow and Keras imported, and I tried to import keras using the following code</p>
<pre><code>import keras as ks
</code></pre>
<p>but it didn't work instead I got the follwing error:</p>
<pre><code> AttributeError Traceback (most recent call las... | <p><a href="https://github.com/keras-team/keras/issues/17541" rel="nofollow noreferrer">This keras bug</a> says that Keras isn't ready for python 3.11 yet. I suggest downgrading to python 3.10.</p>
| 897 |
keras | How to switch Backend with Keras (from TensorFlow to Theano) | https://stackoverflow.com/questions/42177658/how-to-switch-backend-with-keras-from-tensorflow-to-theano | <p>I tried to switch Backend with Keras (from TensorFlow to Theano) but did not manage.
I followed the temps described <a href="https://keras.io/backend/" rel="noreferrer">here</a> but it doesn't work. I created a keras.json in the keras' directory (as it did not exist) but it doesn't change anything when I import it f... | <p>Create a <code>.keras</code> (note the <code>.</code> in front) folder in you home directory and put the <code>keras.json</code> file there.</p>
<p>For example, <code>/home/DaniPaniz/.keras/keras.json</code> (or <code>~/.keras/keras.json</code> in short) if you are on a UNIX like system (MacOS X, Linux, *BSD). On W... | 898 |
keras | Keras Model nested inside of Custom Keras Layer | https://stackoverflow.com/questions/54752965/keras-model-nested-inside-of-custom-keras-layer | <p>I would like to build a Keras model which uses a numerical SPICE-like method for forward propagation. Since SPICE problems are not analytically-solvable, I have built the following class. The class works very well to implement prediction (numerical forward prorogation) and determine gradients (analytically).</p>
<p... | <p>In short, I was unable to accomplish this using Keras. This is the best solution I found:</p>
<p>I recreated the network using Tensorflow low-level API and defined two loss functions:</p>
<ul>
<li>Loss1: Mean square of error in the feed-forward path (in other words, if loss1 was high, the SPICE solution was bad)</... | 899 |
spaCy | spaCy: Can't find model 'en_core_web_sm' on windows 10 and Python 3.5.3 :: Anaconda custom (64-bit) | https://stackoverflow.com/questions/54334304/spacy-cant-find-model-en-core-web-sm-on-windows-10-and-python-3-5-3-anaco | <p>What is the difference between <code>spacy.load('en_core_web_sm')</code> and <code>spacy.load('en')</code>? <a href="https://stackoverflow.com/questions/50487495/what-is-difference-between-en-core-web-sm-en-core-web-mdand-en-core-web-lg-mod">This link</a> explains different model sizes. But I am still not clear how ... | <p>The answer to your misunderstanding is a Unix concept, <strong>softlinks</strong> which we could say that in Windows are similar to shortcuts. Let's explain this.</p>
<p>When you <code>spacy download en</code>, spaCy tries to find the best <strong>small</strong> model that matches your spaCy distribution. The small ... | 900 |
spaCy | How to verify installed spaCy version? | https://stackoverflow.com/questions/47350942/how-to-verify-installed-spacy-version | <p>I have installed <strong>spaCy</strong> with python for my NLP project.</p>
<p>I have installed that using <code>pip</code>. How can I verify installed spaCy version?</p>
<p>using </p>
<pre><code>pip install -U spacy
</code></pre>
<p>What is command to verify installed spaCy version?</p>
| <p>You can also do <code>python -m spacy info</code>. If you're updating an existing installation, you might want to run <code>python -m spacy validate</code>, to check that the models you already have are compatible with the version you just installed.</p>
| 901 |
spaCy | Spacy nlp = spacy.load("en_core_web_lg") | https://stackoverflow.com/questions/56470403/spacy-nlp-spacy-loaden-core-web-lg | <p>I already have spaCy downloaded, but everytime I try the <code>nlp = spacy.load("en_core_web_lg")</code>, command, I get this error: </p>
<p><code>OSError: [E050] Can't find model 'en_core_web_lg'. It doesn't seem to be a shortcut link, a Python package or a valid path to a data directory.</code></p>
<p>I already ... | <p>For a Linux system run the below code in terminal if you would be using a virtual environment else skip first and second command :</p>
<pre><code>python -m venv .env
source .env/bin/activate
pip install -U spacy
python -m spacy download en_core_web_lg
</code></pre>
<p>The downloaded language model can be found at ... | 902 |
spaCy | spaCy and spaCy models in setup.py | https://stackoverflow.com/questions/53383352/spacy-and-spacy-models-in-setup-py | <p>In my project I have spaCy as a dependency in my <code>setup.py</code>, but I want to add also a default model.</p>
<p>My attempt so far has been:</p>
<pre><code>install_requires=['spacy', 'en_core_web_sm'],
dependency_links=['https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.0.0/en_core... | <p>You can use pip's recent support for PEP 508 URL requirements:</p>
<pre><code>install_requires=[
'spacy',
'en_core_web_sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.0.0/en_core_web_sm-2.0.0.tar.gz',
],
</code></pre>
<p>Note that this requires you to build your project wi... | 903 |
spaCy | How to get the dependency tree with spaCy? | https://stackoverflow.com/questions/36610179/how-to-get-the-dependency-tree-with-spacy | <p>I have been trying to find how to get the dependency tree with spaCy but I can't find anything on how to get the tree, only on <a href="https://spacy.io/usage/examples#subtrees" rel="noreferrer">how to navigate the tree</a>.</p>
| <p>It turns out, the tree is available <a href="https://spacy.io/docs#token-navigating" rel="noreferrer">through the tokens</a> in a document.</p>
<p>Would you want to find the root of the tree, you can just go though the document:</p>
<pre><code>def find_root(docu):
for token in docu:
if token.head is to... | 904 |
spaCy | Spacy BILOU format to spacy json format | https://stackoverflow.com/questions/64675654/spacy-bilou-format-to-spacy-json-format | <p>i am trying to upgrade my spacy version to nightly especially for using spacy transformers</p>
<p>so i converted spacy simple train datasets of format like</p>
<p><code>td = [["Who is Shaka Khan?", {"entities": [(7, 17, "FRIENDS")]}],["I like London.", {"entities": [... | <p>You can skip intermediate JSON step and convert the annotation directly to <code>DocBin</code>.</p>
<pre class="lang-py prettyprint-override"><code>import spacy
from spacy.training import Example
from spacy.tokens import DocBin
td = [["Who is Shaka Khan?", {"entities": [(7, 17, "FRIENDS&quo... | 905 |
spaCy | Add/remove custom stop words with spacy | https://stackoverflow.com/questions/41170726/add-remove-custom-stop-words-with-spacy | <p>What is the best way to add/remove stop words with spacy? I am using <a href="https://spacy.io/docs/api/token" rel="noreferrer"><code>token.is_stop</code></a> function and would like to make some custom changes to the set. I was looking at the documentation but could not find anything regarding of stop words. Thanks... | <p>You can edit them before processing your text like this (see <a href="https://github.com/explosion/spaCy/issues/364" rel="noreferrer">this post</a>):</p>
<pre><code>>>> import spacy
>>> nlp = spacy.load("en")
>>> nlp.vocab["the"].is_stop = False
>>> nlp.vocab["definitelynotastopw... | 906 |
spaCy | Anaconda - JupyterLab - spaCy : "No module named spacy" in terminal | https://stackoverflow.com/questions/66969484/anaconda-jupyterlab-spacy-no-module-named-spacy-in-terminal | <p>I'm using Anaconda and I'm trying to install spaCy.</p>
<p>At this point:
<code>python -m spacy download fr_core_news_sm</code></p>
<p>I get stuck with the "no module named spacy" error.</p>
<p>Don't understand what I'm doing wrong.</p>
<p>Thanks,</p>
| <p>You have to install spaCy before you use it to download a model. You can use the <a href="https://spacy.io/usage" rel="nofollow noreferrer">install helper</a> to guide you on how to this, for example:</p>
<pre><code>conda install -c conda-forge spacy
python -m spacy download fr_core_news_sm
</code></pre>
| 907 |
spaCy | translate text using spacy | https://stackoverflow.com/questions/51311392/translate-text-using-spacy | <p>Is it possible to use spacy to translate this sentence into some other language, for e.g. french?</p>
<pre><code>import spacy
nlp = spacy.load('en')
doc = nlp(u'This is a sentence.')
</code></pre>
<p>If spacy is not the right tool for this, then which (Free and open source) python library can translate text? </p>
| <p>The comment to your question is correct.
You cannot use spaCy to translate text.
A good open-source solution could be <a href="https://pypi.org/project/translate/" rel="noreferrer">this</a> library.
Sample code:</p>
<pre><code>from translate import Translator
translator = Translator(from_lang='el', to_lang='en')
tra... | 908 |
spaCy | Spacy-nightly (spacy 2.0) issue with "thinc.extra.MaxViolation has wrong size" | https://stackoverflow.com/questions/46544808/spacy-nightly-spacy-2-0-issue-with-thinc-extra-maxviolation-has-wrong-size | <p>After apparently successful installation of spacy-nightly (spacy-nightly-2.0.0a14) and english model (en_core_web_sm) I was still receiving error message during attempt to run it</p>
<pre><code>import spacy
nlp = spacy.load('en_core_web_sm')
ValueError: thinc.extra.search.MaxViolation has the wrong size, try recom... | <p>Issue is probably with thinc package, spacy-nightly needs thinc<6.9.0,>=6.8.1 but version 6.8.2 is causing some issues --> way how <strong>to solve i</strong>t is run command bellow <strong>before</strong> you install spacy-nightly</p>
<pre><code>pip install thinc==6.8.1
</code></pre>
<p>After this everything w... | 909 |
spaCy | Noun phrases with spacy | https://stackoverflow.com/questions/33289820/noun-phrases-with-spacy | <p>How can I extract noun phrases from text using spacy?<br>
I am not referring to part of speech tags.
In the documentation I cannot find anything about noun phrases or regular parse trees.</p>
| <p>If you want base NPs, i.e. NPs without coordination, prepositional phrases or relative clauses, you can use the noun_chunks iterator on the Doc and Span objects:</p>
<pre><code>>>> from spacy.en import English
>>> nlp = English()
>>> doc = nlp(u'The cat and the dog sleep in the basket nea... | 910 |
spaCy | Unable to install spacy using pip install spacy | https://stackoverflow.com/questions/57335852/unable-to-install-spacy-using-pip-install-spacy | <p>I attempt to install spacy in my <code>Python</code> using <code>conda install spacy</code> at <code>anaconda</code> prompt.
However, the prompt returns a lot of conflicts.
Some of them are</p>
<pre><code>Package lxml conflicts for:
anaconda==2019.07=py3_0 -> lxml==4.3.4=py3h1350720_0
Package openpyxl conflic... | <p>According to <a href="https://spacy.io/usage" rel="nofollow noreferrer">https://spacy.io/usage</a>, you can install <code>spacy</code> using <code>conda</code> command as:</p>
<pre><code>conda install -c conda-forge spacy
</code></pre>
| 911 |
spaCy | Extract verb phrases using Spacy | https://stackoverflow.com/questions/47856247/extract-verb-phrases-using-spacy | <p>I have been using Spacy for noun chunks extraction using Doc.noun_chunks property provided by Spacy.
How could I extract verb phrases from input text using Spacy library (of the form 'VERB ? ADV * VERB +' )?</p>
| <p>This might help you.</p>
<pre><code>from __future__ import unicode_literals
import spacy,en_core_web_sm
import textacy
nlp = en_core_web_sm.load()
sentence = 'The author is writing a new book.'
pattern = r'<VERB>?<ADV>*<VERB>+'
doc = textacy.Doc(sentence, lang='en_core_web_sm')
lists = textacy.ext... | 912 |
spaCy | Installing spacy | https://stackoverflow.com/questions/51996739/installing-spacy | <p>I am trying to install spacy. I am using python 2 and I saw a post <a href="https://stackoverflow.com/questions/43370851/failed-building-wheel-for-spacy">Failed building wheel for spacy</a> as I am having the same issue.</p>
<p>I ran <code>pip install --no-cache-dir spacy</code> but still I am getting </p>
<pre><c... | <p>First off, this (dependencies) is the worst part of Python by far and everyone struggles with this.</p>
<p>I notice that you are using pip, but the command that is erring shows your python interpreter is anaconda. Can you do <code>conda install spacy</code> instead of <code>pip install spacy</code>?</p>
<p>If you ... | 913 |
spaCy | Can't import spacy | https://stackoverflow.com/questions/67890652/cant-import-spacy | <p>i've been trying to import <strong>spacy</strong> but everytime an error appears as a result.
I used this line to install the package :</p>
<pre><code>conda install -c conda-forge spacy
</code></pre>
<p>then i tried to <strong>import spacy</strong> and it gives me this error:</p>
<pre><code>------------------------... | <p>The problem is that the file you are working in is named <code>spacy.py</code>, which is interfering with the spacy module. So you should rename your file to something other than "spacy".</p>
| 914 |
spaCy | Spacy 1 vs spacy 2 (spacy-nightly) Have they changed data-model? Why similarity calculation does not work? | https://stackoverflow.com/questions/46608372/spacy-1-vs-spacy-2-spacy-nightly-have-they-changed-data-model-why-similarity | <p>I understand that spacy 2 alpha (or called spacy-nightly) is building vectors of words based on their context - so I do understand differences between values of similarity for words in nlp('apples oranges') and separated nlp('apples') and nlp('oranges') (and of course I am using different models for spacy 1 and spac... | <p>Well here it goes an answer with super delay.</p>
<p>The short answer is Yes, Spacy v2 introduces a lot of changes, and brand new models so you might experience some weird situations in case you don't update the models too and re-train your own models.</p>
<p>A brief quote from <a href="https://github.com/explosion/... | 915 |
spaCy | Phrasematcher Spacy error | https://stackoverflow.com/questions/48293778/phrasematcher-spacy-error | <p>I am using Phrasematcher in Spacy and getting an error like this - </p>
<pre><code>matcher = PhraseMatcher(nlp.vocab)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "spacy/matcher.pyx", line 505, in spacy.matcher.PhraseMatcher.__init__ (spacy/matcher.cpp:11371)
TypeErro... | <p>Perhaps your version of Spacy is out of date with the documentation? I get the same error on a machine running an older version of Spacy, and PhraseMatcher appears to be new in 2.0.0+. </p>
<p>See: <a href="https://spacy.io/usage/v2#migrating-matcher" rel="nofollow noreferrer">https://spacy.io/usage/v2#migrating-ma... | 916 |
spaCy | Spacy linking not working | https://stackoverflow.com/questions/50399260/spacy-linking-not-working | <p>I am using rasa.ai to build a bot. So far it was working fine but this morning I installed this <a href="https://github.com/JustinaPetr/Weatherbot_Tutorial/blob/master/Video%20files/requirements.txt" rel="nofollow noreferrer">requirement</a> , then installed Spacy with below command.</p>
<pre><code>python -m spacy ... | <p>Turns out the <a href="https://github.com/JustinaPetr/Weatherbot_Tutorial/blob/master/Video%20files/requirements.txt" rel="nofollow noreferrer">requirement</a> file is getting an older version of <code>Spacy</code>. So, I had to so <code>pip install rasa_nlu[spacy]</code> to get the latest <code>Spacy</code> (>2). T... | 917 |
spaCy | python -m spacy download en_core_web_sm fails using spacy 3.0.3 | https://stackoverflow.com/questions/66586400/python-m-spacy-download-en-core-web-sm-fails-using-spacy-3-0-3 | <p>Why am I getting this error <code>AttributeError: module 'srsly' has no attribute 'read_yaml'</code></p>
<p>when I attempt <code>python -m spacy download en_core_web_sm</code></p>
<p>I've been following the instructions here <a href="https://spacy.io/usage" rel="nofollow noreferrer">Install spaCy</a></p>
| <p>I was using an earlier version of <code>srsly</code> which gave me this issue. Fixed it by upgrading it to latest version</p>
<pre><code>pip install -U srsly
</code></pre>
| 918 |
spaCy | Spacy - nlp.pipe() returns generator | https://stackoverflow.com/questions/51369858/spacy-nlp-pipe-returns-generator | <p>I am using Spacy for NLP in Python. I am trying to use <code>nlp.pipe()</code> to generate a list of Spacy doc objects, which I can then analyze. Oddly enough, <code>nlp.pipe()</code> returns an object of the class <code><generator object pipe at 0x7f28640fefa0></code>. How can I get it to return a list of doc... | <p>For iterating through docs just do </p>
<pre><code>for item in docs
</code></pre>
<p>or do</p>
<pre><code> list_of_docs = list(docs)
</code></pre>
| 919 |
spaCy | Spacy 3.1 - KeyError: 'train' using spacy train command | https://stackoverflow.com/questions/68982157/spacy-3-1-keyerror-train-using-spacy-train-command | <p>I'm following this tutorial <a href="https://spacy.io/usage/training#quickstart" rel="nofollow noreferrer">https://spacy.io/usage/training#quickstart</a> in order to train a custom model of distilbert.
Everything is already installed, data are converted and the config file is ready.</p>
<p>When I launch this trainin... | <p>This part of your config is wrong.</p>
<pre><code>[training]
accumulate_gradient = 3
dev_corpus = "dev.spacy"
train_corpus = "train.spacy"
</code></pre>
<p>This is a little confusing, but the <code>corpus</code> values here are not file paths, they are the location of the value <strong>in the con... | 920 |
spaCy | Meaningless Spacy Nouns | https://stackoverflow.com/questions/66751457/meaningless-spacy-nouns | <p>I am using Spacy for extracting nouns from sentences. These sentences are grammatically poor and may contain some spelling mistakes as well.</p>
<p>Here is the code that I am using:</p>
<p><strong>Code</strong></p>
<pre><code>import spacy
import re
nlp = spacy.load("en_core_web_sm")
sentence= "HANDB... | <p>It seems you can use <a href="https://pypi.org/project/pyenchant/" rel="noreferrer"><code>pyenchant</code> library</a>:</p>
<blockquote>
<p>Enchant is used to check the spelling of words and suggest corrections for words that are miss-spelled. It can use many popular spellchecking packages to perform this task, incl... | 921 |
spaCy | spaCy nlp.pipe error with multiprocessing (n_process > 1) using spacy-langdetect | https://stackoverflow.com/questions/69120859/spacy-nlp-pipe-error-with-multiprocessing-n-process-1-using-spacy-langdetect | <p>My environment</p>
<ul>
<li>MacOS 10.15 / Debian 11</li>
<li>Python 3.8.2 / 3.8.12</li>
<li>Spacy 3.1.2</li>
<li>Spacy-langdetect 0.1.2</li>
</ul>
<p>I'm trying to use <a href="https://spacy.io/universe/project/spacy-langdetect" rel="nofollow noreferrer">spacy-langdetect</a> to add a language detection feature in my... | 922 | |
spaCy | How to fix spaCy en_training incompatible with current spaCy version | https://stackoverflow.com/questions/70880056/how-to-fix-spacy-en-training-incompatible-with-current-spacy-version | <pre><code>UserWarning: [W094] Model 'en_training' (0.0.0) specifies an under-constrained spaCy version requirement: >=2.1.4.
This can lead to compatibility problems with older versions,
or as new spaCy versions are released, because the model may say it's compatible when it's not.
Consider changing the "spa... | <p>For spacy v2 models, the under-constrained requirement <code>>=2.1.4</code> means <code>>=2.1.4,<2.2.0</code> in effect, and as a result this model will only work with spacy v2.1.x.</p>
<p>There is no way to convert a v2 model to v3. You can either use the model with v2.1.x or retrain the model from scratch... | 923 |
spaCy | Migrate trained Spacy 2 pipelines to Spacy 3 | https://stackoverflow.com/questions/67146973/migrate-trained-spacy-2-pipelines-to-spacy-3 | <p>I've been using spacy 2.3.1 until now and have trained and saved a couple of pipelines for my custom Language class. But now using spacy 3.0 and <code>spacy.load('model-path')</code> I'm facing problems such as <code>config.cfg file not found</code> and other kinds of errors.</p>
<p>Do I have to train the models fro... | <p>I'm afraid you won't be able to just migrate the trained pipelines. The pipelines trained with v2 are not compatible with v3, so you won't be able to just use <code>spacy.load</code> on them.</p>
<p>You'll have to migrate your codebase to v3, and retrain your models. You have two options:</p>
<ul>
<li>Update your tr... | 924 |
spaCy | Correcting incorrect spacy label | https://stackoverflow.com/questions/71847943/correcting-incorrect-spacy-label | <p>I try to use Spacy to syntactically parse the following sentence:</p>
<pre><code>my_sentence = "delete failed setup"
</code></pre>
<p>So I do the following:</p>
<pre><code>import spacy
nlp = spacy.load("en")
doc = nlp(my_sentence)
</code></pre>
<p>However, Spacy does not recognize this sentence ... | <pre><code>import spacy
nlp = spacy.load("en_core_web_sm")
text = ("delete the failed setup")
doc = nlp(text)
print("Noun phrases:", [chunk.text for chunk in doc.noun_chunks])
print("Verbs:", [token.lemma_ for token in doc if token.pos_ == "VERB"])
for entity in doc.e... | 925 |
spaCy | Installing spaCy - SSL Certificate Error | https://stackoverflow.com/questions/41725166/installing-spacy-ssl-certificate-error | <p>I have installed spaCy using <code>pip install spacy</code> but when trying <code>python -m spacy.en.download all</code>, I get the following error ..</p>
<p><a href="https://i.sstatic.net/XmMd8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/XmMd8.png" alt="enter image description here"></a></p>
<p... | <p>Try installing the new version in Linux. It will work.</p>
| 926 |
spaCy | Import spaCy KeyError: '__reduce_cython__' | https://stackoverflow.com/questions/78648747/import-spacy-keyerror-reduce-cython | <p>While trying to import spaCy in my jupyter notebook, I encountered this error:</p>
<pre><code>---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[8], line 7
4 import seaborn as sns
5 import matplot... | 927 | |
spaCy | Use spacy Spanish Tokenizer | https://stackoverflow.com/questions/42947733/use-spacy-spanish-tokenizer | <p>I always used spacy library with english or german. </p>
<p>To load the library I used this code:</p>
<pre><code>import spacy
nlp = spacy.load('en')
</code></pre>
<p>I would like to use the Spanish tokeniser, but I do not know how to do it, because spacy does not have a spanish model.
I've tried this</p>
<pre><c... | <p>For version till 1.6 this code works properly:</p>
<pre><code>from spacy.es import Spanish
nlp = Spanish()
</code></pre>
<p>but in version 1.7.2 a little change is necessary:</p>
<pre><code>from spacy.es import Spanish
nlp = Spanish(path=None)
</code></pre>
<p>Source:@honnibal in gitter chat</p>
| 928 |
spaCy | python - spaCy module won't import | https://stackoverflow.com/questions/44886163/python-spacy-module-wont-import | <p>I recently tried to install the spaCy module for python 3.x. The installation looks like it runs successfully (shows no errors), but when I try to import spaCy, or when I try to install spaCy models, I get the error below. I have tried installing spaCy using both <code>pip install</code> and <code>conda install</cod... | <p>I newly had the same problem and apparently, the problem is a conflict with numpy version. Just uninstall numpy and install nupmy 1.18.4:</p>
<pre><code>pip uninstall numpy
</code></pre>
<p>Then:</p>
<pre><code>pip install numpy==1.18.4
</code></pre>
<p>Of course you may use <code>conda</code> instead of <code>pip</... | 929 |
spaCy | spacy convert conllul to spacy json format | https://stackoverflow.com/questions/53318940/spacy-convert-conllul-to-spacy-json-format | <p>I get data from Universal Dependencies I work mostly with Indonesian (bahasa) so I clone the repo:</p>
<ul>
<li><a href="https://github.com/conllul/UL_Indonesian-PUD" rel="nofollow noreferrer">https://github.com/conllul/UL_Indonesian-PUD</a></li>
<li><a href="https://github.com/conllul/UL_Indonesian-GSD" rel="nofol... | <p>Ok, let's clarify things a bit, before answering your question.</p>
<p>The following statements are true:</p>
<ul>
<li>There are different ConNLL formats</li>
<li>The different formats have in common that they derive from <a href="http://www.conll.org/2018" rel="nofollow noreferrer">CoNLL</a> conference. </li>
<li... | 930 |
spaCy | How to add a Spacy model to a requirements.txt file? | https://stackoverflow.com/questions/61702357/how-to-add-a-spacy-model-to-a-requirements-txt-file | <p>I have an app that uses the Spacy model "en_core_web_sm". I have tested the app on my local machine and it works fine.</p>
<p>However when I deploy it to Heroku, it gives me this error:</p>
<p>"Can't find model 'en_core_web_sm'. It doesn't seem to be a shortcut link, a Python package or a valid path to a data dire... | <p>Ok, so after some more Googling and hunting for a solution, I found this solution that worked:</p>
<p>I downloaded the tarball from the url that @tausif shared in his answer, to my local system.</p>
<p>Saved it in the directory which had my requirements.txt file.</p>
<p>Then I added this line to my requirements.t... | 931 |
spaCy | How to fix Spacy Transformers for Spacy version 3.1 | https://stackoverflow.com/questions/71977955/how-to-fix-spacy-transformers-for-spacy-version-3-1 | <p>I'm having the following problem.
I've been trying to replicate example code from this source:
<a href="https://github.com/huggingface/transformers/issues/2986" rel="nofollow noreferrer">Github</a></p>
<p>I'm using Jupyter Lab environment on Linux and Spacy 3.1</p>
<pre><code># $ pip install spacy-transformers
# $ p... | <p><code>Doc.similarity</code> uses word vectors to calculate similarity, and Transformers models don't include them. You should use <code>en_core_web_lg</code> or another model with word vectors, or use an alternate method like a custom hook or sentence transformers.</p>
<p>For more details, see the <a href="https://s... | 932 |
spaCy | OSerror import language model spacy | https://stackoverflow.com/questions/60753705/oserror-import-language-model-spacy | <p>I'm trying to work with spacy . I need to download language model for English, Italian and Spanish.
I can't manually install the model ( because I hope to build a piece of code that is portable ) so i wrote a little function which basically is </p>
<pre><code>import os
import spacy
lang='en'
try:
mod = lang... | <p>Try installing en_core_web_sm through:</p>
<pre><code>pip3 install https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.2.5/en_core_web_sm-2.2.5.tar.gz
</code></pre>
| 933 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.