Help with Problem 16 Advanced
I get the error “The answer is not correct - Test cases: 9 / 10” along with “Test Failed: AssertionError: '[1 1]' != '[0 1]'“
I know it’s right, at least visually, because when I plot it it connects to three nearest dots.
This almost exact same thing happens when I do the intermediate exercise. Any help would be welcome:
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
# create random data with two classes
X, Y = make_blobs(n_samples=16, n_features=2, centers=2, center_box=(-2, 2))
# scale the data so that all values are between 0.0 and 1.0
X = MinMaxScaler().fit_transform(X)
# split two data points from the data as test data and
# use the remaining n-2 points as the training data
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=2)
# place-holder for the predicted classes
y_predict = np.empty(len(y_test), dtype=np.int64)
# produce line segments that connect the test data points
# to the nearest neighbors for drawing the chart
lines = []
# distance function
def dist(a, b):
sum = 0
for ai, bi in zip(a, b):
sum = sum + (ai - bi) ** 2
return np.sqrt(sum)
def main(X_train, X_test, y_train, y_test):
global y_predict
global lines
count=[]
k = 3 # classify our test items based on the classes of 3 nearest neighbors
# process each of the test data points
for i, test_item in enumerate(X_test):
# calculate the distances to all training points
distances = [dist(train_item, test_item) for train_item in X_train]
nearest = np.argmin(distances)
nearest_in_order = np.argsort(distances)#returns the indices of
#the sorted(small to large) 'nearest' list
#sorts through list of k=3 neighbors of "y_train"
#to see if it is if the three nearest neighbors are zero or one
for j in nearest_in_order[0:k]:
if y_train[j]==1:
count.append(1)
elif y_train[j]==0:
count.append(0)
NN=np.round(np.mean(count)) #the nearesst neighbor of "count" can be
#found by these argument given to us by "Building AI"
# create a line connecting the points for the chart
# you may change this to do the same for all the k nearest neigbhors if you like
# but it will not be checked in the tests
lines.append(np.stack((test_item, X_train[nearest])))
lines.append(np.stack((test_item, X_train[nearest_three[1]])))
lines.append(np.stack((test_item, X_train[nearest_three[2]])))
y_predict[i] =NN #this is nearest neighbor
print(y_predict)
main(X_train, X_test, y_train, y_test)