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

This commit is contained in:
2024-11-03 20:42:22 +08:00
parent 94bd2f553f
commit e8e2071256
+26 -51
View File
@@ -25,71 +25,46 @@ id = "202210423204"
name = "陈垣豪"
# 这里写自己的代码实现
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
"""
对率回归训练函数。
"""训练逻辑回归模型."""
n_samples, n_features = X.shape
weights = np.zeros(n_features + 1) # 增加一位用于偏置
X = np.c_[X, np.ones((n_samples, 1))] # 增加偏置项
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- learning_rate (float): 学习率。
- iterations (int): 迭代次数。
for _ in range(iterations):
linear_model = np.dot(X, weights)
# 直接使用线性模型的输出进行梯度更新
dw = (1 / n_samples) * np.dot(X.T, (linear_model - y))
weights -= learning_rate * dw
Returns:
- numpy array: 训练得到的权重。
"""
m, n = X.shape
weights = np.zeros(n) # 初始化权重
for i in range(iterations):
z = np.dot(X, weights)
predictions = 1 / (1 + np.exp(-z)) # 计算sigmoid值
# 更新权重
gradient = np.dot(X.T, (predictions - y)) / m
weights -= learning_rate * gradient
return weights
def predict_logreg(inX, weights):
"""
对率回归预测函数。
Args:
- inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
"""
prob = 1 / (1 + np.exp(-np.dot(inX, weights))) # 计算sigmoid值
return 1 if prob >= 0.5 else 0 # 阈值为0.5
"""使用线性模型预测结果."""
inX = np.append(inX, 1) # 增加偏置项
linear_model = np.dot(inX, weights)
return 1 if linear_model >= 0 else 0 # 直接返回0或1
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
Args:
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
data = np.loadtxt(filepath, delimiter=',') # 假设数据是以逗号分隔的
X = data[:, :-1] # 特征数据
y = data[:, -1] # 标签数据
"""加载数据并处理缺失值."""
data = np.genfromtxt(filepath, delimiter=' ', dtype=float, missing_values='?', filling_values=np.nan)
nan_columns = np.isnan(data)
mean_values = np.nanmean(data, axis=0)
data[nan_columns] = np.take(mean_values, np.where(nan_columns)[1])
X = data[:, :-1]
y = data[:, -1]
return X, y
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
# 加载测试集
X_test, y_test = load_data("./data/horse-colic.test")
# 训练对率回归模型
# 训练逻辑回归模型
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
# 测试单个数据
X_test, y_test = load_data("./data/horse-colic.test")
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")