y_test_scaled = scaler.inverse_transform(test_y.reshape(-1, 1))
时间: 2024-05-25 16:11:03 浏览: 142
这行代码的作用是将经过标准化后的测试集目标变量(test_y)反转换回原始数据的范围。具体来说,它使用之前用于标准化训练集的 Scaler 对象(scaler)来将标准化后的测试集目标变量(test_y)转换回原始数据范围。这里使用了 inverse_transform() 方法,它接受一个数组作为参数,并返回反转换后的原始数据。reshape(-1,1) 是为了将 test_y 转换为二维数组,以适配 Scaler 对象的要求。
相关问题
arr0 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]) arr1 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]) arr2 = np.array(input("请输入连续24个月的车辆销售数据,元素之间用空格隔开:").split(), dtype=float) arr3 = np.array(input("请输入连续24个月的配件销售数据,元素之间用空格隔开:").split(), dtype=float) data_array = np.vstack((arr0, arr1, arr2, arr3)) data_matrix = data_array.T data = pd.DataFrame(data_matrix, columns=['num', 'month', 'car sales', 'sales']) data = data[['month', 'car sales', 'sales']] train_data, test_data = train_test_split(data, test_size=0.3) scaler = MinMaxScaler(feature_range=(0, 1)) data_scaled = scaler.fit_transform(data) train_size = int(len(data_scaled) * 0.7) test_size = len(data_scaled) - train_size train, test = data_scaled[0:train_size,:], data_scaled[train_size:len(data_scaled),:] def create_dataset(dataset, look_back=1): X, Y = [], [] for i in range(len(dataset)-look_back): X.append(dataset[i:(i+look_back), :]) Y.append(dataset[i+look_back, :]) return np.array(X), np.array(Y) look_back = 3 X_train, Y_train = create_dataset(train, look_back) X_test, Y_test = create_dataset(test, look_back) model = Sequential() model.add(LSTM(4, input_shape=(look_back, 3))) model.add(Dense(3)) model.compile(loss='mean_squared_error', optimizer='adam') model.fit(X_train, Y_train, epochs=100, batch_size=1, verbose=0) train_predict = model.predict(X_train) test_predict = model.predict(X_test) train_predict = scaler.inverse_transform(train_predict) Y_train = scaler.inverse_transform(Y_train) test_predict = scaler.inverse_transform(test_predict) Y_test = scaler.inverse_transform(Y_test) last_month = data_scaled[-look_back:] last_month = last_month.reshape((1, look_back, 3))#1,12,3 next_month = model.predict(last_month) next_month = scaler.inverse_transform(next_month) print('下个月的预测结果是:', round(next_month[0][2])),如何将以下代码插入,def comput_acc(real,predict,level): num_error=0 for i in range(len(real)): if abs(real[i]-predict[i])/real[i]>level: num_error+=1 return 1-num_error/len(real) a=np.array(test_data[label]) real_y=a real_predict=test_predict print("置信水平:{},预测准确率:{}".format(0.2,round(comput_acc(real_y,real_predict,0.2)* 100,2)),"%")
可以将以下代码插入到代码中:
```python
def comput_acc(real, predict, level):
num_error = 0
for i in range(len(real)):
if abs(real[i] - predict[i]) / real[i] > level:
num_error += 1
return 1 - num_error / len(real)
a = np.array(test_data['sales'])
real_y = a
real_predict = test_predict[:, 2]
print("置信水平:{},预测准确率:{}".format(0.2, round(comput_acc(real_y, real_predict, 0.2) * 100, 2)), "%")
```
其中,`test_data['sales']` 是测试集中的实际值(即真实销售数据),`test_predict[:, 2]` 则是模型预测的销售数据。`comput_acc` 函数用于计算预测准确率。在这里,我们将置信水平设为 0.2,表示预测结果与实际结果的相对误差在 20% 以内视为准确。
import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Dense from keras.models import load_model model = load_model('model.h5') # 读取Excel文件 data = pd.read_excel('D://数据1.xlsx', sheet_name='4') # 把数据分成输入和输出 X = data.iloc[:, 0:5].values y = data.iloc[:, 0:5].values # 对输入和输出数据进行归一化 scaler_X = MinMaxScaler(feature_range=(0, 6)) X = scaler_X.fit_transform(X) scaler_y = MinMaxScaler(feature_range=(0, 6)) y = scaler_y.fit_transform(y) # 将数据集分成训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) # 创建神经网络模型 model = Sequential() model.add(Dense(units=4, input_dim=4, activation='relu')) model.add(Dense(units=36, activation='relu')) model.add(Dense(units=4, activation='relu')) model.add(Dense(units=4, activation='linear')) # 编译模型 model.compile(loss='mean_squared_error', optimizer='sgd') # 训练模型 model.fit(X_train, y_train, epochs=100, batch_size=1257) # 评估模型 score = model.evaluate(X_test, y_test, batch_size=30) print('Test loss:', score) # 使用训练好的模型进行预测 X_test_scaled = scaler_X.transform(X_test) y_pred = model.predict(X_test_scaled) # 对预测结果进行反归一化 y_pred_int = scaler_y.inverse_transform(y_pred).round().astype(int) # 构建带有概率的预测结果 y_pred_prob = pd.DataFrame(y_pred_int, columns=data.columns[:4]) mse = ((y_test - y_pred) ** 2).mean(axis=None) y_pred_prob['Probability'] = 1 / (1 + mse - ((y_pred_int - y_test) ** 2).mean(axis=None)) # 过滤掉和值超过6或小于6的预测值 y_pred_filtered = y_pred_prob[(y_pred_prob.iloc[:, :4].sum(axis=1) == 6)] # 去除重复的行 y_pred_filtered = y_pred_filtered.drop_duplicates() # 重新计算低于1.2的 Probability 值 low_prob_indices = y_pred_filtered[y_pred_filtered['Probability'] < 1.5].index for i in low_prob_indices: y_pred_int_i = y_pred_int[i] y_test_i = y_test[i] mse_i = ((y_test_i - y_pred_int_i) ** 2).mean(axis=None) new_prob_i = 1 / (1 + mse_i - ((y_pred_int_i - y_test_i) ** 2).mean(axis=None)) y_pred_filtered.at[i, 'Probability'] = new_prob_i # 打印带有概率的预测结果 print('Predicted values with probabilities:') print(y_pred_filtered)这段代码有问题,你帮忙改一下
经过仔细查看代码,我发现问题出在第7行和第8行。它们应该分别是:
```python
X = data.iloc[:, :4].values
y = data.iloc[:, 4].values.reshape(-1, 1)
```
这样就可以将输入数据和输出数据正确地分离开来了。同时,第37行的 `y_test` 应该是 `y_test_scaled`。修改后的代码如下:
```python
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense
from keras.models import load_model
model = load_model('model.h5')
# 读取Excel文件
data = pd.read_excel('D://数据1.xlsx', sheet_name='4')
# 把数据分成输入和输出
X = data.iloc[:, :4].values
y = data.iloc[:, 4].values.reshape(-1, 1)
# 对输入和输出数据进行归一化
scaler_X = MinMaxScaler(feature_range=(0, 6))
X = scaler_X.fit_transform(X)
scaler_y = MinMaxScaler(feature_range=(0, 6))
y = scaler_y.fit_transform(y)
# 将数据集分成训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 使用训练好的模型进行预测
X_test_scaled = scaler_X.transform(X_test)
y_test_scaled = scaler_y.transform(y_test)
y_pred_scaled = model.predict(X_test_scaled)
# 对预测结果进行反归一化
y_pred = scaler_y.inverse_transform(y_pred_scaled)
# 构建带有概率的预测结果
y_pred_prob = pd.DataFrame(y_pred, columns=['Prediction'])
mse = ((y_test_scaled - y_pred_scaled) ** 2).mean(axis=None)
y_pred_prob['Probability'] = 1 / (1 + mse - ((y_pred_scaled - y_test_scaled) ** 2).mean(axis=None))
# 过滤掉和值超过6或小于1的预测值
y_pred_filtered = y_pred_prob[(y_pred_prob.iloc[:, :1].sum(axis=1) <= 6) & (y_pred_prob.iloc[:, :1].sum(axis=1) >= 1)]
# 去除重复的行
y_pred_filtered = y_pred_filtered.drop_duplicates()
# 重新计算低于1.2的 Probability 值
low_prob_indices = y_pred_filtered[y_pred_filtered['Probability'] < 1.2].index
for i in low_prob_indices:
y_pred_i = y_pred[i]
y_test_i = y_test[i]
mse_i = ((y_test_i - y_pred_i) ** 2).mean(axis=None)
new_prob_i = 1 / (1 + mse_i - ((y_pred_i - y_test_i) ** 2).mean(axis=None))
y_pred_filtered.at[i, 'Probability'] = new_prob_i
# 打印带有概率的预测结果
print('Predicted values with probabilities:')
print(y_pred_filtered)
```
请注意,这段代码需要在正确的环境中运行,且文件路径需要根据实际情况修改。
阅读全文