perceptron python implementation
python3 implementation of perceptron
# imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
# create dataset
x, y = make_blobs(n_samples=100, n_features=2, centers=2, random_state=42)
# create a dataframe
df = pd.DataFrame(data=x, columns=["feature_1", "feature_2"])
df["target"] = y
# plot the dataset
fig = plt.figure(figsize=(10, 8))
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
# plot circles for target = 0 class
target_0_x = df[df["target"] == 0][["feature_1", "feature_2"]]
feature_1_x = target_0_x["feature_1"]
feature_2_x = target_0_x["feature_2"]
plt.plot(feature_1_x, feature_2_x, "bo")
# plot plus symbol for target = 1 class
target_1_x = df[df["target"] == 1][["feature_1", "feature_2"]]
feature_1_x = target_1_x["feature_1"]
feature_2_x = target_1_x["feature_2"]
plt.plot(feature_1_x, feature_2_x, "r+")
# plot figure now
# plt.show()
# define predict function
def predict(input_features, weights):
dot_product = np.dot(input_features, weights)
rv = np.where(dot_product > 0, 1, 0)
return rv
# add bias column to model
df["bias"] = 1
# define model
def fit(input_data, target, epochs=100, alpha=0.1):
feature_ct = input_data.shape[1]
weights = np.random.random(feature_ct)
for i in range(epochs):
error = 0
# write weight update logic
for xi, y in zip(df[["feature_1", "feature_2", "bias"]].values, target):
weights = weights + alpha * (y - predict(xi, weights)) * xi
return weights
input_data = df[["feature_1", "feature_2", "bias"]]
target = df["target"]
w = fit(input_data, target)
# test the model using the predict method.
random_row = df.sample(n=1)
print(random_row)
rv = predict(random_row[["feature_1", "feature_2", "bias"]], w)
print("Actual Output : ", random_row["target"].values)
print("Predicted Output : ", rv)