generated from LufsX/Experiment-LogReg
This commit is contained in:
+9
-11
@@ -6,6 +6,8 @@ from sklearn.impute import SimpleImputer
|
||||
id = "202210423107"
|
||||
name = "刘燚燊"
|
||||
|
||||
import pandas as pd
|
||||
|
||||
def load_data(filepath):
|
||||
"""
|
||||
从文件中加载数据,处理缺失值和标签。
|
||||
@@ -17,20 +19,15 @@ def load_data(filepath):
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
with open(filepath, 'r') as f:
|
||||
data = [line.strip().split() for line in f.readlines()]
|
||||
# 使用pandas读取数据
|
||||
data = pd.read_csv(filepath, header=None, na_values='?')
|
||||
|
||||
# 将数据中缺失值用0填充
|
||||
data = [[0 if value == '?' else float(value) for value in line] for line in data]
|
||||
data = np.array(data)
|
||||
# 填充缺失值
|
||||
data.fillna(data.mean(), inplace=True)
|
||||
|
||||
# 分离特征和标签
|
||||
X = data[:, :-1]
|
||||
y = data[:, -1]
|
||||
|
||||
# 使用均值填充缺失值
|
||||
imputer = SimpleImputer(strategy='mean')
|
||||
X = imputer.fit_transform(X)
|
||||
X = data.iloc[:, :-1].values
|
||||
y = data.iloc[:, -1].values
|
||||
|
||||
# 过滤掉没有类别标签的数据
|
||||
valid_indices = np.isfinite(y)
|
||||
@@ -40,6 +37,7 @@ def load_data(filepath):
|
||||
return X, y
|
||||
|
||||
|
||||
|
||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000, reg_param=0.01):
|
||||
# 初始化权重
|
||||
weights = np.zeros(X.shape[1])
|
||||
|
||||
Reference in New Issue
Block a user