Untitled
unknown
plain_text
a year ago
1.2 kB
4
Indexable
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('HW2_ellipse.csv', delimiter=',')
x = np.array([row[0] for row in data])
y = np.array([row[1] for row in data])
A = []
for i in range(len(x)):
A.append([x[i]**2, y[i]**2])
A = np.array(A)
b = np.array([[1] for i in range(len(x))])
a = np.array([[1.0],[1.0]])
iters = 1000
mu = 1 / (np.linalg.norm(np.matmul(A.T, A), 2))
for i in range(iters):
grad = np.matmul(A.T,(np.matmul(A,a)-b))
a_new = a - mu * grad
a = a_new
if (np.linalg.norm(grad)<10**(-3)):
print("t:",i)
break
print("a_new:", a)
f_a = np.sum((np.matmul(A,a) - b)**2)
print("f(a):", f_a)
print("f(x)/len(A):", f_a/len(A))
theta = np.linspace(0, 2 * np.pi, 300)
ellipse_x = np.sqrt(1 / a[0, 0]) * np.cos(theta)
ellipse_y = np.sqrt(1 / a[1, 0]) * np.sin(theta)
plt.plot(ellipse_x, ellipse_y, color='blue')
plt.scatter(x, y, color='red', s=0.5)
plt.xlabel('x')
plt.ylabel('y')
plt.title('HW2_ellipse.csv')
plt.axhline(0, color='black', linewidth = 0.3 )
plt.axvline(0, color='black', linewidth = 0.3 )
plt.grid(color = 'gray', linestyle = '--', linewidth = 0.2)
plt.show()
Editor is loading...
Leave a Comment