def splitset(self, train_word_num, train_label, train_size=0.9, random_state=1): self.train_X, self.test_X, train_y, test_y = train_test_split( train_word_num, train_label, train_size=0.9, random_state=1) self.Y_train = np_utils.to_categorical(train_y, self.nb_classes) self.Y_test = np_utils.to_categorical(test_y, self.nb_classes)
def score(self, x, y, **kwargs): """Returns the mean accuracy on the given test data and labels. Arguments: x: array-like, shape `(n_samples, n_features)` Test samples where n_samples in the number of samples and n_features is the number of features. y: array-like, shape `(n_samples,)` or `(n_samples, n_outputs)` True labels for x. **kwargs: dictionary arguments Legal arguments are the arguments of `Sequential.evaluate`. Returns: score: float Mean accuracy of predictions on X wrt. y. Raises: ValueError: If the underlying model isn't configured to compute accuracy. You should pass `metrics=["accuracy"]` to the `.compile()` method of the model. """ y = np.searchsorted(self.classes_, y) kwargs = self.filter_sk_params(Sequential.evaluate, kwargs) loss_name = self.model.loss if hasattr(loss_name, '__name__'): loss_name = loss_name.__name__ if loss_name == 'categorical_crossentropy' and len(y.shape) != 2: y = to_categorical(y) outputs = self.model.evaluate(x, y, **kwargs) if not isinstance(outputs, list): outputs = [outputs] for name, output in zip(self.model.metrics_names, outputs): if name == 'acc': return output raise ValueError('The model is not configured to compute accuracy. ' 'You should pass `metrics=["accuracy"]` to ' 'the `model.compile()` method.')
def score(self, x, y, **kwargs): """Returns the mean accuracy on the given test data and labels. Arguments: x: array-like, shape `(n_samples, n_features)` Test samples where `n_samples` is the number of samples and `n_features` is the number of features. y: array-like, shape `(n_samples,)` or `(n_samples, n_outputs)` True labels for `x`. **kwargs: dictionary arguments Legal arguments are the arguments of `Sequential.evaluate`. Returns: score: float Mean accuracy of predictions on `x` wrt. `y`. Raises: ValueError: If the underlying model isn't configured to compute accuracy. You should pass `metrics=["accuracy"]` to the `.compile()` method of the model. """ y = np.searchsorted(self.classes_, y) kwargs = self.filter_sk_params(Sequential.evaluate, kwargs) loss_name = self.model.loss if hasattr(loss_name, '__name__'): loss_name = loss_name.__name__ if loss_name == 'categorical_crossentropy' and len(y.shape) != 2: y = to_categorical(y) outputs = self.model.evaluate(x, y, **kwargs) if not isinstance(outputs, list): outputs = [outputs] for name, output in zip(self.model.metrics_names, outputs): if name == 'acc': return output raise ValueError('The model is not configured to compute accuracy. ' 'You should pass `metrics=["accuracy"]` to ' 'the `model.compile()` method.')
def generator(data_x, data_y, batch_size=32): n_batches = math.ceil(len(data_x) / batch_size) while True: for i in range(n_batches): start = i * batch_size end = (i + 1) * batch_size data_x_mb = data_x[start:end] data_y_mb = data_y[start:end] data_x_mb = np.array(data_x_mb).astype('float32') / 255. data_y_mb = pad_sequences(data_y_mb, dtype='int32', padding='post', value=w2i['<pad>']) data_y_mb_oh = np.array([ np_utils.to_categorical(datum_y, vocab_size) for datum_y in data_y_mb[:, 1:] ]) yield [data_x_mb, data_y_mb], data_y_mb_oh
def fit(self, x, y, **kwargs): """Constructs a new model with `build_fn` & fit the model to `(x, y)`. Arguments: x : array-like, shape `(n_samples, n_features)` Training samples where n_samples in the number of samples and n_features is the number of features. y : array-like, shape `(n_samples,)` or `(n_samples, n_outputs)` True labels for X. **kwargs: dictionary arguments Legal arguments are the arguments of `Sequential.fit` Returns: history : object details about the training history at each epoch. """ if self.build_fn is None: self.model = self.__call__(**self.filter_sk_params(self.__call__)) elif (not isinstance(self.build_fn, types.FunctionType) and not isinstance(self.build_fn, types.MethodType)): self.model = self.build_fn( **self.filter_sk_params(self.build_fn.__call__)) else: self.model = self.build_fn(**self.filter_sk_params(self.build_fn)) loss_name = self.model.loss if hasattr(loss_name, '__name__'): loss_name = loss_name.__name__ if loss_name == 'categorical_crossentropy' and len(y.shape) != 2: y = to_categorical(y) fit_args = copy.deepcopy(self.filter_sk_params(Sequential.fit)) fit_args.update(kwargs) history = self.model.fit(x, y, **fit_args) return history
def fit(self, x, y, **kwargs): """Constructs a new model with `build_fn` & fit the model to `(x, y)`. Arguments: x : array-like, shape `(n_samples, n_features)` Training samples where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like, shape `(n_samples,)` or `(n_samples, n_outputs)` True labels for `x`. **kwargs: dictionary arguments Legal arguments are the arguments of `Sequential.fit` Returns: history : object details about the training history at each epoch. """ if self.build_fn is None: self.model = self.__call__(**self.filter_sk_params(self.__call__)) elif (not isinstance(self.build_fn, types.FunctionType) and not isinstance(self.build_fn, types.MethodType)): self.model = self.build_fn( **self.filter_sk_params(self.build_fn.__call__)) else: self.model = self.build_fn(**self.filter_sk_params(self.build_fn)) loss_name = self.model.loss if hasattr(loss_name, '__name__'): loss_name = loss_name.__name__ if loss_name == 'categorical_crossentropy' and len(y.shape) != 2: y = to_categorical(y) fit_args = copy.deepcopy(self.filter_sk_params(Sequential.fit)) fit_args.update(kwargs) history = self.model.fit(x, y, **fit_args) return history
# mnist = input_data.read_data_sets('MNIST_data', one_hot=True) batch_size = 128 n_classes = 10 n_epoch = 12 # 训练轮数 img_rows, img_cols = 28, 28 n_filters = 32 poll_size = (2, 2) # 池化大小 kernel_size = (3, 3) # 卷积核大小 (train_x, train_y), (test_x, test_y) = mnist.load_data() train_x = train_x.reshape(train_x.shape[0], img_rows, img_cols, 1) test_x = test_x.reshape(test_x.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) train_x = train_x.astype('float32') test_x = test_x.astype('float32') train_x /= 255 test_x /= 255 # 将类向量转换成二进制矩阵 train_y = np_utils.to_categorical(train_y, n_classes) test_y = np_utils.to_categorical(test_y, n_classes) # 构建训练模型 model = Sequential() # 添加卷积层 model.add(Convolution2D(n_filters, kernel_size[0], kernel_size[1], border_mode='valid', input_shape=input_shape))
a0 = 0.440240602542388 a1 = -0.334501803331783 b1 = -0.198990393984879 a2 = -0.050159136439220 b2 = 0.099347477830878 w = 2 * np.pi HEART_RATES = np.linspace(55, 240, 75) NB_CLASSES = len(HEART_RATES) # prepare labels and label categories labels = np.zeros(NB_CLASSES + 1) for i in range(NB_CLASSES + 1): labels[i] = i labels_cat = np_utils.to_categorical(labels) EPOCHS = 5000 CONTINUE_TRAINING = False SAVE_ALL_MODELS = False train_loss = [] val_loss = [] train_acc = [] val_acc = [] # 1. DEFINE OR LOAD MODEL / WEIGHTS if (CONTINUE_TRAINING == False): init_batch_nb = 0 model = Sequential()