I'm trying to define the operator type add when it comes to my class Point. Point is exactly what it seems, (x, y). I can't seem to get the operator to work though because the code keeps printing the <main.Point...>. I'm pretty new to this stuff, so can someone explain what I am doing wrong? Thanks. Here is my code:
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
p1 = Point(3,4)
p2 = Point(5,6)
p3 = p1 + p2
print(p3)
Your add function is working as intended. It's your print that's the problem. You're getting an ugly result like <__main__.Point object at 0x027FA5B0> because you haven't told the class how you want it to display itself. Implement __str__ or __repr__ so that it shows a nice string.
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __repr__(self):
return "Point({}, {})".format(self.x, self.y)
p1 = Point(3,4)
p2 = Point(5,6)
p3 = p1 + p2
print(p3)
Result:
Point(8, 10)
Related
How can I access attribute array in Parent class from Child class? Here is an example of my code that doesn't work
class Parent:
def __init__(self, x, y):
self.x = x
self.y = y
def __createArray(self): # Private function
x = self.x
y = self.y
array = []
array.append(f(x), f(y)) # f() is a random function
self.array = array
return array
class Child(Parent):
def __init__(self, x, y):
super().__init__(x, y)
def __create2ndArray(self): # Private function
x = self.x
y = self.y
# This line below doesn't work
array = self.array
Many people tell me to use super() function but I still don't know how. But it looks like I can't use super() in this situation since it only use for methods, not attributes
class Parent:
def __init__(self, x, y):
self.x = x
self.y = y
def _createArray(self): # Protected function - children cannot run private
x = self.x
y = self.y
array = []
f = lambda x: x
array.append(f(x)) # f() is a random function
array.append(f(y))
self.array = array
return array
class Child(Parent):
def __init__(self, x, y):
super().__init__(x, y)
def create2ndArray(self): # Public function - so that I can run it
super()._createArray()
x = self.x
y = self.y
# This line below doesn't work
array = self.array
print(array)
x = Child(3,4)
x.create2ndArray()
You have never ran __createArray() method in child so self.array was None
i buit from scratch the perceptron class in python, and now i'm trying to make the animated visualization of the decision boundary in every iteration of the learning process.The problem is that my code doesn't works, cuz looks like the "animation_func" is not called, i don't know why. can you help me.
class Perceptron:
def __init__(self,X=None, y=None,lr=0.001, niter=1000):
self.lr = lr
self.niter = niter
self.w = None
self.b = None
def fit(self,X,y):
for indice,X_i in enumerate(X):
self.w += self.lr*(y_[indice]-self.predic(X_i))* X_i
def animar_perceptron(self,X,y,niter):
samples,features = X.shape
self.w = np.zeros(features)
self.b = 0
y_ = np.array([1 if i>0 else 0 for i in y])
x0_1 = np.amin(X[:,0])
x0_2 = np.amax(X[:,0])
ymin = np.amin(X[:,1])
ymax= np.amax(X[:1])
fig, ax = plt.subplots()
ax.scatter(X[:,0], X[:,1],marker='o', c=y )
boundary, =ax.plot([X0_1, X0_2],[0, 0],'k')
def animation_func(_):
self.fit(X,y)
x1_1 = (-self.w[0]*x0_1-self.b )/self.w[1]
x1_2 = (-self.w[0]*x0_2-self.b )/self.w[1]
boundary.set_ydata([x1_1,x1_2])
return boundary,
return FuncAnimation(fig, func=animation_func, frames=np.arange(1,niter), interval=50)
def predic(self, X):
y_hat = np.dot(X,self.w) + self.b
y_hat =self.activate_fun(y_hat)
return y_hat
def activate_fun(self,z):
return np.where(z>0, 1,0)
def score(self, y_true, y_pred):
accuracy = np.sum(y_true == y_pred)/len(y_true)
return accuracy
p = Perceptron()
animacion = animar_perceptron(X,y,1000)
I am trying to implement a function that calculates the area of a triangle in the Euclidean space, using the Heron's formula. Unfortunately I have no idea how to outsource partial functions and then pass them as parameters.
That is what I have so far:
import scala.math._
def sqr(a:Double) = a*a
def length(x1:Double,y1:Double,x2:Double,y2:Double)=sqrt(sqr(x2-x1)+sqr(y2-y1))
val a = length(x1,y1,x2,y2)
val b = length(x2,y2,x3,y3)
val c = length(x3,y3,x1,y1)
val u = 0.5*a*b*c
heron(x1:Double,y1:Double,x2:Double,y2:Double,x3:Double,y3:Double) = sqrt(u*(u-a)*(u-b)*(u-c))
That obviously doesn't work, but I hope you get what I am trying to do.
I think you just want to define those intermediate values inside of your function:
// btw, using scala.math.power you can write 'power(a, 2)'
def sqr(a: Double): Double = a * a
def length(
x1: Double, y1: Double,
x2: Double, y2: Double
): Double = sqrt(
sqr(x2 - x1) +
sqr(y2 - y1)
)
def heron(
x1: Double, y1: Double,
x2: Double, y2: Double,
x3: Double, y3: Double
): Double = {
val a = length(x1, y1, x2, y2)
val b = length(x2, y2, x3, y3)
val c = length(x3, y3, x1, y1)
val u = 0.5 * a * b * c
sqrt(u * (u - a) * (u - b) * (u - c))
}
I would also recommend you to make more spaces in the code, it makes it more readable.
class X
class Y extends X
class Z extends Y
class M {
def f(x: X): String = "f with X at M"
def f(x: Y): String = "f with Y at M"
}
class N extends M {
override def f(x: Y): String = "f with Y at N"
def f(x: Z): String = "f with Z at N"
}
val z: Z = new Z
val y: Y = z
val x: X = y
val m: M = new N
println(m.f(x))
// m dynamically matches as type N and sees x as type X thus goes into class M where it calls "f with X at M"
println(m.f(y))
// m dynamically matches as type N and sees y as type Y where it calls "f with Y at N"
println(m.f(z))
// m dynamically matches as type N and sees z as type Z where it calls "f with Z at N"
Consider this code, I don't understand with the final call println(m.f(z)) doesn't behave as I wrote in the comments - is there a good resource for understanding how overloading works in Scala?
Thank!
Firstly overloading in Scala works the same as in Java.
Secondly, it's about static and dynamic binding. Let's find out what compiler see. You have m: M object. Class M has f(X) and f(Y) methods. When you call m.f(z) compiler resolves that method f(Y) should be called because Z is subclass of Y. It's a very important point: compiler doesn't know real class of m object that's why it knows nothing about method N.f(Z). And it's called static binding: compiler resolves method's signature. Later, in runtime, dynamic binding happens. JVM knows real class of m and it calls f(Y) which is overloaded in Z.
Hope my explanations are clearly enough to understand.
class x
class Y extends X
class Z extends Y
class M {
def f(x: X): String = "f with X at M"
def f(x: Y): String = "f with Y at M"
}
class N extends M {
override def f(x: Y): String = "f with Y at N"
def f(x: Z): String = "f with Z at N"
}
val z: Z = new Z
val y: Y = z
val x: X = y
val m: M = new N
println(m.f(x))
// m dynamically matches as type N and sees x as type X thus goes into class M where it calls "f with X at M"
println(m.f(y))
// m dynamically matches as type N and sees y as type Y where it calls "f with Y at N"
println(m.f(z))
// m dynamically matches as type N and sees z as type Z where it calls "f with Z at N"
Because the function will be overloaded on N.so N is depends on m.f(y) .finally it is related with x and y that is reason z function will call
When you do this
val m: M = new N
It means that m is capable of doing everything that class M can. M has two methods - first which can take X, other Y.
And hence when you do this
m.f(z)
Runtime is going to search for a method which can accept z (of type Z). The method in N is not a candidate here because of two reasons
The reference is of type M
Your N does not override any method of M which can accept an argument of type Z. You do have a method in N which can accept a Z but that's not a candidate because it's not overriding anything from M
The best match is f in M which can accept a Y this is because Z ISA Y
You can get what your last comment says if
You define a method in M which takes argument of type Z and then you override it in N
You instantiate a val of type N e.g: val m : N = new N
I think the existing questions on SO already elaborate this point.
I need to find matching between two independent sets of features extracted from two images of the same scene captured by two different cameras.
I'm using the HumanEvaI data set, so I have the calibration matrices of the cameras (in this particular case BW1 and BW2).
I can not use method like simple correlation, SIFT or SURF to solve the problem because the cameras are quite far away from each other and also rotated. So the differences between the images are big and there is occlusion as well.
I have been focused in finding an Homography between the captured images based on ground truth points matching that I have been able to build due to the calibration information I already have.
Once I have this homography I will use a perfect matching (Hungarian algorithm) to find the best correspondence. The importance of the homography here is that is the way I have to calculate the distance between the points.
So far everything seems fine, my problem is that I haven't been able to find a good homography . I have tried RANSAC method, gold standard method with sampson distance (this is a nonlinear optimization approach) and mainly everything from a book called 'Multiple View Geometry in Computer Vision' Second Edition by Richard Hartley.
I have implemented everything in matlab so far.
Is there another way to do this? I'm I in the right path? If so what could I have been doing wrong?
You can try these two methods:
A new point matching algorithm for non-rigid registration (uses Thin-plate Spline) - relatively slower.
Point Set Registration: Coherent Point Drift (faster and more accurate I feel).
As far as 2nd method is concerned, I feel that it gives very good registration result in presence of outliers, it is fast and is able to recover complex transformations. But the 1st method is also a well-known method in registration field and you may try that as well.
Try understanding the core of the algorithm and then move on to the codes available online.
Thin plate spline here - Download the TPS-RPM demo.
Point Set Registration: Coherent Point Drift here
You might find my solution interesting. It is a pure numpy implementation of the Coherent Point Drift algorithm.
Here is an example:
from functools import partial
from scipy.io import loadmat
import matplotlib.pyplot as plt
import numpy as np
import time
class RigidRegistration(object):
def __init__(self, X, Y, R=None, t=None, s=None, sigma2=None, maxIterations=100, tolerance=0.001, w=0):
if X.shape[1] != Y.shape[1]:
raise 'Both point clouds must have the same number of dimensions!'
self.X = X
self.Y = Y
(self.N, self.D) = self.X.shape
(self.M, _) = self.Y.shape
self.R = np.eye(self.D) if R is None else R
self.t = np.atleast_2d(np.zeros((1, self.D))) if t is None else t
self.s = 1 if s is None else s
self.sigma2 = sigma2
self.iteration = 0
self.maxIterations = maxIterations
self.tolerance = tolerance
self.w = w
self.q = 0
self.err = 0
def register(self, callback):
self.initialize()
while self.iteration < self.maxIterations and self.err > self.tolerance:
self.iterate()
callback(X=self.X, Y=self.Y)
return self.Y, self.s, self.R, self.t
def iterate(self):
self.EStep()
self.MStep()
self.iteration = self.iteration + 1
def MStep(self):
self.updateTransform()
self.transformPointCloud()
self.updateVariance()
def updateTransform(self):
muX = np.divide(np.sum(np.dot(self.P, self.X), axis=0), self.Np)
muY = np.divide(np.sum(np.dot(np.transpose(self.P), self.Y), axis=0), self.Np)
self.XX = self.X - np.tile(muX, (self.N, 1))
YY = self.Y - np.tile(muY, (self.M, 1))
self.A = np.dot(np.transpose(self.XX), np.transpose(self.P))
self.A = np.dot(self.A, YY)
U, _, V = np.linalg.svd(self.A, full_matrices=True)
C = np.ones((self.D, ))
C[self.D-1] = np.linalg.det(np.dot(U, V))
self.R = np.dot(np.dot(U, np.diag(C)), V)
self.YPY = np.dot(np.transpose(self.P1), np.sum(np.multiply(YY, YY), axis=1))
self.s = np.trace(np.dot(np.transpose(self.A), self.R)) / self.YPY
self.t = np.transpose(muX) - self.s * np.dot(self.R, np.transpose(muY))
def transformPointCloud(self, Y=None):
if not Y:
self.Y = self.s * np.dot(self.Y, np.transpose(self.R)) + np.tile(np.transpose(self.t), (self.M, 1))
return
else:
return self.s * np.dot(Y, np.transpose(self.R)) + np.tile(np.transpose(self.t), (self.M, 1))
def updateVariance(self):
qprev = self.q
trAR = np.trace(np.dot(self.A, np.transpose(self.R)))
xPx = np.dot(np.transpose(self.Pt1), np.sum(np.multiply(self.XX, self.XX), axis =1))
self.q = (xPx - 2 * self.s * trAR + self.s * self.s * self.YPY) / (2 * self.sigma2) + self.D * self.Np/2 * np.log(self.sigma2)
self.err = np.abs(self.q - qprev)
self.sigma2 = (xPx - self.s * trAR) / (self.Np * self.D)
if self.sigma2 <= 0:
self.sigma2 = self.tolerance / 10
def initialize(self):
self.Y = self.s * np.dot(self.Y, np.transpose(self.R)) + np.repeat(self.t, self.M, axis=0)
if not self.sigma2:
XX = np.reshape(self.X, (1, self.N, self.D))
YY = np.reshape(self.Y, (self.M, 1, self.D))
XX = np.tile(XX, (self.M, 1, 1))
YY = np.tile(YY, (1, self.N, 1))
diff = XX - YY
err = np.multiply(diff, diff)
self.sigma2 = np.sum(err) / (self.D * self.M * self.N)
self.err = self.tolerance + 1
self.q = -self.err - self.N * self.D/2 * np.log(self.sigma2)
def EStep(self):
P = np.zeros((self.M, self.N))
for i in range(0, self.M):
diff = self.X - np.tile(self.Y[i, :], (self.N, 1))
diff = np.multiply(diff, diff)
P[i, :] = P[i, :] + np.sum(diff, axis=1)
c = (2 * np.pi * self.sigma2) ** (self.D / 2)
c = c * self.w / (1 - self.w)
c = c * self.M / self.N
P = np.exp(-P / (2 * self.sigma2))
den = np.sum(P, axis=0)
den = np.tile(den, (self.M, 1))
den[den==0] = np.finfo(float).eps
self.P = np.divide(P, den)
self.Pt1 = np.sum(self.P, axis=0)
self.P1 = np.sum(self.P, axis=1)
self.Np = np.sum(self.P1)
def visualize(X, Y, ax):
plt.cla()
ax.scatter(X[:,0] , X[:,1], color='red')
ax.scatter(Y[:,0] , Y[:,1], color='blue')
plt.draw()
plt.pause(0.001)
def main():
fish = loadmat('./data/fish.mat')
X = fish['X'] # number-of-points x number-of-dimensions array of fixed points
Y = fish['Y'] # number-of-points x number-of-dimensions array of moving points
fig = plt.figure()
fig.add_axes([0, 0, 1, 1])
callback = partial(visualize, ax=fig.axes[0])
reg = RigidRegistration(X, Y)
reg.register(callback)
plt.show()
if __name__ == '__main__':
main()
Another method I think you might find useful is described here.
This approach tries to fit local models to group of points. Its global optimization method allows it to outperform RANSAC when several distinct local models exists.
I also believe they have code available.