forked from LufsX/Experiment-LogReg
This commit is contained in:
+26
-28
@@ -1,4 +1,5 @@
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
|
from sklearn.preprocessing import StandardScaler
|
||||||
|
|
||||||
"""
|
"""
|
||||||
请在这里填写学号和姓名,不填写即成绩无效。
|
请在这里填写学号和姓名,不填写即成绩无效。
|
||||||
@@ -37,20 +38,20 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
|||||||
return weights
|
return weights
|
||||||
|
|
||||||
|
|
||||||
def predict_logreg(X, weights):
|
def predict_logreg(inX, weights):
|
||||||
"""
|
"""
|
||||||
对率回归预测函数。
|
对率回归预测函数。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
- X (numpy array): 输入待分类的样本。
|
- inX (numpy array): 输入待分类的样本。
|
||||||
- weights (numpy array): 训练得到的权重。
|
- weights (numpy array): 训练得到的权重。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
- numpy array: 预测的分类标签。
|
- int: 预测的分类标签。
|
||||||
"""
|
"""
|
||||||
linear_model = np.dot(X, weights)
|
linear_model = np.dot(inX, weights)
|
||||||
y_predicted = sigmoid(linear_model)
|
y_predicted = sigmoid(linear_model)
|
||||||
return (y_predicted > 0.5).astype(int)
|
return 1 if y_predicted > 0.5 else 0
|
||||||
|
|
||||||
|
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
@@ -64,40 +65,37 @@ def load_data(filepath):
|
|||||||
- X (np.array): 特征数据。
|
- X (np.array): 特征数据。
|
||||||
- y (np.array): 标签数据。
|
- y (np.array): 标签数据。
|
||||||
"""
|
"""
|
||||||
# 使用 np.genfromtxt 加载数据,并且忽略文件中不能转换为 float 的行
|
data = np.genfromtxt(filepath, delimiter=' ', dtype=float)
|
||||||
# 更新分隔符为逗号,根据实际格式来修改,通常csv用',',txt文件则可能用'\t'或者' '来分隔
|
X = data[:, :-1]
|
||||||
data = np.genfromtxt(filepath, delimiter=',', dtype=float, filling_values=np.nan)
|
y = data[:, -1]
|
||||||
|
|
||||||
# 删除所有包含缺失值的行
|
|
||||||
data = data[~np.isnan(data).any(axis=1)]
|
|
||||||
|
|
||||||
# 确保数据的正确性: 不同于训练集的标签列
|
|
||||||
if data.ndim == 1:
|
|
||||||
data = np.array([data])
|
|
||||||
|
|
||||||
# 假设最后一列为标签
|
|
||||||
X = data[:, :-1] # 特征
|
|
||||||
y = data[:, -1] # 标签
|
|
||||||
return X, y
|
return X, y
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
def main():
|
||||||
# 加载训练集
|
# 加载训练集
|
||||||
X_train, y_train = load_data("./data/horse-colic.data")
|
X_train, y_train = load_data("./data/horse-colic.data")
|
||||||
|
|
||||||
# 加载测试集
|
# 加载测试集
|
||||||
X_test, y_test = load_data("./data/horse-colic.test")
|
X_test, y_test = load_data("./data/horse-colic.test")
|
||||||
|
|
||||||
# 确保训练集和测试集特征数量匹配
|
# 标准化特征数据
|
||||||
if X_train.shape[1] != X_test.shape[1]:
|
scaler = StandardScaler()
|
||||||
raise ValueError("训练集和测试集特征数量不匹配!")
|
X_train = scaler.fit_transform(X_train)
|
||||||
|
X_test = scaler.transform(X_test)
|
||||||
|
|
||||||
# 训练对率回归模型
|
# 训练对率回归模型
|
||||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
|
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
|
||||||
|
|
||||||
# 测试多个数据
|
# 测试单个数据
|
||||||
y_pred = predict_logreg(X_test, weights)
|
correct_predictions = 0
|
||||||
|
for i in range(X_test.shape[0]):
|
||||||
|
y_pred = predict_logreg(X_test[i], weights)
|
||||||
|
if y_pred == y_test[i]:
|
||||||
|
correct_predictions += 1
|
||||||
|
|
||||||
# 输出部分预测结果
|
accuracy = correct_predictions / X_test.shape[0]
|
||||||
for i in range(min(10, len(y_pred))): # 只输出前10个预测结果
|
print(f"Accuracy: {accuracy:.2f}")
|
||||||
print(f"预测结果: {y_pred[i]}, 实际结果: {y_test[i]}")
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user