import numpy as np
from scipy.optimize import minimize

# 导入鸢尾花数据集
from sklearn.datasets import load_iris
iris = load_iris()

# 划分训练集和测试集
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target)

# 定义神经网络模型
def neural_network(weights):
    # 将权重矩阵转换为神经网络层的形状
    w1 = np.reshape(weights[:40], (4, 10))
    b1 = np.reshape(weights[40:50], (10,))
    w2 = np.reshape(weights[50:80], (10, 3))
    b2 = np.reshape(weights[80:], (3,))
    
    # 前向传播计算输出
    z1 = np.dot(x_train, w1) + b1
    a1 = np.maximum(z1, 0)
    z2 = np.dot(a1, w2) + b2
    y_pred = np.exp(z2) / np.sum(np.exp(z2), axis=1, keepdims=True)
    
    # 计算交叉熵损失
    loss = -np.sum(np.log(y_pred[np.arange(len(y_train)), y_train]))
    
    return loss

# 随机初始化权重矩阵
weights = np.random.randn(90)

# 使用Nelder-Mead方法优化权重矩阵
result = minimize(neural_network, weights, method='Nelder-Mead', options={'maxiter': 1000})

# 将优化后的权重矩阵转换为神经网络层的形状
w1 = np.reshape(result.x[:40], (4, 10))
b1 = np.reshape(result.x[40:50], (10,))
w2 = np.reshape(result.x[50:80], (10, 3))
b2 = np.reshape(result.x[80:], (3,))

# 构建最终的神经网络模型
model = keras.models.Sequential([
    keras.layers.Dense(10, activation='relu', input_shape=x_train.shape[1:], weights=[w1, b1]),
    keras.layers.Dense(3, activation='softmax', weights=[w2, b2])
])

# 编译模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# 评估模型
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)

# 输出测试准确率
print('Test accuracy:', test_acc)
报错了：

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[8], line 35
     32 weights = np.random.randn(90)
     34 # 使用Nelder-Mead方法优化权重矩阵
---> 35 result = minimize(neural_network, weights, method='Nelder-Mead', options={'maxiter': 1000})
     37 # 将优化后的权重矩阵转换为神经网络层的形状
     38 w1 = np.reshape(result.x[:40], (4, 10))

File c:\Users\29252\AppData\Local\Programs\Python\Python311\Lib\site-packages\scipy\optimize\_minimize.py:684, in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
    681     bounds = standardize_bounds(bounds, x0, meth)
    683 if meth == 'nelder-mead':
--> 684     res = _minimize_neldermead(fun, x0, args, callback, bounds=bounds,
    685                                **options)
    686 elif meth == 'powell':
    687     res = _minimize_powell(fun, x0, args, callback, bounds, **options)

File c:\Users\29252\AppData\Local\Programs\Python\Python311\Lib\site-packages\scipy\optimize\_optimize.py:845, in _minimize_neldermead(func, x0, args, callback, maxiter, maxfev, disp, return_all, initial_simplex, xatol, fatol, adaptive, bounds, **unknown_options)
    843 try:
    844     for k in range(N + 1):
--> 845         fsim[k] = func(sim[k])
    846 except _MaxFuncCallError:
    847     pass

File c:\Users\29252\AppData\Local\Programs\Python\Python311\Lib\site-packages\scipy\optimize\_optimize.py:569, in _wrap_scalar_function_maxfun_validation..function_wrapper(x, *wrapper_args)
    567 ncalls[0] += 1
    568 # A copy of x is sent to the user function (gh13740)
--> 569 fx = function(np.copy(x), *(wrapper_args + args))
    570 # Ideally, we'd like to a have a true scalar returned from f(x). For
    571 # backwards-compatibility, also allow np.array([1.3]),
    572 # np.array([[1.3]]) etc.
    573 if not np.isscalar(fx):

Cell In[8], line 18, in neural_network(weights)
     16 b1 = np.reshape(weights[40:50], (10,))
     17 w2 = np.reshape(weights[50:80], (10, 3))
---> 18 b2 = np.reshape(weights[80:], (3,))
     20 # 前向传播计算输出
     21 z1 = np.dot(x_train, w1) + b1

File <__array_function__ internals>:180, in reshape(*args, **kwargs)

File c:\Users\29252\AppData\Local\Programs\Python\Python311\Lib\site-packages\numpy\core\fromnumeric.py:298, in reshape(a, newshape, order)
    198 @array_function_dispatch(_reshape_dispatcher)
    199 def reshape(a, newshape, order='C'):
    200     """
    201     Gives a new shape to an array without changing its data.
    202 
   (...)
    296            [5, 6]])
    297     """
--> 298     return _wrapfunc(a, 'reshape', newshape, order=order)

File c:\Users\29252\AppData\Local\Programs\Python\Python311\Lib\site-packages\numpy\core\fromnumeric.py:57, in _wrapfunc(obj, method, *args, **kwds)
     54     return _wrapit(obj, method, *args, **kwds)
     56 try:
---> 57     return bound(*args, **kwds)
     58 except TypeError:
     59     # A TypeError occurs if the object does have such a method in its
     60     # class, but its signature is not identical to that of NumPy's. This
   (...)
     64     # Call _wrapit from within the except clause to ensure a potential
     65     # exception has a traceback chain.
     66     return _wrapit(obj, method, *args, **kwds)

ValueError: cannot reshape array of size 10 into shape (3,)
