date_history = pd.DataFrame(data_integrity.iloc[:, 0]) dataset_history = pd.DataFrame(data_integrity.iloc[:, 1]) # 数据划分完,数据格式转换 dataset_history = [each[0] for each in np.array(dataset_history.iloc[:, [0]]).tolist()] # 历史数据 data_history_conversion = [{i: dataset_history[i * 96:96 * (i + 1)]} for i in range(int(len(dataset_history) / 96))] # 历史数据转化 data_pre = [each for each in np.array(dataset_pre).tolist()] # 预测所需要的今日数据 data_pre_conversion = np.array([float(item) for item in data_pre[0:96]]) # 预测所需要的今日数据的格式转化 代码优化

时间: 2024-01-14 10:04:51 浏览: 30
可以将第一行和第二行合并,即: ``` date_history = pd.DataFrame(data_integrity.iloc[:, 0]) dataset_history = [each[0] for each in np.array(data_integrity.iloc[:, 1]).tolist()] ``` 第三行可以使用列表推导式简化,即: ``` data_history_conversion = [{i: dataset_history[i * 96:96 * (i + 1)]} for i in range(len(dataset_history) // 96)] ``` 第四行可以直接将`dataset_pre`转换为`numpy array`,即: ``` data_pre_conversion = np.array(dataset_pre[0:96], dtype=float) ``` 这样就可以避免使用`for`循环了。
相关问题

date_history = pd.DataFrame(data_integrity.iloc[:, 0]) dataset_history = pd.DataFrame(data_integrity.iloc[:, 1]) # 数据划分完,数据格式转换 dataset_history = [each[0] for each in np.array(dataset_history.iloc[:, [0]]).tolist()] # 历史数据 data_history_conversion = [{i: dataset_history[i * 96:96 * (i + 1)]} for i in range(int(len(dataset_history) / 96))] # 历史数据转化 data_pre = [each for each in np.array(dataset_pre).tolist()] # 预测所需要的今日数据 data_pre_conversion = np.array([float(item) for item in data_pre[0:96]]) # 预测所需要的今日数据的格式转化 代码优化

以下是对代码的优化: ```python date_history = pd.DataFrame(data_integrity.iloc[:, 0]) dataset_history = pd.DataFrame(data_integrity.iloc[:, 1]) # 数据划分完,数据格式转换 dataset_history = dataset_history.iloc[:, 0].tolist() # 历史数据 data_history_conversion = [dict(enumerate(dataset_history[i * 96:96 * (i + 1)])) for i in range(len(dataset_history) // 96)] # 历史数据转化 data_pre = np.array(dataset_pre).flatten().astype(float) # 预测所需要的今日数据 ``` 主要优化点有: 1. `dataset_history` 可以直接使用 `tolist()` 方法转换为列表,不需要使用 `np.array` 和 `iloc` 索引。 2. `data_history_conversion` 可以使用 `enumerate` 函数代替手动计算索引,可以使代码更加简洁。 3. `data_pre` 可以使用 `flatten()` 方法将多维数组转换为一维数组,并使用 `astype(float)` 方法将字符串转换为浮点数。

time_new_list= data_integrity.iloc[-1, 0] minutes = int(time_new_list.minute) + int(time_new_list.hour) * 60 interval_length = ((minutes / 15) + 1) if interval_length == 96: dataset_pre = data_integrity.load.tail(int(interval_length)) else: dataset_pre = (data_integrity.load[:-int(interval_length)]).tail(96) date_history = pd.DataFrame(data_integrity.iloc[:, 0]) dataset_history = pd.DataFrame(data_integrity.iloc[:, 1]) # 数据划分完,数据格式转换 dataset_history = [each[0] for each in np.array(dataset_history.iloc[:, [0]]).tolist()] # 历史数据 data_history_conversion = [{i: dataset_history[i * 96:96 * (i + 1)]} for i in range(int(len(dataset_history) / 96))] # 历史数据转化 data_pre = [each for each in np.array(dataset_pre).tolist()] # 预测所需要的今日数据 data_pre_conversion = np.array([float(item) for item in data_pre[0:96]]) # 预测所需要的今日数据的格式转化 代码优化

以下是代码优化后的版本: ``` # 计算时间间隔 time_new_list = data_integrity.iloc[-1, 0] minutes = time_new_list.minute + time_new_list.hour * 60 interval_length = (minutes // 15) + 1 # 获取预测数据集 if interval_length == 96: dataset_pre = data_integrity.load.tail(interval_length) else: dataset_pre = data_integrity.load[:-interval_length].tail(96) # 获取历史数据集 date_history = data_integrity.iloc[:, 0] dataset_history = data_integrity.iloc[:, 1].iloc[:, 0].tolist() # 将历史数据转换为字典格式 data_history_conversion = [ {i: dataset_history[i * 96 : 96 * (i + 1)]} for i in range(len(dataset_history) // 96) ] # 获取预测所需要的今日数据 data_pre = dataset_pre.values.tolist() data_pre_conversion = np.array(data_pre[0:96], dtype=float) ``` 优化后的代码主要做了以下几个方面的改进: 1. 使用了整除符号 "//" 来计算时间间隔,避免了使用 int() 函数进行类型转换。 2. 使用了 pandas 库的 tail() 函数来获取最后几行数据,使代码更加简洁。 3. 将历史数据集的转换方式改为了使用列表推导式,避免了使用 for 循环。 4. 使用了 numpy 库的 array 函数来将预测数据转换为数组格式,避免了使用列表推导式和 for 循环。同时,指定了数组的数据类型为 float,避免了使用 float() 函数进行类型转换。

相关推荐

import pandas as pd import math as mt import numpy as np from sklearn.model_selection import train_test_split from Recommenders import SVDRecommender triplet_dataset_sub_song_merged = triplet_dataset_sub_song_mergedpd triplet_dataset_sub_song_merged_sum_df = triplet_dataset_sub_song_merged[['user','listen_count']].groupby('user').sum().reset_index() triplet_dataset_sub_song_merged_sum_df.rename(columns={'listen_count':'total_listen_count'},inplace=True) triplet_dataset_sub_song_merged = pd.merge(triplet_dataset_sub_song_merged,triplet_dataset_sub_song_merged_sum_df) triplet_dataset_sub_song_merged['fractional_play_count'] = triplet_dataset_sub_song_merged['listen_count']/triplet_dataset_sub_song_merged small_set = triplet_dataset_sub_song_merged user_codes = small_set.user.drop_duplicates().reset_index() song_codes = small_set.song.drop_duplicates().reset_index() user_codes.rename(columns={'index':'user_index'}, inplace=True) song_codes.rename(columns={'index':'song_index'}, inplace=True) song_codes['so_index_value'] = list(song_codes.index) user_codes['us_index_value'] = list(user_codes.index) small_set = pd.merge(small_set,song_codes,how='left') small_set = pd.merge(small_set,user_codes,how='left') mat_candidate = small_set[['us_index_value','so_index_value','fractional_play_count']] data_array = mat_candidate.fractional_play_count.values row_array = mat_candidate.us_index_value.values col_array = mat_candidate.so_index_value.values data_sparse = coo_matrix((data_array, (row_array, col_array)),dtype=float) K=50 urm = data_sparse MAX_PID = urm.shape[1] MAX_UID = urm.shape[0] recommender = SVDRecommender(K) U, S, Vt = recommender.fit(urm) Compute recommendations for test users uTest = [1,6,7,8,23] uTest_recommended_items = recommender.recommend(uTest, urm, 10) Output recommended songs in a dataframe recommendations = pd.DataFrame(columns=['user','song', 'score','rank']) for user in uTest: rank = 1 for song_index in uTest_recommended_items[user, 0:10]: song = small_set.loc[small_set['so_index_value'] == song_index].iloc[0] # Get song details recommendations = recommendations.append({'user': user, 'song': song['title'], 'score': song['fractional_play_count'], 'rank': rank}, ignore_index=True) rank += 1 display(recommendations)这段代码报错了,为什么?给出修改后的 代码

代码改进:import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt from sklearn.datasets import make_blobs def distEclud(arrA,arrB): #欧氏距离 d = arrA - arrB dist = np.sum(np.power(d,2),axis=1) #差的平方的和 return dist def randCent(dataSet,k): #寻找质心 n = dataSet.shape[1] #列数 data_min = dataSet.min() data_max = dataSet.max() #生成k行n列处于data_min到data_max的质心 data_cent = np.random.uniform(data_min,data_max,(k,n)) return data_cent def kMeans(dataSet,k,distMeans = distEclud, createCent = randCent): x,y = make_blobs(centers=100)#生成k质心的数据 x = pd.DataFrame(x) m,n = dataSet.shape centroids = createCent(dataSet,k) #初始化质心,k即为初始化质心的总个数 clusterAssment = np.zeros((m,3)) #初始化容器 clusterAssment[:,0] = np.inf #第一列设置为无穷大 clusterAssment[:,1:3] = -1 #第二列放本次迭代点的簇编号,第三列存放上次迭代点的簇编号 result_set = pd.concat([pd.DataFrame(dataSet), pd.DataFrame(clusterAssment)],axis = 1,ignore_index = True) #将数据进行拼接,横向拼接,即将该容器放在数据集后面 clusterChanged = True while clusterChanged: clusterChanged = False for i in range(m): dist = distMeans(dataSet.iloc[i,:n].values,centroids) #计算点到质心的距离(即每个值到质心的差的平方和) result_set.iloc[i,n] = dist.min() #放入距离的最小值 result_set.iloc[i,n+1] = np.where(dist == dist.min())[0] #放入距离最小值的质心标号 clusterChanged = not (result_set.iloc[:,-1] == result_set.iloc[:,-2]).all() if clusterChanged: cent_df = result_set.groupby(n+1).mean() #按照当前迭代的数据集的分类,进行计算每一类中各个属性的平均值 centroids = cent_df.iloc[:,:n].values #当前质心 result_set.iloc[:,-1] = result_set.iloc[:,-2] #本次质心放到最后一列里 return centroids, result_set x = np.random.randint(0,100,size=100) y = np.random.randint(0,100,size=100) randintnum=pd.concat([pd.DataFrame(x), pd.DataFrame(y)],axis = 1,ignore_index = True) #randintnum_test, randintnum_test = kMeans(randintnum,3) #plt.scatter(randintnum_test.iloc[:,0],randintnum_test.iloc[:,1],c=randintnum_test.iloc[:,-1]) #result_test,cent_test = kMeans(data, 4) cent_test,result_test = kMeans(randintnum, 3) plt.scatter(result_test.iloc[:,0],result_test.iloc[:,1],c=result_test.iloc[:,-1]) plt.scatter(cent_test[:,0],cent_test[:,1],color = 'red',marker = 'x',s=100)

param = {'num_leaves': 31, 'min_data_in_leaf': 20, 'objective': 'binary', 'learning_rate': 0.06, "boosting": "gbdt", "metric": 'None', "verbosity": -1} trn_data = lgb.Dataset(trn, trn_label) val_data = lgb.Dataset(val, val_label) num_round = 666 # clf = lgb.train(param, trn_data, num_round, valid_sets=[trn_data, val_data], verbose_eval=100, # early_stopping_rounds=300, feval=win_score_eval) clf = lgb.train(param, trn_data, num_round) # oof_lgb = clf.predict(val, num_iteration=clf.best_iteration) test_lgb = clf.predict(test, num_iteration=clf.best_iteration)thresh_hold = 0.5 oof_test_final = test_lgb >= thresh_hold print(metrics.accuracy_score(test_label, oof_test_final)) print(metrics.confusion_matrix(test_label, oof_test_final)) tp = np.sum(((oof_test_final == 1) & (test_label == 1))) pp = np.sum(oof_test_final == 1) print('accuracy1:%.3f'% (tp/(pp)))test_postive_idx = np.argwhere(oof_test_final == True).reshape(-1) # test_postive_idx = list(range(len(oof_test_final))) test_all_idx = np.argwhere(np.array(test_data_idx)).reshape(-1) stock_info['trade_date_id'] = stock_info['trade_date'].map(date_map) stock_info['trade_date_id'] = stock_info['trade_date_id'] + 1tmp_col = ['ts_code', 'trade_date', 'trade_date_id', 'open', 'high', 'low', 'close', 'ma5', 'ma13', 'ma21', 'label_final', 'name'] stock_info.iloc[test_all_idx[test_postive_idx]] tmp_df = stock_info[tmp_col].iloc[test_all_idx[test_postive_idx]].reset_index() tmp_df['label_prob'] = test_lgb[test_postive_idx] tmp_df['is_limit_up'] = tmp_df['close'] == tmp_df['high'] buy_df = tmp_df[(tmp_df['is_limit_up']==False)].reset_index() buy_df.drop(['index', 'level_0'], axis=1, inplace=True)buy_df['buy_flag'] = 1 stock_info_copy['sell_flag'] = 0tmp_idx = (index_df['trade_date'] == test_date_min+1) close1 = index_df[tmp_idx]['close'].values[0] test_date_max = 20220829 tmp_idx = (index_df['trade_date'] == test_date_max) close2 = index_df[tmp_idx]['close'].values[0]tmp_idx = (stock_info_copy['trade_date'] >= test_date_min) & (stock_info_copy['trade_date'] <= test_date_max) tmp_df = stock_info_copy[tmp_idx].reset_index(drop=True)from imp import reload import Account reload(Account) money_init = 200000 account = Account.Account(money_init, max_hold_period=20, stop_loss_rate=-0.07, stop_profit_rate=0.12) account.BackTest(buy_df, tmp_df, index_df, buy_price='open')tmp_df2 = buy_df[['ts_code', 'trade_date', 'label_prob', 'label_final']] tmp_df2 = tmp_df2.rename(columns={'trade_date':'buy_date'}) tmp_df = account.info tmp_df['buy_date'] = tmp_df['buy_date'].apply(lambda x: int(x)) tmp_df = tmp_df.merge(tmp_df2, on=['ts_code', 'buy_date'], how='left')最终的tmp_df是什么?tmp_df[tmp_df['label_final']==1]又选取了什么股票?

# seeds = [2222, 5, 4, 2, 209, 4096, 2048, 1024, 2015, 1015, 820]#11 seeds = [2]#2 num_model_seed = 1 oof = np.zeros(X_train.shape[0]) prediction = np.zeros(X_test.shape[0]) feat_imp_df = pd.DataFrame({'feats': feature_name, 'imp': 0}) parameters = { 'learning_rate': 0.008, 'boosting_type': 'gbdt', 'objective': 'binary', 'metric': 'auc', 'num_leaves': 63, 'feature_fraction': 0.8,#原来0.8 'bagging_fraction': 0.8, 'bagging_freq': 5,#5 'seed': 2, 'bagging_seed': 1, 'feature_fraction_seed': 7, 'min_data_in_leaf': 20, 'verbose': -1, 'n_jobs':4 } fold = 5 for model_seed in range(num_model_seed): print(seeds[model_seed],"--------------------------------------------------------------------------------------------") oof_cat = np.zeros(X_train.shape[0]) prediction_cat = np.zeros(X_test.shape[0]) skf = StratifiedKFold(n_splits=fold, random_state=seeds[model_seed], shuffle=True) for index, (train_index, test_index) in enumerate(skf.split(X_train, y)): train_x, test_x, train_y, test_y = X_train[feature_name].iloc[train_index], X_train[feature_name].iloc[test_index], y.iloc[train_index], y.iloc[test_index] dtrain = lgb.Dataset(train_x, label=train_y) dval = lgb.Dataset(test_x, label=test_y) lgb_model = lgb.train( parameters, dtrain, num_boost_round=10000, valid_sets=[dval], early_stopping_rounds=100, verbose_eval=100, ) oof_cat[test_index] += lgb_model.predict(test_x,num_iteration=lgb_model.best_iteration) prediction_cat += lgb_model.predict(X_test,num_iteration=lgb_model.best_iteration) / fold feat_imp_df['imp'] += lgb_model.feature_importance() del train_x del test_x del train_y del test_y del lgb_model oof += oof_cat / num_model_seed prediction += prediction_cat / num_model_seed gc.collect()解释上面的python代码

最新推荐

recommend-type

Macbook录屏软件,KAP,开源免费

Macbook上免费的,最简单好用的,干净清洁的,不占资源的录屏软件。 从某度上搜索“Macbook录屏软件”,前几页全部都是各种各样的收费软件 再从某度上搜索“Macbook 免费录屏软件”,还是会出现各种各样的收费软件推荐,然后会有OBS studio。obs也挺好的,不过osb操作有点复杂,对于只需要简单录屏来说,根本用不到obs stidio。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB图像处理算法宝典:从理论到实战

![MATLAB图像处理算法宝典:从理论到实战](https://img-blog.csdnimg.cn/20200717112736401.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2d1emhhbzk5MDE=,size_16,color_FFFFFF,t_70) # 1. MATLAB图像处理基础理论 MATLAB图像处理是一种利用MATLAB编程语言进行图像处理的强大工具。它提供了丰富的函数和工具箱,用于图像获取、增强、分
recommend-type

matlab中1/x的非线性规划

在MATLAB中,可以使用非线性规划函数(`fmincon`)来优化一个包含1/x的非线性目标函数。下面是一个简单的例子: ```matlab % 定义目标函数 fun = @(x) 1/x; % 定义约束函数(这里没有约束) nonlcon = []; % 定义初始点 x0 = 1; % 定义优化选项 options = optimoptions('fmincon', 'Display', 'iter'); % 进行非线性规划 [x, fval] = fmincon(fun, x0, [], [], [], [], [], [], nonlcon, options); ``` 在
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

MATLAB数据可视化黑科技:洞悉数据背后的秘密

![MATLAB数据可视化黑科技:洞悉数据背后的秘密](https://img-blog.csdnimg.cn/img_convert/1a36558cefc0339f7836cca7680c0aef.png) # 1. MATLAB数据可视化的基本原理 MATLAB数据可视化是一种将数据转化为图形表示形式的技术,以帮助人们理解和分析数据。其基本原理包括: - **数据表示:**将原始数据转换为图形元素,如点、线和条形。 - **图形布局:**确定图形元素在绘图区域中的位置和大小。 - **图形美化:**添加标题、标签、颜色和纹理等元素,以增强图形的可读性和美观性。 - **交互性:**允
recommend-type

优化算法计算单位面积年平均输出热功率的代码

计算单位面积年平均输出热功率的代码具体情况取决于你所要解决的问题和需要的数据。然而,我可以给你一个通用的优化算法的框架,你可以根据具体情况进行调整。 首先,你需要明确计算单位面积年平均输出热功率的数学公式或算法。假设你已经有了计算热功率的函数 `calculate_power`,它接受一些输入参数,并返回热功率值。 下面是一个示例的优化算法框架,以最大化单位面积年平均输出热功率为目标: ```python import random def objective_function(params): # 这个函数用于计算目标函数的值 # 根据具体情况,你需要将 params
recommend-type

c++校园超市商品信息管理系统课程设计说明书(含源代码) (2).pdf

校园超市商品信息管理系统课程设计旨在帮助学生深入理解程序设计的基础知识,同时锻炼他们的实际操作能力。通过设计和实现一个校园超市商品信息管理系统,学生掌握了如何利用计算机科学与技术知识解决实际问题的能力。在课程设计过程中,学生需要对超市商品和销售员的关系进行有效管理,使系统功能更全面、实用,从而提高用户体验和便利性。 学生在课程设计过程中展现了积极的学习态度和纪律,没有缺勤情况,演示过程流畅且作品具有很强的使用价值。设计报告完整详细,展现了对问题的深入思考和解决能力。在答辩环节中,学生能够自信地回答问题,展示出扎实的专业知识和逻辑思维能力。教师对学生的表现予以肯定,认为学生在课程设计中表现出色,值得称赞。 整个课程设计过程包括平时成绩、报告成绩和演示与答辩成绩三个部分,其中平时表现占比20%,报告成绩占比40%,演示与答辩成绩占比40%。通过这三个部分的综合评定,最终为学生总成绩提供参考。总评分以百分制计算,全面评估学生在课程设计中的各项表现,最终为学生提供综合评价和反馈意见。 通过校园超市商品信息管理系统课程设计,学生不仅提升了对程序设计基础知识的理解与应用能力,同时也增强了团队协作和沟通能力。这一过程旨在培养学生综合运用技术解决问题的能力,为其未来的专业发展打下坚实基础。学生在进行校园超市商品信息管理系统课程设计过程中,不仅获得了理论知识的提升,同时也锻炼了实践能力和创新思维,为其未来的职业发展奠定了坚实基础。 校园超市商品信息管理系统课程设计的目的在于促进学生对程序设计基础知识的深入理解与掌握,同时培养学生解决实际问题的能力。通过对系统功能和用户需求的全面考量,学生设计了一个实用、高效的校园超市商品信息管理系统,为用户提供了更便捷、更高效的管理和使用体验。 综上所述,校园超市商品信息管理系统课程设计是一项旨在提升学生综合能力和实践技能的重要教学活动。通过此次设计,学生不仅深化了对程序设计基础知识的理解,还培养了解决实际问题的能力和团队合作精神。这一过程将为学生未来的专业发展提供坚实基础,使其在实际工作中能够胜任更多挑战。