绘制神经网络的基本示例

时间:2017-06-08 11:25:58

标签: python pandas neural-network deep-learning artificial-intelligence

我正在研究神经网络教程并制作如下所示的简单感知器代码

目的是

  • 将20分分成两组。

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's wrong!!
        Y = (w[0] * X + w[1] * X) - b # it's wrong!!

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

这个源代码给了我 这样的最终答案

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

但我该如何策划?

我想在两组之间划线。

最终图表(行)应该与此enter image description here

类似

1 个答案:

答案 0 :(得分:0)

您可以使用scatter绘制数据,使用contour进行边界决策:

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