《python深度学习》笔记---3.5、路透社数据集:多分类问题
《python深度学习》笔记---3.5、路透社数据集:多分类问题
一、总结
一句话总结:
对于文字分类,可以转化为类似one_hot的方式,也就是单词数字对应的位置为1
def vectorize_sequences(sequences, dimension=10000): results = np.zeros((len(sequences), dimension)) for i, sequence in enumerate(sequences): results[i, sequence] = 1. return results
1、将标签向量化有两种方法?
整数张量:你可以将标签列表转换为整数张量,
one-hot:或者使用one-hot 编码。
2、如果是分46类,中间层最好大于46?
信息无法被找回:对于前面用过的 Dense 层的堆叠,每层只能访问上一层输出的信息。如果某一层丢失了与 分类问题相关的一些信息,那么这些信息无法被后面的层找回,也就是说,每一层都可能成为 信息瓶颈。
维度较小的层可能成为信息瓶颈:上一个例子使用了16 维的中间层,但对这个例子来说16 维空间可能太小了,无法 学会区分 46 个不同的类别。这种维度较小的层可能成为信息瓶颈,永久地丢失相关信息。
3、多分类损失函数用分类交叉熵?
多分类的损失函数几乎总是应该使用分类交叉熵:model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['acc'])
二、路透社数据集:多分类问题
博客对应课程的视频位置:
import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
步骤
1、读取数据集
2、格式化数据集(方便数据使用)
3、构建模型
4、训练模型
5、检验模型
需求
1、读取数据集
In [2]:
(train_data, train_labels), (test_data, test_labels) = tf.keras.datasets.reuters.load_data(num_words=10000)
2、格式化数据集
格式化X数据
In [3]:
def vectorize_sequences(sequences, dimension=10000):
results = np.zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences):
results[i, sequence] = 1.
return results
In [4]:
x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)
格式化Y数据
In [5]:
print(train_labels)
In [6]:
print(max(train_labels))
In [7]:
y_train=tf.one_hot(train_labels,depth=46)
y_test=tf.one_hot(test_labels,depth=46)
print(y_train[0:2])
3、构建模型
10000->256->128->46
In [8]:
# 构建容器
model = tf.keras.Sequential()
# 输入层
model.add(tf.keras.Input(shape=(10000,)))
# 中间层
model.add(tf.keras.layers.Dense(256,activation='relu'))
model.add(tf.keras.layers.Dense(128,activation='relu'))
# 输出层
model.add(tf.keras.layers.Dense(46,activation='softmax'))
# 模型的结构
model.summary()
4、训练模型
In [9]:
# 配置优化函数和损失器
model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['acc'])
# 开始训练
history = model.fit(x_train,y_train,epochs=20,validation_data=(x_test,y_test))
In [10]:
plt.plot(history.epoch,history.history.get('loss'),'b--',label='train_loss')
plt.plot(history.epoch,history.history.get('val_loss'),'r-',label='test_loss')
plt.title("loss")
plt.legend()
plt.show()
In [11]:
plt.plot(history.epoch,history.history.get('acc'),'b--',label='train_acc')
plt.plot(history.epoch,history.history.get('val_acc'),'r-',label='test_acc')
plt.title("acc")
plt.legend()
plt.show()
5、检验模型
In [12]:
pridict_y=model.predict(x_test)
print(pridict_y)
print(y_test)
In [13]:
pridict_y = tf.argmax(pridict_y, axis=1)
print(pridict_y)
#
y_test = tf.argmax(y_test, axis=1)
print(y_test)
In [ ]: