generated from LufsX/Experiment-LogReg
This commit is contained in:
+62
-50
@@ -1,70 +1,82 @@
|
|||||||
# function.py
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from sklearn.preprocessing import StandardScaler
|
from sklearn.preprocessing import StandardScaler
|
||||||
from sklearn.metrics import accuracy_score
|
|
||||||
|
|
||||||
# 学号和姓名
|
# 填写学号和姓名
|
||||||
id = "202210423223"
|
id = "20221042323"
|
||||||
name = "李顺潮"
|
name = "李顺潮"
|
||||||
|
|
||||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.1):
|
def train_logreg(X, y, other_params="你自己设置一些其它参数", learning_rate=0.01, num_iterations=1000):
|
||||||
m, n = X.shape
|
"""
|
||||||
|
对率回归训练函数。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- X (numpy array): 特征数据。
|
||||||
|
- y (numpy array): 标签数据。
|
||||||
|
- other_params (str): 其它参数,这里暂未使用。
|
||||||
|
- learning_rate (float): 学习率。
|
||||||
|
- num_iterations (int): 迭代次数。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- numpy array: 训练得到的权重。
|
||||||
|
"""
|
||||||
|
# 添加偏置项
|
||||||
|
X_b = np.c_[np.ones((X.shape[0], 1)), X] # 添加一列1作为偏置项
|
||||||
|
m, n = X_b.shape
|
||||||
weights = np.zeros(n)
|
weights = np.zeros(n)
|
||||||
bias = 0
|
|
||||||
|
|
||||||
for _ in range(iterations):
|
# 梯度下降
|
||||||
linear_output = np.dot(X, weights) + bias
|
for iteration in range(num_iterations):
|
||||||
y_predicted = 1 / (1 + np.exp(-linear_output))
|
y_pred_prob = 1 / (1 + np.exp(-np.dot(X_b, weights)))
|
||||||
|
dw = (1 / m) * np.dot(X_b.T, (y_pred_prob - y))
|
||||||
# 计算梯度(包括正则化项)
|
|
||||||
dw = (1 / m) * np.dot(X.T, (y_predicted - y)) + (lambda_reg / m) * weights
|
|
||||||
db = (1 / m) * np.sum(y_predicted - y)
|
|
||||||
|
|
||||||
# 更新权重和偏置
|
|
||||||
weights -= learning_rate * dw
|
weights -= learning_rate * dw
|
||||||
bias -= learning_rate * db
|
|
||||||
|
|
||||||
return weights, bias
|
return weights
|
||||||
|
|
||||||
def predict_logreg(inX, weights, bias):
|
def predict_logreg(inX, weights):
|
||||||
linear_output = np.dot(inX, weights) + bias
|
"""
|
||||||
y_predicted = 1 if linear_output >= 0 else 0
|
对率回归预测函数。
|
||||||
return y_predicted
|
|
||||||
|
Args:
|
||||||
|
- inX (numpy array): 输入待分类的样本。
|
||||||
|
- weights (numpy array): 训练得到的权重。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- int: 预测的分类标签。
|
||||||
|
"""
|
||||||
|
# 添加偏置项
|
||||||
|
inX_b = np.c_[1, inX]
|
||||||
|
y_pred_prob = 1 / (1 + np.exp(-np.dot(inX_b, weights)))
|
||||||
|
return 1 if y_pred_prob > 0.5 else 0
|
||||||
|
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
data = []
|
"""
|
||||||
with open(filepath, 'r') as file:
|
从文件中加载数据。
|
||||||
for line in file:
|
|
||||||
parts = line.strip().split()
|
|
||||||
features = [float(part) if part != '?' else np.nan for part in parts[:-1]]
|
|
||||||
features = np.nan_to_num(features, nan=0.0)
|
|
||||||
label = int(parts[-1])
|
|
||||||
data.append(features + [label])
|
|
||||||
|
|
||||||
data_array = np.array(data)
|
Args:
|
||||||
X = data_array[:, :-1]
|
- filepath (str): 数据文件路径。
|
||||||
y = data_array[:, -1]
|
|
||||||
|
|
||||||
# 特征缩放
|
Returns:
|
||||||
scaler = StandardScaler()
|
- np.array: 特征数据。
|
||||||
X_scaled = scaler.fit_transform(X)
|
- np.array: 标签数据。
|
||||||
|
"""
|
||||||
return X_scaled, y
|
data = np.loadtxt(filepath, delimiter=",")
|
||||||
|
X = data[:, :-1] # 特征
|
||||||
|
y = data[:, -1] # 标签,转换为0和1
|
||||||
|
y = np.where(y == 2, 1, 0) # 将标签2转换为1,其他(1和3,这里只有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")
|
|
||||||
|
# 数据标准化
|
||||||
|
scaler = StandardScaler()
|
||||||
|
X_train_scaled = scaler.fit_transform(X_train)
|
||||||
|
|
||||||
# 训练模型
|
# 训练模型
|
||||||
weights, bias = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000, lambda_reg=0.1)
|
weights = train_logreg(X_train_scaled, y_train)
|
||||||
|
|
||||||
# 测试模型并评估性能
|
# 测试预测(这里示例性地选择一个样本进行预测)
|
||||||
y_pred = [predict_logreg(x, weights, bias) for x in X_test]
|
sample_index = 0 # 选择第一个样本进行预测
|
||||||
accuracy = accuracy_score(y_test, y_pred)
|
y_pred = predict_logreg(X_train_scaled[sample_index], weights)
|
||||||
print(f"模型准确率: {accuracy}")
|
print(f"预测结果: {y_pred}, 实际结果: {y_train[sample_index]}")
|
||||||
|
|
||||||
# 如果测试样本有效
|
|
||||||
if len(y_test) > 11:
|
|
||||||
sample_index = 11
|
|
||||||
print(f"预测结果: {y_pred[sample_index]}, 实际结果: {y_test[sample_index]}")
|
|
||||||
Reference in New Issue
Block a user