tensorflow学习---气温预测练习代码

本文探讨了如何通过TensorFlow的Keras库,结合历史气温数据(包括前两天、前一天及历史平均温度),构建并训练一个深度学习模型来预测实际温度。作者展示了数据预处理、特征工程、模型构建与训练过程,最终可视化预测结果与实际数据对比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

'''
数据集:年月日,星期,前两天的温度,前一天的温度,历史平均温度,实际温度值,
'''
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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值