Basic example of a neural network

I am studying a neural network tutorial and made a simple perceptron code as shown below

purpose

  • Dividing 20 points into two groups.

perceptron.py

import numpy as np
from pprint import pprint 

import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from tensorflow.contrib.learn.python.learn.tests.dataframe.mocks import Mock2x2Transform

plt.style.use('ggplot') 
font = {'family' : 'meiryo'}
matplotlib.rc('font', **font)

rng = np.random.RandomState(123)

d = 2  #dimension
N = 10 # each group items

mean = 5
x1 = rng.randn(N,d) + np.array([0,0]) # group 0
x2 = rng.randn(N,d) + np.array([mean,mean]) $group 1

x = np.concatenate((x1,x2),axis = 0)    

##### Plot points 
allDf = pd.DataFrame(columns=['x','y'])
k = 0
for i in x:
    print(i[0])
    temp = pd.DataFrame({'x' : i[0],
                         'y' : i[1]},index=[k])
    k = k + 1
    allDf = pd.concat([allDf,temp])

pprint(allDf)
allDf.plot(kind='scatter',x = 'x',y='y')
#########


#initialize w b
w = np.zeros(d)
b = 0

def y(x):
    return step(np.dot(w,x) + b)

def step(x):
    return 1 * (x > 0)

def t(i):
    if i < N:
        return 0
    else:
        return 1

while True:
    classified = True
    for i in range(N * 2):
        delta_w = (t(i) - y(x[i])) * x[i] 
        delta_b = (t(i) - y(x[i]))

        w += delta_w
        b += delta_b

        classified *= all(delta_w == 0 ) * (delta_b == 0)
    if classified:
        print("Final answer")
        pprint(w)
        pprint(b) # I get the answer here but how can I plot this w and b

        X = np.linspace(-2,6,100) #  it wrong!!
        Y = (w[0] * X + w[1] * X) - b # it wrong!!

        plt.plot(X,Y)
        plt.show()
        break

      

This source code gives me a definitive answer like this

w = array([ 2.14037745,  1.2763927 ])
b = -9

      

But how to do that?

I want to draw a line between two groups.

The final graph (line) should be like enter image description here

+3


source to share


1 answer


You can plot using scatter

for data and contour

for edge solution:

xx = np.linspace(-2,10)
yy = np.linspace(-2,10)
[X1,X2] = np.meshgrid(xx,yy)
Y = [t(i) for i in range(len(x))]

Z = (w[0] * X1.ravel() + w[1] * X2.ravel()) + b 

plt.scatter(x[:,0], x[:,1], s=20, c=Y, cmap=None, vmin=0, vmax=2)
plt.contour(X1,X2,Z.reshape(X1.shape), levels=[0], cmap='gray')
plt.show()

      



enter image description here

0


source







All Articles