ToB企服应用市场:ToB评测及商务社交产业平台

标题: LSTM实现天气模子练习与猜测 [打印本页]

作者: 嚴華    时间: 2024-12-28 04:35
标题: LSTM实现天气模子练习与猜测
要实现一个天气猜测的模子,并确保该模子可以反复举行练习和更新,先设计:
设计方案


详细实现

以下是设计后的方案和代码:
项目文件夹布局

  1. weather-prediction/
  2. ├── data/
  3. │   ├── raw/                  # 原始天气数据文件
  4. │   ├── processed/            # 预处理后的数据文件
  5. │   └── model/                # 存储训练好的模型
  6. ├── scripts/
  7. │   ├── download_weather_data.py   # 下载天气数据并保存为CSV
  8. │   ├── preprocess_data.py         # 数据预处理脚本
  9. │   ├── train_model.py            # 训练LSTM模型脚本
  10. │   ├── continue_training.py      # 持续训练脚本
  11. │   └── predict_weather.py        # 预测天气脚本
  12. ├── models/
  13. │   ├── weather_lstm_model.h5    # 保存的LSTM模型
  14. └── requirements.txt           # 项目依赖包
复制代码
详细步骤

1. 下载天气数据并保存到CSV文件(download_weather_data.py)

  1. import requests
  2. import pandas as pd
  3. import os
  4. from datetime import datetime
  5. # 下载天气数据
  6. def fetch_weather_data(api_key, city="Beijing"):
  7.     url = f"http://api.openweathermap.org/data/2.5/forecast?q={city}&appid={api_key}&units=metric"
  8.     response = requests.get(url)
  9.     data = response.json()
  10.     weather_data = []
  11.     for item in data['list']:
  12.         weather_data.append({
  13.             "datetime": item['dt_txt'],
  14.             "temperature": item['main']['temp'],
  15.             "humidity": item['main']['humidity'],
  16.             "pressure": item['main']['pressure'],
  17.             "wind_speed": item['wind']['speed'],
  18.             "rain": item.get('rain', {}).get('3h', 0)
  19.         })
  20.     df = pd.DataFrame(weather_data)
  21.     return df
  22. def save_weather_data_to_csv(df, filename="../data/raw/weather_data.csv"):
  23.     if not os.path.exists(os.path.dirname(filename)):
  24.         os.makedirs(os.path.dirname(filename))
  25.     df.to_csv(filename, index=False)
  26.     print(f"Weather data saved to {filename}")
  27. def main():
  28.     api_key = "your_openweather_api_key"
  29.     city = "Beijing"
  30.     df = fetch_weather_data(api_key, city)
  31.     save_weather_data_to_csv(df)
  32. if __name__ == "__main__":
  33.     main()
复制代码
2. 数据预处置惩罚脚本(preprocess_data.py)

  1. import pandas as pd
  2. from sklearn.preprocessing import StandardScaler
  3. import os
  4. def load_data(filename="../data/raw/weather_data.csv"):
  5.     df = pd.read_csv(filename)
  6.     df['datetime'] = pd.to_datetime(df['datetime'])
  7.     return df
  8. def preprocess_data(df):
  9.     # 时间特征处理
  10.     df['hour'] = df['datetime'].dt.hour
  11.     df['day'] = df['datetime'].dt.dayofweek
  12.     df['month'] = df['datetime'].dt.month
  13.     df['year'] = df['datetime'].dt.year
  14.     # 特征选择
  15.     features = ['temperature', 'humidity', 'pressure', 'wind_speed', 'rain', 'hour', 'day', 'month', 'year']
  16.     df = df[features]
  17.     # 标准化特征
  18.     scaler = StandardScaler()
  19.     df[features] = scaler.fit_transform(df[features])
  20.     return df, scaler
  21. def save_processed_data(df, filename="../data/processed/processed_weather_data.csv"):
  22.     df.to_csv(filename, index=False)
  23.     print(f"Processed data saved to {filename}")
  24. def main():
  25.     df = load_data()
  26.     processed_data, scaler = preprocess_data(df)
  27.     save_processed_data(processed_data)
  28.     return scaler
  29. if __name__ == "__main__":
  30.     main()
复制代码
3. 练习LSTM模子脚本(train_model.py)

  1. import pandas as pd
  2. import numpy as np
  3. import tensorflow as tf
  4. from tensorflow.keras.models import Sequential
  5. from tensorflow.keras.layers import LSTM, Dense, Dropout
  6. from sklearn.model_selection import train_test_split
  7. import os
  8. def load_processed_data(filename="../data/processed/processed_weather_data.csv"):
  9.     return pd.read_csv(filename)
  10. def prepare_lstm_data(df, time_steps=10):
  11.     X, y = [], []
  12.     for i in range(time_steps, len(df)):
  13.         X.append(df.iloc[i-time_steps:i, :-1].values)  # 选择过去的时间步作为特征
  14.         y.append(df.iloc[i, 0])  # 预测当前温度
  15.     X, y = np.array(X), np.array(y)
  16.     return X, y
  17. def create_lstm_model(input_shape):
  18.     model = Sequential([
  19.         LSTM(50, return_sequences=True, input_shape=input_shape),
  20.         Dropout(0.2),
  21.         LSTM(50, return_sequences=False),
  22.         Dropout(0.2),
  23.         Dense(1)
  24.     ])
  25.     model.compile(optimizer='adam', loss='mean_squared_error')
  26.     return model
  27. def train_model(X, y):
  28.     X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  29.     model = create_lstm_model((X_train.shape[1], X_train.shape[2]))
  30.     model.fit(X_train, y_train, epochs=20, batch_size=32, validation_data=(X_test, y_test))
  31.     return model
  32. def save_model(model, filename="../models/weather_lstm_model.h5"):
  33.     if not os.path.exists(os.path.dirname(filename)):
  34.         os.makedirs(os.path.dirname(filename))
  35.     model.save(filename)
  36.     print(f"Model saved to {filename}")
  37. def main():
  38.     df = load_processed_data()
  39.     X, y = prepare_lstm_data(df)
  40.     model = train_model(X, y)
  41.     save_model(model)
  42. if __name__ == "__main__":
  43.     main()
复制代码
4. 持续练习脚本(continue_training.py)

  1. import tensorflow as tf
  2. import pandas as pd
  3. from train_model import load_processed_data, prepare_lstm_data, create_lstm_model, save_model
  4. import os
  5. def load_model(filename="../models/weather_lstm_model.h5"):
  6.     return tf.keras.models.load_model(filename)
  7. def continue_training(model, df, time_steps=10):
  8.     X, y = prepare_lstm_data(df, time_steps)
  9.     model.fit(X, y, epochs=10, batch_size=32)
  10.     return model
  11. def main():
  12.     df = load_processed_data()
  13.     model = load_model()
  14.     updated_model = continue_training(model, df)
  15.     save_model(updated_model)
  16. if __name__ == "__main__":
  17.     main()
复制代码
5. 猜测天气脚本(predict_weather.py)

  1. import tensorflow as tf
  2. import pandas as pd
  3. from train_model import prepare_lstm_data
  4. def load_model(filename="../models/weather_lstm_model.h5"):
  5.     return tf.keras.models.load_model(filename)
  6. def predict_weather(model, df, time_steps=10):
  7.     X, _ = prepare_lstm_data(df, time_steps)
  8.     predictions = model.predict(X)
  9.     return predictions
  10. def main():
  11.     df = pd.read_csv("../data/processed/processed_weather_data.csv")
  12.     model = load_model()
  13.     predictions = predict_weather(model, df)
  14.     print(predictions)
  15. if __name__ == "__main__":
  16.     main()
复制代码
6. 依赖文件(requirements.txt)

  1. pandas
  2. numpy
  3. scikit-learn
  4. tensorflow
  5. requests
复制代码
代码说明

   没有谁生来就是优秀的人,你可以不优秀,但是不可以失去动力,不求上进,只会荒废一生。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4