finds.py
import numpy as np
class Finds:
def __init__(self, samples, labels):
positive_indices = np.array([
index for (index, label) in enumerate(labels)
if label == 1
], dtype='int')
self.samples = samples[positive_indices, :]
self.H = [None] * samples.shape[1]
print('initialization finished')
print(self.samples)
print(self.H)
print()
def train(self):
for sample in self.samples:
index = 0
for _property in sample:
if self.H[index] == None:
self.H[index] = _property
elif _property != self.H[index]:
self.H[index] = '?'
index += 1
print('rule of judging is:', self.H)
def predict(self, input):
index = 0
for _property in self.H:
if input[index] == _property or _property == '?':
index += 1
else:
break
if index == len(self.H):
print('True')
return True
else:
print('False')
return False
test_finds.py
import finds
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sb
if __name__ == "__main__":
samples = np.array([
['Sunny', 'Warm', 'Normal', 'Strong', 'Warm', 'Same'],
['Sunny', 'Warm', 'High', 'Strong', 'Warm', 'Same'],
['Rainy', 'Cold', 'High', 'Strong', 'Warm', 'Change'],
['Sunny', 'Warm', 'High', 'Strong', 'Cold', 'Change'],
], dtype='str')
labels = [
1, 1, 0, 1
]
instance = finds.Finds(samples, labels)
instance.train()
instance.predict(samples[0])
instance.predict(samples[2])
output
initialization finished
[['Sunny' 'Warm' 'Normal' 'Strong' 'Warm' 'Same']
['Sunny' 'Warm' 'High' 'Strong' 'Warm' 'Same']
['Sunny' 'Warm' 'High' 'Strong' 'Cold' 'Change']]
[None, None, None, None, None, None]
rule of judging is: ['Sunny', 'Warm', '?', 'Strong', '?', '?']
True
False