напиши примеры для тестирования кода для упражнения from abc import ABC, abstractmethod…
- User
напиши примеры для тестирования кода для упражнения from abc import ABC, abstractmethod import datetime
Абстрактный класс публикации
class Publication(ABC): def init(self, title, author, publish_year): self.title = title self.author = author self.publish_year = publish_year self.is_available = True
code@abstractmethod def display_info(self): """ Display essential information about the publication. This method must be overridden by each subclass. """ raise NotImplementedError("Subclasses must override display_info()")Классы конкретных изданий
class Book(Publication): def init(self, title, author, publish_year, genre): super().init(title, author, publish_year) self.genre = genre
codedef display_info(self): print(f"Book: {self.title} by {self.author}, Genre: {self.genre}, Year: {self.publish_year}")class Journal(Publication): def init(self, title, author, publish_year, issue_number): super().init(title, author, publish_year) self.issue_number = issue_number
codedef display_info(self): print(f"Journal: {self.title}, Issue: {self.issue_number}")class Newspaper(Publication): def init(self, title, publish_year, date): super().init(title, None, publish_year) self.date = date
codedef display_info(self): print(f"Newspaper: {self.title}, Date: {self.date}")Класс пользователя
class User: def init(self, user_id, name): self.user_id = user_id self.name = name self.borrowed_items = []
codedef borrow_item(self, item): self.borrowed_items.append(item) item.is_available = False def return_item(self, item): self.borrowed_items.remove(item) item.is_available = TrueКласс библиотеки
class Library: def init(self): self.users = {} self.publications = []
- Assistant
Для тестирования приведенного кода мы могли бы создать несколько сценариев использования классов, а также проверить их взаимодействие. Вот примеры тестовых случаев:
- User
ты тут?
- Assistant
Да, я здесь! Как я могу помочь вам сегодня?
- User
Преобразование даты
df['year'] = df['date'].dt.year df['month'] = df['date'].dt.month df['day'] = df['date'].dt.day df['weekday'] = df['date'].dt.weekday
Кодирование категориальной переменной
ohe = OneHotEncoder(sparse=False, drop='first') encoded_features = ohe.fit_transform(df[['airport_arrival']]) encoded_df = pd.DataFrame(encoded_features, columns=ohe.get_feature_names_out(['airport_arrival'])) encoded_df.index = df.index df_ml = pd.concat([df, encoded_df], axis=1)
Подготовка данных для обучения
y = df_ml['price_index'] X = df_ml.drop(['price_index', 'airport_arrival', 'date'], axis=1) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
GradientBoostingRegressor
model = GradientBoostingRegressor(n_estimators=200, learning_rate=0.2, max_depth=2, random_state=42) model.fit(X_train, y_train)
predictions = model.predict(X_test) rmse = np.sqrt(mean_squared_error(y_test, predictions)) print(f'RMSE: {rmse}')
plt.figure(figsize=(10, 5)) plt.scatter(y_test, predictions, alpha=0.5) plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r') # Линия идеального прогноза plt.title('Сравнение тестовых и предсказанных значений') plt.xlabel('Реальные значения') plt.ylabel('Предсказания') plt.show()
- Assistant
- User
- Assistant
- User
так выглядит датафрейм df airport_arrival date price_index year month day weekday 0 Абакан 2022-05-18 1.000000 2022 5 18 2 1 Абакан 2022-05-25 1.000000 2022 5 25 2 2 Абакан 2022-06-01 1.301353 2022 6 1 2 3 Абакан 2022-06-08 1.301353 2022 6 8 2 4 Абакан 2022-06-15 0.638513 2022 6 15 2 ... ... ... ... ... ... ... ... 3217 Якутск 2023-11-29 1.615152 2023 11 29 2 3218 Якутск 2023-12-06 1.143804 2023 12 6 2 3219 Якутск 2023-12-13 1.143804 2023 12 13 2 3220 Якутск 2023-12-20 1.143804 2023 12 20 2 3221 Якутск 2023-12-27 1.192053 2023 12 27 2
выполнил этот код
Кодирование категориальной переменной
ohe = OneHotEncoder(sparse=False, drop='first') encoded_features = ohe.fit_transform(df[['airport_arrival']]) encoded_df = pd.DataFrame(encoded_features, columns=ohe.get_feature_names_out(['airport_arrival'])) encoded_df.index = df.index df_ml = pd.concat([df, encoded_df], axis=1)
Подготовка данных для обучения
y = df_ml['price_index'] X = df_ml.drop(['price_index', 'airport_arrival', 'date'], axis=1) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = GradientBoostingRegressor(n_estimators=200, learning_rate=0.2, max_depth=2, random_state=42) model.fit(X_train, y_train)
- Assistant