Na podstawie artyułu i zawartego w nim kodu, napisz mi kod pythonowy wraz z polskimi opisami i komentarzami. Dodatkowo kod ma wyświetlac poszczególne etapy działania na terminalu oraz zapisywać wszystko do pliku, łacznie z efektami nauczania i testowania, czyli musisz to rozbudować. Oto artykuł z kodem, który w niektórych miejsach moze być błędny wiec do napraw: Chcę by przy okazji to był materiał do nauki: How to Guess Accurately 3 Lottery Numbers Out of 6 using LSTM Model
Roi Polanitzer
Roi Polanitzer
·
Follow
9 min read
·
May 27, 2022
81
17
Photo Credit: www.istockphoto.com
Motivation
In order to predict at least 3 lottery numbers out of 6 (variable y) lottery numbers in an Israeli general lottery game, I chose the Israeli general lottery games dataset that was sourced from Mifal HaPais. This dataset was based on the results of Israeli general lottery games between September 1968 and May 2022. It has many characteristics of learning, and the dataset can be downloaded from here.
Artificial Neural Networks can also be referred to as Multilayer perceptrons. The perceptron model was created in 1958 by American psychologist Frank Rosenblatt. Its singular nature allows it to adapt to basic binary patterns through a series of inputs, simulating the learning patterns of a human-brain. A Multilayer perceptron is the classic neural network model consisting of more than 2 layers.
Recurrent Neural Networks
Recurrent Neural Networks (RNNs) were invented to be used around predicting sequences. LSTM (Long short-term memory) is a popular RNN algorithm with many possible use cases:
When to use:
One to one: a single input mapped to a single output.
e.g — Image Classification
One to many: a single input mapped to a sequence of outputs.
e.g — Image captioning (multiple words from a single image)
Many to one: A sequence of inputs produces a single output.
e.g — Sentiment Analysis (binary output from multiple words)
Many to many: A sequence of inputs produces a sequence of outputs.
e.g — Video classification (splitting the video into frames and labeling each frame separately)
Business Understanding
The Israeli general lottery game called Loto. Lotto is a weekly game where the participant chooses 6 numbers out of 37 and an additional one number out of 7. Mifal HaPais draws 6 numbers of 37 and 1 number of 7, and the maximum prize is paid for matching all of them.
Various options allow the user to bet double, play random numbers, 5 numbers plus a random number, or all combinations of 7–12 numbers. The drawings are held once on Tuesday and once on Saturday, with occasional drawings on Thursday.
The prize pool is a minimum of ₪5,000,000 and a maximum of ₪80,000,000.
Data Understanding
First, let’s import the relevant libraries and packages:
Assistant
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from keras.models import Sequential
from keras.layers import LSTM, Dense, Bidirectional, Dropout
Second, Let’s load the required dataset using pandas’s read CSV function.
df = pd.read_csv(“IsraeliLottery.csv”)
We can take a closer look at the data took help of “head()”function of pandas library which returns first five observations.
df.head()
Similarly “tail()” returns last five observations.
df.tail()
The dataset provides the lottery results information. It includes 4,047 records and 8 fields.
print(df.shape)
(4047, 8)
After we have loaded the dataset, we might want to know a little bit more about it. We can check attributes names and datatypes using info().
data.info()
No variable column has null/missing values.
The describe() function in pandas is convenient in getting various summary statistics. This function returns the count, mean, standard deviation, minimum and maximum values and the quantiles of the data.
df.describe()
The count, mean, min and max rows are self-explanatory. The std shows the standard deviation, and the 25%, 50% and 75% rows show the corresponding percentiles.
Data Processing
There are several features that we do not need, such as “Game” and “Date”, so, we will drop them.
Deep learning algorithms expect all input features to vary in a similar way, and ideally to have a mean of 0, and a variance of 1. We must re-scale our data so that it fulfills these requirements.
Next, let’s crate X and y for each row in our scaled data. It should have format for Keras LSTM model (rows, window size, balls)
X = np.empty([ number_of_rows — window_length, window_length, number_of_features], dtype=float)
y = np.empty([ number_of_rows - window_length, number_of_features], dtype=float)
for i in range(0, number_of_rows-window_length):
X[i] = transformed_df.iloc[i : i+window_length, 0 : number_of_features]
y[i] = transformed_df.iloc[i+window_length : i+window_length+1, 0 : number_of_features]
Let’s check out X shape:
X.shape
(4040, 7, 6)
Let’s check out y shape:
y.shape
(4040, 6)
Lets’ check out our first scaled sample (which made of 7 consecutive lottery games):
X[0]
Lets’ check out our first scaled label:
y[0]
Lets’ check out the second scaled sample (which made of 7 consecutive lottery games):
X[1]
Lets’ check out our second scaled label:
y[1]
Modeling
First, let’s initialise the RNN
model = Sequential()
Let’s add the input layer and the LSTM layer
model.add(Bidirectional(LSTM(240, input_shape = (window_length, number_of_features), return_sequences = True)))
Let’s add a first Dropout layer in order to reduce overfitting
model.add(Dropout(0.2))
Let’s add a second LSTM layer
model.add(Bidirectional(LSTM(240, input_shape = (window_length, number_of_features), return_sequences = True)))
Let’s add a second Dropout layer
model.add(Dropout(0.2))
Then, let’s add a third LSTM layer
model.add(Dense(59))
Finally, let’s add the last output layer
model.add(Dense(number_of_features))
Now, let's compile the RNN
from tensorflow import keras
from tensorflow.keras.optimizers import Adam
model.compile(optimizer=Adam(learning_rate=0.0001), loss ='mse', metrics=['accuracy'])
Next, let’s train our LSTM model
Now, let’s predict the results (i.e., the 6 numbers) of the May 24th, 2022 lottety game based on those 7 games:
y_pred = model.predict(np.array([scaled_to_predict]))
print(“The predicted numbers in the last lottery game are:”, scaler.inverse_transform(y_pred).astype(int)[0])
The predicted numbers in the last lottery game are: [ 5 9 12 20 23 35]
Let’s see what were the real results of the May 24th, 2022 lottety game:
prediction = np.array(prediction)
print(“The actual numbers in the last lottery game were:”, prediction[0])
The actual numbers in the last lottery game were: [ 6 10 13 20 23 35]
3 number sout of 6 numbers, not bad at all!!! especially considering the fact that there was not supposed to be a model within the data, that is, the numbers had to be 100% random.
python
# Importowanie wymaganych bibliotek
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Bidirectional, Dropout
from tensorflow.keras.optimizers import Adam
# Otwarcie pliku do zapisu wyników
output_file = open('output.txt', 'w', encoding='utf-8')
# Wyświetlenie informacji w terminalu i zapisanie do pliku
print('Importowanie bibliotek...')
output_file.write('Importowanie bibliotek...\n')
# Wczytanie danych z pliku CSV
print('Wczytywanie danych z pliku...')
output_file.write('Wczytywanie danych z pliku...\n')
df = pd.read_csv('IsraeliLottery.csv')
# Wyświetlenie pierwszych pięciu wierszy danych i zapisanie do pliku
print('Pierwsze pięć wierszy danych:')
print(df.head())
output_file.write('Pierwsze pięć wierszy danych:\n')
output_file.write(df.head().to_string())
output_file.write('\n')
# Wyświetlenie ostatnich pięciu wierszy danych i zapisanie do pliku
print('Ostatnie pięć wierszy danych:')
print(df.tail())
output_file.write('Ostatnie pięć wierszy danych:\n')
output_file.write(df.tail().to_string())
output_file.write('\n')
# Wyświetlenie informacji o kształcie danych i zapisanie do pliku
print('Kształt danych:', df.shape)
output_file.write(f'Kształt danych: {df.shape}\n')
# Wyświetlenie informacji o typach danych i brakujących wartościach
print('Informacje o danych:')
print(df.info())
output_file.write('Informacje o danych:\n')
df.info(buf=output_file)
output_file.write('\n')
# Sprawdzenie podstawowych statystyk danych
print('Statystyki danych:')
print(df.describe())
output_file.write('Statystyki danych:\n')
output_file.write(df.describe().to_string())
output_file.write('\n')
# Przetwarzanie danych
print('Przetwarzanie danych...')
output_file.write('Przetwarzanie danych...\n')
# Usunięcie niepotrzebnych kolumn
print('Usuwanie niepotrzebnych kolumn...')
output_file.write('Usuwanie niepotrzebnych kolumn...\n')
df.drop(['Game', 'Date'], axis=1, inplace=True)
# Wyświetlenie pierwszych pięciu wierszy po usunięciu kolumn
print('Dane po usunięciu kolumn:')
print(df.head())
output_file.write('Dane po usunięciu kolumn:\n')
output_file.write(df.head().to_string())
output_file.write('\n')
# Skalowanie danych
print('Skalowanie danych...')
output_file.write('Skalowanie danych...\n')
scaler = StandardScaler().fit(df.values)
transformed_dataset = scaler.transform(df.values)
transformed_df = pd.DataFrame(data=transformed_dataset, index=df.index)
# Wyświetlenie przeskalowanych danych
print('Przeskalowane dane:')
print(transformed_df.head())
output_file.write('Przeskalowane dane:\n')
output_file.write(transformed_df.head().to_string())
output_file.write('\n')
# Definiowanie zmiennych
print('Definiowanie zmiennych...')
output_file.write('Definiowanie zmiennych...\n')
number_of_rows = df.values.shape[0]
window_length = 7
number_of_features = df.values.shape[1]
print(f'Liczba wierszy: {number_of_rows}')
print(f'Długość okna (window_length): {window_length}')
print(f'Liczba cech (number_of_features): {number_of_features}')
output_file.write(f'Liczba wierszy: {number_of_rows}\n')
output_file.write(f'Długość okna (window_length): {window_length}\n')
output_file.write(f'Liczba cech (number_of_features): {number_of_features}\n')
# Przygotowanie danych X i y
print('Przygotowywanie danych treningowych...')
output_file.write('Przygotowywanie danych treningowych...\n')
X = np.empty([number_of_rows - window_length, window_length, number_of_features], dtype=float)
y = np.empty([number_of_rows - window_length, number_of_features], dtype=float)
for i in range(0, number_of_rows - window_length):
X[i] = transformed_df.iloc[i : i + window_length, 0 : number_of_features]
y[i] = transformed_df.iloc[i + window_length : i + window_length + 1, 0 : number_of_features]
# Wyświetlenie kształtu X i y
print('Kształt X:', X.shape)
print('Kształt y:', y.shape)
output_file.write(f'Kształt X: {X.shape}\n')
output_file.write(f'Kształt y: {y.shape}\n')
# Wyświetlenie pierwszej próbki X i odpowiadającego jej y
print('Pierwsza próbka X:')
print(X[0])
print('Odpowiadająca etykieta y:')
print(y[0])
output_file.write('Pierwsza próbka X:\n')
output_file.write(str(X[0]))
output_file.write('\nOdpowiadająca etykieta y:\n')
output_file.write(str(y[0]))
output_file.write('\n')
# Budowanie modelu
print('Budowanie modelu LSTM...')
output_file.write('Budowanie modelu LSTM...\n')
model = Sequential()
model.add(Bidirectional(LSTM(240, input_shape=(window_length, number_of_features), return_sequences=True)))
model.add(Dropout(0.2))
model.add(Bidirectional(LSTM(240, return_sequences=True)))
model.add(Dropout(0.2))
model.add(Bidirectional(LSTM(240, return_sequences=True)))
model.add(Bidirectional(LSTM(240, return_sequences=False)))
model.add(Dense(59))
model.add(Dense(number_of_features))
# Kompilacja modelu
print('Kompilacja modelu...')
output_file.write('Kompilacja modelu...\n')
model.compile(optimizer=Adam(learning_rate=0.0001), loss='mse', metrics=['accuracy'])
# Trening modelu
print('Trening modelu...')
output_file.write('Trening modelu...\n')
history = model.fit(x=X, y=y, batch_size=100, epochs=300, verbose=2)
# Zapisanie wyników treningu do pliku
print('Zapisanie wyników treningu do pliku...')
output_file.write('Wyniki treningu:\n')
for key in history.history.keys():
output_file.write(f'{key}: {history.history[key]}\n')
# Ocena modelu
print('Ocena modelu...')
output_file.write('Ocena modelu...\n')
# Przygotowanie danych do przewidywania
print('Przygotowywanie danych do przewidywania...')
output_file.write('Przygotowywanie danych do przewidywania...\n')
to_predict = df.tail(8) # Ostatnie 8 gier
to_predict.drop([to_predict.index[-1]], axis=0, inplace=True) # Usunięcie ostatniego wiersza
prediction = df.tail(1) # Ostatni wiersz (prawdziwe wyniki do porównania)
print('Dane do przewidywania:')
print(to_predict)
output_file.write('Dane do przewidywania:\n')
output_file.write(to_predict.to_string())
output_file.write('\n')
print('Prawdziwe wyniki (do porównania):')
print(prediction)
output_file.write('Prawdziwe wyniki (do porównania):\n')
output_file.write(prediction.to_string())
output_file.write('\n')
# Konwersja danych do formatu potrzebnego dla modelu
to_predict_array = np.array(to_predict)
scaled_to_predict = scaler.transform(to_predict_array)
# Przewidywanie
print('Przewidywanie wyników...')
output_file.write('Przewidywanie wyników...\n')
y_pred = model.predict(np.array([scaled_to_predict]))
# Odwrócenie skalowania
predicted_numbers = scaler.inverse_transform(y_pred).astype(int)[0]
# Wyświetlenie przewidzianych liczb
print('Przewidziane liczby w ostatniej grze to:', predicted_numbers)
output_file.write(f'Przewidziane liczby w ostatniej grze to: {predicted_numbers}\n')
# Wyświetlenie prawdziwych wyników
actual_numbers = prediction.values[0]
print('Prawdziwe liczby w ostatniej grze to:', actual_numbers)
output_file.write(f'Prawdziwe liczby w ostatniej grze to: {actual_numbers}\n')
# Porównanie wyników
matching_numbers = set(predicted_numbers) & set(actual_numbers)
print('Liczby trafione:', matching_numbers)
output_file.write(f'Liczby trafione: {matching_numbers}\n')
# Zakończenie
print('Gotowe!')
output_file.write('Gotowe!\n')
# Zamknięcie pliku
output_file.close()
Wyjaśnienie:
Powyższy kod implementuje model LSTM do przewidywania wyników loterii na podstawie dostarczonego artykułu. Zostały dodane polskie opisy i komentarze, a także rozszerzono kod o dodatkowe funkcjonalności:
Wyświetlanie poszczególnych etapów działania na terminalu za pomocą funkcji print().
Zapis wszystkich informacji, etapów i wyników do pliku output.txt.
Poprawiono ewentualne błędy w kodzie z artykułu.
Dodano porównanie przewidzianych liczb z rzeczywistymi wynikami i wypisanie trafionych liczb.
Instrukcje:
Upewnij się, że posiadasz plik IsraeliLottery.csv w tym samym katalogu co skrypt.
Zainstaluj wymagane biblioteki, jeśli jeszcze ich nie masz:
bash
pip install numpy pandas scikit-learn tensorflow
Uruchom skrypt:
bash
python nazwa_skryptu.py
Wyniki zostaną wyświetlone w terminalu oraz zapisane w pliku output.txt.
Uwaga:
Model przewidujący wyniki loterii jest przykładem edukacyjnym i służy do demonstracji zastosowania sieci LSTM. W rzeczywistości wyniki loterii są losowe i nieprzewidywalne, a model nie będzie w stanie skutecznie przewidywać przyszłych losowań.