二分类问题
Posted strategist-614
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分类问题相关的知识,希望对你有一定的参考价值。
二分类问题
首先进行数据处理:
将读入的数据转成向量,将整数序列编码为二维矩阵
def v(sequences, dimension=10000):
results = np.zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences):
results[i, sequence] = 1.
return results
x_train = v(train_data)
x_test = v(test_data)
标签同时也要向量化:
y_train = np.asarray(train_labels).astype(‘float32‘)
y_test = np.asarray(test_labels).astype(‘float32‘)
初始化、编译、添加层
model = models.Sequential()
model.add(layers.Dense(16,activation=‘relu‘,input_shape=(10000,)))
model.add(layers.Dense(16,activation=‘relu‘))
model.add(layers.Dense(1,activation=‘sigmoid‘))
model.compile(optimizer=‘rmsprop‘,loss=‘binary_crossentropy‘,metrics=[‘accuracy‘])
model.fit(x_train,y_train,epochs=4,batch_size=512)
results = model.evaluate(x_test,y_test)
binary_crossentropy
作为二分类的损失函数
metrics=[‘accuracy‘]
监控精度
optimizer=‘rmsprop‘
作为优化器
import tensorflow as tf
import numpy as np
from keras.datasets import imdb
from keras import models
from keras import layers
def v(sequences, dimension=10000):
results = np.zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences):
results[i, sequence] = 1.
return results
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
x_train = v(train_data)
x_test = v(test_data)
y_train = np.asarray(train_labels).astype(‘float32‘)
y_test = np.asarray(test_labels).astype(‘float32‘)
model = models.Sequential()
model.add(layers.Dense(16,activation=‘relu‘,input_shape=(10000,)))
model.add(layers.Dense(16,activation=‘relu‘))
model.add(layers.Dense(1,activation=‘sigmoid‘))
model.compile(optimizer=‘rmsprop‘,loss=‘mse‘,metrics=[‘accuracy‘])
model.fit(x_train,y_train,epochs=4,batch_size=512)
results = model.evaluate(x_test,y_test)
以上是关于二分类问题的主要内容,如果未能解决你的问题,请参考以下文章
火炉炼AI深度学习005-简单几行Keras代码解决二分类问题