1、from tensorflow.keras.models import Sequential环境配置不上怎么办? 2、无法解析导入“tensorflow.keras.models”PylancereportMissingImports 发生异常: ImportError cannot import name 'OrderedDict' from 'typing' (F:\Anaconda\lib\typing.py) File "D:\桌面\python项目\demomo.py", line 57, in <module> from tensorflow.keras.models import Sequential ImportError: cannot import name 'OrderedDict' from 'typing' (F:\Anaconda\lib\typing.py)
就是下面这些代码,直接无脑复制粘贴到vscode终端就行了,不用管其他的。
在这里粘贴就可以了。
conda create -n tf3 python=3.7
pip install ipykernel -i https://pypi.tuna.tsinghua.edu.cn/simple/
python -m ipykernel install --name tf3
conda activate tf3
pip install tensorflow==2.3.1 -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install keras==2.4.3 -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install numpy==1.19.5 -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install pandas==1.1.4 -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install scikit-learn==0.24.1 -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install scipy==1.5.4 -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install matplotlib==3.3.3 -i https://pypi.tuna.tsinghua.edu.cn/simple/
最后在vscode里面引入相关库,没报错就说明ok了。
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
✨下面是我问题中导入的相关库,问题已经解决了。
import matplotlib.pyplot as plt
from pandas import read_csv
from pandas import DataFrame
from pandas import concat
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM,Dense,Dropout
from numpy import concatenate
from sklearn.metrics import mean_squared_error,mean_absolute_error,r2_score
from math import sqrt
已经完成了,可以正常运行。
让我们用我之前报错了的预测模型来检测一下是否成功运行。下面测试是运行代码。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas import read_csv
from pandas import DataFrame
from pandas import concat
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM,Dense,Dropout
from numpy import concatenate
from sklearn.metrics import mean_squared_error,mean_absolute_error,r2_score
from math import sqrt
# 加载数据
df = pd.read_csv('合并结果.csv') # 替换为你的数据文件路径
# 选择要预测的列(比如黄金价格)
data = df['USD'].values.reshape(-1, 1)
# 归一化数据
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# 划分训练集和测试集
train_size = int(len(scaled_data) * 0.8)
train_data, test_data = scaled_data[:train_size], scaled_data[train_size:]
# 准备训练数据
def create_dataset(dataset, time_steps=1):
dataX, dataY = [], []
for i in range(len(dataset)-time_steps):
a = dataset[i:(i+time_steps), 0]
dataX.append(a)
dataY.append(dataset[i + time_steps, 0])
return np.array(dataX), np.array(dataY)
time_steps = 1
X_train, y_train = create_dataset(train_data, time_steps)
X_test, y_test = create_dataset(test_data, time_steps)
# 将数据重塑为LSTM输入的格式 [样本数, 时间步, 特征数]
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
# 建立LSTM模型
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(LSTM(units=50))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
# 训练模型
model.fit(X_train, y_train, epochs=10, batch_size=16, verbose=2)
# 使用模型进行预测
train_predict = model.predict(X_train)
test_predict = model.predict(X_test)
# 反归一化预测结果
train_predict = scaler.inverse_transform(train_predict)
test_predict = scaler.inverse_transform(test_predict)
# 绘制预测结果
plt.plot(data, label='True Data')
plt.plot([None for _ in range(train_size)] + [x for x in train_predict], label='Train Prediction')
plt.plot([None for _ in range(train_size + time_steps)] + [x for x in test_predict], label='Test Prediction')
plt.legend()
plt.show()
运行成功!