tensorflow一个简单的例子
tensorflow一个简单的例子:定义变量w和x,计算wx的值。跟numpy定义变量一样很相似,不同点在于:使用tf的时候,需要进行全局变量初始化操作。tf的所有操作都是在session中进行的,可以理解为tf首先定义了一个画板,然后所有的操作类似于在画板中画画一样。
import tensorflow as tf
w = tf.Variable([[0.5,1.0]])
x = tf.Variable([[2.0],
[1.0]])
y = tf.matmul(w,x)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
print(sess.run(y))
[[2.]]
numpy转换为tensor
既然tensor跟numpy定义变量的形式很像,那么我们是不是可以通过某种函数将numpy转换为tensor呢?
答案是yes啦,我们可以使用tf中的convert_to_tensor函数来进行转换,示例如下:
import numpy as np
s = np.zeros((9,9))
s_tensor = tf.convert_to_tensor(s)
with tf.Session() as sess:
print(sess.run(s_tensor))
[[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]]
placeholder
之前我们设置了一个画板session,在里面创建了w和x。placeholder函数则是在画板中先预占一个位置,可以在之后对其进行赋值。feed_dict以字典的方式对变量在run的时候进行赋值。
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1,input2)
with tf.Session() as sess:
print(sess.run(output,feed_dict={
input1:[7.99],input2:[3.2]}))
[25.567999]
用tensorflow实现一个线性函数
1、制作数据集
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# 随机生成点
num_points = 500
vectors_set = []
for i in range(num_points):
x1 = np.random.normal(0,0.5) # 随机高斯随机化
y1 = x1 * 0.2 + 0.5 + np.random.normal(0,0.05) # 按照高斯随机产生噪点
vectors_set.append([x1,y1])
# 生成一些样本点
x_data = [x[0] for x in vectors_set]
y_data = [x[1] for x in vectors_set]
# 画散点图,查看数据点分布情况
plt.scatter(x_data,y_data,c='r')
plt.show()
模型训练
计算误差,并使用梯度下降的方法进行训练。
# 初始化w和b
# 生成1维的w矩阵,取值是-1到1之间的随机数
W = tf.Variable(tf.random_uniform([1],-1,1),name='W')
#生成1维的b矩阵,初始值是0 + 0.01
b = tf.Variable(tf.zeros([1]),name='b') + 0.01
# 计算预估的y值
y = W*x_data + b
# 计算真实值和预估值之间的误差
loss = tf.reduce_mean(tf.square(y-y_data),name='loss')
# 采用梯度下降法来优化参数
optimizer = tf.train.GradientDescentOptimizer(0.1)
# 训练的过程是最小化误差值
train = optimizer.minimize(loss,name="train")
# 对变量进行初始化
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# 执行300次训练,每隔50步打印一次训练情况
for step in range(200):
sess.run(train)
if step%50 == 0:
print(step, "W=",sess.run(W),"b=",sess.run(b),"loss=",sess.run(loss))
0 W= [0.15018867] b= [0.10818303] loss= 0.15713301
50 W= [0.1915173] b= [0.5012479] loss= 0.0024183749
100 W= [0.19657716] b= [0.5013066] loss= 0.0024114968
150 W= [0.19714049] b= [0.5013125] loss= 0.002411412
Mnist
1、数据集的下载
# 从input_data类中加载数据集,如果有需要请私聊
import input_data
print("packs loading")
print("Download and Extract MNIST dataset")
mnist = input_data.read_data_sets('data/',one_hot=True)
print("data sets:")
print("type of mnist is %s"%(type(mnist)))
print("number of train data is %d"%(mnist.train.num_examples))
print("number of test data is %d"%(mnist.test.num_examples))
packs loading
Download and Extract MNIST dataset
WARNING:tensorflow:From C:\Users\flinjin\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\datasets\mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.
Instructions for updating:
Please write your own downloading logic.
WARNING:tensorflow:From C:\Users\flinjin\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\datasets\base.py:252: _internal_retry.<locals>.wrap.<locals>.wrapped_fn (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.
Instructions for updating:
Please use urllib or similar directly.
Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
WARNING:tensorflow:From C:\Users\flinjin\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\datasets\mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.
Instructions for updating:
Please use tf.data to implement this functionality.
Extracting data/train-images-idx3-ubyte.gz
Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
WARNING:tensorflow:From C:\Users\flinjin\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\datasets\mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.
Instructions for updating:
Please use tf.data t