from keras.models import Sequential
from keras.layers import Dense, LSTM, Activation
from keras.optimizers import adam, rmsprop, adadelta
import numpy as np
import matplotlib.pyplot as plt
#construct model
models = Sequential()
models.add(Dense(100, init='uniform',activation='relu' ,input_dim=1))
models.add(Dense(50, activation='relu'))
models.add(Dense(1,activation='tanh'))
adamoptimizer = adam(lr=0.001, beta_1=0.9, beta_2=0.999, decay=0.00001)
models.compile(optimizer='rmsprop', loss='mse',metrics=["accuracy"] )
#train data
dataX = np.linspace(-2 * np.pi,2 * np.pi, 1000)
dataX = np.reshape(dataX, [dataX.__len__(), 1])
noise = np.random.rand(dataX.__len__(), 1) * 0.1
dataY = np.sin(dataX) + noise
models.fit(dataX, dataY, epochs=100, batch_size=10, shuffle=True, verbose = 1)
predictY = models.predict(dataX, batch_size=1)
score = models.evaluate(dataX, dataY, batch_size=10)
print(score)
#plot
fig, ax = plt.subplots()
ax.plot(dataX, dataY, 'b-')
ax.plot(dataX, predictY, 'r.',)
ax.set(xlabel="x", ylabel="y=f(x)", title="y = sin(x),red:predict data,bule:true data")
ax.grid(True
plt.show()
# plt.plot(dataX,dataY,'b-')
# plt.plot(dataX,predictY,'r-')
#两种画图的方法
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
X = np.linspace(-2, 6, 200)
np.random.shuffle(X)
Y = 0.5 * X + 2 + 0.15 * np.random.randn(200, )
# plot data
# plt.scatter(X, Y)
# plt.show()
X_train, Y_train = X[:160], Y[:160] # train first 160 data points
X_test, Y_test = X[160:], Y[160:]
model = Sequential()
model.add(Dense(64,input_dim=1))#input_dim使我们的输入维度,64,是我们的输出维度
model.add(Dense(1))#这一层我们最终的输出时一个维度
'''
#或者写成这种等价于上面的连个全连接层
model.add(Dense(1,1))
'''
model.compile(loss='mse', optimizer=SGD(lr=0.01, momentum=0.9, nesterov=True))
model.fit(X_train,Y_train,epochs=100,batch_size=64)
Y_pred = model.predict(X_test)
plt.scatter(X_test,Y_test)
plt.plot(X_test,Y_pred)
score=model.evaluate(X_test,Y_test,batch_size=64)
plt.show()
print(score)