generated from LufsX/Experiment-LogReg
This commit is contained in:
+17
-12
@@ -28,38 +28,43 @@ name = "廖子豪"
|
|||||||
# 这里写自己的代码实现
|
# 这里写自己的代码实现
|
||||||
|
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
try:
|
"""
|
||||||
# 尝试加载数据文件的前几行来检查格式
|
从文件中加载数据。
|
||||||
with open(filepath, 'r') as file:
|
|
||||||
for _ in range(5):
|
|
||||||
line = file.readline()
|
|
||||||
print(line.strip()) # 打印前5行数据
|
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- filepath (str): 数据文件路径。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- np.array: 特征数据。
|
||||||
|
- np.array: 标签数据。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
# 使用 numpy 的 genfromtxt 函数加载数据,自动处理缺失值
|
# 使用 numpy 的 genfromtxt 函数加载数据,自动处理缺失值
|
||||||
data = np.genfromtxt(filepath, delimiter=',', dtype=float, filling_values=np.nan)
|
# 指定空格作为分隔符
|
||||||
|
data = np.genfromtxt(filepath, delimiter=' ', dtype=float, filling_values=np.nan)
|
||||||
|
|
||||||
print(f"Loaded data shape: {data.shape}") # 调试打印数据形状
|
print(f"Loaded data shape: {data.shape}") # 调试打印数据形状
|
||||||
|
|
||||||
|
# 检查数据是否为一维数组
|
||||||
if data.ndim == 1:
|
if data.ndim == 1:
|
||||||
raise ValueError("数据加载后为一维数组,预期为二维数组。请检查数据文件格式。")
|
raise ValueError("数据加载后为一维数组,预期为二维数组。请检查数据文件格式。")
|
||||||
|
|
||||||
|
# 检查数据文件中是否有足够的列
|
||||||
if data.shape[1] < 2:
|
if data.shape[1] < 2:
|
||||||
raise ValueError("数据文件中没有足够的列。每行至少需要包含一个特征和一个标签。")
|
raise ValueError("数据文件中没有足够的列。每行至少需要包含一个特征和一个标签。")
|
||||||
|
|
||||||
|
# 分离特征和标签
|
||||||
X = data[:, :-1] # 所有行,除了最后一列
|
X = data[:, :-1] # 所有行,除了最后一列
|
||||||
y = data[:, -1] # 所有行,只有最后一列
|
y = data[:, -1] # 所有行,只有最后一列
|
||||||
|
|
||||||
|
# 填充缺失值,这里使用每列的均值来填充
|
||||||
X = np.nan_to_num(X, nan=np.nanmean(X, axis=0))
|
X = np.nan_to_num(X, nan=np.nanmean(X, axis=0))
|
||||||
|
|
||||||
return X, y
|
return X, y
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error loading data: {e}")
|
print(f"Error loading data: {e}")
|
||||||
|
# 返回空数组而不是None,以避免后续代码中出现错误
|
||||||
return np.empty((0, 0)), np.empty(0)
|
return np.empty((0, 0)), np.empty(0)
|
||||||
|
|
||||||
# 调用 load_data 函数并打印结果
|
|
||||||
X, y = load_data("./data/horse-colic.data")
|
|
||||||
print("Features:", X)
|
|
||||||
print("Labels:", y)
|
|
||||||
|
|
||||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||||
"""
|
"""
|
||||||
|
|||||||
Reference in New Issue
Block a user