更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 13s

This commit is contained in:
hao
2024-11-02 13:19:45 +08:00
parent 8dc9ed34ab
commit cf6cb2c1a1
+12 -67
View File
@@ -26,104 +26,49 @@ name = "黎世浩"
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
Args:
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
# 读取数据,将非数值转换为NaN
data = np.genfromtxt(filepath, delimiter=' ', dtype=float, missing_values='?')
# 分离特征和标签
X = data[:, :-1]
y = data[:, -1]
# 将缺失值填充为每列的平均值
for i in range(X.shape[1]):
X[:, i] = np.where(np.isnan(X[:, i]), np.nanmean(X[:, i]), X[:, i])
X[:, i] = np.where(np.isnan(X[:, i]), np.mean(X[:, i]), X[:, i])
return X, y.astype(int)
def scale_features(X):
"""
对特征进行标准化处理。
Args:
- X (numpy array): 特征数据。
Returns:
- numpy array: 标准化后的特征数据。
"""
mean = np.mean(X, axis=0)
std = np.std(X, axis=0)
# 避免除以零的错误
std[std == 0] = 1
scaled_X = (X - mean) / std
return scaled_X
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
"""
对率回归训练函数。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- learning_rate (float): 学习率,默认为0.01。
- iterations (int): 迭代次数,默认为1000。
Returns:
- numpy array: 训练得到的权重。
"""
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.01):
m, n = X.shape
weights = np.zeros(n)
for _ in range(iterations):
for i in range(m):
x_i = X[i]
y_i = y[i]
# 计算预测值
prediction = 1 / (1 + np.exp(-np.dot(x_i, weights)))
# 计算梯度
gradient = x_i * (prediction - y_i)
# 更新权重
weights -= learning_rate * gradient
weights -= learning_rate * (gradient + lambda_reg * weights)
return weights
def predict_logreg(inX, weights):
"""
对率回归预测函数。
Args:
- inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
"""
prediction = 1 / (1 + np.exp(-np.dot(inX, weights)))
return 1 if prediction > 0.5 else 0
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
# 加载测试集
X_test, y_test = load_data("./data/horse-colic.test")
# 特征缩放
X_train_scaled = scale_features(X_train)
X_test_scaled = scale_features(X_test)
# 训练对率回归模型
weights = train_logreg(X_train_scaled, y_train, learning_rate=0.01, iterations=1000)
# 测试单个数据
y_pred = predict_logreg(X_test_scaled[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
# 测试模型
y_pred = [predict_logreg(x, weights) for x in X_test_scaled]
accuracy = np.mean(y_pred == y_test)
print(f"Accuracy: {accuracy}")