I want to learn whether the x,y coordinates entered into the neural network are located above or below the sin curve.

Asked 2 years ago, Updated 2 years ago, 115 views

I was writing a code to learn whether the x,y coordinates entered into the neural network in python 3 are located above or below the sin curve, but an error occurred and I couldn't move forward and hit the wall.

Does the valueError seem to be a different type?I'm looking into it and expecting it, but what do you think?
If there is a mistake with the code, I would be very happy if you could let me know.

ValueError Traceback (most recent call last)
<ipython-input-15-628624d42e80>in<module>()
    126plt.plot(

ValueError Traceback (most recent call last)
<ipython-input-15-628624d42e80>in<module>()
    126plt.plot(X,sin_data,linestyle="dashed")
    127plt.scatter(x_1,y_1,marker="+")
-->128plt.scatter(x_2,y_2,marker="=")
    129plt.show()
    130 

~/anaconda3/lib/python3.6/site-packages/matplotlib/pyplot.py inscatter(x,y,s,c,marker,cmap,nX,sin_data,linestyle="dashed")
    127plt.scatter(x_1,y_1,marker="+")
-->128plt.scatter(x_2,y_2,marker="=")
    129plt.show()
    130 

~/anaconda3/lib/python3.6/site-packages/matplotlib/pyplot.py inscatter(x,y,s,c,marker,cmap,norm,vmin,vmax,alpha,linewidths,verts,edgecolors,hold,data,**kwargs)
   3355 vmin=vmin, vmax=vmax, alpha=alpha,
   3356 linewidths = linewidths, verts = verts,
->3357 edgecolors=edgecolors, data=data, **kwargs)
   3358 finally:
   3359ax._hold = washold

~/anaconda3/lib/python 3.6/site-packages/matplotlib/_init__.py in inner(ax, *args, **kwargs)
   1708 warnings.warn(msg%(label_namer, func.__name__),
   1709 RuntimeWarning, stacklevel=2)
- > 1710 return func (ax, *args, **kwargs)
   1711 pre_doc = inner.__doc__
   1712 if pre_doc is None:

~/anaconda3/lib/python 3.6/site-packages/matplotlib/axes/_axes.py inscatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewides, verts, edgecolors, **kwargs)
   4017y=np.ma.ravel(y)
   4018 if x.size!=y.size:
->4019 raise ValueError ("x and y must be the same size")
   4020 
   4021 if is None:

ValueError: x and y must be the same size

hereafter

%matplotlib inline

import numpy as np
import matplotlib.pyplot asplt

X = np.range (-1.0, 1.1, 0.1)
Y = np.range (-1.0, 1.1, 0.1)

input_data=[ ]
correct_data = [ ]
for x in X:
    for y in Y:
        input_data.append([x,y])
        if y<np.sin(np.pi*x):
            correct_data.append([0,1])
        else:
            correct_data.append([10])

n_data=len(correct_data)

input_data=np.array(input_data)
correct_data=np.array(correct_data)

n_in = 2
n_mid = 6
n_out = 2

wb_width=0.01
eta = 0.1
epoch=101
interval = 10

class MiddleLayer:
    def_init__(self, n_upper, n):
        self.w=wb_width*np.random.randn(n_upper,n)
        self.b = wb_width*np.random.randn(n)

    def forward (self, x):
        self.x = x
        u = np.dot(x,self.w) + self.b
        self.y = 1/(1+np.exp(-u))

    def backward(self,grad_y):
        delta=grad_y*(1-self.y)*self.y

        self.grad_w=np.dot(self.x.T, delta)
        self.grad_b=np.sum( delta,axis=0)

        self.grad_x = np.dot ( delta, self.w.T )

    default (self, eta):
        self.w -=eta*self.grad_w
        self.b - =eta*self.grad_b


classOutputLayer:
    def_init__(self, n_upper, n):
        self.w=wb_width*np.random.randn(n_upper,n)
        self.b = wb_width*np.random.randn(n)

    def forward (self, x):
        self.x = x
        u = np.dot(x,self.w) + self.b
        self.y=np.exp(u)/np.sum(np.exp(u), axis=1, keepdims=True)

    def backward (self, t):
        delta = self.y -t

        self.grad_w=np.dot(self.x.T, delta)
        self.grad_b=np.sum( delta,axis=0)

        self.grad_x = np.dot ( delta, self.w.T )

    default (self, eta):
        self.w -=eta*self.grad_w
        self.b - =eta*self.grad_b


middle_layer=MiddleLayer(n_in,n_mid)
output_layer = OutputLayer(n_mid, n_out)

sin_data=np.sin(np.pi*X)
for i in range (epoch):

    index_random=np.range(n_data)
    np.random.shuffle(index_random)


total_error = 0
x_1 = [ ]
y_1 = [ ]
x_2 = [ ]   
y_2 = [ ] 

for idx in index_random:

    x = input_data [idx]
    t=correct_data [idx]

    middle_layer.forward(x.reshape(1,2))
    output_layer.forward (middle_layer.y)

    output_layer.backward(t.reshape(1,2))
    middle_layer.backward (output_layer.grad_x)

    middle_layer.update(eta)
    output_layer.update(eta)

    if i% interval == 0:

        y = output_layer.y.reshape(-1)

        total_error+=np.sum(t*np.log(y+1e-7))

        if y[0]>y[1]:
            x_1.append(x[0])
            y_1.append(x[1])
        else:
            x_2.append(x[0])
            x_2.append(x[1])


if i% interval == 0:

    plt.plot(X,sin_data,linestyle="dashed")
    plt.scatter(x_1,y_1,marker="+")
    plt.scatter(x_2,y_2,marker="=")
    plt.show()

    print("Epoch:"+str(i)+"/"+str(epoch),
          "Error:" + str(total_error/n_data))

python matplotlib numpy anaconda

2022-09-30 15:42

1 Answers

The reason is that x_2 and y_2 have different sizes (print(len(x_2), len(y_2) displays 460,0 respectively).It seems to be a mistake in the following parts.

if y[0]>y[1]:
    x_1.append(x[0])
    y_1.append(x[1])
else:
    x_2.append(x[0])
    What about x_2.append(x[1])#<-y_2.append?


2022-09-30 15:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.