TensorFlow学习(一)

       TensorFlow的安装参考官网:https://www.tensorflow.org/install/?hl=zh-cn

       TensorFlow是一个开源软件库,采用数据流图用于高性能计算,是一种较好的机器学习工具。TensorFlow有许多功能,但主要用来构建深度神经网络模型。TensorFlow的名字由Tensor (张量)和Flow(流)组成。

       在TensorFlow 程序中,所有数据都通过张量的形式表示,零阶张量表示标量(Scaka),一阶张量表示向量,n阶张量表示n维数组。要注意的是,张量在TensorFlow中的实现不是直接采用数组,它是对TensorFlow中运算结果的引用。在张量中并没有真正保存数字,保存的是得到这些数字的计算过程。

       

  • np.random.rand()  # [0,1)之间均匀分布的随机样本
  • np.randam.randn() #N(0,1) 正态分布
  • np.random.randint() # [low,high)返回随机整数,或整数型数组
  • tf.random_normal() #正态分布
  • tf.reduce_mean()             
x = tf.constant([[1., 1.], [2., 2.]])
tf.reduce_mean(x)  # 1.5
tf.reduce_mean(x, 0)  # [1.5, 1.5]
tf.reduce_mean(x, 1)  # [1.,  2.]

     使用梯度下降算法的优化器

     learning_rate: A Tensor or a floating point value. The learning rate to use.

举个简单例子:

import numpy as np
import tensorflow as tf

# creat data
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1+0.3

### start
Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0)) #平均分布
biases = tf.Variable(tf.zeros([1]))

y=Weights*x_data+biases

loss=tf.reduce_mean(tf.square(y-y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
### end

sess = tf.Session() #创建一个会话

init = tf.global_variables_initializer()

sess.run(init)

for step in range(301):
    sess.run(train)
    if step % 20 ==0:
        print(step,sess.run(Weights),sess.run(biases))

Result:



Reference:
在机器学习中对于张量的理解可以参考: 深度学习初学者必读:张量究竟是什么?


猜你喜欢

转载自blog.csdn.net/Mao_Jonah/article/details/81046365
今日推荐