generated from LufsX/Challenge-SVM
This commit is contained in:
+20
-8
@@ -9,17 +9,17 @@ def load_data(filepath):
|
|||||||
data = np.genfromtxt(filepath, delimiter=',', dtype=float, filling_values=np.nan)
|
data = np.genfromtxt(filepath, delimiter=',', dtype=float, filling_values=np.nan)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"数据加载错误,可能是由于数据格式不正确:{e}")
|
print(f"数据加载错误,可能是由于数据格式不正确:{e}")
|
||||||
return None, None
|
return None
|
||||||
|
|
||||||
# 检查数据是否为二维数组
|
# 检查数据是否为二维数组
|
||||||
if data is None or data.ndim != 2:
|
if data is None or data.ndim != 2:
|
||||||
print("数据不是二维数组,无法继续处理。")
|
print("数据不是二维数组,无法继续处理。")
|
||||||
return None, None
|
return None
|
||||||
|
|
||||||
# 确保所有行都有相同数量的列
|
# 确保所有行都有相同数量的列
|
||||||
if data.shape[1] < 2:
|
if data.shape[1] < 2:
|
||||||
print("数据列数不正确,无法继续处理。")
|
print("数据列数不正确,无法继续处理。")
|
||||||
return None, None
|
return None
|
||||||
|
|
||||||
# 分离特征和标签
|
# 分离特征和标签
|
||||||
X = data[:, :-1]
|
X = data[:, :-1]
|
||||||
@@ -45,20 +45,32 @@ def train_svm(X, y, learning_rate=0.01, iterations=1000, regularization=1.0):
|
|||||||
def predict_svm(inX, weights, bias):
|
def predict_svm(inX, weights, bias):
|
||||||
return np.sign(np.dot(inX, weights) - bias)
|
return np.sign(np.dot(inX, weights) - bias)
|
||||||
|
|
||||||
|
def evaluate_svm(X_test, y_test, weights, bias):
|
||||||
|
if X_test is None or y_test is None:
|
||||||
|
print("测试数据加载失败,无法评估。")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
correct = 0
|
||||||
|
for i in range(len(X_test)):
|
||||||
|
if predict_svm(X_test[i], weights, bias) == y_test[i]:
|
||||||
|
correct += 1
|
||||||
|
accuracy = correct / len(X_test)
|
||||||
|
return accuracy
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 加载训练集
|
# 加载训练集
|
||||||
X_train, y_train = load_data("./data/horse-colic.data")
|
X_train, y_train = load_data("./data/horse-colic.data")
|
||||||
if X_train is None or y_train is None:
|
if X_train is None:
|
||||||
print("训练数据加载失败。")
|
print("训练数据加载失败。")
|
||||||
else:
|
else:
|
||||||
# 加载测试集
|
# 加载测试集
|
||||||
X_test, y_test = load_data("./data/horse-colic.test")
|
X_test, y_test = load_data("./data/horse-colic.test")
|
||||||
if X_test is None or y_test is None:
|
if X_test is None:
|
||||||
print("测试数据加载失败。")
|
print("测试数据加载失败。")
|
||||||
else:
|
else:
|
||||||
# 训练支持向量机模型
|
# 训练支持向量机模型
|
||||||
weights, bias = train_svm(X_train, y_train, learning_rate=0.01, iterations=1000)
|
weights, bias = train_svm(X_train, y_train, learning_rate=0.01, iterations=1000)
|
||||||
|
|
||||||
# 测试单个数据
|
# 评估模型
|
||||||
y_pred = predict_svm(X_test[11], weights, bias)
|
accuracy = evaluate_svm(X_test, y_test, weights, bias)
|
||||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
print(f"模型准确率: {accuracy}")
|
||||||
Reference in New Issue
Block a user