Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am new at Python and running the code below. I get an index error (shown at th

ID: 3804062 • Letter: I

Question

I am new at Python and running the code below. I get an index error (shown at the buttom of the code below) and cant seem to figure out what i am doing wrong: Any ideas as how to fix will be appreciated.

===========================================================

import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import norm,inv
import csv
import numpy

# Load CSV (using python)
Xtest = 'X_test.csv'
Ytest = 'Y_test.csv'
Xtrain = 'X_train.csv'
Ytrain = 'Y_train.csv'

Xtraindata = numpy.genfromtxt(Xtrain,delimiter=',')
Xtestdata = numpy.genfromtxt(Xtest,delimiter=',')
Ytraindata = numpy.genfromtxt(Ytrain,delimiter=',')
Ytestdata = numpy.genfromtxt(Ytest,delimiter=',')
print(Xtraindata.shape)
print(Xtestdata.shape)
print(Ytestdata.shape)
print(Ytraindata.shape)

def KN(b):
rows = Xtraindata.shape[0]
print (rows)
matrix = numpy.zeros((350,350))
print(matrix.shape)
for i in range(rows):
for j in range(rows):
val = numpy.exp((-1/b)*(norm(Xtraindata[i]-Xtraindata[j])**2))
matrix[i][j]=val
return matrix

#calculating K(X, Dn)
def K(b):
rows = Xtraindata.shape[0]
print (rows)
matrix = numpy.zeros((350,350))
print(matrix.shape)
for i in range(rows):
for j in range(rows):
val = numpy.exp((-1/b)*(norm(Xtraindata[i]-Xtestdata[j])**2))
matrix[i][j]=val
return matrix

# Loping KN over b and sigma squared.

for b in [5,7,9,11,13,15]:
for sigma in [.1,.2,.3,.4,.5,.6,.7,.8,.9,1]:
kxdn=K(b)
kn =KN(b)
ypredict = MU(kxdn,sigma,kn)

Explanation / Answer

<ipython-input-119-22f043ab945a> in K(b)
      7     for i in range(rows):
      8         for j in range(rows):
----> 9             val = numpy.exp((-1/b)*(norm(Xtraindata[i]-Xtestdata[j])**2))
     10             matrix[i][j]=val
     11     return matrix

  
   Xtraindata is having size 42. Here elements
   will be indexed from 0 to 41, you are trying
   to access element 42 which is not possible
   leading to this error,
  
   To fix it:
  
   def K(b):
    #rows = Xtraindata.shape[0] // This line is culprit, Update this line we need size of this Xtraindata to iterate over
   rows = len(Xtraindata)
    print (rows)
    matrix = numpy.zeros((350,350))
    print(matrix.shape)
    for i in range(rows):
        for j in range(rows):
            val = numpy.exp((-1/b)*(norm(Xtraindata[i]-Xtestdata[j])**2))
            matrix[i][j]=val
    return matrix