0%

Tensorflow-Coding-Notes:非线性逻辑回归

Notes

Note1 linspace()函数功能

1
x_data = np.linspace(-0.5,0.5,10)
1
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
属性 说明
start 队列的开始值
stop 队列的结束值
num 要生成的样本数,非负数,默认是50
endpoint 若为True,“stop”是最后的样本;否则“stop”将不会被包含。默认为True
retstop 若为False,返回等差数列;否则返回array([samples, step])。默认为False

Note2 [:,newaxis]功能

执行代码

1
2
3
4
x_data = np.linspace(-0.5,0.5,10)
print(x_data.shape)
x_data = x_data[:,newaxis]
print(x_data.shape)

输出结果为

(10,)

(10,1)

x_data[:,newaxis]能将原来的数据扩充一个维度。

Note3 正态分布生成函数

1
np.random.normal(loc=0.0,scale=1.0,size=None)
属性 类型 说明
loc float 正态分布的均值
scale float 正态分布的标准差,对应于分布的宽度,scale越大越矮胖,scale越小,越瘦高
size int or tuple of ints 输出的shape,默认为None,只输出一个值

Note4 y = np.square(x)

1
y = np.square(x)

返回的y与x有相同的shape,其中y的每个元素是x每个元素的平方。

Note5 Tensorflow的占位符

1
x = tf.placeholder(tf.float32,[None,1])

定义了一个32位浮点型的占位符,shape为[None,1],行数没有定义,列数定义为1

执行时使用feed_dict{}以字典的形式传入数据

1
sess.run(train_step,feed_dict={x:x_data,y:y_data})

前面定义了operation,我们运行的时候seess.run()最后一个operation就可以,前面的会自动执行(我的推断)。

1
tf.placeholder(dtype,shape=None,name=None)
属性 说明
dtype 数据类型。常用的是tf.float32,tf.float64等数值类型
shape 数据形状。默认是None,就是一维值,也可以是多维(比如[2,3], [None, 3]表示列是3,行不定)
name 名称

Codes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

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



#使用numpy生成200个随机点
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])

#定义神经网络中间层
Weights_L1 = tf.Variable(tf.random_normal([1,10]))
biases_L1 = tf.Variable(tf.zeros([1,10]))
Wx_plus_b_L1 = tf.matmul(x,Weights_L1) + biases_L1
L1 = tf.nn.tanh(Wx_plus_b_L1)

#定义神经网络输出层
Weights_L2 = tf.Variable(tf.random_normal([10,1]))
biases_L2 = tf.Variable(tf.zeros([1,1]))
Wx_plus_b_L2 = tf.matmul(L1,Weights_L2) + biases_L2
prediction = tf.nn.tanh(Wx_plus_b_L2)

#二次代价函数
loss = tf.reduce_mean(tf.square(y-prediction))
#使用梯度下降法训练
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

with tf.Session() as sess:
#变量初始化
sess.run(tf.global_variables_initializer())
for _ in range(2000):
sess.run(train_step,feed_dict={x:x_data,y:y_data})

#获得预测值
prediction_value = sess.run(prediction,feed_dict={x:x_data})
#画图
plt.figure()
plt.scatter(x_data,y_data)
plt.plot(x_data,prediction_value,'r-',lw=5)
plt.show()