Tensorflow基础语法

import tensorflow as tf;
import numpy as np;

state = tf.Variable(0,name='counter')   #参数值为0,name为counter
# print(state.name)
one = tf.constant(1)

new_value = tf.add(state,one)
update = tf.assign(state,new_value)  #assgin英文是:赋值,分配,所以在这里就是一个赋值过程

init = tf.initialize_all_variables()  #如果定义变量一定需要

with tf.Session() as sess:
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))

 

 

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

#create data  代码预测参数。就是为了预测weight接近0.1,biaes接近0.3
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1+0.3

# creat tensorflow structure start #
Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0)) #生成一个随机数列,是一维的,范围是-1-1
biases = tf.Variable(tf.zeros([1])) #第一次赋值是0

y = Weights*x_data+biases
loss = tf.reduce_mean(tf.square(y-y_data))#真实值和预测值的一个差
optimizer = tf.train.GradientDescentOptimizer(0.5)#优化器,optimizer可以有很多种选择,先选择GradientDescentOptimizer;0.5是一个学习效率,一般是小于一的数
train = optimizer.minimize(loss)#用优化器减少误差

init = tf.initialize_all_variables()#都是需要初始化的,就是模型建立好了,需要初始化让这个模型“活”起来
# creat tensorflow structure end #

sess = tf.Session()
sess.run(init)  #结构激活!!!sess就像一个指针指像init,并激活!

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

 

 

import tensorflow as tf;
import numpy as np;

matrix1 = tf.constant([[3,3]])  #constnt恒量
matrix2 = tf.constant([[2],[2]])

product = tf.matmul(matrix1,matrix2)  #matmul: matrix muliply  用np.dot(m1,m2)也是对两个矩阵进行乘法运算

#method 1
# sess = tf.Session()
# result = sess.run(product)  #sess.run()返回值给result
# print(result)
#sess.close()

#mesthod 2
with tf.Session() as sess:    #用sess打开tf.Session()
    print(sess.run(product))  #自动close

 

#placeholder是传入值

import tensorflow as tf

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.],input2:[2.]}))  #placeholder传入的值是和先开始定义的数据是绑定的,在输出的时候一定需要feed_dict

你可能感兴趣的:(Tensorflow基础语法)