generated from LufsX/Experiment-LogReg
This commit is contained in:
+19
-10
@@ -29,6 +29,9 @@ name = "Tanjunfeng"
|
|||||||
|
|
||||||
# 这里写自己的代码实现
|
# 这里写自己的代码实现
|
||||||
|
|
||||||
|
# 这里写自己的代码实现
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
# 这里写自己的代码实现
|
# 这里写自己的代码实现
|
||||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||||
"""
|
"""
|
||||||
@@ -85,17 +88,23 @@ def load_data(filepath):
|
|||||||
- np.array: 特征数据。
|
- np.array: 特征数据。
|
||||||
- np.array: 标签数据。
|
- np.array: 标签数据。
|
||||||
"""
|
"""
|
||||||
data = []
|
# 使用 numpy.genfromtxt 读取数据
|
||||||
with open(filepath, 'r') as file:
|
data = np.genfromtxt(
|
||||||
for line in file:
|
filepath,
|
||||||
line = line.strip().split()
|
delimiter=None, # 自动检测分隔符(包括空白符、制表符等)
|
||||||
if '?' in line:
|
dtype=float,
|
||||||
continue # 跳过包含缺失值的行
|
missing_values='?',
|
||||||
data.append([float(x) for x in line])
|
filling_values=np.nan,
|
||||||
data = np.array(data)
|
autostrip=True
|
||||||
|
)
|
||||||
|
|
||||||
|
# 删除包含缺失值的行
|
||||||
|
data = data[~np.isnan(data).any(axis=1)]
|
||||||
|
|
||||||
|
# 将数据分为特征和标签
|
||||||
X = data[:, :-1]
|
X = data[:, :-1]
|
||||||
y = data[:, -1]
|
y = data[:, -1]
|
||||||
# 将标签转换为二分类1: 存活,0: 死亡或安乐死
|
# 将标签转换为二分1: 存活,0: 死亡或安乐死
|
||||||
y = np.where(y == 1, 0, 1)
|
y = np.where(y == 1, 0, 1)
|
||||||
return X, y
|
return X, y
|
||||||
|
|
||||||
@@ -113,7 +122,7 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
# 测试单个数据
|
# 测试单个数据
|
||||||
y_pred = predict_logreg(X_test[11], weights)
|
y_pred = predict_logreg(X_test[11], weights)
|
||||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
print(f"预测结果: {y_pred}, 实际结果: {int(y_test[11])}")
|
||||||
|
|
||||||
# 可选:计算测试集上的准确率
|
# 可选:计算测试集上的准确率
|
||||||
correct = sum(predict_logreg(X_test[i], weights) == y_test[i] for i in range(len(X_test)))
|
correct = sum(predict_logreg(X_test[i], weights) == y_test[i] for i in range(len(X_test)))
|
||||||
|
|||||||
Reference in New Issue
Block a user