generated from LufsX/Experiment-LogReg
This commit is contained in:
+59
-37
@@ -1,57 +1,79 @@
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
|
# 填写学号和姓名
|
||||||
id = "202210423105"
|
id = "202210423105"
|
||||||
name = "魏明帅"
|
name = "魏明帅"
|
||||||
|
|
||||||
|
def sigmoid(z):
|
||||||
|
return 1 / (1 + np.exp(-z))
|
||||||
|
|
||||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||||
|
"""
|
||||||
|
对率回归训练函数。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- X (numpy array): 特征数据。
|
||||||
|
- y (numpy array): 标签数据。
|
||||||
|
- learning_rate (float): 学习率。
|
||||||
|
- iterations (int): 迭代次数。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- numpy array: 训练得到的权重。
|
||||||
|
"""
|
||||||
m, n = X.shape
|
m, n = X.shape
|
||||||
# 添加偏置项
|
weights = np.zeros(n)
|
||||||
X = np.c_[np.ones((m, 1)), X]
|
bias = 0
|
||||||
weights = np.zeros(n + 1)
|
|
||||||
|
|
||||||
for _ in range(iterations):
|
for i in range(iterations):
|
||||||
for i in range(m):
|
h = sigmoid(np.dot(X, weights) + bias)
|
||||||
x_i = X[i]
|
error = h - y
|
||||||
y_i = y[i]
|
weights -= learning_rate * (1 / m) * np.dot(X.T, error)
|
||||||
z = np.dot(x_i, weights)
|
bias -= learning_rate * (1 / m) * np.sum(error)
|
||||||
h = 1 / (1 + np.exp(-z))
|
|
||||||
error = y_i - h
|
|
||||||
weights += learning_rate * error * x_i
|
|
||||||
|
|
||||||
return weights
|
return weights, bias
|
||||||
|
|
||||||
def predict_logreg(inX, weights):
|
def predict_logreg(inX, weights, bias):
|
||||||
z = np.dot(inX, weights)
|
"""
|
||||||
h = 1 / (1 + np.exp(-z))
|
对率回归预测函数。
|
||||||
return 1 if h >= 0.5 else 0
|
|
||||||
|
Args:
|
||||||
|
- inX (numpy array): 输入待分类的样本。
|
||||||
|
- weights (numpy array): 训练得到的权重。
|
||||||
|
- bias (float): 训练得到的偏置项。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- int: 预测的分类标签。
|
||||||
|
"""
|
||||||
|
prob = sigmoid(np.dot(inX, weights) + bias)
|
||||||
|
return 1 if prob > 0.5 else 0
|
||||||
|
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
X = []
|
"""
|
||||||
y = []
|
从文件中加载数据,若不自行正确实现,则无法通过评测,不记录成绩。
|
||||||
with open(filepath, 'r') as f:
|
|
||||||
for line in f:
|
|
||||||
values = line.strip().split()
|
|
||||||
# 跳过包含 '?' 的行
|
|
||||||
if '?' in values:
|
|
||||||
continue
|
|
||||||
# 将标签和特征转换为浮点数
|
|
||||||
y.append(float(values[-1]))
|
|
||||||
X.append([float(x) for x in values[:-1]])
|
|
||||||
|
|
||||||
X_array = np.array(X)
|
Args:
|
||||||
y_array = np.array(y).reshape(-1, 1)
|
- filepath (str): 数据文件路径。
|
||||||
|
|
||||||
# 特征缩放,处理标准差为零的特征
|
Returns:
|
||||||
means = np.mean(X_array, axis=0)
|
- np.array: 特征数据。
|
||||||
stds = np.std(X_array, axis=0)
|
- np.array: 标签数据。
|
||||||
X_scaled = (X_array - means) / np.where(stds == 0, 1, stds)
|
"""
|
||||||
|
data = np.loadtxt(filepath, delimiter=',')
|
||||||
return X_scaled, y_array
|
X = data[:, :-1]
|
||||||
|
y = data[:, -1]
|
||||||
|
y = (y > 0).astype(int) # 将标签转换为1和0
|
||||||
|
return X, y
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
# 加载训练集
|
||||||
X_train, y_train = load_data("./data/horse-colic.data")
|
X_train, y_train = load_data("./data/horse-colic.data")
|
||||||
|
|
||||||
|
# 加载测试集
|
||||||
X_test, y_test = load_data("./data/horse-colic.test")
|
X_test, y_test = load_data("./data/horse-colic.test")
|
||||||
|
|
||||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
|
# 训练对率回归模型
|
||||||
y_pred = predict_logreg(X_test[11], weights)
|
weights, bias = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
|
||||||
|
|
||||||
|
# 测试单个数据
|
||||||
|
y_pred = predict_logreg(X_test[11], weights, bias)
|
||||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||||
Reference in New Issue
Block a user