Пожалуйста, помогите устранить неполадки моего кода на классификацию с использованием машинного обучения
модель. Выкидывает ниже ошибки. Основная суть кода заключается в обучении
модель с использованием данных IMDB для правильной классификации между положительными отзывами и
отрицательные отзывы.
File "/Users/darlingtonemeagi/Downloads/untitled14.py", line 49, in <module>
model = models.Sequential()
File "/anaconda3/lib/python3.5/site-packages/keras/engine/sequential.py", line 87, in __init__
super(Sequential, self).__init__(name=name)
File "/anaconda3/lib/python3.5/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "/anaconda3/lib/python3.5/site-packages/keras/engine/network.py", line 96, in __init__
self._init_subclassed_network(**kwargs)
File "/anaconda3/lib/python3.5/site-packages/keras/engine/network.py", line 300, in _init_subclassed_network
self._base_init(name=name)
File "/anaconda3/lib/python3.5/site-packages/keras/engine/network.py", line 110, in _base_init
self.name = name
File "/anaconda3/lib/python3.5/site-packages/keras/engine/network.py", line 322, in __setattr__
super(Network, self).__setattr__(name, value)
TypeError: super(type, obj): obj must be an instance or subtype of type"
Я посмотрел на критический код, но не смог определить причину проблемы.
from keras import models
from keras import layers
from keras.datasets import imdb
import numpy as np
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
#Vectorised the data using Hot-encode technology
def vectorise_sequence(sequences, dimension=10000):
results = np.zeros((len(sequences), dimension)) #Create zeros matrix of shape len(sequences) and dimension
for i, sequence in enumerate(sequences):
results[i, sequence] = 1 # set specific indices of results[i] to 1
return results
#Vectorise training and test data
x_train = vectorise_sequence(train_data)
x_test = vectorise_sequence(test_data)
#Also vectorising the labels which is also straight forward
y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')
#The inputs data are vectors while the output data is scalar (0 and 1)
#Set aside a validation set: Data the model has never seen before in other to monitor
#the accuracy of the model
x_val= x_train[:10000]
partial_x_train = x_train[10000:]
y_val = y_train[:10000]
partial_y_train = y_train[10000:]
#Building the Network Model
model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_size=(10000,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
#Compiling the network
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])
history = model.fit(partial_x_train, partial_y_train, epochs=20,\
batch_size=512, validation_data = (x_val,y_val))
history_dict = history.history
print(history_dict.keys())
import matplotlib.pyplot as plt
loss_values = history_dict['loss']
val_loss_values = history_dict['val_loss']
epochs = range(1, 20)
plt.plot(epochs, loss_values, 'bo', label='Training Loss')
plt.plot (epochs, val_loss_values, 'b', label='Validation Loss')
plt.title('Training and Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.Legend()
plt.show()
Ожидаемый результат является графическим представлением потерь обучения и проверки.