AttributeError: module 'torch' has no attribute 'cmul' - torch

I was trying to do element-wise multiplication of two tensors using the example provided here.
My code:
import torch
x = torch.Tensor([2, 3])
y = torch.Tensor([2, 1])
z = torch.cmul(x, y)
print(z)
It is giving me the following error.
AttributeError: module 'torch' has no attribute 'cmul'
Can anyone tell me why I am getting this error?

I got the solution. Instead of using cmul, I need to use mul. The following code worked for me!
import torch
x = torch.Tensor([2, 3])
y = torch.Tensor([2, 1])
z = torch.mul(x, y)
print(z)
PS: I was using pytorch, not lua.

Because Torch doesnt have this method.
Cmul is a class on its own which is located at torch.legacy.nn which takes Torch as arguments
https://github.com/pytorch/pytorch/blob/master/torch/legacy/nn/CMul.py

try:
z = x.cmul(y)
I think cmul is a method of the class Tensor, not a function...
PS: The exemple in the documentation you gave is written in lua, not python.

Related

how to correctly pass a value to an included function?

I have 2 julia files, alpha.jl and beta.jl.
in alpha.jl, there are 2 functions:
der that returns a derivative using Zygote,
derPlot that plots the function as well as the derivative:
function der(f, x)
y = f'(x)
return y
end
function derPlt(der,z)
plot(f, aspect_ratio=:equal, label="f(x)")
g(f,x₀) = (x -> f(x₀) + f'(x₀)*(x-x₀))
plot!(g(f,x), label="dy",color="magenta")
xlims!(-z,z)
ylims!(-z,z)
end
everything comes out fine when i call these 2 functions in beta.jl, after including the files:
include("alpha.jl")
f(x)=-x^2+2
x = -1.3
derPlt(der(f, x), 6)
However, if i directly enter in a value for the function, the plotted derivative line doesnt update; i.e, if i enter 2.0 instead of passing in some variable named x,
derPlt(der(f, 2.0), 6)
no change is reflected on the plot. New to Julia, trying to understand and fix it.
I think it's because in your derPlt function, you call
plot!(g(f,x),...)
on x instead of the z argument. The problem is then that you define a x = -1.3, the value of which is used inside of derPlt, regardless of what z argument you feed it.
Maybe replace that line with
plot!(g(f,z),...)
and you should be fine.
Seeing as this is a follow up to a question I answered previously I thought I'd have to respond: Benoit is broadly speaking correct, you are running into a scoping issue here, but a few more changes are in order.
Note that your function signature is derPlot(der, z) but then:
You never actually use the der argument in your function body; and
You construct your tangent line as g(f,x₀) = (x -> f(x₀) + f'(x₀)*(x-x₀)) - note that there's no z in there, only an x
Now where does that x come from? In the absence of any x argument being passed to your function, Julia will look for it in the global scope (outside your function). Here, you define x = -1.3, and when you then call derPlt, that's the x that will be used to construct your tangent, irrespective of the z argument you're passing.
Here's a cleaned up and working version:
using Plots, Zygote
function derPlt(f,z)
plot(f, label="f(x)", aspect_ratio = :equal,
xlims = (-5,5), ylims = (-5,5))
g(f,x₀) = (z -> f(x₀) + f'(x₀)*(z-x₀))
plot!(i -> g(f, z)(i), label="dy",color="magenta")
end
f(x)=-x^2+2
derPlt(f, -1.5)
I would encourage you to read the relevant manual section on Scope of Variables to ensure you get an understanding of what's happening in your code - good luck!

InterpND for one dimension

I'm trying to use the function InterpND from openmdao.components.interp_util.interp.
No problem using it for multidimensional data - I can interpolate a 3-D tensor without problems. However I'd also like to use for 1-D data. Not sure what I am doing wrong, but when I try to do something really simple like
import numpy as np
from openmdao.components.interp_util.interp import InterpND
x = np.array([0.,1.,2.,3.,4.])
y = x**2
f = InterpND(points=x, values=y)
I get the following error message:
ValueError: There are 5 point arrays, but values has 1 dimensions
Looking at the InterpND source code it seems like I SHOULD be able to just have x and y as simple 1-D arrays.
Parameters
----------
points : ndarray or tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
The points defining the regular grid in n dimensions. For 1D interpolation, this
can be an ndarray.
values : array_like, shape (m1, ..., mn, ...)
x is a 1D ndarray, y is also a 1D nd array.
This looks like a bug in OpenMDAO V3.7.0 related to the input error checking. Here is a workaround. If you put the 1-D table points into a list, it works without error:
f = InterpND(points=[x], values=y)

Plot of function, DomainError. Exponentiation yielding a complex result requires a complex argument

Background
I read here that newton method fails on function x^(1/3) when it's inital step is 1. I am tring to test it in julia jupyter notebook.
I want to print a plot of function x^(1/3)
then I want to run code
f = x->x^(1/3)
D(f) = x->ForwardDiff.derivative(f, float(x))
x = find_zero((f, D(f)),1, Roots.Newton(),verbose=true)
Problem:
How to print chart of function x^(1/3) in range eg.(-1,1)
I tried
f = x->x^(1/3)
plot(f,-1,1)
I got
I changed code to
f = x->(x+0im)^(1/3)
plot(f,-1,1)
I got
I want my plot to look like a plot of x^(1/3) in google
However I can not print more than a half of it
That's because x^(1/3) does not always return a real (as in numbers) result or the real cube root of x. For negative numbers, the exponentiation function with some powers like (1/3 or 1.254 and I suppose all non-integers) will return a Complex. For type-stability requirements in Julia, this operation applied to a negative Real gives a DomainError. This behavior is also noted in Frequently Asked Questions section of Julia manual.
julia> (-1)^(1/3)
ERROR: DomainError with -1.0:
Exponentiation yielding a complex result requires a complex argument.
Replace x^y with (x+0im)^y, Complex(x)^y, or similar.
julia> Complex(-1)^(1/3)
0.5 + 0.8660254037844386im
Note that The behavior of returning a complex number for exponentiation of negative values is not really different than, say, MATLAB's behavior
>>> (-1)^(1/3)
ans =
0.5000 + 0.8660i
What you want, however, is to plot the real cube root.
You can go with
plot(x -> x < 0 ? -(-x)^(1//3) : x^(1//3), -1, 1)
to enforce real cube root or use the built-in cbrt function for that instead.
plot(cbrt, -1, 1)
It also has an alias ∛.
plot(∛, -1, 1)
F(x) is an odd function, you just use [0 1] as input variable.
The plot on [-1 0] is deducted as follow
The code is below
import numpy as np
import matplotlib.pyplot as plt
# Function f
f = lambda x: x**(1/3)
fig, ax = plt.subplots()
x1 = np.linspace(0, 1, num = 100)
x2 = np.linspace(-1, 0, num = 100)
ax.plot(x1, f(x1))
ax.plot(x2, -f(x1[::-1]))
ax.axhline(y=0, color='k')
ax.axvline(x=0, color='k')
plt.show()
Plot
That Google plot makes no sense to me. For x > 0 it's ok, but for negative values of x the correct result is complex, and the Google plot appears to be showing the negative of the absolute value, which is strange.
Below you can see the output from Matlab, which is less fussy about types than Julia. As you can see it does not agree with your plot.
From the plot you can see that positive x values give a real-valued answer, while negative x give a complex-valued answer. The reason Julia errors for negative inputs, is that they are very concerned with type stability. Having the output type of a function depend on the input value would cause a type instability, which harms performance. This is less of a concern for Matlab or Python, etc.
If you want a plot similar the above in Julia, you can define your function like this:
f = x -> sign(x) * abs(complex(x)^(1/3))
Edit: Actually, a better and faster version is
f = x -> sign(x) * abs(x)^(1/3)
Yeah, it looks awkward, but that's because you want a really strange plot, which imho makes no sense for the function x^(1/3).

IPython, Plotting a Polynomial

I've been working with Sympy for an Interpolation, in which I obtain as a result a 7th degree Polynomial (ax^7 + bx^6 + cx^5 + ...+ h) which I want to Plot, but wen I try to plot it I get errors, for example, if I try:
plt.plot(r,U.subs(x,r))
where r = np.linspace(0,20,num=100) and U = Polynomial(x);
the result is an error message: ValueError: sequence too large; must be smaller than 32, I obtain MemoryError: if I try `r = np.arange(20)'. The only way I could plot it is with a for cycle, substituting one by one and saving it in another variable as a list. So my question is, what is wrong with the first's inputs? is there an easy way to plot a polynomial?
Welcome to SO!
The subs() method is not meant to be used with numpy arrays. lambdify() does what you want. Try:
import numpy as np
import matplotlib.pyplot as plt
import sympy as sy
sy.init_printing() # nice formula rendering in IPython
x = sy.symbols("x", real=True)
# the sample polynomial:
pp = x**3 + 3*x**2 - 6*x - 8
# Convert expression function usable with numpy array:
f_pp = sy.lambdify(x, pp, modules=np)
# Do the plotting:
x_n = np.linspace(-5, 2, 500)
y_n = f_pp(x_n) # evaluate all x_n
fg, ax = plt.subplots(1, 1)
ax.plot(x_n, y_n)
fg.canvas.draw()
plt.show()
The parameter modules=np ensures, that numpy is used for functions in the expression (e.g., sin() => np.sin()). In this example, it is not explicitly needed.
PS: If you include a runnable example in your question, it makes live much easier for potential answerers.

Formatter error from sympy in ipython notebook

I have the following Sympy related code in iPython Notebook:
from sympy import *
init_printing()
...
define constants
c, d, e, f = symbols("c, d, e, f")
...
define two matrices
v = Matrix(2,1,[1,1])
w = Matrix(2,1,[2,3])
define symbolic matrices
v, v1, v2 = symbols("v, v1, v2")
v = Matrix(2,1, [v1, v2])
w, w1, w2 = symbols("w, w1, w2")
w = Matrix(2,1, [w1, w2])
addition of symbolic vectors v & w
v + w
results in the following error message
/home/ron/anaconda/lib/python2.7/site-packages/IPython/core/formatters.py:239: FormatterWarning: Exception in image/png formatter:
\left[\begin{smallmatrix}v_{1} + w_{1}\\v_{2} + w_{2}\end{smallmatrix}\right]
^
Expected "\right" (at char 6), (line:1, col:7)
FormatterWarning,
and then produces the correct answer
[v1+w1v2+w2]
The interesting thing is that if I re-execute the cell the error message goes away. I've tried the same code in ipython qtconsole with identical results. Is this a bug or just poor coding on my part?
After further searching I tried the following in the first cell:
from IPython.display import display
from sympy.interactive import printing
printing.init_printing(use_latex='mathjax')
from __future__ import division
import sympy as sym
from sympy import *
This eliminates the above errors so far.
New cell from SymPy: Open Source Symbolic Mathematics on nbviewer
This is a bug, which has been fixed in the git version of SymPy. You can safely ignore it. It will only be an issue if you export your notebook to a format that uses png for the math. If you want to suppress the error entirely, you can use init_printing(use_latex='mathjax').

Resources