I had to implement QDA without libries. Can you check it, add some comments and correct…
- User
I had to implement QDA without libries. Can you check it, add some comments and correct it, if needed: iris_dataset = datasets.load_iris()
X = iris_dataset.data[iris_dataset.target != 0, :2] # sepal length and sepal width for versicolor and virginica y = iris_dataset.target[iris_dataset.target != 0] # # target classes: 1 for Versicolor, 2 for Virginica
def compute_parameters(features, target): classes = np.unique(target) means = {} covariances = {}
codefor cls in classes: x_cls = features[target == cls] means[cls] = np.mean(x_cls, axis=0) covariances[cls] = np.cov(x_cls, rowvar=False) return means, covariances_means, _covariances = compute_parameters(X, y)
QDA function
def qda(features, means, covariances): probs = np.zeros((features.shape[0], len(means)))
codefor cls in means.keys(): mean = means[cls] covariance = covariances[cls] inv_covariance = np.linalg.inv(covariance) # Difference between feature and mean for the current class diff = features - mean # Calculate the probability prob = -0.5 * (np.sum(diff @ inv_covariance * diff, axis=1)) \ - 0.5 * np.log(np.linalg.det(covariance)) probs[:, cls - 1] = prob # Store probabilities accordingly return np.argmax(probs, axis=1) + 1 # Return class labelsxx, yy = make_meshgrid(X[:, 0], X[:, 1]) Z = qda(np.array([xx.ravel(), yy.ravel()]).T, _means, _covariances) Z = Z.reshape(xx.shape)
plt.figure(figsize=(10, 6)) plt.contourf(xx, yy, Z, alpha=0.4, cmap='coolwarm') plt.scatter(X[:, 0], X[:, 1], c=y, edgecolors='k', cmap='coolwarm', marker='o') plt.xlabel("Sepal Length") plt.ylabel("Sepal Width") plt.title("Quadratic Discriminant Analysis (QDA)") plt.xlim(X[:, 0].min() - 1, X[:, 0].max() + 1) plt.ylim(X[:, 1].min() - 1, X[:, 1].max() + 1) plt.show()
- Assistant
- User
Can we visualite it in another way?
- Assistant
- User
What is the formula for QDA that function uses? Can you write it with LaTex (I need it for my google colab)?
- Assistant
Certainly! The formula for the Quadratic Discriminant Analysis (QDA) model can be expressed in terms of the log-likelihood function for a given class ( C_k ). The QDA model utilizes the multivariate Gaussian distribution for each class.
QDA Formula
The decision rule for classification in QDA is based on the following log-probability function:
[ \log P(X | C_k) = -\frac{1}{2} (X - \mu_k)^T \Sigma_k^{-1} (X - \mu_k) - \frac{1}{2} \log |\Sigma_k| + \log P(C_k) ]