排序Test

本文介绍了一个简单的Java程序,演示了如何使用选择排序和冒泡排序两种基本算法对整数数组进行排序。通过代码实例,读者可以了解到这两种排序方法的具体实现方式,并通过输出结果直观地看到排序效果。
package java基础知识.小结与练习;

class XuanzeTest {

	/**
	 * @param 选择排序和冒泡排序的练习
	 */
	public static void main(String[] args) {
		//定义数组
		int arr[]=new int [] {123,344,56,11,223};
		shuchu(arr);
		maopao(arr);
		//xuanze(arr);
		shuchu(arr);
	}
	//选择排序
	public static void xuanze(int []arr){
		for(int a = 0;a<arr.length-1;a++){
			for(int b =a+1;b<arr.length;b++){
				if(arr[a]>arr[b]){
					int temp = arr[a];
					arr[a]=arr[b];
					arr[b]=temp;
				}
			}
		}
	}
	//输出数组
	public static void shuchu (int []arr){
		System.out.print("[");
		for(int a =0;a<arr.length;a++){
			if(a==arr.length-1){
				System.out.print(arr[a]+"]");
			}else{
				System.out.print(arr[a]+",");
			}
		}
	}
	// 冒泡排序
	public static void maopao(int arr[]){
		for(int a=0;a<arr.length-1;a++){
			for(int b =0;b<arr.length-a-1;b++){
				if(arr[b]>arr[b+1]){
					int temp =arr[b];
					arr[b]=arr[b+1];
					arr[b+1]=temp;
				}
			}
		}
	}
}

# =============================== # 第二部分:按月评估预测精度 # =============================== best_model_name = comparison_df.index[0] best_model_predictions = predictions[best_model_name] # 使用最终集成模型的测试集预测结果 pred_test = best_model_predictions # 统一变量名用于后续分析 y_test = y_test_original # 创建DataFrame df_test = pd.DataFrame({ 'dates_test': dates_test, 'y_test': y_test, 'pred_test': pred_test }) # 提取月份和年份 df_test['month'] = df_test['dates_test'].dt.month df_test['year'] = df_test['dates_test'].dt.year # 初始化评估列表 evaluation = [] # 遍历每个月份 months = sorted(df_test['month'].unique()) for month in months: month_data = df_test[df_test['month'] == month] for year in sorted(month_data['year'].unique()): specific_month_data = month_data[month_data['year'] == year] if specific_month_data.empty: continue total_days = len(specific_month_data) accurate_count = 0 overestimate_count = 0 underestimate_count = 0 # 逐日评估 for _, row in specific_month_data.iterrows(): lower_bound = row['pred_test'] * 0.75 upper_bound = row['pred_test'] * 1.25 actual_value = row['y_test'] if lower_bound <= actual_value <= upper_bound: accurate_count += 1 elif actual_value < lower_bound: overestimate_count += 1 elif actual_value > upper_bound: underestimate_count += 1 # 计算比率 accuracy_rate = accurate_count / total_days overestimate_rate = overestimate_count / total_days underestimate_rate = underestimate_count / total_days # 存储结果 evaluation.append({ 'Year': year, 'Month': month, 'Accuracy Rate': accuracy_rate, 'Overestimate Rate': overestimate_rate, 'Underestimate Rate': underestimate_rate }) # 转换为 DataFrame 并输出 evaluation_df = pd.DataFrame(evaluation) print("\n📊 Monthly Evaluation Results:") print(evaluation_df) import pandas as pd import numpy as np import matplotlib.pyplot as plt # 设置全局字体为 Times New Roman plt.rcParams['font.family'] = 'Times New Roman' # 假定 evaluation_df 已存在 evaluation_df['Year'] = evaluation_df['Year'].astype(int) evaluation_df['Month'] = evaluation_df['Month'].astype(int) # 创建 YearMonth 列用于排序 evaluation_df['YearMonth'] = evaluation_df['Year'].astype(str) + '-' + evaluation_df['Month'].astype(str).str.zfill(2) evaluation_df = evaluation_df.sort_values(by='YearMonth').reset_index(drop=True) # 2. 绘图设置 # ----------------------------- plt.figure(figsize=(18, 7)) # 稍微加宽,让柱子之间显得更宽松 ind = ind = np.arange(len(evaluation_df)) width = 0.3 # 减小柱子宽度,制造更多空白 # 绘制柱状图:从左到右为 Underestimate, Accuracy, Overestimate accuracy_bar = plt.bar(ind- width, evaluation_df['Accuracy Rate'], width, color='green', label='Accuracy Rate') underestimate_bar = plt.bar(ind , evaluation_df['Underestimate Rate'], width, color='red', label='Underestimate Rate') overestimate_bar = plt.bar(ind + width, evaluation_df['Overestimate Rate'], width, color='blue', label='Overestimate Rate') # 添加数值标签 for bars in [ accuracy_bar, underestimate_bar,overestimate_bar]: for bar in bars: height = bar.get_height() plt.text(bar.get_x() + bar.get_width() / 2.0, height, f'{height:.1%}', ha='center', va='bottom', fontsize=9) # 折线图(只画准确率) plt.plot(ind- width, evaluation_df['Accuracy Rate'], marker='o', linestyle='-', color='green', label='Accuracy Line', linewidth=2, markersize=5) # 设置标题和坐标轴 plt.title('AQI Range Forecast Accuracy Evaluation', fontsize=16) plt.xlabel('Month', fontsize=12) plt.ylabel('Rate', fontsize=12) # x轴标签旋转 plt.xticks(ind, evaluation_df['YearMonth'], rotation=45) # ❗关键修改:将图例放在图表外部右侧,防止遮挡 plt.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0) # 自动调整布局,防止裁剪 plt.tight_layout() # 显示图形 plt.show()将一下信息带入以上代码# 创建一个DataFrame来排序测试数据(按日期) test_data = pd.DataFrame({ 'date': dates_test, 'true': y_test_original, 'pred': best_model_predictions }) # 按日期排序 test_data = test_data.sort_values('date') # 计算最后10%的数据点数量 n_last = int(len(test_data) * 0.1) if n_last < 5: # 确保至少有5个数据点 n_last = min(5, len(test_data)) # 获取最后10%的数据(按日期排序后的最后10%) last_dates = test_data['date'].values[-n_last:] last_true = test_data['true'].values[-n_last:] last_pred = test_data['pred'].values[-n_last:] 评估最后10%的数据的预测效果
11-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值