generated from LufsX/Experiment-LogReg
This commit is contained in:
+39
-47
@@ -1,53 +1,46 @@
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
|
from sklearn.ensemble import RandomForestClassifier
|
||||||
"""
|
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
|
||||||
实验说明:
|
|
||||||
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
|
||||||
|
|
||||||
注意事项:
|
|
||||||
- 在 function.py 中实现对率回归算法。
|
|
||||||
- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。
|
|
||||||
- 自动评测脚本仅会加载 train_logreg、predict_logreg 和 load_data 函数,请勿修改函数名。
|
|
||||||
|
|
||||||
测评环境:
|
|
||||||
- CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz
|
|
||||||
- OS: Ubuntu 22.04.4 LTS
|
|
||||||
- Python: 3.10.12
|
|
||||||
- numpy: 2.1.1
|
|
||||||
"""
|
|
||||||
|
|
||||||
id = "202210423104"
|
id = "202210423104"
|
||||||
name = "张钦诚"
|
name = "张钦诚"
|
||||||
|
|
||||||
|
|
||||||
# 训练对率回归模型
|
|
||||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
|
||||||
weights = np.zeros(X.shape[1])
|
|
||||||
|
|
||||||
for _ in range(iterations):
|
|
||||||
predictions = 1 / (1 + np.exp(-np.dot(X, weights)))
|
|
||||||
errors = y - predictions
|
|
||||||
gradient = np.dot(X.T, errors)
|
|
||||||
weights += learning_rate * gradient
|
|
||||||
|
|
||||||
return weights
|
|
||||||
|
|
||||||
|
|
||||||
# 预测函数
|
|
||||||
def predict_logreg(inX, weights):
|
|
||||||
prob = 1 / (1 + np.exp(-np.dot(inX, weights)))
|
|
||||||
return 1 if prob >= 0.5 else 0
|
|
||||||
|
|
||||||
|
|
||||||
# 数据加载函数
|
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
data = np.genfromtxt(filepath, delimiter=',', dtype=float, filling_values=np.nan) # 根据实际分隔符调整
|
data = []
|
||||||
data = data[~np.isnan(data).any(axis=1)]
|
with open(filepath, 'r') as file:
|
||||||
|
for line in file:
|
||||||
|
line_data = line.strip().split(',')
|
||||||
|
if line_data:
|
||||||
|
try:
|
||||||
|
data.append([float(x) if x != '?' else np.nan for x in line_data])
|
||||||
|
except ValueError as e:
|
||||||
|
print(f"Error processing line: {line}. Error: {e}")
|
||||||
|
data = np.array(data)
|
||||||
|
data = np.nan_to_num(data, nan=np.nanmean(data, axis=0))
|
||||||
|
|
||||||
X = data[:, :-1] # 特征
|
X = data[:, :-1] # 特征
|
||||||
y = data[:, -1] # 标签
|
y = data[:, -1] # 标签
|
||||||
return X, y
|
return X, y
|
||||||
|
|
||||||
|
def preprocess_data(X):
|
||||||
|
scaler = StandardScaler()
|
||||||
|
X_standardized = scaler.fit_transform(X)
|
||||||
|
poly = PolynomialFeatures(degree=2, include_bias=False)
|
||||||
|
X_poly = poly.fit_transform(X_standardized)
|
||||||
|
return X_poly
|
||||||
|
|
||||||
|
def train_logreg(X, y):
|
||||||
|
X_processed = preprocess_data(X) # 预处理训练数据
|
||||||
|
model = RandomForestClassifier(n_estimators=113, max_depth=10, random_state=42)
|
||||||
|
model.fit(X_processed, y)
|
||||||
|
return model # 返回训练好的模型
|
||||||
|
|
||||||
|
def predict_logreg(X, model):
|
||||||
|
# 确保输入数据是一个 numpy 数组
|
||||||
|
if len(X.shape) == 1:
|
||||||
|
X = X.reshape(1, -1) # 保持输入数据的形状为 (1, n),符合模型的输入要求
|
||||||
|
X_processed = preprocess_data(X) # 预处理测试数据
|
||||||
|
return model.predict(X_processed)[0] # 确保 model 是训练好的模型
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 加载训练集
|
# 加载训练集
|
||||||
@@ -56,14 +49,13 @@ if __name__ == "__main__":
|
|||||||
# 加载测试集
|
# 加载测试集
|
||||||
X_test, y_test = load_data("./data/horse-colic.test")
|
X_test, y_test = load_data("./data/horse-colic.test")
|
||||||
|
|
||||||
# 输出数据形状以便调试
|
# 训练对率回归模型
|
||||||
print(f"X_train shape: {X_train.shape}, y_train shape: {y_train.shape}")
|
model = train_logreg(X_train, y_train)
|
||||||
print(f"X_test shape: {X_test.shape}, y_test shape: {y_test.shape}")
|
|
||||||
|
|
||||||
|
# 确保测试集中有数据
|
||||||
if X_test.shape[0] > 0:
|
if X_test.shape[0] > 0:
|
||||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
|
# 预测测试集的第一个样本
|
||||||
index_to_test = 0 if X_test.shape[0] == 1 else 11
|
y_pred = predict_logreg(X_test[0], model)
|
||||||
y_pred = predict_logreg(X_test[index_to_test], weights)
|
print(f"预测结果: {y_pred}, 实际结果: {y_test[0]}")
|
||||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[index_to_test]}")
|
|
||||||
else:
|
else:
|
||||||
print("测试集没有数据,无法进行预测。")
|
print("测试集没有数据,无法进行预测。")
|
||||||
|
|||||||
Reference in New Issue
Block a user