Joan C.

asked • 10/08/21

I have a SGD perceptron training algorithm. I would like to modify this code to include different batch sizes with 5-fold cross validation.

def perce_online(X,y,w_ini,rho):

  (l,N) = np.shape(X)

  max_iter=500000

  w=np.reshape(w_ini,(3,1));

  iter=0;

  mis_clas=N;

  while mis_clas>0 and iter<max_iter:

    mis_clas=0

    for i in range(N):

      if np.dot((X[:,i]),w)*y[i]<0:

          mis_clas=mis_clas+1

          w=w+np.reshape(rho*y[i]*X[:,i],(3,1))

      iter=iter+1

  return w,iter,mis_clas

N= [100,100]

l=2

np.random.seed(0)

x=[3,3]

X1=np.concatenate((2*np.random.rand(l,N[0]),2*np.random.rand(l,N[1])+np.concatenate((np.ones((1,N[1]))*x[0],np.ones((1,N[1]))*x[1]),axis=0)),axis=1)

X1=np.concatenate((X1,np.ones((1,sum(N)))),axis=0)

y1=np.concatenate((np.ones((1,N[0])),-np.ones((1,N[1]))),axis=1)[0]

print(y1.shape)

plt.plot(X1[0,:100],X1[1,:100],'bo',X1[0,100:],X1[1,100:],'r.')

rho=0.01

w_ini=np.transpose([1,1,.5]);

w,iter,mis_clas=perce_online(X1,y1,w_ini,rho)

print('Number of iterations=',iter)

Xtrain has dimensions 90, 2

Xval has dimensions 30, 2

Xtest has dimensions 30, 2

Ytrain has dimensions 90, 1

Yval has dimensions 30, 1

Ytest has dimensions 30, 1

1 Expert Answer

By:

TutorKelvin D. answered • 01/03/24

Tutor
New to Wyzant

R Studio Expert for Machine Learning and Data Science

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.