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

This commit is contained in:
2024-10-30 10:56:46 +08:00
parent d5a373a8f9
commit 9a87a95171
+65 -49
View File
@@ -24,67 +24,83 @@ import numpy as np
id = "202210423222" id = "202210423222"
name = "邓龙树" name = "邓龙树"
# user_code.py
import numpy as np import numpy as np
def load_data(filepath): def sigmoid(z):
"""计算sigmoid函数"""
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
""" """
从文件中加载数据。 对率回归训练函数。
Args: Args:
- filepath (str): 数据文件路径。 - X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- learning_rate (float): 学习率,默认值为0.01。
- iterations (int): 迭代次数,默认值为1000。
Returns: Returns:
- np.array: 特征数据。 - weights (numpy array): 训练得到的权重。
- np.array: 标签数据。
""" """
# 读取每一行作为字符串 # 初始化权重
weights = np.zeros(X.shape[1])
# 训练模型
for _ in range(iterations):
z = np.dot(X, weights)
predictions = sigmoid(z)
# 计算梯度
gradient = np.dot(X.T, (predictions - y)) / y.size
# 更新权重
weights -= learning_rate * gradient
return weights
def predict_logreg(X, weights):
"""使用训练好的权重预测标签"""
z = np.dot(X, weights)
predictions = sigmoid(z)
return np.where(predictions >= 0.5, 1, 0)
def load_data(filepath):
"""从文件中加载数据,处理不规则列数问题"""
with open(filepath, 'r') as file: with open(filepath, 'r') as file:
lines = file.readlines() lines = file.readlines()
# 分割每一行并填充缺失的列 max_columns = 0
max_cols = 0 data = []
rows = []
for line in lines: for line in lines:
# 分割每一行 parts = line.strip().split()
cols = line.strip().split(' ') max_columns = max(max_columns, len(parts))
# 记录最大列数 data.append(parts)
max_cols = max(max_cols, len(cols))
rows.append(cols) # 填充缺失的列
for i in range(len(data)):
# 将所有行填充到相同的列数 if len(data[i]) < max_columns:
for row in rows: data[i].extend(['nan'] * (max_columns - len(data[i])))
while len(row) < max_cols:
row.append('nan') # 转换成numpy数组,处理缺失值
data_array = np.array(data, dtype=float)
# 转换为numpy数组 data_array[np.isnan(data_array)] = np.nanmean(data_array, axis=0)
data = np.array(rows, dtype=float)
return data_array[:, :-1], data_array[:, -1]
# 用np.nan替换字符串'nan'
data[data == 'nan'] = np.nan
X = data[:, :-1] # 假设最后一列是标签
y = data[:, -1]
return X, y
# 主逻辑
if __name__ == "__main__": if __name__ == "__main__":
# 加载训练集 # 加载数据
X_train, y_train = load_data("./data/horse-colic.data") X, y = load_data('path_to_data_file.txt')
# 加载测试集 # 训练模型
X_test, y_test = load_data("./data/horse-colic.test") weights = train_logreg(X, y)
# 处理缺失值,例如用列的均值替代 # 加载测试数据并预测
X_train = np.nan_to_num(X_train, nan=np.nanmean(X_train, axis=0)) X_test, y_test = load_data('path_to_test_data_file.txt')
X_test = np.nan_to_num(X_test, nan=np.nanmean(X_train, axis=0)) # 用训练集的均值替代测试集 predictions = predict_logreg(X_test, weights)
# 确保标签为浮点型 # 打印预测结果和实际结果
y_train = y_train.astype(float) for i in range(min(10, len(y_test))): # 打印前10个结果或全部结果,取决于测试数据量
y_test = y_test.astype(float) print(f"预测结果: {predictions[i]}, 实际结果: {y_test[i]}")
# 训练对率回归模型
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]}")