Commits

Miki Tebeka committed 49428a4

rename

Comments (0)

Files changed (2)

+# coding=utf8
+
+import matplotlib.pylab as plt
+import numpy as np
+from sklearn import linear_model
+
+
+def parse_line(line):
+    return map(float, line.split(','))
+
+
+def load():
+    return np.loadtxt('ex2/ex2data1.txt', delimiter=',')
+
+
+def load_features():
+    data = load()
+    xys = data[:,0:2]
+    ones = np.ones((len(xys), 1))
+    return np.append(ones, xys, 1), data[:,2]
+
+
+def sigmoid(z):
+    return 1. / (1 + np.e**(-z))
+
+usig = np.vectorize(sigmoid)
+
+
+def diff(theta, xi, yi):
+    ht = xi * theta.T
+    return -np.log(ht) if yi else np.log(1-ht)
+
+
+def J(theta, xs, ys):
+    d = lambda xi, yi: diff(theta, xi, yi)
+    m = float(len(xs))
+    return sum(d(xi, yi) for (xi, yi) in zip(xs, ys)) / m
+
+
+def learn_p():
+    xs, ys = load_features()
+    clf = linear_model.LogisticRegression()
+    clf.fit(xs, ys)
+
+    count = 0
+    for x, y in zip(xs, ys):
+        v = clf.predict(x)
+        if v >= 0.5 and y:
+            count += 1
+        elif v < 0.5 and not y:
+            count += 1
+
+    return float(count) / len(xs) * 100
+
+
+def plot(data):
+    passed = data[data[:,2]==1]
+    failed = data[data[:,2]==0]
+
+
+    fig = plt.figure()
+    ax = fig.add_subplot(111)
+    ax.scatter(passed[:,0], passed[:,1], color='black', marker='+',
+               label='Admitted')
+    ax.scatter(failed[:,0], failed[:,1], color='red', marker='o',
+              label='Not admitted')
+    ax.set_xlabel('Exam 1 score')
+    ax.set_ylabel('Exam 2 score')
+    plt.legend()
+    plt.show()
+
+
+if __name__ == '__main__':
+    print(learn_p())

ex2.py

-import matplotlib.pylab as plt
-import numpy as np
-
-
-def parse_line(line):
-    return map(float, line.split(','))
-
-
-def load():
-    with open('ex2/ex2data1.txt') as fo:
-        return np.array([parse_line(line) for line in fo])
-
-
-def plot(data):
-    passed = data[data[:,2]==1]
-    failed = data[data[:,2]==0]
-
-    fig = plt.figure()
-    ax = fig.add_subplot(111)
-    ax.scatter(passed[:,0], passed[:,1], color='black', marker='+',
-               label='Admitted')
-    ax.scatter(failed[:,0], failed[:,1], color='orange', marker='o',
-              label='Not admitted')
-    ax.set_xlim(min(data[:,0]), max(data[:,0]))
-    ax.set_ylim(min(data[:,1]), max(data[:,1]))
-    ax.set_xlabel('Exam 1 score')
-    ax.set_ylabel('Exam 2 score')
-    plt.legend()
-    plt.show()
-
-