zoukankan      html  css  js  c++  java
  • 【2-1】非线性回归

     1 import tensorflow as tf
     2 import numpy as np
     3 import matplotlib.pyplot as plt
     4 
     5 #使用numpy生成200个随机点
     6 x_data = np.linspace(-0.5,0.5,200)[:,np.newaxis]    
     7 noise = np.random.normal(0,0.02,x_data.shape)
     8 y_data = np.square(x_data) + noise
     9 
    10 #定义两个placeholder
    11 x = tf.placeholder(tf.float32,[None,1])
    12 y = tf.placeholder(tf.float32,[None,1])
    13 
    14 #输入层1个神经元节点,中间层10个神经元节点,输出层1个神经元节点
    15 #定义神经网络中间层
    16 Weights_L1 = tf.Variable(tf.random_normal([1,10]))
    17 biases_L1 = tf.Variable(tf.zeros([1,10]))
    18 Wx_plus_b_L1 = tf.matmul(x,Weights_L1) + biases_L1
    19 L1 = tf.nn.tanh(Wx_plus_b_L1)
    20 
    21 #定义神经网络输出层
    22 Weight_L2 = tf.Variable(tf.random_normal([10,1]))
    23 biases_L2 = tf.Variable(tf.zeros([1,1]))
    24 Wx_plus_b_L2 = tf.matmul(L1,Weight_L2) + biases_L2
    25 prediction = tf.nn.tanh(Wx_plus_b_L2)
    26 
    27 #二次代价函数
    28 loss= tf.reduce_mean(tf.square(y-prediction))
    29 #使用梯度下降法训练网络
    30 train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
    31 
    32 with tf.Session() as sess:
    33     #变量初始化
    34     sess.run(tf.global_variables_initializer())
    35     for _ in range(2000):
    36         sess.run(train_step,feed_dict={x:x_data,y:y_data})
    37     #print(sess.run(Weights_L1))
    38     #获得预测值
    39     prediction_value = sess.run(prediction,feed_dict={x:x_data})
    40     #画图
    41     plt.figure()
    42     plt.scatter(x_data,y_data)
    43     plt.plot(x_data,prediction_value,'r-',lw=5)
    44     plt.show()

    2019-05-30 10:58:12

  • 相关阅读:
    python 冒泡排序
    python链式调用REST API把参数放到URL中
    python assert断言用法
    python实现斐波那契数列
    Pycharm快捷键集合
    linux shell中$0,$?,$!等的特殊用法
    搭建邮箱服务器
    linux安装IB驱动方法
    Oracle:Redhat 7.4+Oracle Rac 11.2.0.4 执行root.sh报错处理
    Struts学习(一)
  • 原文地址:https://www.cnblogs.com/direwolf22/p/10948367.html
Copyright © 2011-2022 走看看