def update(self): # 若标记的长度比历史数据更长,则无法回测并报错 if len(self.history_price) < len(self.choose_position): print( 'Error! The length of choose_position is larger than that of history_price!' ) return # 若标记的长度比历史数据更短,则用0补齐标记数组及amount数组使之与历史数据长度一致 if len(self.history_price) > len(self.choose_position): for i in range( len(self.history_price) - len(self.choose_position)): self.choose_position.append(0) self.choose_amount.append(0) real_capital = 0 now_hold = 0 capital = [] capital_return = [] for t in range(len(self.history_price)): if t > 0: capital_return.append( now_hold * (self.history_price[t] - self.history_price[t - 1])) if t == 0: capital_return.append(0) self.total_amount = self.total_amount + self.choose_amount[t] if self.choose_position[t] == 1: now_hold = now_hold + self.choose_amount[t] real_capital = real_capital + self.choose_amount[ t] * self.history_price[t] if self.choose_position[t] == 2: real_capital = real_capital * ( (now_hold - self.choose_amount[t]) / now_hold) if MathUtils.double_compare(now_hold - self.choose_amount[t], 0) < 0: print("Error! Hold can't be smaller than 0!") now_hold = now_hold - self.choose_amount[t] capital.append(real_capital) max_draw_down = -float("inf") temp_sum_return = [capital_return[0]] for i in range(1, len(capital_return)): temp = temp_sum_return[i - 1] + capital_return[i] if MathUtils.double_compare(-temp, max_draw_down) > 0: max_draw_down = -temp temp_sum_return.append(temp) self.sum_return = np.array(temp_sum_return) self.capital = np.array(capital) self.capital_return = np.array(capital_return) self.max_draw_down = max_draw_down self.final_return = self.sum_return[-1]
def interpolate(self, x, y): """ :param x: [] :param y: [] :return: """ if len(x) != len(y): raise ArgumentsException("lenth of x and y is diffrence") if len(x) < 3: raise ArgumentsException("lenth of x is less than 3") n = len(x) - 1 MathUtils.checkOrder(x) h = [] for i in range(n): h.append(x[i + 1] - x[i]) mu = [] z = [] mu.append(float(0)) z.append(float(0)) # g = 0 for i in range(1, n): # g = 2d * (x[i + 1] - x[i - 1]) - h[i - 1] * mu[i - 1]; g = float(2) * (x[i + 1] - x[i - 1]) - h[i - 1] * mu[i - 1] mu.append(h[i] / g) # z[i] = (3d * (y[i + 1] * h[i - 1] - y[i] * (x[i + 1] - x[i - 1]) + y[i - 1] * h[i]) / (h[i - 1] * h[i]) - h[i - 1] * z[i - 1]) / g; z.append(float(3) * (y[i + 1] * h[i - 1] - y[i] * (x[i + 1] - x[i - 1]) + y[i - 1] * h[i]) / (h[i - 1] * h[i] - h[i - 1] * z[i - 1]) / g) b = [float(0)] * n # linear: 线性 c = [float(0)] * (n + 1) # quadratic: 二次方程 d = [float(0)] * n # cubic: 多项式 z.append(float(0)) for j in range(n - 1, -1, -1): # c[j] = z[j] - mu[j] * c[j + 1]; # b[j] = (y[j + 1] - y[j]) / h[j] - h[j] * (c[j + 1] + 2d * c[j]) / 3d; # d[j] = (c[j + 1] - c[j]) / (3d * h[j]); c[j] = z[j] - mu[j] * c[j + 1] b[j] = (y[j + 1] - y[j]) / h[j] - h[j] * (c[j + 1] + float(2) * c[j]) / float(3) d[j] = (c[j + 1] - c[j]) / (float(3) * h[j]) polynomials = [] coefficients = [0] * 4 for i in range(n): coefficients[0] = y[i] coefficients[1] = b[i] coefficients[2] = c[i] coefficients[3] = d[i] polynomials.append(PolynomialFunction(coefficients)) return PolynomiaSplineFuction(x, polynomials)
def compute_q(dict_q, tag, prev_tag, prev_prev_tag, lr1=0.90, lr2=0.09, lr3=0.01): if lr1 + lr2 + lr3 != 1.0: raise Exception('summing factors should be 1 !!!') prob1 = MathUtils.calc_fraction(DictUtils.get_value(dict_q, (tag, prev_tag, prev_prev_tag)), DictUtils.get_value(dict_q, (prev_tag, prev_prev_tag))) prob2 = MathUtils.calc_fraction(DictUtils.get_value(dict_q, (tag, prev_tag)), DictUtils.get_value(dict_q, prev_tag)) prob3 = MathUtils.calc_fraction(DictUtils.get_value(dict_q, tag), DictUtils.get_value(dict_q, 'ALL')) return lr1 * prob1 + lr2 * prob2 + lr3 * prob3
def draw_controls(self, angle: int, speed: int): image_angle = angle if angle >= 0 and angle <= 90: image_angle = MathUtils.remap(angle, 0, 90, 90, 0) elif angle > 90 and angle <= 180: image_angle = MathUtils.remap(angle, 90, 180, 0, -90) image = imutils.rotate(self.__wheel_img, image_angle) cropped = self.__get_cropped_wheel(image) height, width, _ = cropped.shape enlarged = self.__get_enlarged_wheel(cropped) acceleration_bar_height = int(speed / 100 * height) cv2.rectangle(enlarged, (width + 10, height - acceleration_bar_height), (width + self.__ACCELERATION_BAR_WIDTH - 10, height), (107, 29, 74), -1) self.__show_acceleration_percent(enlarged, speed) cv2.imshow('Wheel', enlarged)
def __get_converted_power(self, percent_power: int, forward: bool) -> str: power_limits_key = {True: 'forward', False: 'backward'}[forward] return str( MathUtils.remap(percent_power, 0, 100, self.POWER_LIMITS[power_limits_key]['min'], self.POWER_LIMITS[power_limits_key]['max']))
def _backprop(self, x, y, batch_size): x = self._get_fixed_input(x) d_w = [np.zeros(w.shape) for w in self._weights] d_b = [np.zeros(b.shape) for b in self._biases] activation = x activations = [x] z_vector = [] for idx, (w, b) in enumerate(zip(self._weights, self._biases)): z = (w.dot(activation)) + b activation = self._activations[idx].compute(z) z_vector.append(z) activations.append(activation) y_one_hot = MathUtils.one_hot(y, self._layer_sizes[-1]) error_deriv = (y_one_hot - activations[-1]) delta = error_deriv * self._activations[-1].compute_derivative( z_vector[-1]) d_w[-1] = delta.dot(activations[-2].T) d_b[-1] = np.sum(delta, axis=1, keepdims=True) for l in range(2, self._layer_num): z = z_vector[-l] delta = np.dot(self._weights[-l + 1].T, delta) * self._activations[-l].compute_derivative(z) activation = activations[-l - 1] d_w[-l] = delta.dot(activation.T) d_b[-l] = np.sum(delta, axis=1, keepdims=True) return d_w, d_b
def train(self, train_data, epoch_num, batch_size, learning_rate, test_data=None, log=False): results = [] for i in range(epoch_num): batches = MathUtils.partition_data(train_data, batch_size) for batch in batches: x, y = batch d_w, d_b = self._backprop(x, y, batch_size) self._weights = [ w + (learning_rate * gw) for w, gw in zip(self._weights, d_w) ] self._biases = [ b + (learning_rate * gb) for b, gb in zip(self._biases, d_b) ] accuracy = self.eval(test_data) / len(test_data[1]) train_accuracy = self.eval(train_data) / len(train_data[1]) results.append((accuracy, train_accuracy)) if test_data and log: print("Epoch {0}: {1}/{2}".format(i, self.eval(test_data), len(test_data[1]))) return results
def sample(self, inputs, last, sequence_len): hp = np.zeros(self.num_hidden_units) sprev = np.zeros(self.num_hidden_units) g_y = [0, 0] eps = 0.01 x = np.copy(inputs) t = 0 rez = [] rez.append(inputs) a = 0 while True: if sequence_len/1 - a <= 0: break if abs(g_y[0] - last[0]) < eps and abs(g_y[1] - last[1]) < eps: break if t >= 100: break temp_in = np.hstack((x, np.array([last[0], last[1]]))) received_loss, sprev, hp, g_y = self.feed_forward(hp, sprev, temp_in, [0, 0], sequence_len-a, True) x = g_y t += 1 a += 1 rez.append(g_y) if 5 == 5: inputs = rez[0] angle = MathUtils.getAngle( rez[len(rez)-1], last, inputs) rez = MathUtils.rotateLines( rez, angle) distReal = MathUtils.distance(inputs, last) distSampled = MathUtils.distance(inputs, rez[len(rez)-1]) sampledOrig = np.copy(rez) l,r,mid = 0,100,0 if 2 == 2: while (r - l) > 0.000000000001: midl = (l*2 + r) / 3 midr = ((l + 2*r)) / 3 dummy1 = MathUtils.strecthLines(sampledOrig, midl) dummy2 = MathUtils.strecthLines(sampledOrig, midr) d1 = MathUtils.distance(dummy1[len(dummy1) - 1], last) d2 = MathUtils.distance(dummy2[len(dummy2) - 1], last) if(d1 <= d2): r = midr else: l = midl rez = MathUtils.strecthLines(rez, r) inputs = x[0] return rez
def get(self, image, face_model: FaceModel) -> Coordonates: pupil_center, eye_shape = self.__pupil_detector.find(image, face_model) mouth_height = self.__shape_analizer.get_height(face_model.get_mouth()) if not pupil_center or not self.calibrated_model.is_calibrated(): return Coordonates() height, width, _ = eye_shape from_low, from_high = (self.calibrated_model.eye_max_left, self.calibrated_model.eye_max_right) pupil_center_width = int(MathUtils.constrain(pupil_center[0], (from_low, from_high))) eyes_horizontal_angle = MathUtils.remap(pupil_center_width, from_low, from_high, 0, 180) mouth_height = int(MathUtils.constrain(mouth_height, (self.calibrated_model.mouth_closed_height, self.calibrated_model.mouth_opened_height))) mouth_vertical_percent = MathUtils.remap(mouth_height, self.calibrated_model.mouth_closed_height, self.calibrated_model.mouth_opened_height, 0, 100) return Coordonates(eyes_horizontal_angle, mouth_vertical_percent)
def add_choose_position(self, is_buy: bool, position: int, amount: float): # 不检查hold是否充足,在update时再进行检查,但检查amount是否为非负数 if MathUtils.double_compare(amount, 0) < 0: print("Error! Amount can't be smaller than 0!") return # 若两数组长度不够,则用 0 补齐长度 if len(self.choose_position) <= position: for i in range(position - len(self.choose_position) + 1): self.choose_position.append(0) self.choose_amount.append(0) # 在对应的位置上加上标记及amount if is_buy: self.choose_position[position] = 1 else: self.choose_position[position] = 2 self.choose_amount[position] = amount
def __get_converted_direction(self, angle: int) -> int: return MathUtils.remap(angle, self.MIN_ANGLE, self.MAX_ANGLE, self.DIRECTION_LIMITS['left'], self.DIRECTION_LIMITS['right'])
def compute_e(word, tag, dict_q, dict_e): counter = DictUtils.get_value(dict_e, (word, tag)) denominator = DictUtils.get_value(dict_q, tag) return MathUtils.calc_fraction(counter, denominator)