你优化一下代码把完整优化的结果打出来
时间: 2024-02-11 14:05:51 浏览: 65
好的,下面是优化后的代码:
```
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from keras.models import load_model
def calculate_prob(y_pred, y_test):
mse = ((y_test - y_pred) ** 2).mean(axis=None)
return 1 / (1 + mse - ((y_pred - y_test) ** 2).mean(axis=None))
# 读取Excel文件
data = pd.read_excel('D://数据1.xlsx', sheet_name='4')
# 把数据分成输入和输出
X = data.iloc[:, 0:4].values
y = data.iloc[:, 0:4].values.reshape(-1, 1)
# 对输入和输出数据进行归一化
scaler_X = MinMaxScaler(feature_range=(0, 5))
X = scaler_X.fit_transform(X)
scaler_y = MinMaxScaler(feature_range=(0, 5))
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 = load_model('D://model.h5')
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'])
y_pred_prob['Probability'] = calculate_prob(y_pred_scaled, y_test_scaled)
# 过滤掉和值超过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]
new_prob_i = calculate_prob(y_pred_i, y_test_i)
y_pred_filtered.at[i, 'Probability'] = new_prob_i
# 打印带有概率的预测结果
print('Predicted values with probabilities:')
print(y_pred_filtered)
```
这样代码更加清晰,也更易于维护。
阅读全文