np.mean(history.history['accuracy']
时间: 2023-11-11 20:06:04 浏览: 22
I'm sorry but you have provided incomplete code. It seems that there is a closing bracket missing. Please provide the complete code so that I can assist you better.
相关问题
简化并解释每行代码:X_train, y_train = load_data("data/ex2data2.txt") plot_data(X_train, y_train[:], pos_label="Accepted", neg_label="Rejected") plt.ylabel('Microchip Test 2') plt.xlabel('Microchip Test 1') plt.legend(loc="upper right") plt.show() mapped_X = map_feature(X_train[:, 0], X_train[:, 1]) def compute_cost_reg(X, y, w, b, lambda_=1): m = X.shape[0] cost = 0 f = sigmoid(np.dot(X, w) + b) reg = (lambda_/(2*m)) * np.sum(np.square(w)) cost = (1/m)np.sum(-ynp.log(f) - (1-y)*np.log(1-f)) + reg return cost def compute_gradient_reg(X, y, w, b, lambda_=1): m = X.shape[0] cost = 0 dw = np.zeros_like(w) f = sigmoid(np.dot(X, w) + b) err = (f - y) dw = (1/m)*np.dot(X.T, err) dw += (lambda_/m) * w db = (1/m) * np.sum(err) return db,dw X_mapped = map_feature(X_train[:, 0], X_train[:, 1]) np.random.seed(1) initial_w = np.random.rand(X_mapped.shape[1]) - 0.5 initial_b = 0.5 lambda_ = 0.5 dj_db, dj_dw = compute_gradient_reg(X_mapped, y_train, initial_w, initial_b, lambda_) np.random.seed(1) initial_w = np.random.rand(X_mapped.shape[1])-0.5 initial_b = 1. lambda_ = 0.01; iterations = 10000 alpha = 0.01 w,b, J_history,_ = gradient_descent(X_mapped, y_train, initial_w, initial_b, compute_cost_reg, compute_gradient_reg, alpha, iterations, lambda_) plot_decision_boundary(w, b, X_mapped, y_train) p = predict(X_mapped, w, b) print('Train Accuracy: %f'%(np.mean(p == y_train) * 100))
这段代码主要实现了一个二分类问题的训练和预测。下面是每一行代码的解释:
```
X_train, y_train = load_data("data/ex2data2.txt")
```
从文件中读取训练数据,将特征存储在X_train中,将标签存储在y_train中。
```
plot_data(X_train, y_train[:], pos_label="Accepted", neg_label="Rejected")
plt.ylabel('Microchip Test 2')
plt.xlabel('Microchip Test 1')
plt.legend(loc="upper right")
plt.show()
```
画出训练数据的散点图,其中Accepted为正例标签,Rejected为负例标签,横坐标为Microchip Test 1,纵坐标为Microchip Test 2。
```
mapped_X = map_feature(X_train[:, 0], X_train[:, 1])
```
将原始特征映射成更高维的特征,以便更好地拟合非线性决策边界。
```
def compute_cost_reg(X, y, w, b, lambda_=1):
m = X.shape[0]
cost = 0
f = sigmoid(np.dot(X, w) + b)
reg = (lambda_/(2*m)) * np.sum(np.square(w))
cost = (1/m)np.sum(-ynp.log(f) - (1-y)*np.log(1-f)) + reg
return cost
```
计算带正则化的逻辑回归代价函数,其中X为特征数据,y为标签,w为权重,b为偏置,lambda_为正则化参数。
```
def compute_gradient_reg(X, y, w, b, lambda_=1):
m = X.shape[0]
cost = 0
dw = np.zeros_like(w)
f = sigmoid(np.dot(X, w) + b)
err = (f - y)
dw = (1/m)*np.dot(X.T, err)
dw += (lambda_/m) * w
db = (1/m) * np.sum(err)
return db,dw
```
计算带正则化的逻辑回归梯度,其中X为特征数据,y为标签,w为权重,b为偏置,lambda_为正则化参数。
```
X_mapped = map_feature(X_train[:, 0], X_train[:, 1])
np.random.seed(1)
initial_w = np.random.rand(X_mapped.shape[1]) - 0.5
initial_b = 0.5
lambda_ = 0.5
dj_db, dj_dw = compute_gradient_reg(X_mapped, y_train, initial_w, initial_b, lambda_)
```
将映射后的特征、权重、偏置和正则化参数传入梯度计算函数,计算出代价函数对权重和偏置的偏导数。
```
np.random.seed(1)
initial_w = np.random.rand(X_mapped.shape[1])-0.5
initial_b = 1.
lambda_ = 0.01; iterations = 10000; alpha = 0.01
w,b, J_history,_ = gradient_descent(X_mapped, y_train, initial_w, initial_b, compute_cost_reg, compute_gradient_reg, alpha, iterations, lambda_)
```
使用梯度下降算法对代价函数进行优化,得到最优的权重和偏置,lambda_为正则化参数,iterations为迭代次数,alpha为学习率。
```
plot_decision_boundary(w, b, X_mapped, y_train)
```
画出决策边界。
```
p = predict(X_mapped, w, b)
print('Train Accuracy: %f'%(np.mean(p == y_train) * 100))
```
使用训练好的模型进行预测,并计算训练精度。
import matplotlib.pyplot as plt import pandas as pd from keras.models import Sequential from keras import layers from keras import regularizers import os import keras import keras.backend as K import numpy as np from keras.callbacks import LearningRateScheduler data = "data.csv" df = pd.read_csv(data, header=0, index_col=0) df1 = df.drop(["y"], axis=1) lbls = df["y"].values - 1 wave = np.zeros((11500, 178)) z = 0 for index, row in df1.iterrows(): wave[z, :] = row z+=1 mean = wave.mean(axis=0) wave -= mean std = wave.std(axis=0) wave /= std def one_hot(y): lbl = np.zeros(5) lbl[y] = 1 return lbl target = [] for value in lbls: target.append(one_hot(value)) target = np.array(target) wave = np.expand_dims(wave, axis=-1) model = Sequential() model.add(layers.Conv1D(64, 15, strides=2, input_shape=(178, 1), use_bias=False)) model.add(layers.ReLU()) model.add(layers.Conv1D(64, 3)) model.add(layers.Conv1D(64, 3, strides=2)) model.add(layers.BatchNormalization()) model.add(layers.Dropout(0.5)) model.add(layers.Conv1D(64, 3)) model.add(layers.Conv1D(64, 3, strides=2)) model.add(layers.BatchNormalization()) model.add(layers.LSTM(64, dropout=0.5, return_sequences=True)) model.add(layers.LSTM(64, dropout=0.5, return_sequences=True)) model.add(layers.LSTM(32)) model.add(layers.Dropout(0.5)) model.add(layers.Dense(5, activation="softmax")) model.summary() save_path = './keras_model3.h5' if os.path.isfile(save_path): model.load_weights(save_path) print('reloaded.') adam = keras.optimizers.adam() model.compile(optimizer=adam, loss="categorical_crossentropy", metrics=["acc"]) # 计算学习率 def lr_scheduler(epoch): # 每隔100个epoch,学习率减小为原来的0.5 if epoch % 100 == 0 and epoch != 0: lr = K.get_value(model.optimizer.lr) K.set_value(model.optimizer.lr, lr * 0.5) print("lr changed to {}".format(lr * 0.5)) return K.get_value(model.optimizer.lr) lrate = LearningRateScheduler(lr_scheduler) history = model.fit(wave, target, epochs=400, batch_size=128, validation_split=0.2, verbose=2, callbacks=[lrate]) model.save_weights(save_path) print(history.history.keys()) # summarize history for accuracy plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() # summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show()
这段代码是用来训练一个深度学习模型的代码,使用了Keras和Tensorflow进行模型的搭建、训练和保存。该模型包含了卷积层、批量归一化层、Dropout层、LSTM层和全连接层,并且最终使用softmax激活函数得到预测的类别。通过对数据进行处理,将输入数据按照一定的规范进行规范化,将标签转换成了一个one-hot编码的形式。最后,该代码通过在数据上进行训练,得到一个可以用来做预测的深度学习模型。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)