这是一个使用Python实现线性回归模型预测未来一天天气和温度的程序,并提供GUI界面、Excel数据导入和样例表格下载功能。

功能介绍

  • 使用Tkinter库构建GUI界面,包括:
    • 标题和说明文字
    • 输入框和标签,用于输入Excel文件路径和日期
    • 下载按钮,用于下载样例Excel表格
    • 预测按钮,用于读取Excel数据、进行预处理、训练模型并预测未来一天的天气和温度
    • 显示框,用于显示预测结果
  • 使用pandas库读取Excel文件数据,进行预处理:
    • 提取所需的列,包括日期、天气和温度
    • 将日期转换为Python中的日期对象
    • 将天气和温度进行数值化,例如将'晴天'、'阴天'、'大雨'、'下雨'、'雾'分别转换为0、1、2、3、4,将温度区间离散化为0、1、2、3、4等级
  • 使用sklearn库构建线性回归模型,并使用训练数据进行模型训练。
  • 使用训练好的模型对用户输入的日期进行预测,得到未来一天的天气和温度,并进行反向转换,将数值化的天气和温度转换为对应的字符串和区间范围。
  • 提供样例Excel表格生成和下载功能,方便用户使用。

代码框架

import tkinter as tk
import pandas as pd
from sklearn.linear_model import LinearRegression
from datetime import datetime
import os.path
import requests

class WeatherPredictor:
    def __init__(self, master):
        self.master = master
        master.title("Weather Predictor")

        # 标题和说明文字
        self.title_label = tk.Label(master, text="Weather Predictor", font=("Arial", 24))
        self.title_label.pack(pady=10)
        self.desc_label = tk.Label(master, text="Input the path of the Excel file and the date you want to predict.", font=("Arial", 12))
        self.desc_label.pack()

        # 输入框和标签
        self.path_label = tk.Label(master, text="Excel file path:")
        self.path_label.pack()
        self.path_entry = tk.Entry(master)
        self.path_entry.pack()
        self.date_label = tk.Label(master, text="Prediction date (YYYY-MM-DD):")
        self.date_label.pack()
        self.date_entry = tk.Entry(master)
        self.date_entry.pack()

        # 下载按钮
        self.download_button = tk.Button(master, text="Download sample Excel file", command=self.download_sample)
        self.download_button.pack(pady=10)

        # 预测按钮
        self.predict_button = tk.Button(master, text="Predict", command=self.predict)
        self.predict_button.pack(pady=10)

        # 显示框
        self.result_label = tk.Label(master, text="", font=("Arial", 18))
        self.result_label.pack(pady=20)

    def download_sample(self):
        url = "https://example.com/sample.xlsx"  # 样例Excel文件的下载链接
        filename = "sample.xlsx"  # 下载后保存的文件名
        response = requests.get(url)
        with open(filename, "wb") as f:
            f.write(response.content)
        tk.messagebox.showinfo("Download", "Sample Excel file has been downloaded.")

    def predict(self):
        # 读取路径和日期,检查是否合法
        path = self.path_entry.get()
        if not os.path.isfile(path):
            tk.messagebox.showerror("Error", "Invalid Excel file path.")
            return
        date_str = self.date_entry.get()
        try:
            date = datetime.strptime(date_str, "%Y-%m-%d")
        except ValueError:
            tk.messagebox.showerror("Error", "Invalid date format.")
            return

        # 读取Excel数据,进行预处理
        df = pd.read_excel(path, usecols=["日期", "天气", "温度"], parse_dates=["日期"])
        df["天气"] = df["天气"].map({"晴天": 0, "阴天": 1, "大雨": 2, "下雨": 3, "雾": 4})
        df["温度"] = pd.cut(df["温度"], bins=[-50, -10, 0, 10, 20, 50], labels=[0, 1, 2, 3, 4])

        # 训练线性回归模型
        X = df[["日期"]]
        y1 = df["天气"]
        y2 = df["温度"]
        model1 = LinearRegression().fit(X, y1)
        model2 = LinearRegression().fit(X, y2)

        # 预测未来一天的天气和温度
        next_date = date + pd.Timedelta(days=1)
        X_next = pd.DataFrame({"日期": [next_date]})
        next_weather = int(round(model1.predict(X_next)[0]))
        next_temperature = int(round(model2.predict(X_next)[0]))

        # 将数值化的天气和温度转换为字符串和区间范围
        weather_dict = {0: "晴天", 1: "阴天", 2: "大雨", 3: "下雨", 4: "雾"}
        temperature_dict = {0: "-50℃ ~ -10℃", 1: "-10℃ ~ 0℃", 2: "0℃ ~ 10℃", 3: "10℃ ~ 20℃", 4: "20℃ ~ 50℃"}
        next_weather_str = weather_dict[next_weather]
        next_temperature_str = temperature_dict[next_temperature]

        # 在GUI界面中显示预测结果
        result_str = f"On {date_str}, the weather will be {next_weather_str} and the temperature will be in the range of {next_temperature_str}."
        self.result_label.config(text=result_str)

root = tk.Tk()
app = WeatherPredictor(root)
root.mainloop()

注意:

  • 以上代码仅提供框架和思路,具体实现需要根据实际情况进行修改和完善。
  • 样例Excel表格下载链接需要根据实际情况进行修改。
  • 在实际应用中,需要考虑各种异常情况的处理、用户输入的正确性检查等问题。
  • 为了提高预测准确率,可以尝试使用其他机器学习模型或进行特征工程。
  • 由于时间和篇幅限制,无法提供完整的代码,但建议参考以下Python库和函数:
    • Tkinter: GUI界面设计
    • pandas: Excel数据读取和预处理、样例表格生成
    • sklearn: 线性回归模型训练和预测
    • datetime: 日期对象转换
    • os.path: 路径检查和拼接
    • requests: 下载文件
线性回归天气预测:使用Python代码预测未来一天的天气和温度

原文地址: https://www.cveoy.top/t/topic/oka6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录