generated from LufsX/Experiment-LogReg
This commit is contained in:
+7
-10
@@ -26,10 +26,6 @@ name = "刘子豪"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def sigmoid(z):
|
||||
return 1 / (1 + np.exp(-z)) #用于将数据转化成一个0 - 1之间的概率值
|
||||
|
||||
|
||||
def train_logreg(X, y, other_params="你自己设置一些其它参数"):
|
||||
"""
|
||||
对率回归训练函数。
|
||||
@@ -44,11 +40,14 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"):
|
||||
"""
|
||||
m, n = X.shape
|
||||
weights = np.zeros(n)
|
||||
|
||||
for _ in range(iterations):
|
||||
predictions = sigmoid(np.dot(X, weights))
|
||||
z = np.dot(X, weights)
|
||||
predictions = 1 / (1 + np.exp(-z)) # 计算sigmoid
|
||||
errors = y - predictions
|
||||
gradient = np.dot(X.T, errors) / m
|
||||
weights += learning_rate * gradient
|
||||
|
||||
return weights
|
||||
|
||||
|
||||
@@ -63,7 +62,8 @@ def predict_logreg(inX, weights):
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
probability = sigmoid(np.dot(inX, weights))
|
||||
z = np.dot(inX, weights)
|
||||
probability = 1 / (1 + np.exp(-z))
|
||||
return 1 if probability >= 0.5 else 0
|
||||
|
||||
|
||||
@@ -84,17 +84,14 @@ def load_data(filepath):
|
||||
with open(filepath, 'r') as file:
|
||||
for line in file:
|
||||
fields = line.strip().split()
|
||||
# 检查是否有缺失值,并排除不符合行长度要求的数据
|
||||
if '?' in fields or len(fields) < 2:
|
||||
continue
|
||||
try:
|
||||
# 假设特征在前面,标签在最后一列
|
||||
data.append([float(x) for x in fields[:-1]])
|
||||
labels.append(int(fields[-1]))
|
||||
except ValueError:
|
||||
# 如果无法转换为浮点数或整数,跳过该行
|
||||
continue
|
||||
# 返回值需要是两个NumPy数组
|
||||
|
||||
return np.array(data), np.array(labels)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user