import numpy as np import pandas as pd from keras.models import Sequential from keras.layers import * from keras.wrappers.scikit_learn import * from keras.utils import np_utils from sklearn.model_selection import cross_val_score, KFold from sklearn.preprocessing import LabelEncoder from keras.models import model_from_json # 设置参数 seed = 13 np.random.seed(seed) # 读取数据 df = pd.read_csv("E:/study/tensorflow/project/machinelearning/iris/data/Iris.csv") x = df.values[:, 1:5].astype(float) y = df.values[:, 5] # 将y列的数据字符串转换成数字再转换成onehot encoder = LabelEncoder() y_encoder = encoder.fit_transform(y) y_onehot = np_utils.to_categorical(y_encoder) # # # # 定义神经网络模型 def baseline_model(): model = Sequential() # 添加隐藏层 model.add(Dense(7, input_dim=4, activation="tanh")) # 网络层数,输入的列数,激活函数 model.add(Dense(3, activation="softmax")) model.compile(loss="mean_squared_error", optimizer="sgd", metrics=["accuracy"]) return model # # 通过交叉熵验证训练模型 estimator = KerasClassifier(build_fn=baseline_model, epochs=20, batch_size=1, verbose=1) print(estimator) # # 设置参数evalute kfold = KFold(n_splits=10, shuffle=True, random_state=seed) print(kfold) result = cross_val_score(estimator, x, y_onehot, cv=kfold, verbose=0) print("Accuray of cross valitaion, means %.2f, std %2f" % (result.mean(), result.std())) # save model print("======================") estimator.fit(x, y_onehot) model_json = estimator.model.to_json() with open("model.json", "w") as jsonfile: jsonfile.write(model_json) # 保存参数 estimator.model.save_weights("model.h5") print("保存模型成功") # 读取模型 json_file = open("model.json", "r") loaded_model_json = json_file.read() json_file.close() # 读取模型参数权重 loaded_model = model_from_json(loaded_model_json) loaded_model.load_weights("model.h5") print("loaded model successful") # 进行预测 predicted = loaded_model.predict(x) print("prediction rob:" + str(predicted)) predicted_label = loaded_model.predict_classes(x) print("predicted_label:" + str(predicted_label))
深度学习之iris分类
最新推荐文章于 2024-08-01 15:32:59 发布