Na podstawie tego arykułu napisz mi pełny kod z komentarzami. W moim przypadku plikiem zródłowym będzie mini.csv:
Write
Sign up
Sign in
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:
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.
Assistant
User
chyba coś żle przpeisałeśL Traceback (most recent call last):
File "c:\PYTHONPROJ\MINI_AI\sylwek.py", line 35, in
scaler = StandardScaler().fit(df.values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\PYTHON3125\Lib\site-packages\sklearn\preprocessing_data.py", line 878, in fit
return self.partial_fit(X, y, sample_weight)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\PYTHON3125\Lib\site-packages\sklearn\base.py", line 1473, in wrapper
return fit_method(estimator, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\PYTHON3125\Lib\site-packages\sklearn\preprocessing_data.py", line 914, in partial_fit
X = self._validate_data(
^^^^^^^^^^^^^^^^^^^^
File "c:\PYTHON3125\Lib\site-packages\sklearn\base.py", line 633, in _validate_data
out = check_array(X, input_name="X", **check_params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\PYTHON3125\Lib\site-packages\sklearn\utils\validation.py", line 1012, in check_array
array = _asarray_with_order(array, order=order, dtype=dtype, xp=xp)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\PYTHON3125\Lib\site-packages\sklearn\utils_array_api.py", line 745, in _asarray_with_order
array = numpy.asarray(array, order=order, dtype=dtype)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: could not convert string to float: '01.12.2015'
Assistant
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.
Your Turn!
Hopefully, this post gives you a good idea of what a deep learning sequential project looks like. As you can see, much of the work is in the data wrangling and the preparation steps, and these procedures consume most of the time spent on deep learning.
Now it’s time to get out there and start exploring and cleaning your data. Try two or three algorithms, and let me know how it goes.
Source code that created this post can be found here. I would be pleased to receive feedback or questions on any of the above.
About the Author
Roi Polanitzer, FRM, F.IL.A.V.F.A., CFV
Roi Polanitzer, CFV, QFV, FEM, F.IL.A.V.F.A., FRM, CRM, PDS, is a well-known authority in Israel the field of business valuation and has written hundreds of papers that articulate many of the concepts used in modern business valuation around the world. Mr. Polanitzer is the Owner and Chief Appraiser of Intrinsic Value — Independent Business Appraisers, a business valuation firm headquartered in Rishon LeZion, Israel. He is also the Owner and Chief Data Scientist of Prediction Consultants, a consulting firm that specializes in advanced analysis and model development.
Over more than 17 years, he has performed valuation engagements for mergers and acquisitions, purchase price allocation (PPA) valuations, goodwill impairment test valuations, embedded option and real option valuations, employee stock option (ESOP) valuations, common stock valuations (409A), splitting equity components and complicated equity/liability instrument valuations (PWERM / CCM / OPM), contingent liability, guarantees and loan valuations, independent expert opinions for litigation purposes, damage quantifications, balancing resources between spouses due to divorce proceedings and many other kinds of business valuations. Mr. Polanitzer has testified in courts and tribunals across the country and from time to time participates in mediation proceedings between spouses.
Mr. Polanitzer holds an undergraduate degree in economics and a graduate degree in business administration, majoring in finance, both from the Ben-Gurion University of the Negev. He is a Full Actuary (Fellow), a Corporate Finance Valuator (CFV), a Quantitative Finance Valuator (QFV) and a Financial and Economic Modeler (FEM) from the Israel Association of Valuators and Financial Actuaries (IAVFA). Mr. Polanitzer is the Founder of the IAVFA and currently serves as its chairman.
Mr. Polanitzer’s professional recognitions include being designated a Financial Risk Manager (FRM) by the Global Association of Risk Professionals (GARP), a Certified Risk Manager (CRM) by the Israel Association of Risk Managers (IARM), as well as being designated a Python Data Analyst (PDA), a Machine Learning Specialist (MLS), an Accredited in Deep Learning (ADL) and a Professional Data Scientist (PDS) by the Professional Data Scientists’ Israel Association (PDSIA). Mr. Polanitzer is the Founder of the PDSIA and currently serves as its CEO.
He is the editor of IAVFA’s weekly newsletter since its inception (primarily for the professional appraisal community in Israel).
Mr. Polanitzer develops and teaches business valuation professional trainings and courses for the Israel Association of Valuators and Financial Actuaries, and frequently speaks on business valuation at professional meetings and conferences in Israel. He also developed IAVFA’s certification programs in the field of valuation and he is responsible for writing the IAVFA’s statement of financial valuation standards.
To replicate the LSTM model described in the article using your own data file mini.csv, you'll need to follow the steps outlined in the article but modify the file loading and possibly reshape the input depending on the content of mini.csv. I will create a Python script based on your description assuming mini.csv has a similar format to IsraeliLottery.csv. Make sure to adjust the script if your data differs.
Here's the complete Python code:
# Import necessary libraries
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
from tensorflow.keras.optimizers import Adam
# Load the dataset
df = pd.read_csv("mini.csv")
# View the first few rows of the dataframe to understand its structure
print("Dataframe Head:")
print(df.head())
# View the dataset's structure
print("\nDataframe Info:")
print(df.info())
# View summary statistics
print("\nDataframe Description:")
print(df.describe())
# Drop unnecessary columns - adjust as necessary
df.drop(['Game', 'Date'], axis=1, inplace=True, errors='ignore')
# Scale the data
scaler = StandardScaler().fit(df.values)
transformed_dataset = scaler.transform(df.values)
transformed_df = pd.DataFrame(data=transformed_dataset, index=df.index)
# Define constants
number_of_rows = df.values.shape[0]
window_length = 7
number_of_features = df.values.shape[1]
# Prepare the data for LSTM
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(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]
# Initialize the model
model = Sequential()
# Add layers to the model
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))
# Compile the model
model.compile(optimizer=Adam(learning_rate=0.0001), loss='mse', metrics=['accuracy'])
# Train the model
model.fit(X, y, batch_size=100, epochs=300, verbose=2)
# Evaluate / Test the model using last 8 data items for prediction
to_predict = df.tail(8).drop([df.index[-1]], axis=0)
to_predict_np_array = np.array(to_predict)
# Rescale the data to match the scale of training
scaled_to_predict = scaler.transform(to_predict_np_array)
# Make predictions
y_pred = model.predict(np.array([scaled_to_predict]))
predicted_numbers = scaler.inverse_transform(y_pred).astype(int)[0]
# Output the predictions
print("\nThe predicted numbers for the next lottery draw are:", predicted_numbers)
# Actual results, assuming the last row in data is the actual latest result
actual_results = np.array(df.tail(1))
print("The actual numbers in the last lottery game were:", actual_results[0])
Instructions:
Ensure your mini.csv file has a similar structure to IsraeliLottery.csv, with relevant lottery numbers data and any unnecessary columns removed.
This script initializes an LSTM model to predict lottery numbers based on historical data, scales the data, formats it for the LSTM input, compiles the model, fits it, and then makes a prediction on newly formatted data.
If the column names or nature of mini.csv differ, adjust the df.drop() line and reshape operations accordingly.
Important Considerations:
Deep learning models require large datasets and relevant features to make reliable predictions. The performance on a small or simplified dataset like mini.csv might not be as effective.
Ensure the numbers are correctly formatted and features are appropriately scaled; verify the transformation logic fits your specific dataset.
Adjust the script to match your data format and perform any additional data preprocessing as necessary.
The error you encountered indicates that there are non-numeric values in your dataset, specifically a date string '01.12.2015'. For scaling numerical features, all non-numeric data has to be either removed or converted into a numeric format. Here's how you can handle this issue:
Identify Non-Numeric Columns: Determine which columns contain non-numeric data and handle them appropriately.
Convert or Drop Non-Numeric Columns: Either convert these columns to a suitable numeric format where applicable or drop them if they are unnecessary for prediction.
Here's how you can adjust the code to handle your dataset:
# Import necessary libraries
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
from tensorflow.keras.optimizers import Adam
# Load the dataset
df = pd.read_csv("mini.csv")
# Check the datastructure to identify non-numeric columns
print("Dataframe Info Before Processing:")
print(df.info())
# Drop or Parse Date Columns if necessary
# If you have a Date column you want to keep for any reason (e.g., time-based feature), parse it to datetime format
# Otherwise, drop it as demonstrated below if it's not useful. Adjust column names as needed.
# Attempt to drop irrelevant non-numeric columns
df.drop(['Date'], axis=1, inplace=True, errors='ignore') # Change column names to those present in your dataset
# View the dataframe to confirm changes
print("\nDataframe Head After Dropping Non-Numeric Columns:")
print(df.head())
# Ensure all columns are numeric now. Cast to float if necessary.
try:
df = df.astype(float)
except ValueError as e:
print("Error converting data to float. Check your dataset:", e)
# Scale the data
scaler = StandardScaler().fit(df.values)
transformed_dataset = scaler.transform(df.values)
transformed_df = pd.DataFrame(data=transformed_dataset, index=df.index)
# Define constants
number_of_rows = df.values.shape[0]
window_length = 7
number_of_features = df.values.shape[1]
# Prepare the data for LSTM
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(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]
# Initialize the model
model = Sequential()
# Add layers to the model
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))
# Compile the model
model.compile(optimizer=Adam(learning_rate=0.0001), loss='mse', metrics=['accuracy'])
# Train the model
model.fit(X, y, batch_size=100, epochs=300, verbose=2)
# Evaluate / Test the model using last 8 data items for prediction
to_predict = df.tail(8).drop([df.index[-1]], axis=0)
to_predict_np_array = np.array(to_predict)
# Rescale the data to match the scale of training
scaled_to_predict = scaler.transform(to_predict_np_array)
# Make predictions
y_pred = model.predict(np.array([scaled_to_predict]))
predicted_numbers = scaler.inverse_transform(y_pred).astype(int)[0]
# Output the predictions
print("\nThe predicted numbers for the next lottery draw are:", predicted_numbers)
# Actual results, assuming the last row in data is the actual latest result
actual_results = np.array(df.tail(1))
print("The actual numbers in the last lottery game were:", actual_results[0])
Steps:
Non-Numeric Columns: Identify and handle any non-numeric columns, such as dates, by dropping them unless relevant for the task.
Data Type Conversion: Ensure all relevant columns are cast to numeric types.
Scaling: Use the StandardScaler only on numeric columns.
Ensure your CSV file (mini.csv) is configured correctly for the code provided above. Adjust column names and data handling steps based on your specific dataset.