text_cnn.py
#coding:utf-8
import tensorflow as tf
import numpy as np
import pickle
class TextCNN(object):
"""
A CNN for text classification.
Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer.
"""
# sequence_length-最长词汇数
# num_classes-分类数
# vocab_size-总词汇数
# embedding_size-词向量长度
# filter_sizes-卷积核尺寸3,4,5
# num_filters-卷积核数量
# l2_reg_lambda-l2正则化系数
def __init__(
self, sequence_length, num_classes, vocab_size,
embedding_size, filter_sizes, num_filters, l2_reg_lambda=0.0):
# Placeholders for input, output and dropout
self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name="input_x")
self.input_y = tf.placeholder(tf.float32, [None, num_classes], name="input_y")
self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob")
# Keeping track of l2 regularization loss (optional)
l2_loss = tf.constant(0.0)
# Embedding layer
with tf.device('/cpu:0'), tf.name_scope("embedding"):
self.W = tf.Variable(
tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0),
name="W")
# [batch_size, sequence_length, embedding_size]
self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x)
# 添加一个维度,[batch_size, sequence_length, embedding_size, 1]
self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1)
# Create a convolution + maxpool layer for each filter size
pooled_outputs = []
for i, filter_size in enumerate(filter_sizes):
with tf.name_scope("conv-maxpool-%s" % filter_size):
# Convolution Layer
filter_shape = [filter_size, embedding_size, 1, num_filters]
W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W")
b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b")
conv = tf.nn.conv2d(
self.embedded_chars_expanded,
W,
strides=[1, 1, 1, 1],
padding="VALID",
name="conv")
# Apply nonlinearity
h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")
# Maxpooling over the outputs
pooled = tf.nn.max_pool(
h,
ksize=[1, sequence_length - filter_size + 1, 1, 1],
strides=[1, 1, 1, 1],
padding='VALID',
name="pool")
pooled_outputs.append(pooled)
# Combine all the pooled features
num_filters_total = num_filters * len(filter_sizes)
self.h_pool = tf.concat(pooled_outputs, 3)
# 把池化层输出变成一维向量
self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total])
# Add dropout
with tf.name_scope("dropout"):
self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob)
# Final (unnormalized) scores and predictions
with tf.name_scope("output"):
W = tf.get_variable(
"W",
shape=[num_filters_total, num_classes],
initializer=tf.contrib.layers.xavier_initializer())
b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b")
l2_loss += tf.nn.l2_loss(W)
l2_loss += tf.nn.l2_loss(b)
self.scores = tf.nn.softmax(tf.nn.xw_plus_b(self.h_drop, W, b, name="scores"))
self.predictions = tf.argmax(self.scores, 1, name="predictions")
# CalculateMean cross-entropy loss
with tf.name_scope("loss"):
losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.scores, labels=self.input_y)
self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss
# Accuracy
with tf.name_scope("accuracy"):
correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))
self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")
12-1 第十一周作业(未完成)
# coding: utf-8
# In[1]:
#! /usr/bin/env python
import tensorflow as tf
import numpy as np
import os
import time
import datetime
import data_helpers
from text_cnn import TextCNN
from tensorflow.contrib import learn
from six.moves import xrange
import pickle
# In[2]:
# Parameters
# ==================================================
# Data loading params
# validation数据集占比
tf.flags.DEFINE_float("dev_sample_percentage", .1, "Percentage of the training data to use for validation")
# 正样本
tf.flags.DEFINE_string("positive_data_file", "./data/rt-polaritydata/rt-polarity.pos", "Data source for the positive data.")
# 负样本
tf.flags.DEFINE_string("negative_data_file", "./data/rt-polaritydata/rt-polarity.neg", "Data source for the negative data.")
# Model Hyperparameters
# 词向量长度
tf.flags.DEFINE_integer("embedding_dim", 128, "Dimensionality of character embedding (default: 128)")
# 卷积核大小
tf.flags.DEFINE_string("filter_sizes", "3,4,5", "Comma-separated filter sizes (default: '3,4,5')")
# 每一种卷积核个数
tf.flags.DEFINE_integer("num_filters", 64, "Number of filters per filter size (default: 128)")
# dropout参数
tf.flags.DEFINE_float("dropout_keep_prob", 0.5, "Dropout keep probability (default: 0.5)")
# l2正则化参数
tf.flags.DEFINE_float("l2_reg_lambda", 0.0005, "L2 regularization lambda (default: 0.0)")
# Training parameters
# 批次大小
tf.flags.DEFINE_integer("batch_size", 64, "Batch Size (default: 64)")
# 迭代周期
tf.flags.DEFINE_integer("num_epochs", 6, "Number of training epochs (default: 200)")
# 多少step测试一次
tf.flags.DEFINE_integer("evaluate_every", 100, "Evaluate model on dev set after this many steps (default: 100)")
# 多少step保存一次模型
tf.flags.DEFINE_integer("checkpoint_every", 100, "Save model after this many steps (default: 100)")
# 最多保存多少个模型
tf.flags.DEFINE_integer("num_checkpoints", 5, "Number of checkpoints to store (default: 5)")
# Misc Parameters
# tensorFlow 会自动选择一个存在并且支持的设备来运行 operation
tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement")
# 获取你的 operations 和 Tensor 被指派到哪个设备上运行
tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices")
# flags解析
FLAGS = tf.flags.FLAGS
#FLAGS._parse_flags()
FLAGS.flag_values_dict()
# 打印所有参数
print("\nParameters:")
for attr, value in sorted(FLAGS.__flags.items()):
print("{}={}".format(attr.upper(), value))
print("")
# In[3]:
# Load data
print("Loading data...")
# 读入预处理过后的数据和标签
x_text, y = data_helpers.load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file)
# 一行数据最多的词汇数
max_document_length = max([len(x.split(" ")) for x in x_text])
print("max_document_length:",max_document_length)
text = np.array([x.split(" ") for x in x_text])
print("text:",text[:5])
# In[4]:
with open('w2v_dict.pickle', 'rb') as f:
w2v_dict = pickle.load(f)
x = []
for line in text:
line_len = len(line)
text2num = []
for i in xrange(max_document_length):
if(i < line_len):
try:
text2num.append(w2v_dict[line[i]]) # 把词转为数字
except:
text2num.append(0) # 没有对应的词
else:
text2num.append(0) # 填充0
x.append(text2num)
x = np.array(x)
# In[5]:
print("x_shape:",x.shape)
print("y_shape:",y.shape)
# Randomly shuffle data
np.random.seed(10)
shuffle_indices = np.random.permutation(np.arange(len(y)))
x_shuffled = x[shuffle_indices]
y_shuffled = y[shuffle_indices]
# Split train/test set
# TODO: This is very crude, should use cross-validation
# 数据集切分为两部分
dev_sample_index = -1 * int(FLAGS.dev_sample_percentage * float(len(y)))
x_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:]
y_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:]
print("Train/Dev split: {:d}/{:d}".format(len(y_train), len(y_dev)))
print("x:",x_train[0:5])
print("y:",y_train[0:5])
# In[6]:
# Training
# ==================================================
with tf.Graph().as_default():
session_conf = tf.ConfigProto(
allow_soft_placement=FLAGS.allow_soft_placement,
log_device_placement=FLAGS.log_device_placement)
sess = tf.Session(config=session_conf)
with sess.as_default():
cnn = TextCNN(
sequence_length=x_train.shape[1],
num_classes=y_train.shape[1],
vocab_size=len(w2v_dict),
embedding_size=FLAGS.embedding_dim,
filter_sizes=list(map(int, FLAGS.filter_sizes.split(","))),
num_filters=FLAGS.num_filters,
l2_reg_lambda=FLAGS.l2_reg_lambda)
# Define Training procedure
global_step = tf.Variable(0, name="global_step", trainable=False)
optimizer = tf.train.AdamOptimizer(1e-3)
# 计算梯度
grads_and_vars = optimizer.compute_gradients(cnn.loss)
# 将计算出的梯度应用到变量上,是函数minimize()的第二部分,
# 返回一个应用指定的梯度的操作Operation,对global_step做自增操作
train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)
# Keep track of gradient values and sparsity (optional)
grad_summaries = []
for g, v in grads_and_vars:
if g is not None:
grad_hist_summary = tf.summary.histogram("{}/grad/hist".format(v.name), g)
sparsity_summary = tf.summary.scalar("{}/grad/sparsity".format(v.name), tf.nn.zero_fraction(g))
grad_summaries.append(grad_hist_summary)
grad_summaries.append(sparsity_summary)
grad_summaries_merged = tf.summary.merge(grad_summaries)
# Output directory for models and summaries
# 定义输出路径
timestamp = str(int(time.time()))
out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", timestamp))
print("Writing to {}\n".format(out_dir))
# Summaries for loss and accuracy
loss_summary = tf.summary.scalar("loss", cnn.loss)
acc_summary = tf.summary.scalar("accuracy", cnn.accuracy)
# Train Summaries
train_summary_op = tf.summary.merge([loss_summary, acc_summary, grad_summaries_merged])
train_summary_dir = os.path.join(out_dir, "summaries", "train")
train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph)
# Dev summaries
dev_summary_op = tf.summary.merge([loss_summary, acc_summary])
dev_summary_dir = os.path.join(out_dir, "summaries", "dev")
dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)
# Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it
checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints"))
checkpoint_prefix = os.path.join(checkpoint_dir, "model")
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.num_checkpoints)
# Initialize all variables
sess.run(tf.global_variables_initializer())
def train_step(x_batch, y_batch):
"""
A single training step
"""
feed_dict = {
cnn.input_x: x_batch,
cnn.input_y: y_batch,
cnn.dropout_keep_prob: FLAGS.dropout_keep_prob
}
_, step, summaries, loss, accuracy = sess.run(
[train_op, global_step, train_summary_op, cnn.loss, cnn.accuracy],
feed_dict)
time_str = datetime.datetime.now().isoformat()
if (step%10==0):
print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy))
train_summary_writer.add_summary(summaries, step)
def dev_step(x_batch, y_batch, writer=None):
"""
Evaluates model on a dev set
"""
feed_dict = {
cnn.input_x: x_batch,
cnn.input_y: y_batch,
cnn.dropout_keep_prob: 1.0
}
step, summaries, loss, accuracy = sess.run(
[global_step, dev_summary_op, cnn.loss, cnn.accuracy],
feed_dict)
time_str = datetime.datetime.now().isoformat()
print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy))
if writer:
writer.add_summary(summaries, step)
# Generate batches
batches = data_helpers.batch_iter(
list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs)
# Training loop. For each batch...
for batch in batches:
x_batch, y_batch = zip(*batch)
train_step(x_batch, y_batch)
current_step = tf.train.global_step(sess, global_step)
# 测试
if current_step % FLAGS.evaluate_every == 0:
print("\nEvaluation:")
dev_step(x_dev, y_dev, writer=dev_summary_writer)
print("")
# 保存模型
if current_step % FLAGS.checkpoint_every == 0:
path = saver.save(sess, checkpoint_prefix, global_step=current_step)
print("Saved model checkpoint to {}\n".format(path))
# In[ ]:
缺少文件:
Traceback (most recent call last):
File “C:/Users/SSC/PycharmProjects/test20191011/12-1第十一周作业.py”, line 79, in
x_text, y = data_helpers.load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file)
File “C:\Users\SSC\PycharmProjects\test20191011\data_helpers.py”, line 39, in load_data_and_labels
positive_examples = list(open(positive_data_file, “r”, encoding=“utf-8”).readlines())
FileNotFoundError: [Errno 2] No such file or directory: ‘./data/rt-polaritydata/rt-polarity.pos’
12-2 声音分类(未完成)
# coding: utf-8
# 数据集:https://serv.cusp.nyu.edu/projects/urbansounddataset/
#
# librosa:https://github.com/librosa/librosa
#
# 分类:
# 0 = air_conditioner
# 1 = car_horn
# 2 = children_playing
# 3 = dog_bark
# 4 = drilling
# 5 = engine_idling
# 6 = gun_shot
# 7 = jackhammer
# 8 = siren
# 9 = street_music
# In[1]:
import os
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import time
import librosa # pip install librosa
from tqdm import tqdm # pip install tqdm
import random
# In[2]:
# Parameters
# ==================================================
# Data loading params
# validation数据集占比
tf.flags.DEFINE_float("dev_sample_percentage", .2, "Percentage of the training data to use for validation")
# 父目录
tf.flags.DEFINE_string("parent_dir", "audio/", "Data source for the data.")
# 子目录
tf.flags.DEFINE_string("tr_sub_dirs", ['fold1/','fold2/','fold3/'], "Data source for the data.")
# Model Hyperparameters
# 第一层输入,MFCC信号
tf.flags.DEFINE_integer("n_inputs", 40, "Number of MFCCs (default: 40)")
# cell个数
tf.flags.DEFINE_string("n_hidden", 300, "Number of cells (default: 300)")
# 分类数
tf.flags.DEFINE_integer("n_classes", 10, "Number of classes (default: 10)")
# 学习率
tf.flags.DEFINE_integer("lr", 0.005, "Learning rate (default: 0.005)")
# dropout参数
tf.flags.DEFINE_float("dropout_keep_prob", 0.5, "Dropout keep probability (default: 0.5)")
# Training parameters
# 批次大小
tf.flags.DEFINE_integer("batch_size", 50, "Batch Size (default: 50)")
# 迭代周期
tf.flags.DEFINE_integer("num_epochs", 100, "Number of training epochs (default: 100)")
# 多少step测试一次
tf.flags.DEFINE_integer("evaluate_every", 50, "Evaluate model on dev set after this many steps (default: 50)")
# 多少step保存一次模型
tf.flags.DEFINE_integer("checkpoint_every", 500, "Save model after this many steps (default: 500)")
# 最多保存多少个模型
tf.flags.DEFINE_integer("num_checkpoints", 2, "Number of checkpoints to store (default: 2)")
# flags解析
FLAGS = tf.flags.FLAGS
FLAGS._parse_flags()
# 打印所有参数
print("\nParameters:")
for attr, value in sorted(FLAGS.__flags.items()):
print("{}={}".format(attr.upper(), value))
print("")
# In[3]:
# 获得训练用的wav文件路径列表
def get_wav_files(parent_dir,sub_dirs):
wav_files = []
for l, sub_dir in enumerate(sub_dirs):
wav_path = os.path.join(parent_dir, sub_dir)
for (dirpath, dirnames, filenames) in os.walk(wav_path):
for filename in filenames:
if filename.endswith('.wav') or filename.endswith('.WAV'):
filename_path = os.sep.join([dirpath, filename])
wav_files.append(filename_path)
return wav_files
# 获取文件mfcc特征和对应标签
def extract_features(wav_files):
inputs = []
labels = []
for wav_file in tqdm(wav_files):
# 读入音频文件
audio,fs = librosa.load(wav_file)
# 获取音频mfcc特征
# [n_steps, n_inputs]
mfccs = np.transpose(librosa.feature.mfcc(y=audio, sr=fs, n_mfcc=FLAGS.n_inputs), [1,0])
inputs.append(mfccs.tolist())
#获取label
for wav_file in wav_files:
label = wav_file.split('/')[-1].split('-')[1]
labels.append(label)
return inputs, np.array(labels, dtype=np.int)
# In[4]:
# 获得训练用的wav文件路径列表
wav_files = get_wav_files(FLAGS.parent_dir,FLAGS.tr_sub_dirs)
# 获取文件mfcc特征和对应标签
tr_features,tr_labels = extract_features(wav_files)
np.save('tr_features.npy',tr_features)
np.save('tr_labels.npy',tr_labels)
# tr_features=np.load('tr_features.npy')
# tr_labels=np.load('tr_labels.npy')
# In[5]:
#(batch,step,input)
#(50,173,40)
# 计算最长的step
wav_max_len = max([len(feature) for feature in tr_features])
print("max_len:",wav_max_len)
# 填充0
tr_data = []
for mfccs in tr_features:
while len(mfccs) < wav_max_len: #只要小于wav_max_len就补n_inputs个0
mfccs.append([0] * FLAGS.n_inputs)
tr_data.append(mfccs)
tr_data = np.array(tr_data)
# In[6]:
# Randomly shuffle data
np.random.seed(10)
shuffle_indices = np.random.permutation(np.arange(len(tr_data)))
x_shuffled = tr_data[shuffle_indices]
y_shuffled = tr_labels[shuffle_indices]
# Split train/test set
# TODO: This is very crude, should use cross-validation
# 数据集切分为两部分
dev_sample_index = -1 * int(FLAGS.dev_sample_percentage * float(len(y_shuffled)))
train_x, test_x = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:]
train_y, test_y = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:]
# In[7]:
# placeholder
x = tf.placeholder("float", [None, wav_max_len, FLAGS.n_inputs])
y = tf.placeholder("float", [None])
dropout = tf.placeholder(tf.float32)
# learning rate
lr = tf.Variable(FLAGS.lr, dtype=tf.float32, trainable=False)
# 定义RNN网络
# 初始化权制和偏置
weights = tf.Variable(tf.truncated_normal([FLAGS.n_hidden, FLAGS.n_classes], stddev=0.1))
biases = tf.Variable(tf.constant(0.1, shape=[FLAGS.n_classes]))
# 多层网络
num_layers = 3
def grucell():
cell = tf.contrib.rnn.GRUCell(FLAGS.n_hidden)
# cell = tf.contrib.rnn.LSTMCell(FLAGS.n_hidden)
cell = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=dropout)
return cell
cell = tf.contrib.rnn.MultiRNNCell([grucell() for _ in range(num_layers)])
outputs,final_state = tf.nn.dynamic_rnn(cell,x,dtype=tf.float32)
# 预测值
prediction = tf.nn.softmax(tf.matmul(final_state[0],weights) + biases)
# labels转one_hot格式
one_hot_labels = tf.one_hot(indices=tf.cast(y, tf.int32), depth=FLAGS.n_classes)
# loss
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=one_hot_labels))
# optimizer
optimizer = tf.train.AdamOptimizer(learning_rate=lr).minimize(cross_entropy)
# Evaluate model
correct_pred = tf.equal(tf.argmax(prediction,1), tf.argmax(one_hot_labels,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# In[8]:
def batch_iter(data, batch_size, num_epochs, shuffle=True):
"""
Generates a batch iterator for a dataset.
"""
data = np.array(data)
data_size = len(data)
# 每个epoch的num_batch
num_batches_per_epoch = int((len(data) - 1) / batch_size) + 1
print("num_batches_per_epoch:",num_batches_per_epoch)
for epoch in range(num_epochs):
# Shuffle the data at each epoch
if shuffle:
shuffle_indices = np.random.permutation(np.arange(data_size))
shuffled_data = data[shuffle_indices]
else:
shuffled_data = data
for batch_num in range(num_batches_per_epoch):
start_index = batch_num * batch_size
end_index = min((batch_num + 1) * batch_size, data_size)
yield shuffled_data[start_index:end_index]
# In[9]:
# Initializing the variables
init = tf.global_variables_initializer()
# 定义saver
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
# Generate batches
batches = batch_iter(list(zip(train_x, train_y)), FLAGS.batch_size, FLAGS.num_epochs)
for i,batch in enumerate(batches):
i = i + 1
x_batch, y_batch = zip(*batch)
sess.run([optimizer], feed_dict={x: x_batch, y: y_batch, dropout: FLAGS.dropout_keep_prob})
# 测试
if i % FLAGS.evaluate_every == 0:
sess.run(tf.assign(lr, FLAGS.lr * (0.99 ** (i // FLAGS.evaluate_every))))
learning_rate = sess.run(lr)
tr_acc, _loss = sess.run([accuracy, cross_entropy], feed_dict={x: train_x, y: train_y, dropout: 1.0})
ts_acc = sess.run(accuracy, feed_dict={x: test_x, y: test_y, dropout: 1.0})
print("Iter {}, loss {:.5f}, tr_acc {:.5f}, ts_acc {:.5f}, lr {:.5f}".format(i, _loss, tr_acc, ts_acc, learning_rate))
# 保存模型
if i % FLAGS.checkpoint_every == 0:
path = saver.save(sess, "sounds_models/model", global_step=i)
print("Saved model checkpoint to {}\n".format(path))
# In[ ]:
报错如下:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File “C:/Users/SSC/PycharmProjects/test20191011/12声音分类.py”, line 43, in
tf.flags.DEFINE_string(“tr_sub_dirs”, [‘fold1/’,‘fold2/’,‘fold3/’], “Data source for the data.”)
File “D:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\platform\flags.py”, line 58, in wrapper
return original_function(*args, **kwargs)
File “D:\ProgramData\Anaconda3\lib\site-packages\absl\flags_defines.py”, line 241, in DEFINE_string
DEFINE(parser, name, default, help, flag_values, serializer, **args)
File “D:\ProgramData\Anaconda3\lib\site-packages\absl\flags_defines.py”, line 81, in DEFINE
DEFINE_flag(_flag.Flag(parser, serializer, name, default, help, **args),
File “D:\ProgramData\Anaconda3\lib\site-packages\absl\flags_flag.py”, line 110, in init
self._set_default(default)
File “D:\ProgramData\Anaconda3\lib\site-packages\absl\flags_flag.py”, line 216, in _set_default
self.default = self._parse(value)
File “D:\ProgramData\Anaconda3\lib\site-packages\absl\flags_flag.py”, line 184, in _parse
‘flag --%s=%s: %s’ % (self.name, argument, e))
absl.flags._exceptions.IllegalFlagValueError: flag --tr_sub_dirs=[‘fold1/’, ‘fold2/’, ‘fold3/’]: flag value must be a string, found “<class ‘list’>”
Process finished with exit code 1