Usando scikit-learn

Aqui mostramos como usar alguns classificadores disponíveis no scikit-learn

1. Gerar os dados

In [1]:
import numpy as np
import matplotlib.pyplot as plt
from funcoes import geraDados2DfronteiraNonLinear

%matplotlib inline

N = 100
X, y, x, fx = geraDados2DfronteiraNonLinear(N)
Shape do X:  (100, 3)
Shape do y:  (100,)
In [2]:
from sklearn.linear_model import LogisticRegression

clf = LogisticRegression(max_iter=100)  # default max_iter=100
clf.fit(X,y)

z = clf.predict(X)

print(z)

for i in range(N):
    if z[i] > 0.5:
        plt.plot(X[i,1], X[i,2], 'bx')
    else:
        plt.plot(X[i,1], X[i,2], 'ro')

plt.plot(x, fx, lw=2)
plt.xlabel('x1')
plt.ylabel('x2')
plt.show()
[1 1 0 1 1 1 1 0 1 0 1 1 1 1 0 0 1 1 1 1 0 0 0 1 0 1 1 1 1 1 0 1 0 1 1 0 0
 1 1 0 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 0 1 0 1 1 0 0 0 0 0
 1 0 1 0 1 1 1 1 0 1 1 0 0 0 1 0 1 0 1 1 0 0 1 1 0 1]
In [3]:
from sklearn import svm

clf = svm.SVC(gamma=0.3, C=100.)
clf.fit(X,y)

z = clf.predict(X)

print(z)

for i in range(N):
    if z[i] > 0.5:
        plt.plot(X[i,1], X[i,2], 'bx')
    else:
        plt.plot(X[i,1], X[i,2], 'ro')
        
plt.plot(x, fx, lw=2)
plt.xlabel('x1')
plt.ylabel('x2')
plt.show()
[1 0 0 1 1 0 1 0 1 1 0 1 1 1 0 0 0 0 1 1 1 0 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0
 1 1 1 1 1 0 1 1 0 1 0 0 0 1 0 0 1 1 1 0 0 0 0 1 1 1 0 0 1 0 0 1 0 0 1 0 0
 0 1 1 1 0 1 0 0 0 1 1 1 0 1 0 1 0 1 0 1 0 1 0 0 1 0]
In [4]:
from sklearn.neural_network import MLPClassifier

clf = MLPClassifier(solver='sgd', learning_rate_init=0.01, max_iter=500, hidden_layer_sizes=(10), random_state=1)

clf.fit(X, y)

z = clf.predict(X)
print(z)

for i in range(N):
    if z[i] > 0.5:
        plt.plot(X[i,1], X[i,2], 'bx')
    else:
        plt.plot(X[i,1], X[i,2], 'ro')
        
plt.plot(x, fx, lw=2)
plt.xlabel('x1')
plt.ylabel('x2')
plt.show()
[1 1 0 1 0 1 1 0 1 1 1 1 1 1 0 0 1 1 1 1 0 0 1 1 0 1 1 1 1 1 0 1 0 1 0 0 0
 1 1 0 1 0 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 0 0 0 1 1 1 1 1 0 1 1 0 1 0 0 0
 1 1 1 0 0 1 1 1 0 1 1 1 0 0 1 0 1 1 1 1 0 0 1 1 1 1]
/home/nina/anaconda3/lib/python3.5/site-packages/sklearn/neural_network/multilayer_perceptron.py:563: ConvergenceWarning: Stochastic Optimizer: Maximum iterations reached and the optimization hasn't converged yet.
  % (), ConvergenceWarning)