使用TensorFlow对高斯数据进行曲线拟合

niwlg2el  于 2023-03-19  发布在  其他
关注(0)|答案(1)|浏览(167)

我想用Tensorflow对一个数据进行曲线拟合,我尝试了很多方法,但都没有找到合适的方法,所以我有两个疑问
1.我是否正确创建了数据集?-我有多个图表,如下所示。它们都有不同的X轴和Y轴比例。我已将它们添加到csv文件中,其中第一行和第二行是对应的X轴和Y轴数据点(301点),就像成对一样。目前我只是试图拟合曲线的峰值,我唯一的输入是第一对X和Y点。但是我想使用另一对X和Y来训练模型。我不确定我怎么能做到这一点!!所以这甚至是可能的。x1c 0d1xx 1c 1d 1x
1.除了数据集中的问题,我已经制定了以下代码,这是肯定不工作,因为我可以看到接近17670360.0000的损失。这是我的代码

data = np.genfromtxt('DatasetTry1.csv',delimiter=',')
x_ini = data[0,0:301] #taking only row 1 of csv
y_ini = data[1,0:301] #taking only row 2 of csv

x_inter = []
y_inter = []

peak_index = np.argmax(y_ini) # finding the peak 

for i in range(peak_index - 25, peak_index + 35): # for loop to fit only few point across the peak
        x_inter.append(x_ini[i])
        y_inter.append(y_ini[i])

x_data = np.array(x_inter)
y_data = np.array(y_inter)

model = keras.Sequential()
model.add(keras.layers.Dense(units = 301, activation = 'linear' ,input_shape=[1])) 
model.add(keras.layers.Dense(units = 128, activation = 'relu'))
model.add(keras.layers.Dense(units = 64, activation = 'relu'))
model.add(keras.layers.Dense(units = 1, activation = 'linear'))
model.compile(loss='mse', optimizer='adam')

# Display the model
model.summary()

model.fit( x_data, y_data, epochs=100, verbose=1)
y_predicted = model.predict(x_data)

# Display the result
plt.scatter(x_data[::1], y_data[::1])
plt.plot(x_data, y_predicted, 'r', linewidth=4)
plt.grid()
plt.show()

我做错了什么?如果你有任何资源,我可以看一看,并帮助自己,我也将不胜感激!谢谢。
以下是我想要的

但通过MI代码,我得到了以下

ecbunoof

ecbunoof1#

您有一个输入要素x和目标y,目标y是高斯值。密集网络在50个历元上收敛。最后一个密集图层应该是线性的

from keras.utils.np_utils import to_categorical
from keras.layers import Dense
from keras.models import Sequential
from keras.callbacks import EarlyStopping
from keras.optimizers import SGD
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from keras.layers import LeakyReLU
from keras.utils import plot_model

# define a function to generate a Gaussian data
def gaussian(x, mu, sig):
    return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))

n=500
x = np.linspace(0, 1, n)
mu=x.mean()
sig=x.std()

y=gaussian(x,mu,sig)

plt.plot(x, y, '.')
plt.show()

#print(y)

#scaler = StandardScaler()
#coordinates_df=pd.DataFrame({'x':x,'y':y})
#scaler.fit(coordinates_df)

#StandardScaler(copy=True, with_mean=True,with_std=True)
#coordinates_df=scaler.transform(coordinates_df)

model = Sequential()

n_features=1
model.add(Dense(100, input_shape=(n_features,)))
model.add(LeakyReLU(alpha=0.03))
model.add(Dense(100))
model.add(LeakyReLU(alpha=0.03))
model.add(Dense(1,activation="linear"))

# Compile your model
#model.compile(optimizer='sgd', loss='mean_squared_error', metrics=['acc'])
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['acc'])

history=model.fit(x,y, epochs = 50,verbose=0)

#plot_model(model, to_file='model.png')
#img=plt.imread('model.png')
#plt.imshow(img)
#plt.show()
plt.figure()
plt.plot(history.history['loss'])
plt.xlabel('loss')
plt.show()

y_pred = model.predict(x)
#print(y_pred)
item_count=len(y_pred)
pred_x=[]
pred_y=[]
for i in np.arange(0,item_count):
    pred_x.append(i)
    pred_y.append(y_pred[i])

plt.figure(figsize=(10,3)) #fig size same as before
ax = plt.gca() #you first need to get the axis handle
#ax.set_aspect(1.5) #sets the height to width ratio to 1.5. 
ax.plot(pred_x,pred_y)
plt.show()

相关问题