Files
Experiment-LogReg/function.py
T
2024-11-02 21:01:58 +08:00

69 lines
1.6 KiB
Python

import numpy as np
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423224"
name = "吴杨洋"
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
m, n = X.shape
weights = np.zeros(n)
for i in range(iterations):
linear_model = np.dot(X, weights)
y_predicted = sigmoid(linear_model)
gradient = np.dot(X.T, (y_predicted - y)) / m
weights -= learning_rate * gradient
return weights
def predict_logreg(inX, weights):
linear_model = np.dot(inX, weights)
y_predicted = sigmoid(linear_model)
return 1 if y_predicted > 0.5 else 0
def load_data(filepath):
data = np.genfromtxt(filepath, delimiter=' ', dtype=float)
X = data[:, :-1]
y = data[:, -1]
return X, y
def standardize(X):
mean = X.mean(axis=0)
std = X.std(axis=0)
return (X - mean) / std, mean, std
def main():
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
# 加载测试集
X_test, y_test = load_data("./data/horse-colic.test")
# 标准化特征数据
X_train, mean, std = standardize(X_train)
X_test = (X_test - mean) / std
# 训练对率回归模型
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
# 测试单个数据
correct_predictions = 0
for i in range(X_test.shape[0]):
y_pred = predict_logreg(X_test[i], weights)
if y_pred == y_test[i]:
correct_predictions += 1
accuracy = correct_predictions / X_test.shape[0]
print(f"Accuracy: {accuracy:.2f}")
if __name__ == "__main__":
main()