category
stringclasses
107 values
title
stringlengths
15
179
question_link
stringlengths
59
147
question_body
stringlengths
53
33.8k
answer_html
stringlengths
0
28.8k
__index_level_0__
int64
0
1.58k
gradient descent implementation
Implementation of Logistic regression with Gradient Descent in Java
https://stackoverflow.com/questions/28824327/implementation-of-logistic-regression-with-gradient-descent-in-java
<p>I have implemented Logistic Regression with Gradient Descent in Java. It doesn't seem to work well (It does not classify records properly; the probability of y=1 is a lot.) I don't know whether my implementation is correct.I have gone through the code several times and i am unable to find any bug. I have been foll...
<p>As I am studying logistic regression, I took the time to review your code in detail.</p> <p><strong>TLDR</strong></p> <p>In fact, it appears the algorithm is correct.</p> <p>The reason you had so much false negatives or false positives is, I think, because of the hyper parameters you choose.</p> <p>The model was...
334
gradient descent implementation
Implementing naive gradient descent in python
https://stackoverflow.com/questions/41202817/implementing-naive-gradient-descent-in-python
<p>I'm trying to implement a very naive gradient descent in python. However, it looks like it goes into an infinite loop. Could you please help me debug it? </p> <pre><code>y = lambda x : x**2 dy_dx = lambda x : 2*x def gradient_descent(function,derivative,initial_guess): optimum = initial_guess while derivati...
<p>Your <code>while</code> loop stops only when a calculated floating-point value equals zero. This is naïve, since floating-point values are rarely calculated exactly. Instead, stop the loop when the calculated value is <em>close enough</em> to zero. Use something like</p> <pre><code>while math.abs(derivative(optimum...
335
gradient descent implementation
gradient descent doesn&#39;t change in my linear regression implementation
https://stackoverflow.com/questions/70010085/gradient-descent-doesnt-change-in-my-linear-regression-implementation
<p>I am beginner in gradient descent concept . I implemented a multivariate linear regression with gradient descent optimization algorithm. but my program doesn't converge and just early iteration has small changes! my methods(in my class) is following below :</p> <pre><code>def gradientDescent(self, X, y, theta): ...
336
gradient descent implementation
How do I implement stochastic gradient descent correctly?
https://stackoverflow.com/questions/55757307/how-do-i-implement-stochastic-gradient-descent-correctly
<p>I'm trying to implement stochastic gradient descent in MATLAB however I am not seeing any convergence. Mini-batch gradient descent worked as expected so I think that the cost function and gradient steps are correct.</p> <p>The two main issues I am having are:</p> <ol> <li>Randomly shuffling the data in the trainin...
<p>First we need to shuffle the data correctly:</p> <pre><code>data = [ xrange', target']; data = data(randperm(size(data,1)),:); </code></pre> <p>Next we need to index X and y correctly:</p> <pre><code>y = data(:,2); X = data(:,1); </code></pre> <p>Then during gradient descent I need to update based on a single v...
337
gradient descent implementation
Gradient descent with polynomial features implementation issue
https://stackoverflow.com/questions/62625339/gradient-descent-with-polynomial-features-implementation-issue
<p>I am trying to implement gradient descent after transforming some random data using sklearns polynomial transformer. My code works when not using polynomial features, but gives really high coefficients when transforming.</p> <p>Is there an issue with my code (below)?</p> <pre><code> l= 20 np.random.seed(0) ...
338
gradient descent implementation
correct implementation of Hinge loss minimization for gradient descent
https://stackoverflow.com/questions/28988732/correct-implementation-of-hinge-loss-minimization-for-gradient-descent
<p>I copied the hinge loss function from <a href="https://code.google.com/p/java-statistical-analysis-tool/source/browse/trunk/JSAT/src/jsat/lossfunctions/HingeLoss.java?r=762" rel="nofollow">here</a> (also LossC and LossFunc upon which it's based. Then I included it in my gradient descent algorithm like so: </p> <pre...
<p>The code you provided for gradient does not look like a gradient of Hinge loss. Take a look at a valid equation, for example here: <a href="https://stats.stackexchange.com/questions/4608/gradient-of-hinge-loss">https://stats.stackexchange.com/questions/4608/gradient-of-hinge-loss</a></p>
339
gradient descent implementation
Implementation of Linear Regression Using Gradient Descent
https://stackoverflow.com/questions/63861962/implementation-of-linear-regression-using-gradient-descent
<p>Linear Regression Using Gradient Descent</p> <p>Reference: <a href="https://towardsdatascience.com/linear-regression-using-gradient-descent-in-10-lines-of-code-642f995339c0" rel="nofollow noreferrer">Linear Regression Using Gradient Descent in 10 Lines of Code</a></p> <p>Dataset:</p> <p>House price No. of bedroom...
340
gradient descent implementation
Logistic Regression, Gradient Descent Octave implementation
https://stackoverflow.com/questions/63046676/logistic-regression-gradient-descent-octave-implementation
<p>I'm taking the Machine Learning class by Prof. Ng. There is a homework need to implement logistic regression gradient descent. And here is my code:</p> <pre><code>function [J, grad] = costFunction(theta, X, y) %COSTFUNCTION Compute cost and gradient for logistic regression % J = COSTFUNCTION(theta, X, y) computes ...
<p>I believe you were supposed to get the average of the gradient <code>grad = grad / m</code> as well, just like for the cost <code>J</code>. But it has been a while since I last did Andrew Ng's course, so I might be wrong.</p>
341
gradient descent implementation
Implementing Stochastic Gradient Descent Python
https://stackoverflow.com/questions/44344006/implementing-stochastic-gradient-descent-python
<p>I've been trying to implement stochastic gradient descent as part of a recommendation system following these equations:</p> <p><a href="https://i.sstatic.net/mIzbi.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/mIzbi.jpg" alt="enter image description here" /></a></p> <p>I have:</p> <pre><code>for ste...
<p>When you update <em>qi</em> and <em>px</em>, you should exchange <em>mu1</em> and <em>mu2</em>.</p>
342
gradient descent implementation
Gradient descent with random input implementation
https://stackoverflow.com/questions/27009256/gradient-descent-with-random-input-implementation
<p>I am trying to implement gradient descent on a dataset. Even though I tried everything, I couldn't make it work. So, I created a test case. I am trying my code on a random data and try to debug. </p> <p>More specifically, what I am doing is, I am generating random vectors between 0-1 and random labels for these vec...
<p>Your code has a couple of faults:</p> <ul> <li>In <code>GetVectors()</code> method, you did not actually use the input variable <code>m</code>;</li> <li>In <code>GDLearn()</code> method, you have a double loop, but you use the same variable <code>i</code> as the loop variables in both loops. (I guess the logic is s...
343
gradient descent implementation
Linear Regression\Gradient Descent python implementation
https://stackoverflow.com/questions/14993454/linear-regression-gradient-descent-python-implementation
<p>I'm trying to implement linear regression using the gradient descent method from scratch for learning purposes. One part of my code is really bugging me. For some reason the variable <code>x</code> is being altered after I run a line of code and I'm not sure why. </p> <p>The variables are as follow. <code>x</code> ...
<p>What is happening is that python is computing the list <code>zip(x,y)</code>, then each iteration of your for loop is overwriting <code>(x,y)</code> with the corresponding element of <code>zip(x,y)</code>. When your for loop terminates <code>(x,y)</code> contains <code>zip(x,y)[-1]</code>.</p> <p>Try </p> <pre><c...
344
gradient descent implementation
Better gradient descent implementation for linear SVM with varying loss?
https://stackoverflow.com/questions/64126137/better-gradient-descent-implementation-for-linear-svm-with-varying-loss
<p>I'm implementing SVM with hinge loss (linear SVM, soft margin), and try to minimize the loss using gradient descent.<br /> Here's my current gradient descent, in Julia:</p> <pre><code>for i in 1:max_iter if n_cost_no_change &lt;= 0 &amp;&amp; early_stop break end learn!(X_data, Y_data, weights, l...
<p>After reading this <a href="https://ruder.io/optimizing-gradient-descent/index.html#momentum" rel="nofollow noreferrer">article</a>, I tried to use a momentum on gradient update.</p> <p>My new <code>learn!</code> function looks like this:</p> <pre><code>function learn!(X_data::Array{T} where T&lt;:Number, Y_data::Ar...
345
gradient descent implementation
Self-Implementation of Gradient Descent Compared to SciPy Minimize
https://stackoverflow.com/questions/56586436/self-implementation-of-gradient-descent-compared-to-scipy-minimize
<p>This is an assignment for a convex optimization class that I'm taking. The assignment is as follows:</p> <blockquote> <p>Implement the gradient descent algorithm with backtracking line search to find the optimal step size. Your implementation will be compared to Python's <a href="https://docs.scipy.org/doc/scipy/ref...
<p>Your guess about the tolerance checking is right: the norm of the current vector is not related to convergence. A typical criterion would be a small gradient, so <code>min_gd</code> should look like</p> <pre><code>def min_gd(fun, x0, grad, args=()): alpha = 0.3 beta = 0.8 eps = 0.001 x_new = x0 ...
346
gradient descent implementation
Python implementation of Gradient Descent Algorithm isn&#39;t working
https://stackoverflow.com/questions/30745627/python-implementation-of-gradient-descent-algorithm-isnt-working
<p>I am trying to implement a gradient descent algorithm for simple linear regression. For some reason it doesn't seem to be working. </p> <pre class="lang-py prettyprint-override"><code>from __future__ import division import random def error(x_i,z_i, theta0,theta1): return z_i - theta0 - theta1 * x_i def squ...
347
gradient descent implementation
Implement gradient descent in python
https://stackoverflow.com/questions/56887503/implement-gradient-descent-in-python
<p>I am trying to implement gradient descent in python. Though my code is returning result by I think results I am getting are completely wrong. </p> <p>Here is the code I have written:</p> <pre><code>import numpy as np import pandas dataset = pandas.read_csv('D:\ML Data\house-prices-advanced-regression-techniques\\...
<p>try to reduce the learning rate with iteration otherwise it wont be able to reach the optimal lowest.try this</p> <pre><code>import numpy as np import pandas dataset = pandas.read_csv('start.csv') X = np.empty((0, 1),int) Y = np.empty((0, 1), int) for i in range(dataset.shape[0]): X = np.append(X, dataset.at[i...
348
gradient descent implementation
Gradient Descent and Normal Equation give different theta values for multivariate linear regression.Why?
https://stackoverflow.com/questions/44347215/gradient-descent-and-normal-equation-give-different-theta-values-for-multivariat
<h1>Vectorized implementation of gradient descent</h1> <pre><code>for iter = 1:num_iters theta = theta - (alpha / m) * X' * (X * theta - y); J_history(iter) = computeCostMulti(X, y, theta); end </code></pre> <h1>Implementation of computeCostMulti()</h1> <pre><code>function J = computeCostMulti(X, y, theta) m...
<p>I suppose that when you use gradient descent, you first process your input using feature scaling. That is not done with the normal equation method (as feature scaling is not required), and that should result in a different theta. If you use your models to make predictions they should come up with the same result.</...
349
gradient descent implementation
Gradient becoming larger and larger while implementing gradient descent
https://stackoverflow.com/questions/48348275/gradient-becoming-larger-and-larger-while-implementing-gradient-descent
<p>I am trying to implement the gradient descent in python. The data is that of housing prices and i want to predict the house price. But the problem is that the gradient is becoming larger and larger until python cannot process it anymore.</p> <pre><code>import numpy as np import sys from numpy import genfromtxt tra...
350
gradient descent implementation
Simple Gradient Descent Implementation Error
https://stackoverflow.com/questions/65609277/simple-gradient-descent-implementation-error
<p>I have tried to use a toy problem of linear regression for implanting the optimisation on the MSE function using the algorithm of gradient decent.</p> <pre><code>import numpy as np # Data points x = np.array([1, 2, 3, 4]) y = np.array([1, 1, 2, 2]) # MSE function f = lambda a, b: 1 / len(x) * np.sum(np.power(y - (...
<p>It's great that you are learning machine learning (^_^) by implementing some base algorithms by yourself. Regarding your question, there are two problems in your code, first one is <strong>mathematical</strong>, the sign in:</p> <pre><code>def grad_f(v_coefficients): a = v_coefficients[0, 0] b = v_coefficien...
351
gradient descent implementation
Linear Regression and Gradient Descent in Scikit learn?
https://stackoverflow.com/questions/34469237/linear-regression-and-gradient-descent-in-scikit-learn
<p>In <a href="https://share.coursera.org/wiki/index.php/ML:Linear_Regression_with_Multiple_Variables#Gradient_Descent_for_Multiple_Variables" rel="nofollow noreferrer">this Coursera course</a> for machine learning, it says gradient descent should converge.</p> <p>I'm using Linear regression from scikit learn. It doesn...
<p>Scikit learn provides you two approaches to linear regression:</p> <ol> <li><p><code>LinearRegression</code> object uses Ordinary Least Squares solver from scipy, as LR is one of two classifiers which have <strong>closed form solution</strong>. Despite the ML course - you can actually learn this model by just invert...
352
gradient descent implementation
Implementing backpropagation gradient descent using scipy.optimize.minimize
https://stackoverflow.com/questions/47579719/implementing-backpropagation-gradient-descent-using-scipy-optimize-minimize
<p>I am trying to train an autoencoder NN (3 layers - 2 visible, 1 hidden) using numpy and scipy for the MNIST digits images dataset. The implementation is based on the notation given <a href="http://ufldl.stanford.edu/wiki/index.php/Neural_Networks" rel="nofollow noreferrer">here</a> Below is my code:</p> <pre><code>...
<p>Turns out the issue was a syntax error (very silly) with this line:</p> <pre><code>J = lambda x: utils.autoencoder_cost_and_grad(theta, visible_size, hidden_size, lambda_, patches_train) </code></pre> <p>I don't even have the <code>lambda</code> parameter <code>x</code> in the function declaration. So the <code>th...
353
gradient descent implementation
Batch gradient descent algorithm implementation in python
https://stackoverflow.com/questions/47593225/batch-gradient-descent-algorithm-implementation-in-python
<p>I learned the Batch gradient descent algorithm recently and tried implementing it in Python. I used a data set which is not random. When I tried running the below code, the process is converging after 3 iterations but with a big error. Can someone guide me in a right way? Sample Data set:(original data set length is...
354
gradient descent implementation
Python implementation of gradient descent (Machine Learning)
https://stackoverflow.com/questions/19889918/python-implementation-of-gradient-descent-machine-learning
<p>I have tried to implement gradient descent here in python but the cost J just seems to be increasing irrespective of lambda ans alpha value, i am unable to figure out what the issue over here is. It'll be great if someone can help me out with this. The input is a matrix Y and R with same dimensions. Y is a matrix of...
<p>I did not check the whole code logic, but assuming it is correct, your <code>costfunc</code> is supposed to return gradient of the cost function, and in these lines:</p> <pre><code>for i in range(1,10): (x,theta) = costFunc(x,theta,y,r) </code></pre> <p>you are overwriting the last values of x and theta with ...
355
gradient descent implementation
What is the issue with this implementation of gradient descent?
https://stackoverflow.com/questions/41349806/what-is-the-issue-with-this-implementation-of-gradient-descent
<p>I tried to implement linear regresion with gradient descent, but my error diverges to infinity. I've read over my code and still cannot figure out where I went wrong. I'm hoping someone can help me debug why this implementation of linear regression isn't working. </p> <p>When <code>N=100</code> then there are no p...
<p>You've exceeded the convergence radius of your method. I put in a print statement to trace the effect, at the bottom of <strong>propagate</strong>:</p> <pre><code> self.w = np.array(res).astype(np.float) print self.error(ys, yhat), '\t', r1, '\t', r2, '\t', self.w </code></pre> <p>As K.A. Buhr pointed out,...
356
gradient descent implementation
Issue Implementing Custom Gradient Descent Function
https://stackoverflow.com/questions/67266157/issue-implementing-custom-gradient-descent-function
<p>I am implementing my own/custom Gradient descent algorithm using python but the weights and biases that are returned by my algorithm has 10 values (shape=(10, )) but my input data has only 1 column so I am expecting it to return <strong>1 Weight and 1 Bias</strong></p> <p>Code:</p> <pre><code>import numpy as np impo...
<p>I think this is because your <code>y</code> is a 1d row list, but <code>y_pred</code> is a <code>1xn</code> column list, so subtracting them will give you an <code>nxn</code> matrix which you don't want. The fix is to just reshape <code>y</code> before you call your function like so:</p> <pre><code>import numpy as n...
357
gradient descent implementation
My vectorization implementation of gradient descent does not get me the right answer
https://stackoverflow.com/questions/56520284/my-vectorization-implementation-of-gradient-descent-does-not-get-me-the-right-an
<p>I'm currently working on Andrew Ng's gradient descent exercise using python but keeps getting me the wrong optimal theta. I followed this vectorization cheatsheet for gradient descent --- <a href="https://medium.com/ml-ai-study-group/vectorized-implementation-of-cost-functions-and-gradient-vectors-linear-regression-...
358
gradient descent implementation
Gradient descent values not correct
https://stackoverflow.com/questions/37845650/gradient-descent-values-not-correct
<p>I'm attempting to implement gradient descent using code from : </p> <p><a href="https://stackoverflow.com/questions/10591343/gradient-descent-implementation-in-octave">Gradient Descent implementation in octave</a></p> <p>I've amended code to following : </p> <pre><code>X = [1; 1; 1;] y = [1; 0; 1;] m = length(y)...
<p>You are misinterpreting dimensions here. Your data consists of <strong>3 points</strong>, each having <strong>a single dimension</strong>. Furthermore, you <strong>add a dummy dimension</strong> of 1s </p> <pre><code>X = [ones(m, 1), data(:,1)]; </code></pre> <p>thus</p> <pre><code>octave:1&gt; data = [1;2;3] da...
359
gradient descent implementation
Implementing Gradient Descent In Python and receiving an overflow error
https://stackoverflow.com/questions/49865952/implementing-gradient-descent-in-python-and-receiving-an-overflow-error
<h2>Gradient Descent and Overflow Error</h2> <p>I am currently implementing vectorized gradient descent in python. However, I continue to get an overflow error. The numbers in my dataset are not extremely large though. I am using this formula:</p> <p><a href="https://i.sstatic.net/wPecc.png" rel="nofollow noreferrer"...
<p>Your data values are really very large, which makes your loss function very steep. The result is that you need a <em>tiny</em> alpha unless you normalize your data to smaller values. With an alpha value that is too large your gradient descent is hopping all over the place and actually diverges, which is why your er...
360
gradient descent implementation
Java implementation of multivariate gradient descent
https://stackoverflow.com/questions/41144206/java-implementation-of-multivariate-gradient-descent
<p>I'm trying to implement the multivariate gradient descent algorithm in Java (from AI coursera course), and I cannot figure where is the fault located in my code.</p> <p>This is the output of the below program:</p> <pre><code>Before train: parameters := [0.0, 0.0, 0.0] -&gt; cost function := 2.5021875E9 After first...
<p>It seems you have a reasonable start, but there were some issues in the translation of the math to code. See the following math.</p> <p><img src="https://i.sstatic.net/QtKss.png" alt="The math"></p> <p>There were a few steps I took to clarify the math and the algorithm's convergence mechanism.</p> <ol> <li>To in...
361
gradient descent implementation
Trouble Implementing Gradient Descent in Octave
https://stackoverflow.com/questions/42944688/trouble-implementing-gradient-descent-in-octave
<p>I've been trying to implement gradient descent in Octave. This is the code I have so far:</p> <pre><code>function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters) %GRADIENTDESCENT Performs gradient descent to learn theta % theta = GRADIENTDESCENT(X, y, theta, alpha, num_iters) updates theta...
<p>I think my problem is that I had an extra for loop in there for some reason.</p>
362
gradient descent implementation
How to implement minibatch gradient descent in tensorflow without using feeddict?
https://stackoverflow.com/questions/51091129/how-to-implement-minibatch-gradient-descent-in-tensorflow-without-using-feeddict
<p>From what I understand, using <code>feed_dict</code> is a computationally expensive process and should be avoided according to <a href="https://towardsdatascience.com/how-to-use-dataset-in-tensorflow-c758ef9e4428" rel="nofollow noreferrer">this article</a>. Tensorflow's input pipelines are supposedly better. </p> <...
<p>If you are just making a small model, you will do fine with <code>feed_dict</code>. Many large models have been trained with the <code>feed_dict</code> method in the past. If you are scaling to a very deep convnet with a large dataset or something, you may want to use <code>tf.data</code> and the dataset pipeline, p...
363
gradient descent implementation
Issue when Implementing gradient descent in R
https://stackoverflow.com/questions/50249691/issue-when-implementing-gradient-descent-in-r
<p>I have problems implementing a gradient descent in R for an exponential function.</p> <p>Let's say</p> <pre><code>foo &lt;- function(x) { y = -2 + 2.5 * exp(0.1*x^2-0.7*x) return(y) } </code></pre> <p>is my exponential function then</p> <pre><code> grad &lt;- function(x) { y = 2.5*exp(0.1*x^2-0.7*x)*(0....
364
gradient descent implementation
Why is my implementation of gradient descent on python producing outputs so slow?
https://stackoverflow.com/questions/55357592/why-is-my-implementation-of-gradient-descent-on-python-producing-outputs-so-slow
<p>Why are the outputs from the code getting slow with every successive iteration?</p> <p>I want to write a working code , that implements Gradient descent and Newton's method on same function and I want to compare the speeds and iterations for both the methods to arrive at the approximate solution.</p> <p>This code ...
365
gradient descent implementation
Implementing gradient descent in python
https://stackoverflow.com/questions/66494060/implementing-gradient-descent-in-python
<p>I was trying to build a gradient descent function in python. I have used the binary-crossentropy as the loss function and sigmoid as the activation function.</p> <pre><code>def sigmoid(x): return 1/(1+np.exp(-x)) def binary_crossentropy(y_pred,y): epsilon = 1e-15 y_pred_new = np.array([max(i,epsilon) fo...
<p>Usually, <code>binary cross-entropy</code> loss is used for binary classification task. However, here your task is a linear regression so I would prefer using <code>Mean Square Error</code> as loss function. Here is my suggesstion:</p> <pre><code>def gradient_descent(X, y, epochs=1000, learning_rate=0.5): w = np...
366
gradient descent implementation
Gradient descent not updating theta values
https://stackoverflow.com/questions/37229574/gradient-descent-not-updating-theta-values
<p>Using the vectorized version of gradient as described at : <a href="https://stackoverflow.com/questions/10479353/gradient-descent-seems-to-fail">gradient descent seems to fail</a></p> <pre><code>theta = theta - (alpha/m * (X * theta-y)' * X)'; </code></pre> <p>The theta values are not being updated, so whatever ...
<p><code>theta = theta - (alpha/m * (X * theta-y)' * X)';</code> is indeed the correct vectorized implementation of gradient-descent.</p> <p>You totally forgot to set the learning rate, <code>alpha</code>.</p> <p>After setting <code>alpha = 0.01</code>, your code becomes:</p> <pre><code>m = 1 # numbe...
367
gradient descent implementation
Understanding Gradient Descent for Multivariate Linear Regression python implementation
https://stackoverflow.com/questions/33629734/understanding-gradient-descent-for-multivariate-linear-regression-python-impleme
<p>It seems that the following code finds the gradient descent correctly:</p> <pre><code>def gradientDescent(x, y, theta, alpha, m, numIterations): xTrans = x.transpose() for i in range(0, numIterations): hypothesis = np.dot(x, theta) loss = hypothesis - y cost = np.sum(loss ** 2) / (2...
<p>First: Congrats on taking the course on Machine Learning on Coursera! :)</p> <p><code>hypothesis = np.dot(x,theta)</code> will compute the hypothesis for all x(i) at the same time, saving each h_theta(x(i)) as a row of <code>hypothesis</code>. So there is no need to reference a single row.</p> <p>Same is true for ...
368
gradient descent implementation
Can I implement a gradient descent for arbitrary convex loss function?
https://stackoverflow.com/questions/42587696/can-i-implement-a-gradient-descent-for-arbitrary-convex-loss-function
<p>I have a loss function I would like to try and minimize:</p> <pre><code>def lossfunction(X,b,lambs): B = b.reshape(X.shape) penalty = np.linalg.norm(B, axis = 1)**(0.5) return np.linalg.norm(np.dot(X,B)-X) + lambs*penalty.sum() </code></pre> <p>Gradient descent, or similar methods, might be useful. ...
<p>You could try <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html" rel="nofollow noreferrer">scipy.optimize.minimize</a> For your case a sample call would be: </p> <pre><code> import scipy.optimize.minimize scipy.optimize.minimize(lossfunction, args=(b, lambs), method='Neld...
369
gradient descent implementation
Implementing gradient descent for multiple variables in Octave using &quot;sum&quot;
https://stackoverflow.com/questions/35945445/implementing-gradient-descent-for-multiple-variables-in-octave-using-sum
<p>I'm doing Andrew Ng's course on Machine Learning and I'm trying to wrap my head around the vectorised implementation of gradient descent for multiple variables which is an optional exercise in the course.</p> <p>This is the algorithm in question (taken from <a href="http://www.holehouse.org/mlclass/04_Linear_Regres...
<p>The general "rule of the thumb" is as follows, if you encounter something in the form of</p> <pre><code>SUM_i f(x_i, y_i, ...) g(a_i, b_i, ...) </code></pre> <p>then you can easily vectorize it (and this is what is done in the above) through</p> <pre><code>f(x, y, ...)' * g(a, b, ...) </code></pre> <p>As this is...
370
gradient descent implementation
Python implemented Gradient Descent Algorithm won&#39;t converge
https://stackoverflow.com/questions/30221211/python-implemented-gradient-descent-algorithm-wont-converge
<p>I've implemented a gradient descent algorithm in python and it is just not converging when it runs. When I debugging it, I have to make the alpha very small to let it 'seems' to converge. The alpha is like, have to be 1e-12 that small.</p> <p>Here is my code</p> <pre><code> def batchGradDescent(dataMat, labelMa...
371
gradient descent implementation
Stochastic gradient descent converges too smoothly
https://stackoverflow.com/questions/42766970/stochastic-gradient-descent-converges-too-smoothly
<p>As a part of my homework I was asked to implement a stochastic gradient descent in order to solve a linear regression problem (even though I have only 200 training examples). My problem is that stochastic gradient descent converges too smoothly, almost exactly as batch gradient descent, which brings me to my questio...
<p>There is nothing unusual with your graph. You should also note that your batch method takes fewer iterations to converge. </p> <p>You may be letting SGD plots from neural networks cloud your view on what SGD "should" look like. Most neural networks are much more complicated models (difficult to optimize) working on...
372
gradient descent implementation
Trying to Implement Linear Regression with Stochastic Gradient Descent
https://stackoverflow.com/questions/66756559/trying-to-implement-linear-regression-with-stochastic-gradient-descent
<p>[<a href="https://docs.google.com/spreadsheets/d/1AVNrWBwn22c1QWc6X9zG8FkvTMXHXZGuZH2sPAT9a00/edit?usp=sharing" rel="nofollow noreferrer">Dataset</a>]<a href="https://docs.google.com/spreadsheets/d/1AVNrWBwn22c1QWc6X9zG8FkvTMXHXZGuZH2sPAT9a00/edit?usp=sharing" rel="nofollow noreferrer">1</a>I'm attempting to impleme...
<p>Adding on to the answer from @Agni</p> <p>The CSV file that you are reading has a header line</p> <p><code>num_preg PlGlcConc BloodP tricept insulin BMI ped_func Age HasDiabetes</code></p> <p>When you use <code>reader(file)</code> to read the file and then iterate over it, the first line also gets added in <...
373
gradient descent implementation
Python gradient descent - cost keeps increasing
https://stackoverflow.com/questions/39771075/python-gradient-descent-cost-keeps-increasing
<p>I'm trying to implement gradient descent in python and my loss/cost keeps increasing with every iteration.</p> <p>I've seen a few people post about this, and saw an answer here: <a href="https://stackoverflow.com/questions/17784587/gradient-descent-using-python-and-numpy">gradient descent using python and numpy</a>...
<p>Assuming that your derivation of the gradient is correct, you are using: <code>=-</code> and you should be using: <code>-=</code>. Instead of updating <code>theta</code>, you are reassigning it to <code>- (alpha * gradient)</code></p> <p>EDIT (after the above issue was fixed in the code):</p> <p>I ran what the cod...
374
gradient descent implementation
Gradient descent in Java
https://stackoverflow.com/questions/32169988/gradient-descent-in-java
<p>I've recently started the AI-Class at Coursera and I've a question related to my implementation of the gradient descent algorithm.</p> <p>Here's my current implementation (I actually just &quot;translated&quot; the mathematical expressions into Java code):</p> <pre><code> public class GradientDescent { priva...
<p>To solve this issue, it's necessary to normalize the data with this formular: (Xi-mu)/s. Xi is the current training set value, mu the average of values in the current column and s the maximum value minus the minimum value of the current column. This formula will get the training data approximately into a range betw...
375
gradient descent implementation
How is Nesterov&#39;s Accelerated Gradient Descent implemented in Tensorflow?
https://stackoverflow.com/questions/50774683/how-is-nesterovs-accelerated-gradient-descent-implemented-in-tensorflow
<p>The documentation for <a href="https://www.tensorflow.org/api_docs/python/tf/train/MomentumOptimizer" rel="noreferrer"><code>tf.train.MomentumOptimizer</code></a> offers a <code>use_nesterov</code> parameter to utilise Nesterov's Accelerated Gradient (NAG) method.</p> <p>However, NAG requires the gradient at a loca...
<p><strong>TL;DR</strong></p> <p>TF's implementation of Nesterov is indeed an approximation of the original formula, valid for high values of momentum.</p> <p><strong>Details</strong></p> <p>This is a great question. In the paper, the NAG update is defined as</p> <pre><code>v<sub>t+1</sub> = μ.v<sub>t</sub> - λ.∇f(...
376
gradient descent implementation
Implementing numba for word2vec gradient descent but getting LoweringError
https://stackoverflow.com/questions/48698936/implementing-numba-for-word2vec-gradient-descent-but-getting-loweringerror
<p>I am running gradient descent for word2vec and would like to implement numba to speed up the training. </p> <p>EDIT: It seems the real error is this </p> <blockquote> <p>NotImplementedError: unsupported nested memory-managed object</p> </blockquote> <p>This is a subsequent error: </p> <pre><code>raise NotImple...
<p>As the error message hints at, lists in numba have only partial support. They can't contain "memory-managed" objects, which means they can only hold scalar, primitive types - for example:</p> <pre><code>@njit def list_first(l): return l[0] list_first([1, 2, 3]) # Out[65]: 1 list_first([[1], [2]]) # LoweringEr...
377
gradient descent implementation
Implementation of gradient descent blowing up to infinity?
https://stackoverflow.com/questions/68356680/implementation-of-gradient-descent-blowing-up-to-infinity
<p>This is how I generated the training data for my Linear Regression.</p> <pre><code>!pip install grapher, numpy from grapher import Grapher import matplotlib.pyplot as plt import numpy as np # Secret: y = 3x + 4 # x, y = [float(row[0]) for row in rows], [float(row[5]) for row in rows] x, y = [a for a in range(-20...
<p>Now that I see, the main problem is with the learning rate. Learning rate of <code>0.01</code> is too high. Keeping it lower than <code>0.00035</code> works well. About <code>0.0002</code> works well and quick. I tried graphing things, and saw it made a lot of difference.</p> <p>With a learning rate of <code>0.00035...
378
gradient descent implementation
Implementation of Gradient (Steepest) Descent
https://stackoverflow.com/questions/3950349/implementation-of-gradient-steepest-descent
<p>I'm looking for some advice on how to go about implementing <a href="http://en.wikipedia.org/wiki/Gradient_descent" rel="nofollow">Gradient (steepest) Descent</a> in C. I am finding the minimum of f(x)=||Ax-y||^2, with A(n,n) and y(n) given.</p> <p>This is difficult in C (I think) because computing the gradient, Δf...
<p>1) Start in 2D, this way you can plot the path of the descent and actually see your algorithm working.</p> <p>2) df/dx = (f(x+h)-f(x-h))/(2*h) if f evaluation is cheap, (f(x+h)-f(x))/h if it is expensive. The choice of h should balance truncation error (mostly with big h) and roundoff error (small h). Typical value...
379
gradient descent implementation
Vectorized gradient descent basics
https://stackoverflow.com/questions/24337887/vectorized-gradient-descent-basics
<p>I'm implementing simple gradient descent in octave but its not working. Here is the data I'm using:</p> <pre><code>X = [1 2 3 1 4 5 1 6 7] y = [10 11 12] theta = [0 0 0] alpha = 0.001 and itr = 50 </code></pre> <p>This is my gradient descent implementation:</p> <pre><code>...
<p>Your Batch gradient descent implementation seems perfectly fine to me. Can you be more specific on what is the error you are facing. Having said that, for your question Is that the correct way to test the hypothesis? [h(x) = theta' * x]. Based on the dimensions of your test set here, you should test it as h(x) = X*t...
380
gradient descent implementation
sklearn: Hyperparameter tuning by gradient descent?
https://stackoverflow.com/questions/43420493/sklearn-hyperparameter-tuning-by-gradient-descent
<p>Is there a way to perform hyperparameter tuning in scikit-learn by gradient descent? While a formula for the gradient of hyperparameters might be difficult to compute, numerical computation of the hyperparameter gradient by evaluating two close points in hyperparameter space should be pretty easy. Is there an existi...
<p>The calculation of the gradient is the least of problems. At least in times of advanced <a href="https://en.wikipedia.org/wiki/Automatic_differentiation" rel="noreferrer">automatic differentiation</a> software. (Implementing this in a general way for all sklearn-classifiers of course is not easy)</p> <p>And while t...
381
gradient descent implementation
Understanding gradient of gradient descent algorithm in Numpy
https://stackoverflow.com/questions/33621399/understanding-gradient-of-gradient-descent-algorithm-in-numpy
<p>I'm trying to figure out the python code for multivariate gradient descent algorithm, and have found several several implementations like this:</p> <pre><code>import numpy as np # m denotes the number of examples here, not the number of features def gradientDescent(x, y, theta, alpha, m, numIterations): xTrans...
<p>The code is actually very straightforward, it would be beneficial to spend a bit more time to read it.</p> <ul> <li><code>hypothesis - y</code> is the first part of the square loss' gradient (as a vector form for each component), and this is set to the <code>loss</code> variable. The calculuation of the hypothesis ...
382
gradient descent implementation
Gradient descent Search implemented in matlab theta1 incorrect
https://stackoverflow.com/questions/52862164/gradient-descent-search-implemented-in-matlab-theta1-incorrect
<p>I studied the Machine learning course taught by Prof. Andrew Ng. <a href="http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=MachineLearning&amp;doc=exercises/ex2/ex2.html" rel="nofollow noreferrer">This is the link</a> </p> <p>I try to implement the 1st assignment of this course. <strong>Exercis...
<p>You get wrong results because you write long unnecessary code that is easily prone to bugs, that is exactly why we have matlab:</p> <pre><code>clear x = load('d:/ex2x.dat'); y = load('d:/ex2y.dat'); figure(1), clf, plot(x, y, '*'), xlabel('Age in years'), ylabel('Height in meters') m = length(y); % store the numb...
383
gradient descent implementation
Using tf.py_func as loss function to implement gradient descent
https://stackoverflow.com/questions/55266743/using-tf-py-func-as-loss-function-to-implement-gradient-descent
<p>I'm trying to use <code>tf.train.GradientDescentOptimizer().minimize(loss)</code> to get the minimum value of the loss function. But the loss function is very complicated and I need to use numpy to calculate the value, so I use <code>tf.py_func</code> to change the output to tensor again and try to use gradient desc...
384
gradient descent implementation
How do I implement stochastic gradient descent from the following gradient descent code? (trouble adding a random sample)
https://stackoverflow.com/questions/54523274/how-do-i-implement-stochastic-gradient-descent-from-the-following-gradient-desce
<p>I'm struggling to make the gradient descent function I already have into one for stochastic gradient descent. I have the following:</p> <pre><code> gd &lt;- function(f, grad, y, X, theta0, npars, ndata, a, niters) { theta &lt;- matrix(data=NA, nrow=niters, ncol=npars) cost &lt;- vector(mode="numeric", length=n...
385
gradient descent implementation
What is wrong with my gradient descent implementation (SVM classifier with hinge loss)
https://stackoverflow.com/questions/79055573/what-is-wrong-with-my-gradient-descent-implementation-svm-classifier-with-hinge
<p>I am trying to implement and train an SVM multi-class classifier from scratch using python and numpy in jupyter notebooks.</p> <p>I have been using the CS231n course as my base of knowledge, especially this page: <a href="https://cs231n.github.io/optimization-1/" rel="nofollow noreferrer">https://cs231n.github.io/op...
<p>To anyone who runs across this thread, I solved my problem. Turns out, I was misreading the formula, and had the locations of two of the terms mixed up. The comments in my original code were actually correct. The variables wj_xi and wyi_xi should actually be defined like this (in both the gradient and the loss metho...
386
gradient descent implementation
how can i implement plain gradient descent with keras?
https://stackoverflow.com/questions/58759354/how-can-i-implement-plain-gradient-descent-with-keras
<p>I am a student learning deep learning. These days, I am trying to see the plot of a loss function with respect to weights and bias. Especially, I want to apply gradient descent method to get smooth lines rather than random characteristics orginated from other optimizers.</p> <p>Keras framework offers various types ...
<p>I think setting batch_size = n_samples is not sufficient, u have to set momentum=0, nesterov=False, inspite of this i didnt see it gets stuck in to local optima, which means it will still has a way to respawn so that it breakout and find new optima</p>
387
gradient descent implementation
Convert stochastic gradient descent to mini batch gradient descent
https://stackoverflow.com/questions/64172528/convert-stochastic-gradient-descent-to-mini-batch-gradient-descent
<p>I need to convert a training with stochastic gradient descent in mini batch gradient descent. I report a simple example of a neural network with only 4 training sample so we can for example implement a batch size of 2 only for understand how to change the training part.</p> <p>This is the simple example of a net tha...
<p>Check <a href="https://stats.stackexchange.com/questions/117919/what-are-the-differences-between-epoch-batch-and-minibatch">What are the differences between 'epoch', 'batch', and 'minibatch'?</a>.</p> <p>In your case your input is random. You could split your training data in 2 mini-batches. Run two times your for l...
388
gradient descent implementation
Numpy Overflow Error when implementing gradient descent algorithm
https://stackoverflow.com/questions/74264293/numpy-overflow-error-when-implementing-gradient-descent-algorithm
<p>I was trying to learn the gradient descent algorithm purely for fun and I made some code that seems to work event though it get stuck in a local minimum sometimes</p> <p>but sometimes when I run it works and sometimes it gives an overflow error</p> <h3>Output when failed:</h3> <pre><code>[2 4 6 8] E:\Projects\Python...
<p>Numpy arrays cannot auto promote like Python built-in types. This is because they are fixed to a Data Type to make operations faster which is a reason NumPy is good. Although like in your case, you lose the flexibility that when a number overshoots it automatically changes its datatype to accommodate your needs.</p>...
389
gradient descent implementation
Trying to Implement Gradient Descent Algorithm with Fixed Step Size
https://stackoverflow.com/questions/67466602/trying-to-implement-gradient-descent-algorithm-with-fixed-step-size
<p>I am trying to implement the gradient descent algorithm with fixed step size on MATLAB.\</p> <pre><code>syms x1 x2 x3 x4 f(x1,x2,x3,x4) = (x1+10*x2)^2 + 5*(x3-x4)^2 + (x2-2*x3)^4 + 10*(x1-x4)^4 ; grad_f = gradient(f); xk = [3;-1;0;1]; while euclidian(grad_f(xk(1),xk(2),xk(3),xk(4)),4) &gt; 0.01 xk = xk- 0.001*gr...
<p>Frame the problem as a vector dot product to take advantage of MATLAB's built-in linear algebra routines, which are much faster than explicit loops:</p> <pre><code>function euclidean_norm = euclidean(x) euclidean_norm = x' * x; end </code></pre> <p>You don't need the <code>size</code> parameter (even in your exi...
390
gradient descent implementation
Implementing a gradient descent from a single point in Numpy?
https://stackoverflow.com/questions/70040011/implementing-a-gradient-descent-from-a-single-point-in-numpy
<p>I have encountered this question in an online test. I am looking for advice on what approach to use, rather than a full solution.</p> <p>You are walking on a mountain. You want to descend to the lowest point on the mountain and choose to apply a gradient descent to plan your route. the height at any location x,y is ...
<p>wasnt able to figure out an array solution yet,</p> <p>reverting to SymPy library I got this code to retrieve a list of</p> <p>dx, dy at point x,y given your function:</p> <pre><code>import sympy as sym from sympy.parsing.sympy_parser import parse_expr class FunZ: def __init__(self, f): self.x...
391
gradient descent implementation
Gradient Descent Matlab implementation
https://stackoverflow.com/questions/21799435/gradient-descent-matlab-implementation
<p>I have gone through many codes in stack overflow and made my own on same line. there is some problem with this code I am unable to understand. I am storing the value theta1 and theta 2 and also the cost function for analysis purpose. The data for x and Y can be downloaded from this <a href="http://openclassroom.sta...
<p>I have been trying to implement the iterative step with matrices and vectors (i.e not update each parameter of theta). Here is what I came up with (only the gradient step is here):</p> <pre><code>h = X * theta; # hypothesis err = h - y; # error gradient = alpha * (1 / m) * (X' * err); # update the gradient thet...
392
gradient descent implementation
Implementation of gradient descent is very inefficient and does not work in all cases
https://stackoverflow.com/questions/75255159/implementation-of-gradient-descent-is-very-inefficient-and-does-not-work-in-all
<p>I am supposed to implement gradient descent for linear regression. Here is the implementation:</p> <pre><code>class SimpleLinearRegressionModel(): def __init__(self, x, y, theta, alpha): self.x = x self.y = y self.theta = theta self.alpha = alpha ''' Equation for the reg...
<p>A few things are obvious immediately:</p> <ol> <li><p>You are running <code>self.h(self.x)</code> three times in every loop iteration, once should be enough. Try to store and re-use the intermediate values of your calculation, also for <code>self.h(self.x) - self.y</code> etc. You may need to combine <code>J()</code...
393
gradient descent implementation
Stochastic Gradient Descent on Custom Functions
https://stackoverflow.com/questions/71120229/stochastic-gradient-descent-on-custom-functions
<p>I am working with the R programming language. I am trying to perform Stochastic Gradient Descent on custom defined functions.</p> <p>For instance, here is an example of using Gradient Descent to optimize a custom function (using the well established &quot;pracma&quot; library):</p> <pre><code># define function: R...
394
gradient descent implementation
Implementing stochastic gradient descent
https://stackoverflow.com/questions/64739896/implementing-stochastic-gradient-descent
<p>I am trying to implement a basic way of the stochastic gradient desecent with multi linear regression and the L2 Norm as loss function.</p> <p>The result can be seen in this picture:</p> <p><a href="https://i.sstatic.net/yB5My.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/yB5My.png" alt="enter image...
<p>to illustrate my comment,</p> <pre><code>def SGD(x,y,n,learning_rate): theta = np.array([[0],[0]]) # currently it does exactly one iteration. do more for _ in range(n): for i in range(len(x)): xi = x[i].reshape(1,-1) y_pre = xi@theta theta = theta + learning_...
395
gradient descent implementation
My python implementation of Gradient Descent is not working well
https://stackoverflow.com/questions/77095271/my-python-implementation-of-gradient-descent-is-not-working-well
<p>I am trying to create a Linear regression model that uses batch gradient descent but the error or mse value never decreases. The LinearModel is just a template class that initializes the hyperparameters (step_size=0.001, max_iter=10000, eps=0.001, theta_0=None, verbose=True)</p> <pre><code># The data is stored in an...
<p>So, I was able to get the Code to work as intended.</p> <ul> <li>I had to vectorize the code as much as possible to make it run faster (Gradient Descent and Stochastic Gradient Descent were taking AGES to find the params of training set of shape (18000,7).</li> <li>I was doing some wrong vector calculations in the a...
396
gradient descent implementation
Batch Gradient Descent with Python not converging
https://stackoverflow.com/questions/59406021/batch-gradient-descent-with-python-not-converging
<p>Here's the Jupyter Notebook I used for this practice: <a href="https://drive.google.com/file/d/18-OXyvXSit5x0ftiW9bhcqJrO_SE22_S/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/18-OXyvXSit5x0ftiW9bhcqJrO_SE22_S/view?usp=sharing</a></p> <p>I was practicing simple Linear Regression with <a...
<p>The are many issues with that code.</p> <p>First, the two main issues that are behind the bugs:</p> <p>1) The line</p> <pre><code>temp_1 = theta_1 - alpha * (1 / m) * (matrix_x.transpose() * (theta_0 + theta_1 * matrix_x - matrix_y)).sum() </code></pre> <p>specifically the matrix multiplication <code>matrix_x.tr...
397
gradient descent implementation
Gradient descent algo implementation
https://stackoverflow.com/questions/74258007/gradient-descent-algo-implementation
<p>I am trying question 9.30 in the book 'Convex Optimization' by Boyd. But for some reason I can't make the backtrack line search work. Here is my code:</p> <pre><code>import numpy as np n, m = 100, 200 A = np.random.randn(m, n) a, b = 0.01, 0.5 gtol = 1e-3 def f(x): # return - np.sum(np.log(1-x*x)) - np.sum(np...
<p>Ok I found the issue!</p> <p>I am passing -g and then multiplying a -ive again!</p> <p>thanks.</p>
398
gradient descent implementation
How to Implement Full Batch Gradient Descent with Nesterov Momentum in PyTorch?
https://stackoverflow.com/questions/78102637/how-to-implement-full-batch-gradient-descent-with-nesterov-momentum-in-pytorch
<p>I'm working on a machine learning project in PyTorch where I need to optimize a model using the full batch gradient descent method. The key requirement is that the optimizer should use all the data points in the dataset for each update. My challenge with the existing torch.optim.SGD optimizer is that it doesn't inhe...
<p>The pytorch SGD implementation is actually independent of the batching! It only uses the gradients that were calculated and stored in the parameters <code>.grad</code> attribute in the backward pass. So the batch size used for calculations and the batch size used for optimization are decoupled.</p> <p>You can now ei...
399
transformers
&quot;Monad transformers more powerful than effects&quot; - Examples?
https://stackoverflow.com/questions/31335805/monad-transformers-more-powerful-than-effects-examples
<p>The paper <a href="http://eb.host.cs.st-andrews.ac.uk/drafts/effects.pdf" rel="noreferrer" title="Edwin C. Brady (2013?): &#39;Programming and reasoning with algebraic effects and dependent types&#39;">"Programming and reasoning with algebraic effects and dependent types" by Edwin C. Brady</a> on effects in Idris co...
<p>Continuations can be modelled as monads, using CPS, but they are not algebraic effects as they cannot be modelled using Lawvere theories. See Martin Hyland and John Power, 2007, <a href="https://www.dpmms.cam.ac.uk/~martin/Research/Publications/2007/hp07.pdf">The Category Theoretic Understanding of Universal Algebr...
400
transformers
mtl, transformers, monads-fd, monadLib, and the paradox of choice
https://stackoverflow.com/questions/2769487/mtl-transformers-monads-fd-monadlib-and-the-paradox-of-choice
<p>Hackage has several packages for monad transformers:</p> <ul> <li><a href="http://hackage.haskell.org/package/mtl" rel="noreferrer">mtl</a>: Monad transformer library</li> <li><a href="http://hackage.haskell.org/package/transformers" rel="noreferrer">transformers</a>: Concrete functor and monad transformers</li> <l...
<p>A bunch of them are almost completely equivalent:</p> <ul> <li><code>mtl</code> uses GHC extensions, but <code>transformers</code> is Haskell 98.</li> <li><code>monads-fd</code> and <code>monads-tf</code> are add-ons to <code>transformers</code>, using functional dependencies and type families respectively, both pr...
401
transformers
Transformer: cannot import name &#39;AutoModelWithLMHead&#39; from &#39;transformers&#39;
https://stackoverflow.com/questions/64112358/transformer-cannot-import-name-automodelwithlmhead-from-transformers
<p>I was referring to this answer from stackoverflow but I can't get any leads regarding my problem: [https://stackoverflow.com/questions/63141267/importerror-cannot-import-name-automodelwithlmhead-from-transformers][1]</p> <p>This is the code that I ran:</p> <pre><code>import transformers from transformers import Auto...
<p>just make sure you installed the transformers using its official git link</p> <pre><code>pip install git+https://github.com/huggingface/transformers </code></pre> <p>and not by using pypi</p> <pre><code>pip install transformers </code></pre> <p>coz there are few sub-libraries such as <code>TFLayoutLMForSequenceClass...
402
transformers
Where does hugging face&#39;s transformers save models?
https://stackoverflow.com/questions/61798573/where-does-hugging-faces-transformers-save-models
<p>Running the below code downloads a model - does anyone know what folder it downloads it to?</p> <pre><code>!pip install -q transformers from transformers import pipeline model = pipeline('fill-mask') </code></pre>
<p><strong>Update 2023-05-02:</strong> The cache location has changed again, and is now <strong><code>~/.cache/huggingface/hub/</code></strong>, as reported by @Victor Yan. Notably, the sub folders in the <code>hub/</code> directory are also named similar to the cloned model path, instead of having a SHA hash, as in pr...
403
transformers
Avoiding lift with monad transformers
https://stackoverflow.com/questions/9054731/avoiding-lift-with-monad-transformers
<p>I have a problem to which a stack of monad transformers (or even one monad transformer) over <code>IO</code>. Everything is good, except that using lift before every action is terribly annoying! I suspect there is really nothing to do about that, but I thought I'd ask anyway.</p> <p>I am aware of lifting entire blo...
<p>For all the standard <a href="http://hackage.haskell.org/package/mtl">mtl</a> monads, you don't need <code>lift</code> at all. <code>get</code>, <code>put</code>, <code>ask</code>, <code>tell</code> — they all work in any monad with the right transformer somewhere in the stack. The missing piece is <code>IO</code>, ...
404
transformers
Huggingface transformers: cannot import BitsAndBytesConfig from transformers
https://stackoverflow.com/questions/75563949/huggingface-transformers-cannot-import-bitsandbytesconfig-from-transformers
<p>Following through the <a href="https://huggingface.co/docs/transformers/main/main_classes/quantization" rel="noreferrer">Huggingface quantization guide</a>, I installed the following:</p> <pre class="lang-bash prettyprint-override"><code>pip install transformers accelerate bitsandbytes </code></pre> <p>(It yielded t...
<p>BitsAndBytesConfig was <a href="https://github.com/huggingface/transformers/commit/3668ec17165dbb7823f3bc7e190e1733040c3af8" rel="noreferrer">added only recently</a>, and the latest release dates back to earlier.</p> <p>The online documentation is generated from the source’s mdx, so it sometimes references things th...
405
transformers
Monad Transformers vs Passing parameters to functions
https://stackoverflow.com/questions/12968351/monad-transformers-vs-passing-parameters-to-functions
<p>I am new to Haskell but understand how Monad Transformers can be used. Yet, I still have difficulties grabbing their claimed advantage over passing parameters to function calls.</p> <p>Based on the wiki <a href="http://www.haskell.org/haskellwiki/Monad_Transformers_Explained" rel="noreferrer">Monad Transformers Exp...
<p>Let's say that we're writing a program that needs some configuration information in the following form:</p> <pre><code>data Config = C { logFile :: FileName } </code></pre> <p>One way to write the program is to explicitly pass the configuration around between functions. It would be nice if we only had to pass it t...
406
transformers
Problem loading transformers; ModuleNotFoundError: No module named &#39;transformers&#39;
https://stackoverflow.com/questions/79031959/problem-loading-transformers-modulenotfounderror-no-module-named-transformers
<p>I want to use some of the models available through huggingface. I am having the hardest time even getting started. Can anyone help me identify and solve this problem?</p> <p>I am using Kubuntu 24.04.</p> <hr /> <p>First, I create and activate a virtual environment within which to install transformers.</p> <pre><code...
<p>I recommend you run your code in the terminal that your virtual environment is activated</p>
407
transformers
Monad transformers libraries - which one to use?
https://stackoverflow.com/questions/5797091/monad-transformers-libraries-which-one-to-use
<p>There are many different monad transformers libraries on Hackage. A few seem to get more attention than the others. To name a few: mtl (current version depending on transformers for some reason), transformers, monadLib, monads-tf, mtlx, contstuff.</p> <p>Which one should be preferred and why? What are their unique ...
<p>The <a href="http://haskell.org/platform" rel="noreferrer">Haskell Platform</a> specifies <a href="http://hackage.haskell.org/package/mtl" rel="noreferrer"><code>mtl</code></a> and <a href="http://hackage.haskell.org/package/transformers" rel="noreferrer"><code>transformers</code></a> as standard. </p> <p>If you're...
408
transformers
Using transformers-cli on Windows?
https://stackoverflow.com/questions/61579248/using-transformers-cli-on-windows
<p>I can't figure out how to use transformers-cli on Windows. I got it working on Google Colab, and am using it in the meantime.</p> <p>[EDIT]</p> <p>Here's the process that I'm going through, what I expect, and what is happening:</p> <p><strong>I'm on a Windows System (brackets are the exact commands I'm typing int...
<p>All you have to do is to locate the script and launch it. It won't be added to the $PATH automatically. In my python interpreter installation on Windows 10 (not anaconda just python), it was installed in the <code>Scripts</code> folder of my python interpreter directory. You have to launch it with the python interpr...
409
transformers
Transformers Pipeline from Huggingface
https://stackoverflow.com/questions/61073049/transformers-pipeline-from-huggingface
<p>I am trying out the transformers pipeline from huggingface:</p> <p><a href="https://github.com/huggingface/transformers#installation" rel="nofollow noreferrer">https://github.com/huggingface/transformers#installation</a></p> <p><a href="https://i.sstatic.net/j8p4E.png" rel="nofollow noreferrer"><img src="https://i.s...
410
transformers
Transformers v4.x: Convert slow tokenizer to fast tokenizer
https://stackoverflow.com/questions/65431837/transformers-v4-x-convert-slow-tokenizer-to-fast-tokenizer
<p>I'm following the transformer's pretrained model <a href="https://huggingface.co/joeddav/xlm-roberta-large-xnli?text=%0A&amp;candidate_labels=&amp;multi_class=true" rel="noreferrer">xlm-roberta-large-xnli</a> example</p> <pre><code>from transformers import pipeline classifier = pipeline(&quot;zero-shot-classificatio...
<p>According to Transformers <code>v4.0.0</code> <a href="https://github.com/huggingface/transformers/releases/tag/v4.0.0" rel="noreferrer">release</a>, <code>sentencepiece</code> was removed as a required dependency. This means that</p> <blockquote> <p>&quot;The tokenizers that depend on the SentencePiece library will...
411
transformers
Transformers AutoModelForCasualLM cannot be imported
https://stackoverflow.com/questions/75191536/transformers-automodelforcasuallm-cannot-be-imported
<p>I am trying to follow <a href="https://towardsdatascience.com/run-bloom-the-largest-open-access-ai-model-on-your-desktop-computer-f48e1e2a9a32" rel="nofollow noreferrer">this article</a> to use the <code>AutoModelForCasualLM</code> from <code>transformers</code> to generate text with bloom. But I keep getting an err...
<p>This is because you are using wrong class name this class name not exist in the version of the Transformers library you are using. The correct class name is AutoModelForCausalLM (note the correct spelling of &quot;Causal&quot;). Try this :</p> <p><code>from transformers import AutoTokenizer,AutoModelForCausalLM</cod...
412
transformers
Transformers in Android Studio Chaquopy
https://stackoverflow.com/questions/78420548/transformers-in-android-studio-chaquopy
<pre><code>chaquopy { productFlavors { getByName(&quot;py310&quot;) { version = &quot;3.10&quot; } getByName(&quot;py311&quot;) { version = &quot;3.11&quot; } } defaultConfig { pip { // Install only the pipeline module from transformers with version 4.12.0 in...
<p>Chaquopy's current options for <code>transformers</code> are listed on <a href="https://github.com/chaquo/chaquopy/issues/607" rel="nofollow noreferrer">its issue tracker</a>:</p> <ul> <li>tokenizers 0.10.3 (compatible with <code>transformers==4.15.0</code>)</li> <li>tokenizers 0.7.0 (compatible with <code>transform...
413
transformers
Huggingface Transformers Conda Install issue
https://stackoverflow.com/questions/71754258/huggingface-transformers-conda-install-issue
<p>conda by default installing transformers 2.x however pip installs 4.x by default which is what I want but via conda.</p> <p>If I install by specifying the latest distribution file from conda-forge… <code>conda install https://anaconda.org/conda-forge/transformers/4.16.2/download/noarch/transformers-4.16.2-pyhd8ed1ab...
<p>Just tried installing transformers in the <code>venv</code> that I will be working on as follows</p> <pre><code>conda install transformers </code></pre> <p>And it installed the version <code>transformers-4.18.0</code>.</p> <p>If one wants to install specifically from the channel <code>huggingface</code>, then do the...
414
transformers
cannot import name &#39;GPT2ForQuestionAnswering&#39; from &#39;transformers&#39;
https://stackoverflow.com/questions/75617250/cannot-import-name-gpt2forquestionanswering-from-transformers
<p><a href="https://i.sstatic.net/wZejL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wZejL.png" alt="enter image description here" /></a></p> <blockquote> <p>1 import pandas as pd 2 import torch ----&gt; 3 from transformers import GPT2Tokenizer, GPT2ForQuestionAnswering, AdamW 4 from transformers impo...
<p>Is your package up to date? I had the same issue so upgraded the package, and the error went away</p> <p>Try:</p> <pre><code>pip install transformers --upgrade </code></pre>
415
transformers
cannot import name &#39;TFBertForQuestionAnswering&#39; from &#39;transformers&#39;
https://stackoverflow.com/questions/62907901/cannot-import-name-tfbertforquestionanswering-from-transformers
<p>Currently I am using transformers(3.0.2) and python(3.7.3) which encountered the below error:</p> <blockquote> <p><strong>cannot import name 'TFBertForQuestionAnswering' from 'transformers'</strong></p> </blockquote> <pre><code>from transformers import BertTokenizer, TFBertForQuestionAnswering model = TFBertForQues...
<p>Upgrade your TensorFlow library. It works fine with 2.3.1. version.</p>
416
transformers
Mule ESB: XSLT Transformers or Java Transformers?
https://stackoverflow.com/questions/11421379/mule-esb-xslt-transformers-or-java-transformers
<p>Is there any performance improvement if I use a custom Java transformer in place of an XSLT transformer in Mule?</p> <p>I have a cxf proxy-service and proxy-client pattern, and my transformers are being used to change the payload so that it is a valid input for subsequent SOAP web-service calls.</p>
<p>Measure it and see. You should never make a change to your system for performance reasons unless you can measure the effect. Focus your efforts on instrumentation, and good performance will follow naturally.</p>
417
transformers
cannot import &#39;AutoModelForSequenceClassification&#39; from &#39;transformers&#39;
https://stackoverflow.com/questions/66909773/cannot-import-automodelforsequenceclassification-from-transformers
<p><strong>cannot import 'AutoModelForSequenceClassification' from 'transformers'</strong></p> <p>The code is</p> <pre><code>from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline t = AutoTokenizer.from_pretrained('/some/directory') m = AutoModelForSequenceClassification.from_pretrained('...
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>from transformers import AutoModelForSequenceClassification, BertForSequenceClassification from transformers import (XLMRobert...
418
transformers
Can&#39;t load transformers models
https://stackoverflow.com/questions/68528187/cant-load-transformers-models
<p>I have the following problem to load a transformer model. The strange thing is that it work on google colab or even when I tried on another computer, it seems to be version / cache problem but I didn't found it.</p> <pre class="lang-py prettyprint-override"><code>from sentence_transformers import SentenceTransformer...
<p>Which tokenizer version do you have installed? For me it helped to upgrade the tokenizer:</p> <pre><code>pip3 install tokenizers==0.10.3 </code></pre>
419
transformers
Transformers pipeline model directory
https://stackoverflow.com/questions/64310515/transformers-pipeline-model-directory
<p>I'm using the Huggingface's Transformers pipeline function to download the model and the tokenizer, my Windows PC downloaded them but I don't know where they are stored on my PC. Can you please help me? <a href="https://i.sstatic.net/eHRNO.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eHRNO.png" alt...
<p>You can check the default location with:</p> <pre class="lang-py prettyprint-override"><code>import transformers #it is important to load the library before checking! import os os.environ['TRANSFORMERS_CACHE'] </code></pre> <p>In case you want to change the default location, please have a lock at this <a href="https...
420
transformers
can not import tftrainer from transformers
https://stackoverflow.com/questions/78661481/can-not-import-tftrainer-from-transformers
<p>I try to train a GPT2 model on my own data</p> <pre><code>from transformers import GPT2Tokenizer, GPT2LMHeadModel from transformers import TextDataset, DataCollatorForLanguageModeling from transformers import TFTrainer, TFTrainingArguments </code></pre> <p>but I get the error &quot;cannot import name 'TFTrainer' fro...
<p>TFTrainer is a separate package that transformers, so you need to install it separately and do:</p> <p><code>from tftrainer import Trainer, TrainArgument</code></p> <p>This is because TFTrainer is no longer supported by transformers. You could try to install an older version of transformers which still supports it, ...
421
transformers
Cannot import BertModel from transformers
https://stackoverflow.com/questions/62386631/cannot-import-bertmodel-from-transformers
<p>I am trying to import BertModel from transformers, but it fails. This is code I am using</p> <pre><code>from transformers import BertModel, BertForMaskedLM </code></pre> <p>This is the error I get</p> <pre><code>ImportError: cannot import name 'BertModel' from 'transformers' </code></pre> <p>Can anyone help me f...
<p>Fixed the error. This is the code</p> <pre><code>from transformers.modeling_bert import BertModel, BertForMaskedLM </code></pre>
422
transformers
ModuleNotFoundError: no module named &#39;transformers&#39;
https://stackoverflow.com/questions/71012012/modulenotfounderror-no-module-named-transformers
<p>This is my first post and I am new to coding, so please let me know if you need more information. I have been running some AI to generate artwork and it has been working, but when I reloaded it the python script won't work and it is now saying &quot;No module named 'transformers'&quot;. Can anyone help me out? It wa...
<p>Probably it is because you have not installed in your (new, since you've upgraded to colabs pro) session the library transformers. Try to run as first cell the following: <code>!pip install transformers</code> (the &quot;!&quot; at the beginning of the instruction is needed to go into &quot;terminal mode&quot; ). Th...
423
transformers
transformers No module named &#39;keras.engine&#39;
https://stackoverflow.com/questions/78990350/transformers-no-module-named-keras-engine
<p>I have transformers 4.25.1 and Keras 3.4.1 with Python 3.9 under Windows. <code>permutation_importance</code> uses <code>transformers\utils\import_utils.py</code> which produces:</p> <pre><code>line 1095, in _get_module raise RuntimeError( RuntimeError: Failed to import transformers.modeling_tf_utils because of...
<p>I encountered the same issue too, the config is slightly different from yours; the main problem is due to old Python version mismatches with newer versions of <code>tensorflow</code>. Here is my solution:</p> <p>Versions used:</p> <ul> <li>Ubuntu 22.04 LTS</li> <li>Python 3.10.0</li> <li>transformers 4.28.1</li> <li...
424
transformers
Issue installing transformers
https://stackoverflow.com/questions/77413586/issue-installing-transformers
<p>I'm doing a NLP project on vscode &quot; amazon reviews sentiment analyzer&quot; every thing is going ok until I reached the part for importing transformers</p> <p>when I'm installing transformers from pip Im getting this error :</p> <pre><code>error: subprocess-exited-with-error × Preparing metadata (pyproject.t...
<p>You can <a href="https://github.com/huggingface/transformers#with-pip" rel="nofollow noreferrer">read document</a> about how to install this package.</p> <p>You will need to install at least one of <strong>Flax</strong>, <strong>PyTorch</strong>, or <strong>TensorFlow</strong>.</p> <p>When one of those backends has ...
425
transformers
Unable to install sentence-transformers, getting error
https://stackoverflow.com/questions/71083239/unable-to-install-sentence-transformers-getting-error
<p>Running below command after installing python 3.10.</p> <p>pip3 install -U sentence-transformers</p> <ol> <li>List item</li> </ol> <p>ERROR: Cannot install sentence-transformers==0.1.0, sentence-transformers==0.2.0, sentence-transformers==0.2.1, sentence-transformers==0.2.2, sentence-transformers==0.2.3, sentence-tr...
<p>I encountered the same error, here is how I fixed it:</p> <ul> <li>first install torch 1.10.0 using the following</li> </ul> <pre class="lang-sh prettyprint-override"><code>conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch </code></pre> <ul> <li>then install sentence-transformers 2.1.0 by</li>...
426
transformers
Python Error ModuleNotFoundError: No module named &#39;transformers&#39;
https://stackoverflow.com/questions/74607244/python-error-modulenotfounderror-no-module-named-transformers
<p>I'm getting below error when running 'import transformers', even though I have installed in the same vitual env. I'm using python 3.8</p> <pre><code>ModuleNotFoundError: No module named 'transformers' </code></pre> <p>Error:</p> <p><a href="https://i.sstatic.net/7B3Sb.png" rel="nofollow noreferrer">enter image desc...
<p>its resolved now. I just tried to use %pip install transformers==3.4.0, instead of !pip install transformers==3.4.0 in jupyter book, and it worked. I can proceed with the project for now. Although I don't know what I did wrong in my python command line earlier that caused the inconsistency. Will open a new thread.</...
427
transformers
Hugginface transformers module not recognized by anaconda
https://stackoverflow.com/questions/62538079/hugginface-transformers-module-not-recognized-by-anaconda
<p>I am using Anaconda, python 3.7, windows 10.</p> <p>I tried to install transformers by <a href="https://huggingface.co/transformers/" rel="nofollow noreferrer">https://huggingface.co/transformers/</a> on my env. I am aware that I must have either pytorch or TF installed, I have pytorch installed - as seen in anacond...
<p>The problem is that conda only offers the transformers library in version 2.1.1 (<a href="https://anaconda.org/conda-forge/transformers" rel="nofollow noreferrer">repository information</a>) and this version didn't have a <code>pad_to_max_length</code> argument. I'm don't want to look it up if there was a different ...
428
transformers
Cannot import pipeline after successful transformers installation
https://stackoverflow.com/questions/68499238/cannot-import-pipeline-after-successful-transformers-installation
<h2 id="environment-info-f7cj">Environment info</h2> <ul> <li><code>transformers</code> version: 4.9.0</li> <li>Platform: Linux-4.15.0-151-generic-x86_64-with-glibc2.27</li> <li>Python version: 3.9.2</li> <li>PyTorch version (GPU?): 1.7.1+cu101 (False)</li> <li>Tensorflow version (GPU?): 2.5.0 (False)</li> <li>Flax ver...
<p>Maybe presence of both Pytorch and TensorFlow or maybe incorrect creation of the environment is causing the issue. Try re-creating the environment while installing bare minimum packages and just keep one of Pytorch or TensorFlow.</p> <p>It worked perfectly fine for me with the following config:</p> <pre><code> - tra...
429
transformers
Import of transformers package throwing value_error
https://stackoverflow.com/questions/68997701/import-of-transformers-package-throwing-value-error
<p>I have successfully installed transformers package in my Jupyter Notebook from Anaconda administrator console using the command '<code>conda install -c conda-forge transformers</code>'.</p> <p>However when I try to load the transformers package in my Jupyter notebook using '<code>import transformers</code>' command,...
<p>I had similar error which took a whole day to fix.</p> <p>This is causing due to a version mismatch of some of the expected packages by transformers while importing. You can check the specific package details in the transformers folder in your local disk. 2 python files are shown in the location ..Anaconda3\Lib\site...
430
transformers
from transformers import TFBertModel, BertConfig, BertTokenizerFast
https://stackoverflow.com/questions/64823301/from-transformers-import-tfbertmodel-bertconfig-berttokenizerfast
<p>I am having trouble importing TFBertModel, BertConfig, BertTokenizerFast. I tried the latest version of transformers, tokenizer==0.7.0, and transformers.modeling_bert but they do not seem to work. I get the error</p> <p><code>from transformers import TFBertModel, BertConfig, BertTokenizerFast</code></p> <p>ImportE...
<p>Do you have <code>Tensorflow 2</code> installed? The model you are trying to import required Tensorflow</p>
431
transformers
Monad transformers monad duplication
https://stackoverflow.com/questions/16637221/monad-transformers-monad-duplication
<p>I am new to monad transformers, so sorry easy question. I have value <code>val :: MaybeT IO String</code> and function <code>fn :: String -&gt; IO [String]</code>. So after binding, I have <code>val &gt;&gt;= liftM fn :: MaybeT IO (IO [String])</code>. How can I remove duplicate IO monad and get result of type <code...
<p>Use <code>lift</code> (or <code>liftIO</code>) instead of <code>liftM</code>.</p> <pre><code>&gt; :t val &gt;&gt;= lift . fn val &gt;&gt;= lift . fn :: MaybeT IO [String] </code></pre> <p><code>liftM</code> is for applying pure functions in a monad. <code>lift</code> and <code>liftIO</code> are for lifting actions...
432
transformers
R Reticulate transformers library cannot find torch
https://stackoverflow.com/questions/70262279/r-reticulate-transformers-library-cannot-find-torch
<p>Using R and the <code>reticulate</code> package I am trying to use a pre-trained model from Huggingface. This partcular model requires PyTorch and transformers. Both are available in R via reticulate, however even though I can install and load both, the transformers package can't find the PyTorch installation.</p> <...
<p>It looks like reticulate is pointing to miniconda, and you have likely installed PyTorch, etc. in a different environment.</p> <p>Check out which python environment your <code>Pytorch</code> is installed. Then check where your reticulate environment is using <code>Sys.getenv()</code> and look for <code>RETICULATE_PY...
433