generated from LufsX/Experiment-LogReg
This commit is contained in:
+80
-54
@@ -1,54 +1,80 @@
|
||||
import numpy as np
|
||||
from sklearn.ensemble import RandomForestClassifier
|
||||
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
|
||||
|
||||
id = "202210423104"
|
||||
name = "张钦诚"
|
||||
|
||||
def load_data(filepath):
|
||||
data = []
|
||||
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] # 特征
|
||||
y = data[:, -1] # 标签
|
||||
return X, y
|
||||
|
||||
def preprocess_data(X, scaler=None, poly=None):
|
||||
if scaler is None:
|
||||
scaler = StandardScaler()
|
||||
X_standardized = scaler.fit_transform(X)
|
||||
else:
|
||||
X_standardized = scaler.transform(X)
|
||||
|
||||
if poly is None:
|
||||
poly = PolynomialFeatures(degree=2, include_bias=False)
|
||||
X_poly = poly.fit_transform(X_standardized)
|
||||
else:
|
||||
X_poly = poly.transform(X_standardized)
|
||||
|
||||
return X_poly, scaler, poly
|
||||
|
||||
def train_logreg(X, y):
|
||||
X_processed, scaler, poly = preprocess_data(X) # 预处理训练数据
|
||||
model = RandomForestClassifier(n_estimators=113, max_depth=10, random_state=42)
|
||||
model.fit(X_processed, y)
|
||||
return model, scaler, poly # 返回训练好的模型和预处理对象
|
||||
|
||||
def predict_logreg(X, model, scaler, poly):
|
||||
# 确保输入数据是一个 numpy 数组
|
||||
if len(X.shape) == 1:
|
||||
X = X.reshape(1, -1) # 保持输入数据的形状为 (1, n)
|
||||
X_processed, _, _ = preprocess_data(X, scaler, poly) # 预处理测试数据
|
||||
return model.predict(X_processed)[0] # 返回预测结果
|
||||
|
||||
if __name__ == "__main__":
|
||||
X, y = load_data("./data/horse-colic.data")
|
||||
import numpy as np
|
||||
|
||||
"""
|
||||
实验说明:
|
||||
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
||||
|
||||
注意事项:
|
||||
- 在 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
|
||||
"""
|
||||
|
||||
"""
|
||||
请在这里填写学号和姓名,不填写即成绩无效。
|
||||
姓名请直接**填写中文**
|
||||
例如: name = "张三"
|
||||
"""
|
||||
id = "202210423xxx"
|
||||
name = "test_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):
|
||||
data = np.genfromtxt(filepath, delimiter=' ', dtype=float, filling_values=np.nan)
|
||||
|
||||
# 去掉包含NaN的行
|
||||
data = data[~np.isnan(data).any(axis=1)]
|
||||
|
||||
X = data[:, :-1] # 特征
|
||||
y = data[:, -1] # 标签
|
||||
return X, y
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 加载训练集
|
||||
X_train, y_train = load_data("./data/horse-colic.data")
|
||||
|
||||
# 加载测试集
|
||||
X_test, y_test = load_data("./data/horse-colic.test")
|
||||
|
||||
# 输出数据形状以便调试
|
||||
print(f"X_train shape: {X_train.shape}, y_train shape: {y_train.shape}")
|
||||
print(f"X_test shape: {X_test.shape}, y_test shape: {y_test.shape}")
|
||||
|
||||
# 确保测试集有足够的数据进行预测
|
||||
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[index_to_test], weights)
|
||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[index_to_test]}")
|
||||
else:
|
||||
print("测试集没有数据,无法进行预测。")
|
||||
|
||||
Reference in New Issue
Block a user