Jul 16, 2024
Fancy Indexing: Allows extraction of array elements using lists of indices.
a = np.array([...])
b = a[[0, 2, 3]] # extract specific rows like 0th, 2nd, and 3rd
Boolean Indexing: Extracts elements based on conditions.
mask = a > 50 # condition
result = a[mask] # filtered array
Example combining conditions:
mask = (a > 50) & (a % 2 == 0)
result = a[mask]
Sigmoid Function:
def sigmoid(x):
return 1 / (1 + np.exp(-x))
result = sigmoid(np.array([1, 2, 3]))
Mean Square Error (MSE):
def mse(actual, predicted):
return np.mean((actual - predicted) ** 2)
result = mse(np.array([...]), np.array([...]))
Creating NaN values:
a = np.array([1, 2, np.nan, 4])
Filtering out NaN values:
result = a[~np.isnan(a)] # removes NaNs
Basic Plotting: Plotting simple functions using Matplotlib.
import matplotlib.pyplot as plt
x = np.linspace(-10, 10, 100)
y = x
plt.plot(x, y) # linear line
plt.show()
Example for quadratic:
y = x ** 2
plt.plot(x, y)
plt.show()