代码块
from __future__ import print_function
import tensorflow as tf
from sklearn.datasets import load_digits
from sklearn.model_selection 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.compat.v1.summary.histogram(layer_name + '/outputs', outputs)
return outputs
# define placeholder for inputs to network
keep_prob = tf.compat.v1.placeholder(tf.float32)
xs = tf.compat.v1.placeholder(tf.float32, [None, 64]) # 8x8
ys = tf.compat.v1.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.math.log(prediction),
reduction_indices=[1])) # loss
tf.compat.v1.summary.scalar('loss', cross_entropy)
train_step = tf.compat.v1.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.compat.v1.Session()
merged = tf.compat.v1.summary.merge_all()
# summary writer goes in here
train_writer = tf.compat.v1.summary.FileWriter("/home/lixinming/PycharmProjects/train", sess.graph)
test_writer = tf.compat.v1.summary.FileWriter("/home/lixinming/PycharmProjects/test", sess.graph)
# tf.initialize_all_variables() no long valid from
# 2017-03-02 if using tensorflow >= 0.12
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
init = tf.initialize_all_variables()
else:
init = tf.compat.v1.global_variables_initializer()
sess.run(init)
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)
导入库:
from __future__ import print_function
import tensorflow as tf
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
1.如果某个版本中出现了某个新的功能特性,而且这个特性和当前版本中使用的不兼容,也就是它在该版本中不是语言标准,那么我如果想要使用的话就需要从future模块导入
2.sklearn.model_selection.train_test_split模块
在使用python做机械学习时候,为了制作训练数据(training samples)和测试数据(testing samples),常使用sklearn里面的
3.from sklearn.preprocessing import LabelBinarizer
在多数的机器学习比赛中,给出的标签都是非数字化的,所以我们需要对其进行转换。代码如下:
输入:
from sklearn import preprocessing
feature = [[0,1], [1,1], [0,0], [1,0]]
label= ['yes', 'no', 'yes', 'no']
lb = preprocessing.LabelBinarizer() #构建一个转换对象
Y = lb.fit_transform(label)
re_label = lb.inverse_transform(Y)
print(Y)
print(re_label)
输出:
[[1]
[0]
[1]
[0]]
['yes' 'no' 'yes' 'no']
转换函数将字符串label进行数字化,数字范围从0开始,并且将label转换为了一个列向量。最后在ML任务完成之后,输出的时候需要还原之前的label,因此使用函数inverse_transform()
网络层
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.compat.v1.summary.histogram(layer_name + '/outputs', outputs)
return outputs
tf.nn.dropout函数介绍
tf.nn.dropout是tensorflow的好朋友,它的作用是为了减轻过拟合带来的问题而使用的函数,它一般用在每个连接层的输出。
Dropout就是在不同的训练过程中,按照一定概率使得某些神经元停止工作。也就是让每个神经元按照一定的概率停止工作,这次训练过程中不更新权值,也不参加神经网络的计算。但是它的权重依然存在,下次更新时可能会使用到它。
dropout(x, keep_prob, noise_shape=None, seed=None, name=None)
x: 一般是每一层的输出。
keep_prob,保留keep_prob的神经元继续工作,其余的停止工作与更新。
在实际定义每一层神经元的时候,可以加入dropout。但需要注意的是,神经元的输出层不可以定义dropout参数。因为输出层就是输出的是结果,在输出层定义参数的话,就会导致输出结果被dropout掉。
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3)
X_train,X_test, y_train, y_test =sklearn.model_selection.train_test_split(train_data,train_target,test_size=0.4, random_state=0,stratify=y_train)
train_data:所要划分的样本特征集
train_target:所要划分的样本结果
test_size:样本占比,如果是整数的话就是样本的数量
random_state:是随机数的种子。
随机数种子:其实就是该组随机数的编号,在需要重复试验的时候,保证得到一组一样的随机数。比如你每次都一样填1,其他参数一样的情况下你得到的随机数组是一样的。但填0或不填,每次都会不一样。
stratify是为了保持split前类的分布。比如有100个数据,80个属于A类,20个属于B类。如果train_test_split(… test_size=0.25, stratify = y_all), 那么split之后数据如下:
training: 75个数据,其中60个属于A类,15个属于B类。
testing: 25个数据,其中20个属于A类,5个属于B类。
用了stratify参数,training集和testing集的类的比例是 A:B= 4:1,等同于split前的比例(80:20)。通常在这种类分布不平衡的情况下会用到stratify。
将stratify=X就是按照X中的比例分配
将stratify=y就是按照y中的比例分配