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

This commit is contained in:
2024-11-13 02:43:25 +08:00
parent 5fcc553c83
commit b1f478359d
+48 -32
View File
@@ -28,45 +28,36 @@ name = "章程鸿"
# 这里写自己的代码实现
import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.01, iterations=1000, batch_size=32, init_weights=None):
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。
- batch_size (int): 小批量大小,默认为 32。
- init_weights (numpy array): 权重初始值,默认为 None(即全零初始化)。
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
Returns:
- numpy array: 训练得到的权重。
"""
m, n = X.shape
if init_weights is None:
weights = np.zeros(n)
else:
weights = init_weights
weights = np.zeros(n)
bias = 0
for _ in range(iterations):
indices = np.random.permutation(m)
X_shuffled = X[indices]
y_shuffled = y[indices]
for i in range(0, m, batch_size):
X_batch = X_shuffled[i:i+batch_size]
y_batch = y_shuffled[i:i+batch_size]
z = np.dot(X_batch, weights) + bias
h = sigmoid(z)
dw = (1/batch_size) * np.dot(X_batch.T, (h - y_batch))
db = (1/batch_size) * np.sum(h - y_batch)
weights -= learning_rate * dw
bias -= learning_rate * db
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):
"""
对率回归预测函数。
@@ -82,6 +73,7 @@ def predict_logreg(inX, weights):
h = sigmoid(z)
return 1 if h >= 0.5 else 0
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
@@ -95,31 +87,55 @@ def load_data(filepath):
"""
data = []
with open(filepath, 'r') as file:
for line in file:
# 清理无效数据
cleaned_line = line.strip().replace('?', '0')
values = [float(x) for x in cleaned_line.split()]
# 处理目标变量
if values[22] in [2, 3]:
values[22] = 0
new_values = values[:2] + values[3:23]
lines = file.readlines()
# 处理每一行数据
for line in lines:
values = line.strip().split()
new_values = []
for i in range(len(values)):
if values[i] == '?':
if i == 0 or i == 1:
new_values.append(0)
else:
new_values.append(0) # 先暂时用0填充,后续修改为均值填充
else:
new_values.append(float(values[i]))
data.append(new_values)
data = np.array(data)
X = data[:, :-1]
y = data[:, -1]
return X, y
def fill_with_mean(X):
"""
用均值填充特征矩阵中的缺失值
Args:
- X (numpy array): 特征数据
Returns:
- numpy array: 填充后的特征数据
"""
for i in range(X.shape[1]):
col = X[:, i]
mean_val = np.mean(col[col!= 0])
col[col == 0] = mean_val
return X
if __name__ == "__main__":
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
X_train = fill_with_mean(X_train)
# 加载测试集
X_test, y_test = load_data("./data/horse-colic.test")
X_test = fill_with_mean(X_test)
# 训练对率回归模型
init_weights = np.random.randn(X_train.shape[1]) # 随机初始化权重
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000, batch_size=32, init_weights=init_weights)
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}, 实际结果: {y_test[11]}")
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")