ml.py 5.99 KB
Newer Older
Chetan Sharma's avatar
Chetan Sharma committed
1
2
3
4
5
6
import abc
import numpy as np

from sklearn import linear_model
from matplotlib import pyplot as plt

7
from models import T_lin, F_lin, T_x_vector, T_x_vector_padded, Fy_x_vector
Chetan Sharma's avatar
Chetan Sharma committed
8
from objects import Data, Conditions, EndMill, Prediction
Chetan Sharma's avatar
Chetan Sharma committed
9

Chetan Sharma's avatar
Chetan Sharma committed
10

Chetan Sharma's avatar
Chetan Sharma committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Model(abc.ABC):
    """
    Represents a model that can be trained with one training datum at a time.
    """
    @abc.abstractmethod
    def ingest_datum(self, datum):
        """
        Ingests one datum.
        Args:
            datum : A Data object.
        """
        pass

    def ingest_data(self, data):
25
26
        for datum in data:
            self.ingest_datum(datum)
Chetan Sharma's avatar
Chetan Sharma committed
27
28
29
30
31
32
33
34
35

    @abc.abstractmethod
    def predict_one(self, conditions):
        """
        Predicts milling forces using the model as it currently is.
        """
        pass

    def predict(self, conditions):
36
        return list(map(self.predict_one, conditions))
Chetan Sharma's avatar
Chetan Sharma committed
37
38
39
40
41
42
43
44


class LinearModel(Model):
    def __init__(self):
        self.training_T_x = list()
        self.training_T_y = list()
        self.training_Fy_x = list()
        self.training_Fy_y = list()
Chetan Sharma's avatar
Chetan Sharma committed
45
46
47
48

        self.regressor_T = linear_model.LinearRegression(fit_intercept=False)
        self.regressor_Fy = linear_model.LinearRegression(fit_intercept=False)
        self.params = np.array([0, 0, 0, 0], dtype='float64')
Chetan Sharma's avatar
Chetan Sharma committed
49
50
51

    def ingest_datum(self, datum):
        # decompose
Chetan Sharma's avatar
Chetan Sharma committed
52
        _, _, _, _, _, Ts, Fys = datum.unpack()
53
        T, Fy = np.median(Ts[:, 1]), np.median(Fys[:, 1])
Chetan Sharma's avatar
Chetan Sharma committed
54
        # get linear coefficients
Chetan Sharma's avatar
Chetan Sharma committed
55
56
57
        T_x = T_x_vector(datum.conditions())
        Fy_x = Fy_x_vector(datum.conditions())

Chetan Sharma's avatar
Chetan Sharma committed
58
59
60
61
        # add to training set
        self.training_T_x.append(T_x)
        self.training_T_y.append(T)
        self.training_Fy_x.append(Fy_x)
Chetan Sharma's avatar
Chetan Sharma committed
62
        self.training_Fy_y.append(Fy)
Chetan Sharma's avatar
Chetan Sharma committed
63
64
65
66
67
68
69
70
71
        self.update()

    def update(self):
        # convert force into numpy arrays for convenience
        training_Fy_x = np.array(self.training_Fy_x)
        training_Fy_y = np.array(self.training_Fy_y)

        # calculate best fit from data
        self.regressor_T.fit(self.training_T_x, self.training_T_y)
Chetan Sharma's avatar
Chetan Sharma committed
72
        K_tc, K_te = self.regressor_T.coef_
Chetan Sharma's avatar
Chetan Sharma committed
73
74
75
76
        self.params[0], self.params[1] = K_tc, K_te

        # transform Fy into a smaller linear problem and fit
        intercepts = training_Fy_x @ np.array([K_tc, K_te, 0, 0])[np.newaxis].T
Chetan Sharma's avatar
Chetan Sharma committed
77
78
79
80
        training_Fy_y_no_intercepts = np.reshape(
            training_Fy_y - intercepts.T, (-1))
        self.regressor_Fy.fit(
            training_Fy_x[:, 2:], training_Fy_y_no_intercepts)
Chetan Sharma's avatar
Chetan Sharma committed
81
        K_rc, K_re = self.regressor_Fy.coef_
Chetan Sharma's avatar
Chetan Sharma committed
82
        self.params[2], self.params[3] = K_rc, K_re
Chetan Sharma's avatar
Chetan Sharma committed
83
84
85

    def predict_one(self, conditions):
        # evaluate
Chetan Sharma's avatar
Chetan Sharma committed
86
87
        T = T_lin(conditions, *self.params[:2])
        F = F_lin(conditions, *self.params)
Chetan Sharma's avatar
Chetan Sharma committed
88
89

        # repack and return
Chetan Sharma's avatar
Chetan Sharma committed
90
        return Prediction(*conditions.unpack(), T, F)
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187

class UnifiedLinearModel(Model):
    def __init__(self):
        self.training_Tx = list()
        self.training_Ty = list()
        self.training_Fyx = list()
        self.training_Fyy = list()

        self.regressor = linear_model.LinearRegression(fit_intercept=False)
        self.params = np.array([0, 0, 0, 0], dtype='float64')

    def ingest_datum(self, datum):
        # decompose
        _, _, _, _, _, Ts, Fys = datum.unpack()
        T, Fy = np.median(Ts[:, 1]), np.median(Fys[:, 1])
        # get linear coefficients
        T_x = np.array(T_x_vector_padded(datum.conditions()))
        Fy_x = np.array(Fy_x_vector(datum.conditions()))

        # we want to artificially inflate T to be as big as F
        # this is a little arbitrary, might not be the best idea lol
        ratio = Fy_x[:2].mean() / T_x[:2].mean()
        T_x *= ratio
        T *= ratio

        # add T to training set
        self.training_Tx.append(T_x)
        self.training_Ty.append(T)

        # add Fy to training set
        self.training_Fyx.append(Fy_x)
        self.training_Fyy.append(Fy)

        self.update()

    def update(self):
        # calculate best fit from data
        self.regressor.fit(self.training_Tx + self.training_Fyx, self.training_Ty + self.training_Fyy)
        self.params = np.array(self.regressor.coef_)

    def predict_one(self, conditions):
        # evaluate
        T = T_lin(conditions, *self.params[:2])
        F = F_lin(conditions, *self.params)

        # repack and return
        return Prediction(*conditions.unpack(), T, F)

class RANSACLinearModel(Model):
    def __init__(self):
        self.training_Tx = list()
        self.training_Ty = list()
        self.training_Fyx = list()
        self.training_Fyy = list()

        base_regressor = linear_model.LinearRegression(fit_intercept=False)
        self.regressor = linear_model.RANSACRegressor(base_regressor, min_samples=5)
        self.params = np.array([0, 0, 0, 0], dtype='float64')

    def ingest_datum(self, datum):
        # decompose
        _, _, _, _, _, Ts, Fys = datum.unpack()
        T, Fy = np.median(Ts[:, 1]), np.median(Fys[:, 1])
        # get linear coefficients
        T_x = np.array(T_x_vector_padded(datum.conditions()))
        Fy_x = np.array(Fy_x_vector(datum.conditions()))

        # we want to artificially inflate T to be as big as F
        # this is a little arbitrary, might not be the best idea lol
        ratio = Fy_x[:2].mean() / T_x[:2].mean()
        T_x *= ratio
        T *= ratio

        # add T to training set
        self.training_Tx.append(T_x)
        self.training_Ty.append(T)

        # add Fy to training set
        self.training_Fyx.append(Fy_x)
        self.training_Fyy.append(Fy)

        if (len(self.training_Tx) + len(self.training_Fyx)) > 4:
            self.update()

    def update(self):
        # calculate best fit from data
        self.regressor.fit(self.training_Tx + self.training_Fyx, self.training_Ty + self.training_Fyy)
        self.params = np.array(self.regressor.estimator_.coef_)

    def predict_one(self, conditions):
        # evaluate
        T = T_lin(conditions, *self.params[:2])
        F = F_lin(conditions, *self.params)

        # repack and return
        return Prediction(*conditions.unpack(), T, F)