更新 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
+64 -46
View File
@@ -27,11 +27,13 @@ name = "章程鸿"
# 这里写自己的代码实现 # 这里写自己的代码实现
import numpy as np import numpy as np
from sklearn.preprocessing import StandardScaler
def sigmoid(z): 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: 训练得到的权重。 - numpy array: 训练得到的权重。
""" """
m, n = X.shape m, n = X.shape
weights = np.zeros(n) weights = np.random.randn(n) * 0.01
bias = 0 best_weights = weights.copy()
for _ in range(iterations): best_accuracy = 0
z = np.dot(X, weights) + bias wait = 0
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): 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: Returns:
- int: 预测的分类标签。 - int: 预测的分类标签。
""" """
z = np.dot(inX, weights) z = np.dot(X, weights)
h = sigmoid(z) h = sigmoid(z)
return 1 if h >= 0.5 else 0 return np.where(h > 0.5, 1, 0)
# 这里也写自己的代码实现 # 这里也写自己的代码实现
def load_data(filepath): def load_data(filepath):
""" """
@@ -83,38 +102,37 @@ def load_data(filepath):
- np.array: 标签数据。 - np.array: 标签数据。
""" """
data = [] data = []
with open(filepath, 'r') as file: data = []
for line in file: labels = []
# 清理无效数据 with open(filepath, 'r') as f:
cleaned_line = line.strip().replace('?', '0') # 将问号替换为0 for line in f:
data.append([float(x) for x in cleaned_line.split()]) # 转换为浮点数 line = line.strip().split()
data = np.array(data) if len(line) >= 1 and line[-1].isdigit():
X = data[:, :-1] line_data = [0 if x == '?' else float(x) for x in line[:-1]]
y = data[:, -1] data.append(line_data)
return X, y labels.append(int(line[-1]))
def standardize(X):
"""
标准化特征数据,使其均值为0,标准差为1。
Args:
- X (numpy array): 特征数据。
Returns:
- numpy array: 标准化后的特征数据。
"""
mean = np.mean(X, axis=0)
std = np.std(X, axis=0)
return (X - mean) / std
data = np.array(data)
labels = np.array(labels)
target_variable = np.where((labels == 2) | (labels == 3), 0, labels)
return data, target_variable
def accuracy(X, y, weights):
predictions = predict_logreg(X, weights)
return np.mean(predictions == y)
if __name__ == "__main__": if __name__ == "__main__":
# 加载训练集 X_train, y_train = load_data("./horse-colic.data")
X_train, y_train = load_data("./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)
# 测试单个数据 final_weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=1500, batch_size=64)
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
y_pred = predict_logreg(X_test[11], weights) final_accuracy = accuracy(X_test, y_test, final_weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") print(f"最终测试集的准确率: {final_accuracy:.4f}")