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

This commit is contained in:
2024-11-03 17:01:22 +08:00
parent ab995e1719
commit 03ac83335c
+78 -56
View File
@@ -1,57 +1,79 @@
import numpy as np import numpy as np
id = "202210423105" # 填写学号和姓名
name = "魏明帅" id = "202210423105"
name = "魏明帅"
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
m, n = X.shape def sigmoid(z):
# 添加偏置项 return 1 / (1 + np.exp(-z))
X = np.c_[np.ones((m, 1)), X]
weights = np.zeros(n + 1) def train_logreg(X, y, learning_rate=0.01, iterations=1000):
"""
for _ in range(iterations): 对率回归训练函数。
for i in range(m):
x_i = X[i] Args:
y_i = y[i] - X (numpy array): 特征数据。
z = np.dot(x_i, weights) - y (numpy array): 标签数据。
h = 1 / (1 + np.exp(-z)) - learning_rate (float): 学习率。
error = y_i - h - iterations (int): 迭代次数。
weights += learning_rate * error * x_i
Returns:
return weights - numpy array: 训练得到的权重。
"""
def predict_logreg(inX, weights): m, n = X.shape
z = np.dot(inX, weights) weights = np.zeros(n)
h = 1 / (1 + np.exp(-z)) bias = 0
return 1 if h >= 0.5 else 0
for i in range(iterations):
def load_data(filepath): h = sigmoid(np.dot(X, weights) + bias)
X = [] error = h - y
y = [] weights -= learning_rate * (1 / m) * np.dot(X.T, error)
with open(filepath, 'r') as f: bias -= learning_rate * (1 / m) * np.sum(error)
for line in f:
values = line.strip().split() return weights, bias
# 跳过包含 '?' 的行
if '?' in values: def predict_logreg(inX, weights, bias):
continue """
# 将标签和特征转换为浮点数 对率回归预测函数。
y.append(float(values[-1]))
X.append([float(x) for x in values[:-1]]) Args:
- inX (numpy array): 输入待分类的样本。
X_array = np.array(X) - weights (numpy array): 训练得到的权重。
y_array = np.array(y).reshape(-1, 1) - bias (float): 训练得到的偏置项。
# 特征缩放,处理标准差为零的特征 Returns:
means = np.mean(X_array, axis=0) - int: 预测的分类标签。
stds = np.std(X_array, axis=0) """
X_scaled = (X_array - means) / np.where(stds == 0, 1, stds) prob = sigmoid(np.dot(inX, weights) + bias)
return 1 if prob > 0.5 else 0
return X_scaled, y_array
def load_data(filepath):
if __name__ == "__main__": """
X_train, y_train = load_data("./data/horse-colic.data") 从文件中加载数据,若不自行正确实现,则无法通过评测,不记录成绩。
X_test, y_test = load_data("./data/horse-colic.test")
Args:
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000) - filepath (str): 数据文件路径。
y_pred = predict_logreg(X_test[11], weights)
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
data = np.loadtxt(filepath, delimiter=',')
X = data[:, :-1]
y = data[:, -1]
y = (y > 0).astype(int) # 将标签转换为1和0
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, bias = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights, bias)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")