IIS_2023_1/belyaeva_ekaterina_lab_6/main.py

77 lines
6.3 KiB
Python
Raw Normal View History

2023-11-01 16:08:27 +04:00
import pandas as pd
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import accuracy_score, classification_report
# Чтение данных из файла Current_Pub_Meta.csv
current_pub_meta = pd.read_csv('Current_Pub_Meta.csv')
# Создаем пустой DataFrame для хранения данных
data = pd.DataFrame(columns=['Name', 'Roles', 'Primary Attribute', 'IsDurable', 'IsSupport', 'IsCarry', 'IsDisabler',
'IsInitiator', 'IsNuker', 'IsEscaper', 'IsPusher', 'posCarry', 'posMid',
'posOfflane', 'posSupport', 'posHardSupport'])
# Добавление новых столбцов из файла в датафрейм data
data['Name'] = current_pub_meta['Name']
data['Roles'] = current_pub_meta['Roles']
data['Primary Attribute'] = current_pub_meta['Primary Attribute']
data['Primary Attribute'] = data['Primary Attribute'].map({'str': 0, 'all': 1, 'int': 2, 'agi': 3})
data['IsDurable'] = data['Roles'].apply(lambda x: 1 if 'Durable' in x else 0)
data['IsCarry'] = data['Roles'].apply(lambda x: 1 if 'Carry' in x else 0)
data['IsSupport'] = data['Roles'].apply(lambda x: 1 if 'Support' in x else 0)
data['IsDisabler'] = data['Roles'].apply(lambda x: 1 if 'Disabler' in x else 0)
data['IsInitiator'] = data['Roles'].apply(lambda x: 1 if 'Initiator' in x else 0)
data['IsNuker'] = data['Roles'].apply(lambda x: 1 if 'Nuker' in x else 0)
data['IsEscaper'] = data['Roles'].apply(lambda x: 1 if 'Escaper' in x else 0)
data['IsPusher'] = data['Roles'].apply(lambda x: 1 if 'Pusher' in x else 0)
#Удаление столбца Roles
data.drop('Roles', axis=1, inplace=True)
# Создаем список персонажей на каждую позицию
roles = {
'posHardSupport': ['Undying', 'Pudge', 'Marci', 'Grimstroke', 'Elder Titan', 'Warlock', 'Dazzle', 'Witch Doctor', 'Vengeful Spirit', 'Ancient Apparition', 'Disruptor', 'Keeper of the Light', 'Rubick', 'Jakiro', 'Oracle', 'Visage', 'Silencer', 'Shadow Demon', 'Chen', 'Winter Wyvern', 'Bane', 'Treant Protector', 'Io', 'Enchantress', 'Naga Siren'],
'posSupport': ['Venomancer', 'Tusk', 'Tiny', 'Spirit Breaker', 'Techies', 'Snapfire', 'Pudge', 'Muerta', 'Marci', 'Hoodwink', 'Grimstroke', 'Earth Spirit', 'Bounty Hunter', 'Crystal Maiden', 'Lion', 'Shadow Shaman', 'Lich', 'Ogre Magi', 'Warlock', 'Dazzle', 'Witch Doctor', 'Vengeful Spirit', 'Ancient Apparition', 'Disruptor', 'Keeper of the Light', 'Rubick', 'Jakiro', 'Oracle', 'Visage', 'Silencer', 'Shadow Demon', 'Chen', 'Winter Wyvern', 'Bane', 'Treant Protector', 'Io', 'Enchantress', 'Naga Siren', 'Earthshaker', 'Skywrath Mage', 'Leshrac', 'Shadow Fiend', 'Nyx Assassin', 'Pugna', 'Lina', 'Zeus', "Nature's Prophet", 'Dark Willow'],
'posOfflane': ['Wraith King', 'Spirit Breaker', 'Snapfire', 'Pudge', 'Primal Beast', 'Marci', 'Dragon Knight', 'Tidehunter', 'Centaur Warrunner', 'Dark Seer', 'Beastmaster', 'Mars', 'Brewmaster', 'Timbersaw', 'Bristleback', 'Abaddon', 'Axe', 'Enigma', 'Sand King', 'Clockwerk', 'Doom', 'Underlord', 'Omniknight', 'Legion Commander', "Nature's Prophet", 'Slardar', 'Faceless Void', 'Earthshaker', 'Pangolier', 'Pugna', 'Mars', 'Batrider', 'Windranger', 'Mirana', 'Beastmaster', 'Brewmaster', 'Phoenix', 'Beastmaster', 'Dark Seer', 'Lone Druid', 'Timbersaw', 'Broodmother', "Nature's Prophet", 'Magnus', 'Necrophos', 'Bloodseeker', 'Lycan'],
'posMid': ['Void Spirit', 'Pudge', 'Primal Beast', 'Earth Spirit', 'Dragon Knight', 'Arc Warden', 'Invoker', 'Storm Spirit', 'Shadow Fiend', 'Templar Assassin', 'Queen of Pain', 'Puck', 'Zeus', 'Tinker', 'Lina', 'Ember Spirit', 'Outworld Destroyer', 'Morphling', 'Leshrac', 'Sniper', 'Mirana', 'Viper', 'Death Prophet', 'Razor', 'Pugna', 'Skywrath Mage', "Nature's Prophet", 'Windranger', 'Batrider', 'Lina', 'Shadow Fiend', 'Templar Assassin', 'Ember Spirit', 'Huskar', 'Kunkka', 'Puck', 'Queen of Pain', 'Invoker', 'Storm Spirit', 'Outworld Devourer', 'Death Prophet', 'Razor', 'Lina', 'Sniper', 'Medusa', 'Leshrac', 'Viper'],
'posCarry': ['Pudge', 'Muerta', 'Monkey King', 'Drow Ranger', 'Alchemist', 'Anti-Mage', 'Spectre', 'Juggernaut', 'Phantom Assassin', 'Faceless Void', 'Phantom Lancer', 'Lifestealer', 'Slark', 'Terrorblade', 'Medusa', 'Luna', 'Shadow Fiend', 'Morphling', 'Templar Assassin', 'Ember Spirit', 'Naga Siren', 'Troll Warlord', 'Gyrocopter', 'Lone Druid', 'Ursa', 'Riki', 'Sven', 'Phantom Lancer', 'Chaos Knight', 'Night Stalker', 'Wraith King', 'Meepo', 'Troll Warlord', 'Juggernaut', 'Lifestealer', 'Templar Assassin', 'Ursa', 'Clinkz', 'Weaver', 'Riki', 'Spectre', 'Phantom Assassin', 'Naga Siren', 'Luna', 'Gyrocopter', 'Meepo', 'Lone Druid', 'Slark', 'Morphling', 'Terrorblade', 'Medusa', 'Faceless Void']
}
# Перебираем каждого героя и добавляем значения в соответствующие столбцы
for index, row in data.iterrows():
for role, characters in roles.items():
data.loc[index, role] = int(row['Name'] in characters)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
print(data)
# Разделение датафрейма на признаки и метки
X = data[['Primary Attribute', 'IsDurable', 'IsSupport', 'IsCarry', 'IsDisabler', 'IsInitiator', 'IsNuker', 'IsEscaper', 'IsPusher']]
y = data[['posCarry', 'posMid', 'posOfflane', 'posSupport', 'posHardSupport']]
# Преобразование меток в числовой формат
label_encoder = LabelEncoder()
y = y.apply(label_encoder.fit_transform)
# Разделение выборки на обучающую и тестовую
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)
# Создание и обучение модели
model = MLPClassifier(hidden_layer_sizes=(128, 128, 128), activation='relu', max_iter=1000, random_state=42)
model.fit(X_train, y_train)
# Предсказание позиций для тестовой выборки
y_pred = model.predict(X_test)
# Оценка точности модели
accuracy = accuracy_score(y_test, y_pred)
class_report = classification_report(y_test, y_pred)
print("Accuracy:", accuracy)
print('Classification Report:')
print(class_report)