import numpy as np
np.random.seed(4242)

"""
Explanation: <!--BOOK_INFORMATION-->
<a href="https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv" target="_blank"><img align="left" src="data/cover.jpg" style="width: 76px; height: 100px; background: white; padding: 1px; border: 1px solid black; margin-right:10px;"></a>
This notebook contains an excerpt from the book Machine Learning for OpenCV by Michael Beyeler.
The code is released under the MIT license,
and is available on GitHub.
Note that this excerpt contains only the raw code - the book is rich with additional explanations and illustrations.
If you find this content useful, please consider supporting the work by
buying the book!
<!--NAVIGATION-->
< Detecting Pedestrians in the Wild | Contents | Implementing a Spam Filter with Bayesian Learning >
Additional SVM Exercises
The book refers to a couple of follow-up exercises, where you should think about which SVM kernel is most likely to perform best on the data.
Think you know the answer? Code it up!
You can use the pre-generated datasets below.
End of explanation
"""


n_samples = 500
n_features = 2
X1 = np.random.rand(n_samples, n_features)

y1 = np.ones((n_samples, 1))
idx_neg = (X1[:, 0] - 0.5) ** 2 + (X1[:, 1] - 0.5) ** 2 < 0.03
y1[idx_neg] = 0

import matplotlib.pyplot as plt
%matplotlib inline
plt.figure(figsize=(10, 6))
plt.scatter(X1[:, 0], X1[:, 1], c=y1, s=100)

"""
Explanation: Exercise 1
End of explanation
"""


X2 = np.random.rand(n_samples, n_features)

y2 = np.ones((n_samples, 1))
idx_neg = (X2[:, 0] < 0.5) * (X2[:, 1] < 0.5) + (X2[:, 0] > 0.5) * (X2[:, 1] > 0.5)
y2[idx_neg] = 0

plt.figure(figsize=(10, 6))
plt.scatter(X2[:, 0], X2[:, 1], c=y2, s=100)

"""
Explanation: Code up your own SVM solution below:
Exercise 2
End of explanation
"""


rho_pos = np.random.rand(n_samples // 2, 1) / 2.0 + 0.5
rho_neg = np.random.rand(n_samples // 2, 1) / 4.0
rho = np.vstack((rho_pos, rho_neg))
phi_pos = np.pi * 0.75 + np.random.rand(n_samples // 2, 1) * np.pi * 0.5
phi_neg = np.random.rand(n_samples // 2, 1) * 2 * np.pi
phi = np.vstack((phi_pos, phi_neg))

X3 = np.array([[r * np.cos(p), r * np.sin(p)] for r, p in zip(rho, phi)])
y3 = np.vstack((np.ones((n_samples // 2, 1)), np.zeros((n_samples // 2, 1))))

plt.figure(figsize=(10, 6))
plt.scatter(X3[:, 0], X3[:, 1], c=y3, s=100)

"""
Explanation: Code up your own SVM solution below:
Exercise 3
End of explanation
"""


rho_pos = np.linspace(0, 2, n_samples // 2)
rho_neg = np.linspace(0, 2, n_samples // 2) + 0.5
rho = np.vstack((rho_pos, rho_neg))
phi_pos = 2 * np.pi * rho_pos
phi = np.vstack((phi_pos, phi_pos))

X4 = np.array([[r * np.cos(p), r * np.sin(p)] for r, p in zip(rho, phi)])
y4 = np.vstack((np.ones((n_samples // 2, 1)), np.zeros((n_samples // 2, 1))))

plt.figure(figsize=(10, 6))
plt.scatter(X4[:, 0], X4[:, 1], c=y4, s=100)

"""
Explanation: Code up your own solution:
Exercise 4
End of explanation
"""


