Модифицируй код, чтоб выводились данные прогноза от топ 20 частых Sourcehostname (…
- User
Модифицируй код, чтоб выводились данные прогноза от топ 20 частых Sourcehostname ( import json import numpy as np import plotly.graph_objs as go from plotly.subplots import make_subplots from tensorflow.keras.models import load_model
model = load_model('1.h5')
def load_data(filename, sequence_length): with open(filename, 'r') as file: data = [json.loads(line) for line in file]
sequences = [] sourcehostnames = [] for i in range(0, len(data) - sequence_length + 1): sequence = [[event['EventId'], event['ThreadId'], event['Image']] for event in data[i:i+sequence_length]] sequences.append(sequence) sourcehostnames.append(data[i + sequence_length - 1]['Sourcehostname']) return np.array(sequences), sourcehostnamessequence_length = 100 input_file_name = 'sorted_normalized_records.jsonl' test_sequences, test_sourcehostnames = load_data(input_file_name, sequence_length)
predictions = model.predict(test_sequences).flatten()
def plot_hostname_curves_with_plotly(hostnames, predictions): unique_hostnames = np.unique(hostnames) fig = make_subplots(rows=len(unique_hostnames), cols=1)
for i, hostname in enumerate(unique_hostnames, start=1): hostname_predictions = predictions[(np.array(hostnames) == hostname)] trace = go.Scatter( x=np.arange(len(hostname_predictions)), y=hostname_predictions, mode='lines', name=hostname ) fig.add_trace(trace, row=i, col=1) fig.update_layout(height=300*len(unique_hostnames), width=2200, title='Predictions by Sourcehostname', showlegend=True) fig.update_xaxes(title_text='Prediction Index') fig.update_yaxes(title_text='Prediction Value') fig.show()plot_hostname_curves_with_plotly(test_sourcehostnames, predictions) )
- Assistant
- User
NameError Traceback (most recent call last) d:\Users\PopovAI\Desktop\2\TestLearn\LeaernMain.ipynb Ячейка 10 line 3 31 filtered_predictions = [] 32 filtered_hostnames = [] ---> 33 for hostname, prediction in zip(test_sourcehostnames, predictions): 34 if hostname in top_20_hostnames: 35 filtered_predictions.append(prediction)
NameError: name 'predictions' is not defined
- Assistant
- User
ValueError Traceback (most recent call last) d:\Users\PopovAI\Desktop\2\TestLearn\LeaernMain.ipynb Ячейка 10 line 6 61 fig.update_yaxes(title_text='Prediction Value') 63 fig.show() ---> 65 plot_hostname_curves_with_plotly(test_sourcehostnames, predictions)
d:\Users\PopovAI\Desktop\2\TestLearn\LeaernMain.ipynb Ячейка 10 line 4 42 def plot_hostname_curves_with_plotly(hostnames, predictions): 43 unique_hostnames = np.unique(hostnames) ---> 44 fig = make_subplots(rows=len(unique_hostnames), cols=1) 46 for i, hostname in enumerate(unique_hostnames, start=1): 47 hostname_predictions = predictions[(hostnames == hostname)]
File ~\AppData\Roaming\Python\Python38\site-packages\plotly\subplots.py:305, in make_subplots(rows, cols, shared_xaxes, shared_yaxes, start_cell, print_grid, horizontal_spacing, vertical_spacing, subplot_titles, column_widths, row_heights, specs, insets, column_titles, row_titles, x_title, y_title, figure, **kwargs) 7 def make_subplots( 8 rows=1, 9 cols=1, (...) 26 **kwargs, 27 ) -> go.Figure: 28 """ 29 Return an instance of plotly.graph_objs.Figure with predefined subplots 30 configured in 'layout'. (...) ... 371 if not isinstance(cols, int) or cols <= 0:
- Assistant
Извините за недочёты. Ошибка
ValueErrorуказывает на то, что функцияmake_subplotsвызвана с количеством строк (rows), равным нулю. Это происходит потому что в функцииplot_hostname_curves_with_plotlyбыл вызван на пустом массиве . Причиной этого может быть отсутствие соответствующих в данных, возможно из-за ошибки в фильтрации или входных данных. - User
полный код без ошибок
- Assistant
- User
input_file_name = '23.jsonl' batch_size = 100 window_size = 100 n_features = 3
model = Sequential([ GRU(100, return_sequences=True, input_shape=(window_size, n_features)), GRU(100, return_sequences=True, input_shape=(window_size, n_features)), GRU(100, return_sequences=True, input_shape=(window_size, n_features)), GRU(100, return_sequences=True, input_shape=(window_size, n_features)), GRU(100, return_sequences=True, input_shape=(window_size, n_features)), GRU(100, return_sequences=True, input_shape=(window_size, n_features)), GRU(128, return_sequences=False), Dense(1, activation='sigmoid')
]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])train_generator = DataGenerator(filename=input_file_name, batch_size=batch_size, window_size=window_size)
model.fit(train_generator, epochs=1)
model.save('neural_network_model.h5') rfr ghfdbkmyj cltkfnm 10 эпох
- Assistant
Похоже, что в последней строке комментарий написан на смеси английского и русского языков, и есть некоторая путаница с синтаксисом. Предполагаю, что требуется заменить количество эпох обучения с 1 на 10. Вот как эта часть кода должна выглядеть:
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import GRU, Dense from my_lib import DataGenerator # Предполагаю, что DataGenerator определен в модуле my_lib input_file_name = '23.jsonl' batch_size = 100 window_size = 100 n_features = 3 model = Sequential([ GRU(100, return_sequences=True, input_shape=(window_size, n_features)), GRU(100, return_sequences=True), GRU(100, return_sequences=True), GRU(100, return_sequences=True), GRU(100, return_sequences=True), GRU(100, return_sequences=True), GRU(128, return_sequences=False), Dense(1, activation='sigmoid') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) train_generator = DataGenerator(filename=input_file_name, batch_size=batch_size, window_size=window_size) model.fit(train_generator, epochs=10) # Изменено количество эпох на 10 model.save('neural_network_model.h5')
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.