generated from LufsX/Challenge-SVM
This commit is contained in:
+18
-4
@@ -31,22 +31,36 @@ name = "董秋"
|
|||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
data = []
|
data = []
|
||||||
labels = []
|
labels = []
|
||||||
|
|
||||||
with open(filepath, 'r') as file:
|
with open(filepath, 'r') as file:
|
||||||
for line in file:
|
for line in file:
|
||||||
fields = line.strip().split()
|
fields = line.strip().split()
|
||||||
fields = [0 if f == '?' else float(f) for f in fields] # 缺失值填充
|
|
||||||
|
# 处理缺失值,用0填充
|
||||||
|
fields = [0 if f == '?' else float(f) for f in fields]
|
||||||
|
|
||||||
|
# 特征是除最后一列外的所有列
|
||||||
features = np.array(fields[:-1], dtype=float)
|
features = np.array(fields[:-1], dtype=float)
|
||||||
|
|
||||||
|
# 标签是最后一列
|
||||||
label = int(fields[-1])
|
label = int(fields[-1])
|
||||||
|
|
||||||
|
# 添加数据和标签
|
||||||
data.append(features)
|
data.append(features)
|
||||||
labels.append(label)
|
labels.append(label)
|
||||||
labels = np.array(labels)
|
|
||||||
|
|
||||||
# 检查标签是否为三类
|
# 转换为numpy数组
|
||||||
|
labels = np.array(labels)
|
||||||
|
data = np.array(data)
|
||||||
|
|
||||||
|
# 检查标签的唯一值,确保只有 0, 1, 2
|
||||||
unique_labels = np.unique(labels)
|
unique_labels = np.unique(labels)
|
||||||
|
|
||||||
if len(unique_labels) != 3:
|
if len(unique_labels) != 3:
|
||||||
|
print(f"错误:标签数据包含的类别不是3个,实际类别为:{unique_labels}")
|
||||||
raise ValueError("标签数量不为3,请确保标签未合并!")
|
raise ValueError("标签数量不为3,请确保标签未合并!")
|
||||||
|
|
||||||
return np.array(data), labels
|
return data, labels
|
||||||
|
|
||||||
def train_svm(X, y, learning_rate=0.01, iterations=1000, regularization_strength=0.01):
|
def train_svm(X, y, learning_rate=0.01, iterations=1000, regularization_strength=0.01):
|
||||||
n_samples, n_features = X.shape
|
n_samples, n_features = X.shape
|
||||||
|
|||||||
Reference in New Issue
Block a user