generated from LufsX/Experiment-LogReg
This commit is contained in:
+70
-66
@@ -30,20 +30,19 @@ name = "万子玉"
|
|||||||
def sigmoid(z):
|
def sigmoid(z):
|
||||||
return 1 / (1 + np.exp(-z))
|
return 1 / (1 + np.exp(-z))
|
||||||
|
|
||||||
def train_logreg(X, y, learning_rate=0.01, iterations=2000, lambda_reg=0.01, batch_size=32):
|
def train_logreg(X, y, learning_rate=0.1, iterations=2000, lambda_reg=0.01, batch_size=32):
|
||||||
X = np.insert(X, 0, 1, axis=1) # 添加偏置项
|
|
||||||
m, n = X.shape
|
m, n = X.shape
|
||||||
weights = np.random.randn(n) * 0.01 # 随机初始化权重
|
weights = np.random.randn(n) * 0.01 # 随机初始化权重,取较小值
|
||||||
|
|
||||||
for i in range(iterations):
|
for i in range(iterations):
|
||||||
indices = np.arange(m)
|
# 每次迭代打乱数据
|
||||||
np.random.shuffle(indices)
|
indices = np.random.permutation(m)
|
||||||
X_shuffled = X[indices]
|
X = X[indices]
|
||||||
y_shuffled = y[indices]
|
y = y[indices]
|
||||||
|
|
||||||
for j in range(0, m, batch_size):
|
for j in range(0, m, batch_size): # 按照 batch size 迭代
|
||||||
X_batch = X_shuffled[j:j + batch_size]
|
X_batch = X[j:j + batch_size]
|
||||||
y_batch = y_shuffled[j:j + batch_size]
|
y_batch = y[j:j + batch_size]
|
||||||
|
|
||||||
z = np.dot(X_batch, weights)
|
z = np.dot(X_batch, weights)
|
||||||
predictions = sigmoid(z)
|
predictions = sigmoid(z)
|
||||||
@@ -55,6 +54,10 @@ def train_logreg(X, y, learning_rate=0.01, iterations=2000, lambda_reg=0.01, bat
|
|||||||
# 更新权重
|
# 更新权重
|
||||||
weights -= learning_rate * gradient
|
weights -= learning_rate * gradient
|
||||||
|
|
||||||
|
# 动态调整学习率,逐渐减小
|
||||||
|
if i % 100 == 0: # 每100次迭代输出一次学习率
|
||||||
|
print(f"Iteration {i}, Learning Rate: {learning_rate}")
|
||||||
|
|
||||||
return weights
|
return weights
|
||||||
|
|
||||||
"""
|
"""
|
||||||
@@ -70,12 +73,10 @@ def train_logreg(X, y, learning_rate=0.01, iterations=2000, lambda_reg=0.01, bat
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def predict_logreg(inX, weights):
|
def preprocess_data(X):
|
||||||
inX = np.insert(inX, 0, 1) # 添加偏置项
|
"""特征标准化。"""
|
||||||
z = np.dot(inX, weights)
|
scaler = StandardScaler()
|
||||||
prediction_prob = sigmoid(z)
|
return scaler.fit_transform(X)
|
||||||
return 1 if prediction_prob >= 0.5 else 0
|
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
对率回归预测函数。
|
对率回归预测函数。
|
||||||
@@ -87,61 +88,37 @@ def predict_logreg(inX, weights):
|
|||||||
Returns:
|
Returns:
|
||||||
- int: 预测的分类标签。
|
- int: 预测的分类标签。
|
||||||
"""
|
"""
|
||||||
def evaluate_model(X_val, y_val, weights):
|
|
||||||
predictions = np.array([predict_logreg(x, weights) for x in X_val])
|
|
||||||
accuracy = np.mean(predictions == y_val)
|
|
||||||
return accuracy
|
|
||||||
|
|
||||||
def split_train_val(X, y, val_size=0.2):
|
|
||||||
shuffled_indices = list(range(X.shape[0]))
|
|
||||||
random.shuffle(shuffled_indices)
|
|
||||||
X_shuffled = X[shuffled_indices]
|
|
||||||
y_shuffled = y[shuffled_indices]
|
|
||||||
|
|
||||||
val_count = int(X.shape[0] * val_size)
|
|
||||||
|
|
||||||
X_val = X_shuffled[:val_count]
|
|
||||||
y_val = y_shuffled[:val_count]
|
|
||||||
X_train = X_shuffled[val_count:]
|
|
||||||
y_train = y_shuffled[val_count:]
|
|
||||||
|
|
||||||
return X_train, X_val, y_train, y_val
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# 这里也写自己的代码实现
|
# 这里也写自己的代码实现
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
with open(filepath, 'r') as file:
|
"""加载数据并处理缺失值。"""
|
||||||
lines = file.readlines()
|
data = []
|
||||||
|
labels = []
|
||||||
|
|
||||||
data = [line.strip().split() for line in lines if line.strip().split()[-1].isdigit()]
|
with open(filepath, 'r') as f:
|
||||||
data = [list(map(lambda x: float(x) if x != '?' else np.nan, row)) for row in data]
|
for line in f:
|
||||||
|
values = line.strip().replace('?', '0').split()
|
||||||
|
try:
|
||||||
|
values = [float(v) for v in values]
|
||||||
|
|
||||||
# 移除类别标签缺失的样本
|
# 合并特征23的取值
|
||||||
data = [row for row in data if not np.isnan(row[-1])]
|
if values[22] == 2 or values[22] == 3: # 特征23(索引22)
|
||||||
|
labels.append(0) # 死亡
|
||||||
|
elif values[22] == 1:
|
||||||
|
labels.append(1) # 生存
|
||||||
|
else:
|
||||||
|
continue # 无效标签,丢弃
|
||||||
|
|
||||||
# 使用“0”填充缺失值
|
# 用0填充缺失值
|
||||||
for row in data:
|
values = [0 if v == 0 else v for v in values] # 直接用0填充
|
||||||
for i in range(len(row)):
|
data.append(values[:2] + values[3:23]) # 保留特征1, 2 和特征4-23
|
||||||
if np.isnan(row[i]):
|
except ValueError:
|
||||||
row[i] = 0.0
|
continue
|
||||||
|
|
||||||
# 合并特征23的值2和3为0
|
data = np.array(data)
|
||||||
for row in data:
|
labels = np.array(labels)
|
||||||
if row[22] == 2 or row[22] == 3: # 假设特征23是第23个元素
|
|
||||||
row[22] = 0
|
|
||||||
|
|
||||||
# 移除不需要的特征
|
return data, labels
|
||||||
data = [row[:2] + row[3:23] + row[28:] for row in data]
|
|
||||||
|
|
||||||
# 分离特征和标签
|
|
||||||
X = [row[:-1] for row in data]
|
|
||||||
y = [row[-1] for row in data]
|
|
||||||
|
|
||||||
scaler = StandardScaler()
|
|
||||||
X = scaler.fit_transform(X)
|
|
||||||
|
|
||||||
return np.array(X), np.array(y)
|
|
||||||
"""
|
"""
|
||||||
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||||
|
|
||||||
@@ -154,10 +131,37 @@ def load_data(filepath):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
X_train, y_train = load_data("./data/horse-colic.data")
|
# 加载数据集
|
||||||
X_test, y_test = load_data("./data/horse-colic.test")
|
X, y = load_data("./data/horse-colic.data")
|
||||||
|
|
||||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=2000)
|
# 归一化数据
|
||||||
|
X = preprocess_data(X)
|
||||||
|
|
||||||
|
# 使用 train_test_split 打乱并随机抽取数据
|
||||||
|
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
||||||
|
|
||||||
|
# K折交叉验证
|
||||||
|
k = 5
|
||||||
|
kf = KFold(n_splits=k, shuffle=True, random_state=42)
|
||||||
|
accuracies = []
|
||||||
|
|
||||||
|
for train_index, val_index in kf.split(X_train):
|
||||||
|
X_train_kf, X_val_kf = X_train[train_index], X_train[val_index]
|
||||||
|
y_train_kf, y_val_kf = y_train[train_index], y_train[val_index]
|
||||||
|
|
||||||
|
# 训练逻辑回归模型,设置 batch size
|
||||||
|
batch_size = 32
|
||||||
|
weights = train_logreg(X_train_kf, y_train_kf, learning_rate=0.1, iterations=2000, lambda_reg=0.01, batch_size=batch_size)
|
||||||
|
|
||||||
|
# 验证模型
|
||||||
|
val_predictions = [predict_logreg(X_val_kf[i], weights) for i in range(len(X_val_kf))]
|
||||||
|
accuracy = np.mean(val_predictions == y_val_kf)
|
||||||
|
accuracies.append(accuracy)
|
||||||
|
|
||||||
|
# 输出交叉验证的准确率和平均准确率
|
||||||
|
print(f"K折交叉验证得分: {accuracies}")
|
||||||
|
print(f"平均准确率: {np.mean(accuracies)}")
|
||||||
|
|
||||||
|
# 测试单个数据
|
||||||
y_pred = predict_logreg(X_test[11], weights)
|
y_pred = predict_logreg(X_test[11], weights)
|
||||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||||
Reference in New Issue
Block a user