generated from LufsX/Experiment-LogReg
This commit is contained in:
+23
-11
@@ -90,7 +90,7 @@ def predict_logreg(inX, weights):
|
|||||||
|
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
"""
|
"""
|
||||||
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
从文件中加载数据。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
- filepath (str): 数据文件路径。
|
- filepath (str): 数据文件路径。
|
||||||
@@ -100,17 +100,21 @@ def load_data(filepath):
|
|||||||
- np.array: 标签数据。
|
- np.array: 标签数据。
|
||||||
"""
|
"""
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
|
||||||
|
|
||||||
# 读取数据,指定空格为分隔符,处理缺失值 '?'
|
# 定义数据类型,将缺失值标记为 np.nan
|
||||||
data = pd.read_csv(filepath, delim_whitespace=True, header=None, na_values='?')
|
def conv(value):
|
||||||
|
return np.nan if value == '?' else float(value)
|
||||||
|
|
||||||
# 丢弃包含缺失值的行
|
# 使用 genfromtxt 读取数据
|
||||||
data = data.dropna()
|
data = np.genfromtxt(filepath, delimiter=' ', dtype=float, converters=None,
|
||||||
|
missing_values='?', filling_values=np.nan, autostrip=True)
|
||||||
|
|
||||||
# 提取特征和标签
|
# 删除包含缺失值的行
|
||||||
X = data.iloc[:, :-1].values # 所有列,除最后一列
|
data = data[~np.isnan(data).any(axis=1)]
|
||||||
y = data.iloc[:, -1].values # 最后一列为标签
|
|
||||||
|
# 特征和标签分开
|
||||||
|
X = data[:, :-1]
|
||||||
|
y = data[:, -1]
|
||||||
|
|
||||||
# 将标签转换为二分类1: 存活,0: 死亡或安乐死
|
# 将标签转换为二分类1: 存活,0: 死亡或安乐死
|
||||||
y = np.where(y == 1, 0, 1)
|
y = np.where(y == 1, 0, 1)
|
||||||
@@ -119,8 +123,6 @@ def load_data(filepath):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 以下代码可用于测试,可自行随意修改
|
|
||||||
|
|
||||||
# 加载训练集
|
# 加载训练集
|
||||||
X_train, y_train = load_data("./data/horse-colic.data")
|
X_train, y_train = load_data("./data/horse-colic.data")
|
||||||
|
|
||||||
@@ -134,6 +136,16 @@ if __name__ == "__main__":
|
|||||||
y_pred = predict_logreg(X_test[C_11](), weights)
|
y_pred = predict_logreg(X_test[C_11](), weights)
|
||||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[C_11]()}")
|
print(f"预测结果: {y_pred}, 实际结果: {y_test[C_11]()}")
|
||||||
|
|
||||||
|
# 可选:计算测试集上的准确率
|
||||||
|
correct = 0
|
||||||
|
for i in range(len(X_test)):
|
||||||
|
y_pred = predict_logreg(X_test[i], weights)
|
||||||
|
if y_pred == y_test[i]:
|
||||||
|
correct += 1
|
||||||
|
accuracy = correct / len(X_test)
|
||||||
|
print(f"模型在测试集上��准确率: {accuracy * 100:.2f}%")
|
||||||
|
|
||||||
|
|
||||||
# 可选:计算测试集上的准确率
|
# 可选:计算测试集上的准确率
|
||||||
correct = 0
|
correct = 0
|
||||||
for i in range(len(X_test)):
|
for i in range(len(X_test)):
|
||||||
|
|||||||
Reference in New Issue
Block a user