# How to implement shot allocation methods for VQA

**URL:** <https://discuss.pennylane.ai/t/how-to-implement-shot-allocation-methods-for-vqa/4458>\
**Category:** PennyLane Help\
**Created:** [April 18, 2024, 7:54am UTC](https://discuss.pennylane.ai/t/how-to-implement-shot-allocation-methods-for-vqa/4458 "2024-04-18T07:54:52Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![yokkon](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/yokkon/32/2501_2.png) [@yokkon](https://discuss.pennylane.ai/u/yokkon)\
**Post date:** [April 18, 2024, 7:54am UTC](https://discuss.pennylane.ai/t/how-to-implement-shot-allocation-methods-for-vqa/4458/1 "2024-04-18T07:54:52Z")

</div>

Hey,

I am trying to implement a new method for shot allocation:  
The main idea is to be able to gain N samples from a given circuit, then I want to perform some calculations and based on the results decide if I need more shots or not. What is the best way to implement this?

I tried implementing an objective function that uses a circuit with `qml.counts`:

```python
 def my_objective_function(params):
        sample_circuit = sample_circuit_wrapper(dev_shots)
        sum_samples = {}
        X_hist = []
        while np.sum(X_hist) < 10000: # shots count
            samples = sample_circuit(params)
            sum_samples = add_samples(sum_samples, samples)
            X_hist = np.asarray(list(sum_samples.values()))
            energy = MyEnergyEstimation(X_hist, hamiltonian)
            print(f'X_hist: {X_hist}')
            if enough_shots(X_hist, epsilon=epsilon):
                break
        return energy

```

I use this objective function with a `GradientDescentOptimizer` which put this whole function under an `autograd` and the `autograd.tracer` doesn’t like the operations I do on the `samples`, I get this error:

```python
TypeError: Can't differentiate w.r.t. type <class 'numpy.int64'>

```

---

<div class="post-metadata">

**Author:** ![CatalinaAlbornoz](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/catalinaalbornoz/32/1196_2.png) [@CatalinaAlbornoz](https://discuss.pennylane.ai/u/CatalinaAlbornoz)\
**Post date:** [April 19, 2024, 6:48pm UTC](https://discuss.pennylane.ai/t/how-to-implement-shot-allocation-methods-for-vqa/4458/2 "2024-04-19T18:48:04Z")

</div>

Hi @yokkon, welcome to the forum!

Unfortunately `samples` returns _stochastic_ results so it’s non-differentiable. Something you could try is using `qml.expval` and setting `shots=1`. This will be basically equivalent.  
I hope this helps you!
