DAY14 8.4

模拟赛
A:对每种宝石单独考虑,显然它的情况数先要乘上其他随便选的方案,即:2sum−ci2^{sum-c_i}2sumci。然后考虑同种宝石,发现是一个:
Cci1×vi+Cci2×vi2+...+Ccici×viciC_{c_i}^{1}\times v_i+C_{c_i}^{2}\times v_i^2+...+C_{c_i}^{c_i}\times v_i^{c_i}Cci1×vi+Cci

import sys import pandas as pd import numpy as np import csv # 读入数据 data = pd.read_csv('./train.csv', encoding='big5') # 数据预处理 data = data.iloc[:, 3:].copy() data[data == 'NR'] = 0 raw_data = data.to_numpy() # 按月分割数据 month_data = {} for month in range(12): sample = np.empty([18, 480]) for day in range(20): sample[:, day * 24 : (day + 1) * 24] = raw_data[18 * (20 * month + day) : 18 * (20 * month + day + 1), :] month_data[month] = sample # 分割x和y x = np.empty([12 * 471, 18 * 9], dtype=float) y = np.empty([12 * 471, 1], dtype=float) for month in range(12): for day in range(20): for hour in range(24): if day == 19 and hour > 14: continue x[month * 471 + day * 24 + hour, :] = month_data[month][:, day * 24 + hour : day * 24 + hour + 9].reshape(1, -1) y[month * 471 + day * 24 + hour, 0] = month_data[month][9, day * 24 + hour + 9] # value print(x) print(y) # 对x标准化 mean_x = np.mean(x, axis=0) # 18 * 9 std_x = np.std(x, axis=0) # 18 * 9 for i in range(len(x)): # 12 * 471 for j in range(len(x[0])): # 18 * 9 if std_x[j] != 0: x[i][j] = (x[i][j] - mean_x[j]) / std_x[j] # 训练模型并保存权重 dim = 18 * 9 + 1 w = np.zeros([dim, 1]) x2 = np.concatenate((np.ones([12 * 471, 1]), x), axis=1).astype(float) learning_rate = 2 iter_time = 10000 adagrad = np.zeros([dim, 1]) eps = 1e-7 for t in range(iter_time): loss = np.sqrt(np.sum(np.power(np.dot(x2, w) - y, 2)) / 471 / 12) # mse if (t % 100 == 0): print(str(t) + ":" + str(loss)) gradient = 2 * np.dot(x2.transpose(), np.dot(x2, w) - y) # dim*1 adagrad += gradient ** 2 w = w - learning_rate * gradient / (np.sqrt(adagrad) + eps) np.save(file='weight.npy', arr=w) # 导入测试数据test.csv testdata = pd.read_csv('./test.csv', header=None, encoding='big5') test_data = testdata.iloc[:, 2:].copy() test_data[test_data == 'NR'] = 0 test_data = test_data.to_numpy() test_x = np.empty([240, 18 * 9], dtype=float) for i in range(240): test_x[i, :] = test_data[18 * i : 18 * (i + 1), :].reshape(1, -1) for i in range(len(test_x)): for j in range(len(test_x[0])): if std_x[j] != 0: test_x[i][j] = (test_x[i][j] - mean_x[j]) / std_x[j] test_x = np.concatenate((np.ones([240, 1]), test_x), axis=1).astype(float) # 对test的x进行预测,得到预测值ans_y w = np.load('weight.npy') ans_y = np.dot(test_x, w) # 加上一个预处理<0的都变成0 for i in range(240): if (ans_y[i][0] < 0): ans_y[i][0] = 0 else: ans_y[i][0] = np.round(ans_y[i][0]) with open('submit.csv', mode='w', newline='') as submit_file: csv_writer = csv.writer(submit_file) header = ['id', 'value'] print(header) csv_writer.writerow(header) for i in range(240): row = ['id_' + str(i), ans_y[i][0]] csv_writer.writerow(row) print(row)添加功能,简单一点的
12-10
```markdown # 代码概述 该代码是一个基于线性回归的空气质量预测模型,使用历史 PM2.5 相关数据进行训练,并对测试集进行预测。主要流程包括:数据读取、预处理、特征构建、标准化、模型训练(采用 Adagrad 优化)、预测与结果保存。 目标是根据前9小时的18项环境参数,预测下一小时的 PM2.5 值。 --- # 代码解析 1. **数据加载与清洗** ```python data = pd.read_csv('./train.csv', encoding='big5') data = data.iloc[:, 3:].copy() data[data == 'NR'] = 0 raw_data = data.to_numpy() ``` - 读取训练数据,跳过前3列(日期等非数值信息)。 - 将非数值 `'NR'` 替换为 `0`,便于数值计算。 2. **按月整理数据** ```python for month in range(12): sample = np.empty([18, 480]) for day in range(20): sample[:, day * 24 : (day + 1) * 24] = raw_data[18 * (20 * month + day) : 18 * (20 * month + day + 1), :] month_data[month] = sample ``` - 每月有20天数据,每天24小时,共480小时。 - 每个样本包含18种污染物/气象因素(如PM2.5、湿度等)。 3. **构造输入输出对 `(x, y)`** ```python x = np.empty([12 * 471, 18 * 9], dtype=float) y = np.empty([12 * 471, 1], dtype=float) ``` - 使用过去9小时的数据作为输入(`18*9` 维),预测第10小时的PM2.5值(即索引9对应PM2.5)。 - 总样本数:每月 `20×24 - 9 = 471` 个序列,共 `12×471=5652` 个样本。 4. **特征标准化** ```python mean_x = np.mean(x, axis=0) std_x = np.std(x, axis=0) x[i][j] = (x[i][j] - mean_x[j]) / std_x[j] ``` - 对每个特征维度做零均值标准化,提升训练稳定性。 5. **模型训练(带Adagrad的线性回归)** ```python w = np.zeros([dim, 1]) x2 = np.concatenate((np.ones([12 * 471, 1]), x), axis=1) ``` - 添加偏置项(bias),使用梯度下降配合Adagrad自适应学习率更新权重。 - 损失函数为 RMSE,迭代10000次。 6. **测试集预测** ```python testdata = pd.read_csv('./test.csv', header=None, encoding='big5') test_x = test_data[18 * i : 18 * (i + 1), :].reshape(1, -1) ``` - 处理测试数据,同样标准化后拼接全1列用于偏置。 - 预测并限制负值为0,最后四舍五入。 7. **保存结果** ```python with open('submit.csv', mode='w', newline='') as submit_file: csv_writer.writerow(['id', 'value']) for i in range(240): csv_writer.writerow(['id_' + str(i), ans_y[i][0]]) ``` --- # 新增功能建议(简单易实现) **功能:在控制台输出训练损失变化趋势图(ASCII风格)** ```python # 在训练循环中添加以下代码: loss_history = [] # 记录每100次迭代的损失 for t in range(iter_time): loss = np.sqrt(np.sum(np.power(np.dot(x2, w) - y, 2)) / 471 / 12) loss_history.append(loss) if (t % 100 == 0): print(f"{t}: {loss:.4f}") # 训练结束后打印简易ASCII图表 print("\nLoss Trend (ASCII):") max_loss = max(loss_history) min_loss = min(loss_history) for i, loss in enumerate(loss_history[::100]): # 每100次显示一次 bar = "#" * int((loss - min_loss) * 40 / (max_loss - min_loss + 1e-7)) print(f"{i*100:6d}: {loss:<8.4f} |{bar}") ``` > ✅ **优点**:无需额外库,直观展示收敛过程,适合调试。 --- # 知识点 - **线性回归与梯度下降**:通过最小化预测误差调整权重,使用一阶优化方法逼近最优解。 - **Adagrad优化算法**:自适应调节各参数学习率,解决稀疏梯度问题,防止震荡。 - **数据标准化**:使不同量纲特征处于相近范围,加快收敛速度,提高模型稳定性。 ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值