Exemple #1
0
def linear_regression(features, labels, learning_rate=0.01, epochs=1000):
    price_per_room = random.random()
    base_price = random.random()
    for epoch in range(epochs):
        # Uncomment any of the following lines to plot different epochs
        #if epoch == 1:
        #if epoch <= 10:
        #if epoch <= 50:
        #if epoch > 50:
        if True:
            utils.draw_line(price_per_room, base_price, starting=0, ending=8)
        i = random.randint(0, len(features) - 1)
        num_rooms = features[i]
        price = labels[i]
        # Uncomment any of the 2 following lines to use a different trick
        #price_per_room, base_price = absolute_trick(base_price,
        price_per_room, base_price = square_trick(base_price,
                                                  price_per_room,
                                                  num_rooms,
                                                  price,
                                                  learning_rate=learning_rate)
    utils.draw_line(price_per_room, base_price, 'black', starting=0, ending=8)
    utils.plot_points(features, labels)
    print('Price per room:', price_per_room)
    print('Base price:', base_price)
    return price_per_room, base_price
    def render(self):
        frame = self.env.frame
        read_game = self.env.read_game
        
        if keys["KEY_STATUS"]:
            if keys["KEY_STATUS_UP"]:
                draw_line(frame.line, 0, 9, 845, 0, 20, STATUS_COLOR_LINE)
                text_y = 3
            else:
                draw_line(frame.line, 0, read_game.resolution_y - 10, 845, 0, 20, STATUS_COLOR_LINE)
                text_y = read_game.resolution_y-15
    
            for i in range(1, 13):
                if keys_raw[vk_codes.VK_F1+i-1] & KEY_TOGGLE:
                    color = STATUS_COLOR_ACTIVE
                else:
                    color = STATUS_COLOR_INACTIVE
                label = "F" + str(i) + ":" + getattr(Config, "F"+str(i)+"_LABEL")
                draw_string_left(frame.status_font, (i-1)*70 + 5, text_y, 65, 15, color, label)
            if read_game.is_host_check() and keys["KEY_HOST_DISPLAY"]:
                draw_string_center(frame.rage_font, read_game.resolution_x - 100, read_game.resolution_y - (read_game.resolution_y - 8), 0x9600FF00, "You are host!")   
            
        if read_game.is_in_game and keys["KEY_INSPECT_WEAPON_NAME"]:
            weapon_model = self.env.weapon_names.get_weapon_model(self.env.read_game.my_player.weapon_num)
            if weapon_model is not None:
                draw_string_center(frame.rage_font, read_game.resolution_x - 250, read_game.resolution_y - 10, 0xA0FFFF00, weapon_model)

        if keys["KEY_FPS_VIEWER"]:
            self.calc_fps()
            if self.fps > 0:
                draw_string_center(frame.fps_font, read_game.resolution_x - 50, read_game.resolution_y - 10, FPS_FONT_COLOR, "FPS=%.0f" % self.fps)
        else:
            self.reset_fps()
Exemple #3
0
def linear_regression(features, labels, learning_rate=0.01, epochs=1000):
    price_per_room = random.random()
    base_price = random.random()
    errors = []
    for i in range(epochs):
        predictions = features[0] * price_per_room + base_price
        errors.append(rmse(labels, predictions))
        i = random.randint(0, len(features) - 1)
        num_rooms = features[i]
        price = labels[i]
        # Uncomment one of the following 3 lines to use the simple, the absolute, or the square trick
        #price_per_room, base_price = simple_trick(base_price,
        #price_per_room, base_price = absolute_trick(base_price,
        price_per_room, base_price = square_trick(base_price,
                                                  price_per_room,
                                                  num_rooms,
                                                  price,
                                                  learning_rate=learning_rate)
    utils.draw_line(price_per_room, base_price, 'black', starting=0, ending=9)
    utils.plot_points(features, labels)
    print('Price per room:', price_per_room)
    print('Base price:', base_price)
    plt.show()
    plt.scatter(range(len(errors)), errors)
    plt.show()
    return price_per_room, base_price
Exemple #4
0
 def distinguish(self, line, program_ast):
     unit = utils.get_distinguish_unit(line, program_ast)
     return ("\\n" +
             utils.draw_line(unit=unit) +
             self.scribe(line, program_ast) +
             " + '\\n" +
             utils.draw_line(unit=unit) +
             "'")
Exemple #5
0
 def distinguish(self, line, program_ast):
     unit = utils.get_distinguish_unit(line, program_ast)
     return ("\\n" +
             utils.draw_line(unit=unit) +
             self.scribe(line, program_ast) +
             " + '\\n" +
             utils.draw_line(unit=unit) +
             "'")
Exemple #6
0
def single_person_plot(path, file_name, animation=False):
    if not animation:
        ids, joints = utils.open_json_file(os.path.join(path, file_name))
    part = utils.make_part_dict()
    for i in range(len(ids)):
        globals()['fig%s' %i] = plt.figure()
        ax = plt.axes(projection='3d')
        x, y, z, conf = [array.reshape(26) for array in np.split(joints[i], 4, axis=1)]
        #ax.set_title('id = %s' %ids[i])
        utils.set_range(x, y, z, ax, animation)
        utils.draw_scatter(x, y, z, ax)
        utils.draw_line(x, y, z, ax, part)
        ax.view_init(azim = -90,elev = -90)
Exemple #7
0
 def iter_start(self, node, line, line_num, program_ast, indentation):
     action, ending = self.action_and_ending(line_num)
     text = ("' + '" +
             self.scribe(line, program_ast) +
             " + ' at beginning of for loop at line " +
             str(node.lineno) +
             "' ")
     return (indentation[:-4] +
             action +
             utils.draw_line() +
             text +
             ending)
Exemple #8
0
 def iter_start(self, node, line, line_num, program_ast, indentation):
     action, ending = self.action_and_ending(line_num)
     text = ("' + '" +
             self.scribe(line, program_ast) +
             " + ' at beginning of for loop at line " +
             str(node.lineno) +
             "' ")
     return (indentation[:-4] +
             action +
             utils.draw_line() +
             text +
             ending)
Exemple #9
0
def multi_people_plot(ids, joints, animation=False):    
    # Make the segments with neighbor joints
    part = utils.make_part_dict()
    
    plt.figure()
    ax = plt.axes(projection = '3d')    
    ax.set_axis_off()
    if not joints == []:
        tmp_joints = joints.reshape(-1,4)
        tmp_x, tmp_y, tmp_z, _ = [array.reshape(-1,) for array in np.split(tmp_joints, 4, axis=1)]
        utils.set_range(tmp_x, tmp_y, tmp_z, ax, animation)
    else:
        pass
    
    # Draw ground
    utils.draw_ground(ax)
    
    # Set viewpoint
    ax.view_init(azim = -90,elev = -50)
    for i in range(len(ids)):
        x, y, z, _ = [array.reshape(26) for array in np.split(joints[i], 4, axis=1)]
        utils.draw_line(x, y, z, ax, part)
        str_id = 'id : ' + str(i)
        ax.text(x[25],y[25]-10,z[25], str_id, color='red')
 def render(self):
     read_game = self.env.read_game
     frame = self.env.frame
     bot = self.env.bot
     if not read_game.is_in_game or not keys["KEY_BOT_VISUAL_MOUSE"]: return
     
     rh = rw = VISUAL_MOUSE_SIZE + (VISUAL_MOUSE_SIZE % 2)
     rx = read_game.resolution_x - rw - VISUAL_MOUSE_RIGHT_MARGIN
     ry = read_game.resolution_y - rh - VISUAL_MOUSE_BOTTOM_MARGIN
     
     r = D3DRECT(rx, ry, rx + rw, ry + rh)
     frame.device.Clear(1, byref(r), D3DCLEAR.TARGET, VISUAL_MOUSE_COLOR_BACK, 1, 0)
     
     draw4(frame.line, rx, ry, rx+rw, ry, rx+rw, ry+rh, rx, ry+rh, 2, VISUAL_MOUSE_COLOR_BORDER)
     line_x = bot.mouse_move_x
     line_y = bot.mouse_move_y
     if (line_x < -rw/2): line_x = -rw/2
     if (line_x > +rw/2): line_x = +rw/2
     if (line_y < -rh/2): line_y = -rh/2
     if (line_y > +rh/2): line_y = +rh/2
     
     draw_line(frame.line, rx + rw/2, ry, 0, rh, 1, VISUAL_MOUSE_COLOR_CROSSHAIR)
     draw_line(frame.line, rx, ry + rh/2, rw, 0, 1, VISUAL_MOUSE_COLOR_CROSSHAIR)
     draw_line(frame.line, rx + rw/2, ry + rh/2, line_x, line_y, VISUAL_MOUSE_LINE_WIDTH, VISUAL_MOUSE_COLOR_LINE)
Exemple #11
0
"""
turtle_draw_multi_chinese模拟机械臂.py:
模拟机械臂的坐标
"""

import pickle
import turtle
from time import sleep
from utils import draw_rect, draw_line

# 读
with open('Chinese_strokes', 'rb') as f:
    data = pickle.load(f)

turtle.screensize(100, 100, "white")
draw_line(-100, 0, 100, 0)
draw_line(0, -100, 0, 100)

sleep(1)
#
# sentense = '中央经济工作会议精神出炉'
# sentense = '一二手房车'
sentense = '新年快乐'
num = len(sentense)
width = 100  # 一个字的宽度 100*100
# all_width = width * num  # 总长度

center = (20, 0)

# counter = 0
for i, word in enumerate(sentense):
Exemple #12
0
def process_image(image):
    original_image = image.copy()
    ysize = image.shape[0]
    xsize = image.shape[1]

    gray = grayscale(image)

    # Define a kernel size and apply Gaussian smoothing
    kernel_size = 5
    blur_gray = gaussian_blur(gray, kernel_size)

    # Define our parameters for Canny and apply
    low_threshold = 50
    high_threshold = 150
    edges = canny(blur_gray, low_threshold, high_threshold)

    left_bottom = [0, ysize]
    right_bottom = [xsize, ysize]
    apex = [xsize / 2, ysize / 1.72]

    # This time we are defining a four sided polygon to mask
    vertices = np.array([[left_bottom, apex, apex, right_bottom]],
                        dtype=np.int32)
    masked_edges = region_of_interest(edges, vertices)

    # Define the Hough transform parameters
    # Make a blank the same size as our image to draw on
    rho = 2  # distance resolution in pixels of the Hough grid
    theta = np.pi / 180  # angular resolution in radians of the Hough grid
    threshold = 15  # minimum number of votes (intersections in Hough grid cell)
    min_line_length = 40  # minimum number of pixels making up a line
    max_line_gap = 20  # maximum gap in pixels between connectable line segments
    line_image = np.copy(image) * 0  # creating a blank to draw lines on

    # Run Hough on edge detected image
    # Output "lines" is an array containing endpoints of detected line segments
    # lines = hough_lines(masked_edges, rho, theta, threshold, min_line_length, max_line_gap)
    lines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]),
                            min_line_length, max_line_gap)

    left_points, right_points = separate_by_slope(lines)

    if left_points:
        # Find the slope based on the generated points for the left line
        slope = slope_from_lin_reg(left_points)
        # Calculate x for the largest y. i.e find the lowest point on the image part of the  extrapolate line
        x2 = int(max(left_points)[0] + (ysize - max(left_points)[1]) / slope)
        up_left_point = max(left_points)
        down_left_point = [x2, ysize]
        draw_line(line_image, up_left_point, down_left_point)

    if right_points:
        slope = slope_from_lin_reg(right_points)
        # Calculate x for the largest y. i.e find the lowest point on the image part of the  extrapolate line
        x2 = int(max(right_points)[0] + (ysize - max(right_points)[1]) / slope)
        up_right_point = min(right_points)
        down_right_point = [x2, ysize]
        draw_line(line_image, up_right_point, down_right_point)

    # Draw the lines on the edge image
    lines_edges = weighted_img(line_image, original_image)

    return lines_edges
Exemple #13
0
    def search(edge_map,
               component_class=1,
               number_of_samples=2,
               max_iterations=2000,
               output_image=None,
               original_image=None,
               total_classes_number=0) -> np.ndarray:
        print("--> Searching using class: [", component_class, "]")
        # Select just points from the specified class
        x, y = np.where(edge_map == component_class)
        points = np.column_stack((x, y))

        new_image = np.zeros(
            edge_map.shape) if output_image is None else output_image
        # new_image = new_image if original_image is None else original_image

        lines_eq = []
        lines_points = []
        lines_class = []

        for _ in range(max_iterations):
            print("Iteration [", _, "] Class [", component_class, "/",
                  total_classes_number, "] Points remaining: ",
                  points.shape[0])
            if points.shape[0] <= 1:
                break

            sample_points = np.random.choice(points.shape[0],
                                             size=number_of_samples,
                                             replace=False)
            sample_points = np.array(points[sample_points])
            number_of_inliners, inline_points, line_eq = RANSAC.evaluate_samples(
                points, sample_points)
            inline_points = np.array(inline_points)

            if number_of_inliners > RANSAC.INLINERS_THRESHOLD:
                # Find the ends of the line
                # Sort the inline points by the value of the slope so that we use the correct max values
                first_point = None
                second_point = None
                if line_eq[0] > 1:
                    first_point = inline_points[np.argmin(inline_points[:, 1])]
                    second_point = inline_points[np.argmax(inline_points[:,
                                                                         1])]
                else:
                    first_point = inline_points[np.argmin(inline_points[:, 0])]
                    second_point = inline_points[np.argmax(inline_points[:,
                                                                         0])]

                lines_eq.append(line_eq)
                lines_points.append((first_point, second_point))
                lines_class.append(component_class)

                print((first_point, second_point))
                new_image = utils.draw_line(new_image, first_point,
                                            second_point)

                # Remove the points used in the last search
                for j in range(len(inline_points)):
                    index = np.where((points[:, 0] == inline_points[j][0])
                                     & (points[:, 1] == inline_points[j][1]))
                    points = np.delete(points, index, axis=0)

        # utils.show_image(new_image)
        return new_image, lines_eq, lines_points, lines_class
Exemple #14
0
    def train(self):
        #Do the training 
        print("Training on device:  ",self.device)

        start_time=time.time()
        track_step=50
        running_loss=0
        for epoch in range(self.EPOCHS):
            self.model.train()
            steps=0 
            
            
            display_header(epoch,self.EPOCHS)
            
            for images,labels in self.train_loader: 
                images=images.to(self.device)
                labels=labels.to(self.device)  
                steps+=1 
                self.optimizer.zero_grad() 

                output = self.model.forward(images)
                loss = self.criterion(output, labels)

                loss.backward()
                self.optimizer.step()
                running_loss+=loss.item()
                
                
                if steps%track_step==0: 
                    self.model.eval()
                    with torch.no_grad():
                        val_loss, accuracy = self.validation(self.model, self.val_loader, self.criterion) 
                    
                    pad=get_padding(steps)
                    print(f"      {epoch+1}       ", # epoch
                        f"      {pad}{steps}/{len(self.train_loader)}       ", # step
                        f"      {running_loss/track_step :.2f}       ",# training loss
                        f"      {val_loss/len(self.test_loader):.2f}       ",# validation loss
                        f"      {accuracy/len(self.test_loader):.2f}      ")# validation accuracy
                    draw_line()
                    self.model.train()
                    running_loss=0
                    
            displayDuration("Epoch "+str(epoch+1),start_time) 
        displayDuration("Training ",start_time) 

        #Save Checkpoint
        self.model.class_to_idx = self.train_set.class_to_idx
        checkpoint = {'name':'Flower Classifier Model',  
              'epoch':self.EPOCHS,
              'optimizer': self.optimizer.state_dict(),
              'input_size': self.input_size,
              'output_size': 102,
              'pretrained_arch': 'vgg19', 
              'learning_rate': self.learning_rate,
              'batch_size': self.batch_size,
              'classifier': self.model.classifier,
              'class_to_idx': self.model.class_to_idx,
              'state_dict':self.model.state_dict()}



        torch.save(checkpoint, self.save_dir+"/"+self.checkpoint)
Exemple #15
0
        deviation0 += (h(x[i]) - y[i])
        deviation1 += ((h(x[i]) - y[i]) * x[i])

    deviation0 = (deviation0 * L_RATE) / size
    deviation1 = (deviation1 * L_RATE) / size

    theta0 -= deviation0
    theta1 -= deviation1


iterations = 10000
cost_list = [[], []]
x, y = generate_points(50)
for i in range(iterations):
    update_parameters(x, y)
    if (i % 100 == 0):
        cost_list[0].append(i)
        cost_list[1].append(cost_func(x, y))

# Draw plot of cost vs number of iterations
# iterations, cost = cost_list
# draw_plot(plt, iterations, 'Iterations', cost, 'Cost', 'line')
# plt.show()

# To show the fitted line and data points
draw_plot(plt, x, 'Size of house', y, 'Cost of house', 'dot')
xs = [0, max(x)]
ys = [h(xs[0]), h(xs[1])]
draw_line(plt, xs, ys)
plt.show()
from utils import draw_rect, draw_line

# 读
with open('Chinese_strokes', 'rb') as f:
    data = pickle.load(f)

center_point = (0, 0)
# center_point = (20, 210)  # 中心点为任意点
# turtle.setworldcoordinates(llx, lly, urx, ury)#TODO

turtle.screensize(100, 100, "white")
# turtle.setpos(-100, 0)
# turtle.down()
# turtle.goto(100, 0)
# turtle.up()
draw_line(-100 + center_point[0], 0 + center_point[1], 100 + center_point[0],
          0 + center_point[1])
#
# turtle.setpos(0, -100)
# turtle.down()
# turtle.goto(0, 100)
# turtle.up()
draw_line(0 + center_point[0], -100 + center_point[1], 0 + center_point[0],
          100 + center_point[1])

sleep(2)
#
# sentense = '中央经济工作会议精神出炉'
# sentense = '一二手房车'
sentense = '新年快乐'
num = len(sentense)
width = 100  # 一个字的宽度 100*100