在Python机器学习中 prediction = model.predict(不停报错

问题遇到的现象和发生背景

用chatgpt写了一段回溯期权的深度对冲代码,其中一段用到了机器学习Keras模型,遇到了一些问题。

遇到的现象和发生背景,请写出第一个错误信息

全部代码如下

```python
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

# Set the simulation parameters
n_scenarios = 1000
n_steps = 100
S0 = 100
K = 110
r = 0.05
T = 1
sigma = 0.2

# Define the Monte Carlo simulation function
def monte_carlo_simulation(n_scenarios, n_steps, S0, K, r, T, sigma):
    # Generate the random stock price paths
    dt = T/n_steps
    S = np.zeros((n_steps+1, n_scenarios))
    S[0] = S0
    for t in range(1, n_steps+1):
        S[t] = S[t-1] * np.exp((r-0.5*sigma**2)*dt + sigma*np.sqrt(dt)*np.random.normal(size=n_scenarios))

    # Calculate the maximum price over the period
    S_max = np.amax(S, axis=0)

    # Calculate the payoffs at maturity
    payoffs = np.maximum(S_max - K, 0)

    # Calculate the discounted payoffs
    discounted_payoffs = payoffs*np.exp(-r*T)

    # Return the average discounted payoff
    return discounted_payoffs.mean()

# Define the deep hedging function
def deep_hedging(n_scenarios, n_steps, S0, K, r, T, sigma):

# Define the input layers
  inputs = tf.keras.layers.Input(shape=(n_steps, n_scenarios))
  max_input = tf.keras.layers.Input(shape=(n_scenarios,))

# Concatenate the inputs
  concatenated_inputs = tf.keras.layers.Concatenate()([inputs, max_input])

# Flatten the concatenated inputs
  flattened_inputs = tf.keras.layers.Flatten()(concatenated_inputs)

# Define the hidden layers
  hidden1 = tf.keras.layers.Dense(units=20, activation='relu')(flattened_inputs)
  hidden2 = tf.keras.layers.Dense(units=10, activation='relu')(hidden1)

# Define the output layer
  output = tf.keras.layers.Dense(units=1)(hidden2)

# Define the model
  model = tf.keras.Model(inputs=[inputs, max_input], outputs=output)

# Compile the model
  model.compile(optimizer='adam', loss='mse')

# Train the model
  model.fit(x=[S, S_max], y=hedging_ratio, epochs=100)

# Set the number of simulations to run
n_simulations = 1000

# Initialize the deep hedging results array
deep_hedging_results = np.zeros(n_simulations)

# Run the deep hedging simulations
for i in range(n_simulations):
    # Generate the stock price paths
    S = np.zeros((n_steps+1, n_scenarios))
    S[0] = S0
    for t in range(1, n_steps+1):
        S[t] = S[t-1] * np.exp((r-0.5*sigma**2)*dt + sigma*np.sqrt(dt)*np.random.normal(size=n_scenarios))

    # Calculate the maximum price over the period
    S_max = np.amax(S, axis=0)

    # Run the deep hedging strategy
    hedging_ratio = np.zeros((n_scenarios, 1))
    for t in range(n_steps):
# Get the current stock prices
      current_conditions = S[t]
# Expand the current stock prices to a 2D array with shape (n_scenarios, 1)
      current_conditions_expanded = np.expand_dims(current_conditions, axis=1)
# Expand the maximum stock prices to a 2D array with shape (n_scenarios, 1)
      S_max_expanded = np.expand_dims(S_max, axis=1)
# Use the model to predict the hedging ratio for the current time step
      prediction = model.predict([current_conditions_expanded, S_max_expanded])
# Add the prediction to the running sum of hedging ratios
      hedging_ratio += prediction
    hedging_ratio /= n_steps
    deep_hedging_results[i] = hedging_ratio


    # Calculate the payoffs at maturity
payoffs = np.maximum(S_max - K, 0)

    # Calculate the portfolio value at each time step
portfolio_value = S[:-1] - hedging_ratio*(S[:-1]-S[1:])

    # Calculate the deep hedging result for this simulation
deep_hedging_result = (portfolio_value[-1] - payoffs)/payoffs.mean()
deep_hedging_results[i] = deep_hedging_result

# Calculate the mean and standard deviation of the deep hedging results
mean_deep_hedging_result = deep_hedging_results.mean()
std_deep_hedging_result = deep_hedging_results.std()

# Print the results
print(f"Mean deep hedging result: {mean_deep_hedging_result:.4f}")
print(f"Standard deviation of deep hedging results: {std_deep_hedging_result:.4f}")

# Plot the results
plt.hist(deep_hedging_results, bins=50)
plt.xlabel('Deep Hedging Result')
plt.ylabel('Frequency')
plt.show()


用代码块功能插入代码,请勿粘贴截图。 不用代码块回答率下降 50%

有问题的地方在下面这片,具体就是 # Run the deep hedging strategy这部分的内容

# Set the number of simulations to run
n_simulations = 1000

# Initialize the deep hedging results array
deep_hedging_results = np.zeros(n_simulations)

# Run the deep hedging simulations
for i in range(n_simulations):
    # Generate the stock price paths
    S = np.zeros((n_steps+1, n_scenarios))
    S[0] = S0
    for t in range(1, n_steps+1):
        S[t] = S[t-1] * np.exp((r-0.5*sigma**2)*dt + sigma*np.sqrt(dt)*np.random.normal(size=n_scenarios))

    # Calculate the maximum price over the period
    S_max = np.amax(S, axis=0)

    # Run the deep hedging strategy
    hedging_ratio = np.zeros((n_scenarios, 1))
    for t in range(n_steps):
# Get the current stock prices
      current_conditions = S[t]
# Expand the current stock prices to a 2D array with shape (n_scenarios, 1)
      current_conditions_expanded = np.expand_dims(current_conditions, axis=1)
# Expand the maximum stock prices to a 2D array with shape (n_scenarios, 1)
      S_max_expanded = np.expand_dims(S_max, axis=1)
# Use the model to predict the hedging ratio for the current time step
      prediction = model.predict([current_conditions_expanded, S_max_expanded])
# Add the prediction to the running sum of hedging ratios
      hedging_ratio += prediction
    hedging_ratio /= n_steps
    deep_hedging_results[i] = hedging_ratio


运行结果及详细报错内容

运行结果及报错为
ValueError: in user code:

File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1845, in predict_function  *
    return step_function(self, iterator)
File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1834, in step_function  **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1823, in run_step  **
    outputs = model.predict_step(data)
File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1791, in predict_step
    return self(x, training=False)
File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None

ValueError: Exception encountered when calling layer "tf.concat_10" (type TFOpLambda).

Shape must be rank 2 but is rank 3 for '{{node model_12/tf.concat_10/concat}} = ConcatV2[N=2, T=DT_FLOAT, Tidx=DT_INT32](IteratorGetNext, model_12/tf.expand_dims_12/ExpandDims, model_12/tf.concat_10/concat/axis)' with input shapes: [?,1], [?,1,1], [].

Call arguments received by layer "tf.concat_10" (type TFOpLambda):
  • values=['tf.Tensor(shape=(None, 1), dtype=float32)', 'tf.Tensor(shape=(None, 1, 1), dtype=float32)']
  • axis=1name=concat
我的解答思路和尝试过的方法,不写自己思路的,回答率下降 60%

我通过引导chatgpt进行修改,不论是改成

current_conditions_expanded = np.expand_dims(current_conditions, axis=2)
S_max_expanded = np.expand_dims(S_max.reshape(-1, 1), axis=2)


还是改成

S_max_expanded = S_max.reshape(-1, 1)


都没有用

```

我想

有没有大佬能提供一下行得通的代码啊,本人对这方面并不是很了解

```要达到的结果,如果你需要快速回答,请尝试 “付费悬赏”

试一下这样改

prediction = model.predict([current_conditions_expanded, S_max])