tensorflow2.0的简单训练(1)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/dudu3332/article/details/102744490

tf的张量改变可以使用python的方式

x=tf.ones([6,6])
x=x+3
print(x)
tf.Tensor(
[[4. 4. 4. 4. 4. 4.]
 [4. 4. 4. 4. 4. 4.]
 [4. 4. 4. 4. 4. 4.]
 [4. 4. 4. 4. 4. 4.]
 [4. 4. 4. 4. 4. 4.]
 [4. 4. 4. 4. 4. 4.]], shape=(6, 6), dtype=float32)

然而机器学习中间需要变化的状态(每个参数朝损失变小的方向改变,所以TensorFlow也要内置有状态的操作,这就是Variables,它可以表示模型中的参数,而且方便高效。

Variables是一个存在值的对象,当其被使用是,它被隐式地被从存储中读取,而当有诸如tf.assign_sub, tf.scatter_update这样的操作时,得到的新值会储存到原对象中。
 

v=tf.Variable(2)
v.assign(6)
print(v)
v.assign_add(tf.square(3))
print(v)
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=6>
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=15>

构建一个线型函数进行简单预测

class Modeltest(object):
    def __init__(self):
        self.W=tf.Variable(5.0)
        self.b=tf.Variable(1.0)
    def __call__(self,x):
        return self.W*x+self.b
model=Modeltest()
print(model(3))
tf.Tensor(16.0, shape=(), dtype=float32)

这里当一个类型实现了特殊方法__call__,该类的实例就变成了可调用的类型, 对象名() 等价于 对象名.__call__() ,有时候可以简化对象的调用,让对象变成可调用的对象, 实现__call__即可.

定义损失函数,生成数据

def losstest(pre,true):
    return tf.reduce_mean(tf.square(pre-true))
TRUE_w_1=3.0
TRUE_t_1=2.0
num=1000
inputs=tf.random.normal(shape=[num])
noise=tf.random.normal(shape=[num])
outputs=TRUE_w_1*inputs+TRUE_t_1*noise
plt.scatter(inputs,outputs,c='b')
plt.scatter(inputs,model(inputs),c='r')
plt.show()
print("init loss")
print(losstest(model(inputs),outputs))

init loss
tf.Tensor(9.058104, shape=(), dtype=float32)

 生成训练函数

def train(model,inputs,outputs,learning_rate):
    with tf.GradientTape() as t:
        current_loss=losstest(model(inputs),outputs)
        dw,db=t.gradient(current_loss,[model.W,model.b])
        model.W.assign_sub(dw*learning_rate)
        model.b.assign_sub(db*learning_rate)

dw db为求道

不断拟合训练

model=Modeltest()
w_list,b_list=[],[]
for epoch in range(10):
    w_list.append(model.W.numpy())
    b_list.append(model.b.numpy())
    current_loss=losstest(model(inputs),outputs)
    train(model,inputs,outputs,learning_rate=0.05)
    print('Epoch %d  W=%f b=%d, loss=%e' %(epoch,w_list[-1],b_list[-1],current_loss))
epochs=range(10)
plt.plot(epochs,w_list,'r',
        epochs,b_list,'b')
plt.plot([TRUE_w_1]*len(epochs),'r--',
        [TRUE_t_1]*len(epochs),'b--')
plt.legend(['W','b','TRUE_w_1','TRUE_t_1'])
plt.show()
Epoch 0  W=5.000000 b=1, loss=9.058104e+00
Epoch 1  W=4.796511 b=0, loss=8.094539e+00
Epoch 2  W=4.613240 b=0, loss=7.313749e+00
Epoch 3  W=4.448178 b=0, loss=6.681057e+00
Epoch 4  W=4.299516 b=0, loss=6.168371e+00
Epoch 5  W=4.165624 b=0, loss=5.752928e+00
Epoch 6  W=4.045035 b=0, loss=5.416280e+00
Epoch 7  W=3.936427 b=0, loss=5.143483e+00
Epoch 8  W=3.838609 b=0, loss=4.922424e+00
Epoch 9  W=3.750509 b=0, loss=4.743290e+00

学习率可以自行改变捉摸 

猜你喜欢

转载自blog.csdn.net/dudu3332/article/details/102744490