MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / fit

Method fit

machine_learning/support_vector_machines.py:101–168  ·  view source on GitHub ↗

Fits the SVC with a set of observations. Args: observations (list[ndarray]): list of observations classes (ndarray): classification of each observation (in {1, -1})

(self, observations: list[ndarray], classes: ndarray)

Source from the content-addressed store, hash-verified

99 return np.exp(-(self.gamma * norm_squared(vector1 - vector2)))
100
101 def fit(self, observations: list[ndarray], classes: ndarray) -> None:
102 """
103 Fits the SVC with a set of observations.
104
105 Args:
106 observations (list[ndarray]): list of observations
107 classes (ndarray): classification of each observation (in {1, -1})
108 """
109
110 self.observations = observations
111 self.classes = classes
112
113 # using Wolfe's Dual to calculate w.
114 # Primal problem: minimize 1/2*norm_squared(w)
115 # constraint: yn(w . xn + b) >= 1
116 #
117 # With l a vector
118 # Dual problem: maximize sum_n(ln) -
119 # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm))
120 # constraint: self.C >= ln >= 0
121 # and sum_n(ln*yn) = 0
122 # Then we get w using w = sum_n(ln*yn*xn)
123 # At the end we can get b ~= mean(yn - w . xn)
124 #
125 # Since we use kernels, we only need l_star to calculate b
126 # and to classify observations
127
128 (n,) = np.shape(classes)
129
130 def to_minimize(candidate: ndarray) -> float:
131 """
132 Opposite of the function to maximize
133
134 Args:
135 candidate (ndarray): candidate array to test
136
137 Return:
138 float: Wolfe's Dual result to minimize
139 """
140 s = 0
141 (n,) = np.shape(candidate)
142 for i in range(n):
143 for j in range(n):
144 s += (
145 candidate[i]
146 * candidate[j]
147 * classes[i]
148 * classes[j]
149 * self.kernel(observations[i], observations[j])
150 )
151 return 1 / 2 * s - sum(candidate)
152
153 ly_contraint = LinearConstraint(classes, 0, 0)
154 l_bounds = Bounds(0, self.regularization)
155
156 l_star = minimize(
157 to_minimize, np.ones(n), bounds=l_bounds, constraints=[ly_contraint]
158 ).x

Callers 6

xgboostFunction · 0.45
xgboostFunction · 0.45
sarimax_predictorFunction · 0.45
support_vector_regressorFunction · 0.45
lstm_prediction.pyFile · 0.45

Calls

no outgoing calls

Tested by

no test coverage detected