# TensorFlow篇——常用函数

1、onehot操作
labels=np.array([1,2,3,4,5,6])

def to_one_hot(labels):
num_class=np.unique(labels).shape[0]
num_labels=labels.shape[0]
onehotmatrix=np.zeros((num_labels,num_class))
for i,j in enumerate(labels):
onehotmatrix[i][j-1]=1
return onehotmatrix

2、划分训练集
80%为训练，20%为验证

def split(train_data,train_labels):
shuffled_ix=np.random.permutation(np.arange(len(train_labels)))
x_shuffled=train_data[shuffled_ix]
y_shuffled=train_labels[shuffled_ix]
ix_cutoff=int(len(y_shuffled)*0.80)
x_train,x_test=x_shuffled[:ix_cutoff],x_shuffled[ix_cutoff:]
y_train,y_test=y_shuffled[:ix_cutoff],y_shuffled[ix_cutoff:]


3、batch训练

'''
batch训练与验证

epochs
x_train
y_train
batch_size
'''
for epoch in range(epochs):
shuffled_ix=np.random.permutation(np.arange(len(x_train)))
x_train=x_train[shuffled_ix]
y_train=y_train[shuffled_ix]
num_batches=int(len(x_train)/batch_size)+1
for i in range(num_batches):
min_ix=i*batch_size
max_ix=np.min([len(x_train),((i+1)*batch_size)])
x_train_batch=x_train[min_ix:max_ix]
y_train_batch=y_train[min_ix:max_ix]
train_dict={x_data:x_train_batch,y_output:y_train_batch,dropout_keep_prob:0.5}
sess.run(train_step,feed_dict=train_dict)
train_loss=sess.run(loss,feed_dict=train_dict)
test_dict={x_data:x_test,y_output:y_test,dropout_keep_prob:1.0}
test_loss=sess.run(loss,feed_dict=test_dict)


4、待补充

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120