How can I make this multiplication much simpler with pytorch? - pytorch

I want to multiply two matrix like this(scalar multiplication).
But this method looks dumb. How can I make this much simpler?
A.size # B * S * V
B.size # B
A * B.unsqueeze(1).unsqueeze(2).expand_as(A)

Related

How to calculate Covariance and Correlation in Python without using cov and corr?

How can we calculate the correlation and covariance between two variables without using cov and corr in Python3?
At the end, I want to write a function that returns three values:
a boolean that is true if two variables are independent
covariance of two variables
correlation of two variables.
You can find the definition of correlation and covariance here:
https://medium.com/analytics-vidhya/covariance-and-correlation-math-and-python-code-7cbef556baed
I wrote this part for covariance:
'''
ans=[]
mean_x , mean_y = x.mean() , y.mean()
n = len(x)
Cov = sum((x - mean_x) * (y - mean_y)) / n
sum_x = float(sum(x))
sum_y = float(sum(y))
sum_x_sq = sum(xi*xi for xi in x)
sum_y_sq = sum(yi*yi for yi in y)
psum = sum(xi*yi for xi, yi in zip(x, y))
num = psum - (sum_x * sum_y/n)
den = pow((sum_x_sq - pow(sum_x, 2) / n) * (sum_y_sq - pow(sum_y, 2) / n), 0.5)
if den == 0: return 0
return num / den
'''
For the covariance, just subtract the respective means and multiply the vectors together (using the dot product). (Of course, make sure whether you're using the sample covariance or population covariance estimate -- if you have "enough" data the difference will be tiny, but you should still account for it if necessary.)
For the correlation, divide the covariance by the standard deviations of both.
As for whether or not two columns are independent, that's not quite as easy. For two random variables, we just have that $\mathbb{E}\left[(X - \mu_X)(Y - \mu_Y)\right] = 0$, where $\mu_X, \mu_Y$ are the means of the two variables. But, when you have a data set, you are not dealing with the actual probability distributions; you are dealing with a sample. That means that the correlation will very likely not be exactly $0$, but rather a value close to $0$. Whether or not this is "close enough" will depend on your sample size and what other assumptions you're willing to make.

How to ignore sympy.solve complex solutions

I have been looking for an answer now and I can't find a solution. I am trying to use sympy.solve in Python 3 and I only want to see the real roots and all positive answers.
Sympy is able to solve what equation I want, but It shows a bunch of nonsense as the other answers. I have tried some of the other methods I found like solveset but they seem to still show the complex solutions
Image of Sympy solution
This is my code if that helps:
h, rho_c_s, T_c_s, k, pi, M, M_sun, m_H, m_e, mu_e = symbols(
r"h,\rho_\odot,T_\odot,k,\pi,M,M_\odot,m_H,m_e,\mu_e",positive=True,real=True)
rho_c = rho_c_s * (M / M_sun)**(-2 / 7)
T_c = T_c_s * (M / M_sun)**(4 / 7)
expr1 = (h**2) / (20 * m_e) * (3 / pi)**(2 / 3) * (rho_c /
(mu_e * m_H))**(5 / 3)
expr2 = (rho_c * k * T_c) / (mu_e * m_H)
expr = expr1 - expr2
eqn = Eq(expr, 0)
soln = solve(eqn, M, simplify=True,real=True,positive=True,)
init_printing()
soln
I appreciate your help.
Thanks
Well I figured it out.
You want to do:
soln[0]
And it will only give you:
Solution
Complex solutions are normal and intended. To hide the complex portions look here:
https://stackoverflow.com/a/73669399/11468876

How to make a difference between two function close to zero through iteration?

I need to construct a loop (simulation) that will iterate a certain number of times and display a value of warrant once the new firm value is close to the guess firm value. Specifically, the idea is to start out with a guess for the firm value (for example the stock price multiplied by the number of shares). Then you value the warrant as a call option (the code below) on this value multiplied by dilution factor, using the same volatility as the vol of the share price. You recompute then the value of the firm (number of shares times share price plus number of warrants times warrant price). This value will be different from the value of the firm you started with. Then you redo the procedure and after a few iterations you will see that the difference in values of the firm tends to zero. For this, I have a following code, but what I get is the following:
TypeError: 'int' object is not subscriptable
Please, help me to figure out the error given the code below:
def bsm_call_value(S0, K, T, r, sigma):
from math import log, sqrt, exp
from scipy import stats
S0 = float(S0)
d1 = (log(S0 / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
d2 = (log(S0 / K) + (r - 0.5 * sigma ** 2) * T) / (sigma * sqrt(T))
value = (S0 * stats.norm.cdf(d1, 0.0, 1.0) - K * exp(-r * T) *stats.norm.cdf(d2, 0.0, 1.0))
return value
def warrant_1unobservable(S0, K, T, r, sigma, k, N, M, Iteration):
for i in range(1, Iteration):
Guess_FirmValue = S0*N
dilution = N/(N +k*M)
warrant[i] = bsm_call_value(Guess_FirmValue[i]/N,100,1,0.1,0.2)*dilution
New_FirmValue[i] = Guess_FirmValue[i]+ warrant[i]
Guess_FirmValue[i] - New_FirmValue[i] == 0
return warrant
print(warrant_1unobservable(100,100,1,0.1,0.2,1,100,10, 1000))
I'm not really a python expert and I'm not familiar with the algorithm you're using, but I'll point out a few things that could be causing the issue.
1) In warrant_1observable, you first assign Guess_FirmValue a scalar value (since both S0 and N are scalars the way you call the function), and then you try to access it with an index as Guess_FirmValue[i]. My guess would be that this is causing the error you displayed, since you're trying to index/subscript a variable that, based on your function input values, would be an integer.
2) Both warrant[i] and New_FirmValue[i] are attempts to assign values to an indexed position in a list, but nowhere do you initialize these variables as lists. Lists in python are initialized as warrant = []. Also, it's likely that you would have to either a) pre-allocate the lists to the correct size based on the Iteration or b) use append to push new values onto the back of the list.
3) Guess_FirmValue[i] - New_FirmValue[i] == 0 is a vacuous line of code. All this does is evaluate to either true or false, while performing no other operation. I imagine you're trying to check if the values are equal and then return, but that won't happen even if you stick this in an if statement. It is extremely unlikely that the floating-point representation of the values will ever be identical. This kind of break is accomplished by checking if the difference of the values is below some tolerance, which is set to be a very small number. Ex.:
if (abs(Guess_FirmValue[i] - New_FirmValue[i]) <= 1e-9):
return ...

How to find the cube root of a negative integer such that it does not return NaN?

In Haskell, I have tried to find the cube root of a negative integer, for example, -1, without success.
I have used (-1) ** (1/3), but this returns a NaN. I thought that this might have something to do with type of the (1/3) fraction, but using (1/3 :: Double) yielded no success either.
As a result, my question is how can one find the cube root of -1 using Haskell so that it doesn't return NaN?
For real numbers, the Haskell operator (**) is only defined for negative base (left-hand side) values when the exponent (right-hand side) is integer-valued. If this strikes you as strange, note that the C function pow behaves the same way:
printf("%f\n", pow(-1.0, 1.0/3.0)); // prints "-nan", for me
and so does Python's ** operator:
print((-1.0)**(1.0/3.0))
# gives: ValueError: negative number cannot be raised to fractional power
The problem is partially a mathematical one. The "correct answer" for raising a negative base to a non-integral power is far from obvious. See, for example, this question on the Mathematics SO.
If you only need a cube root that can handle negative numbers, the other answers given should work fine, except that #Istvan's answer should use signum instead of sign, like this:
cbrt x = signum x * abs x ** (1/3)
If you want a more general integral root function for real numbers, be warned that for even n, there are no nth roots of negative numbers that are real, so this is about the best you can do:
-- | Calculate nth root of b
root :: (Integral n, RealFloat b) => n -> b -> b
root n b | odd n && b < 0 = - abs b ** overn
| otherwise = b ** overn
where overn = 1 / fromIntegral n
This gives:
> root 3 (-8)
-2.0
> root 4 (-8)
NaN -- correct, as no real root exists
>
I don't know Haskell, but you can do something like this:
sign(x) * abs(x) ** (1/3)
On ghci I've done something that seems to solve your problem:
let cbrt x = if x < 0 then -((-x) ** (1/3)) else x ** (1/3)
A simple cuberoot function.
As I'm still learning I don't know if this is a proper solution, so please let me know if there's something missing or wrong ;)

If Then Constraints in non-linear programming

I have several constrains in a No linear problem.
For example:
In m(x+y-n)^2
If x+y-n>=0 Then m=0,
Else m=1.
How can I write this conditional constraint as linear or non-linear constraint?
Well you could write this as [min(x+y-n,0)]^2. Not sure if that will do you any good (this is non-differentiable, and thus difficult for many solvers). We can make the min() expression linear using additional binary variables:
z <= x+y-n
z <= 0
z >= x+y-n - b * M
z >= 0 - (1-b) * M
b in {0,1}
with M a large enough constant. In many cases better reformulations can be applied but that depends on the rest of the model.
If you use a constraint-programming solver, such as Choco Solver, then you can use IfThenElse constraints directly as well as other non linear constraints, such as square.

Resources