How to use sympy to replace a symbol in a derivative?

Hello, good afternoon.

Im trying to use sympy to calc an gradient descent in some symbols and having troubles with index. This algorithm is pretty simple using to calc derivative by hand. Using sympy things gets wierd.

m, b, i, n = symbols("m b i n");
x, y = symbols("x y", cls=sympy.Function);

sumofsquares = sympy.Sum((m * x(i) + b - y(i))^2, (i, 0, n));
print("sum of squares:");
display(sumofsquares);

# derivative of m
dm = sympy.diff(sumofsquares, m);

# derivatime of b
db = sympy.diff(sumofsquares, b);
print("derivative of m:"); display(dm);
print("derivative of b:");

points = Tuple.(eachrow(df));
println(points);
dmf = replace(subs(dm, n, length(points) -1), x, i => points[i].x)

but it fail with the error

ArgumentError: invalid index: i of type Sym

Stacktrace:
 [1] to_index(i::Sym)
   @ Base ./indices.jl:300
 [2] to_index(A::Vector{Tuple{Int64, Int64}}, i::Sym)
   @ Base ./indices.jl:277
 [3] to_indices
   @ ./indices.jl:333 [inlined]
 [4] to_indices
   @ ./indices.jl:325 [inlined]
 [5] getindex(A::Vector{Tuple{Int64, Int64}}, I::Sym)
   @ Base ./abstractarray.jl:1241
 [6] top-level scope
   @ In[91]:3

I don’t know what df is, so can’t run all of this, but maybe you should use @syms to create the symbolic functions. The following works as I think you want:

using SymPy
@syms m b i n x() y()
sumofsquares = sympy.Sum((m * x(i) + b - y(i))^2, (i, 0, n))

# derivative of m
dm = diff(sumofsquares, m)

# derivatime of b
db = diff(sumofsquares, b)
1 Like

I will try the way you did, but the code works for me until last line.

dmf = replace(subs(dm, n, length(points) -1), x, i => points[i].x)

Here I got issues with replace functions and the error says Im using a invalid index, because i is a syms variable

Can you share your df variable?

1 Like

issue is in replace function. All but replace(…) works ok.

Try this:

dm = subs(dm, n=>length(points) - 1).doit()
for (i,r) ∈ enumerate(points)
    dm = subs(dm, x(i-1)=>r.x, y(i-1) => r.y)
end

(It seems you need to expand the sum before you can substitute in for x(i))

1 Like