<jupyter_start><jupyter_text>![](https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Machine+Learning+R/iris-machinelearning.png)<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

import warnings
warnings.filterwarnings('default')
from sklearn import datasets
iris = datasets.load_iris()
iris
x=iris.data[:, :2]
y=(iris.target != 0)*1
x
x[y==0]
plt.figure(figsize=(10,6))
plt.scatter(x[y==0][:,0], x[y==0][:,1], color='b', label='0')
plt.scatter(x[y==1][:,0], x[y==1][:,1], color='r', label='1')
plt.legend()
class LogisticRegression:
    def __init__(self, lr=0.01, num_iter=100000, fit_intercept=True, verbose=False):
        self.lr = lr
        self.num_iter = num_iter
        self.fit_intercept = fit_intercept
        self.verbose = verbose
        
    def __add_intercept(self, x):
        intercept = np.ones((x.shape[0], 1))
        return np.concatenate((intercept, x), axis=1)
    
    def __sigmoid(self, z):
        return 1/(1 + np.exp(-z))
    def __loss(self, h, y):
        return (-y*np.log(h) - (1-y)*np.log(1-h)).mean()
    
    def fit(self, x, y):
        if self.fit_intercept:
            x = self.__add_intercept(x)
            
        # weights initialization
        self.theta = np.zeros(x.shape[1])
        
        for i in range(self.num_iter):
            z = np.dot(x, self.theta)
            h = self.__sigmoid(z)
            gradient = np.dot(x.T, (h - y)) / y.size
            self.theta -= self.lr * gradient
            
            z = np.dot(x, self.theta)
            h = self.__sigmoid(z)
            loss = self.__loss(h,y)
            
            if(self.verbose == True and i % 10000 == 0):
                print(f'loss: {loss} \t')
                
    def predict_prob(self, x):
        if self.fit_intercept:
            x = self.__add_intercept(x)
            
        return self.__sigmoid(np.dot(x, self.theta))
    
    def predict(self, x):
        return self.predict_prob(x).round()
            
    
model = LogisticRegression(lr=0.1, num_iter=300000, verbose=True)
%time model.fit(x, y)
preds = model.predict(x)
(preds == y).mean()
model.theta
plt.figure(figsize=(10,6))
plt.scatter(x[y==0][:,0], x[y==0][:,1], color='b', label='0')
plt.scatter(x[y==1][:,0], x[y==1][:,1], color='r', label='1')
plt.legend()
X1_min, X1_max = x[:,0].min(), x[:,0].max(),
X2_min, X2_max = x[:,1].min(), x[:,1].max(),
xx1, xx2 = np.meshgrid(np.linspace(X1_min, X1_max), np.linspace(X2_min, X2_max))
grid = np.c_[xx1.ravel(), xx2.ravel()]
probs = model.predict_prob(grid).reshape(xx1.shape)
plt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors='black')
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(C=1e20)
%time model.fit(x, y)
preds = model.predict(x)
(preds == y).mean()
model.intercept_, model.coef_
for i in %time model.fit(x, y):
    print(i)<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup