炼数成金Tensorflow学习笔记之3.1_非线性回归

炼数成金Tensorflow学习笔记之3.1_非线性回归

代码及分析

# -*- coding: utf-8 -*-
"""
Created on Sun Mar 15 09:10:07 2020

@author: 寒火qwer
"""

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

# 使用numpy生成200个随机点
# numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
# 返回的是 [start, stop]之间的均匀分布
# np.newaxis的作用就是在这一位置增加一个一维,这一位置指的是np.newaxis所在的位置
x_data = np.linspace(-0.5, 0.5, 200)[:, np.newaxis]
noise = np.random.normal(0, 0.02, x_data.shape)
y_data = np.square(x_data) +noise

# 定义两个placeholder
x = tf.placeholder(tf.float32, [None, 1])
y = tf.placeholder(tf.float32, [None, 1])

# 定义神经网络的中间层
weight_l1 = tf.Variable(tf.random_normal([1, 10]))
biases_l1 = tf.Variable(tf.zeros([1,10]))
a1 = tf.matmul(x, weight_l1) + biases_l1
l1 = tf.nn.tanh(a1)

# 定义输出层
weight_l2 = tf.Variable(tf.random_normal([10,1]))
biases_l2 = tf.Variable(tf.zeros([1,1]))
a2 = tf.matmul(l1, weight_l2) + biases_l2
predict = tf.nn.tanh(a2)

# 二次代价函数
loss = tf.reduce_mean(tf.square(y - predict))

# 使用梯度下降法训练
train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    for _ in range(2000):
        sess.run(train_op, feed_dict={x:x_data, y:y_data})
        
        
    # 获得预测值
    predict_value = sess.run(predict, feed_dict={x:x_data})
    # 画图
    plt.figure()
    plt.scatter(x_data, y_data)
    plt.plot(x_data,predict_value, 'r-', lw=5)
    plt.show()
  1. np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
    作用:返回的是 [start, stop](或[start, stop))之间的均匀分布(至于包不包含stop取决于endpoint参数的取值。为True,这时stop就是最后的样本。为False时,不包含stop的值。)
  2. np.newaxis的作用就是在这一位置增加一个一维,这一位置指的是np.newaxis所在的位置
  3. np.random.normal(loc=0.0, scale=1.0, size=None)
    作用:生成高斯分布的概率密度随机数
    loc:float, 此概率分布的均值(对应着整个分布的中心centre)
    scale:float, 此概率分布的标准差(对应于分布的宽度,scale越大越矮胖,scale越小,越瘦高)
    size:int or tuple of ints,输出的shape,默认为None,只输出一个值
  4. tf.nn.tanh(x, name=None)
  5. 作用:tanh激活函数
    在这里插入图片描述
  6. plt.figure((num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True)
    作用:创建自定义画板
    num:图像编号或名称,数字为编号 ,字符串为名称
    figsize:指定figure的宽和高,单位为英寸;
    dpi参数指定绘图对象的分辨率,即每英寸多少个像素,缺省值为80
    facecolor:背景颜色
    edgecolor:边框颜色
    frameon:是否显示边框
  7. plt.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None, **kwargs)
    作用:绘制散点图
    x,y:array_like,shape(n,),输入数据
  8. plt.plot(x,y,format_string,**kwargs)
    作用:绘制折线图
  9. plt.show()
    作用:显示图像
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值