TF的基本操作

4 篇文章 0 订阅

tf的变量和常量操作

#coding=utf-8
import tensorflow as tf

state = tf.Variable(0)
delta = tf.constant(1)
new_state = tf.add(state,delta)

updata = tf.assign(state,new_state)

init = tf.global_variables_initializer()

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

np数组转换为tf变量

#coding=utf-8
import tensorflow as tf
import numpy as np

a = np.ones((3,3))
b = tf.convert_to_tensor(a,dtype = tf.float32)

# init = tf.global_variables_initializer()
with tf.Session() as sess:
#     sess.run(init)
    print(sess.run(b))

tf文件保存,这只是个简单的session保存

#coding=utf-8
import tensorflow as tf

a = tf.Variable([[1.3,2.]])
b = tf.Variable([[3.],[2.1]])

c = tf.matmul(a,b)
init = tf.global_variables_initializer()

saver = tf.train.Saver()

with tf.Session() as sess:
    sess.run(init)
    k = sess.run(c)
    #路径上一定要有一个文件夹
    save_path = saver.save(sess,"1//test3")
    print(k,save_path)

tf中的tf.placeholder的使用方法

#coding=utf-8
import tensorflow as tf
import numpy as np

a = np.array([[1.,2.,3.],
              [1.2,3.2,2.5]])
a1 = np.array([[4.,5.],
              [2.8,4.2],
              [1.,9.]])

w = tf.placeholder(tf.float32,shape = (2,3))
b = tf.placeholder(tf.float32,shape = (3,2))
c = tf.matmul(w,b)

w1 = tf.convert_to_tensor(a)
b1 = tf.convert_to_tensor(a1)   
with tf.Session() as sess:
    w1 = sess.run(w1)
    b1 = sess.run(b1)
     
# with tf.Session() as sess2:
    print(sess.run(c, feed_dict = {w:w1,b:b1}))

给定一条直线y=0.3x+3,根据y=kx+b,训练得出k,b的数值

#coding=utf-8
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

numpoints = 1000
vects = []

for i in range(1000):
    #初始化w,b的值
    x_data = np.random.normal(0.0, 0.5)
    y_data = 0.3 * x_data + 3 + np.random.normal(0.0, 0.06)
    vects.append([x_data,y_data])
#准备训练用的数据    
x = [v[0] for v in vects]
y = [v[1] for v in vects]

figure = plt.figure(figsize= (12,8))#指定大小
ax1 = figure.add_subplot(2,1,1)#添加在1号位置
plt.ylim([2, 4])#y轴刻度
plt.xlim([-2.5,2.5])#x轴刻度
plt.scatter(x, y ,c='r')#散点图
ax2 = figure.add_subplot(2,1,2)#
# plt.show()
# help(plt)plt.show()

#W,b
w = tf.Variable(tf.random_uniform([1,],-1.,1.))
b = tf.Variable(tf.zeros([1,]))

y_pre = w*x + b
loss = tf.reduce_mean(tf.square(y_pre-y))
op = tf.train.AdamOptimizer(0.55).minimize(loss)
#初始化全局变量
init = tf.global_variables_initializer()
#启动session
with tf.Session() as sess:
    sess.run(init)
    for _ in range(20):
        sess.run(op)
        print('w:{},b:{},loss{}'.format(sess.run(w),sess.run(b),sess.run(loss)))
    #显示用w,b画出的直线
    plt.plot(x,sess.run(w) * x + sess.run(b))
plt.show()
sess.close()#释放资源

上图是

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值