更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 20s

This commit is contained in:
Wyy
2024-11-02 21:15:17 +08:00
parent e553731774
commit fd39fb78f3
+5 -12
View File
@@ -9,21 +9,14 @@ def sigmoid(z):
def train_logreg(X, y, numIter=1000, learning_rate=0.01, lambda_reg=0.01): def train_logreg(X, y, numIter=1000, learning_rate=0.01, lambda_reg=0.01):
m, n = X.shape m, n = X.shape
weights = np.zeros(n) weights = np.zeros(n)
val_X, val_y = X[:int(0.2*m)], y[:int(0.2*m)] # Split 20% of data for validation for j in range(numIter):
for i in range(numIter):
z = np.dot(X, weights) z = np.dot(X, weights)
h = sigmoid(z) h = sigmoid(z)
gradient = np.dot(X.T, (h - y)) / m error = y - h
gradient = np.dot(X.T, error) / m
reg_term = lambda_reg * weights reg_term = lambda_reg * weights
gradient += reg_term / m gradient += reg_term / m
weights -= learning_rate * gradient weights -= learning_rate * gradient
# Early stopping
if i % 100 == 0: # Check every 100 iterations
val_z = np.dot(val_X, weights)
val_h = sigmoid(val_z)
val_error = val_h - val_y
if np.mean(np.abs(val_error)) < 0.01: # If the validation error is small enough
break
return weights return weights
def predict_logreg(inX, weights): def predict_logreg(inX, weights):
@@ -54,8 +47,8 @@ def load_data(filepath):
data_number = len(y) data_number = len(y)
y_train = np.array([1 if y[j] == '2' or y[j] == '3' else 0 for j in range(data_number)]) y_train = np.array([1 if y[j] == '2' or y[j] == '3' else 0 for j in range(data_number)])
X = np.array(data_list) X = np.array(data_list)
X_train = np.insert(X, 0, 1, axis=1) # 添加偏置项 X = np.insert(X, 0, 1, axis=1) # 添加偏置项,应该在第一列添加
return X_train, y_train return X, y_train
def standardize(X): def standardize(X):
mean = X.mean(axis=0) mean = X.mean(axis=0)