本文实现一个利用python 进行拟合的代码
拟合的意义
对已经发生过的事实的影响因素当作输入, 事件结果当作输出
以此来发现事物之间的规律,来预测 短暂未来中是否会发生某件事情的概率,或者商品估值
实际上 任何 的预测回归问题,都可以通过 tensorflow的深度学习来实现
预测分析
多因素对 工资分配的拟合 图像
公司业务成本对收益的影响拟合曲线
import matplotlib.pyplot as plt#约定俗成的写法plt
#首先定义两个函数(正弦&余弦)
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
model = tf.keras.Sequential()
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(1,))
#
# model.compile(optimizer=tf.keras.optimizers.Adam(0.5),
# loss='categorical_crossentropy',
# metrics=['accuracy'])
optimizer = tf.keras.optimizers.RMSprop(0.001)
model.compile(loss='mse',
optimizer=optimizer,
metrics=['mae', 'mse'])
X=np.linspace(-np.pi,np.pi,256,endpoint=True)#-π to+π的256个值
print("x的值",X.shape)
S=np.sin(X)
x1=[]
s1=[]
for index in range(len(X)):
x1.append([X[index]])
s1.append([S[index]])
x1=np.array(x1)
s1=np.array(s1)
model.fit(x1,s1,epochs=0, batch_size=32)
before_t=[]
for tempx in X:
print(tempx)
tempx=model.predict([tempx])
tempx=tempx[0]
before_t.append(tempx)
model.fit(x1,s1,epochs=100, batch_size=32)
after_t=[]
for tempx in X:
print(tempx)
tempx=model.predict([tempx])
tempx=tempx[0]
after_t.append(tempx)
print(tempx)
plt.plot(X,S,label='sin(x)')
plt.plot(X,before_t,label="before_train")
plt.plot(X,after_t,label="after_train",color="yellow")
#在python的交互环境中需要这句话才能显示出来
plt.legend()
plt.show()