Cell In[20], line 13 rms = np.sqrt(np.mean(np.power((np.array(valid['close'])-preds_valid),2))) ^ IndentationError: unexpected indent怎么解决
时间: 2024-02-06 08:03:44 浏览: 98
这个错误是因为你的代码缩进有误,导致 Python 解释器无法正确地识别代码块。在 Python 中,代码块通常使用缩进来表示,而缩进的空格数必须是固定的,不能随意变化。一般来说,Python 的缩进为四个空格。
在这个代码中,你需要检查代码缩进是否正确,特别是第 13 行的缩进是否正确。请确保第 13 行的缩进与第 12 行的缩进相同,且为四个空格。如果你使用的是 Tab 键进行缩进,请检查是否将 Tab 键转换为了四个空格。
以下是修改后的示例代码:
```
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM
#读取数据
df = pd.read_csv('NSE-TATAGLOBAL.csv')
#设置日期为索引
df['Date'] = pd.to_datetime(df.Date, format='%Y-%m-%d')
df.index = df['Date']
#创建一个新的数据框,只包含日期和收盘价两列
data = df.sort_index(ascending=True, axis=0)
new_data = pd.DataFrame(index=range(0,len(df)),columns=['Date', 'Close'])
for i in range(0,len(data)):
new_data['Date'][i] = data['Date'][i]
new_data['Close'][i] = data['Close'][i]
#设置索引
new_data.index = new_data.Date
new_data.drop('Date', axis=1, inplace=True)
#创建训练集和验证集
dataset = new_data.values
train = dataset[0:987,:]
valid = dataset[987:,:]
#对数据进行缩放
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(dataset)
x_train, y_train = [], []
for i in range(60,len(train)):
x_train.append(scaled_data[i-60:i,0])
y_train.append(scaled_data[i,0])
x_train, y_train = np.array(x_train), np.array(y_train)
x_train = np.reshape(x_train, (x_train.shape[0],x_train.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(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(x_train, y_train, epochs=1, batch_size=1, verbose=2)
#对验证集进行预测
inputs = new_data[len(new_data) - len(valid) - 60:].values
inputs = inputs.reshape(-1,1)
inputs = scaler.transform(inputs)
X_test = []
for i in range(60,inputs.shape[0]):
X_test.append(inputs[i-60:i,0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1))
closing_price = model.predict(X_test)
closing_price = scaler.inverse_transform(closing_price)
#计算RMSE
preds_valid = []
for i in range(0, len(closing_price) - 102):
a = closing_price[i:i+103].sum()
b = a/103
preds_valid.append(b)
rms = np.sqrt(np.mean(np.power((np.array(valid['Close'])-preds_valid),2)))
print(rms)
```
请核对你的代码缩进是否正确,并进行必要的修改。
阅读全文