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

This commit is contained in:
2024-11-05 11:00:52 +08:00
parent 089f020766
commit 4772ffc881
+21 -39
View File
@@ -18,22 +18,17 @@ import pandas as pd
- numpy: 2.1.1 - numpy: 2.1.1
""" """
""" """
请在这里填写学号和姓名,不填写即成绩无效。 请在这里填写学号和姓名,不填写即成绩无效。
姓名请直接**填写中文** 姓名请直接**填写中文**
例如: name = "张三" 例如: name = "张三"
""" """
id = "202210423223" id = "20221042323"
name = "李顺潮" name = "李顺潮"
def sigmoid(z):
"""Sigmoid函数,用于对率回归的预测。"""
return 1 / (1 + np.exp(-z))
# 这里写自己的代码实现 # 这里写自己的代码实现
def train_logreg(X, y, other_params="你自己设置一些其它参数"): def train_logreg(X, y, other_params=None):
""" """
对率回归训练函数。 对率回归训练函数。
@@ -45,17 +40,17 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"):
Returns: Returns:
- numpy array: 训练得到的权重。 - numpy array: 训练得到的权重。
""" """
# 初始化权重 m, n = X.shape
weights = np.zeros(X.shape[1]) weights = np.zeros(n) # 初始化权重
learning_rate = 0.01 learning_rate = 0.01 # 学习率设置
iterations = 1000 num_iterations = 1000 # 迭代次数
for _ in range(iterations): # 对率回归的梯度下降
z = np.dot(X, weights) for _ in range(num_iterations):
predictions = sigmoid(z) linear_model = np.dot(X, weights)
error = y - predictions predictions = 1 / (1 + np.exp(-linear_model)) # Sigmoid函数
gradient = np.dot(X.T, error) errors = y - predictions
weights += learning_rate * gradient weights += learning_rate * np.dot(X.T, errors) / m # 更新权重
return weights return weights
@@ -71,10 +66,9 @@ def predict_logreg(inX, weights):
Returns: Returns:
- int: 预测的分类标签。 - int: 预测的分类标签。
""" """
# 计算预测值 linear_model = np.dot(inX, weights)
z = np.dot(inX, weights) predictions = 1 / (1 + np.exp(-linear_model)) # Sigmoid函数
probability = sigmoid(z) return np.round(predictions).astype(int) # 返回0或1
return 1 if probability >= 0.5 else 0
# 这里也写自己的代码实现 # 这里也写自己的代码实现
@@ -89,17 +83,13 @@ def load_data(filepath):
- np.array: 特征数据。 - np.array: 特征数据。
- np.array: 标签数据。 - np.array: 标签数据。
""" """
# 使用pandas加载数据 data = pd.read_csv(filepath, header=None)
df = pd.read_csv(filepath, header=None) # 假设最后一列是标签,其余为特征
X = data.iloc[:, :-1].values
# 替换缺失值和非数值数据,这里假设我们用0来填补缺失数据 y = data.iloc[:, -1].values
df.replace('?', np.nan, inplace=True)
df.fillna(0, inplace=True)
# 将数据拆分为特征和标签
X = df.iloc[:, :-1].values # 特征
y = df.iloc[:, -1].values # 标签
# 转换标签为数值,如果是字符串类型可以这样处理
y = np.where(y == '1', 1, 0) # 假设1表示死亡,0表示存活
return X, y return X, y
@@ -107,11 +97,3 @@ if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改 # 以下代码可用于测试,可自行随意修改
# 加载训练集 # 加载训练集
X_train, y_train = load_data("./data/horse-colic.data") X_train, y_train = load_data("./data/horse-colic.data")
# 训练模型
weights = train_logreg(X_train, y_train)
# 测试单个样本的预测
sample = X_train[0].reshape(1, -1) # 取出第一行作为样本
prediction = predict_logreg(sample, weights)
print(f"样本预测: {prediction}")