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

This commit is contained in:
Wyy
2024-11-02 20:55:12 +08:00
parent 7c4caae057
commit 937ae78001
+18 -15
View File
@@ -37,20 +37,20 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
return weights
def predict_logreg(inX, weights):
def predict_logreg(X, weights):
"""
对率回归预测函数。
Args:
- inX (numpy array): 输入待分类的样本。
- X (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
- numpy array: 预测的分类标签。
"""
linear_model = np.dot(inX, weights)
linear_model = np.dot(X, weights)
y_predicted = sigmoid(linear_model)
return 1 if y_predicted > 0.5 else 0
return (y_predicted > 0.5).astype(int)
def load_data(filepath):
@@ -64,13 +64,13 @@ def load_data(filepath):
- X (np.array): 特征数据。
- y (np.array): 标签数据。
"""
# 使用空格分隔符加载数据
data = np.loadtxt(filepath, delimiter=' ')
# 将问号 '?' 替换为 NaN
data = np.where(data == '?', np.nan, data)
# 将 NaN 替换为 0
data = np.where(np.isnan(data), 0, data)
# 分割特征和标签
# 使用np.genfromtxt加载数据,并且忽略文件中不能转换为float的行
data = np.genfromtxt(filepath, delimiter=',', dtype=float, filling_values=0)
if data.ndim == 1: # ensure the data is valid
data = np.array([data])
# 假设最后一列为标签
X = data[:, :-1]
y = data[:, -1]
return X, y
@@ -86,6 +86,9 @@ if __name__ == "__main__":
# 训练对率回归模型
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
# 测试多个数据
y_pred = predict_logreg(X_test, weights)
# 输出部分预测结果
for i in range(10): # 只输出前10个预测结果
print(f"预测结果: {y_pred[i]}, 实际结果: {y_test[i]}")