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

This commit is contained in:
2024-11-02 15:58:49 +08:00
parent b61cfb90a9
commit aed20500d2
+78 -55
View File
@@ -1,5 +1,5 @@
# function.py
import numpy as np
from sklearn.preprocessing import StandardScaler
"""
实验说明:
@@ -18,82 +18,105 @@ from sklearn.preprocessing import StandardScaler
"""
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423130"
name = "董秋"
# 这里写自己的代码实现
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
# 逻辑回归训练函数
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.01):
def sigmoid(z):
return 1.0 / (1 + np.exp(-z))
def compute_gradient(X_batch, y_batch, weights, lambda_reg):
z = np.dot(X_batch, weights)
h = sigmoid(z)
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch)
gradient += (lambda_reg / len(y_batch)) * weights # L2正则化
return gradient
def train_logreg(X, y, learning_rate=0.001, iterations=10000, batch_size=64, lambda_reg=0.1):
m, n = X.shape
weights = np.random.randn(n) * 0.01 # 随机初始化权重
weights = np.random.randn(n) * np.sqrt(2. / n) # He初始化
best_weights = weights.copy()
best_accuracy = 0
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 + (lambda_reg / m) * weights # L2 正则化
weights -= learning_rate * gradient # 更新权重
for _ in range(iterations):
indices = np.random.permutation(m)
X_shuffled = X[indices]
y_shuffled = y[indices]
return weights
for j in range(0, m, batch_size):
X_batch = X_shuffled[j:j + batch_size]
y_batch = y_shuffled[j:j + batch_size]
gradient = compute_gradient(X_batch, y_batch, weights, lambda_reg)
weights -= learning_rate * gradient
# 计算训练集准确率
train_accuracy = accuracy(X, y, weights)
if train_accuracy > best_accuracy:
best_accuracy = train_accuracy
best_weights = weights.copy()
# 逻辑回归预测函数
def predict_logreg(inX, weights):
z = np.dot(inX, weights)
prediction_prob = 1 / (1 + np.exp(-z)) # Sigmoid 激活函数
return 1 if prediction_prob >= 0.5 else 0
# 动态调整学习率
if _ % 100 == 0 and train_accuracy > 0.95: # 达到高准确率时减小学习率
learning_rate *= 0.9
return best_weights
def predict_logreg(X, weights):
z = np.dot(X, weights)
h = sigmoid(z)
return np.where(h >= 0.5, 1, 0)
# 从文件中加载数据
def load_data(filepath):
data = []
labels = []
data, labels = [], []
with open(filepath, 'r') as f:
for line in f:
values = line.strip().replace('?', '0').split()
try:
values = [float(v) for v in values]
# 跳过第3行(索引为2)和24-28行(索引为23-27)
if len(data) in [2, 23, 24, 25, 26, 27]:
continue
# 用0填充缺失值
values = [0 if v == 0 else v for v in values] # 用0填充
# 合并特征23的取值
if values[22] == 2 or values[22] == 3: # 特征23(索引22)
labels.append(0) # 死亡
elif values[22] == 1:
labels.append(1) # 生存
else:
continue # 无效标签,丢弃
data.append(values[:2] + values[3:23]) # 保留特征1, 2 和特征4-23
except ValueError:
continue
line = line.strip().split()
if len(line) >= 1 and line[-1].isdigit():
line_data = [0 if x == '?' else float(x) for x in line[:-1]]
data.append(line_data)
labels.append(int(line[-1]))
data = np.array(data)
labels = np.array(labels)
# 将标签二分类化,2和3为0,其余为1
target_variable = np.where((labels == 2) | (labels == 3), 0, 1)
# 数据归一化
scaler = StandardScaler()
data = scaler.fit_transform(data)
return data, labels
return data, target_variable
def accuracy(X, y, weights):
predictions = predict_logreg(X, weights)
return np.mean(predictions == y)
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
# 加载数据
X, y = load_data("./data/horse-colic.data")
# 拆分训练集和验证集
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)
# 数据归一化
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val)
# 训练模型
final_weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=10000, batch_size=64, lambda_reg=0.1)
# 验证模型
val_accuracy = accuracy(X_val, y_val, final_weights)
print(f"验证集的准确率: {val_accuracy:.4f}")
# 加载测试集
X_test, y_test = load_data("./data/horse-colic.test")
X_test = scaler.transform(X_test)
# 训练对率回归模型
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]}")
# 测试模型
final_test_accuracy = accuracy(X_test, y_test, final_weights)
print(f"最终测试集的准确率: {final_test_accuracy:.4f}")