zoukankan      html  css  js  c++  java
  • DNN拟合曲线

    本文讲解如何用DNN模型拟合一条二次曲线

    导库

    import tensorflow as tf
    from tensorflow.keras import models,layers
    import numpy as np
    import os
    import matplotlib.pyplot as plt
    

    创建训练样本并绘图

    x = np.linspace(-1,1,51)[:,np.newaxis]  # x是样本的特征,注意x是二维numpy数组,其中的每个一维数组用于存放一个样本(特征)
    noise = np.random.normal(0,0.1,size=x.shape)  # 噪声
    y = np.power(x,2) + 0.5*noise  # y是样本的标签,注意y也是二维numpy数组,其中的每个一维数组用于存放一个样本(标签)
    plt.scatter(x,y)  # 绘图
    plt.show()
    

    创建神经网络并训练

    drop_rate = 0.01
    net = models.Sequential()
    net.add(layers.Dense(50,activation='relu',input_shape=(1,)))
    net.add(layers.Dropout(drop_rate))
    net.add(layers.Dense(50,activation='relu'))
    net.add(layers.Dropout(drop_rate))
    net.add(layers.Dense(1))
    adam = tf.keras.optimizers.Adam(lr=0.01,beta_1=0.9,beta_2=0.999,amsgrad=False)
    net.compile(optimizer=adam,loss='mse')
    history = net.fit(x,y,epochs=200,batch_size=10,shuffle=True,verbose=2)
    

    神经网络预测结果绘图

    y_ = net.predict(x)
    plt.scatter(x,y)
    plt.plot(x,y_,color='r')
    plt.show()
    

    全部代码如下

    import tensorflow as tf
    from tensorflow.keras import models,layers
    import numpy as np
    import os
    import matplotlib.pyplot as plt
    
    x = np.linspace(-1,1,51)[:,np.newaxis]  # x是样本的特征,注意x是二维numpy数组,其中的每个一维数组用于存放一个样本(特征)
    noise = np.random.normal(0,0.1,size=x.shape)  # 噪声
    y = np.power(x,2) + 0.5*noise  # y是样本的标签,注意y也是二维numpy数组,其中的每个一维数组用于存放一个样本(标签)
    plt.scatter(x,y)  # 绘图
    plt.show()
    
    drop_rate = 0.01
    net = models.Sequential()
    net.add(layers.Dense(50,activation='relu',input_shape=(1,)))
    net.add(layers.Dropout(drop_rate))
    net.add(layers.Dense(50,activation='relu'))
    net.add(layers.Dropout(drop_rate))
    net.add(layers.Dense(1))
    adam = tf.keras.optimizers.Adam(lr=0.01,beta_1=0.9,beta_2=0.999,amsgrad=False)
    net.compile(optimizer=adam,loss='mse')
    history = net.fit(x,y,epochs=200,batch_size=10,shuffle=True,verbose=2)
    
    y_ = net.predict(x)
    plt.scatter(x,y)
    plt.plot(x,y_,color='r')
    plt.show()
    
  • 相关阅读:
    Entity Framework+SQLite+DataBaseFirst
    接口的实现方式(显示和隐示)及协变和逆变
    C#线程
    UIScrollView放大缩小图片偏移的问题
    SQL Server 2008在添加用户时弹出错误提示:此版本的 Microsoft Windows 不支持 MUST_CHANGE 选项
    jmeter的正则表达式的使用
    Linux下安装jmeter
    系统测试方案
    [ASP.NET].NET逻辑分层架构总结
    [C#]C#时间日期操作
  • 原文地址:https://www.cnblogs.com/bill-h/p/13902554.html
Copyright © 2011-2022 走看看