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

This commit is contained in:
2024-10-30 10:52:26 +08:00
parent 22aaa82ac1
commit d5a373a8f9
+24 -46
View File
@@ -26,47 +26,6 @@ name = "邓龙树"
import numpy as np import numpy as np
def sigmoid(z):
"""计算sigmoid函数"""
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) # 初始化权重
for _ in range(iterations):
z = np.dot(X, weights)
predictions = sigmoid(z)
error = predictions - y
gradient = np.dot(X.T, error) / m
weights -= learning_rate * gradient # 更新权重
return weights
def predict_logreg(inX, weights):
"""
对率回归预测函数。
Args:
- inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
"""
probability = sigmoid(np.dot(inX, weights))
return 1 if probability >= 0.5 else 0 # 二分类阈值为0.5
def load_data(filepath): def load_data(filepath):
""" """
从文件中加载数据。 从文件中加载数据。
@@ -78,17 +37,36 @@ def load_data(filepath):
- np.array: 特征数据。 - np.array: 特征数据。
- np.array: 标签数据。 - np.array: 标签数据。
""" """
# 使用dtype=str先将所有数据加载为字符串 # 读取每一行作为字符串
data = np.loadtxt(filepath, delimiter=' ', dtype=str) with open(filepath, 'r') as file:
lines = file.readlines()
# 替换'?'为np.nan,并转换为浮点数 # 分割每一行并填充缺失的列
data[data == '?'] = np.nan max_cols = 0
data = data.astype(float) rows = []
for line in lines:
# 分割每一行
cols = line.strip().split(' ')
# 记录最大列数
max_cols = max(max_cols, len(cols))
rows.append(cols)
# 将所有行填充到相同的列数
for row in rows:
while len(row) < max_cols:
row.append('nan')
# 转换为numpy数组
data = np.array(rows, dtype=float)
# 用np.nan替换字符串'nan'
data[data == 'nan'] = np.nan
X = data[:, :-1] # 假设最后一列是标签 X = data[:, :-1] # 假设最后一列是标签
y = data[:, -1] y = data[:, -1]
return X, y 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")