generated from LufsX/Experiment-LogReg
This commit is contained in:
+56
-31
@@ -24,62 +24,87 @@ import numpy as np
|
|||||||
id = "202210423222"
|
id = "202210423222"
|
||||||
name = "邓龙树"
|
name = "邓龙树"
|
||||||
|
|
||||||
# user_code.py
|
# user_cod
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from sklearn.preprocessing import StandardScaler
|
from sklearn.preprocessing import StandardScaler
|
||||||
|
|
||||||
def sigmoid(intX):
|
|
||||||
return 1.0 / (1 + np.exp(-intX))
|
|
||||||
|
|
||||||
def train_logreg(X, y, numIter=150):
|
def sigmoid(z):
|
||||||
|
return 1.0 / (1 + np.exp(-z))
|
||||||
|
|
||||||
|
|
||||||
|
def train_logreg(X, y, learning_rate=0.05, iterations=1500, batch_size=64):
|
||||||
m, n = X.shape
|
m, n = X.shape
|
||||||
weights = np.zeros(n) # 初始化权重为0而不是1
|
weights = np.random.randn(n) * 0.01
|
||||||
for j in range(numIter):
|
best_weights = weights.copy()
|
||||||
dataIndex = list(range(m))
|
best_accuracy = 0
|
||||||
for i in range(m):
|
wait = 0
|
||||||
alpha = 4 / (1.0 + j + i) + 0.01
|
|
||||||
randIndex = int(np.random.uniform(0, len(dataIndex)))
|
for i in range(iterations):
|
||||||
h = sigmoid(np.dot(X[randIndex], weights))
|
indices = np.random.permutation(m)
|
||||||
error = y[randIndex] - h
|
X_shuffled = X[indices]
|
||||||
weights = weights + alpha * error * X[randIndex]
|
y_shuffled = y[indices]
|
||||||
del(dataIndex[randIndex])
|
|
||||||
return weights
|
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):
|
def predict_logreg(X, weights):
|
||||||
predictions = []
|
z = np.dot(X, weights)
|
||||||
for x in X:
|
h = sigmoid(z)
|
||||||
prob = sigmoid(np.dot(x, weights))
|
return np.where(h > 0.5, 1, 0)
|
||||||
predictions.append(1 if prob > 0.5 else 0)
|
|
||||||
return predictions
|
|
||||||
|
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
data = []
|
data = []
|
||||||
labels = []
|
labels = []
|
||||||
with open(filepath, 'r') as f:
|
with open(filepath, 'r') as f:
|
||||||
lines = f.readlines()
|
for line in f:
|
||||||
for line in lines:
|
|
||||||
line = line.strip().split()
|
line = line.strip().split()
|
||||||
if len(line) >= 1 and line[-1].isdigit():
|
if len(line) >= 1 and line[-1].isdigit():
|
||||||
line_data = [1] + [0 if x == '?' else float(x) for x in line[:-1]]
|
line_data = [0 if x == '?' else float(x) for x in line[:-1]]
|
||||||
data.append(line_data)
|
data.append(line_data)
|
||||||
labels.append(int(line[-1]))
|
labels.append(int(line[-1]))
|
||||||
|
|
||||||
data = np.array(data)
|
data = np.array(data)
|
||||||
labels = np.array(labels)
|
labels = np.array(labels)
|
||||||
target_variable = labels
|
|
||||||
target_variable[np.logical_or(target_variable == 2, target_variable == 3)] = 0
|
target_variable = np.where((labels == 2) | (labels == 3), 0, labels)
|
||||||
data = np.delete(data, [2] + list(range(23, 28)), axis=1)
|
|
||||||
scaler = StandardScaler()
|
|
||||||
data = scaler.fit_transform(data)
|
|
||||||
return data, target_variable
|
return data, target_variable
|
||||||
|
|
||||||
|
|
||||||
def accuracy(X, y, weights):
|
def accuracy(X, y, weights):
|
||||||
predictions = predict_logreg(X, weights)
|
predictions = predict_logreg(X, weights)
|
||||||
return np.mean(predictions == y)
|
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("./horse-colic.data")
|
||||||
X_test, y_test = load_data("./horse-colic.test")
|
X_test, y_test = load_data("./horse-colic.test")
|
||||||
final_weights = train_logreg(X_train, y_train)
|
|
||||||
|
# 标准化数据
|
||||||
|
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)
|
||||||
|
|
||||||
final_accuracy = accuracy(X_test, y_test, final_weights)
|
final_accuracy = accuracy(X_test, y_test, final_weights)
|
||||||
print(f"最终测试集的准确率: {final_accuracy:.4f}")
|
print(f"最终测试集的准确率: {final_accuracy:.4f}")
|
||||||
|
|||||||
Reference in New Issue
Block a user