Question: HW 1 : K - NN Implementation Requirements: Implement K nearest neighbors algorithm to predict the housing median value ( 2 ) ( 1 0

HW
1
: K
-
NN Implementation
Requirements: Implement K nearest neighbors algorithm to predict the housing median value
(2)(10
points
)
-
Create a function used to calculate the average price of k
-
NNs in the training subset for any given testing sample and a given k
-
Test a sample from the testing subset and compare the k
-
NN price
(
k
=
5)
with the sample real price.
(3)(10
points
)
-
Create a function used to find root mean squared
-
error for all
1000
X
_
test samples with given k
=
5
#
10
points define a function which is used to find k
-
NN
'
s average pricethe formula to calculate the Scipy's Euclidean distance of sample
1
and sample
2
:def find
_
kNNmean
_
price
(
X
,
y
,
selected, k
)
:
""
!
"
for any selected sample, find its K
-
NN neighbors' average price
input:
X: the training dataframe,
y: the training data price,
selected: any row of the testing dataframe,
k: the number of neighbors in the training dataframe. k is int and larger than
0
return:
k
_
nn
'
s average price, floating point
"'""
A sample outputsample
=
0
: the real price
245300.0
For a single sample, the k
-
NN prediction:This step will take about
2
minutes in my case
def root
_
mse
(
X
,
y
,
X
_
test
_
1
k
,
y
_
test
_
1
k
,
k
)
:
"
!
"
,
For a given k
,
collect their kNN
_
average price, then find the rsme
Input:
X
_
test
_
copy: dataframe of all testing samples
y
_
test
_
copy: data series of all testing sample prices
k: the number of neighbors, int.
Return:
rmse: the root mean square erros, floating point type
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
#k
=
5
and rmse
=
68890.19
for k
=
5
,
the rmse

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!