I want to curve fit a data using Tensorflow. I have tried a bunch of things but I just cannot figure it out. So I have two doubts
Have I created the dataset correctly? - I have multiple graphs looking like below. All of them have different X axis and Y axis scale. I have added them into a csv file where the first row and 2nd row is corresponding X-axis and Y-axis data points(301 points), like in pairs. Currently I am just trying to fit the peak of the curve, my only input is the First pair of X and Y points. But I want to use the other pair of x and Y to train the model. I am not sure how I can do that!! So is that even possible.
Apart from the issue in dataset I have worked out the following code which is definitely not working as I can see looses close to 17670360.0000. This is my code
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()
What am I doing wrong? If you have any resource I can take a look at and help myself, I would also appreciate that! Thank you.
you have one input feature x and a target y which is the guassian value. The dense network converges on 50 epochs. Your last dense layer should be linear
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()