Open ItsMyPain opened 1 year ago
python = ">=3.9,<3.13" numpy = "^1.26.0" pandas = "^2.1.1" torch = { url = "https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp39-cp39-linux_x86_64.whl"}
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from math import exp
data = pd.read_csv("data.csv") data.head(10)
X_train, X_test, y_train, y_test = train_test_split(data['Age'], data['Purchased'], test_size=0.20)
def normalize(X): return X - X.mean()
def predict(X, b0, b1): return np.array([1 / (1 + exp(-1b0 + -1b1*x)) for x in X])
def logistic_regression(X, Y):
X = normalize(X)
b0 = 0 b1 = 0 L = 0.001 epochs = 300
for epoch in range(epochs): y_pred = predict(X, b0, b1) D_b0 = -2 sum((Y - y_pred) y_pred (1 - y_pred)) # Loss wrt b0 D_b1 = -2 sum(X (Y - y_pred) y_pred * (1 - y_pred)) # Loss wrt b1
b0 = b0 - L * D_b0
b1 = b1 - L * D_b1
return b0, b1
b0, b1 = logistic_regression(X_train, y_train)# Making predictions and setting a thresholdX_test_norm = normalize(X_test) y_pred = predict(X_test_norm, b0, b1) y_pred = [1 if p >= 0.5 else 0 for p in y_pred]
plt.scatter(X_test, y_test) plt.scatter(X_test, y_pred, c="red") plt.show()# Calculating the accuracy accuracy = 0 for i in range(len(y_pred)): if y_pred[i] == y_test.iloc[i]: accuracy += 1 print(f"Accuracy = {accuracy / len(y_pred)}")
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from math import exp
# Source of dataset - https://www.kaggle.com/rakeshrau/social-network-ads
# !wget "https://drive.google.com/uc?id=15WAD9_4CpUK6EWmgWVXU8YMnyYLKQvW8&export=download" -O data.csv -q# Load the dataset
data = pd.read_csv("data.csv")
data.head(10)
X_train, X_test, y_train, y_test = train_test_split(data['Age'], data['Purchased'], test_size=0.20)
# Building the Logistic Regression model
# Normalising the data
def normalize(X):
return X - X.mean()
# Make predictions
def predict(X, b0, b1):
return np.array([1 / (1 + exp(-1*b0 + -1*b1*x)) for x in X])
# The model
def logistic_regression(X, Y):
X = normalize(X)
# Initializing variables
b0 = 0
b1 = 0
L = 0.001
epochs = 300
for epoch in range(epochs):
y_pred = predict(X, b0, b1)
D_b0 = -2 * sum((Y - y_pred) * y_pred * (1 - y_pred)) # Loss wrt b0
D_b1 = -2 * sum(X * (Y - y_pred) * y_pred * (1 - y_pred)) # Loss wrt b1
# Update b0 and b1
b0 = b0 - L * D_b0
b1 = b1 - L * D_b1
return b0, b1
# Training the Model
b0, b1 = logistic_regression(X_train, y_train)# Making predictions and setting a thresholdX_test_norm = normalize(X_test)
y_pred = predict(X_test_norm, b0, b1)
y_pred = [1 if p >= 0.5 else 0 for p in y_pred]
# Plotting the data
plt.scatter(X_test, y_test)
plt.scatter(X_test, y_pred, c="red")
plt.show()# Calculating the accuracy
accuracy = 0
for i in range(len(y_pred)):
if y_pred[i] == y_test.iloc[i]:
accuracy += 1
print(f"Accuracy = {accuracy / len(y_pred)}")
https://www.kaggle.com/code/vasanth03/cat-or-dog-classification-sklearn-and-pytorch