I am new at Python and running the code below. I get an index error (shown at th
ID: 3804166 • 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. I am trying to use b and sigma squared to calculate the RMSE on the 42test points and show the results in a table but can’t get over the error.
A few additional details:
Xtrain data - 350 rows, 7 Columns
Xtestdata - 42 Rows, 7 Colums
Ytrain data - 350 rows, 1 Columns
Ytestdata - 42 Rows, 1 Colums
b = [5,7,9,11,13,15]:
sigma squared = [.1,.2,.3,.4,.5,.6,.7,.8,.9,1]
===========================================================
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] // I changed this to the line below
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]-Xtraindata[j])**2))
matrix[i][j]=val
return matrix
#calculating K(X, Dn)
def K(b):
# rows = Xtraindata.shape[0] // I changed this to the line below
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
# 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)
350
(350, 350)
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-120-4eacf022e57a> in <module>()
3 for b in [5,7,9,11,13,15]:
4 for sigma in [.1,.2,.3,.4,.5,.6,.7,.8,.9,1]:
----> 5 kxdn=K(b)
6 kn =KN(b)
7 ypredict = MU(kxdn,sigma,kn)
<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
IndexError: index 42 is out of bounds for axis 0 with size 42
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))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.