generated from LufsX/Experiment-LogReg
This commit is contained in:
+40
-3
@@ -21,12 +21,26 @@ import numpy as np
|
|||||||
"""
|
"""
|
||||||
请在这里填写学号和姓名,不填写即成绩无效。
|
请在这里填写学号和姓名,不填写即成绩无效。
|
||||||
"""
|
"""
|
||||||
id = "202210423xxx"
|
id = "202210423209"
|
||||||
name = "test_name"
|
name = "万子玉"
|
||||||
|
|
||||||
|
|
||||||
# 这里写自己的代码实现
|
# 这里写自己的代码实现
|
||||||
def train_logreg(X, y, other_params="你自己设置一些其它参数"):
|
def sigmoid(z):
|
||||||
|
return 1 / (1 + np.exp(-z))
|
||||||
|
|
||||||
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||||
|
X = np.insert(X, 0, 1, axis=1) # 添加偏置项
|
||||||
|
weights = np.zeros(X.shape[1])
|
||||||
|
m = X.shape[0]
|
||||||
|
|
||||||
|
for _ in range(iterations):
|
||||||
|
z = np.dot(X, weights)
|
||||||
|
h = sigmoid(z)
|
||||||
|
gradient = np.dot(X.T, (h - y)) / m
|
||||||
|
weights -= learning_rate * gradient
|
||||||
|
|
||||||
|
return weights
|
||||||
"""
|
"""
|
||||||
对率回归训练函数。
|
对率回归训练函数。
|
||||||
|
|
||||||
@@ -41,6 +55,11 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"):
|
|||||||
|
|
||||||
|
|
||||||
def predict_logreg(inX, weights):
|
def predict_logreg(inX, weights):
|
||||||
|
inX = np.insert(inX, 0, 1) # 添加偏置项
|
||||||
|
z = np.dot(inX, weights)
|
||||||
|
h = sigmoid(z)
|
||||||
|
return 1 if h >= 0.5 else 0
|
||||||
|
|
||||||
"""
|
"""
|
||||||
对率回归预测函数。
|
对率回归预测函数。
|
||||||
|
|
||||||
@@ -55,6 +74,24 @@ def predict_logreg(inX, weights):
|
|||||||
|
|
||||||
# 这里也写自己的代码实现
|
# 这里也写自己的代码实现
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
|
with open(filepath, 'r') as file:
|
||||||
|
lines = file.readlines()
|
||||||
|
|
||||||
|
data = [line.strip().split() for line in lines]
|
||||||
|
data = [list(map(lambda x: float(x) if x != '?' else np.nan, row)) for row in data]
|
||||||
|
|
||||||
|
# 处理缺失值,这里简单用平均值填充
|
||||||
|
for i in range(len(data[0])):
|
||||||
|
mean_val = np.nanmean([row[i] for row in data if not np.isnan(row[i])])
|
||||||
|
for row in data:
|
||||||
|
if np.isnan(row[i]):
|
||||||
|
row[i] = mean_val
|
||||||
|
|
||||||
|
# 分离特征和标签
|
||||||
|
X = [row[:-1] for row in data]
|
||||||
|
y = [row[-1] for row in data]
|
||||||
|
|
||||||
|
return np.array(X), np.array(y)
|
||||||
"""
|
"""
|
||||||
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user