generated from LufsX/Experiment-LogReg
This commit is contained in:
+10
-34
@@ -26,14 +26,15 @@ name = "刘子豪"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def train_logreg(X, y, other_params="你自己设置一些其它参数"):
|
||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||
"""
|
||||
对率回归训练函数。
|
||||
|
||||
Args:
|
||||
- X (numpy array): 特征数据。
|
||||
- y (numpy array): 标签数据。
|
||||
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
|
||||
- learning_rate (float): 学习率。
|
||||
- iterations (int): 迭代次数。
|
||||
|
||||
Returns:
|
||||
- numpy array: 训练得到的权重。
|
||||
@@ -70,10 +71,10 @@ def predict_logreg(inX, weights):
|
||||
# 这里也写自己的代码实现
|
||||
def load_data(filepath):
|
||||
"""
|
||||
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||
从文件中加载数据。
|
||||
|
||||
Args:
|
||||
- directory (str): 数据文件路径。
|
||||
- filepath (str): 数据文件路径。
|
||||
|
||||
Returns:
|
||||
- np.array: 特征数据。
|
||||
@@ -81,39 +82,14 @@ def load_data(filepath):
|
||||
"""
|
||||
data = []
|
||||
labels = []
|
||||
|
||||
# 读取数据并处理缺失值
|
||||
with open(filepath, 'r') as file:
|
||||
for line in file:
|
||||
fields = line.strip().split()
|
||||
if len(fields) < 2:
|
||||
continue
|
||||
|
||||
features = fields[:-1]
|
||||
label = fields[-1]
|
||||
|
||||
# 记录特征和标签
|
||||
data.append(features)
|
||||
labels.append(label)
|
||||
|
||||
# 转换数据为 NumPy 数组,方便进一步处理
|
||||
data = np.array(data)
|
||||
labels = np.array(labels, dtype=int)
|
||||
|
||||
# 用于存储浮点型数据
|
||||
numeric_data = np.zeros(data.shape, dtype=float)
|
||||
|
||||
# 对每列进行缺失值填补
|
||||
for col in range(data.shape[1]):
|
||||
# 获取列数据,将 "?" 替换为 NaN,然后计算均值
|
||||
col_data = np.where(data[:, col] == '?', np.nan, data[:, col]).astype(float)
|
||||
mean_value = np.nanmean(col_data) # 计算均值忽略 NaN
|
||||
|
||||
# 将 NaN 替换为均值
|
||||
col_data = np.where(np.isnan(col_data), mean_value, col_data)
|
||||
numeric_data[:, col] = col_data
|
||||
|
||||
return numeric_data, labels
|
||||
if '?' in fields:
|
||||
continue # 跳过包含缺失值的行
|
||||
data.append([float(x) for x in fields[:-1]])
|
||||
labels.append(int(fields[-1])) # 假设标签在最后一列
|
||||
return np.array(data), np.array(labels)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user