def __test__(): dataSet, labels = kNN.createDataSet() inX = array([1.2, 1.1]) k = 3 outputLabel = kNN.kNNClassify(inX, dataSet, labels, 3) print("Your input is:", inX, "and classified to class: ", outputLabel) inX = array([0.1, 0.3]) outputLabel = kNN.kNNClassify(inX, dataSet, labels, 3) print("Your input is:", inX, "and classified to class: ", outputLabel)
def kNNtest(): # 生成数据集和类别标签 dataSet, labels = kNN.createDataSet() # 定义一个未知类别的数据 with open('test_24.json', 'r') as file: for line in file: line = json.loads(line) testid = line[0] testtarget = line[1:] testX = array([testtarget]) # 调用分类函数对未知数据分类 outputLabel = kNN.kNNClassify(testX, dataSet, labels, 1) result = [outputLabel, testid] with open('testPredict24.json', 'a') as file: file.write(json.dumps(result) + '\n')
def compute_accuracy(test_proto_visual, test_visual, test_proto2label, test_x2label): # test_proto: [50, 312] # test visual: [2993, 1024] # test_proto2label: proto2label [50] # test_x2label: x2label [2993] outpred = [0] * test_visual.shape[0] for i in range(test_visual.shape[0]): outputLabel = kNN.kNNClassify(test_visual[i, :], test_proto_visual.cpu().data.numpy(), test_proto2label, 1) outpred[i] = outputLabel outpred = np.array(outpred) acc = np.equal(outpred, test_x2label).mean() return acc
def compute_accuracy(test_att, test_visual, test_id, test_label): global left_a2 att_pre = sess.run(left_a2, feed_dict={att_features: test_att}) test_id = np.squeeze(np.asarray(test_id)) outpre = [0] * 2933 test_label = np.squeeze(np.asarray(test_label)) test_label = test_label.astype("float32") for i in range(2933): outputLabel = kNN.kNNClassify(test_visual[i, :], att_pre, test_id, 1) outpre[i] = outputLabel correct_prediction = tf.equal(outpre, test_label) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) result = sess.run(accuracy, feed_dict={ att_features: test_att, visual_features: test_visual }) return result
def compute_accuracy(test_att, test_visual, test_id, test_label): global left_a2 att_pre = sess.run(left_a2, feed_dict={att_features: test_att}) test_id = np.squeeze(np.asarray(test_id)) outpre = [0] * test_visual.shape[0] # CUB 2933 test_label = np.squeeze(np.asarray(test_label)) test_label = test_label.astype("float32") for i in range(test_visual.shape[0]): # CUB 2933 outputLabel = kNN.kNNClassify(test_visual[i, :], att_pre, test_id, 1) outpre[i] = outputLabel # compute averaged per class accuracy outpre = np.array(outpre, dtype='int') unique_labels = np.unique(test_label) acc = 0 for l in unique_labels: idx = np.nonzero(test_label == l)[0] acc += accuracy_score(test_label[idx], outpre[idx]) acc = acc / unique_labels.shape[0] return acc
def compute_accuracy(test_att, test_visual, test_id, test_label): # test_att: [2993, 312] # test viaual: [2993, 1024] # test_id: att2label [50] # test_label: x2label [2993] test_att = Variable(torch.from_numpy(test_att).float().cuda()) att_pred = forward(test_att) outpred = [0] * 2933 test_label = test_label.astype("float32") # att_pre [50, 1024], # test_visual: [2993, 1024] # test_id : [50] for i in range(2933): outputLabel = kNN.kNNClassify(test_visual[i, :], att_pred.cpu().data.numpy(), test_id, 1) outpred[i] = outputLabel outpred = np.array(outpred) acc = np.equal(outpred, test_label).mean() return acc
import kNN from numpy import * dataSet, labels = kNN.createDataSet() testX = array([1.9, 3.2]) k = 3 outputLabel = kNN.kNNClassify(testX, dataSet, labels, 3) print("Your input is:", testX, "and classified to class: ", outputLabel) testX = array([4.1, 3.3]) outputLabel = kNN.kNNClassify(testX, dataSet, labels, 3) print("Your input is:", testX, "and classified to class: ", outputLabel)
# -*- coding: utf-8 -*- # writer : lgy # data : 2017-08-19 import kNN from numpy import * dataSet, labels = kNN.createDataSet() testX = array([1.2, 1.0]) k = 3 outputLabel = kNN.kNNClassify(testX, dataSet, labels, 3) print "Your input is:", testX, "and classified to class: ", outputLabel testX = array([0.1, 0.3]) outputLabel = kNN.kNNClassify(testX, dataSet, labels, 3) print "Your input is:", testX, "and classified to class: ", outputLabel
def compute_accuracy(generator, test_semantic, test_visual, test_classIdx, \ test_videoLabel, use_z, n_gene_perC, classifier_type, \ n_epoch_sftcls): '''Evaluation''' device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') n_generation_perClass = n_gene_perC # how many samples are generated by G per class nb_samples = test_visual.shape[0] test_semantic = torch.from_numpy(test_semantic).float().to(device) if use_z == 'true': z = torch.randn(test_semantic.size()[0], z_dim).to(device) syn_vi_fea = generator(test_semantic, z) else: syn_vi_fea = generator(test_semantic) ## kNN as a classifier during testing if classifier_type == 'knn': outpred = [0] * nb_samples test_videoLabel = test_videoLabel.astype("float32") for i in range(nb_samples): outputLabel = kNN.kNNClassify(test_visual[i, :], syn_vi_fea.cpu().data.numpy(), test_classIdx, 5) outpred[i] = outputLabel outpred = np.array(outpred) acc = np.equal(outpred, test_videoLabel).mean() ## kernel svm as a classifier during testing elif classifier_type == 'svm' or 'softmax': expend_testvideoLabel = test_classIdx for cnt in range(n_generation_perClass - 1): if use_z == 'true': z = torch.randn(test_semantic.size()[0], z_dim).to(device) temp_syn_vi_fea = generator(test_semantic, z) else: temp_syn_vi_fea = generator(test_semantic) syn_vi_fea = torch.cat((syn_vi_fea, temp_syn_vi_fea), dim=0) expend_testvideoLabel = np.hstack( (expend_testvideoLabel, test_classIdx)) assert syn_vi_fea.size(0) == expend_testvideoLabel.shape[0] syn_vi_fea = syn_vi_fea.cpu().detach().numpy() dataset_obj = dict() dataset_obj['tr_data'] = syn_vi_fea dataset_obj['tr_label'] = expend_testvideoLabel dataset_obj['te_data'] = test_visual dataset_obj['te_label'] = test_videoLabel if classifier_type == 'svm': ksvm = MyKSVM(dataset_obj) acc1 = ksvm.linear_kernel() acc2 = ksvm.nonlinear_kernel( ) # if the degree equals to 3, may raise a MemoryError acc3 = ksvm.poly_kernel() acc4 = ksvm.RBF_kernel() acc = max((acc1, acc2, acc3, acc4)) elif classifier_type == 'softmax': n_class = len(test_classIdx) n_epoch = n_epoch_sftcls batch_size = -1 lr = 1e-3 sft_cls = fit_softmaxClassifier(n_class, dataset_obj, n_epoch, batch_size, lr) te_y = dataset_obj['te_label'] global_label = set(te_y) globalLabel2localLabel = dict() for global_idx, local_idx in zip(global_label, list(range(len(global_label)))): globalLabel2localLabel[global_idx] = local_idx te_y = np.array([globalLabel2localLabel[i] for i in te_y]) te_x = torch.from_numpy(dataset_obj['te_data']).float() te_y = torch.from_numpy(te_y).long() sft_cls.cpu() te_y_hat = sft_cls(te_x) acc = (np.argmax(te_y_hat.detach().numpy(), axis=1) == te_y.detach().numpy()).sum() / float(te_y.size()[0]) return acc
#!/usr/bin/env python #_*_coding:utf-8_*_ #kNN算法,调用示例。数据集在loadDataSet中设定了,也可以从文件读取 from numpy import mat import kNN if __name__ == "__main__": print("kNN近邻程序,输入:A B,如 1 2") data = mat(input()).tolist() trainData, yLabel = kNN.loadDataSet() result = kNN.kNNClassify(data, trainData, yLabel, 2, k=3) print(result)