a_id
int64
7.84k
73.8M
a_body
stringlengths
61
33k
a_creation_date
stringlengths
25
32
a_last_activity_date
stringlengths
25
32
a_last_edit_date
stringlengths
25
32
a_tags
float64
q_id
int64
826
73.8M
q_body
stringlengths
61
29.9k
q_creation_date
stringlengths
25
32
q_last_activity_date
stringlengths
25
32
q_last_edit_date
stringlengths
25
32
q_tags
stringlengths
1
103
_arxiv_links
stringlengths
2
6.69k
_n_arxiv_links
int64
0
94
61,151,775
<p>This is a very good question! The reason why no fully-connected layer is used is because of a technique called Global Average Pooling, implemented via <code>nn.AdaptiveAvgPool2d(1)</code>. The benefits of this operation over fc layers were introduced in this <a href="https://arxiv.org/pdf/1512.04150.pdf" rel="nofollow noreferrer">paper</a>, including reducing the number of model parameters while preserving performance, acting as a regulariser, and modelling deep localisation information. GAP can be used in place of fc, as well as before a subsequent fc layer.</p> <p>As for why there is no softmax layer, I think that this is because they use the <code>CrossEntropyLoss</code> loss function in the backend. This function takes in raw logits and combines <code>nn.LogSoftmax()</code> and <code>nn.NLLLoss()</code> in one computation. So there is no need to perform an additional softmax function before loss evaluation.</p>
2020-04-11 03:30:09.087000+00:00
2020-04-11 03:30:09.087000+00:00
null
null
61,150,929
<p>The example from <a href="https://pytorch.org/tutorials/beginner/nn_tutorial.html" rel="nofollow noreferrer">PyTorch's official tutorial</a> has the following ConvNet. My understanding is that the output layer uses a softmax to estimate the digit an image corresponds to. Why doesnt the code have a softmax layer or fully connected layer? </p> <pre><code>model = nn.Sequential( nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1), Lambda(lambda x: x.view(x.size(0), -1)), ) opt = optim.SGD(model.parameters(), lr=lr, momentum=0.9) </code></pre>
2020-04-11 01:16:34.430000+00:00
2020-04-11 03:56:15.510000+00:00
null
pytorch
['https://arxiv.org/pdf/1512.04150.pdf']
1
31,780,675
<p>If it is not strict to using only NLTK, you can try our robust and language-independent POS tagging toolkit <a href="http://rdrpostagger.sourceforge.net/" rel="nofollow">RDRPOSTagger</a>.</p> <p>(License: GPLv2; Programming Language: Python &amp; Java)</p> <p>RDRPOSTagger obtains fast performance in both learning and tagging process. In addition, RDRPOSTagger achieves a very competitive accuracy in comparison to the state-of-the-art results. </p> <p>Updated 18/11/2015: release version 1.2 with improved tagging accuracy, especially on morphologically rich languages. See experimental results including performance speed and tagging accuracy in <a href="http://arxiv.org/abs/1412.4021" rel="nofollow">this paper</a>. </p> <p>RDRPOSTagger supports pre-trained POS and morphological tagging models for Bulgarian, Czech, Dutch, English, French, German, Hindi, Italian, Portuguese, Spanish, Swedish, Thai and Vietnamese. RDRPOSTagger also supports the pre-trained Universal POS tagging models for 40 languages.</p>
2015-08-03 06:27:38.353000+00:00
2016-05-19 08:01:12.230000+00:00
2016-05-19 08:01:12.230000+00:00
null
27,604,191
<p>I am using the nltk module in python and i am trying to use this for POS tagging different languages.</p> <p>There is a lot of information on how to train your own POS tagger in different languages - is there a database of really robust well built and tested NLTK POS taggers for different languages? (It is quite easy to export POS taggers using the pickle module)</p>
2014-12-22 14:00:29.387000+00:00
2016-05-19 08:01:12.230000+00:00
2015-08-20 19:57:38.877000+00:00
python|nlp|nltk
['http://rdrpostagger.sourceforge.net/', 'http://arxiv.org/abs/1412.4021']
2
63,602,155
<p>This problem is akin to rolling a <em>k</em>-sided die given only a <em>p</em>-sided die, without wasting randomness.</p> <p>In this sense, by Lemma 3 in &quot;<a href="https://perso.math.u-pem.fr/kloeckner.benoit/papiers/DiceSimulation.pdf" rel="nofollow noreferrer">Simulating a dice with a dice</a>&quot; by B. Kloeckner, this waste is inevitable unless &quot;every prime number dividing <em>k</em> also divides <em>p</em>&quot;. Thus, for example, if <em>p</em> is a power of 2 (and any block of random bits is the same as rolling a die with a power of 2 number of faces) and <em>k</em> has prime factors other than 2, the best you can do is get arbitrarily close to no waste of randomness, such as by batching multiple rolls of the <em>p</em>-sided die until <em>p</em>^<em>n</em> is &quot;close enough&quot; to a power of <em>k</em>.</p> <p>Let me also go over some of your concerns about regenerating random numbers:</p> <ul> <li>&quot;Reducing the period&quot;: Besides batching of bits, this concern can be dealt with in several ways: <ul> <li>Use a <a href="https://peteroupc.github.io/hqprng.html" rel="nofollow noreferrer">PRNG with a bigger &quot;period&quot;</a> (maximum cycle length).</li> <li>Add a <a href="https://peteroupc.github.io/bdshuffle.html" rel="nofollow noreferrer">Bays–Durham shuffle</a> to the PRNG's implementation.</li> <li>Use a &quot;true&quot; random number generator; this is not trivial.</li> <li>Employ <em>randomness extraction</em>, which is discussed in <a href="https://arxiv.org/abs/1502.02539" rel="nofollow noreferrer">Devroye and Gravel 2015-2020</a> and in my <a href="https://peteroupc.github.io/randextract.html" rel="nofollow noreferrer">Note on Randomness Extraction</a>. However, randomness extraction is pretty involved.</li> <li>Ignore the problem, especially if it isn't a security application or serious simulation.</li> </ul> </li> <li>&quot;Time to generate new numbers until one is in the right range&quot;: If you want unbiased random numbers, then any algorithm that does so will generally have to run forever in the worst case. Again, by Lemma 3, the algorithm will run forever in the worst case unless &quot;every prime number dividing <em>k</em> also divides <em>p</em>&quot;, which is not the case if, say, <em>k</em> is 10 and <em>p</em> is 32.</li> </ul> <p>See also the question: <a href="https://stackoverflow.com/questions/6046918/how-to-generate-a-random-integer-in-the-range-0-n-from-a-stream-of-random-bits">How to generate a random integer in the range [0,n] from a stream of random bits without wasting bits?</a>, especially my answer there.</p>
2020-08-26 16:45:54.030000+00:00
2020-11-20 15:25:37.733000+00:00
2020-11-20 15:25:37.733000+00:00
null
734,482
<p>What is the best way to constrain the values of a PRNG to a smaller range? If you use modulus and the old max number is not evenly divisible by the new max number you bias toward the <code>0</code> through <code>(old_max - new_max - 1)</code>. I assume the best way would be something like this (this is floating point, not integer math)</p> <pre><code>random_num = PRNG() / max_orginal_range * max_smaller_range </code></pre> <p>But something in my gut makes me question that method (maybe floating point implementation and representation differences?).</p> <p>The random number generator will produce consistent results across hardware and software platforms, and the constraint needs to as well.</p> <p>I was right to doubt the pseudocode above (but not for the reasons I was thinking). MichaelGG's <a href="https://stackoverflow.com/questions/734482/what-is-the-proper-method-of-constraining-a-pseduo-random-number-to-a-smaller-ran/739945#739945">answer</a> got me thinking about the problem in a different way. I can model it using smaller numbers and test every outcome. So, let's assume we have a PRNG that produces a random number between 0 and 31 and you want the smaller range to be 0 to 9. If you use modulus you bias toward 0, 1, 2, and 3. If you use the pseudocode above you bias toward 0, 2, 5, and 7. I don't think there can be a good way to map one set into the other. The best that I have come up with so far is to regenerate the random numbers that are greater than <code>old_max/new_max</code>, but that has deep problems as well (reducing the period, time to generate new numbers until one is in the right range, etc.).</p> <p>I think I may have naively approached this problem. It may be time to start some serious research into the literature (someone has to have tackled this before).</p>
2009-04-09 14:28:50.187000+00:00
2020-12-05 14:41:45.477000+00:00
2020-12-05 14:41:45.477000+00:00
language-agnostic|random
['https://perso.math.u-pem.fr/kloeckner.benoit/papiers/DiceSimulation.pdf', 'https://peteroupc.github.io/hqprng.html', 'https://peteroupc.github.io/bdshuffle.html', 'https://arxiv.org/abs/1502.02539', 'https://peteroupc.github.io/randextract.html', 'https://stackoverflow.com/questions/6046918/how-to-generate-a-random-integer-in-the-range-0-n-from-a-stream-of-random-bits']
6
65,990,556
<p>What you implemented is a quite unusual type of self-attention. It resembles <a href="https://arxiv.org/pdf/1703.03130.pdf" rel="nofollow noreferrer">the original self-attention for sequence classification</a> which was probably a partial inspiration for the <a href="https://papers.nips.cc/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf" rel="nofollow noreferrer">Attention is all you need</a> paper.</p> <p>In general, attention can be understood as a sort of probabilistic hidden state retrieval. Given some keys, you retrieve some values. In the standard <a href="https://arxiv.org/abs/1409.0473" rel="nofollow noreferrer">Bahdanau's attention</a>, the key is the decoder state and the values are the encoder states. In Transformer self-attention, are used as keys to retrieve some information from other states, i.e., every state is a key and a value at the same time. In the special case, you have implemented, you only have one key that is sort of encrypted in the <code>projection</code>. You use this single constant key to retrieve a vector from the hidden states, as a result, you only get one vector per sequence.</p> <p>What you probably want to is using the Transformer-style self-attention where each state is used as a key a gets a summary of values. For that, you can use the <a href="https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html" rel="nofollow noreferrer"><code>nn.MultiheadAttention</code> class</a> in PyTorch. In addition to what I described, it does the attention in multiple heads, so it can do a more fine-grained retrieval. Note that in your case queries, keys and values are the same tensor, i.e., the output of the Bi-LSTM.</p>
2021-02-01 09:55:27.860000+00:00
2021-02-01 09:55:27.860000+00:00
null
null
65,980,848
<p>I am trying to Implement the BiLSTM-Attention-CRF model for the NER task. I am able to perform NER tasks based on the BILSTM-CRF model (code from <a href="https://github.com/jayavardhanr/End-to-end-Sequence-Labeling-via-Bi-directional-LSTM-CNNs-CRF-Tutorial/blob/master/Named_Entity_Recognition-LSTM-CNN-CRF-Tutorial.ipynb" rel="nofollow noreferrer">here</a>) but I need to add attention to improve the performance of the model.</p> <p>Right now my model is :</p> <p>BiLSTM -&gt; Linear Layer (Hidden to tag) -&gt; CRf Layer</p> <p>The Output from the Linear layer is (seq. length x tagset size) and it is then fed into the CRF layer.</p> <p>I am trying to replace the Linear layer with Attention layer using the code below:</p> <pre><code>class SelfAttention(nn.Module): def __init__(self, hidden_dim): super().__init__() self.hidden_dim = hidden_dim self.projection = nn.Sequential( nn.Linear(hidden_dim, 64), nn.ReLU(True), nn.Linear(64, 1) ) def forward(self, encoder_outputs): batch_size = encoder_outputs.size(0) # (B, L, H) -&gt; (B , L, 1) energy = self.projection(encoder_outputs) weights = F.softmax(energy.squeeze(-1), dim=1) # (B, L, H) * (B, L, 1) -&gt; (B, H) outputs = (encoder_outputs * weights.unsqueeze(-1)).sum(dim=1) return outputs, weights </code></pre> <p>While doing so I have two issues:</p> <ul> <li>I can not make it work so that the output should come in the shape of (seq. length x tagset size) so that it can be fed into CRF Layer.</li> <li>According to this <a href="https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8922599" rel="nofollow noreferrer">paper</a>, we need to initialize and learn word-level context vector which I can not see in this implementation of the attention model.</li> </ul> <p>Kindly help me out.</p> <p>TIA</p>
2021-01-31 15:27:02.940000+00:00
2021-06-10 07:18:32.913000+00:00
null
python|pytorch|named-entity-recognition|attention-model
['https://arxiv.org/pdf/1703.03130.pdf', 'https://papers.nips.cc/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf', 'https://arxiv.org/abs/1409.0473', 'https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html']
4
53,198,053
<blockquote> <p>However I was expecting a single value per channel instead I found a 256x256 array: does it mean that the took a mean on each pixel of each channel?</p> </blockquote> <p>Exactly. According to the shape of <code>mean.binaryproto</code>, this file is the average image of some dataset, which means that it took the mean of each pixel (feature) for each channel.</p> <p>This should not be confused with the mean pixel, which, as you stated, is a single value for each channel. </p> <p>For example, mean pixel was adoped by <a href="https://arxiv.org/pdf/1409.1556.pdf" rel="nofollow noreferrer">Very Deep Convolutional Networks for Large-Scale Image Recognition</a>. According to their paper:</p> <blockquote> <p>The only pre-processing we do is subtracting the mean RGB value, computed on the training set, from each pixel</p> </blockquote> <p>In other words, if you consider an RGB image to be 3 feature arrays of size N x N, the average image will be the mean of <strong>each</strong> feature and the mean pixel will be the mean of <strong>all</strong> features.</p> <hr> <blockquote> <p>Another question is the following: I want to use such NN with OpenCV which instead of RGB uses BGR: How to know if the mean 3x256x256 uses RGB or BGR?</p> </blockquote> <p>I doubt the binary file you are reading stores any information about its color format, but a practical way to figure out is to plot this image using <code>matplotlib</code> and see if the colors make sense. </p> <p>For example, face images. If red and blue channels are swapped the skin tone will look blueish.</p> <p><a href="https://i.stack.imgur.com/8agIV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8agIV.png" alt="enter image description here"></a></p> <p>In fact, the image above is an example of average image (face images) :)</p> <p>You could also assume it is BGR since OpenCV uses this color format.</p> <p>However, the correct way to find out how this <code>mean.binaryproto</code> was generated is by looking at their repositories or by asking the owner of the model.</p>
2018-11-07 21:25:01.287000+00:00
2018-11-07 21:25:01.287000+00:00
null
null
52,974,196
<p>I want to load a Neural Network that has been trained with caffe for image classification.</p> <p>The NN contains a file <code>mean.binaryproto</code> which has the means to be subtracted before inputting an image to be classified.</p> <p>I am trying to understand what is contained in this file so I used Google Colab to see what is inside it.</p> <p>The code to load it is the following:</p> <pre><code># Load the Drive helper and mount from google.colab import drive # This will prompt for authorization. drive.mount('/content/drive') !ls "/content/drive/My Drive" #install packages !apt install -y caffe-cuda !apt update !apt upgrade !apt dist-upgrade !ls "/content/drive/My Drive/NeuralNetwork/CNRPark-Trained-Models/mAlexNet-on-CNRPark/" import caffe import numpy as np with open('/content/drive/My Drive/NeuralNetwork/CNRPark-Trained-Models/mAlexNet-on-CNRPark/mean.binaryproto', 'rb') as f: blob = caffe.proto.caffe_pb2.BlobProto() blob.ParseFromString(f.read()) arr = np.array( caffe.io.blobproto_to_array(blob) ) print(arr.shape) out = arr[0] data = np.array(blob.data).reshape([blob.channels, blob.height, blob.width]) print (data.shape) print(data[0]) #display the mean image from PIL import Image from IPython.display import Image as Im, display display(Image.fromarray(data[0], 'RGB')) </code></pre> <p>which outputs:</p> <pre><code>(1, 3, 256, 256) (3, 256, 256) </code></pre> <p>What I have understood is that the file contain the means and the images we are talking about are 3 channel images so there is a mean for each channel.</p> <p>However I was expecting a single value per channel instead I found a 256x256 array: does it mean that a mean on each pixel of each channel has been taken?</p> <p>Another question is the following: I want to use such NN with OpenCV which instead of RGB uses BGR: How to know if the mean 3x256x256 uses RGB or BGR?</p> <p>The link to the model is <a href="http://www.cnrpark.it" rel="nofollow noreferrer">this</a>. The model I am looking at is contained in the zip file <code>CNRPark-Trained-Models.zip</code> within the folder: <code>mAlexNet-on-CNRPark</code>.</p>
2018-10-24 16:45:48.840000+00:00
2020-03-25 11:21:12.577000+00:00
2020-03-25 11:21:12.577000+00:00
python|neural-network|caffe|pycaffe
['https://arxiv.org/pdf/1409.1556.pdf', 'https://i.stack.imgur.com/8agIV.png']
2
71,486,049
<p>Here are some papers and tools related to finding geodesics (or approximations) on a surface mesh:</p> <p><a href="https://arxiv.org/abs/2007.10430" rel="nofollow noreferrer">A Survey of Algorithms for Geodesic Paths and Distances</a><br /> <a href="https://nmwsharp.com/research/flip-geodesics/" rel="nofollow noreferrer">You Can Find Geodesic Paths in Triangle Meshes by Just Flipping Edges</a> (<a href="http://geometry-central.net/surface/algorithms/flip_geodesics/" rel="nofollow noreferrer">code</a>)<br /> <a href="https://www.cs.cmu.edu/%7Ekmcrane/Projects/VectorHeatMethod/index.html" rel="nofollow noreferrer">The Vector Heat Method</a> (<a href="https://www.cs.cmu.edu/%7Ekmcrane/Projects/HeatMethod/code.zip" rel="nofollow noreferrer">code</a>)</p> <p>You can find more papers in the survey paper.</p> <p>I implemented the algorithm you mentionned (MMP) a long time ago and it's quite difficult to get it right and quite time consuming since the number of splits along an edge grows quite fast.</p>
2022-03-15 16:52:42.360000+00:00
2022-03-15 16:52:42.360000+00:00
null
null
71,469,503
<p>I'm working on my bachelor thesis (on Computer Science) and right now I'm having a problem about finding shortest path between two points on 3D triangular mesh that is manifold. I already read about <a href="https://www.cs.umd.edu/%7Emount/Papers/mmp-sicomp-87.pdf" rel="nofollow noreferrer">MMP</a>, but which computes distance function $d(x)$ between given point and vertex $x$ on mesh.</p> <p>I got to know that the problem I'm solving is named Geodesics but What I really couldn't find is some good algorithm which uses A* for finding shortest path between two given points on two given vertices.</p> <p>I 'invented' also algorithm which uses A* by using Euclidian Distance Heuristics and correction after finding new Point on any Edge.. I also have edges saved in half-edge structure.</p> <p>So my main idea is this:</p> <ol> <li>We will find closest edge by A* algorithm and find on this edge point with minimalizing function $f(x) + g(x)$ where $f$ is our current distance and $g$ is heuristics(euclidean distance)</li> <li>Everytime we find new edge, we will unfold current mesh and find closest path to our starting point</li> </ol> <p>So now my questions:</p> <ul> <li>Do you know some research paper which talks about this problem ??</li> <li>Why nobody wrote about algorithm that uses A* ??</li> <li>What are your opinions about algorithm I proposed ?</li> </ul>
2022-03-14 14:37:34.283000+00:00
2022-03-15 16:52:42.360000+00:00
null
algorithm|geometry|computational-geometry|mesh
['https://arxiv.org/abs/2007.10430', 'https://nmwsharp.com/research/flip-geodesics/', 'http://geometry-central.net/surface/algorithms/flip_geodesics/', 'https://www.cs.cmu.edu/%7Ekmcrane/Projects/VectorHeatMethod/index.html', 'https://www.cs.cmu.edu/%7Ekmcrane/Projects/HeatMethod/code.zip']
5
49,937,523
<p>The paper <a href="https://arxiv.org/abs/1602.04938" rel="noreferrer"> "Why Should I Trust You?": Explaining the Predictions of Any Classifier</a> was submitted 9 days after this question, providing an algorithm for a general solution to this problem! :-)</p> <p>In short, it is called LIME for "local interpretable model-agnostic explanations", and works by fitting a simpler, local model around the prediction(s) you want to understand.</p> <p>What's more, they have made a python implementation (<a href="https://github.com/marcotcr/lime" rel="noreferrer">https://github.com/marcotcr/lime</a>) with pretty detailed examples on how to use it with sklearn. For instance <a href="https://marcotcr.github.io/lime/tutorials/Lime%20-%20basic%20usage%2C%20two%20class%20case.html" rel="noreferrer">this one</a> is on two-class random forest problem on text data, and <a href="https://marcotcr.github.io/lime/tutorials/Tutorial%20-%20continuous%20and%20categorical%20features.html" rel="noreferrer">this one</a> is on continuous and categorical features. They are all to be found via the README on github.</p> <p>The authors had a very productive year in 2016 concerning this field, so if you like reading papers, here's a starter:</p> <ul> <li><a href="https://arxiv.org/abs/1611.07579" rel="noreferrer">Programs as Black-Box Explanations</a></li> <li><a href="https://arxiv.org/abs/1611.05817" rel="noreferrer">Nothing Else Matters: Model-Agnostic Explanations By Identifying Prediction Invariance</a></li> <li><a href="https://arxiv.org/abs/1606.05386" rel="noreferrer">Model-Agnostic Interpretability of Machine Learning</a></li> </ul>
2018-04-20 08:40:21.343000+00:00
2018-04-20 08:40:21.343000+00:00
null
null
35,249,760
<p>I am using a scikit extra trees classifier:</p> <pre><code>model = ExtraTreesClassifier(n_estimators=10000, n_jobs=-1, random_state=0) </code></pre> <p>Once the model is fitted and used to predict classes, I would like to find out the contributions of each feature to a specific class prediction. How do I do that in scikit learn? Is it possible with extra trees classifier or do I need to use some other model?</p>
2016-02-07 04:33:25.243000+00:00
2020-07-28 13:39:42.047000+00:00
2016-03-22 16:48:18.927000+00:00
python|scikit-learn
['https://arxiv.org/abs/1602.04938', 'https://github.com/marcotcr/lime', 'https://marcotcr.github.io/lime/tutorials/Lime%20-%20basic%20usage%2C%20two%20class%20case.html', 'https://marcotcr.github.io/lime/tutorials/Tutorial%20-%20continuous%20and%20categorical%20features.html', 'https://arxiv.org/abs/1611.07579', 'https://arxiv.org/abs/1611.05817', 'https://arxiv.org/abs/1606.05386']
7
28,703,861
<p>You could use the inter- and intra-cluster densities, as defined for undirected graphs in <a href="http://arxiv.org/abs/0906.0612" rel="nofollow">Fortunato'10</a>. Both are based on the notion of graph density, but processed by considering only certain subgraphs. </p> <p>The intra-cluster density is the proportion of existing links <em>inside</em> a community, relatively to the possible number of such links, if all nodes of the community were connected. If there are m_C links and n_C nodes in community C, then the intra-cluster density is: d_intra(C)=m_C/(n_C(n_C-1)/2).</p> <p>The inter-cluster density is the proportion of existing links between a community and the rest of the graph, relatively to the possible number of such links if each community node was connected to the rest of the graph. If there are n nodes in the whole graph, and if m_C' is the number of links connecting a node of community C to a node located in another community, then the inter-cluster density of community C is: d_inter(C)=m_C'/(n_C(n-n_C)).</p> <p>If you need to, the inter-cluster density can be easily modified to characterize the connection between two specific communities (by opposition to: a community and the rest of the graph). If we note m_C1C2 the number of links between communities C1 and C2, and n_C1 and n_C2 their respective numbers of nodes, then we get: d_inter(C1,C2)=m_C1C2/(n_C1*n_C2)</p> <p>I don't think these measures are directly implemented in igraph (or any other software, for that matter).</p>
2015-02-24 18:50:06.883000+00:00
2015-02-24 18:50:06.883000+00:00
null
null
28,662,832
<p>Is there any measure that computes the dependency between communities of a graph in igraph? I am looking for a measure of dependency between communities.</p>
2015-02-22 20:26:27.907000+00:00
2016-09-13 16:56:00.123000+00:00
null
graph|igraph
['http://arxiv.org/abs/0906.0612']
1
41,894,540
<p>the machine learning model you built and the task you are trying to achieve are not the same. the model tries to solve a classification task while your goal is to detect an object inside the image, which is an <a href="https://en.wikipedia.org/wiki/Object_detection" rel="noreferrer">object detection task</a>.</p> <p>classification has a boolean question while detection quesion has more than two answers answers.</p> <h2>What can you do?</h2> <p>I can suggest you three possibilities to try:</p> <p><br /></p> <h3>1. use sliding window combined with your model</h3> <p>crop boxes of defined sizes (e.g. from 20X20 to 160X160) and use sliding window. for each window, try to predict the probability its a dog and finally take the maximum window you predicted on.</p> <p>this will generate multiple candidates for the bounding box and you will choose the bounding box using the highest probability you got.</p> <p>this might be slow as we need to predict on hundreds+ samples.</p> <p>another option is to try implement <a href="https://cs.stanford.edu/people/karpathy/rcnn/" rel="noreferrer">RCNN</a> (<a href="https://github.com/rbgirshick/rcnn" rel="noreferrer">another link</a>) or <a href="https://arxiv.org/abs/1506.01497" rel="noreferrer">Faster-RCNN</a> network on top of your network. These networks are basically reducing the number of bounding box windows candidates to use.</p> <h2>Update - computing sliding window example</h2> <p>the following code demonstrate how to do the sliding window algorithm. you can change the parameters.</p> <pre><code>import random import numpy as np WINDOW_SIZES = [i for i in range(20, 160, 20)] def get_best_bounding_box(img, predict_fn, step=10, window_sizes=WINDOW_SIZES): best_box = None best_box_prob = -np.inf # loop window sizes: 20x20, 30x30, 40x40...160x160 for win_size in window_sizes: for top in range(0, img.shape[0] - win_size + 1, step): for left in range(0, img.shape[1] - win_size + 1, step): # compute the (top, left, bottom, right) of the bounding box box = (top, left, top + win_size, left + win_size) # crop the original image cropped_img = img[box[0]:box[2], box[1]:box[3]] # predict how likely this cropped image is dog and if higher # than best save it print('predicting for box %r' % (box, )) box_prob = predict_fn(cropped_img) if box_prob &gt; best_box_prob: best_box = box best_box_prob = box_prob return best_box def predict_function(x): # example of prediction function for simplicity, you # should probably use `return model.predict(x)` random.seed(x[0][0]) return random.random() # dummy array of 256X256 img = np.arange(256 * 256).reshape((256, 256)) best_box = get_best_bounding_box(img, predict_function) print('best bounding box %r' % (best_box, )) </code></pre> <p>example output:</p> <pre><code>predicting for box (0, 0, 20, 20) predicting for box (0, 10, 20, 30) predicting for box (0, 20, 20, 40) ... predicting for box (110, 100, 250, 240) predicting for box (110, 110, 250, 250) best bounding box (140, 80, 160, 100) </code></pre> <p><br /></p> <h3>2. train new network for object detection task</h3> <p>you can take a look at the <a href="http://host.robots.ox.ac.uk/pascal/VOC/voc2012/index.html#data" rel="noreferrer"><strong>pascal dataset</strong></a> (<a href="http://host.robots.ox.ac.uk/pascal/VOC/voc2012/examples/index.html" rel="noreferrer">examples here</a>) which contains 20 classes and two of them are cats and dogs.</p> <p>the dataset contains the location of the objects as the Y target.</p> <p><br /></p> <h3>3. use existing network for this task</h3> <p>last but not least, you can reuse existing network or even do "knowledge transfer" (keras example here) for your specific task. </p> <p>take a look at the following <a href="https://github.com/heuritech/convnets-keras" rel="noreferrer"><code>convnets-keras</code></a> lib.</p> <p>so choose your best method to go and update us with the results.</p>
2017-01-27 12:59:18.483000+00:00
2017-01-27 21:12:04.833000+00:00
2017-01-27 21:12:04.833000+00:00
null
41,884,001
<p>I am working on a classification then object detection with Keras and Python. I have classified cats/dogs with 80%+ accuracy, Im ok with the current result for now. My question is how do I detect cat or dog from an input image? I'm completely confused. I want to use my own heights and not pretrained ones from internet.</p> <p>Here is my code currently:</p> <pre><code>from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Convolution2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense import numpy as np import matplotlib.pyplot as plt import matplotlib from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img ######################################################################################################### #VALUES # dimensions of our images. img_width, img_height = 150, 150 train_data_dir = 'data/train' validation_data_dir = 'data/validation' nb_train_samples = 2000 #1000 cats/dogs nb_validation_samples = 800 #400cats/dogs nb_epoch = 50 ######################################################################################################### #MODEL model = Sequential() model.add(Convolution2D(32, 3, 3, input_shape=(3, img_width, img_height))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Convolution2D(32, 3, 3)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Convolution2D(64, 3, 3)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(64)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(1)) model.add(Activation('sigmoid')) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # this is the augmentation configuration we will use for training train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) ########################################################################################################## #TEST AUGMENTATION img = load_img('data/train/cats/cat.0.jpg') # this is a PIL image x = img_to_array(img) # this is a Numpy array with shape (3, 150, 150) x = x.reshape((1,) + x.shape) # this is a Numpy array with shape (1, 3, 150, 150) # the .flow() command below generates batches of randomly transformed images # and saves the results to the `preview/` directory i = 0 for batch in train_datagen.flow(x, batch_size=1, save_to_dir='data/TEST AUGMENTATION', save_prefix='cat', save_format='jpeg'): i += 1 if i &gt; 20: break # otherwise the generator would loop indefinitely ########################################################################################################## # this is the augmentation configuration we will use for testing: # only rescaling test_datagen = ImageDataGenerator(rescale=1./255) #PREPARE TRAINING DATA train_generator = train_datagen.flow_from_directory( train_data_dir, #data/train target_size=(img_width, img_height), #RESIZE to 150/150 batch_size=32, class_mode='binary') #since we are using binarycrosentropy need binary labels #PREPARE VALIDATION DATA validation_generator = test_datagen.flow_from_directory( validation_data_dir, #data/validation target_size=(img_width, img_height), #RESIZE 150/150 batch_size=32, class_mode='binary') #START model.fit history =model.fit_generator( train_generator, #train data samples_per_epoch=nb_train_samples, nb_epoch=nb_epoch, validation_data=validation_generator, #validation data nb_val_samples=nb_validation_samples) model.save_weights('savedweights.h5') # list all data in history print(history.history.keys()) #ACC VS VAL_ACC plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy ACC VS VAL_ACC') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() # summarize history for loss #LOSS VS VAL_LOSS plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss LOSS vs VAL_LOSS') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() model.load_weights('first_try.h5') </code></pre> <p>So now since i classified cat and dog, how and what do I need to do to input an image and go through it to find cat or a dog in it with a bounding box? I'm completely new to this nd not even sure if I'm tackling this in a correct way? Thank you.</p> <p><strong>UPDATE</strong> Hi, Sorry to post results so late, was unable to work on this for few days. I am importing an image and reshaping it to 1,3,150,150 shape as 150,150 shape brings error:</p> <pre><code>Exception: Error when checking : expected convolution2d_input_1 to have 4 dimensions, but got array with shape (150L, 150L) </code></pre> <p>Importing image:</p> <pre><code>#load test image img=load_img('data/prediction/cat.155.jpg') #reshape to 1,3,150,150 img = np.arange(1* 150 * 150).reshape((1,3,150, 150)) #check shape print(img.shape) </code></pre> <p>Then I have changed def predict_function(x) to:</p> <pre><code>def predict_function(x): # example of prediction function for simplicity, you # should probably use `return model.predict(x)` # random.seed(x[0][0]) # return random.random() return model.predict(img) </code></pre> <p>Now when I run:</p> <pre><code>best_box = get_best_bounding_box(img, predict_function) print('best bounding box %r' % (best_box, )) </code></pre> <p>I get output as best bounding box: None</p> <p>So I ran just:</p> <pre><code>model.predict(img) </code></pre> <p>And get the following out:</p> <pre><code>model.predict(img) Out[54]: array([[ 0.]], dtype=float32) </code></pre> <p>So it is not checking at all if its a cat or a dog... Any ideas? </p> <p>NOTE: when def predict)function(x) is using:</p> <pre><code>random.seed(x[0][0]) return random.random() </code></pre> <p>I do get the output as , it check boxes and gives the best one.</p>
2017-01-26 22:19:19.827000+00:00
2018-05-18 07:21:43.553000+00:00
2017-12-13 11:53:12.327000+00:00
python|classification|keras|object-detection
['https://en.wikipedia.org/wiki/Object_detection', 'https://cs.stanford.edu/people/karpathy/rcnn/', 'https://github.com/rbgirshick/rcnn', 'https://arxiv.org/abs/1506.01497', 'http://host.robots.ox.ac.uk/pascal/VOC/voc2012/index.html#data', 'http://host.robots.ox.ac.uk/pascal/VOC/voc2012/examples/index.html', 'https://github.com/heuritech/convnets-keras']
7
30,497,907
<p>Why don't you use the <a href="http://caffe.berkeleyvision.org/doxygen/classcaffe_1_1InfogainLossLayer.html" rel="noreferrer"><strong>InfogainLoss</strong></a> layer to compensate for the imbalance in your training set?</p> <p>The Infogain loss is defined using a weight matrix <code>H</code> (in your case 2-by-2) The meaning of its entries are</p> <pre><code>[cost of predicting 1 when gt is 0, cost of predicting 0 when gt is 0 cost of predicting 1 when gt is 1, cost of predicting 0 when gt is 1] </code></pre> <p>So, you can set the entries of <code>H</code> to reflect the difference between errors in predicting 0 or 1.</p> <p>You can find how to define matrix <code>H</code> for caffe in <a href="https://stackoverflow.com/questions/27632440/infogain-loss-layer">this thread</a>.</p> <p>Regarding sample weights, you may find <a href="http://deepdish.io/2014/11/04/caffe-with-weighted-samples/" rel="noreferrer">this post</a> interesting: it shows how to modify the <strong>SoftmaxWithLoss</strong> layer to take into account sample weights.</p> <hr /> <p>Recently, a modification to cross-entropy loss was proposed by <a href="https://arxiv.org/abs/1708.02002" rel="noreferrer"><em>Tsung-Yi Lin, Priya Goyal, Ross Girshick, Kaiming He, Piotr Dollár</em> <strong>Focal Loss for Dense Object Detection</strong>, (ICCV 2017)</a>.<br /> The idea behind focal-loss is to assign different weight for each example based on the relative difficulty of predicting this example (rather based on class size etc.). From the brief time I got to experiment with this loss, it feels superior to <code>&quot;InfogainLoss&quot;</code> with class-size weights.</p>
2015-05-28 05:28:51.720000+00:00
2017-12-04 06:36:48.523000+00:00
2020-06-20 09:12:55.060000+00:00
null
30,486,033
<p><strong>(An update to this question has been added.)</strong></p> <p>I am a graduate student at the university of Ghent, Belgium; my research is about emotion recognition with deep convolutional neural networks. I'm using the <a href="http://caffe.berkeleyvision.org/" rel="noreferrer">Caffe</a> framework to implement the CNNs.</p> <p>Recently I've run into a problem concerning class imbalance. I'm using 9216 training samples, approx. 5% are labeled positively (1), the remaining samples are labeled negatively (0).</p> <p>I'm using the <a href="http://caffe.berkeleyvision.org/doxygen/classcaffe_1_1SigmoidCrossEntropyLossLayer.html" rel="noreferrer">SigmoidCrossEntropyLoss</a> layer to calculate the loss. When training, the loss decreases and the accuracy is extremely high after even a few epochs. This is due to the imbalance: the network simply always predicts negative (0). <em>(Precision and recall are both zero, backing this claim)</em></p> <p>To solve this problem, I would like to <strong>scale the contribution to the loss depending on the prediction-truth combination</strong> (punish false negatives severely). My mentor/coach has also advised me to <strong>use a scale factor when backpropagating</strong> through stochastic gradient descent (sgd): the factor would be correlated to the imbalance in the batch. A batch containing only negative samples would not update the weights at all.</p> <p><em>I have only added one custom-made layer to Caffe: to report other metrics such as precision and recall. My experience with Caffe code is limited but I have a lot of expertise writing C++ code.</em></p> <hr> <p><strong>Could anyone help me or point me in the right direction on how to adjust the <a href="http://caffe.berkeleyvision.org/doxygen/classcaffe_1_1SigmoidCrossEntropyLossLayer.html" rel="noreferrer">SigmoidCrossEntropyLoss</a> and <a href="http://caffe.berkeleyvision.org/doxygen/classcaffe_1_1SigmoidLayer.html" rel="noreferrer">Sigmoid</a> layers to accomodate the following changes:</strong></p> <ol> <li>adjust the contribution of a sample to the total loss depending on the prediction-truth combination (true positive, false positive, true negative, false negative).</li> <li>scale the weight update performed by stochastic gradient descent depending on the imbalance in the batch (negatives vs. positives).</li> </ol> <p>Thanks in advance!</p> <hr> <h2>Update</h2> <p>I have incorporated the <strong><a href="http://caffe.berkeleyvision.org/doxygen/classcaffe_1_1InfogainLossLayer.html#details" rel="noreferrer">InfogainLossLayer</a> as suggested by <a href="https://stackoverflow.com/a/30497907/1714410">Shai</a></strong>. I've also added another custom layer that builds the infogain matrix <code>H</code> based on the imbalance in the current batch.</p> <p>Currently, the matrix is configured as follows:</p> <pre><code>H(i, j) = 0 if i != j H(i, j) = 1 - f(i) if i == j (with f(i) = the frequency of class i in the batch) </code></pre> <p><em>I'm planning on experimenting with different configurations for the matrix in the future.</em></p> <p>I have tested this on a 10:1 imbalance. The results have shown that the network is learning useful things now: <em>(results after 30 epochs)</em></p> <ul> <li>Accuracy is approx. ~70% (down from ~97%);</li> <li>Precision is approx. ~20% (up from 0%);</li> <li>Recall is approx. ~60% (up from 0%).</li> </ul> <p>These numbers were reached at around 20 epochs and didn't change significantly after that.</p> <p><em>!! The results stated above are merely a proof of concept, they were obtained by training a simple network on a 10:1 imbalanced dataset. !!</em></p>
2015-05-27 14:52:41.100000+00:00
2017-12-04 06:36:48.523000+00:00
2017-05-23 10:31:02.950000+00:00
c++|machine-learning|neural-network|deep-learning|caffe
['http://caffe.berkeleyvision.org/doxygen/classcaffe_1_1InfogainLossLayer.html', 'https://stackoverflow.com/questions/27632440/infogain-loss-layer', 'http://deepdish.io/2014/11/04/caffe-with-weighted-samples/', 'https://arxiv.org/abs/1708.02002']
4
62,586,624
<p>Thanks for clarifying a bit. I think what you are expecting is something similar to the output of an ANOVA? But this will not be possible with your data, as you have two random effects specified.</p> <p>As you are running a logistic regression, you should read up a bit on how to interpret them. (I'm just putting this here because you said you were new to this)</p> <p><a href="https://stats.idre.ucla.edu/stata/output/logistic-regression-analysis/" rel="nofollow noreferrer">https://stats.idre.ucla.edu/stata/output/logistic-regression-analysis/</a></p> <p>Now, if you want to test the contribution of one of your factors to to the model, you have to create nested models, and compare them with a likelihood-ratio test using the <code>anova()</code> function in R.</p> <p>For example, let's say that you had the same model you had above, but without any interactions specified:</p> <pre><code>m1 &lt;- glmer(ACC~Group+M_O+Lblock+ (1| Subject) + (1| hand),data = learndata_long3,family=&quot;binomial&quot;) </code></pre> <p>And then one without the Group predictor:</p> <pre><code>m2 &lt;- glmer(ACC~M_O+Lblock+ (1| Subject) + (1| hand),data = learndata_long3,family=&quot;binomial&quot;) </code></pre> <p>Then we compare whether having the <code>Group</code> predictor significantly improved the model:</p> <pre><code>anova(m1,m2) </code></pre> <p>This will give your a p-value telling you if the addition of <code>Group</code> significantly improves model fit.</p> <p>If this seems all like a lot, which it is if you're not familiar with model comparison, I'd recommend looking at this tutorial from Bodo Winter. It's directed at people who are new mixed-models, and want a conceptual foundation of what is going on. I don't know what field you are in, but I think the examples are pretty accessible to everyone.</p> <p><a href="https://arxiv.org/abs/1308.5499" rel="nofollow noreferrer">https://arxiv.org/abs/1308.5499</a></p> <p>Please let me know if you need any other clarifications or have any questions during the tutorial.</p>
2020-06-26 01:25:23.210000+00:00
2020-06-26 01:25:23.210000+00:00
null
null
62,561,091
<p>here is the GLMER model</p> <pre><code>model &lt;- glmer(ACC~Group*M_O*Lblock+ (1| Subject) + (1| hand),data = learndata_long3,family=&quot;binomial&quot;) </code></pre> <p>while the 'Lblock' factor has 9 levels, others have 2 levels.</p> <p>The results generate like this:</p> <pre><code> summary(model)$coefficients Estimate Std. Error z value Pr(&gt;|z|) (Intercept) 0.437931021 0.16334362 2.68104155 7.339340e-03 Group1 -0.032138148 0.14961572 -0.21480463 8.299196e-01 M_O1 0.135726477 0.04115871 3.29763642 9.750230e-04 Lblock1 0.301264476 0.08343952 3.61057288 3.055214e-04 Lblock2 0.623913565 0.08247767 7.56463576 3.889529e-14 Lblock3 1.022046512 0.08235930 12.40960689 2.317880e-35 Lblock4 1.399407518 0.08337615 16.78426631 3.181367e-63 Lblock5 1.741198402 0.08541505 20.38514752 2.265326e-92 Lblock6 2.065315516 0.08843600 23.35378765 1.261292e-120 Lblock7 2.268393650 0.09075950 24.99345703 7.201546e-138 Lblock8 2.637079325 0.09707420 27.16560426 1.656429e-162 </code></pre> <p>ALL I want is extract each factor, like&quot;</p> <p>Estimate : Group / M_O / Lblock</p> <p>how can I do? just sum up and then mean the block? or ?</p> <p>Very new to these fields, thanks for your help</p>
2020-06-24 17:49:25.863000+00:00
2020-06-26 01:25:23.210000+00:00
null
r|lme4|summary|coefficients
['https://stats.idre.ucla.edu/stata/output/logistic-regression-analysis/', 'https://arxiv.org/abs/1308.5499']
2
62,517,401
<p>I think there is still a lot of open research in these areas for Federated Learning.</p> <p>Page 6 of <a href="https://arxiv.org/abs/1912.04977" rel="nofollow noreferrer">https://arxiv.org/abs/1912.04977</a> describes a <em>cross-device</em> and a <em>cross-silo</em> setting for federated learning.</p> <p>In cross-device settings, the population is generally very large (hundreds of thousands or millions) and participants are generally only seen once during the entire training process. In this setting, <a href="https://arxiv.org/abs/2003.00295" rel="nofollow noreferrer">https://arxiv.org/abs/2003.00295</a> demonstrates that hyper-parameters such as client learning rate play an outsized role in determining speed of model convergence and final model accuracy. To demonstrate that finding, we first performed a large coarse grid search to identify promising hyper-parameter space, and then ran finer grids in the promising regions. However this can be expensive depending on the compute resources available for simulation, the training process must be run to completion to understand these effects.</p> <p>It might be possible to view federated learning as very large mini-batch SGD. In fact the FedSGD algorithm in <a href="https://arxiv.org/abs/1602.05629" rel="nofollow noreferrer">https://arxiv.org/abs/1602.05629</a> is exactly this. In this regime, re-using theory from centralized model training may be fruitful.</p> <p>Finally <a href="https://arxiv.org/abs/1902.01046" rel="nofollow noreferrer">https://arxiv.org/abs/1902.01046</a> describes a system used at Google for federated learning, and does have a small discussion on hyper-parameter exploration.</p>
2020-06-22 15:00:20.367000+00:00
2020-06-22 15:00:20.367000+00:00
null
null
62,040,659
<p>I'm currently researching with TFF and image classification (Federated Learning for Image Classification) emnist.</p> <p>I'm looking at hyper parameters for the model learning rate and optimizer. Is grid search a good approach here ? . In a real world scenario would you simply sample clients/devices from the overall domain and if so if I was to do a grid search would I have to fix my client samples 1st. In which case does it make sense to do the grid search. </p> <p>What would be a typical real world way of selecting parameters, ie is this more a heuristic approach. ?</p> <p>Colin . . .</p>
2020-05-27 10:14:02.467000+00:00
2020-11-28 10:55:28.080000+00:00
2020-11-28 10:55:28.080000+00:00
grid-search|tensorflow-federated|federated-learning
['https://arxiv.org/abs/1912.04977', 'https://arxiv.org/abs/2003.00295', 'https://arxiv.org/abs/1602.05629', 'https://arxiv.org/abs/1902.01046']
4
51,923,122
<p>Yolo is one of the best object detection for real time detection. Fast Training and high accuracy are competing goals. Did you mean test speed (with a trained model)?</p> <p>Anyway, if you need fast training I highly suggest the cyclical learning rate strategy <a href="https://arxiv.org/pdf/1803.09820" rel="nofollow noreferrer">proposed</a> by Leslie N. Smith. </p> <p>Yolo has different version, so take a look at that as well.</p>
2018-08-20 01:25:41.900000+00:00
2018-08-20 01:25:41.900000+00:00
null
null
51,923,094
<p>I'm doing a project these days.<br> Goal of this project is approximately 200 symbol recognition.<br> Symbols are using in the navigation(turn_right, turn_left etc..)</p> <p>I'm using YOLO model now<br> For traning this models, I thought I needed some improvement about traning speed.<br> This program will using when testing new navigation.</p> <p>Is there any better models?<br> The model needs very fast traning speed, and high accuracy</p>
2018-08-20 01:18:51.180000+00:00
2018-08-20 12:55:15.310000+00:00
null
python|tensorflow|keras|deep-learning
['https://arxiv.org/pdf/1803.09820']
1
51,273,445
<p>This isn't a python problem, per se. It seems to be more of a machine learning/data validation/data segmentation question, IMO. That being said, you are correct in thinking that you must parallelize your work, but it matters in what ways you do it. There are things like 8-bit quantization and model parallelism in your model that you may look into to help you get at what you're after: training a model on large datasets, in a timely manner, without sacrificing data quality or fidelity. </p> <p>Here is a blog post about quantization: <a href="https://petewarden.com/2016/05/03/how-to-quantize-neural-networks-with-tensorflow/" rel="nofollow noreferrer">https://petewarden.com/2016/05/03/how-to-quantize-neural-networks-with-tensorflow/</a></p> <p>Here is a blog post about model parallelism and 8-bit quantization from Tim Dettmers' Blog: <a href="http://timdettmers.com/2017/04/09/which-gpu-for-deep-learning/" rel="nofollow noreferrer">http://timdettmers.com/2017/04/09/which-gpu-for-deep-learning/</a></p> <p>and the associated paper: <a href="https://arxiv.org/pdf/1511.04561.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1511.04561.pdf</a></p> <p>Though you will want to keep in mind that, depending on FP operations on your GPU, you may not see substantial benefit from this route: <a href="https://blog.inten.to/hardware-for-deep-learning-part-3-gpu-8906c1644664" rel="nofollow noreferrer">https://blog.inten.to/hardware-for-deep-learning-part-3-gpu-8906c1644664</a></p> <p>HTH and YMMV.</p> <p>Also, you may want to look into data folding, but can't remember the details nor the paper I read at this point in time. I'll land this here to remember once I do though. </p>
2018-07-10 20:29:05.323000+00:00
2018-07-10 20:29:05.323000+00:00
null
null
50,915,749
<p>I'm trying to use Gaussian Mixture models on a sample of a dataset. I used both<code>MLlib</code> (with <code>pyspark</code>) and <code>scikit-learn</code> and get very different results, the <code>scikit-learn</code> one looking more realistic. </p> <pre><code>from pyspark.mllib.clustering import GaussianMixture as SparkGaussianMixture from sklearn.mixture import GaussianMixture from pyspark.mllib.linalg import Vectors </code></pre> <p><strong>Scikit-learn</strong>:</p> <pre><code>local = pd.DataFrame([ x.asDict() for x in df.sample(0.0001).collect() ]) model1 = GaussianMixture(n_components=3) model1.fit([ [x] for x in local['field'].tolist() ]) model1.means_ array([[7.56123598e+00], [1.32517410e+07], [3.96762639e+04]]) model1.covariances_ array([[[6.65177423e+00]], [[1.00000000e-06]], [[8.38380897e+10]]]) </code></pre> <p><strong>MLLib</strong>:</p> <pre><code>model2 = SparkGaussianMixture.train( sc.createDataFrame(local).rdd.map(lambda x: Vectors.dense(x.field)), k=3, convergenceTol=1e-4, maxIterations=100 ) model2.gaussians [MultivariateGaussian(mu=DenseVector([28736.5113]), sigma=DenseMatrix(1, 1, [1094083795.0001], 0)), MultivariateGaussian(mu=DenseVector([7839059.9208]), sigma=DenseMatrix(1, 1, [38775218707109.83], 0)), MultivariateGaussian(mu=DenseVector([43.8723]), sigma=DenseMatrix(1, 1, [608204.4711], 0))] </code></pre> <p>However, I'm interested in running the entire dataset through the model which I'm afraid would require parallelizing (and hence use MLlib) to get results in finite time. Am I doing anything wrong / missing something?</p> <p><strong>Data</strong>:</p> <p>The complete data has an extremely long tail and looks like: <a href="https://i.stack.imgur.com/RxS3T.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RxS3T.png" alt="enter image description here"></a></p> <p>whereas the data has a clearly normal dist ceneterd somewhere closer to one clustered by <code>scikit-learn</code>:</p> <p><a href="https://i.stack.imgur.com/1ZAb1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1ZAb1.png" alt="enter image description here"></a></p> <p>I am using Spark 2.3.0 (AWS EMR).</p> <p>Edit: Initialization params:</p> <pre><code>local = pd.DataFrame([ x.asDict() for x in df.sample(0.0001).collect() ]) model1 = GaussianMixture(n_components=3, init_params='random') model1.fit([ [x] for x in local['field'].tolist() ]) model1.means_ array([[2.17611913e+04], [8.03184505e+06], [7.56871801e+00]]) model1.covariances_ rray([[[1.01835902e+09]], [[3.98552130e+13]], [[6.95161493e+00]]]) </code></pre>
2018-06-18 18:49:25.353000+00:00
2019-08-07 06:44:47.407000+00:00
2019-08-07 06:44:47.407000+00:00
python|apache-spark|scikit-learn|pyspark|apache-spark-mllib
['https://petewarden.com/2016/05/03/how-to-quantize-neural-networks-with-tensorflow/', 'http://timdettmers.com/2017/04/09/which-gpu-for-deep-learning/', 'https://arxiv.org/pdf/1511.04561.pdf', 'https://blog.inten.to/hardware-for-deep-learning-part-3-gpu-8906c1644664']
4
68,407,445
<p>Ad 3, current implementations of <code>clpfd/clpz</code> are all a library that has very few connections to the actual compilation process (&quot;preparation for execution&quot;). So there is no such predicate-wise optimization that you are hoping for. The clauses remain and are tried out one after the other — maybe with a little bit indexing due to the 0es in the head. If you want to get efficient code, you need to combine the common cases directly. E.g., you might first consider in a single rule <code>I in 1..3, J in 1..3</code> and then avoid all those other comparisons. This means you would need some intermediary auxiliary predicate.</p> <p>Also note the fine difference between <code>I #=&lt; 3, I #&gt; 0</code> and <code>I in 1..3</code>. The former succeeds for <code>I = 1+0</code> while the latter produces a type error. And for <code>0+0</code> OTOH, your program fails. You probably want at least consistent behaviour wherefore you may also use <code>(#)/1</code> in places where general expressions are expected.</p> <p>Ad 4, <code>if_/3</code> or rather <code>reif</code> might be of interest, because you have just the special case of 0. Also, please note that often in stead of nesting <code>if_/3</code> you may use a more complex reified condition as <a href="https://arxiv.org/abs/1607.01590" rel="nofollow noreferrer">here</a> on page 8 in <code>treememberd_t/3</code>.</p> <p>Ad 1&amp;2 there is some support for this in some systems, but it still is very bleeding edge. In particular if you want to use it together with constraints.</p> <hr /> <p>One final remark about your code in general. What you did was to take one-by-one an existing algorithm and you recoded it directly. Think of the last clause where you explore two paths independently and then join their results. You only can do this, because you know a lot about the actual problem, in particular both paths will have a solution. The only case were actual non-determinism happens is the instantiation of the coordinates.</p>
2021-07-16 10:26:46.963000+00:00
2021-07-16 10:57:32.923000+00:00
2021-07-16 10:57:32.923000+00:00
null
68,389,213
<p>Given a <code>field</code>, find the &quot;cheapest&quot; path from <code>(0, 0)</code> to <code>(3, 3)</code>. Only the moves <em>up</em> and <em>to the right</em> are allowed.</p> <pre><code>field([ [1, 1, 1, 1], [3, 3, 4, 3], [3, 3, 1, 3], [3, 3, 1, 1] ]). nth([A|_], 0, A). nth([_|T], I, A) :- I #&gt; 0, J #= I - 1, nth(T, J, A). at(I, J, E) :- field(M), nth(M, I, R), nth(R, J, E). </code></pre> <p>Here's my recursive solution:</p> <pre><code>:- use_module(library(clpfd)). price(0, 0, P) :- at(0, 0, P). price(I, 0, P) :- I #=&lt; 3, I #&gt; 0, I0 #= I - 1, price(I0, 0, P0), at(I, 0, P1), P #= P0 + P1. price(0, J, P) :- J #=&lt; 3, J #&gt; 0, J0 #= J - 1, price(0, J0, P0), at(0, J, P1), P #= P0 + P1. price(I, J, P) :- I #=&lt; 3, J #=&lt; 3, I #&gt; 0, J #&gt; 0, I0 #= I - 1, J0 #= J - 1, price(I0, J, P0), price(I, J0, P1), at(I, J, P2), P #= min(P0, P1) + P2. </code></pre> <p>I can run it in different directions:</p> <pre><code>?- price(3, 3, P). ?- price(I, J, P), I #= 3, J #= 3. ?- price(I, J, P), P #&gt; 10. </code></pre> <ol> <li>Is it possible to memorize the intermediate steps, and is it strictly necessary?</li> <li>Is there a way to use memorization only when <code>I</code> and <code>J</code> are grounded?</li> <li>How does CLPFD deal with the fact that there are 4 rules for the predicate <code>price</code>? Does the library merge the different rules into one big if?</li> <li>Is it better to write a single rule <code>price</code> with <code>if_</code>'s inside?</li> </ol>
2021-07-15 06:54:43.790000+00:00
2021-07-17 13:51:50.507000+00:00
2021-07-17 13:51:50.507000+00:00
prolog|shortest-path|clpfd|north-east-lattice-path
['https://arxiv.org/abs/1607.01590']
1
37,904,057
<p>You can certainly jump in xorshift, and the process is described <a href="https://arxiv.org/pdf/1404.0390.pdf" rel="nofollow">here</a>, but I haven't read that for myself so I don't know how easy it is to follow.</p> <p>Alternatively, you could look at <a href="http://www.pcg-random.org/" rel="nofollow">PCG</a> which offers a jump function by using an underlying LCG (the same as @Daerst's answer) but post-processes it to improve its statistical properties, or some of the splittable generators described <a href="http://on-demand.gputechconf.com/gtc/2016/presentation/s6665-guy-steele-fast-splittable.pdf" rel="nofollow">here</a>. The SplitMix generator, for example, has only an in-loop addition of a constant, so to jump an arbitrary distance you need only multiply the jump distance by the constant and add that (<a href="http://xoroshiro.di.unimi.it/splitmix64.c" rel="nofollow">here</a>'s a SplitMix derivitive that apparently passes BigCrush).</p>
2016-06-19 04:53:18.457000+00:00
2016-06-19 04:53:18.457000+00:00
null
null
11,692,785
<p>I need a fast random number generator that allows me to randomly access numbers at various positions of the random number sequence. I chose Xorshift, because it's fast and easy to implement.</p> <p>To get a specific random number from the sequence, I implemented the following method (<code>mPos</code> saves the position of the next random number):</p> <pre><code>void XorshiftRandomGenerator::skipTo(unsigned int pos) { // Reset if we passed the position if (mPos&gt;pos) reset(); // Generate random numbers until we're done while (mPos&lt;pos) random(); } </code></pre> <p>A subsequent <code>random()</code> will return the desired number, but this method is very expensive. Is there a way to skip a large amount of random numbers with Xorshift, without calculating every random number in between?</p> <p>As an alternative I could go with another random number generator. Could you suggest one that allows fast skipping ahead?</p>
2012-07-27 17:34:09.960000+00:00
2016-06-19 04:53:18.457000+00:00
2012-07-29 10:55:10.140000+00:00
c++|algorithm|random
['https://arxiv.org/pdf/1404.0390.pdf', 'http://www.pcg-random.org/', 'http://on-demand.gputechconf.com/gtc/2016/presentation/s6665-guy-steele-fast-splittable.pdf', 'http://xoroshiro.di.unimi.it/splitmix64.c']
4
55,827,335
<p>Apologies if my answer seems redundant, but I implemented Ukkonen's algorithm recently, and found myself struggling with it for days; I had to read through multiple papers on the subject to understand the why and how of some core aspects of the algorithm.</p> <p>I found the 'rules' approach of previous answers unhelpful for understanding the underlying <em>reasons</em>, so I've written everything below focusing solely on the pragmatics. If you've struggled with following other explanations, just like I did, perhaps my supplemental explanation will make it 'click' for you.</p> <p>I published my C# implementation here: <a href="https://github.com/baratgabor/SuffixTree" rel="noreferrer">https://github.com/baratgabor/SuffixTree</a></p> <p><em>Please note that I'm not an expert on this subject, so the following sections may contain inaccuracies (or worse). If you encounter any, feel free to edit.</em></p> <h2>Prerequisites</h2> <p>The starting point of the following explanation assumes you're familiar with the content and use of suffix trees, and the characteristics of Ukkonen's algorithm, e.g. how you're extending the suffix tree character by character, from start to end. Basically, I assume you've read some of the other explanations already. </p> <p>(However, I did have to add some basic narrative for the flow, so the beginning might indeed feel redundant.)</p> <p>The most interesting part is the <em>explanation on the difference between using suffix links and rescanning from the root</em>. This is what gave me a lot of bugs and headaches in my implementation.</p> <h2>Open-ended leaf nodes and their limitations</h2> <p>I'm sure you already know that the most fundamental 'trick' is to realize we can just leave the end of the suffixes 'open', i.e. referencing the current length of the string instead of setting the end to a static value. This way when we add additional characters, those characters will be implicitly added to all suffix labels, without having to visit and update all of them.</p> <p>But this open ending of suffixes – for obvious reasons – works only for nodes that represent the end of the string, i.e. the leaf nodes in the tree structure. The branching operations we execute on the tree (the addition of new branch nodes and leaf nodes) won't propagate automatically everywhere they need to.</p> <p><em>It's probably elementary, and wouldn't require mention, that repeated substrings don't appear explicitly in the tree, since the tree already contains these by virtue of them being repetitions; however, when the repetitive substring ends by encountering a non-repeating character, we need to create a branching at that point to represent the divergence from that point onwards.</em></p> <p>For example in case of the string <em>'ABCXABCY'</em> (see below), a branching to <em>X</em> and <em>Y</em> needs to be added to three different suffixes, <em>ABC</em>, <em>BC</em> and <em>C</em>; otherwise it wouldn't be a valid suffix tree, and we couldn't find all substrings of the string by matching characters from the root downwards.</p> <p>Once again, to emphasize – <em>any</em> operation we execute on a suffix in the tree needs to be reflected by its consecutive suffixes as well (e.g. ABC > BC > C), otherwise they simply cease to be valid suffixes.</p> <p><a href="https://i.stack.imgur.com/pyaNY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pyaNY.png" alt="Repeating branching in suffixes"></a></p> <p>But even if we accept that we have to do these manual updates, how do we know how many suffixes need to be updated? Since, when we add the repeated character <em>A</em> (and the rest of the repeated characters in succession), we have no idea yet when/where do we need to split the suffix into two branches. The need to split is ascertained only when we encounter the first non-repeating character, in this case <em>Y</em> (instead of the <em>X</em> that already exists in the tree).</p> <p>What we can do is to match the longest repeated string we can, and count how many of its suffixes we need to update later. This is what <em>'remainder'</em> stands for.</p> <h2>The concept of 'remainder' and 'rescanning'</h2> <p>The variable <code>remainder</code> tells us how many repeated characters we added implicitly, without branching; i.e. how many suffixes we need to visit to repeat the branching operation once we found the first character that we cannot match. This essentially equals to how many characters 'deep' we are in the tree from its root.</p> <p>So, staying with the previous example of the string <em>ABCXABCY</em>, we match the repeated <em>ABC</em> part 'implicitly', incrementing <code>remainder</code> each time, which results in remainder of 3. Then we encounter the non-repeating character <em>'Y'</em>. Here we split the previously added <em>ABCX</em> into <em>ABC</em>-><em>X</em> and <em>ABC</em>-><em>Y</em>. Then we decrement <code>remainder</code> from 3 to 2, because we already took care of the <em>ABC</em> branching. Now we repeat the operation by matching the last 2 characters – <em>BC</em> – from the root to reach the point where we need to split, and we split <em>BCX</em> too into <em>BC</em>-><em>X</em> and <em>BC</em>-><em>Y</em>. Again, we decrement <code>remainder</code> to 1, and repeat the operation; until the <code>remainder</code> is 0. Lastly, we need to add the current character (<em>Y</em>) itself to the root as well.</p> <p>This operation, following the consecutive suffixes from the root simply to reach the point where we need to do an operation is what's called <em>'rescanning'</em> in Ukkonen's algorithm, and typically this is the most expensive part of the algorithm. Imagine a longer string where you need to 'rescan' long substrings, across many dozens of nodes (we'll discuss this later), potentially thousands of times.</p> <p>As a solution, we introduce what we call <em>'suffix links'</em>.</p> <h2>The concept of 'suffix links'</h2> <p>Suffix links basically point to the positions we'd normally have to <em>'rescan'</em> to, so instead of the expensive rescan operation we can simply jump to the linked position, do our work, jump to the next linked position, and repeat – until there are no more positions to update.</p> <p>Of course one big question is how to add these links. The existing answer is that we can add the links when we insert new branch nodes, utilizing the fact that, in each extension of the tree, the branch nodes are naturally created one after another in the exact order we'd need to link them together. Though, we have to link from the last created branch node (the longest suffix) to the previously created one, so we need to cache the last we create, link that to the next one we create, and cache the newly created one.</p> <p>One consequence is that we actually often don't have suffix links to follow, because the given branch node was just created. In these cases we have to still fall back to the aforementioned <em>'rescanning'</em> from root. This is why, after an insertion, you're instructed to either use the suffix link, or jump to root.</p> <p>(Or alternatively, if you're storing parent pointers in the nodes, you can try to follow the parents, check if they have a link, and use that. I found that this is very rarely mentioned, but <em>the suffix link usage is not set in stones.</em> There are multiple possible approaches, and if you understand the underlying mechanism you can implement one that fits your needs the best.)</p> <h2>The concept of 'active point'</h2> <p>So far we discussed multiple efficient tools for building the tree, and vaguely referred to traversing over multiple edges and nodes, but haven't yet explored the corresponding consequences and complexities.</p> <p>The previously explained concept of <em>'remainder'</em> is useful for keeping track where we are in the tree, but we have to realize it doesn't store enough information.</p> <p>Firstly, we always reside on a specific edge of a node, so we need to store the edge information. We shall call this <em>'active edge'</em>.</p> <p>Secondly, even after adding the edge information, we still have no way to identify a position that is farther down in the tree, and not directly connected to the <em>root</em> node. So we need to store the node as well. Let's call this <em>'active node'</em>.</p> <p>Lastly, we can notice that the <em>'remainder'</em> is inadequate to identify a position on an edge that is not directly connected to root, because <em>'remainder'</em> is the length of the entire route; and we probably don't want to bother with remembering and subtracting the length of the previous edges. So we need a representation that is essentially the <em>remainder on the current edge</em>. This is what we call <em>'active length'</em>.</p> <p>This leads to what we call <em>'active point'</em> – a package of three variables that contain all the information we need to maintain about our position in the tree:</p> <p><code>Active Point = (Active Node, Active Edge, Active Length)</code></p> <p>You can observe on the following image how the matched route of <em>ABCABD</em> consists of 2 characters on the edge <em>AB</em> (from <em>root</em>), plus 4 characters on the edge <em>CABDABCABD</em> (from node 4) – resulting in a <em>'remainder'</em> of 6 characters. So, our current position can be identified as <em>Active Node 4, Active Edge C, Active Length 4</em>.</p> <p><a href="https://i.stack.imgur.com/FdbDQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FdbDQ.png" alt="Remainder and Active Point"></a></p> <p>Another important role of the <em>'active point'</em> is that it provides an abstraction layer for our algorithm, meaning that parts of our algorithm can do their work on the <em>'active point'</em>, irrespective of whether that active point is in the root or anywhere else. This makes it easy to implement the use of suffix links in our algorithm in a clean and straight-forward way.</p> <h2>Differences of rescanning vs using suffix links</h2> <p>Now, the tricky part, something that – in my experience – can cause plenty of bugs and headaches, and is poorly explained in most sources, is the difference in processing the suffix link cases vs the rescan cases.</p> <p>Consider the following example of the string <em>'AAAABAAAABAAC'</em>:</p> <p><a href="https://i.stack.imgur.com/YdSPZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YdSPZ.png" alt="Remainder across multiple edges"></a></p> <p>You can observe above how the <em>'remainder'</em> of 7 corresponds to the total sum of characters from root, while <em>'active length'</em> of 4 corresponds to the sum of matched characters from the active edge of the active node.</p> <p>Now, after executing a branching operation at the active point, our active node might or might not contain a suffix link.</p> <p><strong>If a suffix link is present:</strong> We only need to process the <em>'active length'</em> portion. The <em>'remainder'</em> is irrelevant, because <em>the node where we jump to via the suffix link already encodes the correct 'remainder' implicitly</em>, simply by virtue of being in the tree where it is.</p> <p><strong>If a suffix link is NOT present:</strong> We need to <em>'rescan'</em> from zero/root, which means processing the whole suffix from the beginning. To this end we have to use the whole <em>'remainder'</em> as the basis of rescanning.</p> <h2>Example comparison of processing with and without a suffix link</h2> <p>Consider what happens at the next step of the example above. Let's compare how to achieve the same result – i.e. moving to the next suffix to process – with and without a suffix link.</p> <h3><strong>Using <em>'suffix link'</em></strong></h3> <p><a href="https://i.stack.imgur.com/OXxrn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OXxrn.png" alt="Reaching consecutive suffixes via suffix links"></a></p> <p>Notice that if we use a suffix link, we are automatically 'at the right place'. Which is often not strictly true due to the fact that the <em>'active length'</em> can be 'incompatible' with the new position.</p> <p>In the case above, since the <em>'active length'</em> is 4, we're working with the suffix '<em>ABAA'</em>, starting at the linked Node 4. But after finding the edge that corresponds to the first character of the suffix (<em>'A'</em>), we notice that our <em>'active length'</em> overflows this edge by 3 characters. So we jump over the full edge, to the next node, and decrement <em>'active length'</em> by the characters we consumed with the jump.</p> <p>Then, after we found the next edge <em>'B'</em>, corresponding to the decremented suffix <em>'BAA</em>', we finally note that the edge length is larger than the remaining <em>'active length'</em> of 3, which means we found the right place.</p> <p><em>Please note that it seems this operation is usually not referred to as 'rescanning', even though to me it seems it's the direct equivalent of rescanning, just with a shortened length and a non-root starting point.</em></p> <h3><strong>Using <em>'rescan'</em></strong></h3> <p><a href="https://i.stack.imgur.com/2L6U1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2L6U1.png" alt="Reaching consecutive suffixes via rescanning"></a></p> <p>Notice that if we use a traditional 'rescan' operation (here pretending we didn't have a suffix link), we start at the top of the tree, at root, and we have to work our way down again to the right place, following along the entire length of the current suffix.</p> <p>The length of this suffix is the <em>'remainder'</em> we discussed before. We have to consume the entirety of this remainder, until it reaches zero. This might (and often does) include jumping through multiple nodes, at each jump decreasing the remainder by the length of the edge we jumped through. Then finally, we reach an edge that is longer than our remaining <em>'remainder'</em>; here we set the active edge to the given edge, set <em>'active length'</em> to remaining <em>'remainder</em>', and we're done.</p> <p>Note, however, that the actual <em>'remainder'</em> variable needs to be preserved, and only decremented after each node insertion. So what I described above assumed using a separate variable initialized to <em>'remainder'</em>.</p> <p><strong>Notes on suffix links &amp; rescans</strong></p> <p>1) Notice that both methods lead to the same result. Suffix link jumping is, however, significantly faster in most cases; that's the whole rationale behind suffix links.</p> <p>2) The actual algorithmic implementations don't need to differ. As I mentioned above, even in the case of using the suffix link, the <em>'active length'</em> is often not compatible with the linked position, since that branch of the tree might contain additional branching. So essentially you just have to use <em>'active length'</em> instead of <em>'remainder'</em>, and execute the same rescanning logic until you find an edge that is shorter than your remaining suffix length.</p> <p>3) One important remark pertaining to performance is that there is no need to check each and every character during rescanning. Due to the way a valid suffix tree is built, we can safely assume that the characters match. So you're mostly counting the lengths, and the only need for character equivalence checking arises when we jump to a new edge, since edges are identified by their first character (which is always unique in the context of a given node). This means that 'rescanning' logic is different than full string matching logic (i.e. searching for a substring in the tree).</p> <p>4) The original suffix linking described here is just <em>one of the possible approaches</em>. For example <a href="https://arxiv.org/pdf/1403.0457.pdf" rel="noreferrer">NJ Larsson et al.</a> names this approach as <em>Node-Oriented Top-Down</em>, and compares it to <em>Node-Oriented Bottom-Up</em> and two <em>Edge-Oriented</em> varieties. The different approaches have different typical and worst case performances, requirements, limitations, etc., but it generally seems that <em>Edge-Oriented</em> approaches are an overall improvement to the original.</p>
2019-04-24 09:58:09.133000+00:00
2019-04-24 09:58:09.133000+00:00
null
null
9,452,701
<p>I feel a bit thick at this point. I've spent days trying to fully wrap my head around suffix tree construction, but because I don't have a mathematical background, many of the explanations elude me as they start to make excessive use of mathematical symbology. The closest to a good explanation that I've found is <em><a href="http://marknelson.us/1996/08/01/suffix-trees/" rel="noreferrer">Fast String Searching With Suffix Trees</a></em>, but he glosses over various points and some aspects of the algorithm remain unclear.</p> <p>A step-by-step explanation of this algorithm here on Stack&nbsp;Overflow would be invaluable for many others besides me, I'm sure.</p> <p>For reference, here's Ukkonen's paper on the algorithm: <a href="http://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf" rel="noreferrer">http://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf</a></p> <p>My basic understanding, so far:</p> <ul> <li>I need to iterate through each prefix P of a given string T</li> <li>I need to iterate through each suffix S in prefix P and add that to tree</li> <li>To add suffix S to the tree, I need to iterate through each character in S, with the iterations consisting of either walking down an existing branch that starts with the same set of characters C in S and potentially splitting an edge into descendent nodes when I reach a differing character in the suffix, OR if there was no matching edge to walk down. When no matching edge is found to walk down for C, a new leaf edge is created for C.</li> </ul> <p>The basic algorithm appears to be O(n<sup>2</sup>), as is pointed out in most explanations, as we need to step through all of the prefixes, then we need to step through each of the suffixes for each prefix. Ukkonen's algorithm is apparently unique because of the suffix pointer technique he uses, though I think <em>that</em> is what I'm having trouble understanding.</p> <p>I'm also having trouble understanding:</p> <ul> <li>exactly when and how the "active point" is assigned, used and changed</li> <li>what is going on with the canonization aspect of the algorithm</li> <li>Why the implementations I've seen need to "fix" bounding variables that they are using</li> </ul> <hr> <p>Here is the completed <strong>C#</strong> source code. It not only works correctly, but supports automatic canonization and renders a nicer looking text graph of the output. Source code and sample output is at:</p> <blockquote> <p><strong><a href="https://gist.github.com/2373868" rel="noreferrer">https://gist.github.com/2373868</a></strong></p> </blockquote> <hr> <p><strong>Update 2017-11-04</strong></p> <p>After many years I've found a new use for suffix trees, and have implemented the algorithm in <strong>JavaScript</strong>. Gist is below. It should be bug-free. Dump it into a js file, <code>npm install chalk</code> from the same location, and then run with node.js to see some colourful output. There's a stripped down version in the same Gist, without any of the debugging code.</p> <blockquote> <p><strong><a href="https://gist.github.com/axefrog/c347bf0f5e0723cbd09b1aaed6ec6fc6" rel="noreferrer">https://gist.github.com/axefrog/c347bf0f5e0723cbd09b1aaed6ec6fc6</a></strong></p> </blockquote>
2012-02-26 11:30:09.650000+00:00
2020-07-29 05:17:22.430000+00:00
2020-07-29 05:17:22.430000+00:00
string|algorithm|data-structures|language-agnostic|suffix-tree
['https://github.com/baratgabor/SuffixTree', 'https://i.stack.imgur.com/pyaNY.png', 'https://i.stack.imgur.com/FdbDQ.png', 'https://i.stack.imgur.com/YdSPZ.png', 'https://i.stack.imgur.com/OXxrn.png', 'https://i.stack.imgur.com/2L6U1.png', 'https://arxiv.org/pdf/1403.0457.pdf']
7
63,907,870
<p>This is very much possible, and has resulted in a vast area of research called Generative Adversarial Networks (GANs).</p> <p>First off, let me list the problems with your approach:</p> <ol> <li><p>You use a single number as input and expect the model to understand it. This does not practically work. It's better to use a representation called one-hot encoding.</p> </li> <li><p>For each label, multiple images exist. Mathematically, if the domain X consists of labels (one-hot encoded or not) and the range Y consists of images, the relationship is a one-to-many relationship, which can't be learned in a supervised fashion. By its very nature, supervised learning can be used to model only many-to-one relationships, or one-to-one relationships (although there is no point in using ML for this; dictionaries are a much better choice). Therefore, it is easy to predict labels for images, but impossible to generate images for labels using fully supervised approaches, unless you use only one image per label for training.</p> </li> </ol> <p>The way GANs solve the problem in (2) is by generating a &quot;probable&quot; image given a set of random values. Variations of GANs allow specifying the exact value to generate.</p> <p>I suggest reading the <a href="https://arxiv.org/abs/1406.2661" rel="nofollow noreferrer">paper</a> that introduced GANs. Then try out the basic GAN before moving on to generate specific numbers.</p>
2020-09-15 18:30:02.983000+00:00
2020-09-15 18:38:59.047000+00:00
2020-09-15 18:38:59.047000+00:00
null
63,907,371
<p>I'm a beginner in datascience and tensorflow, so, as a test of my &quot;skills&quot; I wanted to try and make an AI that you give a number to and then gives back a 28x28 pixel image of that number. It is possible to do this the other way around, so I figured, why not? So the code works pretty well actually, but the accuracy of the AI is very low, so low in fact that it just returns random pixels. Is there any way to make this AI more accurate, apart from maybe doing like 100 epochs or something? Heres the code I'm using:</p> <pre><code>import tensorflow as tf import tensorflow.keras as tk import numpy as np import matplotlib.pyplot as plt (train_data, train_labels), (test_data, test_labels) = tk.datasets.mnist.load_data() model = tk.Sequential([ tk.layers.Dense(64, activation='relu'), tk.layers.Dense(64, activation='relu'), tk.layers.Dense(784, activation='relu')]) history = model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics=['acc']) train_data = np.reshape(train_data, (60000, 784)) test_data = np.reshape(test_data, (-1, 784)) model.fit(train_labels, train_data, epochs=10, validation_data=(test_labels, test_data)) result = model.predict([2]) result = np.reshape(result, (28, 28)) plt.imshow(result) plt.show() </code></pre> <p>I'm using google.colab since I havent yet been able to install tensorflow in my computer, maybe it has something to do with that. Thanks for any answers in advance!</p>
2020-09-15 17:52:35.183000+00:00
2020-09-15 18:38:59.047000+00:00
null
python|artificial-intelligence|tensorflow2.0
['https://arxiv.org/abs/1406.2661']
1
50,472,409
<p>An easy way to get you started would be to create 161 columns (8 columns for each of the 20 time steps + the designated label). You would rearrange the columns like</p> <pre><code>emg1_t01, emg2_t01, emg3_t01, ..., emg8_t20, gesture_id </code></pre> <p>This will give you the right 2D format to use different algorithms in <a href="http://scikit-learn.org/stable/" rel="nofollow noreferrer">sklearn</a> as well as a feed forward neural network in CNTK. You would use the first 160 columns to predict the 161th one.</p> <p>Once you have that working you can model your data to better represent the natural time series order it contains. You would move away from a 2D shape and instead create a 3D array to represent your data.</p> <ul> <li>The first axis shows the number of samples</li> <li>The second axis shows the number of time steps (20)</li> <li>The thirst axis shows the number of sensors (8)</li> </ul> <p>With this shape you're all set to use a 1D convolutional model (CNN) in CNTK that traverses the time axis to learn local patterns from one step to the next.</p> <p>You might also want to look into RNNs which are often used to work with time series data. However, RNNs are sometimes hard to train and a <a href="https://arxiv.org/abs/1803.01271" rel="nofollow noreferrer">recent paper</a> suggests that CNNs should be the natural starting point to work with sequence data.</p>
2018-05-22 16:23:43.927000+00:00
2018-05-22 16:23:43.927000+00:00
null
null
50,471,492
<p>I'm trying to develop a model to recognize new gestures with the Myo Armband. (It's an armband that possesses 8 electrical sensors and can recognize 5 hand gestures). I'd like to record the sensors' raw data for a new gesture and feed it to a model so it can recognize it.</p> <p>I'm new to machine/deep learning and I'm using CNTK. I'm wondering what would be the best way to do it. </p> <p>I'm struggling to understand how to create the trainer. The input data looks like something like <a href="https://i.stack.imgur.com/HeA7k.png" rel="nofollow noreferrer">that</a> I'm thinking about using 20 sets of these 8 values (they're between -127 and 127). So one label is the output of 20 sets of values.</p> <p>I don't really know how to do that, I've seen tutorials where images are linked with their label but it's not the same idea. And even after the training is done, how can I avoid the model to recognize this one gesture whatever I do since it's the only one it's been trained for.</p>
2018-05-22 15:32:02.207000+00:00
2018-09-19 06:58:37.737000+00:00
2018-09-19 06:58:37.737000+00:00
deep-learning|label|gesture|cntk|myo
['http://scikit-learn.org/stable/', 'https://arxiv.org/abs/1803.01271']
2
55,413,955
<p><strong><em>Dense CNN is a type of Deep CNN in which each layer is connected with another layer deeper than itself.</em></strong></p> <h2>What does that mean ?</h2> <p>In normal CNN each layer is only connected to its siblings. Consider 4 layers,output from L1 is connected to only L2, output from L2 is connected only to L3, output from L3 is connected only to L4.</p> <p>In a dense CNN, consider 4 layers, output from L1 is connected to L2, L3, L4, output from L2 is connected to L3, L4, output from L3 is connected to L4. </p> <p>Here is a figure to illustrate it (source of the image is from <a href="https://arxiv.org/pdf/1608.06993.pdf" rel="nofollow noreferrer">this</a> paper):</p> <p><a href="https://i.stack.imgur.com/aboFF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aboFF.png" alt="enter image description here"></a></p> <h2>Why do we need to do this ?</h2> <p>Nowadays we have neural networks with 100 layers or even more. Neural networks are trained using backpropagation. In this algorithm, gradient (derivative) of the cost function is used to update the weights of each layer. With each new layer, the value of gradient diminishes, specially if you are using sigmoid. This results in longer time to train or sometimes it doesn't train at all. This problem is also known as <em>vanishing gradient</em>. Direct connection in Dense CNN solves this problem.</p> <p>Dense CNN are also less prone to overfitting as compared to normal CNN.</p> <p>For more read <a href="https://arxiv.org/abs/1608.06993" rel="nofollow noreferrer">this</a> paper, it's pretty easy to follow. </p>
2019-03-29 09:11:39.493000+00:00
2019-03-29 09:11:39.493000+00:00
null
null
55,406,924
<p>I know it might be a silly question but am kind of new to machine learning and ANN.</p> <p>Is there any difference between Deep convolutional neural network and Dense Convolutional neural network? </p> <p>Thanks in advance!</p>
2019-03-28 21:12:59.933000+00:00
2019-03-29 09:11:39.493000+00:00
2019-03-28 22:54:23.660000+00:00
machine-learning|neural-network|deep-learning|conv-neural-network
['https://arxiv.org/pdf/1608.06993.pdf', 'https://i.stack.imgur.com/aboFF.png', 'https://arxiv.org/abs/1608.06993']
3
3,098,062
<p>Just an idea. Why not throw some bots in there in the monte carlo fashion. Let's call the first generation of bots gen0. We only keep the bots from gen0 that have some continuous roads in this way: <br>-from the start to some point <br>or -from some point to the end</p> <p>We run a new gen1 of bots in new random dots, then we try to connect the roads of the bots of gen1 with those of gen0 and see if we get a continous road from start to finish.</p> <p>So for genn we try to connect with the bots form gen0, gen1, ..., genn-1.</p> <p>Of course a generation lasts only a feasibil finit amount of time.</p> <p>I don't know if the complexion of the algorithm will prove to be practical for small data sets. <br>Also the algorithm assumes we know start and finish points.</p> <p><br> some good sites for ideas: <br> <a href="http://citeseerx.ist.psu.edu/" rel="nofollow noreferrer">http://citeseerx.ist.psu.edu/</a> <br> <a href="http://arxiv.org/" rel="nofollow noreferrer">http://arxiv.org/</a></p>
2010-06-23 00:05:05.657000+00:00
2010-06-23 00:13:24.790000+00:00
2010-06-23 00:13:24.790000+00:00
null
3,097,556
<p>What are the possible ways to solve a maze?<br> Ive got two ideas, but I think they are not very elegant.</p> <p><strong>Base situation:</strong> We have a matrix, and the elements in this matrix are ordered in a way that it represents a maze, with one way in, and one out.</p> <p>My first idea was to send a robot through the maze, following one side, until it's out of the maze. I think this is a very slow solution.</p> <p>The second one passes through every successive item marked with 1, checks where it can go (up, right, down, left) chooses one way and it continues its path there. This is even slower than the first one.</p> <p>Of course it's a bit faster if I make the two bots multi-threaded at every junction, but thats also not the best way.</p> <p>There needs to be better solutions to send a bot through a maze.</p> <p><strong>EDIT</strong><br> First: Thanks for the nice answers!</p> <p><strong>The second part of my question is:</strong> What to do in the case if we have a multi-dimensional graph? Are there special practices for that, or is the answer of Justin L. usable for that too?<br> I think it's not the best way for this case.</p> <p><strong>The third question:</strong><br> Which of these maze solver algorithms is/are the fastest? (Purely hypothetically)</p>
2010-06-22 22:17:13.273000+00:00
2016-07-15 18:52:57.957000+00:00
2014-09-15 15:51:32.070000+00:00
algorithm|maze
['http://citeseerx.ist.psu.edu/', 'http://arxiv.org/']
2
38,954,700
<p>Yes, this has already been done and well documented in several research papers, like <a href="http://arxiv.org/abs/1403.6382" rel="nofollow">CNN Features off-the-shelf: an Astounding Baseline for Recognition</a> and <a href="https://arxiv.org/abs/1411.1792" rel="nofollow">How transferable are features in deep neural networks?</a>. Both show that using CNN features trained on one dataset, but tested on a different one usually perform very well or beat the state of the art.</p> <p>In general you can take the features from the layer before the last, normalize them and use them with another classifier.</p> <p>Another related technique is fine tuning, where after training a network, the last layer is replaced and retrained, but previous layers' weights are kept fixed.</p>
2016-08-15 12:01:18.863000+00:00
2016-08-15 12:01:18.863000+00:00
null
null
38,940,192
<p>My question is can we use CNN for feature extraction and then can we use this extracted feature as an input to another classification algorithm like SVM.</p> <p>Thanks</p>
2016-08-14 07:44:25.617000+00:00
2017-10-05 06:56:15.823000+00:00
2017-10-05 06:56:15.823000+00:00
neural-network
['http://arxiv.org/abs/1403.6382', 'https://arxiv.org/abs/1411.1792']
2
60,576,034
<p>If you apply a convolution with <code>kernel_size</code> > 1 and <code>strides</code> > 1 the output is going to have a smaller dimension than the input.</p> <p>For example:</p> <pre><code>Conv2D(filters=6, kernel_size=5, stride=2) </code></pre> <p>Would take an input of dimension <code>(32,32,1)</code> and give an output of dimension <code>(28,28,6)</code>. This causes a problem if you try to add this to a <a href="https://arxiv.org/abs/1512.03385" rel="nofollow noreferrer">ResNet</a> style shortcut block because it isn't clear how add to tensors of different dimensions.</p> <p>There are several ways to deal with this.</p> <ul> <li>Do not reduce the dimension from the convolution (keep stride=1)</li> <li>Reduce the size of the shortcut block by using a 1x1 convolution kernel with the same stride as used in <code>Conv2D</code> </li> <li>Change the number of output channels of the shortcut block to be the same as the number of filters in <code>Conv2D</code></li> </ul>
2020-03-07 09:13:03.447000+00:00
2020-03-07 09:13:03.447000+00:00
null
null
60,575,399
<p>I was creating a CNN with a size of 80 for the first hidden layer, 160 for the rest of the conv layers, and 128 for the last hidden layer. But I keep running into an error message and I don't really know what it means. The input data shape is (80, 80, 1) which is what I feed into the neural network. </p> <p>Here is the code to create the CNN:</p> <pre><code> if start_model is not None: model = load_model(start_model) else: def res_net_block(input_layers, conv_size, hm_filters, hm_strides): x = Conv2D(conv_size, kernel_size=hm_filters, strides=hm_strides, activation="relu", padding="same")(input_layers) x = BatchNormalization()(x) x = Conv2D(conv_size, kernel_size=hm_filters, strides=hm_strides, activation=None, padding="same")(x) x = Add()([x, input_layers]) # Creates resnet block x = Activation("relu")(x) return x input = keras.Input(i_shape) x = Conv2D(80, kernel_size=8, strides=4, activation="relu")(input) x = BatchNormalization()(x) for i in range(3): x = res_net_block(x, 160, 4, 2) x = Conv2D(160, kernel_size=4, strides=2, activation="relu")(x) x = BatchNormalization()(x) x = Flatten(input_shape=(np.prod(window_size), 1, 1))(x) x = Dense(128, activation="relu")(x) output = Dense(action_space_size, activation="linear")(x) model = keras.Model(input, output) model.compile(optimizer=Adam(lr=0.01), loss="mse", metrics=["accuracy"]) </code></pre> <p>BTW the error message is located at <code>x = Add()([x, input_layers])</code> in the code</p>
2020-03-07 07:32:21.260000+00:00
2020-03-07 09:13:03.447000+00:00
null
python|tensorflow|machine-learning|artificial-intelligence|conv-neural-network
['https://arxiv.org/abs/1512.03385']
1
58,247,597
<p>Yup, that is the current problem with Capsule Networks. It works well with MNIST because of the dataset's simplicity. All you require is some edges and blobs to be detected in order to classify each data. For more complex datasets, naively stacking the capsules and hoping it to perform well does not work. However, works are being performed currently to tweak the current CapsNet architecture to make it perform better than now. When CNN was developed during the days, it also had this same problem. It took many years for CNN to be what is it now. </p> <p>Refer to this paper if you want to know the performance of CapsNet on different datasets : <a href="https://arxiv.org/abs/1712.03480" rel="nofollow noreferrer">https://arxiv.org/abs/1712.03480</a></p> <p>Earlier I mentioned there are works being done to improve CapsNet. However, there are already some works that has been done so far. You can refer to these:</p> <p><a href="http://openaccess.thecvf.com/content_CVPR_2019/papers/Rajasegaran_DeepCaps_Going_Deeper_With_Capsule_Networks_CVPR_2019_paper.pdf" rel="nofollow noreferrer">http://openaccess.thecvf.com/content_CVPR_2019/papers/Rajasegaran_DeepCaps_Going_Deeper_With_Capsule_Networks_CVPR_2019_paper.pdf</a></p> <p><a href="http://proceedings.mlr.press/v97/jeong19b/jeong19b.pdf" rel="nofollow noreferrer">http://proceedings.mlr.press/v97/jeong19b/jeong19b.pdf</a></p> <p>Bear in mind that the time it takes to train CapsNet is very much higher than CNN. Therefore, it is not easy to test out these architectures.</p>
2019-10-05 10:51:10.390000+00:00
2019-10-05 10:51:10.390000+00:00
null
null
55,579,930
<p>I implement Capsule Network by EM-Routing based-on Sara Sabour &amp; Hinton's article, It works great on MNIST dataset and some other grayscale dataset as same as MNIST such as Hoda (Persian/Arabic Digits) but When I tried on CIFAR10 the accuracy was unbelievable low.</p>
2019-04-08 18:48:11.060000+00:00
2019-10-05 10:51:10.390000+00:00
null
tensorflow|deep-learning|conv-neural-network|mnist
['https://arxiv.org/abs/1712.03480', 'http://openaccess.thecvf.com/content_CVPR_2019/papers/Rajasegaran_DeepCaps_Going_Deeper_With_Capsule_Networks_CVPR_2019_paper.pdf', 'http://proceedings.mlr.press/v97/jeong19b/jeong19b.pdf']
3
27,455,586
<p>If a problem is <strong>NP</strong>-hard, under the assumption that <strong>P</strong> ≠ <strong>NP</strong> there is no algorithm that is</p> <ul> <li>deterministic,</li> <li>exactly correct on all inputs all the time, and</li> <li>efficient on all possible inputs.</li> </ul> <p>If you absolutely need all of the above guarantees, then you're pretty much out of luck. However, if you're willing to settle for a solution to the problem that relaxes some of these constraints, then there very well still might be hope! Here are a few options to consider.</p> <h2>Option One: Approximation Algorithms</h2> <p>If a problem is <strong>NP</strong>-hard and <strong>P</strong> ≠ <strong>NP</strong>, it means that there's is no algorithm that will always efficiently produce the exactly correct answer on all inputs. But what if you don't need the exact answer? What if you just need answers that are <em>close</em> to correct? In some cases, you may be able to combat <strong>NP</strong>-hardness by using an approximation algorithm.</p> <p>For example, a canonical example of an <strong>NP</strong>-hard problem is the <a href="http://en.wikipedia.org/wiki/Travelling_salesman_problem" rel="noreferrer">traveling salesman problem</a>. In this problem, you're given as input a complete graph representing a transportation network. Each edge in the graph has an associated weight. The goal is to find a cycle that goes through every node in the graph exactly once and which has minimum total weight. In the case where the edge weights satisfy the <a href="http://en.wikipedia.org/wiki/Triangle_inequality" rel="noreferrer">triangle inequality</a> (that is, the best route from point A to point B is always to follow the direct link from A to B), then you can get back a cycle whose cost is at most 3/2 optimal by using the <a href="http://en.wikipedia.org/wiki/Christofides_algorithm" rel="noreferrer">Christofides algorithm</a>.</p> <p>As another example, the <a href="http://en.wikipedia.org/wiki/Knapsack_problem" rel="noreferrer">0/1 knapsack problem</a> is known to be <strong>NP</strong>-hard. In this problem, you're given a bag and a collection of objects with different weights and values. The goal is to pack the maximum value of objects into the bag without exceeding the bag's weight limit. Even though computing an <em>exact</em> answer requires exponential time in the worst case, it's possible to approximate the correct answer to an arbitrary degree of precision in polynomial time. (The algorithm that does this is called a fully polynomial-time approximation scheme or <em><a href="http://en.wikipedia.org/wiki/Polynomial-time_approximation_scheme" rel="noreferrer">FPTAS</a></em>).</p> <p>Unfortunately, we do have some theoretical limits on the approximability of certain <strong>NP</strong>-hard problems. The Christofides algorithm mentioned earlier gives a 3/2 approximation to TSP where the edges obey the triangle inequality, but interestingly enough it's possible to show that if <strong>P</strong> ≠ <strong>NP</strong>, there is no polynomial-time approximation algorithm for TSP that can get within <em>any</em> constant factor of optimal. Usually, you need to do some research to learn more about which problems can be well-approximated and which ones can't, since many <strong>NP</strong>-hard problems can be approximated well and many can't. There doesn't seem to be a unified theme.</p> <h2>Option Two: Heuristics</h2> <p>In many <strong>NP</strong>-hard problems, standard approaches like greedy algortihms won't always produce the right answer, but often do reasonably well on &quot;reasonable&quot; inputs. In many cases, it's reasonable to attack <strong>NP</strong>-hard problems with <em>heuristics</em>. The exact definition of a heuristic varies from context to context, but typically a heuristic is either an approach to a problem that &quot;often&quot; gives back good answers at the cost of sometimes giving back wrong answers, or is a useful rule of thumb that helps speed up searches even if it might not always guide the search the right way.</p> <p>As an example of the first type of heuristic, let's look at the <a href="http://en.wikipedia.org/wiki/Graph_coloring" rel="noreferrer">graph-coloring problem</a>. This <strong>NP</strong>-hard problem asks, given a graph, to find the minimum number of colors necessary to paint the nodes in the graph such that no edge's endpoints are the same color. This turns out to be a particularly tough problem to solve with many other approaches (the best known approximation algorithms have terrible bounds, and it's not suspected to have a parameterized efficient algorithm). However, there are many heuristics for graph coloring that do quite well in practice. Many <a href="http://en.wikipedia.org/wiki/Greedy_coloring" rel="noreferrer">greedy coloring heuristics</a> exist for assigning colors to nodes in a reasonable order, and these heuristics often do quite well in practice. Unfortunately, sometimes these heuristics give terrible answers back, but provided that the graph isn't pathologically constructed the heuristics often work just fine.</p> <p>As an example of the second type of heuristic, it's helpful to look at SAT solvers. <a href="http://en.wikipedia.org/wiki/Boolean_satisfiability_problem" rel="noreferrer">SAT</a>, the Boolean satisfiability problem, was the first problem proven to be <strong>NP</strong>-hard. The problem asks, given a propositional formula (often written in <a href="http://en.wikipedia.org/wiki/Conjunctive_normal_form" rel="noreferrer">conjunctive normal form</a>), to determine whether there is a way to assign values to the variables such that the overall formula evaluates to true. <a href="http://www.satcompetition.org/" rel="noreferrer">Modern SAT solvers</a> are getting quite good at solving SAT in many cases by using heuristics to guide their search over possible variable assignments. One famous SAT-solving algorithm, <a href="http://en.wikipedia.org/wiki/DPLL_algorithm" rel="noreferrer">DPLL</a>, essentially tries all possible assignments to see if the formula is satisfiable, using heuristics to speed up the search. For example, if it finds that a variable is either always true or always false, DPLL will try assigning that variable its forced value before trying other variables. DPLL also finds unit clauses (clauses with just one literal) and sets those variables' values before trying other variables. The net effect of these heuristics is that DPLL ends up being very fast in practice, even though it's known to have exponential worst-case behavior.</p> <h2>Option Three: Pseudopolynomial-Time Algorithms</h2> <p>If <strong>P</strong> ≠ <strong>NP</strong>, then no <strong>NP</strong>-hard problem can be solved in polynomial time. However, in some cases, the definition of &quot;polynomial time&quot; doesn't necessarily match the standard intuition of polynomial time. Formally speaking, polynomial time means polynomial in the number of bits necessary to specify the input, which doesn't always sync up with what we consider the input to be.</p> <p>As an example, consider the <a href="http://en.wikipedia.org/wiki/Partition_problem" rel="noreferrer">set partition problem</a>. In this problem, you're given a set of numbers and need to determine whether there's a way to split the set into two smaller sets, each of which has the same sum. The naive solution to this problem runs in time O(2<sup>n</sup>) and works by just brute-force testing all subsets. With dynamic programming, though, it's possible to solve this problem in time O(nN), where n is the number of elements in the set and N is the maximum value in the set. Technically speaking, the runtime O(nN) is not polynomial time because the numeric value N is written out in only log<sub>2</sub> N bits, but assuming that the numeric value of N isn't too large, this is a perfectly reasonable runtime.</p> <p>This algorithm is called a <a href="http://en.wikipedia.org/wiki/Pseudo-polynomial_time" rel="noreferrer">pseudopolynomial-time algorithm</a> because the runtime O(nN) &quot;looks&quot; like a polynomial, but technically speaking is exponential in the size of the input. Many <strong>NP</strong>-hard problems, especially ones involving numeric values, admit pseudopolynomial-time algorithms and are therefore easy to solve assuming that the numeric values aren't too large.</p> <p>For more information on pseudopolynomial time, check out <a href="https://stackoverflow.com/questions/19647658/what-is-pseudopolynomial-time-how-does-it-differ-from-polynomial-time">this earlier Stack Overflow question about pseudopolynomial time</a>.</p> <h2>Option Four: Randomized Algorithms</h2> <p>If a problem is <strong>NP</strong>-hard and <strong>P</strong> ≠ <strong>NP</strong>, then there is no <em>deterministic</em> algorithm that can solve that problem in worst-case polynomial time. But what happens if we allow for algorithms that introduce randomness? If we're willing to settle for an algorithm that gives a good answer <em>on expectation</em>, then we can often get relatively good answers to <strong>NP</strong>-hard problems in not much time.</p> <p>As an example, consider the <a href="http://en.wikipedia.org/wiki/Maximum_cut" rel="noreferrer">maximum cut problem</a>. In this problem, you're given an undirected graph and want to find a way to split the nodes in the graph into two nonempty groups A and B with the maximum number of edges running between the groups. This has some interesting applications in computational physics (unfortunately, I don't understand them at all, but you can peruse <a href="http://theory.stanford.edu/%7Ejvondrak/data/maxcut.ps" rel="noreferrer">this paper</a> for some details about this). This problem is known to be <strong>NP</strong>-hard, but there's a simple randomized approximation algorithm for it. If you just toss each node into one of the two groups completely at random, you end up with a cut that, on expectation, is within 50% of the optimal solution.</p> <p>Returning to SAT, many modern SAT solvers use some degree of randomness to guide the search for a satisfying assignment. The <a href="http://en.wikipedia.org/wiki/WalkSAT" rel="noreferrer">WalkSAT and GSAT</a> algorithms, for example, work by picking a random clause that isn't currently satisfied and trying to satisfy it by flipping some variable's truth value. This often guides the search toward a satisfying assignment, causing these algorithms to work well in practice.</p> <p>It turns out there's a lot of open theoretical problems about the ability to solve <strong>NP</strong>-hard problems using randomized algorithms. If you're curious, check out the complexity class <strong><a href="http://en.wikipedia.org/wiki/BPP_%28complexity%29" rel="noreferrer">BPP</a></strong> and the open problem of its relation to <strong>NP</strong>.</p> <h2>Option Five: Parameterized Algorithms</h2> <p>Some <strong>NP</strong>-hard problems take in multiple different inputs. For example, the <a href="http://en.wikipedia.org/wiki/Longest_path_problem" rel="noreferrer">long path problem</a> takes as input a graph and a length k, then asks whether there's a simple path of length k in the graph. The <a href="http://en.wikipedia.org/wiki/Subset_sum_problem" rel="noreferrer">subset sum problem</a> takes in as input a set of numbers and a target number k, then asks whether there's a subset of the numbers that dds up to exactly k.</p> <p>Interestingly, in the case of the long path problem, there's an algorithm (the <a href="http://en.wikipedia.org/wiki/Color-coding" rel="noreferrer">color-coding algorithm</a>) whose runtime is O((n<sup>3</sup> log n) · b<sup>k</sup>), where n is the number of nodes, k is the length of the requested path, and b is some constant. This runtime is exponential in k, but is only polynomial in n, the number of nodes. This means that if k is fixed and known in advance, the runtime of the algorithm as a function of the number of nodes is only O(n<sup>3</sup> log n), which is quite a nice polynomial. Similarly, in the case of the subset sum problem, there's a dynamic programming algorithm whose runtime is O(nW), where n is the number of elements of the set and W is the maximum weight of those elements. If W is fixed in advance as some constant, then this algorithm will run in time O(n), meaning that it will be possible to exactly solve subset sum in linear time.</p> <p>Both of these algorithms are examples of <a href="http://en.wikipedia.org/wiki/Parameterized_complexity#FPT" rel="noreferrer">parameterized algorithms</a>, algorithms for solving <strong>NP</strong>-hard problems that split the hardness of the problem into two pieces - a &quot;hard&quot; piece that depends on some input parameter to the problem, and an &quot;easy&quot; piece that scales gracefully with the size of the input. These algorithms can be useful for finding exact solutions to <strong>NP</strong>-hard problems when the parameter in question is small. The color-coding algorithm mentioned above, for example, has proven quite useful in practice in computational biology.</p> <p>However, some problems are conjectured to not have any nice parameterized algorithms. Graph coloring, for example, is suspected to not have any efficient parameterized algorithms. In the cases where parameterized algorithms exist, they're often quite efficient, but you can't rely on them for all problems.</p> <p>For more information on parameterized algorithms, check out <a href="https://stackoverflow.com/questions/19643939/what-is-fixed-parameter-tractability-why-is-it-useful">this earlier Stack Overflow question</a>.</p> <h2>Option Six: Fast Exponential-Time Algorithms</h2> <p>Exponential-time algorithms don't scale well - their runtimes approach the lifetime of the universe for inputs as small as 100 or 200 elements.</p> <p>What if you need to solve an <strong>NP</strong>-hard problem, but you know the input is reasonably small - say, perhaps its size is somewhere between 50 and 70. Standard exponential-time algorithms are probably not going to be fast enough to solve these problems. What if you really do need an exact solution to the problem and the other approaches here won't cut it?</p> <p>In some cases, there are &quot;optimized&quot; exponential-time algorithms for <strong>NP</strong>-hard problems. These are algorithms whose runtime is exponential, but not as bad an exponential as the naive solution. For example, a simple exponential-time algorithm for the 3-coloring problem (given a graph, determine if you can color the nodes one of three colors each so that no edge's endpoints are the same color) might work checking each possible way of coloring the nodes in the graph, testing if any of them are 3-colorings. There are 3<sup>n</sup> possible ways to do this, so in the worst case the runtime of this algorithm will be O(3<sup>n</sup> · poly(n)) for some small polynomial poly(n). However, using more clever tricks and techniques, it's possible to develop an algorithm for 3-colorability that runs in time <a href="http://arxiv.org/pdf/cs/0006046v1.pdf" rel="noreferrer">O(1.3289<sup>n</sup>)</a>. This is still an exponential-time algorithm, but it's a much faster exponential-time algorithm. For example, 3<sup>19</sup> is about 10<sup>9</sup>, so if a computer can do one billion operations per second, it can use our initial brute-force algorithm to (roughly speaking) solve 3-colorability in graphs with up to 19 nodes in one second. Using the O((1.3289<sup>n</sup>)-time exponential algorithm, we could solve instances of up to about 73 nodes in about a second. That's a huge improvement - we've grown the size we can handle in one second by more than a factor of three!</p> <p>As another famous example, consider the traveling salesman problem. There's an obvious O(n! · poly(n))-time solution to TSP that works by enumerating all permutations of the nodes and testing the paths resulting from those permutations. However, by using a dynamic programming algorithm similar to that used by the color-coding algorithm, it's possible to improve the runtime to &quot;only&quot; O(n<sup>2</sup> 2<sup>n</sup>). Given that 13! is about one billion, the naive solution would let you solve TSP for 13-node graphs in roughly a second. For comparison, the DP solution lets you solve TSP on 28-node graphs in about one second.</p> <p>These fast exponential-time algorithms are often useful for boosting the size of the inputs that can be exactly solved in practice. Of course, they still run in exponential time, so these approaches are typically not useful for solving very large problem instances.</p> <h2>Option Seven: Solve an Easy Special Case</h2> <p>Many problems that are <strong>NP</strong>-hard in general have restricted special cases that are known to be solvable efficiently. For example, while in general it’s <strong>NP</strong>-hard to determine <a href="http://en.wikipedia.org/wiki/Graph_coloring" rel="noreferrer">whether a graph has a <em>k</em>-coloring</a>, in the specific case of <em>k</em> = 2 this is equivalent to checking whether a graph is bipartite, which can be checked in linear time using a modified depth-first search. Boolean satisfiability is, generally speaking, <strong>NP</strong>-hard, but it can be solved in polynomial time if you have an input formula with at most two literals per clause, or where the formula is formed from clauses using XOR rather than inclusive-OR, etc. Finding the largest independent set in a graph is generally speaking <strong>NP</strong>-hard, but if the graph is bipartite this can be done efficiently due to König’s theorem.</p> <p>As a result, if you find yourself needing to solve what might initially appear to be an <strong>NP</strong>-hard problem, first check whether the inputs you actually need to solve that problem on have some additional restricted structure. If so, you might be able to find an algorithm that applies to your special case and runs much faster than a solver for the problem in its full generality.</p> <h2>Conclusion</h2> <p>If you need to solve an <strong>NP</strong>-hard problem, don't despair! There are lots of great options available that might make your intractable problem a lot more approachable. No one of the above techniques works in all cases, but by using some combination of these approaches, it's usually possible to make progress even when confronted with <strong>NP</strong>-hardness.</p> <p>Hope this helps!</p>
2014-12-13 04:36:48.540000+00:00
2022-01-21 16:21:08.397000+00:00
2022-01-21 16:21:08.397000+00:00
null
27,455,585
<p>There are a lot of real-world problems that turn out to be <a href="https://en.wikipedia.org/wiki/NP-hard" rel="noreferrer"><strong>NP</strong>-hard</a>. If we assume that <strong>P</strong> &ne; <strong>NP</strong>, there aren't any polynomial-time algorithms for these problems.</p> <p>If you have to solve one of these problems, is there any hope that you'll be able to do so efficiently? Or are you just out of luck?</p>
2014-12-13 04:36:48.540000+00:00
2022-01-21 16:21:08.397000+00:00
2018-10-27 19:17:55.573000+00:00
performance|time-complexity|np
['http://en.wikipedia.org/wiki/Travelling_salesman_problem', 'http://en.wikipedia.org/wiki/Triangle_inequality', 'http://en.wikipedia.org/wiki/Christofides_algorithm', 'http://en.wikipedia.org/wiki/Knapsack_problem', 'http://en.wikipedia.org/wiki/Polynomial-time_approximation_scheme', 'http://en.wikipedia.org/wiki/Graph_coloring', 'http://en.wikipedia.org/wiki/Greedy_coloring', 'http://en.wikipedia.org/wiki/Boolean_satisfiability_problem', 'http://en.wikipedia.org/wiki/Conjunctive_normal_form', 'http://www.satcompetition.org/', 'http://en.wikipedia.org/wiki/DPLL_algorithm', 'http://en.wikipedia.org/wiki/Partition_problem', 'http://en.wikipedia.org/wiki/Pseudo-polynomial_time', 'https://stackoverflow.com/questions/19647658/what-is-pseudopolynomial-time-how-does-it-differ-from-polynomial-time', 'http://en.wikipedia.org/wiki/Maximum_cut', 'http://theory.stanford.edu/%7Ejvondrak/data/maxcut.ps', 'http://en.wikipedia.org/wiki/WalkSAT', 'http://en.wikipedia.org/wiki/BPP_%28complexity%29', 'http://en.wikipedia.org/wiki/Longest_path_problem', 'http://en.wikipedia.org/wiki/Subset_sum_problem', 'http://en.wikipedia.org/wiki/Color-coding', 'http://en.wikipedia.org/wiki/Parameterized_complexity#FPT', 'https://stackoverflow.com/questions/19643939/what-is-fixed-parameter-tractability-why-is-it-useful', 'http://arxiv.org/pdf/cs/0006046v1.pdf', 'http://en.wikipedia.org/wiki/Graph_coloring']
25
55,574,263
<p>To use custom image size in MobileNet, download weights form this link: <a href="https://github.com/fchollet/deep-learning-models/releases/tag/v0.6" rel="nofollow noreferrer">https://github.com/fchollet/deep-learning-models/releases/tag/v0.6</a> </p> <p>But make sure which weights you need because it contains different weights files according to the research paper of <a href="https://arxiv.org/pdf/1704.04861.pdf" rel="nofollow noreferrer">MobileNet</a>, as each model is dependent on the parameters <code>alpha</code> and <code>depth_multiplier</code>. There are four different values for <code>alpha</code>: 0.25, 0.50, 0.75, 1.0. Also, <code>depth_multiplier</code> is 1 according to this implementation of <a href="https://github.com/keras-team/keras-applications/blob/master/keras_applications/mobilenet.py" rel="nofollow noreferrer">mobilenet</a>. I would recommend that you download <a href="https://github.com/fchollet/deep-learning-models/releases/download/v0.6/mobilenet_1_0_224_tf.h5" rel="nofollow noreferrer"><code>mobilenet_1_0_224_tf.h5</code></a>. It has the highest ImageNet accuracy among all according to <a href="https://arxiv.org/pdf/1704.04861.pdf" rel="nofollow noreferrer">research paper Table 7</a>.</p> <p>After that,</p> <pre class="lang-py prettyprint-override"><code>from keras.applications.mobilenet import MobileNet feature_model = MobileNet(include_top=False, weights=None, input_shape=(200, 200, 3), alpha=1.0, depth_multiplier=1) feature_model.load_weights('mobilenet_1_0_224_tf.h5') # give the path for downloaded weights </code></pre> <p>And you're good to go.</p>
2019-04-08 13:09:54.800000+00:00
2019-04-08 17:13:29.850000+00:00
2019-04-08 17:13:29.850000+00:00
null
55,571,664
<p>I want to use the MobileNet model pre-trained on ImageNet for feature extraction. I am loading the model as follows:</p> <pre><code>from keras.applications.mobilenet import MobileNet feature_model = MobileNet(include_top=False, weights='imagenet', input_shape=(200, 200, 3)) </code></pre> <p>The Keras manual <a href="https://keras.io/applications/#mobilenet" rel="nofollow noreferrer">clearly says</a> that this input shape is valid:</p> <blockquote> <p>input_shape: optional shape tuple, only to be specified if include_top is False (otherwise the input shape has to be (224, 224, 3) (with 'channels_last' data format) or (3, 224, 224) (with 'channels_first' data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. (200, 200, 3) would be one valid value.</p> </blockquote> <p>However, I get the following error message:</p> <blockquote> <p>ValueError: If imagenet weights are being loaded, input must have a static square shape (one of (128, 128), (160, 160), (192, 192), or (224, 224)). Input shape provided = (200, 200, 3)</p> </blockquote> <p>Why does it require the input shape to match the one it was trained on if I specify <code>include_top=False</code>?</p> <p>Keras: 2.2.4, TensorFlow: 1.13.1</p> <p>Update: As @Soroush pointed out, this exception was removed <a href="https://github.com/keras-team/keras-applications/pull/94/commits/9d2664c5df9f2f018637995d6f40ab51d1669b93" rel="nofollow noreferrer">recently</a>. However, the issue was not fully resolved as described <a href="https://github.com/keras-team/keras-applications/issues/92#issuecomment-480958268" rel="nofollow noreferrer">here</a>.</p> <p>Update2: The problem was resolved by these two pull requests (<a href="https://github.com/keras-team/keras-applications/pull/94" rel="nofollow noreferrer">1</a>, <a href="https://github.com/keras-team/keras-applications/pull/101" rel="nofollow noreferrer">2</a>).</p>
2019-04-08 10:47:04.010000+00:00
2019-04-15 11:30:41.330000+00:00
2019-04-15 11:30:41.330000+00:00
python|tensorflow|keras|deep-learning
['https://github.com/fchollet/deep-learning-models/releases/tag/v0.6', 'https://arxiv.org/pdf/1704.04861.pdf', 'https://github.com/keras-team/keras-applications/blob/master/keras_applications/mobilenet.py', 'https://github.com/fchollet/deep-learning-models/releases/download/v0.6/mobilenet_1_0_224_tf.h5', 'https://arxiv.org/pdf/1704.04861.pdf']
5
19,863,238
<p>People do use HMMs to label noun phrases in POS-labeled sentences, but the typical model setup does not work in quite the way you're describing.</p> <p>Instead, the setup (see <a href="http://arxiv.org/abs/cmp-lg/9807007" rel="nofollow">Chunk tagger-statistical recognition of noun phrases (PDF)</a> and <a href="http://dl.acm.org/citation.cfm?id=1073163" rel="nofollow">Named entity recognition using an HMM-based chunk tagger (PDF)</a> for examples) is to use an HMM with three states:</p> <ul> <li>O (not in an NP),</li> <li>B (beginning of an NP),</li> <li>I (in an NP, but not the beginning).</li> </ul> <p>Each word in a sentence will be assigned one of the states by the HMM. As an example, the sentence:</p> <blockquote> <p>The/DT boy/NN hit/VT the/DT ball/NN with/PP the/DT red/ADJ bat/NN ./.</p> </blockquote> <p>might be ideally labeled as follows:</p> <blockquote> <p>The/DT <strong>B</strong> boy/NN <strong>I</strong> hit/VT <strong>O</strong> the/DT <strong>B</strong> ball/NN <strong>I</strong> with/PP <strong>O</strong> the/DT <strong>B</strong> red/ADJ <strong>I</strong> bat/NN <strong>I</strong> ./. <strong>O</strong></p> </blockquote> <p>The transitions among these three HMM states can be limited based on prior knowledge of how the sequences will behave; in particular, you can only transition to I from B, but the other transitions are all possible with nonzero probability. You can then use Baum-Welch on a corpus of unlabeled text to train up your HMM (to identify any type of chunk at all -- see <a href="http://www.researchgate.net/publication/220873937_Simple_Unsupervised_Grammar_Induction_from_Raw_Text_with_Cascaded_Finite_State_Models/file/79e4150992f8e85b5b.pdf" rel="nofollow">Simple Unsupervised Grammar Induction from Raw Text with Cascaded Finite State Models (PDF)</a> for an example), or some sort of maximum-likelihood method with a corpus of labeled text (in case you're looking specifically for noun phrases).</p>
2013-11-08 15:54:55.100000+00:00
2013-11-08 16:04:18.507000+00:00
2013-11-08 16:04:18.507000+00:00
null
19,824,223
<p>I need a model for the following tasks:</p> <p>a sequence of words, with its POS tags. I want to judge whether this sequence of words is a Noun Phrase or not.</p> <p>One model I can think of is HMM.</p> <p>For those sequences which are noun phrase, we train a HMM (HMM+). For those are not noun phrase, we try an HMM(HMM-). And when we do prediction for a sequence, we can calculate P(sequence| HMM+) and P(sequence|HMM-). If the former is larger, we think this phrase is a noun phrase, otherwise it's not.</p> <p>What do you think of it? and do you have any other models suited for this question? </p>
2013-11-06 22:30:46.697000+00:00
2013-11-08 16:04:18.507000+00:00
null
machine-learning|nlp|hidden-markov-models
['http://arxiv.org/abs/cmp-lg/9807007', 'http://dl.acm.org/citation.cfm?id=1073163', 'http://www.researchgate.net/publication/220873937_Simple_Unsupervised_Grammar_Induction_from_Raw_Text_with_Cascaded_Finite_State_Models/file/79e4150992f8e85b5b.pdf']
3
13,292,574
<p>This question immediately reminded me of the <a href="http://arxiv.org/abs/1010.5023" rel="nofollow">Yacc is dead</a> / <a href="http://research.swtch.com/yaccalive" rel="nofollow">No, it's not</a> debate from the end of 2010. The authors of the <em>Yacc is dead</em> paper provide a <a href="http://www.ucombinator.org/projects/parsing/" rel="nofollow">library</a> in Scala (unmaintained), Haskell and Racket. In the <em>Yacc is alive</em> response, Russ Cox points out that the code runs in exponential time for ambiguous grammars.</p> <p>It's well-known that it is possible to parse ambiguous grammars in <code>O(n^3)</code>, although obviously it can take exponential time to enumerate all the parse trees in the case that there are exponentially many of them -- and there will be in the case of <code>x1 + x2 + x3 ... + xn</code>. <code>bison</code> implements the GLR algorithm which does so; unfortunately, while <code>bison</code> is certainly mature (if not actually moribund), it is written neither in Haskell nor in Scala.</p> <p>Daniel Spiewak implemented a GLL parser in Scala IIRC, but last time I looked at it, it suffered from some performance issues. So I'm not sure that it could be described as mature, either.</p>
2012-11-08 15:53:38.130000+00:00
2012-11-10 03:31:23.967000+00:00
2012-11-10 03:31:23.967000+00:00
null
13,279,087
<p>I'm looking for a mature parser library, either for Scala or Haskell. The most important point is, that the library can handle ambiguity. If an expression is ambiguous, I want every possible abstract syntax tree, that matches the expression. Simple example: The expression <strong>a ⊗ b ⊗ c</strong> can be seen as <strong>(a ⊗ b) ⊗ c</strong> or <strong>a ⊗ (b ⊗ c)</strong>, and I need both variants. Thanks!</p>
2012-11-07 22:05:55.540000+00:00
2013-01-29 11:04:23.470000+00:00
null
parsing|scala|haskell
['http://arxiv.org/abs/1010.5023', 'http://research.swtch.com/yaccalive', 'http://www.ucombinator.org/projects/parsing/']
3
59,454,463
<p>distributed training is model and framework specific. Not all models are easy to distribute, and from ML framework to ML framework things are not equally easy. <strong>It is rarely automatic, even less so with TensorFlow and Keras.</strong></p> <p>Neural nets are conceptually easy to distribute under the data-parallel paradigm, whereby the gradient computation of a given mini-batch is split among workers, which could be multiple devices in the same host (multi-device) or multiple hosts with each multiple devices (multi-device multi-host). The D2L.ai course provides an in-depth view of how neural nets are distributed <a href="http://d2l.ai/chapter_computational-performance/multiple-gpus.html" rel="nofollow noreferrer">here</a> and <a href="http://d2l.ai/chapter_computational-performance/parameterserver.html" rel="nofollow noreferrer">here</a>.</p> <p>Keras used to be trivial to distribute in multi-device, single host fashion with the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/utils/multi_gpu_model" rel="nofollow noreferrer"><code>multi_gpu_model</code>, which will sadly get deprecated in 4 months</a>. In your case, you seem to refer to multi-host model (more than one machine), and that requires writing ad-hoc synchronization code such as the one seen in <a href="https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras" rel="nofollow noreferrer">this official tutorial</a>. </p> <p>Now let's look at how does this relate to SageMaker.</p> <p>SageMaker comes with 3 options for algorithm development. Using distributed training may require a varying amount of custom work depending on the option you choose:</p> <ol> <li><p>The <strong>built-in algorithms</strong> is a library of 18 pre-written algorithms. Many of them are written to be distributed in single-host multi-GPU or multi-GPU multi-host. With that first option, you don't have anything to do apart from setting <code>train_instance_count</code> > 1 to distribute over multiple instances</p></li> <li><p>The <strong>Framework containers</strong> (the option you are using) are containers developed for popular frameworks (TensorFlow, PyTorch, Sklearn, MXNet) and provide pre-written docker environment in which you can write arbitrary code. In this options, some container will support one-click creation of ephemeral training clusters to do distributed training, <strong>however using <code>train_instance_count</code> greater than one is not enough to distribute the training of your model. It will just run your script on multiple machines. In order to distribute your training, you must write appropriate distribution and synchronization code in your <code>mnist_keras_tf.py</code> script.</strong> For some frameworks such code modification will be very simple, for example for TensorFlow and Keras, SageMaker comes with Horovod pre-installed. Horovod is a peer-to-peer ring-style communication mechanism that requires very little code modification and is highly scalable (<a href="https://eng.uber.com/horovod/" rel="nofollow noreferrer">initial annoucement from Uber</a>, <a href="https://sagemaker.readthedocs.io/en/stable/using_tf.html#training-with-horovod" rel="nofollow noreferrer">SageMaker doc</a>, <a href="https://github.com/awslabs/amazon-sagemaker-examples/blob/master/sagemaker-python-sdk/tensorflow_script_mode_horovod/tensorflow_script_mode_horovod.ipynb" rel="nofollow noreferrer">SageMaker example</a>, <a href="https://aws.amazon.com/fr/blogs/machine-learning/launching-tensorflow-distributed-training-easily-with-horovod-or-parameter-servers-in-amazon-sagemaker/" rel="nofollow noreferrer">SageMaker blog post</a>). My recommendation would be to try using Horovod to distribute your code. Similarly, in Apache MXNet you can easily create Parameter Stores to host model parameters in a distributed fashion and sync with them from multiple nodes. MXNet scalability and ease of distribution is one of the reason Amazon loves it.</p></li> <li><p>The <strong>Bring-Your-Own Container</strong> requires you to write both docker container and algorithm code. In this situation, you can of course distribute your training over multiple machines but you also have to write machine-to-machine communication code</p></li> </ol> <p>For your specific situation my recommendation would be to scale horizontally first in a single node with multiple GPUs over bigger and bigger machine types, because latency and complexity increase drastically as you switch from single-host to multi-host context. If truly necessary, use multi-node context and things maybe easier if that's done with Horovod. In any case, things are still much easier to do with SageMaker since it manages creation of ephemeral, billed-per-second clusters with built-in, logging and metadata and artifacts persistence and also handles fast training data loading from s3, sharded over training nodes. </p> <p><strong>Note on the relevancy of distributed training</strong>: Keep in mind that when you distribute over N devices a model that was running fine on one device, you usually grow the batch size by N so that the per-device batch size stays constant and each device keeps being busy. This will disturb your model convergence, because bigger batches means a less noisy SGD. A common heuristic is to grow the learning rate by N (more info in <a href="https://arxiv.org/abs/1706.02677" rel="nofollow noreferrer">this great paper from Priya Goyal et al</a>), but this on the other hand induces instability at the first couple epochs, so it is sometimes associated with a learning rate warmup. Scaling SGD to work well with very large batches is still an active research problem, with new ideas coming up frequently. Reaching good model performance with very large batches sometimes require ad-hoc research and a fair amount of parameter tuning, occasionally to the extent where the extra money spent on finding how to distribute well overcome the benefits of the faster training you eventually manage to run. A situation where distributed training makes sense is when an individual record represent too much compute to form a big enough physical batch on a device, a situation seen on big input sizes (eg vision over HD pictures) or big parameter counts (eg BERT). That being said, for those models requiring very big logical batch you don't necessarily have to distribute things physically: you can run sequentially N batches through your single GPU and wait N per-device batches before doing the gradient averaging and parameter update to simulate having an N times bigger GPU. (a clever hack sometimes called <em>gradient accumulation</em>)</p>
2019-12-23 11:21:55.740000+00:00
2019-12-23 11:44:58.307000+00:00
2019-12-23 11:44:58.307000+00:00
null
59,446,807
<p>I am roughly following this script <a href="https://gitlab.com/juliensimon/dlnotebooks/blob/master/keras/05-keras-blog-post/Fashion%20MNIST-SageMaker.ipynb" rel="nofollow noreferrer">fashion-MNIST-sagemaker</a>.</p> <p>I see that in the notebook </p> <pre><code>from sagemaker.tensorflow import TensorFlow tf_estimator = TensorFlow(entry_point='mnist_keras_tf.py', role=role, train_instance_count=1, train_instance_type='local', framework_version='1.12', py_version='py3', script_mode=True, hyperparameters={'epochs': 1} ) </code></pre> <p>I am wondering to what extent I can and should use the <code>train_instance_count</code> parameter. Will it distribute training along some dimension automatically, if yes - what is the dimension?</p> <p>Further, does it generally make sense to distribute training horizontally in a keras (with tensorflow) based setting?</p>
2019-12-22 18:04:17.400000+00:00
2019-12-23 11:44:58.307000+00:00
null
python|tensorflow|keras|amazon-sagemaker|horizontal-scaling
['http://d2l.ai/chapter_computational-performance/multiple-gpus.html', 'http://d2l.ai/chapter_computational-performance/parameterserver.html', 'https://www.tensorflow.org/api_docs/python/tf/keras/utils/multi_gpu_model', 'https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras', 'https://eng.uber.com/horovod/', 'https://sagemaker.readthedocs.io/en/stable/using_tf.html#training-with-horovod', 'https://github.com/awslabs/amazon-sagemaker-examples/blob/master/sagemaker-python-sdk/tensorflow_script_mode_horovod/tensorflow_script_mode_horovod.ipynb', 'https://aws.amazon.com/fr/blogs/machine-learning/launching-tensorflow-distributed-training-easily-with-horovod-or-parameter-servers-in-amazon-sagemaker/', 'https://arxiv.org/abs/1706.02677']
9
67,919,101
<p>The short answer is &quot;<strong>yes</strong>&quot;: <em>it is a good idea to have as many neurons in output as you have in input, i.e. to output an image with the same resolution of the input images</em>.</p> <p>The network architecture will have an input layer with a neuron for each pixel, then typically the hidden layers will shrink to less neurons, probably with <em>convolutional</em> layers, and then some more layers will re-expand the number of neurons, up to the output layer, which in principle may have the same number of neurons as the input layer.</p> <p>The most common architecture in this type of problem is the <strong>U-net architecture</strong>, described in the article &quot;<em>U-Net: Convolutional Networks for Biomedical Image Segmentation</em>&quot;, by Ronneberger, Fischer, and Brox, published on the open arxiv: <a href="https://arxiv.org/abs/1505.04597" rel="nofollow noreferrer">https://arxiv.org/abs/1505.04597</a>.</p> <p>[<img src="https://i.stack.imgur.com/ZBIFe.png" alt="U-net architecture, as described in the article &quot;U-Net: Convolutional Networks for Biomedical Image Segmentation&quot;, by Ronneberger, Fischer, and Brox, published on the open arxiv: ][1]" /></p>
2021-06-10 10:11:05.803000+00:00
2021-06-10 10:11:05.803000+00:00
null
null
67,874,428
<p>I want to design and train a <strong>neural network</strong> for the <strong>automatic recognition of the edges</strong>, in some microscopic images. I am using Keras for a start, I may consider PyTorch later.</p> <p>The <strong>structure</strong> of the images is rather simple, with some <strong>dark areas</strong>, and some <strong>clear areas</strong>, relatively easy to distinguish, and the task is to select the pixels of the contour between <em>dark</em> and <em>clear</em> areas. The transition between dark and clear is gradual, so my result is not a single line of edge pixels, but rather a 10 or 15 pixels wide &quot;ribbon&quot; at the edge.</p> <p>I have manually annotated 200-something images, so for each image I have another image, of the same size, where the pixels of the contours are black, and all the other pixels are white.</p> <p>I have seen many tutorials on how to <em>design</em>, <em>compile</em> and <em>fit</em> a model (a neural network), and then how to test it, using the manually annotated data.</p> <p>However, most of the tutorials work on problems of classification, where the number of neurons in the output layer is the number of categories.</p> <p>My problem is <strong>not a problem of classification</strong>, and ideally my output should be an image of the same size of the input.</p> <p>So, here is my question:</p> <p><em>What is the best way to design the output layer? Is a layer with a number of neurons equal to the number of pixels the best idea? Or this is a waste, and there is a more efficient way?</em></p> <hr /> <p><strong>Addendum</strong></p> <ol> <li>The images are &quot;easy&quot;, but it is still difficult to find the contour pixels, so I believe that it is worth using the machine learning approach.</li> <li>The transition between dark and clear is a little gradual, so my result is not a single line of pixels on the edge, but rather a band, a 10 or 15 wide ribbon of edge pixels. Since I am after a ribbon of pixels, my categories should be &quot;edge&quot; and &quot;not-edge&quot;. If I use the categories &quot;dark pixels&quot; and &quot;clear pixels&quot;, and then numerically find the pixels between the two areas I do not get the &quot;ribbon&quot; result, which I need.</li> </ol>
2021-06-07 15:24:59.417000+00:00
2021-06-10 10:11:05.803000+00:00
2021-06-08 11:50:36.867000+00:00
python|tensorflow|image-processing|contour
['https://arxiv.org/abs/1505.04597']
1
40,061,717
<p>This is the framing of the "Information Buttleneck" problem, which can be solved in some cases in EM-like iterative algorithm or heuristically through greedy, agglomerative clustering process. </p> <p>Useful references:</p> <ul> <li><a href="https://en.wikipedia.org/wiki/Information_bottleneck_method" rel="nofollow">Wikipedia</a></li> <li><a href="https://arxiv.org/pdf/physics/0004057.pdf" rel="nofollow">Paper</a></li> <li>Matlab code: <a href="http://ai.stanford.edu/~gal/code.html" rel="nofollow">(1) by G. Chechik</a> or <a href="http://www.vlfeat.org/matlab/matlab.html" rel="nofollow">(2) in the VLfeat library</a></li> </ul> <p>Indeed it is deeply related to CCA; under certain assumptions on the problem (i.e. Gaussianity) this relation can be made exact (see Wikipedia link and <a href="http://www.jmlr.org/papers/volume6/chechik05a/chechik05a.pdf" rel="nofollow">this paper</a>).</p>
2016-10-15 16:50:28.097000+00:00
2016-10-15 16:50:28.097000+00:00
null
null
39,949,446
<p>I got a dataset D={X,y} which have 800 input features and single continuous output. I am looking for any feature extraction methods that satisfy two conditions</p> <p>(1) Matlab codes are available to download</p> <p>(2). The method should somehow map input x to transformed input z where z is d vector, (d&lt;&lt;800), such that the mutual information between z_i, and y as high as possible. </p> <p>I think the methods should relate to CCA, however when perform CCA(X,y) I will obtain vector z that have only one dimension. I hope the methods should have the options to select top d good features like PCA does.</p> <p>Thanks,</p>
2016-10-09 23:10:19.883000+00:00
2016-10-15 16:50:28.097000+00:00
null
feature-extraction|information-theory
['https://en.wikipedia.org/wiki/Information_bottleneck_method', 'https://arxiv.org/pdf/physics/0004057.pdf', 'http://ai.stanford.edu/~gal/code.html', 'http://www.vlfeat.org/matlab/matlab.html', 'http://www.jmlr.org/papers/volume6/chechik05a/chechik05a.pdf']
5
71,284,080
<p>Answering this to get this question off the unanswered queue.</p> <p>As mentioned in the related question linked, a simple automaton-based algorithm for answering first-order queries in Presburger arithmetic (and some extensions) has worst-case running time about 2↑↑n, where n is the number of quantifier alternations in the query. It has both been implemented and provides useful results. Find more about it <a href="https://arxiv.org/abs/1603.06017" rel="nofollow noreferrer">here</a></p>
2022-02-27 10:44:29.440000+00:00
2022-02-27 10:44:29.440000+00:00
null
null
51,310,304
<p>I’m wondering whether there are any algorithms that use so much time that they must be represented using <a href="https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation" rel="nofollow noreferrer">Knuth up-arrow notation</a>.</p> <p>Required: Use more than one up-arrow for time complexity.</p> <p>Bonus points: </p> <ul> <li><p>Have the algorithm be useful.</p></li> <li><p>Have the algorithm be useful and optimized</p></li> </ul> <p>Sister question on CS: (recommendation from @Amy) <a href="https://cs.stackexchange.com/questions/94184/are-there-any-algorithms-that-run-in-2-">https://cs.stackexchange.com/questions/94184/are-there-any-algorithms-that-run-in-2-</a>↑-↑-n</p>
2018-07-12 16:14:17.777000+00:00
2022-02-27 10:44:29.440000+00:00
2018-07-12 17:02:23.593000+00:00
algorithm|time-complexity
['https://arxiv.org/abs/1603.06017']
1
59,670,724
<p>You are wrong here in assuming that xgboost impute missing values to 0. Actually in case of missing values, it note the NA towards for higher gain split direction while growing tree. </p> <p>For example if splits without considering missing values is decided to be a variable <code>var1</code>'s (range [0,1]) value 0.5 then it calculates the gain considering var1 missing values to be &lt; 0.5 and > 0.5. To whatever split direction it gets more gain it attributes missing values to have that split direction. So missing values now have a range [0,0.5] or [0.5,1] but not actual value assigned to it (i.e. imputed).</p> <p>For more details on this topic please refer to paper <a href="https://arxiv.org/pdf/1603.02754v3.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1603.02754v3.pdf</a></p>
2020-01-09 19:16:08.507000+00:00
2020-01-09 19:16:08.507000+00:00
null
null
58,397,077
<p>Unlike python, where missing value is handled internally by the XGBoost algorithm, While building XGBoost model in SPARK, the missing values are implicitly converted to 0.0(float?!). Is this okay ? There are real values that may be 0.0.How can we be sure this doesn't interfere with the model prediction abilities ? </p>
2019-10-15 14:34:29.680000+00:00
2020-01-09 19:16:08.507000+00:00
null
scala|apache-spark|machine-learning|xgboost
['https://arxiv.org/pdf/1603.02754v3.pdf']
1
60,764,713
<p>This has been asked and answered before <a href="https://stackoverflow.com/questions/46924452/what-to-do-when-seq2seq-network-repeats-words-over-and-over-in-output">here on SO</a>.</p> <p>To summarize, the issue is called <em>text degeneration</em> and <a href="https://stackoverflow.com/a/59407187/1939934">the (awesome) answer</a> to the previously asked question links to an <a href="https://arxiv.org/abs/1904.09751" rel="nofollow noreferrer">excellent paper addressing this exact problem</a>. To quote the authors:</p> <blockquote> <p>Why is text produced by pure sampling so degenerate? In this work we show that the "<strong>unreliable tail</strong>" is to blame. This unreliable tail is composed of tens of thousands of candidate tokens with relatively low probability that are over-represented in the aggregate.</p> </blockquote> <p>They find that simple sampling can lead to loops or repetitions as generative models will keep sampling tokens that form sequences that are <strong>too</strong> probable, i.e., repetition is less "surprising" than novel tokens. Compare the baseline of greedy sampling to methods that explicitly truncate the unreliable tail: <a href="https://i.stack.imgur.com/gUEBH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gUEBH.png" alt="Figure"></a></p> <blockquote> <p>Figure 9, <a href="https://arxiv.org/abs/1904.09751" rel="nofollow noreferrer">Holtzman et al. (2020)</a></p> </blockquote> <p>So first, <a href="https://stackoverflow.com/a/60675672/1939934">as Ronakrit mentioned</a>, you should be outputting a vector of logits (probabilities) over a fixed dictionary of tokens.</p> <p>Then, pick a decoding strategy a little more sophisticated than greedy sampling. TensorFlow ships with <a href="https://www.tensorflow.org/api_docs/python/tf/nn/ctc_beam_search_decoder" rel="nofollow noreferrer">beam search</a> and <a href="https://www.tensorflow.org/api_docs/python/tf/math/top_k?hl=en" rel="nofollow noreferrer">top-k</a>, but I'd recommend starting with random decoding, for which you can see a worked out implementation in the <a href="https://www.tensorflow.org/tutorials/text/text_generation#try_the_model" rel="nofollow noreferrer">TensorFlow Text generation tutorial</a>:</p> <pre><code># Generate probabilities from the model. for input_example_batch, target_example_batch in dataset.take(1): example_batch_predictions = model(input_example_batch) print(example_batch_predictions.shape, "# (batch_size, sequence_length, vocab_size)") # Sample from model outputs. sampled_indices = tf.random.categorical(example_batch_predictions[0], num_samples=1) sampled_indices = tf.squeeze(sampled_indices,axis=-1).numpy() # Look up tokens from the dictionary. print("Input: \n", repr("".join(idx2char[input_example_batch[0]]))) print() print("Next Char Predictions: \n", repr("".join(idx2char[sampled_indices ]))) </code></pre>
2020-03-19 20:39:31.357000+00:00
2020-03-19 20:55:47.333000+00:00
2020-03-19 20:55:47.333000+00:00
null
60,605,838
<p>I'm trying to create a simple text (name) generator using RNN. I create the model fine but when I try to predict values I always get the same letter.</p> <p>My code is as follows:</p> <pre><code>from tensorflow.keras.activations import softmax from tensorflow.keras.losses import categorical_crossentropy from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense # parameters LSTM_NODES = 100 MAX_NAME_LEN = 30 STOP_MARKER = '.' # hyper-parameters EPOCHS = 10 # read _names.train into an array names = open('names.train', encoding='utf-8').read().strip().split('\n') # precompute the number of samples SAMPLES = 0 for name in names: for _ in name: SAMPLES = SAMPLES + 1 # get a sorted list of all unique characters used corpus = sorted(list({l for name in names for l in name})) # the first letter in the corpus must be the stop indicator corpus.insert(0, STOP_MARKER) # write out the corpus so that the predict script can use it open('corpus.txt', 'w').write('\n'.join(corpus)) # calculate the input shape for the network input_shape = (MAX_NAME_LEN, len(corpus)) # Creating a mapping from unique characters to indices char2idx = {u:i for i, u in enumerate(corpus)} idx2char = np.array(corpus) def get_text(sample): t = '' for x in sample: n = idx2char[np.argmax(x)] t = t + n return t # I need a 3-D array, samples x character position x character one-hot encoded X = np.zeros((SAMPLES, MAX_NAME_LEN, len(corpus)), int) Y = np.zeros((SAMPLES, len(corpus)), int) # for each sample name for name in names: # number of samples for this name is equal to the number of letters (we add one letter per loop) for i in range(len(name)): j = 0 # create one sample while j &lt;= i: one_hot_letter = np.zeros(len(corpus), int) one_hot_letter[char2idx[name[j]]] = 1 X[i, j] = one_hot_letter j = j + 1 # get the next character in the sequence one_hot_next = np.zeros(len(corpus), int) if j &lt; len(name): one_hot_next[char2idx[name[j]]] = 1 # add this character to the Y sample Y[i] = one_hot_next # print this sample print('X={} Y={}'.format(get_text(X[i]), idx2char[np.argmax(Y[i])])) # build the model model = Sequential() model.add(LSTM(LSTM_NODES, input_shape=input_shape)) model.add(Dense(input_shape[1], activation=softmax)) model.compile(loss=categorical_crossentropy, optimizer='adam') model.summary() # train the model model.fit(X, Y, epochs=EPOCHS) # save the model model.save('model.h5') # try a sample prediction # first letter is the seed SEED = 'M' name = SEED x = np.zeros((1, input_shape[0], input_shape[1]), int) one_hot_letter = np.zeros(len(corpus), int) one_hot_letter[char2idx[SEED]] = 1 x[0, 0] = one_hot_letter for i in range(1, MAX_NAME_LEN): predictions = model.predict(x) # get the next letter and add it to the prediction next_letter = np.zeros(input_shape[1], int) next_letter[np.argmax(predictions[0])] = 1 x[0, i] = next_letter name = name + idx2char[np.argmax(next_letter)] print(name) </code></pre> <p>The output at the end is:</p> <pre><code>Mww Mwww Mwwww Mwwwww Mwwwwww Mwwwwwww Mwwwwwwww Mwwwwwwwww Mwwwwwwwwww Mwwwwwwwwwww Mwwwwwwwwwwww Mwwwwwwwwwwwww Mwwwwwwwwwwwwww Mwwwwwwwwwwwwwww Mwwwwwwwwwwwwwwww Mwwwwwwwwwwwwwwwww Mwwwwwwwwwwwwwwwwww Mwwwwwwwwwwwwwwwwwww Mwwwwwwwwwwwwwwwwwwww Mwwwwwwwwwwwwwwwwwwwww Mwwwwwwwwwwwwwwwwwwwwww Mwwwwwwwwwwwwwwwwwwwwwww Mwwwwwwwwwwwwwwwwwwwwwwww Mwwwwwwwwwwwwwwwwwwwwwwwww Mwwwwwwwwwwwwwwwwwwwwwwwwww Mwwwwwwwwwwwwwwwwwwwwwwwwwww Mwwwwwwwwwwwwwwwwwwwwwwwwwwww Mwwwwwwwwwwwwwwwwwwwwwwwwwwwww </code></pre> <p>Any ideas what could be wrong? My samples are fine I think. I used them in another example written by someone else and they produced different results. I have 280 samples. Here is what <code>names.train</code> looks like:</p> <pre><code>Adaldrida Celendine Gloriana Pimpernel Tanta Alfrida Cora Goldilocks Melba </code></pre> <p>The full output from the training is:</p> <pre><code>[snip] X=Valde......................... Y=m X=Valdem........................ Y=a X=Valdema....................... Y=r X=Valdemar...................... Y=. 2020-03-09 13:38:26.827190: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2020-03-09 13:38:26.843439: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x7fa8f211d590 initialized for platform Host (this does not guarantee that XLA will be used). Devices: 2020-03-09 13:38:26.843450: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= lstm (LSTM) (None, 100) 58800 _________________________________________________________________ dense (Dense) (None, 46) 4646 ================================================================= Total params: 63,446 Trainable params: 63,446 Non-trainable params: 0 _________________________________________________________________ Train on 1795 samples Epoch 1/10 1795/1795 [==============================] - 2s 1ms/sample - loss: 0.0168 Epoch 2/10 1795/1795 [==============================] - 1s 462us/sample - loss: 0.0167 Epoch 3/10 1795/1795 [==============================] - 1s 445us/sample - loss: 0.0164 Epoch 4/10 1795/1795 [==============================] - 1s 450us/sample - loss: 0.0163 Epoch 5/10 1795/1795 [==============================] - 1s 449us/sample - loss: 0.0162 Epoch 6/10 1795/1795 [==============================] - 1s 453us/sample - loss: 0.0160 Epoch 7/10 1795/1795 [==============================] - 1s 593us/sample - loss: 0.0159 Epoch 8/10 1795/1795 [==============================] - 1s 599us/sample - loss: 0.0160 Epoch 9/10 1795/1795 [==============================] - 1s 442us/sample - loss: 0.0160 Epoch 10/10 1795/1795 [==============================] - 1s 440us/sample - loss: 0.0160 Mw Mww Mwww Mwwww Mwwwww Mwwwwww Mwwwwwww Mwwwwwwww Mwwwwwwwww Mwwwwwwwwww Mwwwwwwwwwww [snip]``` </code></pre>
2020-03-09 17:44:40.590000+00:00
2020-03-19 20:55:47.333000+00:00
2020-03-09 18:02:57.357000+00:00
python|tensorflow|machine-learning|keras|recurrent-neural-network
['https://stackoverflow.com/questions/46924452/what-to-do-when-seq2seq-network-repeats-words-over-and-over-in-output', 'https://stackoverflow.com/a/59407187/1939934', 'https://arxiv.org/abs/1904.09751', 'https://i.stack.imgur.com/gUEBH.png', 'https://arxiv.org/abs/1904.09751', 'https://stackoverflow.com/a/60675672/1939934', 'https://www.tensorflow.org/api_docs/python/tf/nn/ctc_beam_search_decoder', 'https://www.tensorflow.org/api_docs/python/tf/math/top_k?hl=en', 'https://www.tensorflow.org/tutorials/text/text_generation#try_the_model']
9
3,145,842
<p>This paper gives a survey of different text categorization techniques and their accuracies. In short, you can categorize text with decision trees, but there are other algorithms that are much better.</p> <p>Sebastiani, F. (2002). Machine learning in automated text categorization. ACM Computing Surveys, cs.IR/0110053v1. Available from: <a href="http://arxiv.org/abs/cs.IR/0110053v1" rel="nofollow noreferrer">http://arxiv.org/abs/cs.IR/0110053v1</a>.</p>
2010-06-30 01:10:26.627000+00:00
2010-06-30 01:10:26.627000+00:00
null
null
3,114,734
<p>Hi I wanted to know that is it possible to use decision trees for document classification and if yes then how should be the data representation be? I know the use of R package <a href="http://cran.r-project.org/web/packages/party/index.html" rel="nofollow noreferrer">party</a> for Decision Trees. </p>
2010-06-24 23:57:18.893000+00:00
2012-12-27 17:20:52.110000+00:00
2011-08-04 21:11:54.600000+00:00
r|nlp|classification|text-mining|document-classification
['http://arxiv.org/abs/cs.IR/0110053v1']
1
34,481,693
<p>I guess what you want is a ML system which plays chess?</p> <p>One way to get it, is to see it as a pattern recognition problem. If you modeled it with a neural network, you could approach it like this:</p> <ul> <li>the input is a binary vector of size 768=64*2*6 (64=8*8 positions on the board, 2 Players, 6 different chess figures)</li> <li>64 output neurons (one for each field).</li> <li>The network would give you a clue which piece to move. It tries to <strong>predict which piece a human player would choose</strong>. If the network chooses something invalid, you can just go to the next most likely piece (assuming you make use of softmax at the end).</li> </ul> <p>You could train a second network which takes the same input. You might think about building a CNN with 12 feature maps instead of a MLP. This network should <strong>predict which player will win</strong>. Then you know which figure would be moved by a human with the first network and then you can find the "best" move with the second network.</p> <h2>More resources</h2> <p>You might be interested in <a href="http://arxiv.org/abs/1511.06410" rel="nofollow">Better Computer Go Player with Neural Network and Long-term Prediction</a> by Facebook Research.</p>
2015-12-27 15:06:11.690000+00:00
2015-12-27 15:36:30.503000+00:00
2015-12-27 15:36:30.503000+00:00
null
34,481,196
<p>As a part of my project, I'm now working on training a chess system with games played by humans. I have significant knowledge on machine learning but am clueless on how to proceed with this. Is this project too complex? Kindly advise on how to proceed. </p>
2015-12-27 14:07:00.953000+00:00
2015-12-27 15:36:30.503000+00:00
null
machine-learning|neural-network|artificial-intelligence|deep-learning
['http://arxiv.org/abs/1511.06410']
1
53,475,584
<p>In the current tutorial, the black-box model is a neural network implemented with TensorFlow and its predictions (the labels) are used to train a substitute model (a copy of the black-box model). The substitute model is then used to craft adversarial examples that transfer to the black-box model. </p> <p>In your case, you would have to replace bbox_val in </p> <pre><code>bbox_val = batch_eval(sess, [x], [bbox_preds], [x_sub_prev], args=eval_params)[0] </code></pre> <p>by the predictions of your random forest on the numpy array of substitute training data <code>x_sub_prev</code>. </p> <p>You can find more information about the attack implemented in this tutorial in the following paper: <a href="https://arxiv.org/abs/1602.02697" rel="nofollow noreferrer">https://arxiv.org/abs/1602.02697</a></p>
2018-11-26 06:10:47.127000+00:00
2018-11-26 06:10:47.127000+00:00
null
null
53,473,184
<p>I am new to this stuff and trying to attack Random Forest with Black Box FGSM (from clever hans)</p> <p>But I'm not sure how to implement it. They've a <a href="https://github.com/tensorflow/cleverhans/blob/master/cleverhans_tutorials/mnist_blackbox.py" rel="nofollow noreferrer">blackbox example for Mnist data</a> but I dont understand where should I put my random forest and where should I attack. Any help would be appreciated.</p>
2018-11-25 23:51:53.117000+00:00
2018-11-26 06:10:47.127000+00:00
null
python|tensorflow|random-forest|cleverhans
['https://arxiv.org/abs/1602.02697']
1
69,050,774
<p>Since these representations are from two different modalities (i.e., text and image) and they contain valuable features that are of great importance to the final goal, I would suggest to <em>fuse</em> them in a &quot;learnable&quot; manner instead of a mere concatenation or addition. Furthermore, such a learnable weighting (between features) would be optimal since in some cases one representation would be far more useful than the other whereas at other instances the vice versa applies.</p> <p>Please note that a mere concatenation can also happen in this fusion module that you would implement. For the actual implementation, there are several types of fusion techniques. E.g. Simple Fusion, Cold Fusion etc. (cf. <a href="https://arxiv.org/abs/2010.15251" rel="nofollow noreferrer">Fusion Models for Improved Visual Captioning, 2021</a>)</p> <p>For instance, one straightforward idea would be to use a simple linear layer to project one of the features to the same dimensionality as the other and then do a simple concatenation, with some optional non-linearity if needed.</p>
2021-09-03 21:36:42.630000+00:00
2021-09-03 21:36:42.630000+00:00
null
null
69,036,172
<p>I have two tensors:</p> <pre><code>a = torch.randn((1, 30, 1220)) # represents text embedding vector (30 spans, each with embedding size of 1220) b = torch.randn((1, 128, 256)) # represents image features obtained from a pretrained CNN (object detection) </code></pre> <ol> <li><p>How do I concatenate everything in <code>b</code> to each one of the 30 spans of <code>a</code>?</p> </li> <li><p>How to concatenate the whole <code>b</code> to the whole <code>a</code>?</p> </li> </ol> <p>This is what I'm trying to do:</p> <p><a href="https://i.stack.imgur.com/GZUZI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GZUZI.png" alt="Image features concatenated with LSTM output" /></a></p> <p>The authors have only provided this text:</p> <p><a href="https://i.stack.imgur.com/CLU73.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CLU73.png" alt="Model description" /></a></p> <p>I'm extracting features (outlined in red) from a 3d point cloud (similar to CNN but for 3d) as shown below:</p> <p><a href="https://i.stack.imgur.com/7GZaq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7GZaq.png" alt="3D Feature Extraction" /></a></p>
2021-09-02 19:41:10.157000+00:00
2021-09-04 17:02:20.527000+00:00
2021-09-04 17:02:20.527000+00:00
python|machine-learning|deep-learning|pytorch|concatenation
['https://arxiv.org/abs/2010.15251']
1
41,088,665
<p>One approach is to take pre-trained Google News word2vec and use this "retrofitting" tool:</p> <p>Faruqui, Manaal, Jesse Dodge, Sujay K. Jauhar, Chris Dyer, Eduard Hovy, and Noah A. Smith. "Retrofitting word vectors to semantic lexicons." arXiv preprint arXiv:1411.4166 (2014). <a href="https://arxiv.org/abs/1411.4166" rel="nofollow noreferrer">https://arxiv.org/abs/1411.4166</a></p> <blockquote> <p>This paper proposes a method for refining vector space representations using relational information from semantic lexicons by encouraging linked words to have similar vector representations, and it makes no assumptions about how the input vectors were constructed.</p> </blockquote> <p>The code is available at <a href="https://github.com/mfaruqui/retrofitting" rel="nofollow noreferrer">https://github.com/mfaruqui/retrofitting</a> and is straightforward to use (I've personally used it for <a href="https://arxiv.org/abs/1607.02802" rel="nofollow noreferrer">https://arxiv.org/abs/1607.02802</a>).</p>
2016-12-11 16:57:16.550000+00:00
2016-12-11 16:57:16.550000+00:00
null
null
41,085,755
<p>I am trying to adapt the pre-trained Google News word2vec model to my specific domain. For the domain I am looking at, certain words are known to be similar to each other so in an ideal world, the Word2Vec representation of those words should represent that. I understand that I can train the pre-trained model on a corpus of domain-specific data to update the vectors. </p> <p>However, if I know for certain that certain words are highly similar and should be together, is there a way for me to incorporate that constraint into the word2vec model? Mathematically, I would like to add a term to the loss function of word2vec that provides a penalty if two that I know to be similar are not positioned close to each other in the vector space. Does anyone have advice on how to implement this? Will this require me to unpack the word2vec model or is there a way for me to potentially add that additional term to the loss function?</p>
2016-12-11 11:41:51.487000+00:00
2016-12-11 16:57:16.550000+00:00
null
nlp|stanford-nlp|word2vec
['https://arxiv.org/abs/1411.4166', 'https://github.com/mfaruqui/retrofitting', 'https://arxiv.org/abs/1607.02802']
3
24,832,382
<p>This is a common misunderstanding of vowpal wabbit.</p> <p><strong><em>One cannot compare batch learning with online learning.</em></strong></p> <p>vowpal wabbit is not a batch learner. It is an online learner. Online learners learn by looking at examples one at a time and <em>slightly</em> adjusting the weights of the model as they go.</p> <p>There are advantages and disadvantages to online learning. The downside is that convergence to the final model is slow/gradual. The learner doesn't do a "perfect" job at extracting information from each example, because the process is iterative. Convergence on a final result is deliberately restrained/slow. This can make online learners appear weak on tiny data-sets like the above.</p> <p>There are several upsides though:</p> <ul> <li>Online learners don't need to load the full data into memory (they work by examining one example at a time and adjusting the model based on the real-time observed per-example loss) so they can scale easily to billions of examples. <a href="http://arxiv.org/abs/1110.4198">A 2011 paper by 4 Yahoo! researchers</a> describes how vowpal wabbit was used to learn from a tera (10^12) feature data-set in 1 hour on 1k nodes. Users regularly use <code>vw</code> to learn from billions of examples data-sets on their desktops and laptops.</li> <li>Online learning is adaptive and can track changes in conditions over time, so it can learn from non-stationary data, like learning against an adaptive adversary.</li> <li>Learning introspection: one <a href="https://github.com/arielf/vowpal_wabbit/wiki/vw-top-errors:-online-learning-debugging-for-better-models">can observe loss convergence rates while training</a> and identify specific issues, and even gain significant insights from specific data-set examples or features.</li> <li>Online learners can learn in an incremental fashion so users can intermix labeled and unlabeled examples to keep learning while predicting at the same time.</li> <li>The estimated error, even during training, is always "out-of-sample" which is a <a href="http://hunch.net/~jl/projects/prediction_bounds/progressive_validation/coltfinal.pdf">good estimate of the test error</a>. There's no need to split the data into train and test subsets or perform N-way cross-validation. The next (yet unseen) example is always used as a hold-out. This is a tremendous advantage over batch methods from the operational aspect. It greatly simplifies the typical machine-learning process. In addition, as long as you don't run multiple-passes over the data, it serves as a great over-fitting avoidance mechanism.</li> </ul> <p>Online learners are very sensitive to example order. The worst possible order for an online learner is when classes are clustered together (all, or almost all, <code>-1</code>s appear first, followed by all <code>1</code>s) like the example above does. So the first thing to do to get better results from an online learner like vowpal wabbit, is to uniformly shuffle the <code>1</code>s and <code>-1</code>s (or simply order by time, as the examples typically appear in real-life).</p> <hr> <p>OK now what?</p> <p><strong><em>Q: Is there any way to produce a reasonable model in the sense that it gives reasonable predictions on small data when using an online learner?</em></strong></p> <p><strong><em>A: Yes, there is!</em></strong></p> <p>You can emulate what a batch learner does more closely, by taking two simple steps:</p> <ul> <li><strong><em>Uniformly shuffle</em></strong> <code>1</code> and <code>-1</code> examples.</li> <li>Run <strong><em>multiple passes</em></strong> over the data to give the learner a chance to converge</li> </ul> <p>Caveat: if you run multiple passes until error goes to 0, there's a danger of over-fitting. The online learner has perfectly learned your examples, but it may not generalize well to unseen data.</p> <p>The second issue here is that the predictions <code>vw</code> gives are not logistic-function transformed (this is unfortunate). They are akin to standard deviations from the middle point (truncated at [-50, 50]). You need to pipe the predictions via <code>utl/logistic</code> (in the source tree) to get signed probabilities. Note that these signed probabilities are in the range [-1, +1] rather than [0, 1]. You may use <code>logistic -0</code> instead of <code>logistic</code> to map them to a [0, 1] range.</p> <p>So given the above, here's a recipe that should give you more expected results:</p> <pre><code># Train: vw train.vw -c --passes 1000 -f model.vw --loss_function logistic --holdout_off # Predict on train set (just as a sanity check) using the just generated model: vw -t -i model.vw train.vw -p /dev/stdout | logistic | sort -tP -n -k 2 </code></pre> <p>Giving this more expected result on your data-set:</p> <pre><code>-0.95674145247658 P1 -0.930208359811439 P2 -0.888329575506748 P3 -0.823617739247262 P4 -0.726830630992614 P5 -0.405323815830325 P6 0.0618902961794472 P7 0.298575998150221 P8 0.503468453150847 P9 0.663996516371277 P10 0.715480084449868 P11 0.780212725426778 P12 </code></pre> <p>You could make the results more/less polarized (closer to <code>1</code> on the older ages and closer to <code>-1</code> on the younger) by increasing/decreasing the number of passes. You may also be interested in the following options for training:</p> <pre><code>--max_prediction &lt;arg&gt; sets the max prediction to &lt;arg&gt; --min_prediction &lt;arg&gt; sets the min prediction to &lt;arg&gt; -l &lt;arg&gt; set learning rate to &lt;arg&gt; </code></pre> <p>For example, by increasing the learning rate from the default <code>0.5</code> to a large number (e.g. <code>10</code>) you can force <code>vw</code> to converge much faster when training on small data-sets thus requiring less passes to get there.</p> <p><em>Update</em></p> <p>As of mid 2014, <code>vw</code> no longer requires the external <code>logistic</code> utility to map predictions back to [0,1] range. A new <code>--link logistic</code> option maps predictions to the logistic function [0, 1] range. Similarly <code>--link glf1</code> maps predictions to a generalized logistic function [-1, 1] range.</p>
2014-07-18 19:27:14.050000+00:00
2016-01-18 19:01:35.190000+00:00
2016-01-18 19:01:35.190000+00:00
null
24,822,288
<p>I have started using <strong>Vowpal Wabbit</strong> for logistic regression, however I am unable to reproduce the results it gives. Perhaps there is some undocumented "magic" it does, but has anyone been able to replicate / verify / check the calculations for logistic regression?</p> <p>For example, with the simple data below, we aim to model the way <code>age</code> predicts <code>label</code>. It is obvious there is a strong relationship as when age increases the probability of observing 1 increases. </p> <p>As a simple unit test, I used the 12 rows of data below:</p> <pre><code>age label 20 0 25 0 30 0 35 0 40 0 50 0 60 1 65 0 70 1 75 1 77 1 80 1 </code></pre> <p>Now, performing a logistic regression on this dataset, using <strong>R</strong> , <strong>SPSS</strong> or even by hand, produces a model which looks like <code>L = 0.2294*age - 14.08</code>. So if I substitude the age, and use the logit transform prob=1/(1+EXP(-L)) I can obtain the predicted probabilities which range from <code>0.0001</code> for the first row, to <code>0.9864</code> for the last row, as reasonably expected. </p> <p>If I plug in the same data in <strong>Vowpal Wabbit</strong>, </p> <pre><code>-1 'P1 |f age:20 -1 'P2 |f age:25 -1 'P3 |f age:30 -1 'P4 |f age:35 -1 'P5 |f age:40 -1 'P6 |f age:50 1 'P7 |f age:60 -1 'P8 |f age:65 1 'P9 |f age:70 1 'P10 |f age:75 1 'P11 |f age:77 1 'P12 |f age:80 </code></pre> <p>And then perform a logistic regression using </p> <pre><code>vw -d data.txt -f demo_model.vw --loss_function logistic --invert_hash aaa </code></pre> <p>(command line consistent with <a href="https://stackoverflow.com/questions/24634602/how-to-perform-logistic-regression-using-vowpal-wabbit">How to perform logistic regression using vowpal wabbit on very imbalanced dataset</a> ) , I obtain a model <code>L= -0.00094*age - 0.03857</code> , which is <strong>very different.</strong> </p> <p>The predicted values obtained using <code>-r</code> or <code>-p</code> further confirm this. The resulting probabilities end up nearly all the same, for example <code>0.4857</code> for age=20, and <code>0.4716</code> for age=80, which is extremely off. </p> <p>I have noticed this inconsistency with larger datasets too. In what sense is Vowpal Wabbit carrying out the logistic regression differently, and how are the results to be interpreted?</p>
2014-07-18 10:00:42.523000+00:00
2016-01-18 19:01:35.190000+00:00
2017-05-23 12:32:21.507000+00:00
logistic-regression|vowpalwabbit
['http://arxiv.org/abs/1110.4198', 'https://github.com/arielf/vowpal_wabbit/wiki/vw-top-errors:-online-learning-debugging-for-better-models', 'http://hunch.net/~jl/projects/prediction_bounds/progressive_validation/coltfinal.pdf']
3
48,739,513
<p>Recurrent Layers are like Feed Forward Neural Networks with a Feedback Loop in it. They just pass on the useful information from the past to present.</p> <p>A decent explanation is at: <a href="https://kevinzakka.github.io/2017/07/20/rnn/" rel="nofollow noreferrer">https://kevinzakka.github.io/2017/07/20/rnn/</a></p> <p>And coming to Adding More layers to RNN you can find the details for that Deep RNNs in the <a href="https://arxiv.org/pdf/1312.6026.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1312.6026.pdf</a></p> <p>The paper says that Deep RNNs are better than conventional RNNs</p>
2018-02-12 04:23:01.733000+00:00
2018-02-12 04:23:01.733000+00:00
null
null
48,734,004
<p>For convolutional networks, one can view the convolutional part (convolutional, max-pooling etc) as feature extraction which then gets feed into feedforward networks which does the classifying (more or less).</p> <p>Is the same true for recurrent networks (RNN, LSTM etc), i.e. the recurrent layers creates a represenation of the data/features which then gets feed into a feed-forward layers?</p> <p>I was think in terms of sentiment analysis, i.e. "sequence to one" model. Do you think that having one recurrent layer + one feed-forward layer would outperform only one recurrent layer network?</p>
2018-02-11 16:58:12.693000+00:00
2018-02-12 04:23:01.733000+00:00
null
machine-learning|deep-learning|recurrent-neural-network
['https://kevinzakka.github.io/2017/07/20/rnn/', 'https://arxiv.org/pdf/1312.6026.pdf']
2
39,464,289
<p>The patch size and the number of features are network hyper-parameters, therefore the are completely arbitrary.</p> <p>There are rules of thumb, by the way, to follow in order to define a working and performing network. The kernel size should be small, due to the equivalence between the application of multiple small kernels and lower number of big kernels (it's an image processing topic and it's well explained in the <a href="https://arxiv.org/pdf/1409.1556.pdf" rel="nofollow">VGG paper</a>). In addiction, operations with small filters are way faster to execute.</p> <p>The number of features to extract (32 in you example) is completely arbitrary and find the right number is somehow an art.</p>
2016-09-13 07:20:59.037000+00:00
2016-09-13 07:20:59.037000+00:00
null
null
39,461,904
<p>When I reading the chapter of &quot;Deep MNIST for expert&quot; in tensorflow tutorial.</p> <p>There give below function for the weight of first layer. I can't understand why the patch size is 5*5 and why features number is 32, are they the random numbers that you can pick anyone or some rules must be followed? and whether the features number &quot;32&quot; is the “Convolution kernel”?</p> <blockquote> <p>W_conv1 = weight_variable([5, 5, 1, 32])</p> <p>First Convolutional Layer</p> <p>We can now implement our first layer. It will consist of convolution, followed by max pooling. The convolutional will compute 32 features for each 5x5 patch. Its weight tensor will have a shape of [5, 5, 1, 32]. The first two dimensions are the patch size, the next is the number of input channels, and the last is the number of output channels. We will also have a bias vector with a component for each output channel.</p> </blockquote>
2016-09-13 03:44:15.133000+00:00
2017-05-21 07:47:14.263000+00:00
2020-06-20 09:12:55.060000+00:00
tensorflow|conv-neural-network
['https://arxiv.org/pdf/1409.1556.pdf']
1
70,494,842
<p>With object detection, you can identify objects and the object's location and extent on an image. This would be an option to check if specific objects are blocking your path. There is also the option of detecting/segmenting unknown objects (as described <a href="https://arxiv.org/abs/1907.09127" rel="nofollow noreferrer">here</a>). However, what you are after sounds more like depth estimation or even SLAM.</p> <p>One example for depth estimation is <a href="https://github.com/nianticlabs/monodepth2" rel="nofollow noreferrer">monodepth</a> - a neural network that can estimate the depth for each pixel from a single camera image. You can use that to verify if your path is clear or if something in front of your product is blocking the path.</p> <p>The other one SLAM - simultaneous location and mapping - might be a bit over the top for just checking if you can drive somewhere. Anyways, SLAM solves the task of navigating an unknown environment by building an internal model of the world and at the same time estimates the own location inside this model to solve navigation tasks.</p>
2021-12-27 11:25:23.373000+00:00
2021-12-27 11:33:15.467000+00:00
2021-12-27 11:33:15.467000+00:00
null
70,492,747
<p>Can I Use Tensorflow object detection API for detecting any objects which come in between my path so that can stop the movement of my product? I have done customized Object detections before but here I can't train each object which may interrupt my product path. So is that possible to use Tensorflow API as a kind of collision detection?</p>
2021-12-27 07:32:51.027000+00:00
2021-12-27 11:33:15.467000+00:00
null
tensorflow|deep-learning|artificial-intelligence|object-detection
['https://arxiv.org/abs/1907.09127', 'https://github.com/nianticlabs/monodepth2']
2
18,409,543
<p>On one hand, it is true that with gsl_vector you can use gsl BLAS which is a big advantage. On the other hand, it is also true that gsl interface is quite cumbersome for a c++ programmer. So, neither solutions are truly satisfactory. However, I strongly prefer the use of gsl_matrix because </p> <p>(i) with some effort you can write a small wrapper class that ameliorate the cumbersome C interface of gsl_matrix (it is much harder to deal with the lack of BLAS library in std::vector). </p> <p>(ii) gsl_matrix is just a wrapper to an one dimensional continuous array where <code>m(i,j) = array[i*N + j]</code> for square matrix (even if the matrix is not square gsl_matrix still implements it as one dimensional array). In <code>std::vector&lt;gsl_vector*&gt;</code>, you will need to "malloc" each gsl_vector individually and this implies that memory won't be contiguous. This hits performance because the lack of "spatial locality" in memory allocation usually increases cache misses substantially.</p> <p>If you have the choice to use a completely different solution, I would implement the tensor calculation using StaticMatrix or DynamicMatrix classes in Blaze lib</p> <p><a href="https://code.google.com/p/blaze-lib/" rel="nofollow">Blaze</a></p> <p>Why Blaze? </p> <p>(i) The StaticMatrix or DynamicMatrix interface is much better than <code>std::vector&lt;gsl_vector*&gt;</code> or gsl_matrix </p> <p>(ii) Blaze is the fastest BLAS lib available in C++. It is faster than gsl if you have available Intel MKL (remember that Intel MKL is faster than gsl BLAS). Why so? Because Blaze uses a new technique called "Smart Expression Template" . Basically, researchers in Germany showed in a series of articles <a href="http://www10.informatik.uni-erlangen.de/Publications/TechnicalReports/TechRep09-17.pdf" rel="nofollow">paper 1</a> <a href="http://arxiv.org/pdf/1104.1729.pdf" rel="nofollow">paper 2</a> that the "Expression Template" technique, which is the standard technique in many C++ BLAS libraries, is terrible for matrix operations (BLAS 3 operations) because compiler can't be smarter than low level code. However, "Expression Template" can be used as a smarter wrapper to low level BLAS libraries like intel MKL. So they create "Smart Expression Template" technique which is just a wrapper to your choice of low level blas lib. Their benchmarks are astonishing</p> <p><a href="https://code.google.com/p/blaze-lib/wiki/Benchmarks" rel="nofollow">benchmark</a></p>
2013-08-23 18:30:18.427000+00:00
2013-08-23 18:35:22.450000+00:00
2013-08-23 18:35:22.450000+00:00
null
17,805,247
<p>I am considering implementing an array like container, and I'm not sure whether to use a gsl::gsl_vector or a std::vector. The container needs to be space efficient but also very fast at calling values. The container will be referenced constantly in the main program to, for example, input values into tensor functions, amongst other things. I am calling from the container literally billions of times.</p> <p>Here are the pros and cons that I've considered so far: The gsl_vector is convenient because it will allow me to use the gsl BLAS libraries on occasion, and the <code>gsl_vector_get(...)</code> call is very efficient. On the other hand, I am able to get almost the same speed of calls using stl iterators, and the stl vector has an interface that I find quite natural.</p> <p>Are there any memory overheads/efficiency issues I should be aware of that I've overlook in the above code?</p> <p>Also, I am using a <code>std::vector&lt;gsl_vector*&gt;</code> implementation at the moment, and an iterator to traverse the std::vector. Would it be smarter to use a gsl_matrix here? The idea would be to use gsl_vector_views to get the right vector, rather than the iterator. Would this be more efficient?</p>
2013-07-23 08:37:06.777000+00:00
2013-08-23 18:35:22.450000+00:00
null
c++|vector|stl|comparison|gsl
['https://code.google.com/p/blaze-lib/', 'http://www10.informatik.uni-erlangen.de/Publications/TechnicalReports/TechRep09-17.pdf', 'http://arxiv.org/pdf/1104.1729.pdf', 'https://code.google.com/p/blaze-lib/wiki/Benchmarks']
4
68,102,773
<p>As far as I understand by reading the <a href="https://arxiv.org/pdf/1411.4166.pdf" rel="nofollow noreferrer">paper</a> and browsing the <a href="https://github.com/mfaruqui/retrofitting" rel="nofollow noreferrer">repository</a>, <strong>the proposed methodology only allows to improve the quality of the vectors</strong> (.vec) given in input.</p> <p>As you can read <a href="https://stackoverflow.com/questions/47118678/difference-between-fasttext-vec-and-bin-file">here</a>, fastText's ability to represent out-of-vocabulary words is inherent in the .bin model (which contains the vectors for all the n-grams).</p> <p><strong>As you too may have understood, there is no out-of-the-box way to retrofit a fastText model, using the proposed methodology.</strong></p>
2021-06-23 15:24:59.257000+00:00
2021-06-23 15:24:59.257000+00:00
null
null
68,100,358
<p>I have read various research papers that one can retrofitting a fasttext model to improve its accuracy (<a href="https://github.com/mfaruqui/retrofitting" rel="nofollow noreferrer">https://github.com/mfaruqui/retrofitting</a>). However I am having trouble on how to implement it.</p> <p>The github link above, will take one vector file and retrofitting it, output another vector file. I can load it using gensim library. However, since it is a vector file, it is no longer a model and it will not predict OOV (out-of-vocabulary) words. This makes it pointless. Is there a way to retrain the model somehow so it has better accuracy?</p>
2021-06-23 13:01:01.397000+00:00
2021-06-23 15:24:59.257000+00:00
null
python|gensim|fasttext
['https://arxiv.org/pdf/1411.4166.pdf', 'https://github.com/mfaruqui/retrofitting', 'https://stackoverflow.com/questions/47118678/difference-between-fasttext-vec-and-bin-file']
3
66,288,381
<p>I would say behavior such as this is to be expected for stochastic optimization in general. The inherent variance causes you to oscillate somewhere around good solution. The magnitude of the variance and properties of the optimization objective control how much this oscillates when looking at a accuracy metric.</p> <p>For plain SGD, decreasing learning rate decreases the variance and slows down convergence.</p> <p>For optimization methods for federated learning, the story is a bit more complicated, but decreasing the <em>client</em> learning rate, or decreasing the number of local steps (while keeping other things the same) can have a similar effect, typically including slowing down convergence. More details can be found in <a href="https://arxiv.org/abs/2007.00878" rel="nofollow noreferrer">https://arxiv.org/abs/2007.00878</a> mentioned also in the other answer. Potentially decreasing the client learning rate across rounds could also work. The details can differ also based on what exactly is the optimization method you are using.</p>
2021-02-20 05:37:33.433000+00:00
2021-02-20 05:37:33.433000+00:00
null
null
66,259,690
<p>I train a ResNet50 model with TFF, I use test accuracy on test data for evaluation, but I find many fluctuations as shown in the figure below, So please how can I avoid this fluctuation ?</p> <p><a href="https://i.stack.imgur.com/JDtmg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JDtmg.png" alt="enter image description here" /></a></p>
2021-02-18 12:10:21.837000+00:00
2021-03-03 07:22:26.220000+00:00
2021-03-03 07:22:26.220000+00:00
tensorflow-federated|federated-learning
['https://arxiv.org/abs/2007.00878']
1
66,288,150
<p>How is the test accuracy calculated? How many local epochs are the clients training?</p> <p>If the global model is tested on a held out set of examples, it is possible that clients are detrimentally overfitting during local training. As the global model approaches convergence, each client ends up training a model that works well for them individually, but may be diverging from the optimal global model (sometimes called <em>client drift</em> <a href="https://arxiv.org/abs/1910.06378" rel="nofollow noreferrer">https://arxiv.org/abs/1910.06378</a>). This is may occur when the client's local dataset has a distribution very different from the global distribution and more likely when the client learning rates are high (<a href="https://arxiv.org/abs/2007.00878" rel="nofollow noreferrer">https://arxiv.org/abs/2007.00878</a>).</p> <p>Decreasing the client learning rate, reducing the number of steps/batches, and other methods that cause the clients to do less &quot;work&quot; per communication round may reduce the fluctuation.</p>
2021-02-20 04:51:46.420000+00:00
2021-02-20 04:51:46.420000+00:00
null
null
66,259,690
<p>I train a ResNet50 model with TFF, I use test accuracy on test data for evaluation, but I find many fluctuations as shown in the figure below, So please how can I avoid this fluctuation ?</p> <p><a href="https://i.stack.imgur.com/JDtmg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JDtmg.png" alt="enter image description here" /></a></p>
2021-02-18 12:10:21.837000+00:00
2021-03-03 07:22:26.220000+00:00
2021-03-03 07:22:26.220000+00:00
tensorflow-federated|federated-learning
['https://arxiv.org/abs/1910.06378', 'https://arxiv.org/abs/2007.00878']
2
52,008,685
<p>Most programming languages, R included, do not track the number of significant digits for floating-point values. This is because in many cases significant digits are not necessary, would significantly slow down computations and require more RAM.</p> <p>You may want to be interested in some libraries for computations with uncertainties, like the <a href="https://arxiv.org/pdf/1804.08552.pdf" rel="nofollow noreferrer"><code>errors</code></a> (PDF) package.</p>
2018-08-24 16:43:57.093000+00:00
2018-08-24 16:43:57.093000+00:00
null
null
52,008,197
<p>Maybe a daft question but why does R remove the significant 0 in the end of a number? For example 1.250 becomes 1.25 which has not the same accuracy. I have been trying to calculate the number of significant digits of a number by using <code>as.character()</code> in combination with <code>gsub()</code> and regular expressions (according to various posts) but i get the wrong result for numbers such as 1.250, since <code>as.character</code> removes the last 0 digit. Therefore the answer for 1.250 comes out as 2 digits rather than 3 which is the correct.</p> <p>To be more specific why this is an issue for me:</p> <p>I have long tables in word comprising of bond lengths which are in the format eg: 1.2450(20): </p> <p><a href="https://i.stack.imgur.com/vnciQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vnciQ.png" alt="enter image description here"></a></p> <p>The number in parenthesis is the uncertainty in the measurement which means that the real value is somewhere between 1.2450+0.0020 and 1.2450-0.0020. I have imported all these data from word in a large data frame like so:</p> <pre><code>df&lt;-data.frame(Activity = c(69790, 201420, 17090), WN1=c(1.7598, 1.759, 1.760), WN1sd=c(17, 15, 3)) </code></pre> <p>My aim is to plot the WN1 values against activity but also have the error bar on. This means that i will need to manually convert the WN1sd to: <code>WN1sd=c(0.0017, 0.015, 0.003)</code> which is not the R way to go, hence the need to obtain the number of significant digits of WN1. This works fine for the first two WN1 values but not for the 3rd value since R mistakenly thinks that the last 0 is not significant.</p>
2018-08-24 16:10:00.397000+00:00
2018-08-28 09:45:49.570000+00:00
2018-08-28 09:45:49.570000+00:00
r
['https://arxiv.org/pdf/1804.08552.pdf']
1
43,586,947
<p>I agree with you that this is a key question, but I am not aware of much work in that area either. </p> <p>There's one recent paper by <a href="https://arxiv.org/abs/1511.03719" rel="noreferrer">Zhang and LeCun</a>, that addresses the question for image classification in particular. They use large quantities of unlabelled data to create an additional "none of the above" class. The catch though is that, in some cases, their unlabelled data is not completely unlabelled, and they have means of removing "unlabelled" images that are actually in one of their labelled classes. Having said that, the authors report that apart from solving the "none of the above" problem, they even see performance gains even on their test sets.</p> <p>As for fitting something post-hoc, just by looking at the outputs of the softmax, I can't provide any pointers.</p>
2017-04-24 11:32:36.457000+00:00
2017-04-24 11:32:36.457000+00:00
null
null
43,578,715
<p>This seems to be a fundamental question which some of you out there must have an opinion on. I have an image classifier implemented in CNTK with 48 classes. If the image does not match any of the 48 classes very well, then I'd like to be able to conclude that it was not among these 48 image types. My original idea was simply that if the highest output of the final Softmax layer was low, I would be able to conclude that the test image matched none well. While I occasionally see this occur, in most testing, Softmax still produces a very high (and mistaken) result when handed an 'unknown image type'. But maybe my network is 'over fit' and if it wasn't, my original idea would work fine. What do you think? Any way to define a 49-th class called 'none-of-the-above'?</p>
2017-04-24 02:07:00.003000+00:00
2017-04-24 16:00:47.353000+00:00
null
classification|cntk|softmax
['https://arxiv.org/abs/1511.03719']
1
57,590,067
<p>Treating the genres as tokens, and training a vector-per-genre, should be possible. </p> <p>For training, you'd need "texts" that use the different genres together - these could be the multiple genres users have assigned to a single track, or the sequences-of-genres within a certain user's listening-history, or the sequences-of-genres within a certain artist's works, etc. </p> <p>And, I suspect this approach could work fairly well, successfully placing genres into a coordinate space where their relative distances/directions to each other resemble human judgements. These "dense embeddings" could then be used as inputs to other downstream ML techniques. </p> <p>Some thoughts that may help:</p> <ul> <li><p>For a good dense embedding, you'll want the space dimensionality to be much smaller than the count of unique tokens. That is, much smaller in number-of-continuous dimensions than the "one-hot" encoding would be. So you probably <strong>don't</strong> want to collapse related genres (like <code>low-fi trap</code> into <code>trap</code>) - that'd be throwing away potentially useful subtleties in the data, even if they're noisy, when the point of *2vec training is to be able to learn/numerically-model such subtleties (as long as there are enough examples of contextual use). </p></li> <li><p>When training on data that isn't truly natural language, and for specific predictive purposes, it becomes more likely that training parameters far from the usual defaults may be optimal – once you have a repeatable way to score different models for your purposes. (For example, there's a exponentiation parameter used in the negative-sampling that was fixed at <code>0.75</code> in most word2vec implementations - but a <a href="https://arxiv.org/abs/1804.04212" rel="nofollow noreferrer">recent paper</a> suggests very-different values may be noticeably better in recommendation-applications. So, it's been made specifiable in recent versions of the Python <code>gensim</code> library.)</p></li> </ul>
2019-08-21 10:55:55.860000+00:00
2019-08-21 10:55:55.860000+00:00
null
null
57,588,825
<p>I'm in the process of creating a predictive model of track popularity. One of the features that I have is music genre. The variable contains many unique, but similar values, for instance: 'contemporary country', 'country pop', 'trap', 'lo-fi trap'. <strong>I'm looking for a ways to represent that column numerically</strong>.</p> <p>I would like to create 1D embeddings for my the music genre variable based on audio features of tracks belonging to a particular genre. Is that actually possible ?</p> <p>I'd be super grateful for any kind of assistance with the problem.</p>
2019-08-21 09:45:50.090000+00:00
2019-08-21 14:01:47.830000+00:00
2019-08-21 14:01:47.830000+00:00
machine-learning|vectorization|word2vec
['https://arxiv.org/abs/1804.04212']
1
54,295,849
<p>The below VGG-16 architechture is in the <a href="https://arxiv.org/pdf/1409.1556.pdf" rel="noreferrer">original paper as highlighted by @deltheil in (table 1, column D) </a>, and I quote from there</p> <blockquote> <p>2.1 ARCHITECTURE</p> <p>During training, the input to our ConvNets is a fixed-size 224 × 224 RGB images. The only preprocessing we do is subtracting the mean RGB value, computed on the training set, from each pixel.</p> <p>The image is passed through a stack of convolutional (conv.) layers, where we use filters with a very small receptive field: 3 × 3 (which is the smallest size to capture the notion of left/right, up/down, center). The convolution stride is fixed to 1 pixel; the spatial padding of conv. layer input is such that the spatial resolution is preserved after convolution, i.e. the padding is 1 pixel for 3 × 3 conv. layers. Spatial pooling is carried out by five max-pooling layers, which follow some of the conv. layers (not all the conv. layers are followed by max-pooling). Max-pooling is performed over a 2 × 2 pixel window, with stride 2.</p> <p>A stack of convolutional layers (which has a different depth in different architectures) is followed by three Fully-Connected (FC) layers: the first two have 4096 channels each, the third performs 1000-way ILSVRC classification and thus contains 1000 channels (one for each class). </p> <p>The final layer is the soft-max layer.</p> </blockquote> <p>Using the above, and </p> <ul> <li>A formula to find activation shape of a layer!</li> </ul> <p><img src="https://i.stack.imgur.com/oucTkt.jpg" width="200" /></p> <ul> <li>A formula to calculate the weights corresponding to every layer:</li> </ul> <p><img src="https://i.stack.imgur.com/R8F7a.png" width="200" /></p> <p><strong>Note:</strong></p> <ul> <li><p>you can simply multiply respective activation shape column to get the activation size</p></li> <li><p>CONV3: means a filter of 3*3 will convolve on the input!</p></li> <li><p>MAXPOOL3-2: means, 3rd pooling layer, with 2*2 filter, stride=2, padding=0(pretty standard in pooling layers)</p></li> <li><p>Stage-3 : means it has multiple CONV layer stacked! with same padding=1, , stride=1, and filter 3*3</p></li> <li><p>Cin : means the depth a.k.a channel coming from the input layer!</p></li> <li><p>Cout: means the depth a.k.a channel outgoing (you configure it differently- to learn more complex features!),</p></li> </ul> <p>Cin and Cout are the number of filters that you stack together to learn multiple features at different scales such as in the first layer you might want to learn vertical edges, and horizontal edges and edges at say 45degree, blah blah!, 64 possible different filters each of different kind of edges!! </p> <ul> <li><p>n: input dimension without depth such n=224 in case of INPUT-image!</p></li> <li><p>p: padding for each layer</p></li> <li><p>s: stride used for each layer</p></li> <li><p>f: filter size i.e 3*3 for CONV and 2*2 for MAXPOOL layers! </p></li> <li><p>After MAXPOOL5-2, you simply flatten the volume and interface it with the first FC layer.!</p></li> </ul> <p><strong><em>We get the table:</em></strong> <a href="https://i.stack.imgur.com/zCwzX.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/zCwzX.jpg" alt="enter image description here"></a></p> <p><strong><em>Finally, if you add all the weights calculated in the last column, you end up with 138,357,544(138 million) parameters to train for VGG-15!</em></strong></p>
2019-01-21 18:27:33.553000+00:00
2019-01-21 18:45:12.300000+00:00
2019-01-21 18:45:12.300000+00:00
null
28,232,235
<p>I can't give the correct number of parameters of <a href="http://www.cs.toronto.edu/~fritz/absps/imagenet.pdf">AlexNet</a> or <a href="http://arxiv.org/abs/1409.1556">VGG Net</a>.</p> <p>For example, to calculate the number of parameters of a <code>conv3-256</code> layer of VGG Net, the answer is 0.59M = (3*3)*(256*256), that is (kernel size) * (product of both number of channels in the joint layers), however in that way, I can't get the <code>138M</code> parameters.</p> <p>So could you please show me where is wrong with my calculation, or show me the right calculation procedure?</p>
2015-01-30 08:51:14.553000+00:00
2020-11-12 07:59:45.033000+00:00
2018-10-30 13:36:28.840000+00:00
machine-learning|neural-network|computer-vision|vgg-net
['https://arxiv.org/pdf/1409.1556.pdf', 'https://i.stack.imgur.com/zCwzX.jpg']
2
66,918,391
<p>We directly use a pre-trained VGGNet or ResNet backbone. Although the backbone is pre-trained for classification task, the hidden layers learn features which can be used for object detection also. Initial layers will learn low level features such as lines, dots, curves etc. Next layer will learn learn high-level features that are built on top of low-level features to detect objects and larger shapes in the image.</p> <p><a href="https://i.stack.imgur.com/K03Wx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K03Wx.jpg" alt="enter image description here" /></a></p> <p>Then the last layers are modified to output the object detection coordinates rather than class.</p> <p>There are object detection specific backbones too. Check these papers:</p> <ul> <li><a href="https://arxiv.org/abs/1804.06215" rel="nofollow noreferrer">DetNet: A Backbone network for Object Detection</a></li> <li><a href="https://github.com/PKUbahuangliuhe/CBNet" rel="nofollow noreferrer">CBNet: A Novel Composite Backbone Network Architecture for Object Detection</a></li> <li><a href="https://papers.nips.cc/paper/2019/file/228b25587479f2fc7570428e8bcbabdc-Paper.pdf" rel="nofollow noreferrer">DetNAS: Backbone Search for Object Detection</a></li> <li><a href="https://www.microsoft.com/en-us/research/blog/high-resolution-network-a-universal-neural-architecture-for-visual-recognition/" rel="nofollow noreferrer">High-Resolution Network: A universal neural architecture for visual recognition</a></li> </ul> <p>Lastly, the pretrained weights will be useful only if you are using them for similar images. E.g.: weights trained on Image-net will be useless on ultrasound medical image data. In this case we would rather train from scratch.</p>
2021-04-02 11:06:15.310000+00:00
2021-04-02 11:06:15.310000+00:00
null
null
66,915,996
<p>I am trying to understand the training process of a object deetaction deeplearng algorithm and I am having some problems understanding how the backbone network (the network that performs feature extraction) is trained.</p> <p>I understand that it is common to use CNNs like AlexNet, VGGNet, and ResNet but I don't understand if these networks are pre-trained or not. If they are not trained what does the training consist of?</p>
2021-04-02 07:42:52.377000+00:00
2021-04-02 11:06:15.310000+00:00
2021-04-02 09:03:29.613000+00:00
deep-learning|computer-vision|conv-neural-network|object-detection
['https://i.stack.imgur.com/K03Wx.jpg', 'https://arxiv.org/abs/1804.06215', 'https://github.com/PKUbahuangliuhe/CBNet', 'https://papers.nips.cc/paper/2019/file/228b25587479f2fc7570428e8bcbabdc-Paper.pdf', 'https://www.microsoft.com/en-us/research/blog/high-resolution-network-a-universal-neural-architecture-for-visual-recognition/']
5
64,616,311
<p>Have a look at <a href="https://huggingface.co/" rel="nofollow noreferrer">HuggingFace</a>'s pretrained models.</p> <ol> <li>They have a multilingual NER model trained on 40 languages, including Cyrillic languages like Russian. It's a fine-tuned version of RoBERTa, so accuracy seems to be very good. See details here: <a href="https://huggingface.co/jplu/tf-xlm-r-ner-40-lang" rel="nofollow noreferrer">https://huggingface.co/jplu/tf-xlm-r-ner-40-lang</a></li> <li>They also have a multilingual DistilBERT model trained for typo detection based on the <a href="https://arxiv.org/pdf/1911.12893.pdf" rel="nofollow noreferrer">GitHub Typo Corpus</a>. The corpus seems to include typos from 15 different languages, including Russian. See details here: <a href="https://huggingface.co/mrm8488/distilbert-base-multi-cased-finetuned-typo-detection" rel="nofollow noreferrer">https://huggingface.co/mrm8488/distilbert-base-multi-cased-finetuned-typo-detection</a></li> </ol> <p>Here is some example code from the documentation slightly altered for your use-case:</p> <pre><code>from transformers import pipeline typo_checker = pipeline(&quot;ner&quot;, model=&quot;mrm8488/distilbert-base-multi-cased-finetuned-typo-detection&quot;, tokenizer=&quot;mrm8488/distilbert-base-multi-cased-finetuned-typo-detection&quot;) result = typo_checker(&quot;я живу в Мосве&quot;) result[1:-1] #[{'word': 'я', 'score': 0.7886862754821777, 'entity': 'ok', 'index': 1}, #{'word': 'жив', 'score': 0.6303715705871582, 'entity': 'ok', 'index': 2}, #{'word': '##у', 'score': 0.7259598970413208, 'entity': 'ok', 'index': 3}, #{'word': 'в', 'score': 0.7102937698364258, 'entity': 'ok', 'index': 4}, #{'word': 'М', 'score': 0.5045614242553711, 'entity': 'ok', 'index': 5}, #{'word': '##ос', 'score': 0.560469925403595, 'entity': 'typo', 'index': 6}, #{'word': '##ве', 'score': 0.8228507041931152, 'entity': 'ok', 'index': 7}] result = typo_checker(&quot;I live in Moskkow&quot;) result[1:-1] #[{'word': 'I', 'score': 0.7598089575767517, 'entity': 'ok', 'index': 1}, #{'word': 'live', 'score': 0.8173692226409912, 'entity': 'ok', 'index': 2}, #{'word': 'in', 'score': 0.8289134502410889, 'entity': 'ok', 'index': 3}, #{'word': 'Mo', 'score': 0.7344270944595337, 'entity': 'ok', 'index': 4}, #{'word': '##sk', 'score': 0.6559176445007324, 'entity': 'ok', 'index': 5}, #{'word': '##kow', 'score': 0.8762879967689514, 'entity': 'ok', 'index': 6}] </code></pre> <p>It doesn't seem to always work, unfortunately, but maybe it's sufficient for your use case.</p> <p>Another option would be <a href="https://spacy.io/" rel="nofollow noreferrer">SpaCy</a>. They don't have as many models for different languages, but with <a href="https://spacy.io/usage/rule-based-matching#entityruler" rel="nofollow noreferrer">SpaCy's EntityRuler</a> it's easy to manually define new entities i.e. &quot;extend the entity recognition database&quot;.</p>
2020-10-30 21:59:46.807000+00:00
2020-10-30 21:59:46.807000+00:00
null
null
44,763,499
<p>We would like to identify from a simple search neighborhood and streets in various cities. We don't only use English but also various other Cyrillic languages. We need to be able to identify spelling mistakes of locations. When looking at python libraries, I found this one: <a href="http://polyglot.readthedocs.io/en/latest/NamedEntityRecognition.html" rel="noreferrer">http://polyglot.readthedocs.io/en/latest/NamedEntityRecognition.html</a></p> <p>We tried to play around with it, but cannot find a way to extend the entity recognition database. How can that be done?<br> If not is there any other suggestion for a multi lingual nlp that can help spell check and also extract various entities matching a custom database? </p>
2017-06-26 15:44:28.557000+00:00
2020-10-30 21:59:46.807000+00:00
null
python|machine-learning|nlp|polyglot|named-entity-extraction
['https://huggingface.co/', 'https://huggingface.co/jplu/tf-xlm-r-ner-40-lang', 'https://arxiv.org/pdf/1911.12893.pdf', 'https://huggingface.co/mrm8488/distilbert-base-multi-cased-finetuned-typo-detection', 'https://spacy.io/', 'https://spacy.io/usage/rule-based-matching#entityruler']
6
59,142,908
<p>Have a look at the PCA implementation in dask-ML, <a href="https://ml.dask.org/modules/generated/dask_ml.decomposition.PCA.html" rel="nofollow noreferrer">https://ml.dask.org/modules/generated/dask_ml.decomposition.PCA.html</a>, this might already work for your case, as it uses the tsqr algorithm (<a href="https://arxiv.org/abs/1301.1071" rel="nofollow noreferrer">https://arxiv.org/abs/1301.1071</a>)</p>
2019-12-02 16:23:01.363000+00:00
2019-12-02 16:23:01.363000+00:00
null
null
59,047,684
<p>I am using a dask dataframe which can not be loaded directly into the memory because of the size of it. I want to perform dimentionality reduction of top of using incremental PCA.</p> <p>My dataframe is sparse in nature, so the question is can I perform it and if yes then how to do so.</p> <pre><code>image_features_df.head(3) feat1 feat2 feat3 ... feat25087 feat25088 fid selling_price 0 0.0 0.0 0.0 ... 0.0 0.0 2 269.00 4 0.3 0.1 0.0 ... 0.0 0.8 26 1720.00 6 0.8 0.0 0.0 ... 0.0 0.1 50 18145.25 </code></pre> <p>The above is a view of my dataframe. I want the output to have 95% cumulative varience. How to do so?</p> <p>My dataframe has 100,000 rows and 25088 columns so please tell a solution which is memory efficient.</p>
2019-11-26 09:29:39.743000+00:00
2019-12-02 16:23:01.363000+00:00
2019-11-26 09:36:38.580000+00:00
python|pandas|dask
['https://ml.dask.org/modules/generated/dask_ml.decomposition.PCA.html', 'https://arxiv.org/abs/1301.1071']
2
44,760,317
<p>In a classification task improving the accuracy is the goal.</p> <p>However, pooling allows you to:</p> <ol> <li>Reduce the input dimensionality</li> <li>Force the network to learn particular features, depending on the type of pooling you apply.</li> </ol> <p>Reducing the input dimensionality is something you want because it forces the network to project its learned representations in a different and with lower dimensionality space. This is good computationally speaking because you have to allocate less memory and thus you can have bigger batches. But it's also something desirable because usually high-dimensional spaces have a lot of redundancy and are spaces in which all abjects appears to be sparse and dissimilar ( see <a href="https://en.wikipedia.org/wiki/Curse_of_dimensionality)" rel="nofollow noreferrer">The curse of dimensionality</a> )</p> <p>The function you decide to use for the pooling operation, moreover, can force the network to give more importance to some features.</p> <p>Max-pooling, for instance, is widely used because allow the network to be robust to small variations of the input image.</p> <p>What happens, in practice, it that only the features with the highest activations pass through the max-pooling gate. If the input image is shifted by a small amount, then the max-pooling op produces the same output although the input is shifted (the maximum shift is thus equal to the kernel size).</p> <p>CNN without pooling are also capable of learning this kind of features, but with a bigger cost in term of parameters and computing time (see <a href="https://arxiv.org/abs/1412.6806" rel="nofollow noreferrer">Striving for Simplicity: The All Convolutional Net</a>)</p>
2017-06-26 12:57:24.547000+00:00
2017-06-26 12:57:24.547000+00:00
null
null
44,750,752
<p>I'm following Udacity Deep Learning video by Vincent Vanhoucke and trying to understand the (practical or intuitive or obvious) effect of max pooling.</p> <p>Let's say my current model (without pooling) uses convolutions with stride 2 to reduce the dimensionality. </p> <pre><code> def model(data): conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME') hidden = tf.nn.relu(conv + layer1_biases) conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME') hidden = tf.nn.relu(conv + layer2_biases) shape = hidden.get_shape().as_list() reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]]) hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases) return tf.matmul(hidden, layer4_weights) + layer4_biases </code></pre> <p>Now I introduced pooling: Replace the strides by a max pooling operation (nn.max_pool()) of stride 2 and kernel size 2.</p> <pre><code> def model(data): conv1 = tf.nn.conv2d(data, layer1_weights, [1, 1, 1, 1], padding='SAME') bias1 = tf.nn.relu(conv1 + layer1_biases) pool1 = tf.nn.max_pool(bias1, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME') conv2 = tf.nn.conv2d(pool1, layer2_weights, [1, 1, 1, 1], padding='SAME') bias2 = tf.nn.relu(conv2 + layer2_biases) pool2 = tf.nn.max_pool(bias2, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME') shape = pool2.get_shape().as_list() reshape = tf.reshape(pool2, [shape[0], shape[1] * shape[2] * shape[3]]) hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases) return tf.matmul(hidden, layer4_weights) + layer4_biases </code></pre> <p>What would be the compelling reason that we use the later model instead of no-pool model, besides the improved accuracy? Would love to have some insights from people who have already used cnn many times!</p>
2017-06-25 21:20:45.020000+00:00
2017-06-26 12:57:24.547000+00:00
null
tensorflow|deep-learning|conv-neural-network
['https://en.wikipedia.org/wiki/Curse_of_dimensionality)', 'https://arxiv.org/abs/1412.6806']
2
66,357,164
<p>The reason why convolutions are more efficient than fully connected layers is <em>beacause</em> they are translation invariant. If you wish to have convolutions which are dependent on location you would need to add two extra parameters to the convolution i.e. having N+2 input channels where x, y coord are the values of the two additonal channels (as in e.g. <a href="https://arxiv.org/abs/1807.03247" rel="nofollow noreferrer">CoordConv</a>, or <a href="https://arxiv.org/pdf/1510.02927.pdf" rel="nofollow noreferrer">Location Biased Convolutions</a>).</p>
2021-02-24 18:57:15.117000+00:00
2021-02-26 08:19:00.227000+00:00
2021-02-26 08:19:00.227000+00:00
null
52,614,786
<p>I want to implement a convolutional layer, with a different convolutional filter for each output location. Specifically, think of the case when the output is of 16*16*128 (W * H * C). Instead of having a 3*3*128 filter we have 16*16 filters; each with size 3*3*128. This would lead to huge amount of parameters, but it can the case be that each of the 3*3*128 filter may be the same except scaled by a different constant, and the constants can be learned through a side network. In this way the number of parameters won't be too much.</p> <p>The similar idea is briefly in <a href="https://arxiv.org/abs/1605.09673" rel="nofollow noreferrer">Dynamic Filter Networks</a>, but I cannot find an implementation of location specific filters. My question is, if we want a location specific convolutional filter how do I implement it in Tensorflow or Pytorch? Do I need to write my own operation or there is some smart way to use the functions provided? If I have to write an OP is there any trick that can easily achieve this idea? Any help is appreciated!</p>
2018-10-02 19:01:10.193000+00:00
2021-02-26 08:19:00.227000+00:00
2018-10-02 19:24:30.340000+00:00
python|tensorflow|deep-learning|conv-neural-network|pytorch
['https://arxiv.org/abs/1807.03247', 'https://arxiv.org/pdf/1510.02927.pdf']
2
25,089,932
<p>If you have the points of the border of your shape that lies on the same y as the enemy, then you can simply count the number of borders, starting from either left or right to the enemy. If it's odd then it's inside. If it's even then it's outside.</p> <p>Since you are using a grid system this should be <s>easy</s> to implement (and very fast). This algorithm is called the <a href="https://en.wikipedia.org/wiki/Point_in_polygon#Ray_casting_algorithm" rel="nofollow noreferrer">Ray casting algorithm</a>.</p> <p>Here's a simple example I created: <a href="http://jsfiddle.net/DerekL/8QBz6/" rel="nofollow noreferrer">http://jsfiddle.net/DerekL/8QBz6/</a> (can't deal with degenerate cases)</p> <pre><code>function testInside(){ var passedBorder = 0, passingBorder = false; for(var x = 0; x &lt;= enemy[0]; x++){ if(board[x][enemy[1]] === 1) passingBorder = true; else if(board[x][enemy[1]] === 0 &amp;&amp; passingBorder){ passingBorder = false; passedBorder++; } } return !!(passedBorder%2); } </code></pre> <p>For example, you have this shape which you have determined:<br> <img src="https://i.stack.imgur.com/UYywj.png" alt="enter image description here"></p> <p><em>removed</em></p> <hr> <p>Guess <a href="http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html" rel="nofollow noreferrer">what I found</a>, (slightly modified)</p> <pre><code>//simple enough, it only needs the x,y of your testing point and the wall. //no direction or anything else function testInside3() { var i, j, c = 0; for (i = 0, j = wallList.length-1; i &lt; wallList.length; j = i++) { if ( ((wallList[i][1]&gt;enemy[1]) ^ (wallList[j][1]&gt;enemy[1])) &amp;&amp; (enemy[0] &lt; (wallList[j][0]-wallList[i][0]) * (enemy[1]-wallList[i][1]) / (wallList[j][1]-wallList[i][1]) + wallList[i][0]) ) c = !c; } return !!c; } </code></pre> <p><a href="http://jsfiddle.net/DerekL/NvLcK/" rel="nofollow noreferrer">http://jsfiddle.net/DerekL/NvLcK/</a></p> <p>This is using the same ray casting algorithm I mentioned, but this time the "ray" is now mathematical using the following inequality for x and a condition for y:</p> <pre class="lang-none prettyprint-override"><code> (X2 - X1)(Py - Y1) Px &lt; ────────────────── + X1 Y2 - Y1 </code></pre> <p>which is derived by combining these two:</p> <pre class="lang-none prettyprint-override"><code>Ray: x(t) = Px + t, y(t) = Py, where t &gt; 0 (the ray goes to the right) Edge: x(u) = (X2 - X1)u + X1, y(u) = (Y2 - Y1)u + Y1, where 0 &lt;= u &lt;= 1 </code></pre> <p>And the condition for y:</p> <pre><code>(Y1 &gt; Py) ⊕ (Y2 &gt; Py) </code></pre> <p>which is equivalent to:</p> <pre><code>(Y1 ≥ Py &gt; Y2) ∨ (Y2 ≥ Py &gt; Y1) </code></pre> <p>and yadi yadi yada some other interesting technical stuff.</p> <p>Seems like this is the default algorithm in many native libraries. The method used to dealing with degenerate cases is called Simulation of Simplicity, described in <a href="http://arxiv.org/pdf/math/9410209.pdf" rel="nofollow noreferrer">this paper</a> (section 5.1).</p> <p>Nevertheless, here's the result generated with the algorithm testing every coordinate:<br> <img src="https://i.stack.imgur.com/mmkQO.png" alt="enter image description here"></p>
2014-08-01 23:05:18.620000+00:00
2014-08-02 20:49:23.280000+00:00
2014-08-02 20:49:23.280000+00:00
null
25,089,749
<p><strong>Background:</strong></p> <p>I am working on a tile-based game in Javascript where a character freely moves around the map (<strong>no diagonal</strong> - Left/Right/Up/Down) and fills in tiles as he moves around the map. There are three tile types -- tiles you've filled (blue), your current path (red), and empty ones (black). There are also enemies (stars) that move around the map as well, but only in empty areas. The objective is to fill as much of the map as possible.</p> <p>Map is sized as roughly 40x40 tiles. There is a 1 tile thick border around the entire outside of the map that is already "filled" (blue).</p> <p>I have established that a flood-fill algorithm will work for filling up areas of tiles when needed. However, my problem is as follows:</p> <p><strong>PROBLEM STATEMENT:</strong> I want to only fill a sectioned-off part of the map if there are no enemies in it. </p> <p><strong>My Question:</strong> I could run flood-fill algorithm and stop it if it reaches a tile occupied by an enemy -- however, is this the most efficient approach (for a real time game)?<br> IF YES, <strong>how do I determine where to start the algorithm from in a systematic way</strong> since there are multiple areas to check and the character doesn't have to move in a perfectly straight line (can zig-zag up/down/right/left, but can't move diagonally). </p> <p><strong>Picture Example 1 (pics explain better):</strong> </p> <p>Note: <strong>red areas turn blue (filled) once you reach another filled area</strong>. In example below, there are no enemies in the contained area, so the area is filled.</p> <p><img src="https://i.stack.imgur.com/n4dxr.png" alt="FillExample1:inprogress"> <img src="https://i.stack.imgur.com/IJ9kz.png" alt="FillExample1:filled"></p> <p><strong>Picture Example 2:</strong> </p> <p>In this second example, there is an enemy within the contained area (and on the outside area - not shown) so nothing but the line is filled.</p> <p><img src="https://i.stack.imgur.com/LJ2Ew.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/5rMk6.png" alt="enter image description here"></p> <p><strong><em>Summary:</em></strong> What is the best approach for doing this type of filling? Is flood fill the best choice for determining whether to fill or not -- 40x40 makes for a pretty large calculation. If yes, how do I determine what tile do I start with?</p>
2014-08-01 22:44:29.380000+00:00
2014-08-02 20:49:23.280000+00:00
2014-08-02 20:23:30.587000+00:00
javascript|algorithm|tile|flood-fill
['https://en.wikipedia.org/wiki/Point_in_polygon#Ray_casting_algorithm', 'http://jsfiddle.net/DerekL/8QBz6/', 'http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html', 'http://jsfiddle.net/DerekL/NvLcK/', 'http://arxiv.org/pdf/math/9410209.pdf']
5
15,640,572
<p>Consider what you're trying to achieve. Typically, the <a href="http://martinfowler.com/bliki/CQRS.html" rel="noreferrer"><strong>Command Query Response Segregation</strong></a> model works well for complex domains.</p> <p>The reason is that you're trying to do one of two things typically:</p> <ol> <li>Create/Update/Delete some complex domain entities</li> <li>Run analytic fetch queries (i.e. summation/aggregation queries)</li> </ol> <p><strong>Hibernate</strong> works well for case 1 allowing you to just make a POJO and persist/update it. It also does this quickly, unless your domain is quite large.</p> <p><strong>myBatis</strong> is great for fetch queries (case 2) where you just want an answer. Hibernate would attempt to load the entire object graph and you'd need to start tuning queries with LazyLoading tricks to keep it working on a large domain. Conversely if you just want some analytic POJO page, the myBatis implementation of the same query would be trivial.</p> <p>Because of this, myBatis <a href="http://arxiv.org/ftp/arxiv/papers/0710/0710.1404.pdf" rel="noreferrer">is faster than Hibernate</a> at SELECTS.</p> <p>These two cases are the difference between <strong>Commands</strong> where you want to change the domain data and <strong>Responses</strong> where you just want to fetch some data.</p> <p>So, consider these two cases and what your application does. If you have a simple domain and just fetch information, use myBatis. If you have a complex domain and persist entities, use Hibernate. If you do both, consider a hybrid approach. That's what we use on our project that has thousands of entities to keep it under control. ;)</p>
2013-03-26 15:11:17.747000+00:00
2013-03-26 15:11:17.747000+00:00
null
null
1,984,548
<p>For our new product re-engineering, we are in the process of selecting the best framework from Java. As the consideration is to go for database agnostic approach for model, we are working on options between Struts + Spring with iBATIS or Hibernate. Please advice which is best as both offer persistence.</p>
2009-12-31 08:39:54.057000+00:00
2020-09-27 00:01:53.287000+00:00
2010-08-07 22:25:20.943000+00:00
java|hibernate|frameworks|persistence|ibatis
['http://martinfowler.com/bliki/CQRS.html', 'http://arxiv.org/ftp/arxiv/papers/0710/0710.1404.pdf']
2
60,588,244
<p>I guess you see the face of the two persons on the image. In this case you can try to use <strong>Facenet</strong> <a href="https://arxiv.org/abs/1503.03832" rel="nofollow noreferrer">Paper</a></p> <p>You can find an implementation for example here <a href="https://github.com/davidsandberg/facenet" rel="nofollow noreferrer">link</a></p>
2020-03-08 13:59:39.040000+00:00
2020-03-08 13:59:39.040000+00:00
null
null
60,587,254
<p>I need a trained deep learning mode can compare two images for two persons and give me the result as if the two image are for the same person or not.</p>
2020-03-08 12:01:08.487000+00:00
2020-03-08 13:59:39.040000+00:00
null
python|machine-learning|deep-learning|computer-vision
['https://arxiv.org/abs/1503.03832', 'https://github.com/davidsandberg/facenet']
2
39,942,443
<p>As far as I know, you cannot choose the outgoing interface without some routing table setup.</p> <p>In my opinion, the best solution is to set up a bunch of <em>source-specific routes</em>, routes that match on the source address of a packet, and bind to a given source address in order to select the route (as you already do). There are two ways of achieving that:</p> <ul> <li>use <code>ip rule</code> and multiple routing tables — this is described in <a href="http://lartc.org/howto/lartc.rpdb.html" rel="nofollow">http://lartc.org/howto/lartc.rpdb.html</a> ;</li> <li>use <code>ip route add ... from ...</code>. As far as I know, this only works for IPv6, but avoids the complexity of multiple routing tables.</li> </ul> <p>You'll find some background about source-specific routing in <a href="https://arxiv.org/pdf/1403.0445v4.pdf" rel="nofollow">https://arxiv.org/pdf/1403.0445v4.pdf</a> (disclaimer, I'm a co-author).</p>
2016-10-09 10:18:08.400000+00:00
2016-10-09 10:18:08.400000+00:00
null
null
39,941,958
<p>There are quite a couple of related questions (e.g. <a href="https://stackoverflow.com/questions/27479901/java-socket-specify-a-certain-network-interface-for-outgoing-connections">Java Socket specify a certain network interface for outgoing connections</a> ) however I couldn't find a satisfying i.e. practical solution to my problem:</p> <p>On my target (<strong>Linux</strong>) platform there are multiple network interfaces (eth0...ethN) from which a Server S is reachable. The default route is normally via eth0, however I'm trying to connect S via e.g. eth4 using</p> <pre><code>new java.net.Socket(IP_of_S, targetport, IP_of_eth4, srcport) </code></pre> <p>or</p> <pre><code>sock.bind( eth4_SocketAddress ); sock.connect( S_SocketAddress ); </code></pre> <p>In this example case the IP of eth4 is assigned correctly but traffic is still going out trough the interface of the default route. I've learned this is due to the the "weak end system model" RFC 1122. However I'm wondering whether there's still a Java-based solution to achieving my original goal or whether I have to trigger external iptables or route calls from my program.</p> <p>(BTW: The outgoing interface needs to be chosen dynamically at runtime, i.e. my program closes the connection and tries to reconnect using a different outbound interface quite frequently.)</p>
2016-10-09 09:19:46.290000+00:00
2016-10-09 10:18:08.400000+00:00
2017-05-23 12:16:31.943000+00:00
java|linux|sockets|network-interface|outbound
['http://lartc.org/howto/lartc.rpdb.html', 'https://arxiv.org/pdf/1403.0445v4.pdf']
2
66,195,015
<p>I think similar problems arise naturally in the stock market and in general when detecting outliers.</p> <p>So there are different way to move. Probably 1 is good enough.</p> <ol> <li><p>It looks like you have a <a href="https://en.wikipedia.org/wiki/Moving_average" rel="nofollow noreferrer">moving average</a> in the graphs. You could just take the difference to the moving average and see the distribution to evaluate the the appropriate thresholds for you to pay attention. It looks like in the first graph you have an event perhaps relevant. You could just place a threshold like two standard deviations of the average of the difference between the real series and the moving average.</p> </li> <li><p>De-trend each series. Even 1) could be good enough (I mean just substraction of real value for the series minus the average for the last X days), you could de-trend using more sophisticated ideas. But that could need more attention for each case, for instance you should be careful with seasonality and so on. Perhaps something line <a href="https://en.wikipedia.org/wiki/Hodrick%E2%80%93Prescott_filter" rel="nofollow noreferrer">Hodrick Prescott</a> or inline with this: <a href="https://machinelearningmastery.com/decompose-time-series-data-trend-seasonality/" rel="nofollow noreferrer">https://machinelearningmastery.com/decompose-time-series-data-trend-seasonality/</a>.</p> </li> <li><p>Perhaps the idea from 1) is more formally described as <a href="https://en.wikipedia.org/wiki/Bollinger_Bands" rel="nofollow noreferrer">Bollinger Bands</a>. That help you to know where the time series should be with some probability.</p> </li> <li><p>There are more sophisticated ways to identify outliers in time series (as in here: <a href="https://towardsdatascience.com/effective-approaches-for-time-series-anomaly-detection-9485b40077f1" rel="nofollow noreferrer">https://towardsdatascience.com/effective-approaches-for-time-series-anomaly-detection-9485b40077f1</a>) or here for a literature review: <a href="https://arxiv.org/pdf/2002.04236.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/2002.04236.pdf</a></p> </li> </ol>
2021-02-14 11:36:36.057000+00:00
2021-02-14 11:49:30.813000+00:00
2021-02-14 11:49:30.813000+00:00
null
66,091,072
<p>Hi I am recording data for around 150k items in influx. I have tried grouping by item id and using some of the functions from <a href="https://docs.influxdata.com/influxdb/v1.8/query_language/functions/" rel="nofollow noreferrer">the docs</a> but they don't seem to show &quot;trend&quot;.</p> <p>As there are a lot of series' to group by. I am currently performing a query on each series to calculate a value, storing it and sorting by that.</p> <p>I have tried to use Linear Regression (the average angle of the line) but it's not quite meant for this as the X axis are timestamps, which do not correlate to the Y axis values, so end up with a near vertical line. Maybe i can calculate the X values to be something else?</p> <p>The other issue i have is some series' are much higher values than others, so one series jumping up by 1000 might be huge (very trending) and not a big deal for other series that are always much higher.</p> <p>Is there a way i can generate a single value from a series that represents how trending the series is, eg its just jumped up quite a lot compared to normal.</p> <p>Here is an example of one series that is not trending and one that was trending a couple days ago. So the latter would have a higher trend value than the first:</p> <p><a href="https://i.imgur.com/lDIIULv.png" rel="nofollow noreferrer"><img src="https://i.imgur.com/lDIIULv.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/EA1gF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EA1gF.png" alt="enter image description here" /></a></p> <p>Thanks!</p>
2021-02-07 17:39:44.863000+00:00
2021-02-14 11:49:30.813000+00:00
2021-02-11 16:46:19.317000+00:00
math|statistics|time-series|influxdb|trend
['https://en.wikipedia.org/wiki/Moving_average', 'https://en.wikipedia.org/wiki/Hodrick%E2%80%93Prescott_filter', 'https://machinelearningmastery.com/decompose-time-series-data-trend-seasonality/', 'https://en.wikipedia.org/wiki/Bollinger_Bands', 'https://towardsdatascience.com/effective-approaches-for-time-series-anomaly-detection-9485b40077f1', 'https://arxiv.org/pdf/2002.04236.pdf']
6
59,294,133
<p><strong>Update</strong>: the LayerNormalization implementation I was using was <em>inter-layer</em>, not <em>recurrent</em> as in the original paper; results with latter may prove superior.</p> <hr> <p><code>BatchNormalization</code> <em>can</em> work with LSTMs - the linked SO gives false advice; in fact, in my application of EEG classification, it dominated <code>LayerNormalization</code>. Now to your case:</p> <ul> <li><em>"Can I add it before <code>Conv1D</code>"</em>? Don't - instead, standardize your data beforehand, else you're employing an inferior variant to do the same thing</li> <li>Try both: <code>BatchNormalization</code> before an activation, and after - apply to both <code>Conv1D</code> and <code>LSTM</code></li> <li>If your model is exactly as you show it, <code>BN</code> after <code>LSTM</code> may be counterproductive per ability to introduce noise, which can confuse the classifier layer - but this is about being one layer before output, not <code>LSTM</code></li> <li>If you aren't using stacked <code>LSTM</code> with <code>return_sequences=True</code> preceding <code>return_sequences=False</code>, you can place <code>Dropout</code> anywhere - before <code>LSTM</code>, after, or both</li> <li><strong>Spatial Dropout</strong>: drop <em>units</em> / <em>channels</em> instead of random activations (see bottom); was shown more effective at reducing coadaptation in CNNs in paper by <a href="https://arxiv.org/pdf/1411.4280.pdf" rel="nofollow noreferrer">LeCun, et al</a>, w/ ideas applicable to RNNs. Can considerably increase convergence time, but also improve performance</li> <li><code>recurrent_dropout</code> is still preferable to <code>Dropout</code> for <code>LSTM</code> - <em>however</em>, you can do both; just do not use with with <code>activation='relu'</code>, for which <code>LSTM</code> is unstable per a bug</li> <li>For data of your dimensionality, any sort of <code>Pooling</code> is redundant and may harm performance; scarce data is better transformed via a non-linearity than simple averaging ops</li> <li>I strongly recommend a <code>SqueezeExcite</code> block after your Conv; it's a form of self-attention - see <a href="https://arxiv.org/abs/1709.01507" rel="nofollow noreferrer">paper</a>; my implementation for 1D below</li> <li>I also recommend trying <code>activation='selu'</code> with <code>AlphaDropout</code> and <code>'lecun_normal'</code> initialization, per paper <a href="https://arxiv.org/abs/1706.02515" rel="nofollow noreferrer">Self Normalizing Neural Networks</a></li> <li><em>Disclaimer</em>: above advice may not apply to NLP and embed-like tasks</li> </ul> <p>Below is an example template you can use as a starting point; I also recommend the following SO's for further reading: <a href="https://stackoverflow.com/questions/48714407/rnn-regularization-which-component-to-regularize/58868383#58868383">Regularizing RNNs</a>, and <a href="https://stackoverflow.com/questions/59017288/how-to-visualize-rnn-lstm-gradients-in-keras-tensorflow/59017289#59017289">Visualizing RNN gradients</a></p> <pre class="lang-py prettyprint-override"><code>from keras.layers import Input, Dense, LSTM, Conv1D, Activation from keras.layers import AlphaDropout, BatchNormalization from keras.layers import GlobalAveragePooling1D, Reshape, multiply from keras.models import Model import keras.backend as K import numpy as np def make_model(batch_shape): ipt = Input(batch_shape=batch_shape) x = ConvBlock(ipt) x = LSTM(16, return_sequences=False, recurrent_dropout=0.2)(x) # x = BatchNormalization()(x) # may or may not work well out = Dense(1, activation='relu') model = Model(ipt, out) model.compile('nadam', 'mse') return model def make_data(batch_shape): # toy data return (np.random.randn(*batch_shape), np.random.uniform(0, 2, (batch_shape[0], 1))) batch_shape = (32, 21, 20) model = make_model(batch_shape) x, y = make_data(batch_shape) model.train_on_batch(x, y) </code></pre> <p><strong>Functions used</strong>:</p> <pre class="lang-py prettyprint-override"><code>def ConvBlock(_input): # cleaner code x = Conv1D(filters=10, kernel_size=3, padding='causal', use_bias=False, kernel_initializer='lecun_normal')(_input) x = BatchNormalization(scale=False)(x) x = Activation('selu')(x) x = AlphaDropout(0.1)(x) out = SqueezeExcite(x) return out def SqueezeExcite(_input, r=4): # r == "reduction factor"; see paper filters = K.int_shape(_input)[-1] se = GlobalAveragePooling1D()(_input) se = Reshape((1, filters))(se) se = Dense(filters//r, activation='relu', use_bias=False, kernel_initializer='he_normal')(se) se = Dense(filters, activation='sigmoid', use_bias=False, kernel_initializer='he_normal')(se) return multiply([_input, se]) </code></pre> <hr> <p><strong>Spatial Dropout</strong>: pass <code>noise_shape = (batch_size, 1, channels)</code> to <code>Dropout</code> - has the effect below; see <a href="https://gist.github.com/OverLordGoldDragon/4d32dffd8f5d9123a886c21558da60a8" rel="nofollow noreferrer">Git gist</a> for code:</p> <p><img src="https://i.stack.imgur.com/gqdNB.png" width="500"></p>
2019-12-11 21:10:37.563000+00:00
2020-02-04 21:53:57.533000+00:00
2020-02-04 21:53:57.533000+00:00
null
59,285,058
<p>Suppose that I have a model like this (this is a model for time series forecasting):</p> <pre><code>ipt = Input((data.shape[1] ,data.shape[2])) # 1 x = Conv1D(filters = 10, kernel_size = 3, padding = 'causal', activation = 'relu')(ipt) # 2 x = LSTM(15, return_sequences = False)(x) # 3 x = BatchNormalization()(x) # 4 out = Dense(1, activation = 'relu')(x) # 5 </code></pre> <p>Now I want to add batch normalization layer to this network. Considering the fact that <a href="https://stackoverflow.com/questions/45493384/is-it-normal-to-use-batch-normalization-in-rnn-lstm-rnn/45495331">batch normalization doesn't work with LSTM</a>, Can I add it before <code>Conv1D</code> layer? I think it's rational to have a batch normalization layer after <code>LSTM</code>.</p> <p>Also, where can I add Dropout in this network? The same places? (after or before batch normalization?)</p> <ul> <li>What about adding <code>AveragePooling1D</code> between <code>Conv1D</code> and <code>LSTM</code>? Is it possible to add batch normalization between <code>Conv1D</code> and <code>AveragePooling1D</code> in this case without any effect on <code>LSTM</code> layer?</li> </ul>
2019-12-11 11:43:11.380000+00:00
2020-02-04 21:53:57.533000+00:00
2019-12-11 21:20:10.740000+00:00
tensorflow|keras|conv-neural-network|lstm|batch-normalization
['https://arxiv.org/pdf/1411.4280.pdf', 'https://arxiv.org/abs/1709.01507', 'https://arxiv.org/abs/1706.02515', 'https://stackoverflow.com/questions/48714407/rnn-regularization-which-component-to-regularize/58868383#58868383', 'https://stackoverflow.com/questions/59017288/how-to-visualize-rnn-lstm-gradients-in-keras-tensorflow/59017289#59017289', 'https://gist.github.com/OverLordGoldDragon/4d32dffd8f5d9123a886c21558da60a8']
6
61,566,139
<p>XGBoost can <em>handle</em> missing values, but it does not fill them. So the answer is no, you cannot use it to some how populate missing values in a feature. </p> <p>On training time, the way it handles missing data is by choosing the direction that will minimise the loss at each split. So all the process that is involved in the handling of missing data is in selecting the optimal path based on how much the loss function is minimized, but there is no value imputation involved.</p> <p>This is mentioned in the <a href="https://arxiv.org/pdf/1603.02754.pdf" rel="nofollow noreferrer">publication</a>:</p> <blockquote> <p>The optimal default directions are learnt from the data. The key improvement is to only visit the non-missing entries Ik. The presented algorithm treats the non-presence as a missing value and learns the best direction to handle missing values</p> </blockquote>
2020-05-02 20:51:41.583000+00:00
2020-05-02 21:16:59.497000+00:00
2020-05-02 21:16:59.497000+00:00
null
61,565,971
<p>I have a dataset which has missing values in it, however it is not a problem for XGBClassifier. It can dynamically fill the value for you. I want to save the features as XGBClassifier fill them. My aim is to use XGBoost to impute missing data, then I will try another algorithms which don't allow NaN values. Is this possible ?</p>
2020-05-02 20:36:58.397000+00:00
2020-05-02 22:16:29.367000+00:00
2020-05-02 22:16:29.367000+00:00
python|machine-learning|missing-data|xgboost|imputation
['https://arxiv.org/pdf/1603.02754.pdf']
1
64,884,458
<p>I think your question is based on a misconception. Even though the <a href="https://arxiv.org/abs/1810.04805" rel="noreferrer">BERT paper</a> uses the term <code>sentence</code> quite often, it is not referring to a linguistic sentence. The paper defines a sentence as</p> <blockquote> <p>an arbitrary span of contiguous text, rather than an actual linguistic sentence.</p> </blockquote> <p>It is therefore completely fine to pass whole paragraphs to BERT and a reason why they can handle those.</p>
2020-11-17 22:44:02.153000+00:00
2020-11-17 22:49:22.580000+00:00
2020-11-17 22:49:22.580000+00:00
null
64,881,478
<p>I have a dataset with paragraphs that I need to classify into two classes. These paragraphs are usually 3-5 sentences long. The overwhelming majority of them are less than 500 words long. I would like to make use of BERT to tackle this problem.</p> <p>I am wondering how I should use BERT to generate vector representations of these paragraphs and especially, whether it is fine to just pass the whole paragraph into BERT?</p> <p>There have been informative discussions of related problems <a href="https://stackoverflow.com/questions/58636587/how-to-use-bert-for-long-text-classification/63413589#63413589">here</a> and <a href="https://stackoverflow.com/questions/63671085/how-to-use-bert-for-long-sentences">here</a>. These discussions focus on how to use BERT for representing whole documents. In my case the paragraphs are not that long, and indeed could be passed to BERT without exceeding its maximum length of 512. However, BERT was trained on sentences. Sentences are relatively self-contained units of meaning. I wonder if feeding multiple sentences into BERT doesn't conflict fundamentally with what the model was designed to do (although this appears to be done regularly).</p>
2020-11-17 18:50:15.513000+00:00
2020-11-17 22:49:22.580000+00:00
null
nlp|text-classification|bert-language-model|huggingface-transformers
['https://arxiv.org/abs/1810.04805']
1
58,213,909
<blockquote> <p>I don't understand the reason behind keeping stride > 1 with window size 1. Isn't it just data loss?</p> </blockquote> <p>Please refer the section on Deeper Bottleneck Architectures in the resnet paper. Also, Figure 5. <a href="https://arxiv.org/pdf/1512.03385.pdf" rel="noreferrer">https://arxiv.org/pdf/1512.03385.pdf</a></p> <p>1 x 1 convolutions are typically used to increase or decrease the dimensionality along the filter dimension. So, in the bottleneck architecture the first 1 x 1 layer reduces the dimensions so that the 3 x 3 layer needs to handle smaller input/output dimensions. Then the final 1 x 1 layer increases the filter dimensions again.</p> <p>It's done to save on computation/training time.</p> <p>From the paper,</p> <p><em>"Because of concerns on the training time that we can afford, we modify the building block as a bottleneck design".</em></p>
2019-10-03 07:03:15.253000+00:00
2019-10-03 07:09:40.733000+00:00
2019-10-03 07:09:40.733000+00:00
null
58,200,107
<p>I'm learning Residual Networks (ResNet50) from Andrew Ng coursera lectures. I understand that one of the main reasons why ResNets work is that they can learn identity function and that's why adding more and more layers in network does not hurt the performance of the network. </p> <p>Now as described in lectures, there are two type of blocks are used in ResNets: 1) Identity block and Convolutional block. </p> <p>Identity Block is used when there is no change in input and output dimensions. Convolutional block is almost same as identity block but there is a convolutional layer in <code>short-cut</code> path to just change the dimension such that the dimension of input and output matches. </p> <p>Here is identity block:</p> <p><a href="https://i.stack.imgur.com/37qzA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/37qzA.png" alt="enter image description here"></a></p> <p>and here is convolutional block:</p> <p><a href="https://i.stack.imgur.com/0mE2p.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0mE2p.png" alt="enter image description here"></a></p> <p>Now in implementation of convolutional block (2nd image), First block (i.e. <code>conv2d --&gt; BatchNorm --&gt; ReLu</code> is implemented with <code>1x1</code> convolution and stride > 1.</p> <pre><code># First component of main path X = Conv2D(F1, (1, 1), strides = (s,s), name = conv_name_base + '2a', padding = 'valid', kernel_initializer = glorot_uniform(seed=0))(X) X = BatchNormalization(axis = 3, name = bn_name_base + '2a')(X) X = Activation('relu')(X) </code></pre> <p>I don't understand the reason behind keeping stride > 1 with window size 1. Isn't it just data loss? We are just considering alternate pixels in this case. </p> <p>What should be the possible reason for such hyperparameter selection? Any intuitive explanation will help! Thanks. </p>
2019-10-02 10:58:22.047000+00:00
2019-10-03 07:09:40.733000+00:00
null
python|tensorflow|keras|deep-learning|resnet
['https://arxiv.org/pdf/1512.03385.pdf']
1
31,193,169
<p>This is going to be a <em>long</em> answer. The answer to your question isn't simple and requires some number theory to fully answer. I've spent about half a day working through the algorithm and I now have a good answer, but I'm not sure I can describe it succinctly.</p> <h1>The short version:</h1> <ul> <li><p>Breaking the input into blocks of size 3<sup>k</sup> + 1 essentially breaks the input apart into blocks of size 3<sup>k</sup> - 1 surrounded by two elements that do not end up moving.</p> </li> <li><p>The remaining 3<sup>k</sup> - 1 elements in the block move according to an interesting pattern: each element moves to the position given by dividing the index by two modulo 3<sup>k</sup>.</p> </li> <li><p>This particular motion pattern is connected to a concept from number theory and group theory called <a href="https://en.wikipedia.org/wiki/Primitive_root_modulo_n" rel="noreferrer">primitive roots</a>.</p> </li> <li><p>Because the number two is a primitive root modulo 3<sup>k</sup>, beginning with the numbers 1, 3, 9, 27, etc. and running the pattern is guaranteed to cycle through all the elements of the array exactly once and put them into the proper place.</p> </li> <li><p>This pattern is highly dependent on the fact that 2 is a primitive root of 3<sup>k</sup> for any k ≥ 1. Changing the size of the array to another value will almost certainly break this because the wrong property is preserved.</p> </li> </ul> <h1>The Long Version</h1> <p>To present this answer, I'm going to proceed in steps. First, I'm going to introduce <a href="https://en.wikipedia.org/wiki/Cycle_decomposition" rel="noreferrer">cycle decompositions</a> as a motivation for an algorithm that will efficiently shuffle the elements around in the right order, subject to an important caveat. Next, I'm going to point out an interesting property of how the elements happen to move around in the array when you apply this permutation. Then, I'll connect this to a number-theoretic concept called <a href="https://en.wikipedia.org/wiki/Primitive_root_modulo_n" rel="noreferrer">primitive roots</a> to explain the challenges involved in implementing this algorithm correctly. Finally, I'll explain why this leads to the choice of 3<sup>k</sup> + 1 as the block size.</p> <h2>Cycle Decompositions</h2> <p>Let's suppose that you have an array A and a permutation of the elements of that array. Following the standard mathematical notation, we'll denote the permutation of that array as σ(A). We can line the initial array A up on top of the permuted array σ(A) to get a sense for where every element ended up. For example, here's an array and one of its permutations:</p> <pre><code> A 0 1 2 3 4 σ(A) 2 3 0 4 1 </code></pre> <p>One way that we can describe a permutation is just to list off the new elements inside that permutation. However, from an algorithmic perspective, it's often more helpful to represent the permutation as a <a href="https://en.wikipedia.org/wiki/Cycle_decomposition" rel="noreferrer">cycle decomposition</a>, a way of writing out a permutation by showing how to form that permutation by beginning with the initial array and then cyclically permuting some of its elements.</p> <p>Take a look at the above permutation. First, look at where the 0 ended up. In σ(A), the element 0 ended up taking the place of where the element 2 used to be. In turn, the element 2 ended up taking the place of where the element 0 used to be. We denote this by writing (0 2), indicating that 0 should go where 2 used to be, and 2 should go were 0 used to be.</p> <p>Now, look at the element 1. The element 1 ended up where 4 used to be. The number 4 then ended up where 3 used to be, and the element 3 ended up where 1 used to be. We denote this by writing (1 4 3), that 1 should go where 4 used to be, that 4 should go where 3 used to be, and that 3 should go where 1 used to be.</p> <p>Combining these together, we can represent the overall permutation of the above elements as (0 2)(1 4 3) - we should swap 0 and 2, then cyclically permute 1, 4, and 3. If we do that starting with the initial array, we'll end up at the permuted array that we want.</p> <p>Cycle decompositions are extremely useful for permuting arrays in place because it's possible to permute any individual cycle in O(C) time and O(1) auxiliary space, where C is the number of elements in the cycle. For example, suppose that you have a cycle (1 6 8 4 2). You can permute the elements in the cycle with code like this:</p> <pre><code>int[] cycle = {1, 6, 8, 4, 2}; int temp = array[cycle[0]]; for (int i = 1; i &lt; cycle.length; i++) { swap(temp, array[cycle[i]]); } array[cycle[0]] = temp; </code></pre> <p>This works by just swapping everything around until everything comes to rest. Aside from the space usage required to store the cycle itself, it only needs O(1) auxiliary storage space.</p> <p>In general, if you want to design an algorithm that applies a particular permutation to an array of elements, you can usually do so by using cycle decompositions. The general algorithm is the following:</p> <pre><code>for (each cycle in the cycle decomposition algorithm) { apply the above algorithm to cycle those elements; } </code></pre> <p>The overall time and space complexity for this algorithm depends on the following:</p> <ol> <li>How quickly can we determine the cycle decomposition we want?</li> <li>How efficiently can we store that cycle decomposition in memory?</li> </ol> <p>To get an O(n)-time, O(1)-space algorithm for the problem at hand, we're going to show that there's a way to determine the cycle decomposition in O(1) time and space. Since everything will get moved exactly once, the overall runtime will be O(n) and the overall space complexity will be O(1). It's not easy to get there, as you'll see, but then again, it's not awful either.</p> <h2>The Permutation Structure</h2> <p>The overarching goal of this problem is to take an array of 2n elements and shuffle it so that even-positioned elements end up at the front of the array and odd-positioned elements end up at the end of the array. Let's suppose for now that we have 14 elements, like this:</p> <pre><code> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 </code></pre> <p>We want to shuffle the elements so that they come out like this:</p> <pre><code> 0 2 4 6 8 10 12 1 3 5 7 9 11 13 </code></pre> <p>There are a couple of useful observations we can have about the way that this permutation arises. First, notice that <strong>the first element does not move</strong> in this permutation, because even-indexed elements are supposed to show up in the front of the array and it's the first even-indexed element. Next, notice that <strong>the last element does not move</strong> in this permutation, because odd-indexed elements are supposed to end up at the back of the array and it's the last odd-indexed element.</p> <p>These two observations, put together, means that if we want to permute the elements of the array in the desired fashion, we actually only need to permute the subarray consisting of the overall array with the first and last elements dropped off. Therefore, going forward, <strong>we are purely going to focus on the problem of permuting the middle elements.</strong> If we can solve that problem, then we've solved the overall problem.</p> <p>Now, let's look at just the middle elements of the array. From our above example, that means that we're going to start with an array like this one:</p> <pre><code> Element 1 2 3 4 5 6 7 8 9 10 11 12 Index 1 2 3 4 5 6 7 8 9 10 11 12 </code></pre> <p>We want to get the array to look like this:</p> <pre><code> Element 2 4 6 8 10 12 1 3 5 7 9 11 Index 1 2 3 4 5 6 7 8 9 10 11 12 </code></pre> <p>Because this array was formed by taking a 0-indexed array and chopping off the very first and very last element, we can treat this as a <strong>one-indexed array</strong>. That's going to be critically important going forward, so be sure to keep that in mind.</p> <p>So how exactly can we go about generating this permutation? Well, for starters, it doesn't hurt to take a look at each element and to try to figure out where it began and where it ended up. If we do so, we can write things out like this:</p> <ul> <li>The element at position 1 ended up at position 7.</li> <li>The element at position 2 ended up at position 1.</li> <li>The element at position 3 ended up at position 8.</li> <li>The element at position 4 ended up at position 2.</li> <li>The element at position 5 ended up at position 9.</li> <li>The element at position 6 ended up at position 3.</li> <li>The element at position 7 ended up at position 10.</li> <li>The element at position 8 ended up at position 4.</li> <li>The element at position 9 ended up at position 11.</li> <li>The element at position 10 ended up at position 5.</li> <li>The element at position 11 ended up at position 12.</li> <li>The element at position 12 ended up at position 6.</li> </ul> <p>If you look at this list, you can spot a few patterns. First, notice that the final index of all the even-numbered elements is always half the position of that element. For example, the element at position 4 ended up at position 2, the element at position 12 ended up at position 6, etc. This makes sense - we pushed all the even elements to the front of the array, so half of the elements that came before them will have been displaced and moved out of the way.</p> <p>Now, what about the odd-numbered elements? Well, there are 12 total elements. Each odd-numbered element gets pushed to the second half, so an odd-numbered element at position 2k+1 will get pushed to at least position 7. Its position within the second half is given by the value of k. Therefore, the elements at an odd position 2k+1 gets mapped to position 7 + k.</p> <p>We can take a minute to generalize this idea. Suppose that the array we're permuting has length 2n. An element at position 2x will be mapped to position x (again, even numbers get halfed), and an element at position 2x+1 will be mapped to position n + 1 + x. Restating this:</p> <blockquote> <p>The final position of an element at position p is determined as follows:</p> <ul> <li>If p = 2x for some integer x, then 2x ↦ x</li> <li>If p = 2x+1 for some integer x, then 2x+1 ↦ n + 1 + x</li> </ul> </blockquote> <p>And now we're going to do something that's entirely crazy and unexpected. Right now, we have a piecewise rule for determining where each element ends up: we either divide by two, or we do something weird involving n + 1. However, from a number-theoretic perspective, there is a <strong>single, unified rule</strong> explaining where all elements are supposed to end up.</p> <p>The insight we need is that in both cases, it seems like, in some way, we're dividing the index by two. For the even case, the new index really is formed by just dividing by two. For the odd case, the new index <em>kinda</em> looks like it's formed by dividing by two (notice that 2x+1 went to x + (n + 1)), but there's an extra term in there. In a number-theoretic sense, though, both of these really correspond to division by two. Here's why.</p> <p>Rather than taking the <em>source</em> index and <em>dividing</em> by two to get the <em>destination</em> index, what if we take the <em>destination</em> index and <em>multiply</em> by two? If we do that, an interesting pattern emerges.</p> <p>Suppose our original number was 2x. The destination is then x, and if we double the destination index to get back 2x, we end up with the source index.</p> <p>Now suppose that our original number was 2x+1. The destination is then n + 1 + x. Now, what happens if we double the destination index? If we do that, we get back 2n + 2 + 2x. If we rearrange this, we can alternatively rewrite this as (2x+1) + (2n+1). In other words, we've gotten back the original index, plus an extra (2n+1) term.</p> <p>Now for the kicker: <em>what if all of our arithmetic is done modulo 2n + 1</em>? In that case, if our original number was 2x + 1, then twice the destination index is (2x+1) + (2n+1) = 2x + 1 (modulo 2n+1). In other words, the destination index really is half of the source index, just done modulo 2n+1!</p> <p>This leads us to a very, very interesting insight: <em>the ultimate destination of each of the elements in a 2n-element array is given by dividing that number by two, modulo 2n+1</em>. This means that there really is a nice, unified rule for determining where everything goes. We just need to be able to divide by two modulo 2n+1. It just happens to work out that in the even case, this is normal integer division, and in the odd case, it works out to taking the form n + 1 + x.</p> <p>Consequently, we can reframe our problem in the following way: given a 1-indexed array of 2n elements, how do we permute the elements so that each element that was originally at index x ends up at position x/2 mod (2n+1)?</p> <h2>Cycle Decompositions Revisited</h2> <p>At this point, we've made quite a lot of progress. Given any element, we know where that element should end up. If we can figure out a nice way to get a cycle decomposition of the overall permutation, we're done.</p> <p>This is, unfortunately, where things get complicated. Suppose, for example, that our array has 10 elements. In that case, we want to transform the array like this:</p> <pre><code> Initial: 1 2 3 4 5 6 7 8 9 10 Final: 2 4 6 8 10 1 3 5 7 9 </code></pre> <p>The cycle decomposition of this permutation is (1 6 3 7 9 10 5 8 4 2). If our array has 12 elements, we want to transform it like this:</p> <pre><code> Initial: 1 2 3 4 5 6 7 8 9 10 11 12 Final: 2 4 6 8 10 12 1 3 5 7 9 11 </code></pre> <p>This has cycle decomposition (1 7 10 5 9 11 12 6 3 8 4 2 1). If our array has 14 elements, we want to transform it like this:</p> <pre><code> Initial: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Final: 2 4 6 8 10 12 14 1 3 5 7 9 11 13 </code></pre> <p>This has cycle decomposition (1 8 4 2)(3 9 12 6)(5 10)(7 11 13 14). If our array has 16 elements, we want to transform it like this:</p> <pre><code> Initial: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Final: 2 4 6 8 10 12 14 16 1 3 5 7 9 11 13 15 </code></pre> <p>This has cycle decomposition (1 9 13 15 16 8 4 2)(3 10 5 11 14 7 12 6).</p> <p>The problem here is that these cycles don't seem to follow any predictable patterns. This is a real problem if we're going to try to solve this problem in O(1) space and O(n) time. Even though given any individual element we can figure out what cycle contains it and we can efficiently shuffle that cycle, it's not clear how we figure out what elements belong to what cycles, how many different cycles there are, etc.</p> <h2>Primitive Roots</h2> <p>This is where number theory comes in. Remember that each element's new position is formed by dividing that number by two, modulo 2n+1. Thinking about this backwards, we can figure out which number will take the place of each number by <em>multiplying</em> by two modulo 2n+1. Therefore, we can think of this problem by finding the cycle decomposition in reverse: we pick a number, keep multiplying it by two and modding by 2n+1, and repeat until we're done with the cycle.</p> <p>This gives rise to a well-studied problem. Suppose that we start with the number k and think about the sequence k, 2k, 2<sup>2</sup>k, 2<sup>3</sup>k, 2<sup>4</sup>k, etc., all done modulo 2n+1. Doing this gives different patterns depending on what odd number 2n+1 you're modding by. This explains why the above cycle patterns seem somewhat arbitrary.</p> <p>I have no idea how anyone figured this out, but it turns out that there's a beautiful result from number theory that talks about what happens if you take this pattern mod 3<sup>k</sup> for some number k:</p> <blockquote> <p><strong>Theorem:</strong> Consider the sequence 3<sup>s</sup>, 3<sup>s</sup>·2, 3<sup>s</sup>·2<sup>2</sup>, 3<sup>s</sup>·2<sup>3</sup>, 3<sup>s</sup>·2<sup>4</sup>, etc. all modulo 3<sup>k</sup> for some k ≥ s. This sequence cycles through through every number between 1 and 3<sup>k</sup>, inclusive, that is divisible by 3<sup>s</sup> but not divisible by 3<sup>s+1</sup>.</p> </blockquote> <p>We can try this out on a few examples. Let's work modulo 27 = 3<sup>2</sup>. The theorem says that if we look at 3, 3 · 2, 3 · 4, etc. all modulo 27, then we should see all the numbers less than 27 that are divisible by 3 and not divisible by 9. Well, let'see what we get:</p> <ul> <li>3 · 2<sup>0</sup> = 3 · 1 = 3 = 3 mod 27</li> <li>3 · 2<sup>1</sup> = 3 · 2 = 6 = 6 mod 27</li> <li>3 · 2<sup>2</sup> = 3 · 4 = 12 = 12 mod 27</li> <li>3 · 2<sup>3</sup> = 3 · 8 = 24 = 24 mod 27</li> <li>3 · 2<sup>4</sup> = 3 · 16 = 48 = 21 mod 27</li> <li>3 · 2<sup>5</sup> = 3 · 32 = 96 = 15 mod 27</li> <li>3 · 2<sup>6</sup> = 3 · 64 = 192 = 3 mod 27</li> </ul> <p>We ended up seeing 3, 6, 12, 15, 21, and 24 (though not in that order), which are indeed all the numbers less than 27 that are divisible by 3 but not divisible by 9.</p> <p>We can also try this working mod 27 and considering 1, 2, 2<sup>2</sup>, 2<sup>3</sup>, 2<sup>4</sup> mod 27, and we should see all the numbers less than 27 that are divisible by 1 and not divisible by 3. In other words, this should give back all the numbers less than 27 that aren't divisible by 3. Let's see if that's true:</p> <ul> <li>2<sup>0</sup> = 1 = 1 mod 27</li> <li>2<sup>1</sup> = 2 = 2 mod 27</li> <li>2<sup>2</sup> = 4 = 4 mod 27</li> <li>2<sup>3</sup> = 8 = 8 mod 27</li> <li>2<sup>4</sup> = 16 = 16 mod 27</li> <li>2<sup>5</sup> = 32 = 5 mod 27</li> <li>2<sup>6</sup> = 64 = 10 mod 27</li> <li>2<sup>7</sup> = 128 = 20 mod 27</li> <li>2<sup>8</sup> = 256 = 13 mod 27</li> <li>2<sup>9</sup> = 512 = 26 mod 27</li> <li>2<sup>10</sup> = 1024 = 25 mod 27</li> <li>2<sup>11</sup> = 2048 = 23 mod 27</li> <li>2<sup>12</sup> = 4096 = 19 mod 27</li> <li>2<sup>13</sup> = 8192 = 11 mod 27</li> <li>2<sup>14</sup> = 16384 = 22 mod 27</li> <li>2<sup>15</sup> = 32768 = 17 mod 27</li> <li>2<sup>16</sup> = 65536 = 7 mod 27</li> <li>2<sup>17</sup> = 131072 = 14 mod 27</li> <li>2<sup>18</sup> = 262144 = 1 mod 27</li> </ul> <p>Sorting these, we got back the numbers 1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26 (though not in that order). These are <em>exactly</em> the numbers between 1 and 26 that aren't multiples of three!</p> <p>This theorem is crucial to the algorithm for the following reason: if 2n+1 = 3<sup>k</sup> for some number k, then if we process the cycle containing 1, it will properly shuffle all numbers that aren't multiples of three. If we then start the cycle at 3, it will properly shuffle all numbers that are divisible by 3 but not by 9. If we then start the cycle at 9, it will properly shuffle all numbers that are divisible by 9 but not by 27. More generally, if we use the cycle shuffle algorithm on the numbers 1, 3, 9, 27, 81, etc., then we will properly reposition all the elements in the array exactly once and will not have to worry that we missed anything.</p> <p>So how does this connect to 3<sup>k</sup> + 1? Well, we need to have that 2n + 1 = 3<sup>k</sup>, so we need to have that 2n = 3<sup>k</sup> - 1. But remember - we dropped the very first and very last element of the array when we did this! Adding those back in tells us that we need blocks of size <strong>3<sup>k</sup> + 1</strong> for this procedure to work correctly. If the blocks are this size, then we know <em>for certain</em> that the cycle decomposition will consist of a cycle containing 1, a nonoverlapping cycle containing 3, a nonoverlapping cycle containing 9, etc. and that these cycles will contain all the elements of the array. Consequently, we can just start cycling 1, 3, 9, 27, etc. and be <em>absolutely guaranteed</em> that everything gets shuffled around correctly. That's amazing!</p> <p>And why is this theorem true? It turns out that a number k for which 1, k, k<sup>2</sup>, k<sup>3</sup>, etc. mod p<sup>n</sup> that cycles through all the numbers that aren't multiples of p (assuming p is prime) is called a <a href="https://en.wikipedia.org/wiki/Cycle_decomposition" rel="noreferrer">primitive root</a> of the number p<sup>n</sup>. There's a theorem that says that 2 is a primitive root of 3<sup>k</sup> for all numbers k, which is why this trick works. If I have time, I'd like to come back and edit this answer to include a proof of this result, though unfortunately my number theory isn't at a level where I know how to do this.</p> <h2>Summary</h2> <p>This problem was tons of fun to work on. It involves cute tricks with dividing by two modulo an odd numbers, cycle decompositions, primitive roots, and powers of three. I'm indebted to <a href="http://arxiv.org/pdf/0805.1598.pdf" rel="noreferrer">this arXiv paper</a> which described a similar (though quite different) algorithm and gave me a sense for the key trick behind the technique, which then let me work out the details for the algorithm you described.</p> <p>Hope this helps!</p>
2015-07-02 19:35:54.387000+00:00
2020-01-19 17:19:21.907000+00:00
2020-06-20 09:12:55.060000+00:00
null
22,424,985
<p>The <a href="http://www.geeksforgeeks.org/an-in-place-algorithm-for-string-transformation/" rel="noreferrer">cycle leader iteration algorithm</a> is an algorithm for shuffling an array by moving all even-numbered entries to the front and all odd-numbered entries to the back while preserving their relative order. For example, given this input:</p> <pre><code>a 1 b 2 c 3 d 4 e 5 </code></pre> <p>the output would be</p> <pre><code>a b c d e 1 2 3 4 5 </code></pre> <p>This algorithm runs in O(n) time and uses only O(1) space.</p> <p>One unusual detail of the algorithm is that it works by splitting the array up into blocks of size 3<sup>k</sup>+1. Apparently this is critical for the algorithm to work correctly, but I have no idea why this is.</p> <p>Why is the choice of 3<sup>k</sup> + 1 necessary in the algorithm?</p> <p>Thanks!</p>
2014-03-15 14:21:36.753000+00:00
2020-01-19 17:19:21.907000+00:00
2015-07-02 19:37:53.570000+00:00
arrays|algorithm|math|permutation|number-theory
['https://en.wikipedia.org/wiki/Primitive_root_modulo_n', 'https://en.wikipedia.org/wiki/Cycle_decomposition', 'https://en.wikipedia.org/wiki/Primitive_root_modulo_n', 'https://en.wikipedia.org/wiki/Cycle_decomposition', 'https://en.wikipedia.org/wiki/Cycle_decomposition', 'http://arxiv.org/pdf/0805.1598.pdf']
6
63,145,320
<p>Let me talk about random integer generating algorithms that are &quot;optimal&quot; in terms of the number of random bits it uses on average. In the rest of this post, we will assume we have a &quot;true&quot; random generator that can produce unbiased and independent random bits. (Here, a random &quot;byte&quot; will be a block of 8 random bits.)</p> <p>In 1976, D. E. Knuth and A. C. Yao showed that any algorithm that produces random integers with a given probability, using only random bits, can be represented as a binary tree, where random bits indicate which way to traverse the tree and each leaf (endpoint) corresponds to an outcome. Knuth and Yao showed that any <em>optimal</em> binary tree algorithm for generating integers in <code>[0, n)</code> uniformly, will need <strong>at least <code>log2(n)</code> and at most <code>log2(n) + 2</code> bits on average</strong>. (Thus, even an <em>optimal</em> algorithm has a chance of &quot;wasting&quot; bits. And thus, they have to be &quot;inelegant&quot; in this sense you give.) See below for examples of optimal algorithms.</p> <p>However, any <em>optimal</em> integer generator that is also <em>unbiased</em> will, in general, run forever in the worst case, as also shown by Knuth and Yao. Going back to the binary tree, each one of the n outcomes labels leaves in the binary tree so that each integer in [0, n) can occur with probability 1/n. But if 1/n has a non-terminating binary expansion (which will be the case if n is not a power of 2), this binary tree will necessarily either—</p> <ul> <li>Have an &quot;infinite&quot; depth, or</li> <li>include &quot;rejection&quot; leaves at the end of the tree,</li> </ul> <p>And in either case, the algorithm will run forever in the worst case, even if it uses very few random bits on average. (On the other hand, when n is a power of 2, the optimal binary tree will have no rejection nodes and require exactly n bits before returning an outcome, so that no bits will be &quot;wasted&quot;.) The Fast Dice Roller is an example of an algorithm that uses &quot;rejection&quot; events to ensure it's unbiased; see the comment in the code below.</p> <p>Thus, in general, <strong>a random integer generator can be <em>either</em> unbiased <em>or</em> constant-time (or even neither), but not both.</strong> And the binary tree concept shows that there is no way in general to &quot;fix&quot; the worst case of an indefinite running time without introducing bias. For instance, modulo reductions (e.g., <code>rand() % n</code>) are equivalent to a binary tree in which rejection leaves are replaced with labeled outcomes — but since there are more possible outcomes than rejection leaves, only some of the outcomes can take the place of the rejection leaves, introducing bias. The same kind of binary tree — and the same kind of bias — results if you stop rejecting after a set number of iterations. (However, this bias may be negligible depending on the application. There are also security aspects to random integer generation, which are too complicated to discuss in this answer.)</p> <h3>Fast Dice Roller Implementation</h3> <p>There are many examples of <em>optimal</em> algorithms in the sense given earlier. One of them is the <a href="https://arxiv.org/abs/1304.1916" rel="nofollow noreferrer">Fast Dice Roller</a> by J. Lumbroso (2013) (implemented below), and perhaps other examples are the algorithm given as an <a href="https://stackoverflow.com/a/10481147/815724">answer to a similar <em>Stack Overflow</em> question</a> and the algorithm given in the <a href="http://mathforum.org/library/drmath/view/65653.html" rel="nofollow noreferrer">Math Forum</a> in 2004. On the other hand, all the algorithms <a href="https://www.pcg-random.org/posts/bounded-rands.html" rel="nofollow noreferrer">surveyed by M. O'Neill</a> are not optimal, since they rely on generating blocks of random bits at a time. See also my note on <a href="https://peteroupc.github.io/randomfunc.html#RNDINT_Random_Integers_in_0_N" rel="nofollow noreferrer">integer generating algorithms</a>.</p> <p>The following is a JavaScript implementation of the Fast Dice Roller. Note that it uses rejection events and a loop to ensure it's unbiased. <code>nextBit()</code> is a method that produces independent unbiased random bits (e.g., <code>Math.random()&lt;0.5 ? 1 : 0</code>, which isn't necessarily efficient in terms of random bits ultimately relied on in JavaScript).</p> <pre class="lang-js prettyprint-override"><code>function randomInt(minInclusive, maxExclusive) { var maxInclusive = (maxExclusive - minInclusive) - 1 var x = 1 var y = 0 while(true) { x = x * 2 var randomBit = nextBit() y = y * 2 + randomBit if(x &gt; maxInclusive) { if (y &lt;= maxInclusive) { return y + minInclusive } // Rejection x = x - maxInclusive - 1 y = y - maxInclusive - 1 } } } </code></pre> <p>The following version returns a BigInt, an arbitrary-precision integer supported in recent versions of JavaScript:</p> <pre class="lang-js prettyprint-override"><code>function randomInt(minInclusive, maxExclusive) { minInclusive=BigInt(minInclusive) maxExclusive=BigInt(maxExclusive) var maxInclusive = (maxExclusive - minInclusive) - BigInt(1) var x = BigInt(1) var y = BigInt(0) while(true) { x = x * BigInt(2) var randomBit = BigInt(Math.random()&lt;0.5 ? 1 : 0) y = y * BigInt(2) + randomBit if(x &gt; maxInclusive) { if (y &lt;= maxInclusive) { return y + minInclusive } // Rejection x = x - maxInclusive - BigInt(1) y = y - maxInclusive - BigInt(1) } } } </code></pre> <h3>Reducing Bit Waste</h3> <p>Recall that &quot;optimal&quot; integer generators, such as the Fast Dice Roller above, use on average at least <code>log2(n)</code> bits (the lower bound), or come within 2 bits of this lower bound on average. There are various techniques that can be used to bring an algorithm (even a less than optimal one) closer to this theoretical lower bound, including batching and randomness extraction. These are discussed in:</p> <ul> <li>The Fast Dice Roller paper itself, see section 3.1 (batching).</li> <li>The paper &quot;<a href="https://arxiv.org/abs/1502.02539" rel="nofollow noreferrer">Random variate generation using only finitely many unbiased, independently and identically distributed random bits</a>&quot; by Devroye and Gravel, section 2.3 (randomness extraction).</li> <li>The Math Forum page given above (recycling).</li> </ul> <p>In your example, one way to reduce bit waste would involve &quot;batching&quot;: to generate four random digits from 0 through 9, simply generate a random integer in [0, 9999], and break the resulting number into digits. Generating eight random digits instead would involve the interval [0, 99999999].</p>
2020-07-29 02:10:35.383000+00:00
2022-01-12 13:41:55.390000+00:00
2022-01-12 13:41:55.390000+00:00
null
63,145,042
<p>Most (if not all) CSPRNG functions available out there provide us byte sequences as result (eg. <code>getrandom</code>, <code>CryptGenRandom</code>, <code>BCryptGenRandom</code>, <code>RNGCryptoServiceProvider</code>, <code>SecureRandom</code>, <code>CRYPT_GEN_RANDOM</code> etc).</p> <p>However, depending where we are supposed to use this random sequence our charset may be different (suppose you need only digits), and we may need to convert the byte sequence to fit our constraint.</p> <p>A naive way to solve the problem is to convert each byte to its decimal representation and concatenate all numbers (the programming language doesn't matter):</p> <pre><code>randbytes = AnyRandomGenerator() sequence = &quot;&quot; for byte in randbytes: sequence = sequence + byte.ToInt().ToStr() return sequence </code></pre> <p>This way, the random sequence <code>0xFE501000</code> would become the sequence <code>25480100</code>.</p> <p>It works, however, there is a big mistake in this approach: the probability of the first number to be &quot;1&quot; or &quot;2&quot; is significantly bigger than any other number (because bytes ranges from 0 to 255 and not from 0 to 999).</p> <p>To solve this, an improvement would be to MOD 10 each digit:</p> <pre><code>randbytes = AnyRandomGenerator() sequence = &quot;&quot; for byte in randbytes: sequence = sequence + (byte.ToInt() MOD 10).ToStr() return sequence </code></pre> <p>However, since MAX_BYTE = 255 is not a multiple of 10, this leads to small unfair distribution for numbers greather than five.</p> <p>In an <a href="https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.rngcryptoserviceprovider" rel="nofollow noreferrer">example made by Microsoft for .NET</a>, they avoid this problem considering some random numbers &quot;unfair&quot;. When an unfair number is generated, it is discarded and a new one is generated. This solves the problem, but I must say it isn't very elegant (it &quot;waste&quot; numbers :P).</p> <p>Is there a best/fast way to achieve this conversion keeping the numbers uniformly distributed? Or the method used by Microsoft is the only way to go?</p> <p>(PS: Although my examples uses a 10-digit charset = [0-9], I'm asking about charsets of any size, like the Dice Roll charset = [0-5] in the Microsoft example)</p>
2020-07-29 01:32:03.210000+00:00
2022-01-12 13:41:55.390000+00:00
2020-07-29 02:11:21.067000+00:00
algorithm|random|cryptography
['https://arxiv.org/abs/1304.1916', 'https://stackoverflow.com/a/10481147/815724', 'http://mathforum.org/library/drmath/view/65653.html', 'https://www.pcg-random.org/posts/bounded-rands.html', 'https://peteroupc.github.io/randomfunc.html#RNDINT_Random_Integers_in_0_N', 'https://arxiv.org/abs/1502.02539']
6
37,674,680
<p>So, what it seems you need to do is get pyKalman rather than using the opencv one. From my quick search, all that is available from opencv is what you mention:</p> <pre><code>'KERNEL_SYMMETRICAL', 'KMEANS_PP_CENTERS', 'KMEANS_RANDOM_CENTERS', 'KMEANS_USE_INITIAL_LABELS', 'KNearest', 'KalmanFilter', 'KeyPoint', 'LEV_MARQ_CALC_J', 'LEV_MARQ_CHECK_ERR', 'LEV_MARQ_DONE', 'LEV_MARQ_STARTED', 'LMEDS', 'LUT', 'Laplacian', 'MAGIC_MASK', </code></pre> <p>You could also just implement your own defintion. </p> <p>Please do read these: <a href="http://filterpy.readthedocs.io/en/latest/kalman/KalmanFilter.html" rel="nofollow noreferrer">http://filterpy.readthedocs.io/en/latest/kalman/KalmanFilter.html</a> <a href="https://arxiv.org/ftp/arxiv/papers/1204/1204.0375.pdf" rel="nofollow noreferrer">https://arxiv.org/ftp/arxiv/papers/1204/1204.0375.pdf</a> <a href="https://stackoverflow.com/questions/29012038/is-there-any-example-of-cv2-kalmanfilter-implementation">Is there any example of cv2.KalmanFilter implementation?</a></p> <p>Sorry I couldn't get your answer all sorted out.</p> <p><strong>--EDIT--</strong></p> <p>According to the documentation you may use:</p> <p>cv2.KalmanFilter.correct(measurement) → retval</p> <pre><code>import numpy as np import cv2 import cv2.cv as cv kalman = cv2.KalmanFilter(4,2) X = np.array([[1,0,0,0],[0,1,0,0]],np.float32) Y=kalman.correct(X) </code></pre> <p>The first problem I notice is that after the first line where the Kalman filter is defined, the filter as such is not shown in my variable explorer. The numpy array does show but it makes me wonder about the Kalman. </p> <p>Further when I use Y=Kalman.correct(X) there is a problem with dimensions, but at least it is one step closer. I also find it odd that the documentation says I can define a CV_32F or CV_64F, as type in the KalmanFilter, but I just can't get it to work!!!</p> <p>source:</p> <p><a href="http://docs.opencv.org/2.4/modules/video/doc/motion_analysis_and_object_tracking.html?highlight=kalman%20python#cv.CreateKalman" rel="nofollow noreferrer">http://docs.opencv.org/2.4/modules/video/doc/motion_analysis_and_object_tracking.html?highlight=kalman%20python#cv.CreateKalman</a></p>
2016-06-07 08:49:44.780000+00:00
2016-06-07 09:59:55.977000+00:00
2017-05-23 11:52:34.227000+00:00
null
37,674,234
<p>I have OpenCv 2.4.8 installed and, for the most part, working on Python 2.7 (I'm on Ubuntu).</p> <p>Everything seems to be working fine with OpenCv. However, the following code</p> <pre><code>import numpy as np kalman = cv2.KalmanFilter(4,2) kalman.measurementMatrix = np.array([[1,0,0,0],[0,1,0,0]],np.float32) </code></pre> <p>gives me this error:</p> <blockquote> <p>AttributeError: 'cv2.KalmanFilter' object has no attribute 'measurementMatrix'</p> </blockquote> <p>Indeed, <code>dir(kalman)</code> shows that only <code>correct()</code> and <code>predict()</code> are the only functions or variables that aren't built-in. No <code>transitionMatrix</code>, <code>processNoiseCov</code> or <code>measurementNoiseCov</code> are present.</p> <p>Does anyone know what the problem here could be?</p>
2016-06-07 08:28:15.260000+00:00
2016-06-07 09:59:55.977000+00:00
null
python|opencv|kalman-filter
['http://filterpy.readthedocs.io/en/latest/kalman/KalmanFilter.html', 'https://arxiv.org/ftp/arxiv/papers/1204/1204.0375.pdf', 'https://stackoverflow.com/questions/29012038/is-there-any-example-of-cv2-kalmanfilter-implementation', 'http://docs.opencv.org/2.4/modules/video/doc/motion_analysis_and_object_tracking.html?highlight=kalman%20python#cv.CreateKalman']
4
44,116,163
<p>The short answer: for a nxn grid, the complexity is at least exponential n.</p> <p>A junction tree is created from the induced graph of the MRF, which depends on the elimination order (which variables you eliminate first to calculate a marginal). The elimination cost is exponential in the size of the largest clique in the induced graph. See <a href="https://arxiv.org/pdf/1506.08544.pdf" rel="nofollow noreferrer">this</a> paper for details.</p> <p>So even though we can use exact inference on the junction tree, the complexity would be exponential in size of the largest clique in the induced graph of the elimination order that was used.</p> <p>The best possible elimination order will yield a largest clique size equal to the tree width, which is n for a nxn grid. But there are no efficient algorithms for finding it.</p>
2017-05-22 14:57:49.960000+00:00
2017-05-22 14:57:49.960000+00:00
null
null
41,763,327
<p>The question is as written in the title</p> <p><a href="https://i.stack.imgur.com/o9MZd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o9MZd.png" alt="enter image description here"></a></p> <p>There is a 3x3 grid graph at the above image. We can convert it into junction tree. Then it is possible to use message-passing(product-sum algorithm) for the inference(estimating likelihood/posterior etc). So I wonder why the exact inference in the grid graph is so hard?</p> <p>Is it impossible to find such a junction tree when the grid goes larger?</p>
2017-01-20 12:07:31.967000+00:00
2017-06-19 03:28:07.573000+00:00
2017-06-19 03:28:07.573000+00:00
machine-learning|message-passing|inference|markov-random-fields
['https://arxiv.org/pdf/1506.08544.pdf']
1
39,599,388
<p>To train a model I would start by concatenating consecutive sequences of messages. What I would do is, using the timestamps, concatenate the messages without any message in between from the other entity.</p> <p>For instance:</p> <pre><code>Hello I have a problem I cannot install software X Hi What error do you get? </code></pre> <p>would be:</p> <pre><code>Hello I have a problem I cannot install software X Hi What error do you get? </code></pre> <p>Then I would train a model with sentences in that format. I would do that because I am assuming that the conversations have a "single topic" all the time between interactions from the entities. And in that scenario suggesting a single message <code>Hi What error do you get?</code> would be totally fine.</p> <p>Also, take a look at the data. If the questions from the users are usually single-sentenced (as in the examples) sentence detection could help a lot. In that case I would apply sentence detection on the concatenated strings (<code>nltk</code> could be an option) and use only single-sentenced questions for training. That way you can avoid the out-of-sync problem when training the model at the price of reducing the size of the dataset.</p> <p>On the other hand, I would <em>really</em> consider to start with a very simple method. For example you could score questions by tf-idf and, to get a suggestion, you can take the most similar question in your dataset wrt some metric (e.g. cosine similarity) and suggest the answer for that question. That will perform very bad in sentences with context information (e.g. <code>how do you do it?</code>) but can perform well in sentences like <code>where are you based?</code>.</p> <p>My last suggestion is because <a href="https://arxiv.org/abs/1509.01626" rel="nofollow">traditional methods perform even better than complex NN methods when the dataset is small</a>. How big is your dataset?</p> <p><em>How</em> you train a NN method is also crucial, there are a lot of hyper-parameters, and tuning them properly can be difficult, that's why having a baseline with a simple method can help you a lot to check how well you are doing. In this other <a href="http://arxiv.org/abs/1607.05368" rel="nofollow">paper</a> they compare the different hyper-parameters for doc2vec, maybe you find it useful.</p> <p><strong>Edit:</strong> a completely different option would be to train a model to "link" questions with answers. But for that you should manually tag each question with the corresponding answer and then train a supervised learning model on that data. That could potentially generalize better but with the added effort of manually labelling the sentences and still it doesn't look like an easy problem to me.</p>
2016-09-20 16:30:32.383000+00:00
2016-09-20 19:30:24.310000+00:00
2016-09-20 19:30:24.310000+00:00
null
39,489,933
<p>I'm using Gensim Doc2Vec model, trying to cluster portions of a customer support conversations. My goal is to give the support team an auto response suggestions.</p> <p><strong>Figure 1:</strong> shows a sample conversations where the user question is answered in the next conversation line, making it easy to extract the data:</p> <p><a href="https://i.stack.imgur.com/N4ri4.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N4ri4.gif" alt="Figure 1"></a> </p> <p><sup>during the conversation <strong>"hello"</strong> and <strong>"Our offices are located in NYC"</strong> should be suggested</sup></p> <hr> <p><strong>Figure 2:</strong> describes a conversation where the questions and answers are not in sync</p> <p><a href="https://i.stack.imgur.com/oHUQu.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oHUQu.gif" alt="Figure 2"></a></p> <p><sup>during the conversation <strong>"hello"</strong> and <strong>"Our offices are located in NYC"</strong> should be suggested</sup></p> <hr> <p><strong>Figure 3:</strong> describes a conversation where the context for the answer is built over time, and for classification purpose (I'm assuming) some of the lines are redundant.</p> <p><a href="https://i.stack.imgur.com/muf6Y.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/muf6Y.gif" alt="Figure 3"></a></p> <p><sup>during the conversation <strong>"here is a link for the free trial account"</strong> should be suggested</sup></p> <hr> <p>I have the following data per conversation line (simplified):<br> who wrote the line (user or agent), text, time stamp</p> <p>I'm using the following code to train my model:</p> <pre><code>from gensim.models import Doc2Vec from gensim.models.doc2vec import TaggedLineDocument import datetime print('Creating documents',datetime.datetime.now().time()) context = TaggedLineDocument('./test_data/context.csv') print('Building model',datetime.datetime.now().time()) model = Doc2Vec(context,size = 200, window = 10, min_count = 10, workers=4) print('Training...',datetime.datetime.now().time()) for epoch in range(10): print('Run number :',epoch) model.train(context) model.save('./test_data/model') </code></pre> <p><strong>Q</strong>: How should I structure my training data and what heuristics could be applied in order to extract it from the raw data?</p>
2016-09-14 12:00:31.297000+00:00
2016-09-20 19:30:24.310000+00:00
2016-09-15 20:44:37.437000+00:00
python|text-mining|doc2vec|gensym
['https://arxiv.org/abs/1509.01626', 'http://arxiv.org/abs/1607.05368']
2
6,637,208
<p>The following is accurate if the points are within 10000 km of each other and if the earth is assumed to be spherical. Use d2 if you just want to compare distances. distance is the approximate distance in km.</p> <pre><code>deg = pi/180; phi1 = lat1 * deg; phi2 = lat2 * deg; lam12 = (lon2 - lon1) * deg; d2 = ( cos(phi1) * sin(phi2) - sin(phi1) * cos(phi2) * cos(lam12) )^2 + ( cos(phi2) * sin(lam12) )^2; a = 6371.009; // kilometers distance = a * asin( sqrt( d2 ) ); </code></pre> <p>For more accuracy you need to treat the earth as an ellipsoid; see my online geodesic calculator at <a href="http://geographiclib.sf.net/cgi-bin/Geod" rel="nofollow">http://geographiclib.sf.net/cgi-bin/Geod</a> and the write-up at <a href="http://arxiv.org/abs/1102.1215" rel="nofollow">http://arxiv.org/abs/1102.1215</a>.</p>
2011-07-09 20:10:46.073000+00:00
2011-07-10 12:57:59.933000+00:00
2011-07-10 12:57:59.933000+00:00
null
6,633,047
<p>I'm working on a tool that will find the closest latitude/longitude position from a list compared to the users current location. The list will be pretty long, and it will be running on a smart phone, so I'd like to make the calculations as simple and speedy as possible. From the threads I've read, calculating a fairly accurate distance between two latitude/longitude locations is a bit complicated, and I'm worried about speed. My question is, can I use something similar to the following to get a reasonable result for closest list position and use that?</p> <pre><code>$distance = sqrt((($firstLongitude-$secondLongitude)*($firstLongitude-$secondLongitude))+(($firstlLatitude-$secondLatitude)*($firstLatitude-$secondLatitude))); </code></pre> <p>I know the example is in PHP, but the logic should be evident. So my question is, will using the above logic to determine the closest location to the user from a list of lat/long locations give me correct results, or is there a potential issue I'm missing? </p> <p>This app would only run for locations in the USA, if that makes any difference.</p> <p>NOTE: I was also wondering if I could further simplify this and drop the sqrt part since I just want to see which is closer, and not how close it is.</p>
2011-07-09 05:50:57.613000+00:00
2011-07-10 13:08:49.750000+00:00
2011-07-10 13:08:49.750000+00:00
distance|latitude-longitude
['http://geographiclib.sf.net/cgi-bin/Geod', 'http://arxiv.org/abs/1102.1215']
2
61,465,173
<p>My notes can be summarized in the following points:</p> <ul> <li><p>First of all, I don't think passing a list of keywords would be any help to the <code>gensim.models.Word2Vec</code> model. As you said, the reason behind using word2vec is to somehow get a feeling of the surrounding words; How can it do this job with a random list of keywords?</p></li> <li><p>Second of all, the vocabulary should be the same words in the documents. So, your vocabulary should have <code>very</code> in it.</p></li> <li><p>The more data you use, the more useful the model becomes. So, 2500 tokens aren't big enough. For example, the first version of word2vec was the <a href="https://arxiv.org/pdf/1310.4546.pdf" rel="nofollow noreferrer">Skipgram model</a> published in 2014/2015 by Google. The vocabulary that Google used was about 692,000 words.</p></li> <li><p>There are two versions of word2vec that can be used: "Skipgram" and "Continuous Bag of Words (CBOW)". Both depend on the surrounding words. You can check my answer <a href="https://stackoverflow.com/a/57508776/5612363">here</a> for more information on how each one of them works.</p></li> </ul>
2020-04-27 17:51:50.837000+00:00
2020-04-27 17:51:50.837000+00:00
null
null
61,460,683
<p>I would like to train a <code>word2vec</code> model using what is an unordered list of keywords and categories for each document. Therefore my vocabulary is quite small around 2.5k tokens.</p> <p>Would the performance be improved if at the training step, I used actual sentences from the document?</p> <p>From example:</p> <pre><code>doc_keywords = ['beach', 'holiday', 'warm'] doc_body = 'Going on a beach holiday it can be very warm' </code></pre> <p>If there is a benefit to using the full documents, could someone also explain why this is the case?</p> <p>Since the model predicts the next word in a document, what would be the benefit to it learning <code>very -&gt; warm</code> as two words which often come together, given that <code>very</code> is not in my vocabulary.</p>
2020-04-27 14:03:20.053000+00:00
2020-04-27 18:18:40.407000+00:00
null
machine-learning|nlp|gensim|word2vec|doc2vec
['https://arxiv.org/pdf/1310.4546.pdf', 'https://stackoverflow.com/a/57508776/5612363']
2
28,201,909
<p>There are many measures to compare top k (ranked) lists. Some very trivial to compute making several simplifying assumptions, others not so trivial but are more rigorous in their evaluation of rank similarity between lists. A recent paper I came across that deals with this problem in a statistically meaningful way, using concepts from information theory and data compression: <a href="http://arxiv.org/abs/1310.0110" rel="nofollow">http://arxiv.org/abs/1310.0110</a></p>
2015-01-28 20:35:10.490000+00:00
2015-01-28 20:35:10.490000+00:00
null
null
13,574,406
<p>I have two lists of ranked items. Each item has an rank and an associated score. The score has decided the rank. The two lists can contains (and usually do) different items, that is their intersection can be empty. I need measures to compare such rankings. Are there well-known algorithms (in literature or real-world systems) to do so ? The measure of distance should take into account the scores as well as the ranks of the items. </p>
2012-11-26 22:40:23.673000+00:00
2018-04-11 11:02:31.300000+00:00
null
list|compare|ranking
['http://arxiv.org/abs/1310.0110']
1
61,731,613
<p>I am not sure if I understand your question correctly, but I can try to provide some details about the C++ memory model.</p> <p>The default memory order of all operations on C++ atomics is <em>sequential consistent</em>. Formally this means that there is a single total order (<em>S</em>) of all sequentially consistent operations (regardless by which thread the are executed). So if a thread <em>A</em> performs a seq-cst-store on some variable <em>X</em>, and thread <em>B</em> performs a seq-cst-load on <em>X</em>, and the store is ordered before the load in <em>S</em>, then it is guaranteed that <em>B</em> sees the value stored by <em>A</em> (or some newer value).</p> <p>However, once you use more relaxed memory orderings for your operations you lose this guarantee, because these more relaxed atomic operations are generally <em>unordered</em>. However, you can introduce orderings by means of a <em>happens-before relation</em> between certain operations. E.g., an acquire-load that sees the value written by a release-store <em>synchronizes-with</em> that store, thereby establishing a happens-before relation.</p> <p>The C++ memory model is certainly one of the more complex aspects of the language and can not be thoroughly explained in a simple answer. For more details I recommend further reading like this paper which I have co-authored: <a href="https://arxiv.org/abs/1803.04432" rel="nofollow noreferrer">Memory Models for C/C++ Programmers</a><br> It not only covers the C++ memory model, but also gives a brief overview over the memory models of x86 and ARM/Power, trying to explain why it is even <em>necessary</em> to have a memory model in the first place.</p>
2020-05-11 14:05:34.843000+00:00
2020-05-11 14:05:34.843000+00:00
null
null
61,686,778
<p>Reading about the C++ memory model and ordering directives raised me a questions - in the same process when a thread-shared atomic variable (eg. atomic) is set in one thread - and the ordering of the load is after the store - is it possible that the load is not seeing the stored value?</p> <p>Rephrased - is ordering a guarantee that a set atomic value is loaded as is, or there is a CPU/cache/etc abstraction that could still provide an older value?</p> <p>The reason of the questions is some literature talks about synchronization (apart from ordering) and the language they use is "as seen by another thread" - which makes me wonder if load is not a direct access to the memory location (which would not need any other synchronization than ordering).</p>
2020-05-08 19:35:45+00:00
2020-05-11 14:05:34.843000+00:00
null
c++|multithreading|memory-model
['https://arxiv.org/abs/1803.04432']
1
44,124,236
<p><strong><code>k</code> is the no. of classes</strong></p> <p>From Section 2.1 of <a href="https://arxiv.org/pdf/1607.01759v3.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1607.01759v3.pdf</a> </p> <blockquote> <p>More precisely, the computational complexity is O(kh) where k is the number of classes and h the dimension of the text representation.</p> </blockquote> <hr> <p><strong>When predicting classes in text classification</strong>, from the <a href="https://github.com/facebookresearch/fastText#text-classification" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>The argument k is optional, and is equal to 1 by default. In order to obtain the k most likely labels for a piece of text, use:</p> <p>$ ./fasttext predict model.bin test.txt k</p> </blockquote> <hr> <p><strong>When training the model</strong>, this is implicitly specified in the training data when performing supervised training with the <code>__label__*</code> tag. </p> <p>From the <a href="https://github.com/facebookresearch/fastText/blob/master/tutorials/supervised-learning.md#getting-and-preparing-the-data" rel="nofollow noreferrer">example tutorial</a>:</p> <pre><code>$ wget https://s3-us-west-1.amazonaws.com/fasttext-vectors/cooking.stackexchange.tar.gz &amp;&amp; tar xvzf cooking.stackexchange.tar.gz --2017-05-23 09:03:26-- https://s3-us-west-1.amazonaws.com/fasttext-vectors/cooking.stackexchange.tar.gz Resolving s3-us-west-1.amazonaws.com... 54.231.236.45 Connecting to s3-us-west-1.amazonaws.com|54.231.236.45|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 457609 (447K) [application/x-gzip] Saving to: ‘cooking.stackexchange.tar.gz.1’ cooking.stackexchange.tar.gz.1 100%[================================================================&gt;] 446.88K 385KB/s in 1.2s 2017-05-23 09:03:28 (385 KB/s) - ‘cooking.stackexchange.tar.gz.1’ saved [457609/457609] x cooking.stackexchange.id x cooking.stackexchange.txt x readme.txt $ cat readme.txt The data in this archive is derived from the user-contributed content on the Cooking Stack Exchange website (https://cooking.stackexchange.com/), used under CC-BY-SA 3.0 (http://creativecommons.org/licenses/by-sa/3.0/). The original data dump can be downloaded from: https://archive.org/download/stackexchange/cooking.stackexchange.com.7z and details about the dump obtained from: https://archive.org/details/stackexchange We distribute two files, under CC-BY-SA 3.0: - cooking.stackexchange.txt, which contains all question titles and their associated tags (one question per line, tags are prefixed by the string "__label__") ; - cooking.stackexchange.id, which contains the corresponding row IDs, from the original data dump. </code></pre>
2017-05-23 01:05:56.683000+00:00
2017-05-23 01:05:56.683000+00:00
null
null
44,115,625
<p>In the <a href="https://arxiv.org/pdf/1607.01759v3.pdf" rel="nofollow noreferrer">paper on fasttext</a> for supervised classification, the authors specified various quantities of hidden units by altering some parameter (h is the one on pages 3,4 - In table 1 you see "It has 10 hidden units and we evaluate it with and without bigrams.") But after reading <a href="https://github.com/facebookresearch/fastText/blob/master/README.md#full-documentation" rel="nofollow noreferrer">the documentation</a> it does not appear that there is a "hidden unit" parameter to alter. Is there a way to specify the number of hidden units? Or is this the same as specifying the -dim option? </p>
2017-05-22 14:33:55.893000+00:00
2017-05-23 16:38:43.250000+00:00
2017-05-23 16:38:43.250000+00:00
facebook|nlp|text-classification|fasttext
['https://arxiv.org/pdf/1607.01759v3.pdf', 'https://github.com/facebookresearch/fastText#text-classification', 'https://github.com/facebookresearch/fastText/blob/master/tutorials/supervised-learning.md#getting-and-preparing-the-data']
3
37,432,424
<p>It depends on the Optimizer you are using. Vanilla SGD needs (accepts) individual adaption of the learning rate. Some others do. Adadelta for example does not. (<a href="https://arxiv.org/abs/1212.5701" rel="nofollow" title="AdaDelta-Paper">https://arxiv.org/abs/1212.5701</a>)</p> <p>So this depends not so much on Tensorflow but rather on the mathematical background of the optimizer you are using.</p> <p>Furthermore: Yes, saving and restarting the training does not reset the learning rates, but continuous at the point saved.</p>
2016-05-25 09:05:18.253000+00:00
2016-05-25 09:05:18.253000+00:00
null
null
37,431,725
<p>From various examples of Tensorflow (translation, ptb) it seems like that you need to explicitly change learning rate when using GradientDescentOptimizer. But is it the case while using some more 'sophisticated' techniques like Adagrad, Adadelta etc. Also when we continue training the model from a saved instance, are the past values used by these optimizers saved in the model file ?</p>
2016-05-25 08:31:12.677000+00:00
2016-05-25 09:05:18.253000+00:00
null
optimization|tensorflow
['https://arxiv.org/abs/1212.5701']
1
41,366,833
<p>This is an open reasearch topic called Generative Adversarial Networks. An explanation of this can be found here: <a href="https://www.quora.com/What-are-Generative-Adversarial-Networks" rel="nofollow noreferrer">https://www.quora.com/What-are-Generative-Adversarial-Networks</a>. </p> <p>Example paper usage: <a href="https://arxiv.org/pdf/1612.07828v1.pdf?utm_campaign=Machine%2BLearning%2BWeekly&amp;utm_medium=web&amp;utm_source=Machine_Learning_Weekly_9" rel="nofollow noreferrer">https://arxiv.org/pdf/1612.07828v1.pdf?utm_campaign=Machine%2BLearning%2BWeekly&amp;utm_medium=web&amp;utm_source=Machine_Learning_Weekly_9</a>. </p> <p>Example youtube tutorial: <a href="https://www.youtube.com/watch?v=deyOX6Mt_As" rel="nofollow noreferrer">https://www.youtube.com/watch?v=deyOX6Mt_As</a>.</p>
2016-12-28 17:21:06.360000+00:00
2016-12-28 17:21:06.360000+00:00
null
null
41,356,180
<p>I know that deep learning is capable of many cool stuff to do with images. the question that i am facing is: is it possible to create a bitmap image of a large data for multiple class and feed it to a deep learning image processing machine, and when trained expect the machine to generate an image for the given class?</p> <p>for example predicting a sport match; giving an image of the statics of each game as input, and the class would be the name of two teams. so when I enter "New England Patriots - Seattle Seahawks" the AI generate an image that is the prediction of statics of the game.</p> <p>will doing so help prediction in anyway?</p>
2016-12-28 05:57:06.357000+00:00
2016-12-28 20:02:49.757000+00:00
null
image-processing|neural-network|artificial-intelligence|deep-learning|prediction
['https://www.quora.com/What-are-Generative-Adversarial-Networks', 'https://arxiv.org/pdf/1612.07828v1.pdf?utm_campaign=Machine%2BLearning%2BWeekly&utm_medium=web&utm_source=Machine_Learning_Weekly_9', 'https://www.youtube.com/watch?v=deyOX6Mt_As']
3
64,611,852
<p>There are many good generators with a small state: MRG32k3a, LFSR113, Chacha-8, Philox-32x4. Even Mixmax (with N=17) would be small by your standard (state of 17 doubles).</p> <p>TinyMT is also a possibility, although Vigna has shown that some of the bits are not always good (not sure if the not so great lower bits really matters in practice).</p> <p>I would be wary of xorshift based rngs, see the paper <a href="https://arxiv.org/abs/1908.10020" rel="nofollow noreferrer">Again, random numbers fall mainly in the planes: xorshift128+ generators</a> by Matsumoto for example. I am also dubious of PCG, if only for the colored table on frontpage of the website: it dumbs things down too much, does not present all the relevant generators, and is skewed towards PCG of course.</p>
2020-10-30 16:04:18.783000+00:00
2020-10-30 16:04:18.783000+00:00
null
null
29,615,188
<p>I need a C++11 random number generator which is "good enough" and which I can save and restore state in. <em>I want the saved state to be significantly smaller</em> than the 6.6kb or so which this code produces</p> <pre><code>std::mt19937 rng (1); std::ofstream save ("save.txt"); save &lt;&lt; rng; </code></pre> <p><a href="http://www.cplusplus.com/reference/random/mersenne_twister_engine/" rel="noreferrer">std::mersenne_twister_engine</a> has a large number of parameters. It's a bit scary.</p> <p>For my purposes, a period on the order of billions is sufficient. I've heard of TinyMT, that may be appropriate but can't see how to implement it as a template specialization.</p> <p>How should I choose the parameters? I suspect it will break badly if I merely reduce the "state size" parameter to a few words.</p> <p>I would consider using a different engine entirely but, apart from tolerating a moderate period, I don't want to sacrifice the quality of statistical randomness. Artefacts such as the below (for linear congruentals) are unacceptable.</p> <p><img src="https://i.stack.imgur.com/9NgZc.gif" alt="enter image description here"></p>
2015-04-13 21:11:48.027000+00:00
2020-10-30 16:04:18.783000+00:00
null
c++|c++11|random|stl|mersenne-twister
['https://arxiv.org/abs/1908.10020']
1
29,617,793
<p>If don't need a lot of numbers, any decent 64bit size RNG will be good. Out of top of my hat very good generator would be XorShift64*, paper <a href="http://arxiv.org/abs/1402.6246" rel="nofollow">http://arxiv.org/abs/1402.6246</a>, code <a href="https://github.com/Iwan-Zotow/xorshift64STAR" rel="nofollow">https://github.com/Iwan-Zotow/xorshift64STAR</a></p> <p>Another option to use is PCG, "Quadratisch. Praktisch. Gut.", paper and code at <a href="http://www.pcg-random.org/" rel="nofollow">http://www.pcg-random.org/</a></p> <p>They are both statistically better than MT, the only disadvantage being small(er) period, but it is ok with you as far as I can see</p>
2015-04-14 01:39:07.387000+00:00
2015-04-14 02:34:02.610000+00:00
2015-04-14 02:34:02.610000+00:00
null
29,615,188
<p>I need a C++11 random number generator which is "good enough" and which I can save and restore state in. <em>I want the saved state to be significantly smaller</em> than the 6.6kb or so which this code produces</p> <pre><code>std::mt19937 rng (1); std::ofstream save ("save.txt"); save &lt;&lt; rng; </code></pre> <p><a href="http://www.cplusplus.com/reference/random/mersenne_twister_engine/" rel="noreferrer">std::mersenne_twister_engine</a> has a large number of parameters. It's a bit scary.</p> <p>For my purposes, a period on the order of billions is sufficient. I've heard of TinyMT, that may be appropriate but can't see how to implement it as a template specialization.</p> <p>How should I choose the parameters? I suspect it will break badly if I merely reduce the "state size" parameter to a few words.</p> <p>I would consider using a different engine entirely but, apart from tolerating a moderate period, I don't want to sacrifice the quality of statistical randomness. Artefacts such as the below (for linear congruentals) are unacceptable.</p> <p><img src="https://i.stack.imgur.com/9NgZc.gif" alt="enter image description here"></p>
2015-04-13 21:11:48.027000+00:00
2020-10-30 16:04:18.783000+00:00
null
c++|c++11|random|stl|mersenne-twister
['http://arxiv.org/abs/1402.6246', 'https://github.com/Iwan-Zotow/xorshift64STAR', 'http://www.pcg-random.org/']
3
33,003,391
<p>Finding the perfect algorithm for playing any game is hard!</p> <p>Consider the game Connect 4. In 1988, Victor Allis proved that under perfect play conditions, white will always win (if a draw doesn't result). <a href="http://www.informatik.uni-trier.de/~fernau/DSL0607/Masterthesis-Viergewinnt.pdf">His thesis</a> is 91 pages long.</p> <p>The game snake, as I played it, involves multiple snakes as well as apples and other items that appear for limited amounts of time.</p> <p>Thanks to <a href="http://arxiv.org/abs/1201.4995">Giovanni Viglietta (2013)</a>, we know that collectible items and paths that can only be traversed a single time (you can't cross over yourself in snakes) are hallmarks of problems which are <a href="https://en.wikipedia.org/wiki/NP-hardness">NP-hard</a>. Viglietta uses his techniques to show that Boulder Dash, Deflektor, Lemmings, Lode Runner, Mindbender, Pac-Man, Pipe Mania, Prince of Persia, Puzzle Bobble 3, Skweek, Starcraft, and Tron are all hard (in some sense).</p> <p>I do not know if Snakes falls into this same category, but similarities in its structure (collectible items, temporarily one-time paths) suggest that it might. If so, then there is no efficient (in some sense) algorithm to guide the behaviour of a snake other than a brute-force approach which would be too slow for real-time play.</p> <p>Therefore, if a perfect algorithm is possible, you should expect the proof of this to be long and complicated. And you should get a Master's degree if you figure it out, which may take about two years.</p> <p>If the problem is NP-hard, then you're unlikely to like a perfect algorithm and you'll have to abandon your quest in favour of a heuristic or approximate algorithm.</p>
2015-10-07 22:20:11.140000+00:00
2015-10-07 22:20:11.140000+00:00
null
null
32,999,136
<p>Before reading this question, please note that I use the term AI to describe an algorithm that doesn't learn from it's mistakes, just an algorithm that plays a game in an efficiently and smart way.</p> <p>After seeing <a href="https://www.youtube.com/watch?v=kTIPpbIbkos" rel="nofollow">this</a> video a while ago, I decided to make my own snake AI. You can find it <a href="https://github.com/loovjo/Snake" rel="nofollow">here</a> (it is a couple of files, and that's why I don't include them here). This AI was far from perfect and now I wonder what the perfect AI algorithm is for the Snake game. Unlike my version, the original version of Snake doesn't contain walls, but it would be good if your AI algorithm could handle it. Your algorithm has to support multiple sizes of the board, and the food is placed out randomly. With perfect AI, I mean an AI that would collect all the cherries/food without dying, not one that would stay alive for as long enough.</p>
2015-10-07 17:50:44.510000+00:00
2021-02-23 08:55:50.977000+00:00
null
algorithm
['http://www.informatik.uni-trier.de/~fernau/DSL0607/Masterthesis-Viergewinnt.pdf', 'http://arxiv.org/abs/1201.4995', 'https://en.wikipedia.org/wiki/NP-hardness']
3
49,809,638
<p>I wrote my masters thesis about the topic:</p> <blockquote> <p>Thoma, Martin. "<a href="https://arxiv.org/pdf/1707.09725.pdf" rel="nofollow noreferrer">Analysis and Optimization of Convolutional Neural Network Architectures</a>." arXiv preprint arXiv:1707.09725 (2017).</p> </blockquote> <p>Long story short: There are a couple of techniques for analysis (chapter 2.5) and algorithms that learn topoligies (chapter 3), but in practice it is mostly trial and error / gut feeling.</p>
2018-04-13 05:03:57.167000+00:00
2018-04-13 05:03:57.167000+00:00
null
null
49,784,827
<p>I have finished two neural network courses and done loads of reading on the subject. I am comfortable with Tensorflow and Keras and building advanced neural networks (multiple inputs, large data, special layers...). I also have a fairly deep understanding of the underlying mathematics.</p> <p>My problem is that I know how to build neural networks but don't know the process by which an "expert" would create one for a specific application.</p> <p>I can:</p> <ul> <li>Collect loads of data and clean it up.</li> <li>Train the neural network.</li> <li>Fine tune hyper parameters.</li> <li>Export it for actual applications.</li> </ul> <p>What I am missing is how to come up with the layers in the neural network (how wide, what kind...). I know it is somewhat trial and error and looking at what has worked for others. But there must be a process that people can use to come up with architectures* that actually work very well. For example state of the art neural networks.</p> <p>I am looking for a free resource that would help me understand this process of creating a very good architecture*.</p> <p>*by architecture I mean the different layers that make up the network and their properties</p>
2018-04-11 21:37:41.227000+00:00
2018-04-13 05:03:57.167000+00:00
null
neural-network|artificial-intelligence
['https://arxiv.org/pdf/1707.09725.pdf']
1
46,415,603
<p><strong>Simhash</strong> is faster (very fast) and typically requires less storage, but imposes a strict limitation on how dissimilar two documents can be and still be detected as duplicates. If you are using a 64-bit simhash (a common choice), and depending on how many permuted tables you are capable of storing, you might be limited to hamming distances of as low as 3 or possibly as high as 6 or 7. Those are small hamming distances! You'll be limited to detecting documents that are mostly identical, and even then you may need to do some careful tuning of what features you choose to go into the simhash and what weightings you give to them.</p> <p>The generation of simhashes is patented by google, though in practice they seem to allow at least non-commercial use.</p> <p><strong>Minhash</strong> uses more memory, since you'd be typically storing 50-400 hashes per document, and it's not as CPU-efficient as simhash, but it allows you to find quite distant similarities, e.g. as low as 5% estimated similarity, if you want. It's also a bit easier to understand than simhash, particularly in terms of how the tables work. It's quite straightforward to implement, typically using shingling, and doesn't need a lot of tuning to get good results. It's not (to my knowledge) patented.</p> <p>If you're dealing with big data, the most CPU-intensive part of the minhash approach will likely be <em>after</em> you've generated the minhashes for your document, when you're hunting through your table to find other documents that share some of its hashes. There may be tens or hundreds of thousands of documents that share at least one hash with it, and you've got to weed through all of these to find those few that share e.g. a minimum of half its hashes. Simhash is a lot quicker here.</p> <p>As Otmar points out in his comment below, there are optimizations of minhash that allow you to achieve the same precision on your similarity estimates with fewer hashes per document. This can substantially reduce the amount of weeding you have to do.</p> <p><em>Edit:</em></p> <p>I have now tried <a href="https://arxiv.org/pdf/1706.05698.pdf" rel="noreferrer"><strong>superminhash</strong></a>. It's fairly fast, though my implementation of minhash <a href="https://stackoverflow.com/questions/19701052/how-many-hash-functions-are-required-in-a-minhash-algorithm">using a single hash function plus bit-transformations to produce all the other hashes</a> was faster for my purposes. It offers more accurate jaccard estimates, about 15% better under some situations I tested (though almost no difference under others). This should mean you need about a third fewer hashes to achieve the <em>same</em> accuracy. Storing fewer hashes in your table means less "weeding" is needed to identify near duplicates, which delivers a significant speed-up. I'm not aware of any patent on superminhash. Thanks Otmar!</p>
2017-09-25 23:27:57.107000+00:00
2018-02-09 04:18:20.687000+00:00
2018-02-09 04:18:20.687000+00:00
null
27,712,472
<p>I'm familiar with the LSH (Locality Sensitive Hashing) techniques of SimHash and MinHash. SimHash uses cosine similarity over real-valued data. MinHash calculates resemblance similarity over binary vectors. But I can't decide which one would be better to use.</p> <p>I am creating a backend system for a website to find near duplicates of semi-structured text data. For example, each record will have a title, location, and a brief text description (&lt;500 words).</p> <p>Specific language implementation aside, which algorithm would be best for a greenfield production system?</p>
2014-12-30 20:59:04.210000+00:00
2019-05-23 15:24:53.027000+00:00
2019-05-23 15:24:53.027000+00:00
minhash|simhash
['https://arxiv.org/pdf/1706.05698.pdf', 'https://stackoverflow.com/questions/19701052/how-many-hash-functions-are-required-in-a-minhash-algorithm']
2
37,331,313
<p>I will provide a general answer, going beyond the scope of OpenCV library.</p> <hr> <p>Quoting this <a href="https://dsp.stackexchange.com/questions/10423/why-do-we-use-keypoint-descriptors">answer</a>:</p> <blockquote> <p><strong>descriptors</strong>: they are the way to compare the keypoints. They summarize, in vector format (of constant length) some characteristics about the keypoints.</p> </blockquote> <p>With that said, we can imagine/treat (<em>geometrically</em>) a descriptor as point in a D dimensional space. So in total, all the descriptors are points in a D dimensional space. For example, for <a href="https://www.quora.com/Computer-Vision-What-is-a-GIST-descriptor" rel="nofollow noreferrer">GIST</a>, D = 960.</p> <p>So actually descriptors <em>describe</em> the image, using less information that the whole image (because when you have 1 billion images, the size matters). They serve as the image's representatives, so we are processing them on behalf of the image (since they are easier/smaller to treat).</p> <hr> <p>The problem you are mentioning <strong>is the <a href="https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm" rel="nofollow noreferrer">Nearest Neighbor</a></strong> problem. Notice that an <em>approximate</em> version of this problem can lead to significant speed ups, when D is big (since the curse of dimensionality will make the traditional approaches, such as a <a href="https://en.wikipedia.org/wiki/K-d_tree" rel="nofollow noreferrer">kd-tree</a> very slow, almost linear in N (number of points)).</p> <p>Algorithms that solve the NN problem, which is a problem of optimization, are usually generic. They may not care if the data are images, molecules, etc., I for example have used my <a href="https://gsamaras.wordpress.com/projects/#geraf" rel="nofollow noreferrer">kd-GeRaF</a> for both. As a result, the <strong>algorithms expect N points in a D dimensional space</strong>, so N descriptors you might want to say.</p> <p>Check my answer for LSH <a href="https://stackoverflow.com/questions/37271413/heuristics-to-sort-array-of-2d-3d-points-according-their-mutual-distance/37308369#37308369">here</a> (which points to a nice implementation).</p> <hr> <p><em>Edit</em>:</p> <p>LSH expects as input <strong>N</strong> vectors of <strong>D</strong> dimension and given a query vector (in <strong>D</strong>) and a range <strong>R</strong>, will find the vectors that lie within this range from the query vector.</p> <p>As a result, we can say that every image is represented by just one vector, in <a href="http://sift.jcvi.org/www/chr_coords_example_indels.html" rel="nofollow noreferrer">SIFT</a> format for example.</p> <p>You see, LSH doesn't actually solve the k-NN problem directly, but it searches within a range (and can give you the k-NNs, if they are withing the range). Read more about R, in the Experiments section, <a href="http://arxiv.org/pdf/1603.09596.pdf" rel="nofollow noreferrer">High-dimensional approximate nearest neighbo</a>. <a href="https://gsamaras.wordpress.com/projects/#geraf" rel="nofollow noreferrer">kd-GeRaF</a> and <a href="http://www.cs.ubc.ca/research/flann/" rel="nofollow noreferrer">FLANN</a> solve directly the k-NN problem.</p>
2016-05-19 18:25:33.643000+00:00
2016-05-20 11:50:05.390000+00:00
2017-05-23 12:02:08.657000+00:00
null
37,318,778
<p>This is my first image processing application, so please be kind with this filthy peasant.</p> <p><strong>THE APPLICATION:</strong></p> <p>I want to implement a fast application (<strong>performance are crucial</strong> even over accuracy) where given a photo (taken by mobile phone) containing a movie poster finds the most similar photo in a given dataset and return a similarity score. The dataset is composed by similar pictures (taken by mobile phone, containing a movie poster). The images can be of different size, resolutions and can be taken from different viewpoints (but there is no rotation, since the posters are supposed to always be right-oriented).</p> <p><strong>Any suggestion on how to implement such an application is well accepted.</strong></p> <p><strong>FEATURE DESCRIPTIONS IN OPENCV:</strong></p> <p>I've never used OpenCV and I've read <a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_table_of_contents_feature2d/py_table_of_contents_feature2d.html" rel="nofollow">this tutorial about Feature Detection and Description</a> by OpenCV.</p> <p>From what I've understood, these algorithms are supposed to find keypoints (usually corners) and eventually define descriptors (which describe each keypoint and are used for matching two different images). I used "eventually" since some of them (eg FAST) provides only keypoints.</p> <p><strong>MOST SIMILAR IMAGE PROBLEM AND LSH:</strong></p> <p>The problems above doesn't solve the problem "given an image, how to find the most similar one in a dataset in a fast way". In order to do that, we can both use the keypoints and descriptors obtained by any of the previous algorithms. The problem stated above seems like a <a href="https://en.wikipedia.org/wiki/Nearest_neighbour_algorithm" rel="nofollow">nearest neighbor problem</a> and <a href="https://en.wikipedia.org/wiki/Locality-sensitive_hashing" rel="nofollow">Locality Sensitive Hashing</a> is a fast and popular solution for find an approximate solution for this problem in high-dimensionality spaces.</p> <p><strong>THE QUESTION:</strong></p> <p>What I don't understand is how to use the result of any of the previous algorithms (i.e. keypoints and descriptors) in LSH.</p> <p>Is there any implementation for this problem?</p>
2016-05-19 09:12:02.153000+00:00
2016-05-20 11:50:05.390000+00:00
2016-05-19 18:25:50.363000+00:00
c++|opencv|image-processing|nearest-neighbor|locality-sensitive-hash
['https://dsp.stackexchange.com/questions/10423/why-do-we-use-keypoint-descriptors', 'https://www.quora.com/Computer-Vision-What-is-a-GIST-descriptor', 'https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm', 'https://en.wikipedia.org/wiki/K-d_tree', 'https://gsamaras.wordpress.com/projects/#geraf', 'https://stackoverflow.com/questions/37271413/heuristics-to-sort-array-of-2d-3d-points-according-their-mutual-distance/37308369#37308369', 'http://sift.jcvi.org/www/chr_coords_example_indels.html', 'http://arxiv.org/pdf/1603.09596.pdf', 'https://gsamaras.wordpress.com/projects/#geraf', 'http://www.cs.ubc.ca/research/flann/']
10
58,798,690
<p>Typically adversarial examples are created by getting the gradient of the output w.r.t. the input and then maximizing the loss. E.g. if you have a classification task for cats and dogs and you want to create adversarial examples, you input a 256 x 256 cat image into your network, get the gradient of the loss w.r.t. the input, which will be also be a 256 x 256 tensor, then add the negative gradient (perturbation) to your image until the network classifies it as a dog. By training on these generated images again with the correct label, the network becomes more robust to noise/perturbation.</p> <p>There are also other more sophisticated approaches. For example <a href="https://arxiv.org/abs/1910.10053" rel="nofollow noreferrer">this paper</a> explains how a pattern in the input can corrupt the output of an optical flow estimation network.</p>
2019-11-11 09:29:05.120000+00:00
2019-11-11 09:34:50.140000+00:00
2019-11-11 09:34:50.140000+00:00
null
58,798,302
<p>Neural Structured Learning (NSL) has recently been introduced in tensorflow 2.0. I have gone through <a href="https://www.tensorflow.org/neural_structured_learning/framework" rel="nofollow noreferrer">this guide</a> on NSL on tensorflow site as also <a href="https://www.tensorflow.org/neural_structured_learning/tutorials/adversarial_keras_cnn_mnist" rel="nofollow noreferrer">this tutorial</a> on '<em>Adversarial regularization for image classification</em>'. Conceptually, it is not clear to me how this works. How are additional adversarial samples generated, what is meant by adversarial training, and how does it help in achieving greater accuracy/performance? The additional code is really short but what this code is doing behind the scenes is not clear. Will be grateful for a step-by-step inside explanation from a layman's point of view.</p>
2019-11-11 09:03:12.037000+00:00
2019-11-12 13:44:23.847000+00:00
2019-11-12 13:44:23.847000+00:00
python|tensorflow|nsl
['https://arxiv.org/abs/1910.10053']
1
16,883,009
<p>R in general was not built with security in mind (see also this <a href="http://arxiv.org/abs/1303.4808" rel="nofollow noreferrer">preprint</a> at arXiv by Jeroen Ooms). It is also notorious for <a href="https://stackoverflow.com/questions/11700748/why-does-the-number-1e9999-31-9s-cause-problems-in-r">flaky parsing of numbers</a>.</p> <p>Judging from the source code (which was <a href="https://github.com/clbustos/rinruby/blob/master/lib/rinruby.rb" rel="nofollow noreferrer">not updated for 2 years</a> (!)) RinRuby doesn't seem to provide any kind of isolation from injection either - bare-bones <code>eval</code> is a gateway to hell, they say :)</p> <p>Thus, it falls upon your shoulders to follow e.g. <a href="https://www.owasp.org/index.php/Main_Page" rel="nofollow noreferrer">OWASP guidelines</a> to avoid injection by carefully validating, parameterizing and whitelisting the input. Having in mind the above-mentioned quirks in parsing numbers, you have to restrict inputs to sane intervals.</p> <p>Just my 2 cents...</p>
2013-06-02 13:02:28.200000+00:00
2013-06-04 07:57:27.380000+00:00
2017-05-23 10:25:52.980000+00:00
null
16,840,294
<p>I recall from some meetups I've attended in NYC that people in bell labs were trying to work on potential security issues with R on the web. There was potential risks of code injection into a Web App if R sessions were kept alive for the user.</p> <p>Now, this was presented in the context of HTML 5 and PHP, but I don't see how it would be different when using RoR with the RinRuby gem. Is there a set of rules we as developers should follow to avoid common security pitfalls when using this gem?</p>
2013-05-30 15:36:20.320000+00:00
2013-06-05 12:33:24.550000+00:00
2013-06-05 12:33:24.550000+00:00
ruby-on-rails|r|security
['http://arxiv.org/abs/1303.4808', 'https://stackoverflow.com/questions/11700748/why-does-the-number-1e9999-31-9s-cause-problems-in-r', 'https://github.com/clbustos/rinruby/blob/master/lib/rinruby.rb', 'https://www.owasp.org/index.php/Main_Page']
4
69,041,742
<p>First, to understand the YOLOv4 loss, I think you should read about the original YOLO loss that was released in YOLO first paper (<a href="https://arxiv.org/abs/1506.02640" rel="noreferrer">https://arxiv.org/abs/1506.02640</a>), you can find it <a href="https://i.stack.imgur.com/5boQl.png" rel="noreferrer">here</a>.<br /> In YOLOv4, you will have the exact same ideas, but with:</p> <ul> <li>Binary cross entropy for the objectness and classification scores,</li> <li>Box-per-cell level prediction instead of cell level prediction for the class probabilities, so a slightly different penalization for the classification terms,</li> <li>CIoU Loss instead of MSE for the regression terms (x,y,w,h). CIoU stands for Complete Intersection over Union, and is not so far from the MSE loss. It proposes to compare width and height a bit more interestingly (consistency between aspect ratios), but it keeps the MSE for the comparison between bounding box centers. You can find more details in <a href="https://arxiv.org/pdf/1911.08287.pdf" rel="noreferrer">this</a> paper.</li> </ul> <p>Finally, YOLOv4 loss can be written <a href="https://i.stack.imgur.com/Z2toj.png" rel="noreferrer">this way</a>. With the complete CIoU loss terms, it looks like <a href="https://i.stack.imgur.com/0Wf6m.png" rel="noreferrer">this</a>.</p>
2021-09-03 08:24:21.870000+00:00
2021-09-04 00:02:33.563000+00:00
2021-09-04 00:02:33.563000+00:00
null
68,892,124
<p>I am unable to find the explanation for the loss function of yolov4.</p>
2021-08-23 11:46:52.457000+00:00
2021-09-04 00:02:33.563000+00:00
null
object-detection|loss-function|darknet|yolov4
['https://arxiv.org/abs/1506.02640', 'https://i.stack.imgur.com/5boQl.png', 'https://arxiv.org/pdf/1911.08287.pdf', 'https://i.stack.imgur.com/Z2toj.png', 'https://i.stack.imgur.com/0Wf6m.png']
5
59,865,565
<p>Generally, TFF considers the feeding of data to be part of the "Python driver loop", which is a helpful distinction to make when writing TFF code.</p> <p>In fact, when writing TFF, there are generally three levels at which one may be writing:</p> <ol> <li>TensorFlow defining local processing (IE, processing that will happen on the clients, or on the server, or in the aggregators, or at any other placement one may want, but only a <em>single</em> placement.</li> <li>Native TFF defining the way data is communicated <em>across</em> placements. For example, writing <code>tff.federated_sum</code> inside of a <code>tff.federated_computation</code> decorator; writing this line declares "this data is moved from clients to server, and aggregated via the sum operator".</li> <li>Python "driving" the TFF loop, e.g. running a single round. It is the job of this final level to do what a "real" federated learning runtime would do; one example here would be selecting the clients for a given round.</li> </ol> <p>If this breakdown is kept in mind, using a generator or some other lazy-evaluation-style construct to feed data in to a federated computation becomes relatively simple; it is just done at the Python level.</p> <p>One way this could be done is via the <a href="https://www.tensorflow.org/federated/api_docs/python/tff/simulation/ClientData#create_tf_dataset_for_client" rel="nofollow noreferrer"><code>create_tf_dataset_for_client</code></a> method on the <code>ClientData</code> object; as you loop over rounds, your Python code can select from the list of <code>client_ids</code>, then you can instantiate a new list of <code>tf.data.Datasets</code>and pass them in as your new set of client data. An example of this relatively simple usage would be <a href="https://github.com/tensorflow/federated/blob/master/tensorflow_federated/python/research/simple_fedavg/emnist_fedavg.py#L161" rel="nofollow noreferrer">here</a>, and a more advanced usage (involving defining a custom <code>client_datasets_fn</code> which takes <code>client_id</code> as a parameter, and passing it to a separately-defined training loop would be <a href="https://github.com/tensorflow/federated/blob/master/tensorflow_federated/python/research/gans/experiments/emnist/train.py#L354" rel="nofollow noreferrer">here</a>, in the code associated to <a href="https://arxiv.org/abs/1911.06679" rel="nofollow noreferrer">this paper</a>.</p> <p>One final note: instantiating a <code>tf.data.Dataset</code> does not actually load the dataset into memory; the dataset is only loaded in when it is iterated over. One helpful tip I have received from the lead author of <code>tf.data.Dataset</code> is to think of <code>tf.data.Dataset</code> more as a "dataset recipe" than a literal instantiation of the dataset itself. It has been suggested that perhaps a better name would have been <code>DataSource</code> for this construct; hopefully that may help the mental model on what is actually happening. Similarly, using the <code>tff.simulation.ClientData</code> object generally shouldn't really load anything into memory until it is iterated over in training on the clients; this should make some nuances around managing dataset memory simpler.</p>
2020-01-22 17:49:38.477000+00:00
2020-01-22 17:49:38.477000+00:00
null
null
59,835,749
<p>(I have posted the question on <a href="https://github.com/tensorflow/federated/issues/793" rel="nofollow noreferrer">https://github.com/tensorflow/federated/issues/793</a> and maybe also here!)</p> <p>I have customized my own data and model to federated interfaces and the training converged. But I am confused about an issue that in an images classification task, the whole dataset is extreme large and it can't be stored in a single <code>federated_train_data</code> nor be imported to memory for one time. So I need to load the dataset from the hard disk in batches to memory real-timely and use <code>Keras model.fit_generator</code> instead of <code>model.fit</code> during training, the approach people use to deal with large data.</p> <p>I suppose in <code>iterative_process</code> shown in image classification tutorial, the model is fitted on a fixed set of data. Is there any way to adjust the code to let it fit to a data generator?I have looked into the source codes but still quite confused. Would be incredibly grateful for any hints.</p>
2020-01-21 07:04:28.147000+00:00
2020-11-28 10:57:46.557000+00:00
2020-11-28 10:57:46.557000+00:00
tensorflow|keras|tensorflow-federated|federated-learning
['https://www.tensorflow.org/federated/api_docs/python/tff/simulation/ClientData#create_tf_dataset_for_client', 'https://github.com/tensorflow/federated/blob/master/tensorflow_federated/python/research/simple_fedavg/emnist_fedavg.py#L161', 'https://github.com/tensorflow/federated/blob/master/tensorflow_federated/python/research/gans/experiments/emnist/train.py#L354', 'https://arxiv.org/abs/1911.06679']
4
62,255,295
<p>I encountered the same issue and I applied van's answer but it did not work. However I agree with van's explanation so I added <code>.distinct()</code> to the query like this:</p> <pre><code>old_votes = models.Papers.query.distinct().join(sub_query, sub_query.c.arxiv_id == models.Papers.arxiv_id).paginate(1, 4, False) </code></pre> <p>It worked as I expected.</p>
2020-06-08 04:59:50.970000+00:00
2020-06-08 04:59:50.970000+00:00
null
null
34,582,014
<p>I am using flask-sqlalchemy together with a sqlite database. I try to get all votes below date1</p> <pre><code>sub_query = models.VoteList.query.filter(models.VoteList.vote_datetime &lt; date1) sub_query = sub_query.filter(models.VoteList.group_id == selected_group.id) sub_query = sub_query.filter(models.VoteList.user_id == g.user.id) sub_query = sub_query.subquery() old_votes = models.Papers.query.join(sub_query, sub_query.c.arxiv_id == models.Papers.arxiv_id).paginate(1, 4, False) </code></pre> <p>where the database model for VoteList looks like this </p> <pre><code>class VoteList(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) group_id = db.Column(db.Integer, db.ForeignKey('groups.id')) arxiv_id = db.Column(db.String(1000), db.ForeignKey('papers.arxiv_id')) vote_datetime = db.Column(db.DateTime) group = db.relationship("Groups", backref=db.backref('vote_list', lazy='dynamic')) user = db.relationship("User", backref=db.backref('votes', lazy='dynamic'), foreign_keys=[user_id]) def __repr__(self): return '&lt;VoteList %r&gt;' % (self.id) </code></pre> <p>I made sure that the 'old_votes' selection above has 20 elements. If I use .all() instead of .paginate() I get the expected 20 result? Since I used a max results value of 4 in the example above I would expect that old_votes.items has 4 elements. But it has only 2? If I increase the max results value the number of elements also increases, but it is always below the max result value? Paginate seems to mess up something here? any ideas? thanks carl</p> <p>EDIT I noticed that it works fine if I apply the paginate() function on add_columns(). So if I add (for no good reason) a column with </p> <pre><code>old_votes = models.Papers.query.join(sub_query, sub_query.c.arxiv_id == models.Papers.arxiv_id) old_votes = old_votes.add_columns(sub_query.c.vote_datetime).paginate(page, VOTES_PER_PAGE, False) </code></pre> <p>it works fine? But since I don't need that column it would still be interesting to know what goes wrong with my example above?</p>
2016-01-03 21:49:55.633000+00:00
2022-03-02 15:15:39.420000+00:00
2016-01-03 23:34:59.600000+00:00
sql|sqlalchemy|flask-sqlalchemy|pagination
[]
0
41,969,647
<p>Here is an approach based on <a href="https://arxiv.org/pdf/1309.3873.pdf" rel="noreferrer">this paper</a> which proves a result about the mixing time needed to scramble a list by using swaps of adjacent items</p> <pre><code>from random import choice from math import log def jitter(items,percent): n = len(items) m = (n**2 * log(n)) items = items[:] indices = list(range(n-1)) for i in range(int(percent*m)): j = choice(indices) items[j],items[j+1] = items[j+1],items[j] return items </code></pre> <p>A test, each line showing the result of <code>jitter</code> with various percents being applied to the same list:</p> <pre><code>ls = list(('0'*20 + '1'*20)*2) for i in range(11): p = i/10.0 print(''.join(jitter(ls,p))) </code></pre> <p>Typical output:</p> <pre><code>00000000000000000000111111111111111111110000000000000000000011111111111111111111 00000000000000111100001101111011011111001010000100010001101000110110111111111111 00000000100100000101111110000110111101000001110001101001010101100011111111111110 00000001010010011011000100111010101100001111011100100000111010110111011001011111 00100001100000001101010000011010011011111011001100000111011011111011010101011101 00000000011101000110000110000010011001010110011111100100111101111011101100111110 00110000000001011001000010110011111101001111001001100101010011010111111011101100 01101100000100100110000011011000001101111111010100000100000110111011110011011111 01100010110100010100010100011000000001000101100011111011111011111011010100011111 10011100101000100010001100100000100111001111011011000100101101101010101101011111 10000000001000111101101011000011010010110011010101110011010100101101011110101110 </code></pre> <p>I'm not sure how principled the above is, but it seems like a reasonable place to start.</p>
2017-01-31 23:51:57.757000+00:00
2017-01-31 23:51:57.757000+00:00
null
null
41,969,036
<p>I am using two architecture programs, with visual programming plugins (Grasshopper for Rhino and Dynamo for Revit - for those that know / are interested) </p> <p>Grasshopper contains a function called 'Jitter' this will shuffle a list, however it has an input from 0.0 to 1.0 which controls the degree of shuffling - 0.0 results in no shuffling 1.0 produces a complete shuffle. </p> <p>The second of the programs (Dynamo) does not contain this functionality. It contains a shuffle module (which contains a seed value) however it is a complete random shuffle. </p> <p>Ultimately the goal is to produce a series of solid and glazed panels, but to produce a slight random effect (but avoiding large clumping of solid and glazed elements - hence I want a "light shuffle")</p> <p>I have written a code which will calculate the number of glazed(True) and solid(False) values required and then evenly distribute True and False values based on the number of items and percent specified.</p> <p>I have checked out the random module reference however I'm not familiar with the various distributions as described. </p> <p>Could someone help out or point me in the right direction if an existing function would achieve this. </p> <p>(I have cheated slightly by adding True False alternately to make up the correct number of items within the list - list3 is the final list, list2 contains the repeated module of true falses) </p> <p>Many thanks </p> <pre><code>import math import random percent = 30 items = 42 def remainder(): remain = items % len(list2) list3.append(True) remain -= 1 while remain &gt; 0 : list3.append(False) remain -= 1 return list3 #find module of repeating True and False values list1 = ([True] + [False] * int((100/percent)-1)) #multiply this list to nearest multiple based on len(items) list2 = list1 * int(items/(100/percent)) # make a copy of list2 list3 = list2[:] #add alternating true and false to match len(list3) to len(items) remainder() #an example of a completely shuffled list - which is not desired shuffled = random.sample(list3, k = len(list3)) </code></pre>
2017-01-31 22:57:21.017000+00:00
2021-03-11 08:24:33.520000+00:00
2017-02-01 13:08:48.637000+00:00
python|random|shuffle
['https://arxiv.org/pdf/1309.3873.pdf']
1
65,704,377
<p>I faced a similar problem and managed to fix it by removing the Batch Normalisation layer that's just before the output dense layer. This made a ton of difference. Also one of the suggestions I was given is to remove the Dropout layer as it might be causing Shift Variance. Check this <a href="https://arxiv.org/pdf/1801.05134.pdf" rel="nofollow noreferrer">paper</a></p> <p>I got part of the solution from this <a href="https://stackoverflow.com/questions/39691902/ordering-of-batch-normalization-and-dropout?noredirect=1&amp;lq=1">thread</a>.</p>
2021-01-13 14:54:44.500000+00:00
2021-01-13 14:54:44.500000+00:00
null
null
47,272,383
<p>I am working on a very sparse dataset with the point of predicting 6 classes. I have tried working with a lot of models and architectures, but the problem remains the same. </p> <p>When I start training, the acc for training will slowly start to increase and loss will decrease where as the validation will do the exact opposite. </p> <p>I have <strong>really tried</strong> to deal with overfitting, and I simply cannot still believe that this is what is coursing this issue. </p> <h2>What have I tried</h2> <p>Transfer learning on VGG16:</p> <ul> <li>exclude top layer and add dense layer with 256 units and 6 units softmax output layer</li> <li>finetune the top CNN block</li> <li>finetune the top 3-4 CNN blocks</li> </ul> <p>To deal with overfitting I use heavy augmentation in Keras and dropout after the 256 dense layer with p=0.5.</p> <p>Creating own CNN with VGG16-ish architecture:</p> <ul> <li>including batch normalization wherever possible</li> <li>L2 regularization on each CNN+dense layer</li> <li>Dropout from anywhere between 0.5-0.8 after each CNN+dense+pooling layer</li> <li>Heavy data augmentation in "on the fly" in Keras</li> </ul> <p>Realising that perhaps I have too many free parameters:</p> <ul> <li>decreasing the network to only contain 2 CNN blocks + dense + output. </li> <li>dealing with overfitting in the same manner as above.</li> </ul> <p>Without exception <strong>all</strong> training sessions are looking like this: <a href="https://i.stack.imgur.com/Vnwhi.png" rel="noreferrer">Training &amp; Validation loss+accuracy</a></p> <p>The last mentioned architecture looks like this:</p> <pre><code> reg = 0.0001 model = Sequential() model.add(Conv2D(8, (3, 3), input_shape=input_shape, padding='same', kernel_regularizer=regularizers.l2(reg))) model.add(BatchNormalization()) model.add(Activation('relu')) model.add(Dropout(0.7)) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.5)) model.add(Conv2D(16, (3, 3), input_shape=input_shape, padding='same', kernel_regularizer=regularizers.l2(reg))) model.add(BatchNormalization()) model.add(Activation('relu')) model.add(Dropout(0.7)) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.5)) model.add(Flatten()) model.add(Dense(16, kernel_regularizer=regularizers.l2(reg))) model.add(BatchNormalization()) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(6)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='SGD',metrics=['accuracy']) </code></pre> <p>And the data is augmented by the generator in Keras and is loaded with flow_from_directory:</p> <pre><code> train_datagen = ImageDataGenerator(rotation_range=10, width_shift_range=0.05, height_shift_range=0.05, shear_range=0.05, zoom_range=0.05, rescale=1/255., fill_mode='nearest', channel_shift_range=0.2*255) train_generator = train_datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, shuffle = True, class_mode='categorical') validation_datagen = ImageDataGenerator(rescale=1/255.) validation_generator = validation_datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=1, shuffle = True, class_mode='categorical') </code></pre>
2017-11-13 19:49:48.633000+00:00
2021-01-13 14:54:44.500000+00:00
2017-11-13 21:33:10.257000+00:00
python|deep-learning|keras|classification
['https://arxiv.org/pdf/1801.05134.pdf', 'https://stackoverflow.com/questions/39691902/ordering-of-batch-normalization-and-dropout?noredirect=1&lq=1']
2
63,705,496
<p>The answer to the similar question of yours can be found in the paper <a href="https://stackoverflow.com/questions/58636587/how-to-use-bert-for-long-text-classification/63413589#63413589">here</a>.</p> <p>Why do you think the chunks of the same document will have different labels if you're talking about classiffcation of texts as news or clickbaits? You can chunk the text and follow the idea of truncation approach proposed in How to <a href="https://stackoverflow.com/questions/58636587/how-to-use-bert-for-long-text-classification/63413589#63413589">Fine-Tune BERT for Text Classification?</a>. The authors show that head+tail truncating delivers high accuracy. I used it several times thanks to the <a href="https://github.com/xuyige/BERT4doc-Classification" rel="nofollow noreferrer">Github</a> page and documentation and got good results.</p> <p>You can choose the truncation method with a flag <strong>--trunc_medium</strong> with the options:</p> <ol> <li>-2 means head-only (keep the first 512 tokens),</li> <li>-1 means tail-only (keep the last 512 tokens),</li> <li>0 means head-half + tail-half (e.g.: head256+tail256),</li> <li>other natural number k means head-k + tail-rest (e.g.: head-k + tail-(512-k)).</li> </ol> <p>Then you may pool the results for the chunks creating the Pooled embeddings for the long texts you have.</p> <p>Here I will also continue discussion about the state-of-the-art approaches for the classification of long texts with BERT reffering to Big BIRD (see the <a href="https://arxiv.org/pdf/2007.14062.pdf" rel="nofollow noreferrer">article</a>). The researchers from Google build on the idea of <a href="https://arxiv.org/pdf/2004.05150.pdf" rel="nofollow noreferrer">Longformers</a> and <a href="https://arxiv.org/abs/2004.08483" rel="nofollow noreferrer">Extended Transformers Construction</a>. Basically they propose combine the idea of Longformers and Randomized Attention that reduces quadratic dependency on the sequence length to linear. You can try even 10000-wording texts. The approach is interesting however, it requires architecture with more layers.</p> <p>Plese check also the stackoverflow <a href="https://stackoverflow.com/questions/58636587/how-to-use-bert-for-long-text-classification/63413589#63413589">question</a>.</p>
2020-09-02 12:25:57.463000+00:00
2020-09-02 12:37:48.687000+00:00
2020-09-02 12:37:48.687000+00:00
null
63,671,085
<p>I am trying to classify given text into news, clickbait or others. The texts which I have for training are long.<a href="https://i.stack.imgur.com/R5N6l.png" rel="nofollow noreferrer">distribution of lengths is shown here.</a> Now, the question is should I trim the text at the middle and make it 512 tokens long? But, I have even documents with circa 10,000 words so won't I loose the gist by truncation? Or, should I split my text into sub texts of 512 length. If so, then the sub text of one text may be similar to subtext of another text but the labels will be different. Doesn't it become noisy data? Or, should I just use bidirectional LSTM's here and pad to max_len?</p>
2020-08-31 12:45:01.110000+00:00
2020-09-03 14:48:10.673000+00:00
2020-09-03 14:48:10.673000+00:00
deep-learning|nlp|bert-language-model
['https://stackoverflow.com/questions/58636587/how-to-use-bert-for-long-text-classification/63413589#63413589', 'https://stackoverflow.com/questions/58636587/how-to-use-bert-for-long-text-classification/63413589#63413589', 'https://github.com/xuyige/BERT4doc-Classification', 'https://arxiv.org/pdf/2007.14062.pdf', 'https://arxiv.org/pdf/2004.05150.pdf', 'https://arxiv.org/abs/2004.08483', 'https://stackoverflow.com/questions/58636587/how-to-use-bert-for-long-text-classification/63413589#63413589']
7
54,395,524
<p>To reproduce the numpy example in TensorFlow, please try <code>depth_to_space</code>:</p> <pre><code>import tensorflow as tf im = tf.random_normal((1, 8, 8, 2)) phased_im_01 = im[:, ::2, 1::2, :] phased_im_00 = im[:, ::2, ::2, :] phased_im_10 = im[:, 1::2, ::2, :] phased_im_11 = im[:, 1::2, 1::2, :] phases = tf.concat( (phased_im_00, phased_im_01, phased_im_10, phased_im_11), axis=3) rebuild_im = tf.nn.depth_to_space(phases, block_size=2, data_format='NHWC') dif = tf.reduce_sum(rebuild_im - im) # 0.0 </code></pre> <p>As kindly suggested by <a href="https://stackoverflow.com/users/5024514/shlomif">ShlomiF</a>, the more general example is:</p> <pre><code>import numpy as np import tensorflow as tf tf.enable_eager_execution() num_of_channels = 20 h = w = 256 num_of_phases = 4 im = np.random.random((1, h, w, num_of_channels)) phase_ims = [] for i in range(num_of_phases): for j in range(num_of_phases): phase_ims.append(im[:, i::num_of_phases, j::num_of_phases, :]) all_phases = tf.concat(phase_ims, axis=3) rebuild_im = tf.depth_to_space(all_phases, block_size=num_of_phases, data_format='NHWC') diff = tf.reduce_sum(rebuild_im - im) print(np.asarray(diff)) # --&gt; 0.0 </code></pre> <p>As far as I know, the idea of <code>depth_to_space</code>, or periodic shuffling, came from <a href="https://arxiv.org/abs/1609.05158" rel="nofollow noreferrer">this paper</a>. You may find more details and visualization there. </p>
2019-01-28 04:23:45.083000+00:00
2019-01-28 09:48:03.753000+00:00
2019-01-28 09:48:03.753000+00:00
null
54,383,569
<p>Or: Scattering different phases of multi-channel images in tensorflow...</p> <p>My question is as follows:<br> I have "images", all of the same dimensions, which in some sense correspond to different phases of a target image. And I'd like to rebuild that full-blown image with tf functionality.<br> This turns out to be much less simple than I originally expected and I'd be very grateful for any help! </p> <p>A more detailed exposition follows:<br> In <code>numpy</code>, one easily interleaves images via simple assignment - </p> <pre><code>import numpy as np im = np.random.random((1, 8, 8, 2)) phased_im_01 = im[:, ::2, 1::2, :] phased_im_00 = im[:, ::2, ::2, :] phased_im_10 = im[:, 1::2, ::2, :] phased_im_11 = im[:, 1::2, 1::2, :] rebuild_im = np.zeros((1, 8, 8, 2)) rebuild_im[:, ::2, ::2, :] = phased_im_00 rebuild_im[:, ::2, 1::2, :] = phased_im_01 rebuild_im[:, 1::2, ::2, :] = phased_im_10 rebuild_im[:, 1::2, 1::2, :] = phased_im_11 print(np.all(rebuild_im == im)) </code></pre> <p>But as known, assignment is a no-go in tf, and one usually uses things like <code>tf.concat</code> coupled with <code>tf.reshape</code> (for very simple cases) or <code>tf.scatter_nd</code> (for more complicated cases). I was unsuccessful in implementing the equivalent of the above numpy-functionality using any of the many things I tried (like permuting the tensor to have the width dimension first, trying to scatter_nd, and permuting back, a method I've successfully used before for other problems), or any solution on SO (like stacking and reshaping oneself to death). </p> <p>Just to be clear, my actual use-case has an unknown batch-size, thousands of channels, and 4 phases in each image dimension. But I just need a working solution for the simple toy example above; generalization is on me ;-)<br> Thanks to any helpers out there, (and sorry I can only describe my efforts and not show them. They're just a mess of unsuccessful mistakes degrading into horrible trial-and-error code snippets until giving up and coming here for some help anyway, so no major loss). </p> <p>Clarifications can be added on demand.</p>
2019-01-26 22:56:44.893000+00:00
2019-01-28 12:04:04.783000+00:00
2019-01-28 12:04:04.783000+00:00
python|tensorflow
['https://stackoverflow.com/users/5024514/shlomif', 'https://arxiv.org/abs/1609.05158']
2
59,274,485
<p>I don't know how useful this is but from my POV, word vector embeddings are naturally separated and the position in the sample space is closely related to different uses of the word. However like you said often a word may be used in several contexts.</p> <hr> <p>To Solve this purpose, generally encoding techniques that utilise the context like continuous bag of words, or continous skip gram models are used for classification of the usage of word in a particular context like change for either exchange or adjust. This very idea is applied in LSTM based architectures as well or RNNs where the context is preserved over input sequences.</p> <hr> <p>The interpretation of word-vectors isn't practical from a visualisation point of view, but only from 'relative distance' point of view with other words in the sample space. Another way is to maintain a matrix of the corpus with contextual uses being represented for the words in that matrix. In fact there's a neural network that utilises bidirectional language model to first predict the upcoming word then at the end of the sentence goes back and tries to predict the previous word. It's called ELMo. You should go through the paper.<a href="https://arxiv.org/pdf/1802.05365.pdf" rel="nofollow noreferrer">ELMo Paper</a> and this <a href="https://blogs.nvidia.com/blog/2018/08/27/nlp-deep-learning/" rel="nofollow noreferrer">blog</a></p> <hr> <p>Naturally the model learns from representative examples. So the better training set you give with the diverse uses of the same word, the better model can learn to utilise context to attach meaning to the word. Often this is what people use to solve their specific cases by using domain centric training data.</p> <p>I think these could be helpful: <a href="https://arxiv.org/pdf/1301.3781.pdf" rel="nofollow noreferrer">Efficient Estimation of Word Representations in Vector Space</a> </p>
2019-12-10 19:58:21.300000+00:00
2019-12-10 19:58:21.300000+00:00
null
null
59,261,462
<p>Take the following sentence:</p> <pre><code>I'm going to change the light bulb </code></pre> <p>The meaning of <code>change</code> means <code>replace</code>, as in someone is going to replace the light bulb. This could easily be solved by using a dictionary api or something similar. However, the following sentences</p> <pre><code>I need to go the bank to change some currency You need to change your screen brightness </code></pre> <p>The first sentence does not mean <code>replace</code> anymore, it means <code>Exchange</code>and the second sentence, <code>change</code> means <code>adjust</code>.</p> <p>If you were trying to understand the meaning of <code>change</code> in this situation, what techniques would someone use to extract the correct definition based off of the context of the sentence? What is what I'm trying to do called?</p> <p>Keep in mind, the input would only be one sentence. So something like:</p> <pre><code>Screen brightness is typically too bright on most peoples computers. People need to change the brightness to have healthier eyes. </code></pre> <p>Is not what I'm trying to solve, because you can use the previous sentence to set the context. Also this would be for lots of different words, not just the word <code>change</code>.</p> <p>Appreciate the suggestions.</p> <p><strong>Edit:</strong> I'm aware that various embedding models can help gain insight on this problem. If this is your answer, how do you interpret the word embedding that is returned? These arrays can be upwards of 500+ in length which isn't practical to interpret. </p>
2019-12-10 06:32:04.600000+00:00
2019-12-18 16:07:12.437000+00:00
2019-12-10 19:38:27.253000+00:00
machine-learning|deep-learning|nlp|word-embedding|linguistics
['https://arxiv.org/pdf/1802.05365.pdf', 'https://blogs.nvidia.com/blog/2018/08/27/nlp-deep-learning/', 'https://arxiv.org/pdf/1301.3781.pdf']
3
58,315,394
<p>Fundamentally, you are changing the number of parameters of your model. As you go from</p> <pre><code>conv1 = tf.get_variable('conv1_1', shape=(11, 11, 3, 64), initializer=tf.contrib.layers.xavier_initializer()) </code></pre> <p>to</p> <pre><code>conv2 = tf.get_variable('conv2_l1', shape=(11, 11, 3, 20), initializer=tf.contrib.layers.xavier_initializer()) </code></pre> <p>Your learnable parameters goes from {Kernel x 64} to {Kernel x 20} This will require you to re-train the network and learn its new weights. </p> <p>However, this is a common problem that has evolved into a research area. Many methods have been proposed for this such as low-rank approximation of weights (Denton et al., 2014; Lebedev et al., 2014), weight quantization(Courbariaux et al., 2016; Rastegari et al., 2016), knowledge distillation (Hinton et al., 2014; Romeroet al., 2015) and network pruning (Han et al., 2015; Li et al., 2017), among which network pruning has gained notable attention due to their competitive performance and compatibility. </p> <p>References to explore:</p> <ol> <li>Emily L Denton, Wojciech Zaremba, Joan Bruna, Yann LeCun, and Rob Fergus. Exploiting linearstructure within convolutional networks for efficient evaluation. InNIPS, 2014.</li> <li>Vadim Lebedev, Yaroslav Ganin, Maksim Rakhuba, Ivan Oseledets, and Victor Lempitsky.Speeding-up convolutional neural networks using fine-tuned cp-decomposition.ICLR, 2014.</li> <li>Matthieu Courbariaux, Itay Hubara, Daniel Soudry, Ran El-Yaniv, and Yoshua Bengio. Binarizedneural networks: Training deep neural networks with weights and activations constrained to+ 1or-1.arXiv preprint arXiv:1602.02830, 2016</li> <li>Geoffrey Hinton, Oriol Vinyals, and Jeff Dean. Distilling the knowledge in a neural network.NIPSWorkshop, 2014.</li> </ol>
2019-10-10 04:18:15.793000+00:00
2019-10-10 04:36:50.190000+00:00
2019-10-10 04:36:50.190000+00:00
null
58,313,035
<p>If I have a trained model, where I want to retrain the same model, with few filters/kernel removed from the existing model. e.g. </p> <pre><code>conv1 = tf.get_variable('conv1_1', shape=(11, 11, 3, 64), initializer=tf.contrib.layers.xavier_initializer()), </code></pre> <p>and I want to resize this tensor such that it has the shape of (11, 11, 3, 20) but the same name and position, mean exactly the same variable. Advance thanks for the help.</p> <p>I have tried <code>tf.reshape</code> but it gives me error of not matching the number of elements in a and b I have also tried <code>tf.assign(a,b, validate_shape=false)</code></p> <pre><code>self.weights = { 'conv1_': tf.get_variable('conv1_l1', shape=(11, 11, 3, 64), initializer=tf.contrib.layers.xavier_initializer()), 'conv2_': tf.get_variable('conv2_l1', shape=(7, 7, 64, 128), initializer=tf.contrib.layers.xavier_initializer()) } </code></pre>
2019-10-09 22:20:01.353000+00:00
2021-07-28 12:30:23.110000+00:00
2019-10-10 02:30:06.310000+00:00
tensorflow|machine-learning|image-processing|computer-vision
[]
0
48,716,909
<p>The following code worked for me:</p> <pre><code>import os from bs4 import BeautifulSoup # Python 3.x from urllib.request import urlopen, urlretrieve URL = 'https://arxiv.org/find/all/1/all:+5g/0/1/0/all/0/1?skip=0&amp;query_id=32bdbf71e4007c69' OUTPUT_DIR = '' # path to output folder, '.' or '' uses current folder u = urlopen(URL) try: html = u.read().decode('utf-8') finally: u.close() soup = BeautifulSoup(html, "html.parser") #print(soup) for link in soup.select('a[href^="/pdf"]'): href = link.get('href') href1 = 'https://arxiv.org'+ href + '.pdf' #print(href) print(href) print(href1) if not any(href1.endswith(x) for x in ['.pdf']): continue filename = os.path.join(OUTPUT_DIR, href1.rsplit('/', 1)[-1]) # We need a https:// URL for this site #href = href.replace('http://','https://') print(filename) print("Downloading %s to %s..." % (href1, filename) ) urlretrieve(href1, filename) print("Done.") </code></pre>
2018-02-10 03:25:56.637000+00:00
2018-02-10 03:25:56.637000+00:00
null
null
48,716,254
<p>Hi I want to download the linked pdf files from the following url: </p> <p><a href="https://arxiv.org/find/all/1/all:+5g/0/1/0/all/0/1?skip=0&amp;query_id=32bdbf71e4007c69" rel="nofollow noreferrer">https://arxiv.org/find/all/1/all:+5g/0/1/0/all/0/1?skip=0&amp;query_id=32bdbf71e4007c69</a></p> <p>Is there any Python3 code available for this? Any help will be appreciated.</p>
2018-02-10 01:12:50.387000+00:00
2018-02-10 03:25:56.637000+00:00
null
python-3.x|pdf|web|download
[]
0
58,784,591
<p>Transfer learning for facial detection would be a great way to go ahead. Also, yes transfer learning with facenet is a great idea. </p> <p>Also, for transfer learning to work it is not necessary that the model had to be initially pre-trained with only faces like using facenet. A model pre-trained with imagenet would also be pretty darn good! This is a very hot topic, so do not try to reinvent the wheel. There are many repositories that have already done this using transfer learning from imagenet dataset and using resnet50 with astonishingly good results. </p> <p>Here is a link to one such repository:</p> <p><a href="https://github.com/loheden/face_recognition_with_siamese_network" rel="nofollow noreferrer">https://github.com/loheden/face_recognition_with_siamese_network</a></p> <p>Also note that siamese networks is a technique that is especially good in the facial recognition use case. The concept of siamese is really simple: take two images and compare the features of these two images. If the similarity in features are above a set threshold, then the two images are the same (the two faces are the same) else not the same (face not recognized). </p> <p>Here is a research paper on <a href="https://arxiv.org/abs/1503.03832" rel="nofollow noreferrer">siamese networks for facial recognition</a>.</p> <p>Also, here is a two-part tutorial on how to implement the siamese network for facial recognition using transfer learning:</p> <p><a href="http://www.loheden.com/2018/07/face-recognition-with-siamese-network.html" rel="nofollow noreferrer">http://www.loheden.com/2018/07/face-recognition-with-siamese-network.html</a></p> <p><a href="http://www.loheden.com/2018/07/face-recognition-with-siamese-network_29.html" rel="nofollow noreferrer">http://www.loheden.com/2018/07/face-recognition-with-siamese-network_29.html</a></p> <p>The above tutorial's code is in the first Github link I shared at the beginning of this answer.</p>
2019-11-09 23:50:10.263000+00:00
2019-11-09 23:50:10.263000+00:00
null
null
58,784,373
<p>I wish to know whether I can use an Inception or ResNet model to identify faces. I want to know whether transfer learning and training is even considerable for my task. </p> <p>I just want to be able to identify faces but I am also curious whether I can retrain/optimize a pre-trained model for my task.</p> <p>Or have I been reading of things wrong; do I need to get a pre-trained model that was designed for faces?</p> <p>I have tried poking around with Inception and VGG16 but I have not trained them for faces. I am working on it but I want to know whether this is even viable or simply a waste of time. If I use transfer learning with FaceNet I think I'll be better off.</p>
2019-11-09 23:12:17.520000+00:00
2020-12-28 09:08:29.340000+00:00
null
python|tensorflow|keras|transfer-learning|facial-identification
['https://github.com/loheden/face_recognition_with_siamese_network', 'https://arxiv.org/abs/1503.03832', 'http://www.loheden.com/2018/07/face-recognition-with-siamese-network.html', 'http://www.loheden.com/2018/07/face-recognition-with-siamese-network_29.html']
4
50,085,879
<p>After a bit of digging, it seems that it is not trivial to compute per-example gradients in TensorFlow, because this library performs standard back-propagation to compute the gradients (as do other deep learning libraries like PyTorch, Theano and so on), which never actually computes the per-example gradients, it directly obtains the sum of the per-example gradients. Check out <a href="https://github.com/tensorflow/tensorflow/issues/4897" rel="nofollow noreferrer">this discussion</a> for more details.</p> <p>However, there are some techniques to work around this issue, at least for some use cases. For example, the paper <a href="https://arxiv.org/abs/1510.01799" rel="nofollow noreferrer">Efficient per-example gradient computation</a> by Ian Goodfellow explains how to efficiently compute per-example vectors containing the sum of squared derivatives. Here is an excerpt from the paper showing the computation (but I highly encourage you read the paper, it is very short):</p> <p><a href="https://i.stack.imgur.com/CKipm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CKipm.png" alt="enter image description here"></a></p> <p>This algorithm is O(mnp) instead of O(mnp²), where m is the number of examples, n is the number of layers in the neural net, and p is the number of neurons per layer. So it is much faster than the naive approach (i.e., performing back-prop once per example), especially when p is large, and even more when using a GPU (which speeds up vectorized approaches by a large factor).</p>
2018-04-29 11:07:11.277000+00:00
2018-04-29 11:07:11.277000+00:00
null
null
50,080,929
<p>TD;DR: is there a way to evaluate f'(x1), f'(x2), ..., f'(xn) in just one graph run, in a vectorized form? Where f'(x) is the derivative of f(x).</p> <p>Something like:</p> <pre><code>x = tf.placeholder(tf.float32, shape=[100]) f = tf.square(x) f_grad = tf.multiple_gradients(x) # f_grad contains f'(x[0]), f'(x[1]), ... </code></pre> <p>More specifically, I'm trying to implement Black Box Stochastic Variational Inference (BBSVI) manually (I know I could use a library like <a href="http://edwardlib.org/" rel="nofollow noreferrer">Edward</a>, but I'm trying to implement it myself). At one point, I need to compute the mean of f'(x)g(x) across many different values of x (x1, x2, ..., xn), where f(x) and g(x) are two functions, and f'(x) is the derivative of f(x).</p> <p>Using TensorFlow's autodiff feature, I can compute f'(x1), f'(x2), ..., f'(xn), by simply calling <code>f_prime.eval(feed_dict={x: xi})</code> once for each value xi in (x1, x2, ..., xn). This is not efficient at all: I would like to use a vectorized form instead, but I'm not sure how to do this.</p> <p>Perhaps using <code>tf.stop_gradient()</code> somehow? Or using the <code>grad_ys</code> argument in <code>tf.gradients()</code>?</p>
2018-04-28 20:46:40.153000+00:00
2020-03-24 20:36:01.477000+00:00
2018-04-29 11:08:31.420000+00:00
python|tensorflow|gradient
['https://github.com/tensorflow/tensorflow/issues/4897', 'https://arxiv.org/abs/1510.01799', 'https://i.stack.imgur.com/CKipm.png']
3
67,963,468
<p><strong>JUNE 2021 UPDATED ANSWER</strong></p> <p>I think this question needs an updated answer.</p> <p><strong>GOOD NEWS</strong>: The R package <code>pdftools</code> has included in its recent update the option to extract <code>font-data</code> from the pdfs. The function <code>pdf_data</code> has now an additional argument <code>font_info</code> described in the <a href="https://github.com/ropensci/pdftools/blob/master/man/pdftools.Rd" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p><strong>font_info</strong> if TRUE, extract font-data for each box. Be careful, this requires a very recent version of poppler and will error otherwise.</p> </blockquote> <p>A simple implementation using <code>pdftools::pdf_data</code> with <code>font_info=TRUE</code> shows that:</p> <pre><code>pdftools::pdf_data(pdf = &quot;https://arxiv.org/pdf/2012.10582.pdf&quot;, font_info = TRUE) </code></pre> <p><a href="https://i.stack.imgur.com/uz0YA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uz0YA.png" alt="enter image description here" /></a></p> <p><strong>REMARKS:</strong></p> <ol> <li>Some <strong>bold</strong> fonts are indicated by suffixes of medium fonts (Medi) as in e.g., <code>KBJWLM+NimbusRomNo9L-Medi</code>.</li> <li>The <em>italics</em> are indicated by suffixes like <code>ReguItal</code> which stands for 'Regular Italics'. For example, <code>ZBSJXS+NimbusRomNo9L-ReguItal</code>.</li> <li>Regular fonts are obviously indicated by purely <code>Regu</code> suffixes as in <code>VDTZKA+NimbusRomNo9L-Regu</code>.</li> </ol> <p><strong>WARNING:</strong> This answer has never been tested for pdf images (scanned) with overlapped/overlayed text.</p>
2021-06-13 23:53:01.240000+00:00
2022-05-08 20:52:26.573000+00:00
2022-05-08 20:52:26.573000+00:00
null
53,398,611
<p>I have searched through SO and the closest I got to the answer was <a href="https://stackoverflow.com/q/49536590/1972786">here</a>. But my requirement is to get a simpler &amp; more elegant way to extract bold from a simple paragraph of text of pdf. The <code>pdftools</code> package only extracts the plain text component. Does anyone know if there is any other way to simply detect bold tokens (or words) from a chunk of text in pdf. I use R so kindly restrict to suggestions in R.</p>
2018-11-20 17:41:59.587000+00:00
2022-05-08 20:52:26.573000+00:00
2018-11-23 07:50:06.870000+00:00
r|pdf
['https://github.com/ropensci/pdftools/blob/master/man/pdftools.Rd', 'https://i.stack.imgur.com/uz0YA.png']
2
65,649,488
<p>I don't think this is necessarily a good idea. I especially don't think it will be easier than using DCGs. You still need to write some sort of proper grammar that knows more about the input's structure than just &quot;combine certain sequences of words&quot;. That said, there is some work on parsing with CHR, see <a href="https://arxiv.org/abs/cs/0408027" rel="nofollow noreferrer">CHR Grammars</a> for example.</p> <p>Your first problem is that CHR constraints are unordered. When you try to match <code>w(L), w(on), w(R)</code>, you have no guarantee that <code>L</code> is actually to the left of <code>R</code> in the input. This information is not recorded for you.</p> <p>So what you can do is to record it yourself. You can replace each <code>w(X)</code> with a <code>w(X, Start, End)</code> constraint where <code>Start</code> and <code>End</code> are some sort of input position markers. For example, simply numbering tokens from left to right:</p> <pre><code>:- use_module(library(chr)). :- chr_constraint w/3. parse(Tokens) :- parse(Tokens, 0). parse([], _Position). parse([Token | Tokens], Position) :- NextPosition is Position + 1, w(Token, Position, NextPosition), parse(Tokens, NextPosition). </code></pre> <p>You can use this as follows:</p> <pre><code>?- parse([the, box, is, on, the, table]). w(table, 5, 6), w(the, 4, 5), w(on, 3, 4), w(is, 2, 3), w(box, 1, 2), w(the, 0, 1). </code></pre> <p>Given this format, you can enhance your matching rules to only combine adjacent inputs (where each component's end marker is the same as the &quot;next&quot; component's start marker):</p> <pre><code>w(the, S, M), w(X, M, E) &lt;=&gt; w([the,X], S, E). w(L, S, M1), w(on, M1, M2), w(R, M2, E) &lt;=&gt; w(on(L,R), S, E). w(L, S, M1), w(is, M1, M2), w(R, M2, E) &lt;=&gt; w(is_(L,R), S, E). </code></pre> <p>(I use <code>is_</code> instead of <code>is</code> because <code>is</code> is a built-in operator, and <code>is(X, Y)</code> facts would be printed as <code>X is Y</code>, which is confusing in what follows.)</p> <p>This allows you to make some progress:</p> <pre><code>?- parse([the, box, is, on, the, table]). w([the, table], 4, 6), w(is_([the, box], on), 0, 4). </code></pre> <p>We see that <code>the</code> and <code>table</code> at positions 4 to 5 and 5 to 6 were merged together into a phrase <code>the, table</code> at position 4 to 6. Also the words <code>the</code>, <code>box</code>, <code>is</code>, <code>on</code>, were merged together into one object covering positions 0 to 4. But this is not correct: &quot;the box is on&quot; is not a valid phrase. The phrase to the right of &quot;is&quot; must be a location or other situation. You need more information about the kinds of sub-phrases in a phrase. You need proper grammar information, the kind that you would encode in a DCG by defining rules with different names.</p> <p>Here is an expanded version:</p> <pre><code>:- chr_constraint noun_phrase/3, situation/3, sentence/3. w(the, S, M), w(X, M, E) &lt;=&gt; noun_phrase([the,X], S, E). w(on, S, M), noun_phrase(R, M, E) &lt;=&gt; situation(on(R), S, E). noun_phrase(L, S, M1), w(is, M1, M2), situation(R, M2, E) &lt;=&gt; sentence(is_(L,R), S, E). </code></pre> <p>And this works:</p> <pre><code>?- parse([the, box, is, on, the, table]). sentence(is_([the, box], on([the, table])), 0, 6). </code></pre> <p>But at this point you are writing a DCG in ugly syntax and with lots of extra information you must track by hand. Why not write the DCG instead?</p> <pre><code>noun_phrase([the, X]) --&gt; [the], [X]. situation(on(Place)) --&gt; [on], noun_phrase(Place). sentence(is_(Thing, Where)) --&gt; noun_phrase(Thing), [is], situation(Where). </code></pre> <p>This works just as nicely:</p> <pre><code>?- phrase(sentence(Sentence), [the, box, is, on, the, table]). Sentence = is_([the, box], on([the, table])). </code></pre> <p>If you want to get this information into a CHR constraint, you can do that by calling that constraint. For example, with the DCG above:</p> <pre><code>:- chr_constraint sentence/1. parse(Tokens) :- phrase(sentence(Sentence), Tokens), sentence(Sentence). </code></pre> <p>This gets the same CHR result as above, but without the position markers which are no longer needed:</p> <pre><code>?- parse([the, box, is, on, the, table]). sentence(is_([the, box], on([the, table]))). </code></pre>
2021-01-10 01:56:17.200000+00:00
2021-01-10 01:56:17.200000+00:00
null
null
65,647,409
<p>Trying to do sort of parsing with CHR (Constraint handling rules) I come up with this (still learning)</p> <pre><code>w(the),w(X) &lt;=&gt; w([the,X]). w(L),w(on),w(R) &lt;=&gt; w(on(L,R)). w(L),w(is),w(R) &lt;=&gt; w(is(L,R)). </code></pre> <p>here is what i got :</p> <pre><code>?- w(the),w(box),w(is),w(on),w(the),w(table). w(table), w([the, on(is, [the, box])]). </code></pre> <p>should be instead :</p> <pre><code>is([the,box],on([the,table])) </code></pre> <p>to make it work I have to figure how to do sort of late-binding on &quot;on&quot; and later &quot;is&quot;, so the the the-X has been already &quot;collected&quot;</p> <p>Second question is how to write CHR rules so that they parse a list, instead of making w(..) goals.</p> <p>PS&gt; also any info on mixing DCG with CHR would be welcome. Cant find anything !!</p>
2021-01-09 20:44:21.757000+00:00
2021-01-10 01:56:17.200000+00:00
null
parsing|prolog|constraints|dcg|chr
['https://arxiv.org/abs/cs/0408027']
1
69,410,069
<p>The per-layer terminology in <a href="https://arxiv.org/pdf/1504.08083.pdf" rel="nofollow noreferrer">that paper</a> is slightly ambiguous. They aren't referring to the layer-specific learning rates.</p> <blockquote> <p>All layers use a per-layer learning rate of 1 for weights and 2 for biases and a global learning rate of 0.001.</p> </blockquote> <p>The concerned statement is w.r.t. Caffe framework in which Fast R-CNN was originally written (<a href="https://github.com/rbgirshick/fast-rcnn" rel="nofollow noreferrer">github link</a>).</p> <p>They meant that they're setting the learning rate multiplier of weights and biases to be 1 and 2 respectively.</p> <p>Check any <code>prototxt</code> file in the repo e.g. <a href="https://github.com/rbgirshick/fast-rcnn/blob/master/models/CaffeNet/train.prototxt" rel="nofollow noreferrer">CaffeNet/train.prototxt</a>.</p> <pre><code> param { lr_mult: 1 decay_mult: 1 } param { lr_mult: 2 decay_mult: 0 } </code></pre> <p>Thus, the effective learning rate is going to be <code>base_lr*lr_mult</code>, and here, the base learning rate is 0.001, which is defined in <code>solver.prototxt</code>.</p>
2021-10-01 17:46:26.607000+00:00
2021-10-01 17:46:26.607000+00:00
null
null
69,406,476
<p>I'm reading a paper about Fast-RCNN model.</p> <p>In the paper section 2.3 part of 'SGD hyper-parameters', it said that <strong>All layers use a per-layer learning rate of 1 for weights and 2 for biases and a global learning rate of 0.001</strong></p> <br> <p>Is 'per-layer learning rate' same as 'layer-specific learning rate' that give different learning rate by layers? If so, I can't understand how they('per-layer learning rate' and 'global learning rate') can be apply at the same time?</p> <br> <p>I found the example of 'layer-specific learning rate' in pytorch.</p> <pre><code>optim.SGD([ {'params': model.some_layers.parameters()}, {'params': model.some_layers.parameters(), 'lr': 1} ], lr=1e-3, momentum=0.9) </code></pre> <p>According to paper, Is this the correct approach?</p> <br> <p>Sorry for may English</p>
2021-10-01 13:11:58.780000+00:00
2021-10-01 17:46:26.607000+00:00
null
deep-learning|pytorch|faster-rcnn
['https://arxiv.org/pdf/1504.08083.pdf', 'https://github.com/rbgirshick/fast-rcnn', 'https://github.com/rbgirshick/fast-rcnn/blob/master/models/CaffeNet/train.prototxt']
3