I'm trying to plot the result of a trapezoidal method into a graph, I figured out that to get the exact value of the integral you can use integrate.trapz(f(x)) from the scypy libary. This is my second month learning comp math, not really sure about libraries usage yet.
Here is my code
from scipy import integrate
def f(x):
return 1 - x - 4*x**3 + 2*x**5
def trapezoid(a, b, n):
h = (b - a) / n
s = (f(a) + f(b))
i = 1
while i < n:
s += 2 * f(a + i * h)
i += 1
area = ((h / 2) * s)
return area
def graphTrapezoid():
val = []
err = []
exact_sum = integrate.trapz(f(b))-integrate.trapz(f(a))
for i in range (2,100):
val.append(trapezoid(a,b,i))
errVal = abs((trapezoid(a,b,i) - exact_sum)/exact_sum)
err.append(errVal)
plt.plot(val, err)
a = 1
b = 5
n = 1
graphTrapezoid()
Below is the error statement that I got
IndexError Traceback (most recent call last)
<ipython-input-134-504c0acc46bf> in <module>
39
40
---> 41 graphTrapezoid()
<ipython-input-134-504c0acc46bf> in graphTrapezoid()
29 val = []
30 err = []
---> 31 exact_sum = integrate.trapz(f(b))-integrate.trapz(f(a))
32 for i in range (2,100):
33 val.append(trapezoid(a,b,i))
~\Anaconda3\lib\site-packages\numpy\lib\function_base.py in trapz(y, x, dx, axis)
4059 slice1 = [slice(None)]*nd
4060 slice2 = [slice(None)]*nd
-> 4061 slice1[axis] = slice(1, None)
4062 slice2[axis] = slice(None, -1)
4063 try:
IndexError: list assignment index out of range
From the scipy.integrate.trapz documentation:
The function definition is:
scipy.integrate.trapz(y, x=None, dx=1.0, axis=-1)
Where y should be "array_like". However, you are passing two integer values to the trapz function.
If you want to integrate f betweeen b and a, maybe you could first define a list of x values:
a = 1
b = 5
step = 0.1 # A smaller step will give you a more precise result
x = []
for i in range(int((b-a)/step + 1)):
x.append(a + i*step)
Then, sample your function:
y = [f(val) for val in x]
And lastly, you could integrate your samples:
result = integrate.trapz(y, x, dx=step)
Related
I want to cal
https://en.wikipedia.org/wiki/Diophantine_equation#Examples
ax + by = c This is a linear Diophantine equation.
i try
I think the way you substituted h is not good.
How should I fix it?
x,y integer
(1)(2)5^4x-2^4y=1
(3)5^5x-2^5y=1
(4)11^5x-2^5y=1
from sympy.solvers.inequalities import reduce_rational_inequalities
from sympy import *
import math
var('x y n')
def myEq(f,g,h,myMax):
myN = Symbol('myN', real=True)
myGcdex = gcdex(f, -g)
myX = g * n + myGcdex[2]
myY = solve((f * x - g * y - h).subs({x: myX}), y)[0]
myN = math.ceil(reduce_rational_inequalities([[myX.subs({n: myN}) >= myMax]], myN).lhs)
return myX.subs({n: myN}),myY.subs({n: myN})
print("#(1)",myEq ( 5**4,2**4,1, 0) )
print("#(2)",myEq ( 5**4,2**4,1, 10) )
print("#(3)",myEq ( 5**5,2**5,1,100), "????<correct>x=125,y=12207")
print("#(4)",myEq (11**5,2**5,1, 0)," ","????<correct>x= 19,y=95624")
#(1) (1, 39)
#(2) (17, 664)
#(3) (129, 100781/8) ????<correct>x=125,y=12207
#(4) (1, 80525/16) ????<correct>x= 19,y=95624
#
#〇(1)nxy 0 16*n + 1 625*n + 39 <correct>x = 16 n + 1 , y = 625 n + 39 , n=0
#〇(2)nxy 1 16*n + 1 625*n + 39
#×(3)nxy 4 32*n + 1 3125*n + 781/8 <correct>x = 32 n + 29 , y = 3125 n + 2832 , n=3
#×(4)nxy 0 32*n + 1 161051*n + 80525/16 <correct>x = 32 n + 19 , y = 161051 n + 95624, n=0
ref
I want function convert from xy to cells
https://mathworld.wolfram.com/Congruence.html
(20220407)
MY_diox( 5**4*x-2**4*y-1, 0) # (( 1, 39), (16*n - 15, 625*n - 586))
MY_diox( 5**4*x-2**4*y-1, 10) # (( 17, 664), (16*n + 1, 625*n + 39))
MY_diox( 5**5*x-2**5*y-1,100) # ((125, 12207), (32*n + 93, 3125*n + 9082))
MY_diox(11**5*x-2**5*y-1, 0) # (( 19, 95624), (32*n - 13, 161051*n - 65427))
(20220410)
ref sage
Get all positive integral solutions for a linear equation
It looks like you are trying to get a specific solution to the equation that has a certain minimum value for x. If you solve the inequality for the parameter you can convert that to an interval on integers and just select the first such integer. A modified equation to give that value at n = 1 can also be given using a shift of origin.
def diox(eq, x):
"""
>>> from sympy.abc import x, y
>>> eq = 5**5*x-2**5*y-1
>>> diox(eq, 30)
((61, 5957), (32*n + 29, 3125*n + 2832))
"""
s = diophantine(eq)
assert len(s) == 1
a, b = s.pop()
p = a.free_symbols
assert len(p) == 1
p = p.pop()
i = solve(a >= x).as_set().intersection(Integers)
if i.start.is_infinite:
i = i.sup
else:
i = i.start
t = Tuple(a, b).xreplace({p: i})
e = Tuple(a, b).xreplace({p: Symbol('n')+i-1})
return t, e
As expected, the following was not possible.
from sympy import *
from sympy.abc import x, y
from sympy.solvers.diophantine import diophantine
var('x a b c')
myFormula= a*x+b*y-c
def diox(eq, x):
.......................................
return t, e
print("#",diox(myFormula,0))
# NotImplementedError: No solver has been written for inhomogeneous_general_quadratic.
Basically, I am trying to sample x and y from a proposal distribution function and then find the weights for the sample, and create 10 different sets of n = 10,000 samples. I was given an array of 55 values for radius and mu and sigma, and I have 10,000 values of x and y as samples.
here is my code:
import numpy as np
import matplotlib.pyplot as plt
GN = 4.302**-6
A = 8445.264
mu = np.array([1,1])
C = [[1,0],[0,1]]
num = 10**4
def chi_sq(x,y):
r = np.zeros(len(radius))
for s in range(len(radius)):
f_xy = np.sqrt( GN * 10**y * radius[s] / (radius[s] + 10**x )**3 )
chi_sqtotal = np.sum((f_xy - mu[s] )**2 / (sigma[s])**2)
r += chi_sqtotal
return r
def P(x,y):
return A*np.exp(-0.5*chi_sq(x,y))
for i in range(10):
def chi_sq(x,y):
r = np.zeros(len(radius))
for s in range(len(radius)):
f_xy = np.sqrt( GN * 10**y * radius[s] / (radius[s] + 10**x )**3 )
chi_sqtotal = np.sum((f_xy - mu[s] )**2 / (sigma[s])**2)
r += chi_sqtotal
return r
def P(x,y):
return A*np.exp(-0.5*chi_sq(x,y))
detC = np.linalg.det(C)
Cinv = np.linalg.inv(C)
def Q(x,y):
r = np.array([x,y]) - mu
prefactor = 1/(2*np.pi*np.sqrt(detC))
exponent = 0.5*(r # Cinv # r)
return prefactor*np.exp(-exponent)
r_samples = np.random.multivariate_normal(mu,C,num)
x_samples = r_samples[:,0]
y_samples = r_samples[:,1]
w = np.zeros(num)
for j in range(num):
x, y = r_samples[j]
w[j] = P(x,y)/Q(x,y)
Here is the error I am getting :
IndexError Traceback (most recent call last)
<ipython-input-114-638cc1a1b2e2> in <module>()
41 x, y = r_samples[j]
42
---> 43 w[j] = P(x,y)/Q(x,y)
1 frames
<ipython-input-114-638cc1a1b2e2> in chi_sq(x, y)
22 for s in range(len(radius)):
23 f_xy = np.sqrt( GN * 10**y * radius[s] / (radius[s] + 10**x )**3 )
---> 24 chi_sqtotal = np.sum((f_xy - mu[s] )**2 / (sigma[s])**2)
25 r += chi_sqtotal
26 return r
IndexError: index 2 is out of bounds for axis 0 with size 2
The error is very descriptive:
IndexError: index 2 is out of bounds for axis 0 with size 2
If I have a numpy.ndarray, let's call it x, then the axes are as follows:
x[axis_0][axis_1]...
They are saying that the size of the axis is 2, and you're indexing it with 2, which is out of bounds. Notice
mu = np.array([1,1])
and the line with mu has the error. In this chunk:
for s in range(len(radius)):
f_xy = np.sqrt( GN * 10**y * radius[s] / (radius[s] + 10**x )**3 )
chi_sqtotal = np.sum((f_xy - mu[s] )**2 / (sigma[s])**2)
r += chi_sqtotal
s goes above 1, causing the error. You need to make a correction somewhere and not loop as high as len(radius), because mu only has 2 elements.
So, I checked other questions and answers about this and I didn't understand the reason, could you please help me with this, please
I'm learning linear regression and I implemented the code for Linear Regression with two variables.
This implementation should predict the sum of two numbers but it's giving an error
Implemented code here:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([[1,1],[1,2],[2,3],[3,4],[4,5],[5,6]])
y = np.array([2,3,5,7,9,11])
#hypothesis
def hypothesis(theta, x):
return theta[0] + theta[1]*x[0] + theta[2]*x[1]
#cost function J(t0, t1, t2)
def cost(theta, x, y):
m = x.shape[0]
error = 0
for i in range(m):
d = x[i]
hx = hypothesis(theta, d)
error = error + (hx - y[i])**2
return error
#differentiation of cost function
def diffGradient(theta, x, y):
grad = np.zeros((3,))
m = x.shape[0]
for i in range(m):
hx = hypothesis(theta, x)
grad[0] = grad[0] + (hx - y[i])
grad[1] = grad[1] + (hx - y[i])*x[0]
grad[2] = grad[2] + (hx - y[i])*x[1]
return 0
#gradient descent funtion
def gradientDescent(x, y, learning_rate = 0.001):
theta = [-2.0,0.0,1.0]
iter = 100
error_list = []
theta_list = []
for i in range(iter):
d = x[i]
grad = diffGradient(theta, d, y)
e = cost(theta, d, y)
error_list.append(e)
theta_list.append((theta[0],theta[1],theta[2]))
#simultaneous update
theta[0] = theta[0] - learning_rate*grad[0]
theta[1] = theta[1] - learning_rate*grad[1]
theta[2] = theta[2] - learning_rate*grad[2]
return theta, theta_list, error_list
final_theta, theta_list, error_list = gradientDescent(x,y)
After the above line, I'm getting this error
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-56-bda7687d0af9> in <module>
----> 1 final_theta, theta_list, error_list = gradientDescent(x,y)
<ipython-input-55-033133fbfbd5> in gradientDescent(x, y, learning_rate)
8 d = x[i]
9 grad = diffGradient(theta, d, y)
---> 10 e = cost(theta, d, y)
11 error_list.append(e)
12 theta_list.append((theta[0],theta[1],theta[2]))
<ipython-input-41-6a07f4b81c9c> in cost(theta, x, y)
5 for i in range(m):
6 d = x[i]
----> 7 hx = hypothesis(theta, d)
8 error = error + (hx - y[i])**2
9 return error
<ipython-input-27-43ce9d7c567b> in hypothesis(theta, x)
1 #hypothesis
2 def hypothesis(theta, x):
----> 3 return theta[0] + theta[1]*x[0] + theta[2]*x[1]
IndexError: invalid index to scalar variable.
I don't know what I'm doing wrong. Any help would be appreciated.
What's the x that you pass to
gradientDescent(x,y)
Look at the traceback and try to figure out what variable has the problem - the problem is that you can't index a scalar, a number. It has to be a list or array. Trace the problem variable back up through your code.
In the traceback:
in the problem line you use x[0] and x[1]. What's x at this point?
In the calling function it's d, which is set with d = x[i]
In gradientDescent the passed variable is again called d, and set as d = x[i]
So you have 3 levels of indexing. Does the original x support that?
You have to understand the problem before you try a fix.
In the following code I am trying to add an index to my graph so I can label the different two lines, However I am running into the following error, how can I fix it?
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-115-3c7429a6498c> in <module>()
36 n_inv_4.append(1.0 / ((2*i)**4))
37 n_lines = plt.loglog(n, n_inv_4)
---> 38 plt.figlegend((error_lines[0], n_lines[0]), ('Error', '1/n**4'), ('upper right'))
39 plt.show()
TypeError: 'Text' object does not support indexing
and here is my code, below I have the image it outputs:
from math import pi, cos, sin
from matplotlib import pyplot as plt
def simpson(f, a, b, n):
h = (b - a) / (2*n)
s = f(a) + f(b)
for i in range(1, 2*n, 2):
s += 4 * f(a + i * h)
for i in range(2, 2*n-1, 2):
s += 2 * f(a + i * h)
return s * h / 3
diffs = {}
exact = 1 - cos(pi/2)
for n in range(1, 100):
result = simpson(lambda x: sin(x), 0.0, pi/2, n)
diffs[2*n] = abs(exact - result) # use 2*n or n here, your choice.
ordered = sorted(diffs.items())
x,y = zip(*ordered)
plt.autoscale()
plt.loglog(x,y)
error_lines = plt.xlabel("Intervals n")
plt.ylabel("Absolute Error")
n = []
n_inv_4 = []
for i in range(1,100):
n.append(2*i)
n_inv_4.append(1.0 / ((2*i)**4))
n_lines = plt.loglog(n, n_inv_4)
plt.figlegend((error_lines[0], n_lines[0]), ('Error', '1/n**4'), ('upper right')
plt.show()
and here is the output:
I think you just missed the intended line for inserting error_lines = - it should be one line above.
However, note that you can simply add a legend without parameters (plt.legend()) when you set the label-kwargs of your plot commands before, e.g.
plt.loglog(x, y, label='firstplot')
plt.loglog(n, n_inv_4, label='secondplot')
I'm trying to turn a code into a python class.
my dataframe "URM" looks like :
user_id anime_id user_rating
0 1 20 7.808497
1 3 20 8.000000
2 5 20 6.000000
3 6 20 7.808497
4 10 20 7.808497
I filter only 999users for computation reason.
If i copy paste all that code below without "self" it works fine.
when i'm trying to dive into class
like that
parameters
`class ALS:
def __init__(self, URM, n_factors, lambda_ , n_iterations) :
self.URM = URM
self.n_factors = n_factors
self.lambda_ = lambda_
self.n_iterations = n_iterations
self.n = max(self.URM["anime_id"])
self.m = max(self.URM["user_id"])
functions for normalise df, metrics, and compute training matrix
def normaliseRow(self, x):
return x / sum(x)
def initialiseMatrix(self, n, n_factors):
A = abs(np.random.randn(self.n, self.n_factors))
return np.apply_along_axis(self.normaliseRow, 1, A)
def ratingsPred(X, Y):
return np.dot(X, Y.T)
def MSE(self, ratingsPred, ratingsMatrix):
idx = ratingsMatrix > 0
return sum((ratingsPred[idx] - ratingsMatrix[idx]) ** 2) / np.count_nonzero(ratingsMatrix)
def compute_matrix(self) :
Y = self.initialiseMatrix(self.n, self.n_factors)
X = self.initialiseMatrix(self.m, self.n_factors)
temp = np.zeros((n, 3)) #user_id, anime_id rating_user
for i in range(1,n):
temp[i,] = [m+1,i,0]
COL_NAME = ["user_id","anime_id", "user_rating"]
RM = self.URM.append(pd.DataFrame(temp, columns =COL_NAME))
RM = RM.pivot_table(columns=['anime_id'], index =['user_id'],
values='user_rating', dropna = False)
RM = RM.fillna(0).as_matrix()
ratingsMatrix = RM[0:self.m,0:self.n]
nonZero = ratingsMatrix > 0
reg = lambda_ * np.eye(n_factors,n_factors)
return X, Y, ratingsMatrix, nonZero, reg
training the alternating least square
def train(self) :
X, Y, ratingsMatrix, nonZero, reg = self.compute_matrix()
print("start training ...")
training_process = []
for k in range(1, self.n_iterations):
for i in range(1, self.m):
idx = nonZero[i,:]
a = Y[idx,]
b = np.dot(np.transpose(Y[idx,]), ratingsMatrix[i, idx])
updateX = np.linalg.solve(np.dot(np.transpose(a), a) + reg, b)
X[i,] = updateX
for j in range(1, self.n):
idx = nonZero[:,j]
a = X[idx,]
b = np.dot(np.transpose(X[idx,]), ratingsMatrix[idx, j])
updateY = np.linalg.solve(np.dot(np.transpose(a), a) + reg, b)
Y[j,] = updateY
ratingsP = self.ratingsPred(X, Y)
mse = self.MSE(ratingsP, ratingsMatrix)
training_process.append((k, mse))
if (k+1) % 5 == 0:
print("Iteration: %d ; mse = %.4f" % (k+1, mse))
return training_process
start training
# df, n_factors, lambda, iteration
als_model = ALS(urm, 15, 0.1, 10) `
als_mode.train()
it return an IndexError
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-130-ce2849580784> in <module>()
----> 1 als_model.train()
<ipython-input-129-14f3d633244d> in train(self)
53 for j in range(1, self.n):
54 idx = nonZero[:,j]
---> 55 a = X[idx,]
56 b = np.dot(np.transpose(X[idx,]), ratingsMatrix[idx, j])
57 updateY = np.linalg.solve(np.dot(np.transpose(a), a) + reg, b)
IndexError: boolean index did not match indexed array along dimension 0; dimension is 34240 but corresponding boolean dimension is 999