generated from LufsX/Experiment-LogReg
This commit is contained in:
+1
-93
@@ -28,92 +28,7 @@ name = "Tanjunfeng"
|
||||
|
||||
# 这里写自己的代码实现
|
||||
|
||||
def sigmoid(z):
|
||||
return 1 / (1 + np.exp(-z))
|
||||
|
||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||
"""
|
||||
对率回归训练函数。
|
||||
|
||||
Args:
|
||||
- X (numpy array): 特征数据。
|
||||
- y (numpy array): 标签数据。
|
||||
- learning_rate (float): 学习率,默认为 0.01。
|
||||
- iterations (int): 迭代次数,默认为 1000。
|
||||
|
||||
Returns:
|
||||
- numpy array: 训练得到的权重。
|
||||
"""
|
||||
m, n = X.shape
|
||||
weights = np.zeros(n)
|
||||
bias = 0
|
||||
|
||||
for _ in range(iterations):
|
||||
z = np.dot(X, weights) + bias
|
||||
h = sigmoid(z)
|
||||
dw = (1 / m) * np.dot(X.T, (h - y))
|
||||
db = (1 / m) * np.sum(h - y)
|
||||
weights -= learning_rate * dw
|
||||
bias -= learning_rate * db
|
||||
|
||||
return weights
|
||||
|
||||
def predict_logreg(inX, weights):
|
||||
"""
|
||||
对率回归预测函数。
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- weights (numpy array): 训练得到的权重。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
z = np.dot(inX, weights)
|
||||
h = sigmoid(z)
|
||||
# 调整分类阈值
|
||||
return 1 if h > 0.6 else 0
|
||||
|
||||
def load_data(filepath):
|
||||
"""
|
||||
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||
|
||||
Args:
|
||||
- directory (str): 数据文件路径。
|
||||
|
||||
Returns:
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
data = []
|
||||
with open(filepath, 'r') as f:
|
||||
for line in f:
|
||||
row = []
|
||||
values = line.strip().split()
|
||||
for value in values:
|
||||
try:
|
||||
row.append(float(value))
|
||||
except ValueError:
|
||||
row.append(-1)
|
||||
data.append(row)
|
||||
np_data = np.array(data)
|
||||
X = np_data[:, :-1]
|
||||
y = np_data[:, -1]
|
||||
return X, 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 = train_logreg(X_train, y_train, learning_rate=0.01, iterations=5000)
|
||||
|
||||
# 测试单个数据
|
||||
correct_count = 0import numpy as np
|
||||
import numpy as np
|
||||
|
||||
|
||||
def sigmoid(z):
|
||||
@@ -195,10 +110,3 @@ if __name__ == "__main__":
|
||||
# 测试单个数据
|
||||
y_pred = predict_logreg(X_test[11], weights)
|
||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||
total_count = len(y_test)
|
||||
for i in range(total_count):
|
||||
y_pred = predict_logreg(X_test[i], weights)
|
||||
if y_pred == y_test[i]:
|
||||
correct_count += 1
|
||||
accuracy = correct_count / total_count
|
||||
print(f"准确率: {accuracy}")
|
||||
Reference in New Issue
Block a user