1.数据输出与存储:
'''
数据输出
'''
print('\n----------------------------OUTPUT----------------------------\n')
stats_list = []
for k, v in results.items():
mean_value = np.mean(v)
std_value = np.std(v)
median_value = np.median(v)
max_value = np.max(v)
min_value = np.min(v)
stats_list.append([k, mean_value, std_value, median_value, max_value, min_value]) # 存储一下,方便保存到csv文件
print(
"{:<15} Mean = {:>7.3f}, Std = {:>7.3f}, Median = {:>7.3f}, Max = {:>7.3f}, Min = {:>7.3f}".format(
k, mean_value, std_value, median_value, max_value, min_value))
'''
数据保存
'''
# N1. 测试结果写入csv文件
headers = ["Metric", "Mean", "Std", "Median", "Max", "Min"]
with open('stats.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(headers) # 写入标题行
writer.writerows(stats_list) # 写入统计结果
print("\nData has been written to stats.csv\n")
2.数据读取与绘制
import csv
import matplotlib.pyplot as plt
# 读取CSV文件并存储数据
def read_csv(filename):
with open(filename, mode='r', newline='') as csvfile:
reader = csv.DictReader(csvfile)
data = {rows['Metric']: {
'Mean': float(rows['Mean']),
'Std': float(rows['Std']),
'Median': float(rows['Median']),
'Max': float(rows['Max']),
'Min': float(rows['Min'])
} for rows in reader}
return data
# 分组数据
def group_data(data):
similarity = {metric: stats for metric, stats in data.items() if stats['Max'] < 2}
distance = {metric: stats for metric, stats in data.items() if stats['Max'] >= 2}
return similarity, distance
# 绘制图表
def plot_data(data_dict, title, filename):
metrics = list(data_dict.keys())
means = [data_dict[metric]['Mean'] for metric in metrics]
stds = [data_dict[metric]['Std'] for metric in metrics]
medians = [data_dict[metric]['Median'] for metric in metrics]
max_values = [data_dict[metric]['Max'] for metric in metrics]
min_values = [data_dict[metric]['Min'] for metric in metrics]
fig, ax = plt.subplots(figsize=(10, 6))
bar_width = 0.35
indices = range(len(metrics))
bars = plt.bar(indices, means, bar_width, color='skyblue', yerr=stds, capsize=5, label='Mean ± Std')
# 为每个柱子添加均值标签
for i, mean_value in enumerate(means):
plt.text(i+0.2, mean_value + stds[i] * 0.05, f'{mean_value:.3f}', ha='center', va='bottom')
for i, metric in enumerate(metrics):
plt.plot(indices[i], medians[i], 'g^', markersize=8) # 绿色三角表示中位数
plt.plot(indices[i], max_values[i], 'mv', markersize=8) # 紫色菱形表示最大值
plt.plot(indices[i], min_values[i], 'k<', markersize=8) # 黑色尖角表示最小值
plt.title(title)
plt.xlabel('Metrics')
plt.ylabel('Values')
plt.xticks(indices, metrics, rotation=45)
plt.legend()
plt.tight_layout()
plt.savefig(filename)
plt.show()
# 主程序
if __name__ == '__main__':
filename = 'stats.csv'
data = read_csv(filename)
similarity, distance = group_data(data)
plot_data(similarity, 'Similarity', 'Similarity.png')
plot_data(distance, 'Distance', 'Distance.png')