generated from LufsX/Experiment-LogReg
This commit is contained in:
+65
-49
@@ -24,67 +24,83 @@ import numpy as np
|
||||
id = "202210423222"
|
||||
name = "邓龙树"
|
||||
|
||||
# user_code.py
|
||||
|
||||
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:
|
||||
- filepath (str): 数据文件路径。
|
||||
|
||||
- X (numpy array): 特征数据。
|
||||
- y (numpy array): 标签数据。
|
||||
- learning_rate (float): 学习率,默认值为0.01。
|
||||
- iterations (int): 迭代次数,默认值为1000。
|
||||
|
||||
Returns:
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
- weights (numpy 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:
|
||||
lines = file.readlines()
|
||||
|
||||
# 分割每一行并填充缺失的列
|
||||
max_cols = 0
|
||||
rows = []
|
||||
|
||||
max_columns = 0
|
||||
data = []
|
||||
|
||||
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] # 假设最后一列是标签
|
||||
y = data[:, -1]
|
||||
return X, y
|
||||
|
||||
parts = line.strip().split()
|
||||
max_columns = max(max_columns, len(parts))
|
||||
data.append(parts)
|
||||
|
||||
# 填充缺失的列
|
||||
for i in range(len(data)):
|
||||
if len(data[i]) < max_columns:
|
||||
data[i].extend(['nan'] * (max_columns - len(data[i])))
|
||||
|
||||
# 转换成numpy数组,处理缺失值
|
||||
data_array = np.array(data, dtype=float)
|
||||
data_array[np.isnan(data_array)] = np.nanmean(data_array, axis=0)
|
||||
|
||||
return data_array[:, :-1], data_array[:, -1]
|
||||
|
||||
# 主逻辑
|
||||
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 = np.nan_to_num(X_test, nan=np.nanmean(X_train, axis=0)) # 用训练集的均值替代测试集
|
||||
# 加载测试数据并预测
|
||||
X_test, y_test = load_data('path_to_test_data_file.txt')
|
||||
predictions = predict_logreg(X_test, weights)
|
||||
|
||||
# 确保标签为浮点型
|
||||
y_train = y_train.astype(float)
|
||||
y_test = y_test.astype(float)
|
||||
|
||||
# 训练对率回归模型
|
||||
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]}")
|
||||
# 打印预测结果和实际结果
|
||||
for i in range(min(10, len(y_test))): # 打印前10个结果或全部结果,取决于测试数据量
|
||||
print(f"预测结果: {predictions[i]}, 实际结果: {y_test[i]}")
|
||||
|
||||
Reference in New Issue
Block a user