地下水位预测python源代码
时间: 2024-09-29 18:12:26 浏览: 145
地下水位预测通常涉及时间序列分析和机器学习技术,Python作为常用的科学计算语言,有许多库可以帮助完成此类任务。下面是一个简单的例子,展示如何使用Python的`pandas`, `numpy`, 和 `sklearn`(如`LSTM`模型)来进行地下水位预测:
```python
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 假设你已经有了数据集df,包含日期和地下水位值
data = df['groundwater_level'].values.reshape(-1, 1)
# 数据预处理
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# 分割数据集为训练集和测试集
train_size = int(len(scaled_data) * 0.8)
test_size = len(scaled_data) - train_size
train_data, test_data = scaled_data[0:train_size], scaled_data[train_size:]
# 将数据转化为时间序列
def create_dataset(dataset, look_back=1):
X, Y = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
X.append(a)
Y.append(dataset[i + look_back, 0])
return np.array(X), np.array(Y)
look_back = 1
X_train, y_train = create_dataset(train_data, look_back)
X_test, y_test = create_dataset(test_data, look_back)
# 构建LSTM模型
model = Sequential()
model.add(LSTM(50, input_shape=(look_back, 1)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练模型
model.fit(X_train, y_train, epochs=100, batch_size=1, verbose=2)
# 预测
predictions = model.predict(X_test)
predictions = scaler.inverse_transform(predictions)
# 可视化结果
import matplotlib.pyplot as plt
plt.plot(scaler.inverse_transform(y_test), label='Actual')
plt.plot(predictions, label='Predicted')
plt.legend()
plt.show()
阅读全文