import os import pandas as pd from datetime import datetime import random import numpy as np from sklearn.model_selection import cross_val_score from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import GridSearchCV from sklearn.cluster import KMeans from sklearn.cluster import AgglomerativeClustering import matplotlib.pyplot as plt import joblib from gurobipy import * import warnings warnings.filterwarnings('ignore') # 系统参数设定 station_num=5 random.seed(10) soc=[0,1,2] trip_data = pd.read_csv(r"ebike_data/trip.csv") trip_data = trip_data.drop_duplicates(keep='last', inplace=False, ignore_index=True) station_data = pd.read_csv(r"ebike_data/station.csv") weather_data = pd.read_csv(r"ebike_data/weather.csv") weather_data = weather_data.loc[:, ['Date', 'Mean_Temperature_F', 'Mean_Humidity', 'Mean_Visibility_Miles', 'Mean_Wind_Speed_MPH', 'Precipitation_In']] weather_data['Date'] = pd.to_datetime(weather_data["Date"]).dt.strftime("%Y-%m-%d") # out_label = trip_data['from_station_name'] # in_label = trip_data['to_station_name'] # label = pd.concat([out_label, in_label]) # label_count = label.value_counts(sort=True) def clustering(n_clusters,station_data,plot): data=station_data.copy() data=data.drop(labels=["name"],axis=1) data=data.drop(labels=["install_date"], axis=1) data=data.drop(labels=["install_dockcount"],axis=1) data=data.drop(labels=["modification_date"],axis=1) data=data.drop(labels=["decommission_date"],axis=1) # data_2=data[(data['lat']<47.63) & (data['long']<-122.31)] # data_1=data[(data['lat']>=47.63) | (data['long']>=-122.31)] # i=0 # processed_data=[] # for data_i in [data_1,data_2]: coords = data[['long', 'lat']].values # 使用层次聚类方法进行初始聚类,为KMeans算法确定聚类中心 agglo = AgglomerativeClustering(n_clusters=n_clusters) initial_clusters = agglo.fit_predict(coords) # 计算每个簇的中心点 initial_cluster_centers = np.array([coords[initial_clusters == i].mean(axis=0) for i in range(n_clusters)]) # 使用计算得到的中心点作为KMeans算法的初始中心 kmeans = KMeans(n_clusters=n_clusters, init=initial_cluster_centers, n_init=1) data['cluster'] = kmeans.fit_predict(coords) # processed_data.append(data_i) # i=i+1 # data=pd.concat(processed_data) data.reset_index(drop=True, inplace=True) cluster_dict = data.set_index('station_id')['cluster'].to_dict() unique_clusters = np.unique(data['cluster']) if plot: plt.figure(figsize=(10, 8)) for cluster in unique_clusters: subset = data[data['cluster'] == cluster] plt.scatter(subset['long'], subset['lat'], label=f"Cluster {cluster}", s=100) # 标记聚类中心 plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=200, c='red', label='Centers', marker='*') plt.xlabel('Longitude') plt.ylabel('Latitude') # plt.title('KMeans 聚类结果') # plt.legend(title='Cluster') plt.grid(True) plt.savefig('cluster_5.png') plt.show() # 可视化 dock_dict={} for s in unique_clusters: dock=data.loc[(data['cluster']==s)]['current_dockcount'].sum() dock_dict[s]=dock long_dict={i:kmeans.cluster_centers_[i,0] for i in range(n_clusters) } lat_dict={i:kmeans.cluster_centers_[i,1] for i in range(n_clusters)} return cluster_dict,dock_dict,long_dict,lat_dict # station_list = label_count.keys()[:station_num].to_list() # station_dict = dict(zip(station_list, list(range(station_num)))) # trip_data = trip_data[ # (trip_data['from_station_name'].isin(station_list)) & (trip_data['to_station_name'].isin(station_list))] n_clusters=station_num cluster_dict,dock_dict,long_dict,lat_dict=clustering(n_clusters,station_data,plot=True) travel_data = trip_data.loc[:, ['starttime', 'stoptime', 'from_station_id', 'to_station_id']] travel_data['from_cluster'] = travel_data['from_station_id'].map(cluster_dict) travel_data['to_cluster'] = travel_data['to_station_id'].map(cluster_dict) # travel_data['day_of_week'] = trip_data["starttime"].apply(lambda x: datetime.strptime(x, "%m/%d/%Y %H:%M").isoweekday()) travel_data['start_hour'] = trip_data["starttime"].apply(lambda x: datetime.strptime(x, "%m/%d/%Y %H:%M").hour) travel_data['end_hour'] = trip_data["stoptime"].apply(lambda x: datetime.strptime(x, "%m/%d/%Y %H:%M").hour) travel_data['Date'] = pd.to_datetime(trip_data["starttime"]).dt.strftime("%Y-%m-%d") travel_data.to_csv(r"ebike_data/travel04.csv",index=False) rent_counts = pd.DataFrame(travel_data.groupby(["Date", 'start_hour', 'from_cluster'], as_index=False)["from_station_id"].count()) rent_counts = rent_counts.rename(columns={"from_station_id": "count","from_cluster":"cluster"}) rent_counts['cluster']=rent_counts['cluster'].astype(int) return_counts = pd.DataFrame(travel_data.groupby(["Date", "end_hour", "to_cluster"], as_index=False)["to_station_id"].count()) return_counts = return_counts.rename(columns={"to_station_id": "count","to_cluster":"cluster","end_hour":"start_hour"}) return_counts['cluster']=return_counts['cluster'].astype(int) data_1=rent_counts.loc[:,["Date", "start_hour"]] data_2=return_counts.loc[:,["Date", "start_hour"]] data=pd.concat([data_1,data_2]) # data['Date']=pd.to_datetime(data['Date']) data = data.drop_duplicates(keep='first', inplace=False, ignore_index=True) data = data.sort_values(axis=0, by=['Date','start_hour'], ascending=True) data.reset_index(drop=True, inplace=True) data['day_of_week'] = data["Date"].apply(lambda x: datetime.strptime(x, "%Y-%m-%d").isoweekday()) data = pd.merge(data, weather_data, on="Date") for i in range(station_num): data['{}_rent'.format(i)]=0 data['{}_return'.format(i)]=0 for e in soc: data['{}_dispatch_{}'.format(i,e)]=0 if e!=2: data['{}_exchange_{}'.format(i,e)]=0 data['{}_I_{}'.format(i,e)]=-1 from simulation_f import * data=fill_demand_data(data,rent_counts,'rent') data=fill_demand_data(data,return_counts,'return') data=data[(data['start_hour']>=8) &(data['start_hour']<=20)] data.reset_index(drop=True, inplace=True) length=len(data) for i in range(station_num): rent_array=np.random.randint(0,10,size=length) return_array=np.random.randint(0,10,size=length) data['{}_rent'.format(i)]=data['{}_rent'.format(i)]*10+rent_array.tolist() data['{}_return'.format(i)]=data['{}_return'.format(i)]*10+return_array.tolist() data.to_csv(r"ebike_data/origin_data_4.csv", index=False) # 运行simulation_f.py文件,生成训练数据 #如果参数改了,要改文件名 regressor = RandomForestRegressor(n_estimators=30,max_depth=60) def dataset_generate(dataset,test_size=0.2,random_state=0): data=dataset.copy() data=data.drop(labels=['Date','penalty_0','penalty_1'],axis=1) for s in range(station_num): data=data.drop(['{}_rent'.format(s),'{}_return'.format(s)], axis=1) # data=data.drop(['{}_pick'.format(s),'{}_put'.format(s),'{}_I'.format(s)], axis=1) # data=data.drop(['{}_dispatch'.format(s),'{}_I'.format(s)], axis=1) data.to_csv(r"ebike_data/train_data_4.csv",index=False) X = np.asarray(data.iloc[:, :-1]) y = np.asarray(data.iloc[:, -1]) x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=random_state) return x_train, x_test, y_train, y_test dataset=pd.read_csv(r"ebike_data/data04.csv") #跟simulation_f里的文件名对应 x_train, x_test, y_train, y_test=dataset_generate(dataset) regressor.fit(x_train, y_train) y_pred=regressor.predict(x_test) print("Training Score:%f" % regressor.score(x_train, y_train)) print("Testing Score:%f" % regressor.score(x_test, y_test)) # K折检验 param_grid = {"n_estimators":range(5,11,1)} #,"max_depth":[8,9,10] grid_search = GridSearchCV(RandomForestRegressor(),param_grid,cv = 3) grid_search.fit(x_train, y_train) # y_pred=grid_search.predict(x_test) # 拟合优度R2 print("r2:", grid_search.score(x_test, y_test)) # 用Scikit_learn计算MSE grid_search.set_params() print(grid_search.best_params_) path = r"ebike_data/regressor.model" joblib.dump(regressor, path) import gurobipy as gp model = gp.read('ebike_data/model04.mps') model.write('ebike_data/model04.lp')