generated from LufsX/Challenge-SVM
This commit is contained in:
+27
-35
@@ -28,7 +28,7 @@ name = "董秋"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def train_svm(X, y, other_params="你自己设置一些其它参数"):
|
||||
def train_svm(X, y, learning_rate=0.01, iterations=1000):
|
||||
"""
|
||||
支持向量机训练函数。
|
||||
|
||||
@@ -41,21 +41,19 @@ def train_svm(X, y, other_params="你自己设置一些其它参数"):
|
||||
- numpy array: 训练得到的权重。
|
||||
"""
|
||||
n_samples, n_features = X.shape
|
||||
weights = np.zeros(n_features) # 初始化权重
|
||||
bias = 0 # 初始化偏置
|
||||
n_classes = len(np.unique(y))
|
||||
weights = np.zeros((n_classes, n_features))
|
||||
|
||||
for _ in range(iterations):
|
||||
for idx, x_i in enumerate(X):
|
||||
condition = y[idx] * (np.dot(x_i, weights) + bias) >= 1
|
||||
if condition:
|
||||
# 更新公式,不需要正则化项
|
||||
weights -= learning_rate * (2 * lambda_param * weights)
|
||||
else:
|
||||
# 更新公式,包括误分类损失
|
||||
weights -= learning_rate * (2 * lambda_param * weights - np.dot(x_i, y[idx]))
|
||||
bias -= learning_rate * y[idx]
|
||||
for c in range(n_classes):
|
||||
y_i = 1 if y[idx] == c else -1
|
||||
if y_i * (np.dot(weights[c], x_i)) < 1:
|
||||
weights[c] += learning_rate * (y_i * x_i - (2 * 1/iterations) * weights[c])
|
||||
else:
|
||||
weights[c] -= learning_rate * (2 * 1/iterations) * weights[c]
|
||||
|
||||
return np.append(weights, bias) # 将偏置合并到权重中
|
||||
return weights
|
||||
|
||||
def predict_svm(inX, weights):
|
||||
"""
|
||||
@@ -68,10 +66,8 @@ def predict_svm(inX, weights):
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
w = weights[:-1] # 分离权重和偏置
|
||||
b = weights[-1]
|
||||
linear_output = np.dot(inX, w) + b
|
||||
return 1 if linear_output >= 0 else -1
|
||||
scores = [np.dot(w, inX) for w in weights]
|
||||
return np.argmax(scores)
|
||||
|
||||
# 这里也写自己的代码实现
|
||||
def load_data(filepath):
|
||||
@@ -87,27 +83,23 @@ def load_data(filepath):
|
||||
"""
|
||||
data = []
|
||||
labels = []
|
||||
|
||||
with open(filepath, 'r') as file:
|
||||
for line in file:
|
||||
values = line.strip().split()
|
||||
# 将缺失值用0填充,并将所有数据转换为浮点数
|
||||
features = [float(v) if v != '?' else 0.0 for v in values[:-1]]
|
||||
label = values[-1] # 假设最后一列是标签列
|
||||
|
||||
# 根据标签值进行三分类的标签转换
|
||||
if label == '1':
|
||||
labels.append(0) # 存活
|
||||
elif label == '2':
|
||||
labels.append(1) # 死亡
|
||||
elif label == '3':
|
||||
labels.append(2) # 安乐死
|
||||
|
||||
data.append(features)
|
||||
|
||||
X = np.array(data)
|
||||
y = np.array(labels)
|
||||
return X, y
|
||||
line = line.strip().split()
|
||||
if len(line) > 1:
|
||||
label = line[0]
|
||||
if label == "死亡":
|
||||
label = 0
|
||||
elif label == "安乐死":
|
||||
label = 1
|
||||
elif label == "存活":
|
||||
label = 2
|
||||
labels.append(label)
|
||||
|
||||
features = [float(x) if x != '?' else 0.0 for x in line[1:]]
|
||||
data.append(features)
|
||||
|
||||
return np.array(data), np.array(labels)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user