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

This commit is contained in:
2024-11-05 14:53:52 +08:00
parent b80dd1b084
commit 423b53b214
+18 -44
View File
@@ -26,13 +26,10 @@ import numpy as np
id = "202210423629"
name = "Tanjunfeng"
# 这里写自己的代码实现
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# 这里写自己的代码实现
import numpy as np
# 这里写自己的代码实现
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
"""
对率回归训练函数。
@@ -40,25 +37,26 @@ 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。
- learning_rate (float): 学习率,默认为 0.01。
- iterations (int): 迭代次数,默认为 1000。
Returns:
- numpy array: 训练得到的权重。
"""
m, n = X.shape
X = np.hstack((np.ones((m, 1)), X)) # 添加偏置项
weights = np.zeros(n + 1)
weights = np.zeros(n)
bias = 0
for _ in range(iterations):
z = np.dot(X, weights)
h = 1 / (1 + np.exp(-z))
gradient = np.dot(X.T, (h - y)) / m # 计算梯度
weights -= learning_rate * gradient # 更新权重
z = np.dot(X, weights) + bias
h = sigmoid(z)
dw = (1 / m) * np.dot(X.T, (h - y))
db = (1 / m) * np.sum(h - y)
weights -= learning_rate * dw
bias -= learning_rate * db
return weights
def predict_logreg(inX, weights):
"""
对率回归预测函数。
@@ -70,45 +68,26 @@ def predict_logreg(inX, weights):
Returns:
- int: 预测的分类标签。
"""
inX = np.insert(inX, 0, 1) # 添加偏置项
z = np.dot(inX, weights)
h = 1 / (1 + np.exp(-z))
return int(h >= 0.5)
h = sigmoid(z)
return 1 if h > 0.5 else 0
# 这里也写自己的代码实现
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
Args:
- filepath (str): 数据文件路径。
- directory (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
# 使用 numpy.genfromtxt 读取数据
data = np.genfromtxt(
filepath,
delimiter=None, # 自动检测分隔符(包括空白符、制表符等)
dtype=float,
missing_values='?',
filling_values=np.nan,
autostrip=True
)
# 删除包含缺失值的行
data = data[~np.isnan(data).any(axis=1)]
# 将数据分为特征和标签
data = np.loadtxt(filepath, delimiter=',')
X = data[:, :-1]
y = data[:, -1]
# 将标签转换为二分1: 存活,0: 死亡或安乐死
y = np.where(y == 1, 0, 1)
return X, y
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
@@ -118,14 +97,9 @@ if __name__ == "__main__":
X_test, y_test = load_data("./data/horse-colic.test")
# 训练对率回归模型
weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=5000)
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {int(y_test[11])}")
# 可选:计算测试集上的准确率
correct = sum(predict_logreg(X_test[i], weights) == y_test[i] for i in range(len(X_test)))
accuracy = correct / len(X_test)
print(f"模型在测试集上的准确率: {accuracy * 100:.2f}%")
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")