ValueError: x 和 y 必须具有相同的第一个维度,但形状分别为 (5,) 和 (1,)。

huangapple go评论83阅读模式
英文:

ValueError: x and y must have same first dimension, but have shapes (5,) and (1,)

问题

import time
import random
import matplotlib.pyplot as plt

def brute_force(values, weights, capacity):
    num_items = len(values)
    max_value = 0
    subset = []
    
    for i in range(2**num_items):
        current_value = 0
        current_weight = 0
        current_subset = []
        
        for j in range(num_items):
            if(i & (1 << j)) != 0:
                current_value += values[j]
                current_weight += weights[j]
                current_subset.append(j)
                
        if current_weight <= capacity and current_value > max_value:
            max_value = current_value
            subset = current_subset
            
    return max_value, subset

input_sizes = [10, 20, 30, 40, 50]
running_times = []
for size in input_sizes:
    values = [random.randint(1, 100) for _ in range(size)]
    weights = [random.randint(1, 100) for _ in range(size)]
    capacity = sum(weights) // 2

    start_time = time.time()
    max_value, subset = brute_force(values, weights, capacity)
    end_time = time.time()
    running_time = end_time - start_time
    running_times.append(running_time)

    print(f"Input size: {size}")
    print(f"Chosen subset: {subset}")
    print(f"Chosen weight: {sum(weights[i] for i in subset)}")
    print(f"Running time: {running_time:.6f} seconds")

plt.plot(input_sizes, running_times, marker='o')
plt.xlabel('Input size')
plt.ylabel('Running time (s)')
plt.title('Brute force Knapsack')
plt.show()
英文:

I'm creating a brute force approach for the knapsack problem, unfortunately when trying to graph the results I get this error: ValueError: x and y must have same first dimension, but have shapes (5,) and (1,)


import time
import random
import matplotlib.pyplot as plt

def brute_force(values, weights, capacity):
    num_items = len(values)
    max_value = 0
    subset = []
    
    for i in range(2**num_items):
        current_value = 0
        current_weight = 0
        current_subset = []
        
        for j in range(num_items):
            if(i &amp; (1 &lt;&lt; j)) != 0:
                current_value += values[j]
                current_weight += weights[j]
                current_subset.append(j)
                
        if current_weight &lt;= capacity and current_value &gt; max_value:
            max_value = current_value
            subset = current_subset
            
    return max_value, subset

input_sizes = [10, 20, 30, 40, 50]
running_times = []
for size in input_sizes:
   values = [random.randint(1,100) for _ in range(size)]
   weights = [random.randint(1, 100) for _ in range(size)]
   capacity = sum(weights) // 2

  start_time = time.time()
  max_value, subset = brute_force(values, weights, capacity)
  end_time = time.time()
  running_time = end_time - start_time
  running_times.append(running_time)

  print(f&quot;Input size: {size}&quot;)
  print(f&quot;Chosen subset: {subset}&quot;)
  print(f&quot;Chosen weight: {sum(weights[i] for i in subset)}&quot;)
  print(f&quot;Running time: {running_time: .6f} seconds&quot;)

  plt.plot(input_sizes, running_times, marker = &#39;o&#39;)
  plt.xlabel(&#39;Input size&#39;)
  plt.ylabel(&#39;Running time (s)&#39;)
  plt.title(&#39;Brute force Knapsack&#39;)
  plt.show()  

答案1

得分: 0

# 在循环内部有 `plt`,这意味着 `running_times` 只有一个值,而 `input_sizes` 有 5 个值...

这样应该可以工作
```python

import time
import random
import matplotlib.pyplot as plt

def brute_force(values, weights, capacity):
    num_items = len(values)
    max_value = 0
    subset = []
    
    for i in range(2**num_items):
        current_value = 0
        current_weight = 0
        current_subset = []
        
        for j in range(num_items):
            if(i &amp; (1 &lt;&lt; j)) != 0:
                current_value += values[j]
                current_weight += weights[j]
                current_subset.append(j)
                
        if current_weight &lt;= capacity and current_value &gt; max_value:
            max_value = current_value
            subset = current_subset
            
    return max_value, subset

input_sizes = [10, 20, 30, 40, 50]
running_times = []
for size in input_sizes:
    values = [random.randint(1,100) for _ in range(size)]
    weights = [random.randint(1, 100) for _ in range(size)]
    capacity = sum(weights) // 2

    start_time = time.time()
    max_value, subset = brute_force(values, weights, capacity)
    end_time = time.time()
    running_time = end_time - start_time
    running_times.append(running_time)

    print(f&quot;Input size: {size}&quot;)
    print(f&quot;Chosen subset: {subset}&quot;)
    print(f&quot;Chosen weight: {sum(weights[i] for i in subset)}&quot;)
    print(f&quot;Running time: {running_time: .6f} seconds&quot;)

plt.plot(input_sizes, running_times, marker = &#39;o&#39;)
plt.xlabel(&#39;Input size&#39;)
plt.ylabel(&#39;Running time (s)&#39;)
plt.title(&#39;Brute force Knapsack&#39;)
plt.show()  

我将 input_list 减小为 [1, 2, 3, 4, 5](为了速度,你可以将其改回),输出如下:

ValueError: x 和 y 必须具有相同的第一个维度,但形状分别为 (5,) 和 (1,)。


<details>
<summary>英文:</summary>

The `plt` was inside the loop meaning that `running_times` has only one value whereas `input_sizes` has 5 values...

This should work:
```python

import time
import random
import matplotlib.pyplot as plt

def brute_force(values, weights, capacity):
    num_items = len(values)
    max_value = 0
    subset = []
    
    for i in range(2**num_items):
        current_value = 0
        current_weight = 0
        current_subset = []
        
        for j in range(num_items):
            if(i &amp; (1 &lt;&lt; j)) != 0:
                current_value += values[j]
                current_weight += weights[j]
                current_subset.append(j)
                
        if current_weight &lt;= capacity and current_value &gt; max_value:
            max_value = current_value
            subset = current_subset
            
    return max_value, subset

input_sizes = [10, 20, 30, 40, 50]
running_times = []
for size in input_sizes:
    values = [random.randint(1,100) for _ in range(size)]
    weights = [random.randint(1, 100) for _ in range(size)]
    capacity = sum(weights) // 2

    start_time = time.time()
    max_value, subset = brute_force(values, weights, capacity)
    end_time = time.time()
    running_time = end_time - start_time
    running_times.append(running_time)

    print(f&quot;Input size: {size}&quot;)
    print(f&quot;Chosen subset: {subset}&quot;)
    print(f&quot;Chosen weight: {sum(weights[i] for i in subset)}&quot;)
    print(f&quot;Running time: {running_time: .6f} seconds&quot;)

plt.plot(input_sizes, running_times, marker = &#39;o&#39;)
plt.xlabel(&#39;Input size&#39;)
plt.ylabel(&#39;Running time (s)&#39;)
plt.title(&#39;Brute force Knapsack&#39;)
plt.show()  

i reduced the input_list to [1, 2, 3, 4, 5] (for speed, so you can put it back) and the output looks like this:

ValueError: x 和 y 必须具有相同的第一个维度,但形状分别为 (5,) 和 (1,)。

huangapple
  • 本文由 发表于 2023年6月5日 19:10:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76405840.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定