generated from LufsX/Experiment-LogReg
This commit is contained in:
+58
-51
@@ -1,4 +1,9 @@
|
|||||||
import numpy as np
|
import numpy as npimport numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
from sklearn.impute import SimpleImputer
|
||||||
|
from sklearn.preprocessing import StandardScaler
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
实验说明:
|
实验说明:
|
||||||
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
||||||
@@ -24,73 +29,75 @@ name = "陈瑞琪祥"
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
def sigmoid(z):
|
# Sigmoid 函数
|
||||||
return 1 / (1 + np.exp(-z))
|
def sigmoid(x):
|
||||||
|
return 1 / (1 + np.exp(-x))
|
||||||
|
|
||||||
|
# 逻辑回归训练函数
|
||||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000, regularization=0.01):
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000, regularization=0.01):
|
||||||
m, n = X.shape
|
m, n = X.shape
|
||||||
weights = np.zeros(n)
|
weights = np.zeros(n)
|
||||||
for i in range(iterations):
|
for _ in range(iterations):
|
||||||
linear_model = np.dot(X, weights)
|
linear_model = np.dot(X, weights)
|
||||||
y_predicted = sigmoid(linear_model)
|
y_predicted = sigmoid(linear_model)
|
||||||
gradient = np.dot(X.T, (y_predicted - y)) / m
|
gradient = np.dot(X.T, (y_predicted - y)) / m + regularization * weights
|
||||||
# 添加L2正则化
|
|
||||||
gradient += regularization * np.r_[[0], weights[1:]] # 不对偏置项进行正则化
|
|
||||||
weights -= learning_rate * gradient
|
weights -= learning_rate * gradient
|
||||||
return weights
|
return weights
|
||||||
|
|
||||||
|
# 逻辑回归预测函数
|
||||||
def predict_logreg(inX, weights):
|
def predict_logreg(inX, weights):
|
||||||
linear_output = np.dot(inX, weights)
|
linear_output = np.dot(inX, weights)
|
||||||
probability = sigmoid(linear_output)
|
probability = sigmoid(linear_output)
|
||||||
return 1 if probability > 0.5 else 0
|
return 1 if probability > 0.5 else 0
|
||||||
|
|
||||||
def load_data(filepath):
|
# 数据预处理函数
|
||||||
"""
|
def preprocess_data(X, y):
|
||||||
从文件中加载数据。
|
# 合并目标变量的类别
|
||||||
|
y[y == 2] = 0
|
||||||
|
y[y == 3] = 0
|
||||||
|
|
||||||
Args:
|
# 删除特征3和特征24~28
|
||||||
- filepath (str): 数据文件路径。
|
X = np.delete(X, [3], axis=1)
|
||||||
|
X = X[:, :23]
|
||||||
Returns:
|
|
||||||
- X (np.array): 特征数据。
|
|
||||||
- y (np.array): 标签数据。
|
|
||||||
"""
|
|
||||||
# 使用numpy的genfromtxt函数读取数据,以空格为分隔符
|
|
||||||
data = np.genfromtxt(filepath, delimiter=' ', invalid_raise=False, filling_values=np.nan)
|
|
||||||
|
|
||||||
# 检查数据是否为一维数组
|
|
||||||
if data.ndim == 1:
|
|
||||||
print("Data file may have an incorrect delimiter or only contains one column.")
|
|
||||||
return None, None
|
|
||||||
|
|
||||||
# 丢弃完全为NaN的行
|
|
||||||
data = data[~np.isnan(data).any(axis=1)]
|
|
||||||
|
|
||||||
# 分离特征和标签
|
|
||||||
X = data[:, :-1]
|
|
||||||
y = data[:, -1]
|
|
||||||
|
|
||||||
return X, y
|
return X, y
|
||||||
|
|
||||||
def feature_scaling(X):
|
# 加载数据函数
|
||||||
# 特征归一化
|
def load_data(filepath):
|
||||||
X_min = X.min(axis=0)
|
try:
|
||||||
X_max = X.max(axis=0)
|
data = pd.read_csv(filepath, header=None, sep=r'\s+', on_bad_lines='skip')
|
||||||
X_scaled = (X - X_min) / (X_max - X_min)
|
except pd.errors.ParserError as e:
|
||||||
return X_scaled
|
print(f"Error parsing file: {e}")
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
data.replace('?', np.nan, inplace=True)
|
||||||
|
imputer = SimpleImputer(missing_values=np.nan, strategy='constant', fill_value=0)
|
||||||
|
data.iloc[:, :-1] = imputer.fit_transform(data.iloc[:, :-1])
|
||||||
|
|
||||||
|
for col in data.columns[:-1]:
|
||||||
|
data[col] = pd.to_numeric(data[col], errors='coerce')
|
||||||
|
|
||||||
|
X = data.iloc[:, :-1].values
|
||||||
|
y = data.iloc[:, -1].values.astype(int)
|
||||||
|
|
||||||
|
X, y = preprocess_data(X, y)
|
||||||
|
return X, y
|
||||||
|
|
||||||
|
# 主函数
|
||||||
|
def main():
|
||||||
|
X_train, y_train = load_data("D:/data/horse/horse-colic.data")
|
||||||
|
X_test, y_test = load_data("D:/data/horse/horse-colic.test")
|
||||||
|
|
||||||
|
if X_train is not None and X_test is not None:
|
||||||
|
scaler = StandardScaler()
|
||||||
|
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, regularization=0.1)
|
||||||
|
y_pred = [predict_logreg(x, weights) for x in X_test]
|
||||||
|
|
||||||
|
accuracy = np.mean(y_pred == y_test)
|
||||||
|
print(f"准确率: {accuracy}")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
X_train, y_train = load_data("./data/horse-colic.data")
|
main()
|
||||||
X_test, y_test = load_data("./data/horse-colic.test")
|
|
||||||
|
|
||||||
# 特征归一化
|
|
||||||
X_train_scaled = feature_scaling(X_train)
|
|
||||||
X_test_scaled = feature_scaling(X_test)
|
|
||||||
|
|
||||||
# 训练对率回归模型
|
|
||||||
weights = train_logreg(X_train_scaled, y_train, learning_rate=0.01, iterations=1000)
|
|
||||||
|
|
||||||
# 测试单个数据
|
|
||||||
y_pred = predict_logreg(X_test_scaled[11], weights)
|
|
||||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user