generated from LufsX/Experiment-LogReg
70 lines
2.3 KiB
Python
70 lines
2.3 KiB
Python
# function.py
|
|
import numpy as np
|
|
from sklearn.preprocessing import StandardScaler
|
|
from sklearn.metrics import accuracy_score
|
|
|
|
# 学号和姓名
|
|
id = "202210423223"
|
|
name = "李顺潮"
|
|
|
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.1):
|
|
m, n = X.shape
|
|
weights = np.zeros(n)
|
|
bias = 0
|
|
|
|
for _ in range(iterations):
|
|
linear_output = np.dot(X, weights) + bias
|
|
y_predicted = 1 / (1 + np.exp(-linear_output))
|
|
|
|
# 计算梯度(包括正则化项)
|
|
dw = (1 / m) * np.dot(X.T, (y_predicted - y)) + (lambda_reg / m) * weights
|
|
db = (1 / m) * np.sum(y_predicted - y)
|
|
|
|
# 更新权重和偏置
|
|
weights -= learning_rate * dw
|
|
bias -= learning_rate * db
|
|
|
|
return weights, bias
|
|
|
|
def predict_logreg(inX, weights, bias):
|
|
linear_output = np.dot(inX, weights) + bias
|
|
y_predicted = 1 if linear_output >= 0 else 0
|
|
return y_predicted
|
|
|
|
def load_data(filepath):
|
|
data = []
|
|
with open(filepath, 'r') as file:
|
|
for line in file:
|
|
parts = line.strip().split()
|
|
features = [float(part) if part != '?' else np.nan for part in parts[:-1]]
|
|
features = np.nan_to_num(features, nan=0.0)
|
|
label = int(parts[-1])
|
|
data.append(features + [label])
|
|
|
|
data_array = np.array(data)
|
|
X = data_array[:, :-1]
|
|
y = data_array[:, -1]
|
|
|
|
# 特征缩放
|
|
scaler = StandardScaler()
|
|
X_scaled = scaler.fit_transform(X)
|
|
|
|
return X_scaled, y
|
|
|
|
if __name__ == "__main__":
|
|
# 加载训练集和测试集
|
|
X_train, y_train = load_data("./data/horse-colic.data")
|
|
X_test, y_test = load_data("./data/horse-colic.test")
|
|
|
|
# 训练模型
|
|
weights, bias = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000, lambda_reg=0.1)
|
|
|
|
# 测试模型并评估性能
|
|
y_pred = [predict_logreg(x, weights, bias) for x in X_test]
|
|
accuracy = accuracy_score(y_test, y_pred)
|
|
print(f"模型准确率: {accuracy}")
|
|
|
|
# 如果测试样本有效
|
|
if len(y_test) > 11:
|
|
sample_index = 11
|
|
print(f"预测结果: {y_pred[sample_index]}, 实际结果: {y_test[sample_index]}") |