'''
数据集:年月日,星期,前两天的温度,前一天的温度,历史平均温度,实际温度值,
'''
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")
features=pd.read_csv("./temps0.csv")
years=features['year']
months=features['month']
days=features['day']
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)
features=pd.get_dummies(features)
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)
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=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()
prediction=model.predict(input_features)
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()