示例#1
0
        if i == 0:
            plt.title(cls)
# plt.show()
# plt.close()

#选取5000张训练集, 500张测试集,
num_training = 5000
mask = range(num_claesses)
x_train = x_train[mask]
y_train = y_train[mask]
num_test = 500
mask = range(num_test)
x_test = x_test[mask]
y_test = y_test[mask]

x_train = np.reshape(x_train, (x_train.shape[0], -1))  #把图像数据拉长为行向量
x_test = np.reshape(x_test, (x_test.shape[0], -1))
print("x_train的shape:", x_train.shape)
print("x_test的shape:", x_test.shape)

# 3.2) 测试集预测
classifier = KNearestNeighbor()
classifier.train(x_train, y_train)
dists = classifier.compute_distances_no_loops(x_test)
print(dists)

y_test_pred = classifier.predict_labels(dists, k=1)
num_correct = np.sum(y_test_pred == y_test)
accuracy = float(num_correct) / num_test
print('got %d / %d correct => accuracy: %f' %
      (num_correct, num_test, accuracy))
示例#2
0
num_test = 500
mask = range(num_test)
x_test = x_test[mask]
y_test = x_test[mask]

x_train = np.reshape(x_train,(x_train.shape[0],-1))
x_test = np.reshape(x_test,(x_test.shape[0],-1))

classifier = KNearestNeighbor()
classifier.train(x_train,y_train)


#比较准确率
#dists = classifier.compute_distance_two_loops(x_test)
dists = classifier.compute_distance_one_loops(x_test)
y_test_pred = classifier.predict_labels(dists,k=1)
num_correct = np.sum(y_test_pred == y_test)
accuracy = float(num_correct)/num_test
print('get %d / %d correct =>accuracy : %f' % (num_correct ,num_test ,accuracy))

#dists_one = classifier.compute_distance_one_loops(x_test)
#difference = np.linalg.norm(dists-dists_one,ord='fro') #求范数
#print('difference was : %f' % difference)


#比较时间
import time
def time_function(f,*args):
    tic = time.time()
    f(*args)
    toc = time.time()