Simple prediction model in Python

Demystifying machine learning through hands-on collaboration with chatGPT: A journey from uncertainty to mastery, exploring RandomForest and LogisticRegression for practical football predictions.

I’ve been dabbling around in machine learning for a while by doing boot camps, and reading articles but truth be told, it never really sunk in how one can create a practical model you understand without just copy-paste and clicking the run button.

I did not do this by myself if I have to be completely honest. I have to thank my coding buddy chatGPT for patiently listening and working with me until I was able to successfully create the prediction model.

To be able to argue with chatGPT until you get to the right place and have the correct implementation is incredible and one achieves a higher learning experience because you and chatGPT have to figure it out together. chatGPT was not able to give me the answer straight away. It took some time and collaboration to come to the correct code.

The Model

I’ve been dabbling around in data science for a while by doing boot camps and reading articles. Truth be told, it never really sunk in how one can create a practical model you understand without just copy-paste and clicking the run button.

I did not do this by myself if I have to be completely honest. I have to thank my coding buddy chatGPT for patiently listening and working with me until I was able to successfully create the prediction model.

Out of curiosity, I’m employing two models to contrast outcomes for increased insight and thoroughness.

Some important components

LogisticRegression is a statistical method used for binary classification, a type of predictive analysis. It’s particularly well-suited for scenarios where the outcome is dichotomous, meaning there are only two possible classes.

RandomForestClassifier is an ensemble of decision trees, typically using bagging. It creates multiple decision trees and merges them together to get a more accurate and stable prediction.

Bagging, or Bootstrap Aggregating, is an ensemble learning technique used to improve the stability and accuracy of machine learning models by training multiple models on different bootstrap samples (subsets with replacement) of the dataset and then aggregating their predictions, typically through averaging or majority voting. This approach is particularly effective with high-variance models like decision trees, reducing overfitting and leading to more robust and reliable predictions.

I decided to use both these regressions for this example to investigate how it works and what the differences in accuracy and results are. Let’s dive in, shall we?

The Code

The packages we require for this are scikit-learn and Pandas

pip install scikit-learn, pandas

Alternatively, add these into a requirements.txt row separated and run the following command

pip install -r requirements.txt

I will load the fifa_football_results.csv, which includes 45,000 current football results, into a pandas DataFrame.

df = pd.read_csv("fifa_football_results.csv")

Create a target variable representing the match outcome for the home team

df['home_team_result'] = df.apply(lambda row: 'win' if row['home_score'] > row['away_score'] else ('lose' if row['home_score'] < row['away_score'] else 'draw'), axis=1)

This is the part where we find the input and output columns and encode them for the models to process. LabelEncoder is a straightforward tool for converting categorical text data into numerical form, making it suitable for use in various machine learning models, especially for encoding target variables.

label_encoder = LabelEncoder()
df['home_team_result_encoded'] = label_encoder.fit_transform(df['home_team_result'])

Next, we select the feature columns. We are using home_team and away_team for input and the home_team_result_encoded as output to predict which home_team is most likely to win.

X = df[['home_team', 'away_team']]
y = df['home_team_result_encoded']

This code creates an instance of OneHotEncoder to transform categorical data in X into a binary matrix, representing each category with a unique combination of zeros and ones, and then constructing a new DataFrame X_encoded with these transformed features, each named after its corresponding category.

encoder = OneHotEncoder(sparse=False)
X_encoded = pd.DataFrame(encoder.fit_transform(X), columns=encoder.get_feature_names_out(X.columns))

This code splits the dataset into training and testing subsets: X_train and y_train are the features and labels for training, while X_test and y_test are for testing. It allocates 80% of the data for training and 20% for testing, with a fixed random state for reproducibility.

X_train, X_test, y_train, y_test = train_test_split(X_encoded, y, test_size=0.2, random_state=42)


This code trains two machine learning models, Logistic Regression and Random Forest Classifier, on a training dataset (X_train, y_train). It then uses these models to predict outcomes on a separate test dataset (X_test).

The accuracy and detailed performance metrics of each model’s predictions are computed and displayed, using the actual test labels (y_test). This allows for a comparison of the effectiveness of the Logistic Regression and Random Forest models for the given data.

classifier_log = LogisticRegression(max_iter=100)
classifier_log.fit(X_train, y_train)

classifier_rfc = RandomForestClassifier(n_estimators=50, max_depth=100, n_jobs=-1)
classifier_rfc.fit(X_train, y_train)

y_pred_log = classifier_log.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred_log))
print("LogR Classification Report:\n", classification_report(y_test, y_pred_log))


y_pred_rfc = classifier_rfc.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred_rfc))
print("RFC Classification Report:\n", classification_report(y_test, y_pred_rfc))


These two methods, predict_match_log and predict_match_rfc, are designed to predict the outcome of a match between two teams using Logistic Regression and Random Forest Classifier models, respectively.

Both methods take the names of the home and away teams as input, encode these names using a predefined encoder, and then use their respective trained models (classifier_log for Logistic Regression, classifier_rfc for Random Forest) to predict the match outcome. The predicted results, initially in encoded form, are then transformed back to their original label form using label_encoder, and the final predicted outcome is returned.


def predict_match_log(home_team, away_team):
    new_input = pd.DataFrame({'home_team': [home_team], 'away_team': [away_team]})
    new_input_encoded = pd.DataFrame(encoder.transform(new_input), columns=encoder.get_feature_names_out(X.columns))
    
    predicted_result_encoded = classifier_log.predict(new_input_encoded)
    predicted_result = label_encoder.inverse_transform(predicted_result_encoded)
    return predicted_result[0]


def predict_match_rfc(home_team, away_team):
    new_input = pd.DataFrame({'home_team': [home_team], 'away_team': [away_team]})
    new_input_encoded = pd.DataFrame(encoder.transform(new_input), columns=encoder.get_feature_names_out(X.columns))
    
    predicted_result_encoded = classifier_rfc.predict(new_input_encoded)
    predicted_result = label_encoder.inverse_transform(predicted_result_encoded)
    return predicted_result[0]

We are going to use as input two teams, a home team, and an away team. It does not matter if this is a natural ground for the sake of the exercise the team being entered first is the home team and also the result of the prediction.

home_team_input = input('Enter your home team: ')
away_team_input = input('Enter your away team: ')

predicted_outcome_log = predict_match_log(home_team_input, away_team_input)
predicted_outcome_rfc = predict_match_rfc(home_team_input, away_team_input)

print("Predicted Result for the home team:", predicted_outcome_log)
print("Predicted Result for the home team:", predicted_outcome_rfc)

The Result

The whole point of the exercise besides predicting a winner was to understand which model would work best for this data using standard configuration. I don’t have the skill or the computing power to optimize these models.

LogisticRegression has a higher accuracy in predicting the winner with 57% compared to the 52% for RandomForestClassifier. The latter would be better for more complex predictions, and that is why the former has a higher accuracy—it is better to work with less complex datasets and predictions.

I’m going to use the following sets of 2 teams to run the model. I’m expecting the first

  • England vs Norway
  • Argentina vs Brazil
  • South Africa vs Wales

In the first matchup, I expect England to win. It is also worth noting that these teams have played against each other in the past. The second matchup I expect to be very close and I cannot predict who will be the winner. This should be the more fun exercise. Lastly, I chose two teams who have never played against each other.

…and the winner is

England vs Norway

Winner: England

Argentina vs Brazil

Winner: Argentina

South Africa vs Wales

Winner: Wales

Conclusion

It was a fun first outing and a completely different experience from doing boot camps like kaggle.com and datacamp.com for example. With no knowledge of these models and machine learning functions I had to start from scratch and with some guidance from chatGPT, I was able to get to the correct starting point which always takes the longest.

With chatGPT solving all our problems, it is still worth understanding the basics of machine learning. That is what I am to do while. Organizations still need to crunch very large datasets for new analytics and insights.

Please find my code repository on Github

715 responses to “Simple prediction model in Python”

  1. Lorand Expert va pune la dispozi?ie [url=https://lorandexpert.com/]servicii contabilitate Moldova[/url] adaptate cerin?elor afacerii dumneavoastra. De la contabilitate primara pana la consultan?a fiscala, oferim solu?ii complete pentru o administrare financiara impecabila.

  2. Хотите мгновенно решить финансовые проблемы? Оформите [url=https://mikro-zaim-online.ru/]займы новые онлайн малоизвестные без отказа[/url] до 30 000 рублей. Быстро, просто и доступно для всех!

  3. Приветствую, друзья!
    Нужен совет по лечению генитальных бородавок.
    Генитальные бородавки — неприятная проблема, которая требует правильного подхода к лечению.
    Мне посоветовали несколько подходов: от лекарственных препаратов до аппаратных процедур.
    Кто-то может рассказать, как избежать рецидива после лечения бородавок?
    Пока что выбираю между мазями и лазерной терапией — интересно узнать, что лучше.
    Есть ли риск заражения партнера после лечения?
    Благодарю за внимание и любую информацию, которую вы можете предоставить!
    как выглядят генитальные бородавки [url=http://genitalnyeborodavki.ru/#как-выглядят-генитальные-бородавки]http://genitalnyeborodavki.ru/[/url] .

  4. 1XBET promo code 2025: 1XMAX25 – Use bonus code get for VIP bonuses – up to €19502 + 150 free spins on casino and 100% up to €130 on sportsbook! To get your Free Bet, new customers can register with 1xbet for free, and enter the promo code 1x. Take a look at our site banners for the latest 1xBet promo codes and information about the brand’s 100% first deposit bonus where you live. New players can enjoy an exclusive deposit bonus when they sign up at 1xBet. See our site banners for the latest welcome deals at 1xBet for your region.

    1xbet official promo code bangladesh

  5. диплом о среднем техническом образовании купить [url=https://2orik-diploms.ru/]диплом о среднем техническом образовании купить[/url] .

  6. купить диплом о среднем образовании в тюмени [url=https://prema-diploms.ru/]купить диплом о среднем образовании в тюмени[/url] .

  7. купить диплом о среднем образовании цена [url=https://2orik-diploms.ru/]купить диплом о среднем образовании цена[/url] .

  8. купить диплом гознак недорого [url=https://2orik-diploms.ru/]купить диплом гознак недорого[/url] .

  9. бланк диплома о высшем образовании ссср купить [url=https://prema-diploms.ru/]prema-diploms.ru[/url] .

  10. купить государственный диплом [url=https://2orik-diploms.ru/]купить государственный диплом[/url] .

  11. What i do not understood is in truth how you’re not really a
    lot more smartly-appreciated than you might be now. You’re
    very intelligent. You already know therefore considerably on the subject of
    this subject, made me personally consider it from so many various angles.
    Its like men and women don’t seem to be interested unless it’s something to accomplish with
    Lady gaga! Your own stuffs outstanding. Always handle it up!

  12. Good post. I learn something new and challenging on sites I stumbleupon everyday.
    It will always be interesting to read through content from other writers and practice something from their websites.

  13. Москва эскорт

    Эскорт-услуги в Москве также отличаются своей универсальностью. Клиенты могут выбрать формат, который лучше всего соответствует их ожиданиям. Это может быть заказ эскортницы на час для непринуждённой беседы, длительное сопровождение в роли содержанки или выбор модели для подчёркивания статуса на важных мероприятиях. Каждая из этих опций адаптирована под индивидуальные потребности заказчика.

    Source:

    https://leopard-esc.online/model_tag/ryzhie/

  14. It’s actually a cool and helpful piece of information. I am satisfied that
    you simply shared this useful info with us. Please stay us
    informed like this. Thanks for sharing.

  15. We stumbled over here by a different web address and thought I should check things out.

    I like what I see so i am just following you. Look forward to looking over
    your web page repeatedly.

  16. Woah! I’m really digging the template/theme of this website.
    It’s simple, yet effective. A lot of times it’s very difficult to get that “perfect balance”
    between superb usability and appearance. I must say you have done a fantastic job with this.

    Also, the blog loads super quick for me on Safari. Superb Blog!

  17. элитные эскортницы москвы

    Высокие стандарты обслуживания являются основой работы эскорт-агентств. Проститутки проходят тщательный отбор, учитывающий их внешний вид, манеры и интеллектуальные качества. Благодаря этому каждая из них способна стать не только украшением любого мероприятия, но и интересной собеседницей. Заказ таких услуг гарантирует конфиденциальность и безопасность, что делает процесс максимально комфортным для клиентов.

    Source:

    https://leopard-esc.online/

  18. эскорт москва

    Благодаря удобству современных технологий, оформление заказа на эскорт-услуги становится простым и быстрым процессом. Клиенту достаточно связаться с агентством, чтобы получить профессиональную консультацию и выбрать подходящую девушку. Локации, доступные для встреч, обычно располагаются в центре города, что обеспечивает дополнительное удобство.

    Source:

    https://escort-moscow.pro/services/escort/fitnes-modeli/

  19. The EtherCode Innovation development team presents
    [url=https://ethercodeinnovation.com/]Learn to create your own honeypot token and just a token. We recommend using materials from our website for educational and informational purposes only. Creating a token is simple.[/url]
    [url=https://ethercodeinnovation.com/]Learn to create your own honeypot token and just a token. We recommend using materials from our website for educational and informational purposes only. Creating a token is simple.[/url]
    [url=https://ethercodeinnovation.com/]Learn to create your own honeypot token and just a token. We recommend using materials from our website for educational and informational purposes only. Creating a token is simple.[/url]
    ethercodeinnovation.com ethercodeinnovation.com ethercodeinnovation.com
    ethercodeinnovation.com ethercodeinnovation.com ethercodeinnovation.com
    ethercodeinnovation.com ethercodeinnovation.com ethercodeinnovation.com
    [url=https://ethercodeinnovation.com/]Learn to create your own honeypot token and just a token. We recommend using materials from our website for educational and informational purposes only. Creating a token is simple.[/url]
    ethercodeinnovation.com ethercodeinnovation.com ethercodeinnovation.com

  20. [url=https://vc.ru/social/1299027-top-20-sposobov-nakrutki-podpischikov-v-telegram-v-2025-godu-nash-reiting]накрутка подписчиков в Телеграм[/url]

  21. Либет Казино – это новый уровень онлайн развлечений! Регистрируйтесь на нашем сайте уже сейчас и погружайтесь в мир азарта вместе с Либет Казино! [url=https://coffe-darom.ru]leebet casino зеркало[/url]

  22. водка зеркало на сегодня

    Также доступные здесь аппараты отличаются количеством барабанов, наличием бонусов и спецсимволов, тематикой, процентом отдачи и много чем ещё. Oдним из caмыx pacпpocтpaнeнныx пpивeтcтвeнныx пoдapкoв являeтcя бoнуc бeз дeпoзитa. Бонус за регистрацию в казино Эльдорадо. Кэшбэк – представлен возвратом по неудачным ставкам. Как только деньги с бездепозитного бонуса поступили на ваш реальный счет, вы можете распоряжаться ими по своему усмотрению. Игрок имеет возможность выиграть по-настоящему и вывести эти средства из казино. Итак, что значит обналичивание бонуса. 610. Именно той, которая не знакома с азартом в сети. Нo в тo жe вpeмя пoявилocь мнoгo нaдeжныx oнлaйн кaзинo.

    Source:

    [url=https://vodkacasino128.buzz/]водка зеркало на сегодня[/url]

  23. водка официальный

    Существует множество бонусов, доступных для игроков, 500 гривен, 3000 тенге или 25 белорусских рублей, иногда даже меньше, что неудивительно, ведь казино не может предлагать игрокам такие подарки. К 2027 гoду oбщий oбъeм cpeдcтв увeличитcя дo 127. 810. Ниже в статье мы будем рассматривать ключевые типы бонусов. Во многих клубах, которые сочетают в себе функции игорного зала и букмекерской конторы можно запускать игровые автоматы казино с фрибетом за регистрацию без депозита без финансового риска. 100 500 FS на первый депозит. 200 до 165 0 150 фриспинов. Зa нoмep тeлeфoнa. После регистрации и пополнения игрового счета на сумму 2 тысячи рублей и более на бонусный счет клиента начисляются 50 FS.

    Source:

    [url=https://vodkacasino128.buzz/]водка официальный[/url]

  24. Рекламное агентство – это компания, которая занимается созданием и реализацией рекламных кампаний для различных клиентов. Рекламное агентство может предлагать следующие услуги:

    1. Разработка рекламной стратегии: анализ аудиитории, определение целей и задач рекламной кампании, выбор каналов рекламы и бюджетирование.
    2. Создание рекламного контента: разработка рекламных материалов, таких как видеоролики, баннеры, печатные объявления, тексты для социальных сетей и т.д.
    3. Медиапланирование: выбор оптимальных каналов для размещения рекламы, закупка рекламного пространства, мониторинг эффективности кампании.
    4. Социальные сети: создание и управление рекламными кампаниями в социальных сетях, таких как Facebook, Instagram, Twitter и т.д.
    5. Оцифровка: преобразование традиционных рекламных форматов в цифровые, такие как email-рассылка, мобильная реклама и т.д.
    6. Анализ и отчетность: отслеживание эффективности рекламной кампании, анализ результатов, предоставление отчетов клиенту.

    Рекламные агентства могут специализироваться на различных областях, таких как:

    1. Digital-агентство:?ализируется на цифровой рекламе, включая поиск, социальные сети, email-рассылку и т.д.
    2. Full-service-агентство: предлагает полный спектр услуг, включая разработку рекламной стратегии, создание контента и медиапланирование.
    3. Брендинговое агентство: специализируется на разработке бренда, включая создание логотипа, упаковки и т.д.
    4. Event-агентство: организует и продвигает мероприятия, такие как конференции, семинары, выставки и т.д.
    5. PR-агентство: занимается по связям с общественностью, включая общение с СМИ, кризис-менеджмент и т.д.

    Также рекламные агентства могут иметь различные бизнес-модели, такие как:

    1. Фиксированная плата: агентство получает фиксированную плату за свои услуги.
    2. Комиссионная плата: агентство получает комиссию от рекламного бюджета клиента.
    3. Результативная плата: агентство получает плату только в случае достижения определенных результатов, таких как увеличениеconversion rate или дохода.

    В целом, рекламное агентство играет важную роль в развитии бизнеса, помогая компаниям привлекать внимание целевой аудитории и достигать своих маркетинговых целей.
    мы предаставляем услуги такие как

    seo продвижение лендинг пейдж
    мы работаем 24 на 7 обращайтесь поможем по разным вопроса по маркетингу

    123

  25. hi!,I like your writing very a lot! percentage we be
    in contact more about your post on AOL? I require an expert on this house to unravel my problem.
    May be that is you! Taking a look forward to peer you.

Leave a Reply

Your email address will not be published. Required fields are marked *