Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Keras模型为所有输入提供相同的输出_Python_Tensorflow_Machine Learning_Keras_Scikit Learn - Fatal编程技术网

Python Keras模型为所有输入提供相同的输出

Python Keras模型为所有输入提供相同的输出,python,tensorflow,machine-learning,keras,scikit-learn,Python,Tensorflow,Machine Learning,Keras,Scikit Learn,我正在制作一个神经网络,它应该包含480个数据点,输出18个数据点。输入是磁场强度,输出是检测到的物体的坐标(如果没有检测到物体,则为零),因此没有任何数据点是真正分类的。出于某种原因,当我训练模型时,我尝试的每个输入都会得到相同的输出,例如: >>> output2 = loaded_model.predict(X_) >>> output2[0] array([0.32035217, 0.3027814 , 0.2977892 , 0.30922157,

我正在制作一个神经网络,它应该包含480个数据点,输出18个数据点。输入是磁场强度,输出是检测到的物体的坐标(如果没有检测到物体,则为零),因此没有任何数据点是真正分类的。出于某种原因,当我训练模型时,我尝试的每个输入都会得到相同的输出,例如:

>>> output2 = loaded_model.predict(X_)
>>> output2[0]
array([0.32035217, 0.3027814 , 0.2977892 , 0.30922157, 0.3294088 ,
       0.40853357, 0.09848618, 0.15266985, 0.29188123, 0.31177315,
       0.4652696 , 0.6406114 , 0.204305  , 0.23156416, 0.19870688,
       0.21269864, 0.28510743, 0.29115945], dtype=float32)
>>> output2[100]
array([0.32035217, 0.3027814 , 0.2977892 , 0.30922157, 0.3294088 ,
       0.40853357, 0.09848618, 0.15266985, 0.29188123, 0.31177315,
       0.4652696 , 0.6406114 , 0.204305  , 0.23156416, 0.19870688,
       0.21269864, 0.28510743, 0.29115945], dtype=float32)
我用于生成此模型的代码是:

import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from numpy import savetxt
from keras.optimizers import Adam



from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras import regularizers
from keras.layers.advanced_activations import LeakyReLU



from keras.models import model_from_json
#from keras.layers import LeakyReLU
import matplotlib.pyplot as plt



df = pd.read_csv("C:/Users/an/Desktop/python processing/try_2/Hx_output.csv")
dataset = df.values
X = dataset[:,0:480]
Y = dataset[:,480:499]


min_max_scaler = preprocessing.MinMaxScaler()
X_scale = min_max_scaler.fit_transform(X)
Y_scale = min_max_scaler.fit_transform(Y)


X_train, X_val_and_test, Y_train, Y_val_and_test = train_test_split(X_scale, Y_scale, test_size=0.3)
X_val, X_test, Y_val, Y_test = train_test_split(X_val_and_test, Y_val_and_test, test_size=0.5)



pd.DataFrame(X_val).to_csv("C:/Users/an/Desktop/python processing/try_2/X_val.csv", header=None, index=None)
pd.DataFrame(Y_val).to_csv("C:/Users/an/Desktop/python processing/try_2/Y_val.csv", header=None, index=None)




# activation = LeakyReLU(alpha=0.05)
model = Sequential([    Dense(480, activation= 'sigmoid', kernel_regularizer=regularizers.l2(0.01), input_shape=(480,)),
                        Dropout(0.3),
                        Dense(5000, activation= 'softplus', kernel_regularizer=regularizers.l2(0.01)),
                        Dropout(0.3),
                        Dense(5000, activation= 'softplus', kernel_regularizer=regularizers.l2(0.01)),
                        Dropout(0.3),
                        Dense(5000, activation= 'softplus', kernel_regularizer=regularizers.l2(0.01)),
                        Dropout(0.3),
                        Dense(5000, activation= 'softplus', kernel_regularizer=regularizers.l2(0.01)),
                        Dropout(0.3),
                        Dense(5000, activation= 'softplus', kernel_regularizer=regularizers.l2(0.01)),
                        Dropout(0.3),
                        Dense(18, activation= 'sigmoid', kernel_regularizer=regularizers.l2(0.01))])





#opt = keras.optimizers.Adam(lr=0.001)
model.compile(optimizer= Adam(lr=0.0001),              loss='mean_squared_error',              metrics=['mean_squared_error'])
##callbacks=[early_stopping_monitor]
hist = model.fit(X_train, Y_train,          batch_size=32, epochs=150,          validation_data=(X_val, Y_val))

print("Done training !!!")



# serialize model to JSON
model_json = model.to_json()
with open("C:/Users/an/Desktop/python processing/try_2/model.json", "w") as json_file:
    json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("C:/Users/an/Desktop/python processing/try_2/model.h5")
print("Saved model to disk")

plt.plot(hist.history['mean_squared_error'])
#plt.plot(hist.history['val_acc'])
plt.title('Model Mean Squared Error')
plt.ylabel('MeanSquaredError')
plt.xlabel('Epoch')
#plt.legend(['Train', 'Val'], loc='lower right')
plt.show()
我了解到造成这种情况的一些原因是学习率太高,禁用层的“可训练”功能,批量小。我试图将我的学习率降低到0.0001,但我仍然得到了相同的结果,据我所知,我的所有层都是可训练的,最后一个问题是批次大小,我还没有尝试过。我有几千个训练样本,所以可能这就是问题所在,我将在即将进行的新一轮训练中把它从32个增加到400个,但可能问题出在我没有看到的其他地方

我还读到使用回调是个好主意=['early\u stopping\u monitor']在这种情况下合适吗


编辑:kernel_regularizer=regularizers.l2(0.01)项是否也会对此产生影响?

由于在密集层中使用了大量神经元,因此您的拟合过度。请将它们减少到合理的范围[512,1024],粘在下方,然后根据需要向上移动。同时减少层数,仅在必要时增加层数

您确定您的加载也会影响模型的权重吗。试一试

model.load\u权重(路径)

如果你没有加载训练后获得的重量,那么 该模型将使用随机权重,每次都给出相同的预测 模特儿什么也没学到


根据您的问题描述,使用
sigmoid
作为最后一层激活绝对没有意义;还不清楚为什么在中间层使用
softplus
而不是
relu
。我本来想使用leaky relu,因为普通relu没有梯度,但遇到了一些问题,所以我使用softplus作为折衷方案。。。不过我不确定这是不是个好主意。我认为可以使用sigmoid,因为最小-最大标量。。。但是我对激活函数不是很精通,你对这个问题有什么建议?谢谢,将神经元数量减少到600个,并且只有两层600个神经元,对于不同的输入,似乎会得到不同的结果。你提到了[1281024]的范围,我可以问一下为什么128是这个范围的下限吗?我的印象是,你希望模型中的“中间”层有比输入稍多的神经元。你是对的,它们应该更多。是的,这是明智的,但如果数据没有太多的可变性,您可以少用。但是,最好的做法是保持更多。我已相应地更正了我的答案。谢谢你指出这一点。