Skip to content

Commit 105f931

Browse files
authored
Merge pull request #140 from jeffin07/master
Logistic Regression
2 parents c0f75b7 + b6d6a52 commit 105f931

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
from sklearn.datasets import load_iris
2+
from sklearn.model_selection import train_test_split
3+
import numpy as np
4+
5+
6+
7+
class LogisticRegression:
8+
def __init__(self, learning_rate, epochs):
9+
self.learning_rate = learning_rate
10+
self.epochs = int(epochs)
11+
12+
13+
def sigmoid(self, z):
14+
return 1 / (1 + np.exp(-z))
15+
16+
17+
def loss(self, h, y):
18+
return (-y * np.log(h) - (1-y) * np.log(1 - h)).mean()
19+
20+
21+
def fit(self, x, y):
22+
y=np.array(y)
23+
self.w=np.random.randn(x.shape[1])
24+
for i in range(self.epochs):
25+
z = np.dot(x,self.w)
26+
h=self.sigmoid(z)
27+
difference = np.dot(x.T,(h - y ))/len(y)
28+
self.w -= self.learning_rate*difference
29+
if i % 10 ==0:
30+
lo=self.loss(h, y)
31+
print("Loss at {} epoch is {} ".format(i,lo))
32+
return self.w
33+
34+
35+
def predict(self, x):
36+
return(self.sigmoid(np.dot(x, self.w)))
37+
38+
#Data preprocess
39+
iris = load_iris()
40+
x = iris.data[0:100, :2]
41+
y = []
42+
for i in iris.target:
43+
if i==0 or i==1:
44+
y.append(i)
45+
46+
model = LogisticRegression(0.1,1000)
47+
x_train,x_test, y_train, y_test=train_test_split(x , y)
48+
model.fit(x_train , y_train)
49+
y_pred = model.predict(x_test)
50+
for i in range(len(y_pred)):
51+
if y_pred[i] > 0.5:
52+
y_pred[i]=1
53+
else:
54+
y_pred[i]=0
55+
y_test=np.array(y_test)
56+
print("Accuracy is {} ".format((y_test == y_pred ).mean()*100))

0 commit comments

Comments
 (0)