赞
踩
''' 数据集:年月日,星期,前两天的温度,前一天的温度,历史平均温度,实际温度值, ''' import numpy as np import numpy as py import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.python.keras import layers import tensorflow.python.keras import datetime from sklearn import preprocessing import warnings warnings.filterwarnings("ignore") #matplotlib inline #读数据 features=pd.read_csv("./temps0.csv") #展示数据的样子(数据集的维度348*9) # print(features.head()) #处理时间数据,得到年月日 years=features['year'] months=features['month'] days=features['day'] #将年月日数据转为datatime格式(年-月-日) dates=[str(int(year))+'-'+str(int(month))+'-'+str(int(day)) for year,month,day in zip(years,months,days)] dates=[datetime.datetime.strptime(date,'%Y-%m-%d') for date in dates] #数据展示 #指定默认风格 plt.style.use("fivethirtyeight") #设置布局 fig,((ax1,ax2),(ax3,ax4))=plt.subplots(nrows=2,ncols=2,figsize=(10,10)) fig.autofmt_xdate(rotation=45) #标签值 ax1.plot(dates,features["actual"]) ax1.set_xlabel('');ax1.set_ylabel('temperature');ax1.set_title('Max temp') #昨天 ax2.plot(dates,features["actual"]) ax2.set_xlabel('');ax2.set_ylabel('temperature');ax2.set_title('Previous Max temp') #前天 ax3.plot(dates,features["actual"]) ax3.set_xlabel('');ax3.set_ylabel('temperature');ax3.set_title('Two Days Prior Max temp') #我的逗逼朋友 ax4.plot(dates,features["actual"]) ax4.set_xlabel('');ax4.set_ylabel('temperature');ax4.set_title('Friend') plt.tight_layout(pad=2) #plt.show() #one-hot编码,将特征值用【1,0,0,0....】的形式表示 features=pd.get_dummies(features) #print(features.head(6)) #提取实际温度作为标签,随后将实际温度从数据中剔除 labels=np.array(features['actual']) features=features.drop('actual',axis=1) #保存名字,以防万一 features_colname=list(features.columns) #转换数据类型格式 featurs=np.array(features) #对数据进行归一化预处理 input_features=preprocessing.StandardScaler().fit_transform(featurs) #使用keras构建模型 model=tf.keras.Sequential()#构建序列模型 ''' 未改变初始化 model.add(layers.Dense(16))#全连接层tf.keras.layers.Dense(神经元个数) model.add(layers.Dense(32)) model.add(layers.Dense(1)) ''' #更改初始化方法后效果,加入正则化处罚 model.add(layers.Dense(64,kernel_initializer='random_normal',kernel_regularizer=tf.keras.regularizers.l2(0.03))) model.add(layers.Dense(32,kernel_initializer='random_normal',kernel_regularizer=tf.keras.regularizers.l2(0.03))) model.add(layers.Dense(1,kernel_initializer='random_normal',kernel_regularizer=tf.keras.regularizers.l2(0.03))) ##model.compile()方法用于在配置训练方法时,告知训练时用的优化器、损失函数和准确率评测标准;optimizer = 优化器,loss = 损失函数,metrics = ["准确率”] model.compile(optimizer=tf.keras.optimizers.SGD(0.001),loss='mean_squared_error') model.fit(input_features,labels,validation_split=0.25,epochs=100,batch_size=64) #model.summary()输出模型各层的参数状况 model.summary() #预测结果 prediction=model.predict(input_features) #print(predict) #测试结果显示 true_data=pd.DataFrame(data={'date':dates,'actual':labels}) test_data=dates predict_data=pd.DataFrame(data={'date':test_data,'prediction':prediction.reshape(-1)}) plt.plot(true_data['date'],true_data['actual'],'b-',label='actual') plt.plot(predict_data['date'],predict_data['prediction'],'ro',label='prediction') plt.xticks(rotation='60') plt.legend() plt.xlabel("date");plt.ylabel('Maximum Temperture(F)');plt.title('Actuak and Predict') plt.show()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。