tensorflow初学
鉴于实验室环境以及一些因素,选择安装的tensorflow版本为1.4.1,python版本为3.6(anaconda自带的,要先去下载安装包),然后用pycharm编,这些环境的配置网上都有。机子环境是mac
配置完环境后我首先跑了几个小程序进行测试
第一个是线性拟合的
import tensorflow as tf
import numpy as np
#creat data
x_data = np.random .rand (100 ).astype (np.float 32)
y_data = x_data*0.1 + 0.3
### creat tensorflow structure 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)
init = tf.initialize _all_variables()
### create tensorflow structure end###
sess = tf.Session ()
sess.run (init) ## Very important
for step in range(201 ):
sess.run (train)
if step % 20 == 0 :
print(step, sess.run (Weights), sess.run (biases))
第二个是矩阵相乘,用了两种方法打开Session,隔热板更加倾向于第二种
import tensorflow as tf
import numpy as np
#creat data
x_data = np.random .rand (100 ).astype (np.float 32)
y_data = x_data*0.1 + 0.3
### creat tensorflow structure 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)
init = tf.initialize _all_variables()
### create tensorflow structure end###
sess = tf.Session ()
sess.run (init) ## Very important
for step in range(201 ):
sess.run (train)
if step % 20 == 0 :
print(step, sess.run (Weights), sess.run (biases))
第三个是tensorflow中变量的应用
import tensorflow as tf
state = tf.Variable(0 , name='counter' )
one = tf.constant (1 )
new_value = tf.add (state , one )
update = tf.assign(state, new_value)
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
for _in range(3 ):
sess.run(update)
print(sess.run(state))
第四个是使用了占位符placeholder和用feed_dict进行赋值
import tensorflow as tf
input1 = tf.placeholder (tf.float 32)
## placeholder是一个保存数据的利器,第一个参数放的是参数类型,第二个可以放一个参数规模
input2 = tf.placeholder (tf.float 32)
output = tf.multiply (input1, input2) ##新版本不能使用mul只能用multiply
with tf.Session () as sess:
print(sess.run (output, feed_dict = {input1:[7. ], input2:[2. ]}))
#fact_dict是将刚才用占位符placeholder占的位置赋上值。
之后了解了一下tensorflow activation
官方api链接