'''简单小例子'''
import tensorflow as tf
import numpy as np
#create data
x_data = np.random.rand(100).astype(np.float32)
y_data = 0.1*x_data + 0.3
###create 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)#0.5指的是机器学习的学习效率
train = optimizer.minimize(loss)#用optimizer这个优化器减少误差
init = tf.initialize_all_variables()
###create tensorflow structure end###
sess = tf.Session()
sess.run(init) #像一个指针,指向tensorflow框架init,使其激活
for step in range(201):
sess.run(train) #session指针指向train
if step%20 == 0:
print(step,sess.run(Weights),sess.run(Biases))
In [4]:
'''Session会话'''
matrix1 = tf.constant([[3,3]]) #shape=(1, 2), dtype=int32)
matrix2 = tf.constant([[2],
[2]]) #shape=(2, 1) dtype=int32
product = tf.matmul(matrix1,matrix2) #matrix multiply like np.doc(m1,m2)
# mothond 1
# sess = tf.Session()
# result = sess.run(product) #返回执行的结果,每run一次就执行一次上面执行的结果
# print(result)
# sess.close()
# mothond 2
with tf.Session() as sess:
result = sess.run(product)
print(result)
In [5]:
'''变量'''
state = tf.Variable(0,name='number') #变量需要定义,还可以定义变量的初始值,此处为0,变量的名字为number
# print(state.name)
one = tf.constant(1)
new_value = tf.add(state,one)
update = tf.assign(state,new_value) #把new_value 加载到state 返回的是assign的对象
init = tf.initialize_all_variables() #初始化所有的变量,定义变量时必须用这个。但还没有激活,必须使用run才可以激活
with tf.Session() as sess:
sess.run(init)
for _ in range(3):
sess.run(update)
print(sess.run(state))
In [6]:
'''传入值'''
input1 = tf.placeholder(tf.float32) #也可以传入[2,2]来表示2行2列
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1,input2) #原来这个tf.mul函数已经被换成了tf.multiply了
with tf.Session() as sess:
print(sess.run(output,feed_dict={input1:[7.],input2:[2.]}))
In [13]:
print(np.newaxis)
In [16]:
#np.linspace(-1,1,300)[:, np.newaxis]
In [17]:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def add_layer(inputs, in_size, out_size, activation_function=None):
# add one more layer and return the output of this layer
Weights = tf.Variable(tf.random_normal([in_size, out_size]))
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
# Make up some real data
x_data = np.linspace(-1,1,300)[:, np.newaxis] # np.newaxis 类似于None,该用法是把一维数组改为二维的N阶数组
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise
# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])
# add hidden layer
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
# add output layer
prediction = add_layer(l1, 10, 1, activation_function=None)
# the error between prediciton and real data
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
reduction_indices=[1]))# reduction_indices=[1]:把数组降到一维,[0],降到0维,也就是一个数
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
# important step
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data,y_data)
plt.ion()
plt.show()
for i in range(1000):
# training
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
if i % 50 == 0:
try:
ax.lines.remove(lines[0])
except Exception:
pass
# to see the step improvement
#print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))
prediction_value = sess.run(prediction,feed_dict={xs:x_data})
lines = ax.plot(x_data,prediction_value,'r-',lw=5)
plt.pause(0.1)
In [2]:
'''tensorflow可视化'''
# coding=utf-8
def add_layer(inputs, in_size, out_size, activation_function=None):
# add one more layer and return the output of this layer
with tf.name_scope('weights'):
Weights = tf.Variable(tf.random_normal([in_size, out_size]),name='W')
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1,name='b')
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
# define placeholder for inputs to network
with tf.name_scope('input'):
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])
# add hidden layer
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
# add output layer
prediction = add_layer(l1, 10, 1, activation_function=None)
# the error between prediciton and real data
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
reduction_indices=[1]))
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
# important step
init = tf.initialize_all_variables()
sess = tf.Session()
write = tf.summary.FileWriter('doudou/',sess.graph)
sess.run(init)
In [23]:
'''tensorflow 分类学习'''
from tensorflow.examples.tutorials.mnist import input_data
# 参数:train_dir:文件夹的文件夹的位置,fake_data:是否使用假数据,one_hot:是否把标签转为一维向量
minist = input_data.read_data_sets('MNIST_data',one_hot=True)
def add_layer(inputs, in_size, out_size, activation_function=None, ):
# add one more layer and return the output of this layer
Weights = tf.Variable(tf.random_normal([in_size, out_size]))
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, )
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b, )
return outputs
def compute_accuracy(v_xs,v_ys):
global prediction
y_pre = sess.run(prediction,feed_dict={xs:v_xs})
correct_prediction = tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
return result
# define placeholder for inputs to network
xs = tf.placeholder(tf.float32,[None,784])
ys = tf.placeholder(tf.float32,[None,10])
# add output layer
prediction = add_layer(xs,784,10,activation_function=tf.nn.softmax)
# the error between prediction and real data
cross_entropy = tf.reduce_mean(tf.reduce_sum(ys*tf.log(prediction),
reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.Session()
# important step
sess.run(tf.initialize_all_variables())
for i in range(1000):
batch_xs,batch_ys = minist.train.next_batch(100)
sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys})
if i % 50 == 0:
print(compute_accuracy(
minist.test.images,minist.test.labels))
In [3]:
'''tensorflow dropout解决overfiting问题'''
import tensorflow as tf
from sklearn.datasets import load_digits
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import LabelBinarizer
# load data
digits = load_digits()
X = digits.data
y = digits.target
y = LabelBinarizer().fit_transform(y) # 把非数字化标签转化为数字化标签
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3)
def add_layer(inputs, in_size, out_size, layer_name, activation_function=None, ):
# add one more layer and return the output of this layer
Weights = tf.Variable(tf.random_normal([in_size, out_size]))
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, )
Wx_plus_b = tf.matmul(inputs, Weights) + biases
# here to dropout
Wx_plus_b = tf.nn.dropout(Wx_plus_b, keep_prob)
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b, )
tf.summary.histogram(layer_name + '/outputs', outputs)
return outputs
# define placeholder for inputs to network
keep_prob = tf.placeholder(tf.float32)
xs = tf.placeholder(tf.float32, [None, 64]) # 8x8
ys = tf.placeholder(tf.float32, [None, 10])
# add output layer
l1 = add_layer(xs, 64, 50, 'l1', activation_function=tf.nn.tanh)
prediction = add_layer(l1, 50, 10, 'l2', activation_function=tf.nn.softmax)
# the loss between prediction and real data
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
reduction_indices=[1])) # loss
tf.summary.scalar('loss', cross_entropy)
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.Session()
merged = tf.summary.merge_all()
# summary writer goes in here
train_writer = tf.summary.FileWriter("logs/train", sess.graph)
test_writer = tf.summary.FileWriter("logs/test", sess.graph)
sess.run(tf.initialize_all_variables())
for i in range(500):
# here to determine the keeping probability
sess.run(train_step, feed_dict={xs: X_train, ys: y_train, keep_prob: 0.5})
if i % 50 == 0:
# record loss
train_result = sess.run(merged, feed_dict={xs: X_train, ys: y_train, keep_prob: 1})
test_result = sess.run(merged, feed_dict={xs: X_test, ys: y_test, keep_prob: 1})
train_writer.add_summary(train_result, i)
test_writer.add_summary(test_result, i)