【问题标题】:Plot basic example of neural network绘制神经网络的基本示例
【发布时间】:2017-11-10 02:12:09
【问题描述】:

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

目的是

  • 将 20 个点分成两组。

感知器.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

但是我怎样才能绘制这个呢?

我想在两组之间划清界限。

最终的图形(线)应该是这样的

【问题讨论】:

  • 你确定w和x的尺寸吗?
  • 是的 w 和 x 是二维的
  • w 和 b 是常量,Y = (w[0] * X + w[1] * X) - b 中没有任何内容会随着 X 的值增加而减小。可能你想使用X = np.linspace(100,1,100)
  • 感谢 Sardar,我添加了完整的源代码。

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


【解决方案1】:

您可以使用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()

【讨论】:

    猜你喜欢
    • 2017-02-03
    • 2022-01-20
    • 2017-08-27
    • 2016-03-21
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    相关资源
    最近更新 更多