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

This commit is contained in:
2024-11-01 20:46:15 +08:00
parent 47abc5938e
commit ecac184a30
+61 -43
View File
@@ -27,11 +27,13 @@ name = "章程鸿"
# 这里写自己的代码实现
import numpy as np
from sklearn.preprocessing import StandardScaler
def sigmoid(z):
return 1 / (1 + np.exp(-z))
return 1.0 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
def train_logreg(X, y, learning_rate=0.05, iterations=1500, batch_size=64):
"""
对率回归训练函数。
@@ -44,18 +46,36 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
- numpy array: 训练得到的权重。
"""
m, n = X.shape
weights = np.zeros(n)
bias = 0
for _ in range(iterations):
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
weights = np.random.randn(n) * 0.01
best_weights = weights.copy()
best_accuracy = 0
wait = 0
def predict_logreg(inX, weights):
for i in range(iterations):
indices = np.random.permutation(m)
X_shuffled = X[indices]
y_shuffled = y[indices]
for j in range(0, m, batch_size):
X_batch = X_shuffled[j:j + batch_size]
y_batch = y_shuffled[j:j + batch_size]
z = np.dot(X_batch, weights)
h = sigmoid(z)
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch)
weights -= learning_rate * gradient
# 计算训练集准确率
train_accuracy = accuracy(X, y, weights)
if train_accuracy > best_accuracy:
best_accuracy = train_accuracy
best_weights = weights.copy()
wait = 0
else:
wait += 1
return best_weights
def predict_logreg(X, weights):
"""
对率回归预测函数。
@@ -66,10 +86,9 @@ def predict_logreg(inX, weights):
Returns:
- int: 预测的分类标签。
"""
z = np.dot(inX, weights)
z = np.dot(X, weights)
h = sigmoid(z)
return 1 if h >= 0.5 else 0
return np.where(h > 0.5, 1, 0)
# 这里也写自己的代码实现
def load_data(filepath):
"""
@@ -83,38 +102,37 @@ def load_data(filepath):
- np.array: 标签数据。
"""
data = []
with open(filepath, 'r') as file:
for line in file:
# 清理无效数据
cleaned_line = line.strip().replace('?', '0') # 将问号替换为0
data.append([float(x) for x in cleaned_line.split()]) # 转换为浮点数
data = []
labels = []
with open(filepath, 'r') as f:
for line in f:
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)
X = data[:, :-1]
y = data[:, -1]
return X, y
def standardize(X):
"""
标准化特征数据,使其均值为0,标准差为1。
labels = np.array(labels)
Args:
- X (numpy array): 特征数据。
target_variable = np.where((labels == 2) | (labels == 3), 0, labels)
Returns:
- numpy array: 标准化后的特征数据。
"""
mean = np.mean(X, axis=0)
std = np.std(X, axis=0)
return (X - mean) / std
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_train, y_train = load_data("./horse-colic.data")
X_test, y_test = load_data("./horse-colic.test")
# 加载测试集
X_test, y_test = load_data("./data/horse-colic.test")
# 标准化数据
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
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_weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=1500, batch_size=64)
final_accuracy = accuracy(X_test, y_test, final_weights)
print(f"最终测试集的准确率: {final_accuracy:.4f}")