From a0d15c231558b62cf23bec917e8256b45cefc638 Mon Sep 17 00:00:00 2001 From: snsd0805 Date: Wed, 6 Dec 2023 04:01:52 +0800 Subject: [PATCH] feat: add hw5 p9, p10 --- hw5/hw5_10.py | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ hw5/hw5_9.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 hw5/hw5_10.py create mode 100644 hw5/hw5_9.py diff --git a/hw5/hw5_10.py b/hw5/hw5_10.py new file mode 100644 index 0000000..d0878a3 --- /dev/null +++ b/hw5/hw5_10.py @@ -0,0 +1,48 @@ +import numpy as np +import datetime +import random +from libsvm.svmutil import * +import matplotlib.pyplot as plt + +FILENAME = "satimage.scale" +TEST_FILENAME = "satimage.scale.t" +TARGET = 1 + +def new_label(y, target): + ans = [] + for i in y: + if i == target: + ans.append(1) + else: + ans.append(0) + return ans + +def error(predict, gt): + error_count = 0 + for index in range(len(predict)): + if predict[index] != gt[index]: + error_count += 1 + return error_count / len(predict) + +if __name__ == '__main__': + + y, x = svm_read_problem(FILENAME) + y = new_label(y, TARGET) + + test_y, test_x = svm_read_problem(TEST_FILENAME) + test_y = new_label(test_y, TARGET) + + for c in [0.01, 0.1, 1, 10, 100]: + print("C=", c) + prob = svm_problem(y, x) + param = svm_parameter('-s 0 -t 2 -g 1 -c {} -q'.format(c)) + m = svm_train(prob, param) + + p_label, p_acc, p_val = svm_predict(test_y, test_x, m) + my_error = error(p_label, test_y) + print("p_acc:", p_acc) + print("0/1 error:", my_error) + + + print("="*20) + diff --git a/hw5/hw5_9.py b/hw5/hw5_9.py new file mode 100644 index 0000000..13d058e --- /dev/null +++ b/hw5/hw5_9.py @@ -0,0 +1,30 @@ +import numpy as np +import datetime +import random +from libsvm.svmutil import * +import matplotlib.pyplot as plt + +FILENAME = "satimage.scale" +TEST_FILENAME = "satimage.scale.t" + +def new_label(y, target): + ans = [] + for i in y: + if i == target: + ans.append(1) + else: + ans.append(0) + return ans + +if __name__ == '__main__': + y, x = svm_read_problem(FILENAME) + y = new_label(y, 4) + + for c in [0.1, 1, 10]: + for q in [2, 3, 4]: + print("(C, Q)=({}, {})".format(c, q)) + prob = svm_problem(y, x) + param = svm_parameter('-s 0 -t 1 -d {} -c {}'.format(q, c)) + m = svm_train(prob, param) + print("="*20) +