[ML&DL]tensorflow学习1

  1. 第一个例子:常量的使用
import tensorflow as tf

m1 = tf.constant([[3,3]])
m2 = tf.constant([[2],[3]])
pro = tf.matmul(m1, m2)
ProMul = m1 * m2
Sess = tf.Session()

print(Sess.run(ProMul))
print(Sess.run(m2))
print(Sess.run(pro))

Sess.close()


输出结果:
[[6 6]
 [9 9]]
[[2]
 [3]]
[[15]]

其中m1 为tensorflow中创建的1行2列的向量常量,m2为创建的2行1列的向量常量。
tf.matmul为两个向量的乘法操作,如果直接做乘法结果就是每个向量的单独乘法
tensorflow构建的是一个图计算的过程,matmul为整个图计算过程中的一个节点(OP操作),因此需要在会话中进行执行。
2. 第二个例子:变量的使用

import tensorflow as tf

x = tf.Variable([1,2])
a = tf.constant([3,3])
#增加一个减法op
sub = tf.subtract(x,a)
#增加一个加法op
add = tf.add(x,sub)

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(sub))
    print(sess.run(add))

state = tf.Variable(0,name='counter')
new_value = tf.add(state,1)
#赋值操作
update = tf.assign(state,new_value)
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(state))
    for _ in range(5):
        sess.run(update)
        print(sess.run(state))

State = tf.Variable(0, name = ‘counter’) 是变量命名的一种方式:
其中name = 'counter’中调用时候使用State,后边属于变量的属性,目的是更好得表示变量的代表的含义,而不具有代入功能。
变量的使用中需要使用tf.global_variables_initializer()对全局进行初始化的操作
同时使用with语句确定Session()的作用域
3. 占位函数使用:

import tensorflow as tf
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
add = tf.add(input2, input3)
mul = tf.multiply(input1, add)
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:[5], input2:[10]}))

函数原形:
tf.placeholder(
dtype,
shape=None,
name=None
)
dtype:数据类型。常用的是tf.float32,tf.float64等数值类型
shape:数据形状。默认是None,就是一维值,也可以是多维(比如[2,3], [None, 3]表示列是3,行不定)
name:名称
调用时候需要使用字典进行赋值。

  1. 线性回归:
import tensorflow as tf
import numpy as np

# 随机产生100个随机点
x_data = np.random.rand(100)
y_data = x_data * 1.1 + 0.4

#训练数据
b = tf.Variable(0.)
k = tf.Variable(0.)
y = k * x_data + b

#二阶代价函数
loss = tf.reduce_mean(tf.square(y_data - y))
#定义一个梯度下降法
optimizer = tf.train.GradientDescentOptimizer(0.2)

#定义最小化函数
train = optimizer.minimize(loss)

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for step in range(401):
        sess.run(train)
        if step % 20 == 0:
            print(sess.run([k,b]))

tf.reduce_mean 原形:
reduce_mean(input_tensor,
axis=None,
keep_dims=False,
name=None,
reduction_indices=None)
第一个参数input_tensor: 输入的待降维的tensor;
第二个参数axis: 指定的轴,如果不指定,则计算所有元素的均值;
第三个参数keep_dims:是否降维度,设置为True,输出的结果保持输入tensor的形状,设置为False,输出结果会降低维度;
第四个参数name: 操作的名称;
第五个参数 reduction_indices:在以前版本中用来指定轴,已弃用;
GradientDescentOptimizer使用梯度下降法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值