ValueError: operands could not be broadcast together with shapes (0) (26) when using optimize.curve - curve-fitting

I'm trying to get a best fit line to some data my script generates. This is what I have:
import numpy as np
import scipy as sp
.
.
.
def func(x, a, b, c):
return a*np.exp(-b*x) + c
popt, pcov = sp.optimize.curve_fit(func, numgelt, turnsG)
I keep getting this error:
ValueError: operands could not be broadcast together with shapes (0) (26)
I have checked and the two arrays (numgelt and turnsG) are definitely the same size. I've also ensured that the entries are float. Thank you!

I had the same problem until I realized I had been using lists instead of Numpy arrays. Converting to arrays fixed it for me.

ValueError: operands could not be broadcast together with shapes (0) (26)
implies that first of your arrays is of length 0. From your post it is most obviously the case and the error provoking ValueError.

Related

Julia BoundsError Means

ERROR: BoundsError: attempt to access Tuple{Int64} at index [2]
Stacktrace:
[1] indexed_iterate
# .\tuple.jl:89 [inlined]
When I run my Julia code, it shows this BoundsError. What does this mean and how can I solve it?
My code is to find the size of a Vector{Float64}.
(m,n)=size(c)
where c is a Vector{Float64}.
A Tuple{Int64} is a tuple containing a single element. So the error message is saying that you tried to access element 2 of a one-element tuple.
In Julia, vectors are truly one-dimensional, so size returns only one value (for eg. size(1:10) is just (10,)). When you try to assign that to (m, n), you're trying to extract two values from it, hence the error.
Since you know it's a Vector already, you know that its number of columns is going to be just 1. So you can instead just do n = length(c) to obtain the number of elements c contains.

Control print order of matrix terms in Sympy

I have a matrix addition with several terms that I want to display in a Jupyter Notebook. I need the order of terms to match the standard notation - in my case, of linear regression. But, the terms do not, by default, appear in the correct order for my purpose, and I would like to ask how to control the order of display of matrices in a matrix addition (MatAdd) term in Sympy. For example, here we see that Sympy selects a particular order for the terms, that appears to be based on the values in the Matrix.
from sympy import MatAdd, Matrix
A = Matrix([1])
B = Matrix([0])
print(MatAdd(A, B, evaluate=False))
This gives
Matrix([[0]]) + Matrix([[1]])
Notice the matrix terms do not follow the order of defintion or the variable names.
Is there anything I can do to control the print output order of Matrix terms in a MatAdd expression?
You can use init_printing to chose from a few options. In particular, the order keyword should control how things are shown on the screen vs how things are stored in SymPy objects.
Now comes the differences: by setting init_printing(order="none") printers behave differently. I believe this is some bug.
For example, I usually use Latex rendering when using Jupyter Notebook:
from sympy import MatAdd, Matrix, init_printing
init_printing(order="none")
A = Matrix([1])
B = Matrix([0])
add = MatAdd(A, B, evaluate=False)
print(add)
# out: Matrix([[0]]) + Matrix([[1]])
display(add)
# out: [1] + [0]
Here you can see that the latex printer is displaying the elements as they are stored (check add.args), whereas the string printer is not following that convention...

Why some symbolic expressions don´t get simplified?

Hi I was working on a model for oscilation problems with Lagrangian mechanichs for my Classical Mechanics I course.
My problem is the following:
When I try to Simplify some expressions like the one in the image below, sympy just shows the division and doesn´t reduce the expression.
I was wondering whether this is some kind of limitation of SymPy (probably that´s not the case) or is just me missing something.
enter image description here
If SymPy doesn't know enough about the variables (like whether they are positive or zero) then it doesn't make a simplification. For sqrt you will get better results if you indicate that the variables are positive. Alternatively, you can use posify on the expression before attempting the simplification.
>>> from sympy import symbols
>>> x,y = symbols('x y', positive=True)
>>> sqrt(x/y)/sqrt(y/x)
x/y
This would not be true if x were positive and y were negative (in which case the answer would be -x/y)

For loop in Julia. Syntax confusion

I am a complete noob in Julia and its syntax. I am trying to follow this article on semi-definite-programming on Julia.
I would apprecieate if someone can help me figure out what the for loop in In[4] actually does:
for i in 1:m
A[:, (i-1)*n+1:i*n] .= random_mat_create(n)
b[i] = tr(A[:, (i-1)*n+1:i*n]*X_test)
end
To my understanding it should create a vector of matrices A (m of those) as well as an m-dimensional vector b. I am totally confused though on the indexing of A and the indexing of b.
I would like an explanation of the :, (i-1)*n+1:i*n part of this code. The reason I ask here is because I also dont know what to Google or what to search for in Julia documentation.
(i-1)*n+1:i*n creates a range from (i-1)*n + 1 to i*n. For example, if i=2 and n=10, this range becomes 11:20, so A[:, (i-1)*n+1:i*n] will grab all the rows of A (that's what : does), and columns 11-20.
There are two operations there that are not clear to you:
: operator. Consider a Matrix a = zeros(3,3). You could use array slicing operator (similarly to numpy or Matlab) to select the entire second columns as: a[1:end,2]. However, when selecting everything from start to the end those two values can be omitted and hence you can write a[:,2] (this always looked the easiest way for me to remember that)
. (dot) operator. Julia is very careful about what gets vectorized and what not. In numpy or R, vectorizing operations happens kind of always automatically. In Julia you have the control - but with the control comes the responsibility. Hence trying to assign values to the second column by writing a[:, 2] = 5.0 will throw an error because there is vector on the right and a scalar on the left. If you want to vectorize you need to tell that to Julia. Hence the dot operator .= means "perform element-wise assignment". Note that any Julia function or operator, even your own functions can be decorated by such dot .. Since this is a very important language feature have a look at https://docs.julialang.org/en/v1/manual/arrays/#Broadcasting

Double curly-brace syntax in Torch

I am trying to better understand this syntax in Lua when using Torch:
local ten = torch.Tensor{{1,2,3},{4,5,6},{7,8,9}}
for i=1,(#ten)[2] do
print(ten[i][{{2}}])
end
Specifically the line
print(ten[i][{{2}}])
When I run the code, it prints
2
[torch.DoubleTensor of size 1]
5
[torch.DoubleTensor of size 1]
8
[torch.DoubleTensor of size 1]
I am familiar with table literals and their basic syntax, but what is the purpose of wrapping the '2' in double curly-braces, and how does it work in the engine?
The following answer was posted on GitHub when I asked the same question:
https://github.com/torch/torch7/issues/501#issuecomment-171290546
Have a look at this part of the documentation.
When you have single curly-braces, you are creating a selection of the tensor. So ten[{1}] is equivalent to ten[1], which is in turn equivalent to ten:select(1,1). If you have several indices like ten[{1,2}], this is also equivalent to the slower ten[1][2] (because the latter returns 2 times a tensor, whereas the former only returns it once). If you select on a 1D tensor, your output is a number.
When you have double curly-braces, it returns a narrow of the tensor, and a narrowed tensor is always a tensor (even if it only has one element). With double curly-braces, you can specify a range in which the tensor will be narrowed, which is not possible with single curly-braces. For example, you can do ten[{{1,2},1}], which will be a 1D tensor of dimension 2, and if your do ten[{{1,2},{2}}] it will return a 2D tensor of size 2x1.
For more information, have a look at select and narrow.
One last note, the doc for select is not precisely correct, as it's possible to do a select on a 1D tensor, and the output is a number.

Resources