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

This commit is contained in:
hao
2024-11-02 13:02:22 +08:00
parent c6d6bfc0ff
commit d104c681d1
+9 -16
View File
@@ -66,7 +66,6 @@ def predict_logreg(inX, weights):
prediction = 1 / (1 + np.exp(-np.dot(inX, weights))) prediction = 1 / (1 + np.exp(-np.dot(inX, weights)))
return 1 if prediction > 0.5 else 0 return 1 if prediction > 0.5 else 0
# 这里也写自己的代码实现
def load_data(filepath): def load_data(filepath):
""" """
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
@@ -78,24 +77,18 @@ def load_data(filepath):
- np.array: 特征数据。 - np.array: 特征数据。
- np.array: 标签数据。 - np.array: 标签数据。
""" """
data = np.loadtxt(filepath, delimiter=',') # 读取数据,将非数值转换为NaN
# 将分类数据和缺失值处理后转换为浮点数 data = np.genfromtxt(filepath, delimiter=',', dtype=float, missing_values='?')
# 分离特征和标签
X = data[:, :-1] X = data[:, :-1]
y = data[:, -1].astype(int) # 假设标签是整数类型 y = data[:, -1]
if X.shape[1] > 1: # 将缺失值填充为列的平均值
# 将第一列分类数据转换为独热编码 for i in range(X.shape[1]):
from sklearn.preprocessing import OneHotEncoder X[:, i] = np.where(np.isnan(X[:, i]), np.nanmean(X[:, i]), X[:, i])
encoder = OneHotEncoder(sparse=False)
X[:, 0] = X[:, 0].astype(str) # 确保是字符串类型
X_encoded = encoder.fit_transform(X[:, 0].reshape(-1, 1))
# 将独热编码结果替换原来的分类列
X = np.hstack((X_encoded, X[:, 1:]))
# 将缺失值填充为0 return X, y.astype(int)
X[np.isnan(X)] = 0
return X, y
if __name__ == "__main__": if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改 # 以下代码可用于测试,可自行随意修改